@mgamadeus/ddd-web 0.4.0 → 0.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude/skills/ddd-web-specialist/SKILL.md +6 -3
- package/.claude/skills/ddd-web-specialist/references/consumer.md +33 -0
- package/CHANGELOG.md +18 -0
- package/README.md +15 -0
- package/dist/api/index.d.ts +53 -2
- package/dist/api/index.js +61 -13
- package/dist/api/index.js.map +1 -1
- package/package.json +1 -1
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
---
|
|
2
2
|
name: ddd-web-specialist
|
|
3
|
-
description: "Use and maintain @mgamadeus/ddd-web, the TS client of mgamadeus/ddd
|
|
3
|
+
description: "Use and maintain @mgamadeus/ddd-web, the TS client of mgamadeus/ddd: openapi-config.ts with defineConfig (schemaFile, sideEffects, responseHandlers, invalidation), the RTK Query SDK from ddd-web-sdk (Enhanced/Tags files, cache tags by entity identity, typed tagTypes via mergeDddTagTypes, downloads via blobResponseHandler, file uploads: multipartFiles argument, buildDddMultipartBody, upload with progress via baseQuery.upload), QueryOptions builders (buildQueryOptions, combineFilters, buildInFilter), createDddBaseQuery (Bearer, shared refresh + retry, relogin for sessions without refresh token, session-bound requests via getSessionKey, shouldRefresh, normalizeDddError), token storage, JWT helpers, link-skills, release. Use when wiring a frontend to a DDD backend, regenerating the SDK, building filters, uploading files, FormData, upload progress, fixing token refresh, guest login, a request sent under the wrong account after an account switch, stale cache tags, downloading an export, or releasing ddd-web."
|
|
4
4
|
metadata:
|
|
5
5
|
author: mgamadeus
|
|
6
|
-
version: "1.
|
|
6
|
+
version: "1.4.0"
|
|
7
7
|
package: "@mgamadeus/ddd-web"
|
|
8
8
|
---
|
|
9
9
|
|
|
@@ -21,7 +21,7 @@ frontend code. No UI components, no domain logic — apps bring their own design
|
|
|
21
21
|
|---|---|---|
|
|
22
22
|
| `@mgamadeus/ddd-web/codegen` | Node only (never in a browser bundle) | `defineConfig`, `generateSdk`, `linkSkills`, `loadSpec` / `validateSpec`; bins `ddd-web-sdk`, `ddd-web` |
|
|
23
23
|
| `@mgamadeus/ddd-web/query` | anywhere, no React | QueryOptions builders and definition-driven validators |
|
|
24
|
-
| `@mgamadeus/ddd-web/api` | needs `@reduxjs/toolkit` 2 (peer) | `createDddBaseQuery` (+ `upload()`, `relogin`), `createDddRefresh`, `normalizeDddError`, downloads, multipart (`buildDddMultipartBody`), `mergeDddTagTypes`, `createAuthEndpoints` |
|
|
24
|
+
| `@mgamadeus/ddd-web/api` | needs `@reduxjs/toolkit` 2 (peer) | `createDddBaseQuery` (+ `upload()`, `relogin`, `getSessionKey`), `createDddRefresh`, `normalizeDddError`, downloads, multipart (`buildDddMultipartBody`), `mergeDddTagTypes`, `createAuthEndpoints` |
|
|
25
25
|
| `@mgamadeus/ddd-web/auth` | anywhere | `TokenStorage` adapters, `decodeJwt`, `isExpired`, SSR-safe storage |
|
|
26
26
|
| `@mgamadeus/ddd-web/contract` | types + small helpers | `x-ddd-*` types, error body, DDD date-time, translations, operators |
|
|
27
27
|
|
|
@@ -97,6 +97,9 @@ const { data } = useGetApiAdminLibraryBooksListQuery({
|
|
|
97
97
|
`fetch` / `XMLHttpRequest` and an own token: it bypasses the session, the refresh and the headers hooks.
|
|
98
98
|
- **Sessions without refresh token** (guest, device, impersonation) recover through the `relogin` option — never a
|
|
99
99
|
placeholder refresh token.
|
|
100
|
+
- **A request whose body belongs to one account is bound to that session**: `getSessionKey` on the base query and
|
|
101
|
+
`withDddExpectedSessionKey` (or `expectedSessionKey` of an upload). A check before `dispatch()` does not cover the
|
|
102
|
+
wait for a running refresh or the retry after it.
|
|
100
103
|
- **Tag names come from the generated `<stem>Tags.ts`**: build `tagTypes` with `mergeDddTagTypes`, never retype a tag.
|
|
101
104
|
- **A route missing from the deployed spec** is generated from a local spec file or local backend (`schemaFile`,
|
|
102
105
|
`--schema`), not injected by hand.
|
|
@@ -286,6 +286,7 @@ DDD date-time otherwise.
|
|
|
286
286
|
| `onLogout(api)` | once, when the session cannot be recovered |
|
|
287
287
|
| `refreshPath` / `refresh` | default refresh = `POST refreshPath { refreshToken }` → `{ accessToken, refreshToken }`; or a custom `DddRefreshFn` |
|
|
288
288
|
| `relogin(context)` | re-opens the session when the refresh cannot: `context.reason` is `'no-refresh-token'` (guest, device, impersonation sessions) or `'refresh-rejected'`; return the new tokens (`refreshToken: null` allowed) or `null` to log out |
|
|
289
|
+
| `getSessionKey(context)` | key of the current session that survives a token refresh (account id, or a counter raised on login and logout; `null` without a session); needed to bind requests to a session, see below |
|
|
289
290
|
| `createUploadRequest()` | the request object of `upload()`; default `new XMLHttpRequest()` |
|
|
290
291
|
| `shouldRefresh(error, request)` | default `defaultShouldRefresh`: status 401 and not an auth route (`…/common/auth/…`, `isDddAuthRequest`) |
|
|
291
292
|
| `languageCode(context)` | value of the DDD `languageCode` header; `context.type` tells queries from mutations (e.g. editing language on writes, UI language on reads) |
|
|
@@ -310,6 +311,36 @@ relogin: async ({ reason, baseQuery, api, extraOptions }) => {
|
|
|
310
311
|
},
|
|
311
312
|
```
|
|
312
313
|
|
|
314
|
+
**Requests bound to a session.** The Bearer token is read when a request is sent: after the wait for a running
|
|
315
|
+
refresh, and again for the retry. A request prepared for account A (an offline queue, an upload, an import) can
|
|
316
|
+
therefore leave with the token of account B when the user switched in between; a check before `dispatch()` does not
|
|
317
|
+
cover that. Give the base query a `getSessionKey` and bind such requests: a bound request is sent, and retried, only
|
|
318
|
+
while its session is the current one. Otherwise it ends with `{ error: { status: 'CUSTOM_ERROR', error:
|
|
319
|
+
'DDD_SESSION_CHANGED' } }` (`isDddSessionChanged(error)`) without a network call, a refresh or a logout. Requests that
|
|
320
|
+
are not bound behave as before.
|
|
321
|
+
|
|
322
|
+
```ts
|
|
323
|
+
createDddBaseQuery({ /* … */ getSessionKey: ({ getState }) => (getState() as RootState).auth.accountId });
|
|
324
|
+
|
|
325
|
+
// The session the caller prepared the request for (strictest form): the key is part of the endpoint's argument.
|
|
326
|
+
saveDraft: build.mutation<void, { accountId: number; draft: Draft }>({
|
|
327
|
+
query: ({ accountId, draft }) =>
|
|
328
|
+
withDddExpectedSessionKey({ url: '/api/client/drafts', method: 'POST', body: { draft } }, accountId),
|
|
329
|
+
}),
|
|
330
|
+
|
|
331
|
+
// An upload:
|
|
332
|
+
dddBaseQuery.upload({ url, files, expectedSessionKey: accountId }, api, extraOptions);
|
|
333
|
+
|
|
334
|
+
// The session that is current when the request starts (also for generated endpoints, through enhanceEndpoints):
|
|
335
|
+
api.enhanceEndpoints({ endpoints: { postClientDrafts: { extraOptions: { bindToSession: true } } } });
|
|
336
|
+
```
|
|
337
|
+
|
|
338
|
+
- The key must survive a token refresh: an account id or an app-side counter, never the access token (a refresh of
|
|
339
|
+
the same session would block the retry).
|
|
340
|
+
- `withDddExpectedSessionKey` carries the key in the header `x-ddd-expected-session-key`; the base query removes it
|
|
341
|
+
before sending. A `queryFn` can pass `{ expectedSessionKey }` as `extraOptions` instead.
|
|
342
|
+
- Treat `DDD_SESSION_CHANGED` like "not sent": a queued item stays queued for its own account.
|
|
343
|
+
|
|
313
344
|
It runs inside the shared refresh, so concurrent failures trigger it once.
|
|
314
345
|
|
|
315
346
|
```ts
|
|
@@ -383,6 +414,8 @@ Idempotent; an existing symlink is repointed, a real file or directory is never
|
|
|
383
414
|
| `type check failed — previous output restored` | Fix the reported type error (often app code using a renamed hook), or `--skip-tsc` to inspect |
|
|
384
415
|
| A list does not refresh after a write | `<stem>Enhanced.ts` not imported; or the write has no tag — see section 3 |
|
|
385
416
|
| A screen shows stale data after a write that changes more than its own entity | Writes invalidate by identity since 0.3 — add an `invalidation` resolver for that endpoint (section 3), or `broadInvalidation` for the 0.2 behaviour |
|
|
417
|
+
| After an account switch a queued request was stored under the new account | Bind it to its session: `getSessionKey` + `withDddExpectedSessionKey` (section 5) |
|
|
418
|
+
| `a request is bound to a session, pass getSessionKey` | The base query has no `getSessionKey` option |
|
|
386
419
|
| A guest / device session logs out at the first 401 | It has no refresh token: pass `relogin` (section 5) |
|
|
387
420
|
| `multipart body not generated (…flattenArg…)` | The endpoint's argument is the body itself; drop `flattenArg` for it or send the files with `upload()` |
|
|
388
421
|
| An invalidation of a hand-written endpoint does nothing | Tag name in another case than the generated one: build `tagTypes` with `mergeDddTagTypes` (section 3) |
|
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,23 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.5.0
|
|
4
|
+
|
|
5
|
+
Requests can be bound to the session they were prepared for. Additive: without `getSessionKey` nothing changes.
|
|
6
|
+
|
|
7
|
+
### Added
|
|
8
|
+
- api: option `getSessionKey` of `createDddBaseQuery` and three ways to bind a request to a session:
|
|
9
|
+
`withDddExpectedSessionKey(request, key)` in an endpoint's `query`, `expectedSessionKey` of an upload, and
|
|
10
|
+
`extraOptions: { bindToSession: true }` (the session that is current when the request starts;
|
|
11
|
+
`{ expectedSessionKey }` for a `queryFn`). A bound request is sent, and repeated after a refresh, only while that
|
|
12
|
+
session is the current one; otherwise it ends with the error of `isDddSessionChanged` (`DDD_SESSION_CHANGED`)
|
|
13
|
+
without a network call, a refresh or a logout. Type `DddSessionBindingOptions`, constant
|
|
14
|
+
`DDD_EXPECTED_SESSION_KEY_HEADER`.
|
|
15
|
+
|
|
16
|
+
### Fixed by binding
|
|
17
|
+
- A request that waited for a running refresh, or was repeated after one, was sent with the token of whatever
|
|
18
|
+
session was current at that moment: after an account switch a body prepared for one account could be stored under
|
|
19
|
+
another. Bind requests whose body belongs to an account (offline queues, uploads, imports).
|
|
20
|
+
|
|
3
21
|
## 0.4.0
|
|
4
22
|
|
|
5
23
|
File uploads, sessions without refresh token and typed cache tags. Minor release: the generated arguments of multipart
|
package/README.md
CHANGED
|
@@ -99,6 +99,21 @@ queryFn: ({ file, onProgress }, api, extraOptions) =>
|
|
|
99
99
|
createDddBaseQuery({ /* … */ relogin: async ({ reason, baseQuery, api, extraOptions }) => reopenGuestSession(baseQuery, api, extraOptions) });
|
|
100
100
|
```
|
|
101
101
|
|
|
102
|
+
### Requests bound to a session
|
|
103
|
+
|
|
104
|
+
A request prepared for one account must not leave with another account's token after an account switch (the token is
|
|
105
|
+
read when the request is sent, after a running refresh, and again for the retry):
|
|
106
|
+
|
|
107
|
+
```ts
|
|
108
|
+
createDddBaseQuery({ /* … */ getSessionKey: ({ getState }) => (getState() as RootState).auth.accountId });
|
|
109
|
+
|
|
110
|
+
query: ({ accountId, draft }) => withDddExpectedSessionKey({ url: '/api/client/drafts', method: 'POST', body: { draft } }, accountId),
|
|
111
|
+
```
|
|
112
|
+
|
|
113
|
+
A bound request whose session is no longer the current one is not sent: `isDddSessionChanged(result.error)`. Uploads
|
|
114
|
+
take `expectedSessionKey`; `extraOptions: { bindToSession: true }` binds an endpoint's requests to the session they
|
|
115
|
+
start in.
|
|
116
|
+
|
|
102
117
|
### Typed cache tags
|
|
103
118
|
|
|
104
119
|
```ts
|
package/dist/api/index.d.ts
CHANGED
|
@@ -122,6 +122,11 @@ interface DddUploadRequest {
|
|
|
122
122
|
onProgress?: (loaded: number, total: number) => void;
|
|
123
123
|
/** Aborting cancels the request; the result is then the error of {@link isDddUploadAborted}. */
|
|
124
124
|
signal?: AbortSignal;
|
|
125
|
+
/**
|
|
126
|
+
* Session this upload belongs to (see {@link DddBaseQueryOptions.getSessionKey}): it is only sent, and only
|
|
127
|
+
* repeated after a refresh, while that session is the current one.
|
|
128
|
+
*/
|
|
129
|
+
expectedSessionKey?: string | number;
|
|
125
130
|
}
|
|
126
131
|
/** Result of an upload: the shape an RTK `queryFn` returns. */
|
|
127
132
|
type DddUploadResult = {
|
|
@@ -150,6 +155,22 @@ type DddUploadingBaseQuery = DddBaseQuery & {
|
|
|
150
155
|
declare const DDD_UPLOAD_ABORTED = "DDD_UPLOAD_ABORTED";
|
|
151
156
|
/** True for the error of an upload that was cancelled through its `signal`. */
|
|
152
157
|
declare const isDddUploadAborted: (error: unknown) => boolean;
|
|
158
|
+
/** `error.error` of a request that was not sent because it was bound to a session that is no longer the current one. */
|
|
159
|
+
declare const DDD_SESSION_CHANGED = "DDD_SESSION_CHANGED";
|
|
160
|
+
/** True for the error of a request that was not sent because its session is no longer the current one. */
|
|
161
|
+
declare const isDddSessionChanged: (error: unknown) => boolean;
|
|
162
|
+
/** Request header that carries the expected session key to the base query; it is removed before the request is sent. */
|
|
163
|
+
declare const DDD_EXPECTED_SESSION_KEY_HEADER = "x-ddd-expected-session-key";
|
|
164
|
+
/**
|
|
165
|
+
* `extraOptions` the base query reads: what binds the requests of an endpoint to a session (see
|
|
166
|
+
* {@link DddBaseQueryOptions.getSessionKey}).
|
|
167
|
+
*/
|
|
168
|
+
interface DddSessionBindingOptions {
|
|
169
|
+
/** Binds each request to the session that is current when the request starts. */
|
|
170
|
+
bindToSession?: boolean;
|
|
171
|
+
/** Binds the request to this session (a `queryFn` passes it on to the base query). */
|
|
172
|
+
expectedSessionKey?: string | number;
|
|
173
|
+
}
|
|
153
174
|
/** Options of {@link createDddBaseQuery}. */
|
|
154
175
|
interface DddBaseQueryOptions {
|
|
155
176
|
/** API origin, e.g. `https://api.example.com`. Request URLs are relative to it. */
|
|
@@ -160,6 +181,29 @@ interface DddBaseQueryOptions {
|
|
|
160
181
|
setTokens: (tokens: DddTokens, api: BaseQueryApi) => MaybePromise<void>;
|
|
161
182
|
/** Called once when the session cannot be recovered (no refresh token, or the refresh was rejected). */
|
|
162
183
|
onLogout: (api: BaseQueryApi) => MaybePromise<void>;
|
|
184
|
+
/**
|
|
185
|
+
* Identifies the current session by a value that survives a token refresh: the account id, or a counter the app
|
|
186
|
+
* raises on every login and logout; `null` without a session. Never the access token: it changes with each refresh.
|
|
187
|
+
*
|
|
188
|
+
* With it a request can be bound to a session. A bound request is sent, and repeated after a refresh, only while
|
|
189
|
+
* that session is the current one; otherwise it is answered with the error of {@link isDddSessionChanged}, without
|
|
190
|
+
* a network call, a refresh or a logout. A request is bound by one of:
|
|
191
|
+
* - {@link withDddExpectedSessionKey} in the endpoint's `query` (the session the caller prepared the request for),
|
|
192
|
+
* - `expectedSessionKey` of an upload ({@link DddUploadRequest}),
|
|
193
|
+
* - `extraOptions: { bindToSession: true }` on the endpoint: the session that is current when the request starts.
|
|
194
|
+
*
|
|
195
|
+
* Requests that are not bound are sent as without this option.
|
|
196
|
+
*
|
|
197
|
+
* @example
|
|
198
|
+
* getSessionKey: ({ getState }) => (getState() as RootState).auth.accountId,
|
|
199
|
+
*
|
|
200
|
+
* // An endpoint whose body belongs to the account it was prepared for:
|
|
201
|
+
* saveDraft: build.mutation<void, { accountId: number; draft: Draft }>({
|
|
202
|
+
* query: ({ accountId, draft }) =>
|
|
203
|
+
* withDddExpectedSessionKey({ url: '/api/client/drafts', method: 'POST', body: { draft } }, accountId),
|
|
204
|
+
* }),
|
|
205
|
+
*/
|
|
206
|
+
getSessionKey?: (context: DddRequestContext) => MaybePromise<string | number | null | undefined>;
|
|
163
207
|
/** Custom refresh. Default: {@link createDddRefresh} on `refreshPath`. */
|
|
164
208
|
refresh?: DddRefreshFn;
|
|
165
209
|
/** Refresh endpoint for the default refresh, e.g. `/api/admin/common/auth/refresh`. Required without `refresh`. */
|
|
@@ -217,6 +261,12 @@ declare const defaultShouldRefresh: DddShouldRefresh;
|
|
|
217
261
|
* Query-string serializer that skips `null` / `undefined` values (the generated SDK passes every optional parameter).
|
|
218
262
|
*/
|
|
219
263
|
declare const dddParamsSerializer: (params: Record<string, unknown>) => string;
|
|
264
|
+
/**
|
|
265
|
+
* Binds a request to a session: the base query sends it, and repeats it after a refresh, only while
|
|
266
|
+
* `expectedSessionKey` is the key of the current session ({@link DddBaseQueryOptions.getSessionKey}). The key travels
|
|
267
|
+
* in a request header that the base query removes before sending.
|
|
268
|
+
*/
|
|
269
|
+
declare const withDddExpectedSessionKey: (request: string | FetchArgs, expectedSessionKey: string | number) => FetchArgs;
|
|
220
270
|
/**
|
|
221
271
|
* Creates the RTK Query base query for a DDD backend.
|
|
222
272
|
*
|
|
@@ -227,6 +277,7 @@ declare const dddParamsSerializer: (params: Record<string, unknown>) => string;
|
|
|
227
277
|
* - No refresh token, or a rejected refresh → `relogin()` when given; without it, or when it returns `null`,
|
|
228
278
|
* `onLogout()` once for that session and the original error is returned.
|
|
229
279
|
* - A refresh whose session was logged out or replaced while it ran is discarded (no `setTokens`, no retry).
|
|
280
|
+
* - A request bound to a session (`getSessionKey`) is not sent once another session is the current one.
|
|
230
281
|
*
|
|
231
282
|
* @example
|
|
232
283
|
* export const baseApi = createApi({
|
|
@@ -395,5 +446,5 @@ declare function createAuthEndpoints<Definitions extends EndpointDefinitions, Re
|
|
|
395
446
|
authRefresh: _reduxjs_toolkit_query.MutationDefinition<DddRefreshRequest, DddBaseQuery, TagTypes, DddAuthResponse, ReducerPath, unknown>;
|
|
396
447
|
}, ReducerPath, TagTypes, Enhancers>;
|
|
397
448
|
|
|
398
|
-
export { DDD_MULTIPART_BODY_FIELD, DDD_UPLOAD_ABORTED, DEFAULT_ERROR_MESSAGE, DEFAULT_ERROR_MESSAGES, DddTokens, applyDebugParams, blobResponseHandler, buildDddFormData, buildDddMultipartBody, createAuthEndpoints, createDddBaseQuery, createDddRefresh, createDownloadResponseHandler, dddParamsSerializer, defaultShouldRefresh, downloadBlob, filenameFromContentDisposition, getErrorMessage, getErrorStatus, getRequestUrl, hasDddMultipartFiles, isDddAuthRequest, isDddUploadAborted, mergeDddTagTypes, normalizeDddError, readDebugFlags };
|
|
399
|
-
export type { DddAuthEndpointsOptions, DddBaseQuery, DddBaseQueryOptions, DddDebugFlags, DddDebugOptions, DddDownloadedFile, DddErrorMessages, DddFilePart, DddFileResponse, DddHeadersContext, DddMultipartFiles, DddNormalizedError, DddRawBaseQuery, DddRefreshContext, DddRefreshFn, DddReloginContext, DddReloginFn, DddRequestContext, DddShouldRefresh, DddUploadRequest, DddUploadResult, DddUploadingBaseQuery };
|
|
449
|
+
export { DDD_EXPECTED_SESSION_KEY_HEADER, DDD_MULTIPART_BODY_FIELD, DDD_SESSION_CHANGED, DDD_UPLOAD_ABORTED, DEFAULT_ERROR_MESSAGE, DEFAULT_ERROR_MESSAGES, DddTokens, applyDebugParams, blobResponseHandler, buildDddFormData, buildDddMultipartBody, createAuthEndpoints, createDddBaseQuery, createDddRefresh, createDownloadResponseHandler, dddParamsSerializer, defaultShouldRefresh, downloadBlob, filenameFromContentDisposition, getErrorMessage, getErrorStatus, getRequestUrl, hasDddMultipartFiles, isDddAuthRequest, isDddSessionChanged, isDddUploadAborted, mergeDddTagTypes, normalizeDddError, readDebugFlags, withDddExpectedSessionKey };
|
|
450
|
+
export type { DddAuthEndpointsOptions, DddBaseQuery, DddBaseQueryOptions, DddDebugFlags, DddDebugOptions, DddDownloadedFile, DddErrorMessages, DddFilePart, DddFileResponse, DddHeadersContext, DddMultipartFiles, DddNormalizedError, DddRawBaseQuery, DddRefreshContext, DddRefreshFn, DddReloginContext, DddReloginFn, DddRequestContext, DddSessionBindingOptions, DddShouldRefresh, DddUploadRequest, DddUploadResult, DddUploadingBaseQuery };
|
package/dist/api/index.js
CHANGED
|
@@ -70,23 +70,43 @@ function createDddRefresh(path) {
|
|
|
70
70
|
// src/api/baseQuery.ts
|
|
71
71
|
var DDD_UPLOAD_ABORTED = "DDD_UPLOAD_ABORTED";
|
|
72
72
|
var isDddUploadAborted = (error) => !!error && typeof error === "object" && error.status === "CUSTOM_ERROR" && error.error === DDD_UPLOAD_ABORTED;
|
|
73
|
+
var DDD_SESSION_CHANGED = "DDD_SESSION_CHANGED";
|
|
74
|
+
var isDddSessionChanged = (error) => !!error && typeof error === "object" && error.status === "CUSTOM_ERROR" && error.error === DDD_SESSION_CHANGED;
|
|
75
|
+
var DDD_EXPECTED_SESSION_KEY_HEADER = "x-ddd-expected-session-key";
|
|
73
76
|
var getRequestUrl = (request) => typeof request === "string" ? request : request.url;
|
|
74
77
|
var isDddAuthRequest = (request) => getRequestUrl(request).includes("/common/auth/");
|
|
75
78
|
var defaultShouldRefresh = (error, request) => error.status === 401 && !isDddAuthRequest(request);
|
|
76
79
|
var dddParamsSerializer = (params) => Object.entries(params).filter(([, value]) => value !== null && value !== void 0).map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(String(value))}`).join("&");
|
|
77
80
|
var toFetchArgs = (args) => typeof args === "string" ? { url: args } : args;
|
|
78
|
-
var
|
|
79
|
-
if (!accessToken) return args;
|
|
81
|
+
var toHeaders = (source) => {
|
|
80
82
|
const headers = new Headers();
|
|
81
|
-
const source = args.headers;
|
|
82
83
|
if (source instanceof Headers) source.forEach((value, key) => headers.set(key, value));
|
|
83
84
|
else if (Array.isArray(source)) source.forEach(([key, value]) => key !== void 0 && headers.set(key, value ?? ""));
|
|
84
85
|
else if (source) Object.entries(source).forEach(([key, value]) => value !== void 0 && headers.set(key, value));
|
|
86
|
+
return headers;
|
|
87
|
+
};
|
|
88
|
+
var withBearer = (args, accessToken) => {
|
|
89
|
+
if (!accessToken) return args;
|
|
90
|
+
const headers = toHeaders(args.headers);
|
|
85
91
|
if (!headers.has("authorization")) headers.set("authorization", `Bearer ${accessToken}`);
|
|
86
92
|
return { ...args, headers };
|
|
87
93
|
};
|
|
94
|
+
var withDddExpectedSessionKey = (request, expectedSessionKey) => {
|
|
95
|
+
const args = toFetchArgs(request);
|
|
96
|
+
const headers = toHeaders(args.headers);
|
|
97
|
+
headers.set(DDD_EXPECTED_SESSION_KEY_HEADER, String(expectedSessionKey));
|
|
98
|
+
return { ...args, headers };
|
|
99
|
+
};
|
|
100
|
+
var takeExpectedSessionKey = (args) => {
|
|
101
|
+
if (!args.headers) return { request: args, expectedSessionKey: null };
|
|
102
|
+
const headers = toHeaders(args.headers);
|
|
103
|
+
const expectedSessionKey = headers.get(DDD_EXPECTED_SESSION_KEY_HEADER);
|
|
104
|
+
if (expectedSessionKey === null) return { request: args, expectedSessionKey: null };
|
|
105
|
+
headers.delete(DDD_EXPECTED_SESSION_KEY_HEADER);
|
|
106
|
+
return { request: { ...args, headers }, expectedSessionKey };
|
|
107
|
+
};
|
|
88
108
|
function createDddBaseQuery(options) {
|
|
89
|
-
const { getTokens, setTokens, onLogout, headers: headersHook, languageCode, fetchOptions, relogin } = options;
|
|
109
|
+
const { getTokens, setTokens, onLogout, getSessionKey, headers: headersHook, languageCode, fetchOptions, relogin } = options;
|
|
90
110
|
const shouldRefresh = options.shouldRefresh ?? defaultShouldRefresh;
|
|
91
111
|
if (!options.refresh && !options.refreshPath) {
|
|
92
112
|
throw new Error("createDddBaseQuery: pass either `refresh` or `refreshPath`.");
|
|
@@ -112,6 +132,21 @@ function createDddBaseQuery(options) {
|
|
|
112
132
|
let lastOutcome = null;
|
|
113
133
|
let inflight = null;
|
|
114
134
|
const currentAccessToken = async (api) => (await getTokens(api))?.accessToken ?? null;
|
|
135
|
+
const currentSessionKey = async (api) => {
|
|
136
|
+
const sessionKey = await getSessionKey(api);
|
|
137
|
+
return sessionKey === null || sessionKey === void 0 ? null : String(sessionKey);
|
|
138
|
+
};
|
|
139
|
+
const resolveBoundSessionKey = async (requestSessionKey, api, extraOptions) => {
|
|
140
|
+
const binding = extraOptions ?? {};
|
|
141
|
+
const expectedSessionKey = requestSessionKey ?? binding.expectedSessionKey ?? null;
|
|
142
|
+
if (expectedSessionKey === null && !binding.bindToSession) return void 0;
|
|
143
|
+
if (!getSessionKey) {
|
|
144
|
+
throw new Error("createDddBaseQuery: a request is bound to a session, pass `getSessionKey`.");
|
|
145
|
+
}
|
|
146
|
+
return expectedSessionKey === null ? currentSessionKey(api) : String(expectedSessionKey);
|
|
147
|
+
};
|
|
148
|
+
const isBoundSessionCurrent = async (boundSessionKey, api) => boundSessionKey === void 0 || await currentSessionKey(api) === boundSessionKey;
|
|
149
|
+
const sessionChanged = { error: { status: "CUSTOM_ERROR", error: DDD_SESSION_CHANGED } };
|
|
115
150
|
const runRefresh = async (api, extraOptions) => {
|
|
116
151
|
const before = await getTokens(api);
|
|
117
152
|
const refreshToken = before?.refreshToken ?? null;
|
|
@@ -152,14 +187,20 @@ function createDddBaseQuery(options) {
|
|
|
152
187
|
if (inflight) await inflight;
|
|
153
188
|
return lastOutcome;
|
|
154
189
|
};
|
|
190
|
+
const sendRequest = async (request, boundSessionKey, api, extraOptions) => {
|
|
191
|
+
const authorizedRequest = withBearer(request, await currentAccessToken(api));
|
|
192
|
+
if (!await isBoundSessionCurrent(boundSessionKey, api)) return sessionChanged;
|
|
193
|
+
return rawBaseQuery(authorizedRequest, api, extraOptions);
|
|
194
|
+
};
|
|
155
195
|
const baseQuery = async (args, api, extraOptions) => {
|
|
196
|
+
const { request, expectedSessionKey } = takeExpectedSessionKey(toFetchArgs(args));
|
|
197
|
+
const boundSessionKey = await resolveBoundSessionKey(expectedSessionKey, api, extraOptions);
|
|
156
198
|
while (inflight) await inflight.catch(() => void 0);
|
|
157
199
|
const startGeneration = generation;
|
|
158
|
-
const
|
|
159
|
-
|
|
160
|
-
if (!result.error || !shouldRefresh(result.error, request)) return result;
|
|
200
|
+
const result = await sendRequest(request, boundSessionKey, api, extraOptions);
|
|
201
|
+
if (!result.error || isDddSessionChanged(result.error) || !shouldRefresh(result.error, request)) return result;
|
|
161
202
|
if (await recover(startGeneration, api, extraOptions) !== "refreshed") return result;
|
|
162
|
-
return
|
|
203
|
+
return sendRequest(request, boundSessionKey, api, extraOptions);
|
|
163
204
|
};
|
|
164
205
|
const uploadHeaders = async (request, api, extraOptions) => {
|
|
165
206
|
const headers = new Headers();
|
|
@@ -179,8 +220,9 @@ function createDddBaseQuery(options) {
|
|
|
179
220
|
if (debugOptions && readDebugFlags(debugOptions).debug) headers.set("x-debug", "true");
|
|
180
221
|
return await headersHook?.(headers, context) ?? headers;
|
|
181
222
|
};
|
|
182
|
-
const sendUpload = async (request, api, extraOptions) => {
|
|
223
|
+
const sendUpload = async (request, boundSessionKey, api, extraOptions) => {
|
|
183
224
|
const headers = await uploadHeaders(request, api, extraOptions);
|
|
225
|
+
if (!await isBoundSessionCurrent(boundSessionKey, api)) return sessionChanged;
|
|
184
226
|
const query = request.params ? dddParamsSerializer(request.params) : "";
|
|
185
227
|
const url = `${options.baseUrl.replace(/\/+$/, "")}/${request.url.replace(/^\/+/, "")}${query ? `${request.url.includes("?") ? "&" : "?"}${query}` : ""}`;
|
|
186
228
|
return new Promise((resolve) => {
|
|
@@ -218,12 +260,14 @@ function createDddBaseQuery(options) {
|
|
|
218
260
|
});
|
|
219
261
|
};
|
|
220
262
|
const upload = async (request, api, extraOptions) => {
|
|
263
|
+
const boundSessionKey = await resolveBoundSessionKey(request.expectedSessionKey, api, extraOptions);
|
|
221
264
|
while (inflight) await inflight.catch(() => void 0);
|
|
222
265
|
const startGeneration = generation;
|
|
223
|
-
const result = await sendUpload(request, api, extraOptions);
|
|
224
|
-
if (!result.error ||
|
|
266
|
+
const result = await sendUpload(request, boundSessionKey, api, extraOptions);
|
|
267
|
+
if (!result.error || isDddSessionChanged(result.error)) return result;
|
|
268
|
+
if (!shouldRefresh(result.error, { url: request.url, method: request.method ?? "POST" })) return result;
|
|
225
269
|
if (await recover(startGeneration, api, extraOptions) !== "refreshed") return result;
|
|
226
|
-
return sendUpload(request, api, extraOptions);
|
|
270
|
+
return sendUpload(request, boundSessionKey, api, extraOptions);
|
|
227
271
|
};
|
|
228
272
|
return Object.assign(baseQuery, { upload });
|
|
229
273
|
}
|
|
@@ -379,7 +423,9 @@ function createAuthEndpoints(api, options) {
|
|
|
379
423
|
});
|
|
380
424
|
}
|
|
381
425
|
export {
|
|
426
|
+
DDD_EXPECTED_SESSION_KEY_HEADER,
|
|
382
427
|
DDD_MULTIPART_BODY_FIELD,
|
|
428
|
+
DDD_SESSION_CHANGED,
|
|
383
429
|
DDD_UPLOAD_ABORTED,
|
|
384
430
|
DEFAULT_ERROR_MESSAGE,
|
|
385
431
|
DEFAULT_ERROR_MESSAGES,
|
|
@@ -400,9 +446,11 @@ export {
|
|
|
400
446
|
getRequestUrl,
|
|
401
447
|
hasDddMultipartFiles,
|
|
402
448
|
isDddAuthRequest,
|
|
449
|
+
isDddSessionChanged,
|
|
403
450
|
isDddUploadAborted,
|
|
404
451
|
mergeDddTagTypes,
|
|
405
452
|
normalizeDddError,
|
|
406
|
-
readDebugFlags
|
|
453
|
+
readDebugFlags,
|
|
454
|
+
withDddExpectedSessionKey
|
|
407
455
|
};
|
|
408
456
|
//# sourceMappingURL=index.js.map
|
package/dist/api/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/api/baseQuery.ts","../../src/api/debug.ts","../../src/api/multipart.ts","../../src/api/refresh.ts","../../src/api/tags.ts","../../src/api/errors.ts","../../src/api/download.ts","../../src/api/endpoints.ts"],"sourcesContent":["import {\n fetchBaseQuery,\n type BaseQueryApi,\n type BaseQueryFn,\n type FetchArgs,\n type FetchBaseQueryArgs,\n type FetchBaseQueryError,\n type FetchBaseQueryMeta,\n} from '@reduxjs/toolkit/query';\nimport type { DddTokens } from '../auth/types';\nimport { applyDebugParams, readDebugFlags, type DddDebugOptions } from './debug';\nimport { buildDddFormData, type DddMultipartFiles } from './multipart';\nimport { createDddRefresh, type DddRawBaseQuery, type DddRefreshFn, type DddReloginFn } from './refresh';\n\ntype MaybePromise<T> = T | Promise<T>;\n\n/** Result of one refresh attempt: new tokens stored, session ended, session replaced while refreshing, or thrown. */\ntype RefreshOutcome = 'refreshed' | 'failed' | 'superseded' | 'error';\n\n/** What `getTokens` can see: the request's Redux context (no dispatch). */\nexport type DddRequestContext = Pick<BaseQueryApi, 'getState' | 'extra' | 'endpoint' | 'type'>;\n\n/** Context of the `headers` / `languageCode` hooks (RTK's `prepareHeaders` context). */\nexport type DddHeadersContext = Parameters<NonNullable<FetchBaseQueryArgs['prepareHeaders']>>[1];\n\n/** Decides whether a failed request is worth a token refresh and one retry. */\nexport type DddShouldRefresh = (error: FetchBaseQueryError, request: FetchArgs) => boolean;\n\n/** The base query type of a DDD api (what {@link createAuthEndpoints} and wrappers accept). */\nexport type DddBaseQuery = BaseQueryFn<string | FetchArgs, unknown, FetchBaseQueryError, {}, FetchBaseQueryMeta>;\n\n/** One upload sent by {@link DddUploadingBaseQuery.upload}. */\nexport interface DddUploadRequest {\n /** Path relative to the base URL. */\n url: string;\n /** Default `POST`. */\n method?: string;\n /** JSON envelope, sent in the form field `body`; left out when `undefined`. */\n body?: unknown;\n /** File parts per form field (the `Parameter::FILES` properties of the request DTO). */\n files: DddMultipartFiles;\n /** Query parameters; `null` / `undefined` values are skipped. */\n params?: Record<string, unknown>;\n /** Bytes of the request body sent so far. Called again from 0 when the upload is repeated after a refresh. */\n onProgress?: (loaded: number, total: number) => void;\n /** Aborting cancels the request; the result is then the error of {@link isDddUploadAborted}. */\n signal?: AbortSignal;\n}\n\n/** Result of an upload: the shape an RTK `queryFn` returns. */\nexport type DddUploadResult = { data: unknown; error?: undefined } | { data?: undefined; error: FetchBaseQueryError };\n\n/** The base query returned by {@link createDddBaseQuery}: a {@link DddBaseQuery} that can also upload with progress. */\nexport type DddUploadingBaseQuery = DddBaseQuery & {\n /**\n * Sends a multipart upload with progress (XMLHttpRequest: `fetch` reports no upload progress) through the same\n * session as every request: Bearer, `headers` / `languageCode` hooks, one shared refresh and one retry.\n *\n * @example\n * uploadAttachment: build.mutation<AttachmentResponse, { id: number; file: File; onProgress?: (loaded: number, total: number) => void }>({\n * queryFn: ({ id, file, onProgress }, api, extraOptions) =>\n * dddBaseQuery.upload({ url: `/api/client/items/${id}/attachments`, files: { attachmentFiles: [file] }, onProgress }, api, extraOptions) as\n * Promise<{ data: AttachmentResponse } | { error: FetchBaseQueryError }>,\n * }),\n */\n upload: (request: DddUploadRequest, api: BaseQueryApi, extraOptions?: unknown) => Promise<DddUploadResult>;\n};\n\n/** `error.error` of an upload cancelled through its `signal`. */\nexport const DDD_UPLOAD_ABORTED = 'DDD_UPLOAD_ABORTED';\n\n/** True for the error of an upload that was cancelled through its `signal`. */\nexport const isDddUploadAborted = (error: unknown): boolean =>\n !!error && typeof error === 'object' && (error as { status?: unknown; error?: unknown }).status === 'CUSTOM_ERROR' &&\n (error as { error?: unknown }).error === DDD_UPLOAD_ABORTED;\n\n/** Options of {@link createDddBaseQuery}. */\nexport interface DddBaseQueryOptions {\n /** API origin, e.g. `https://api.example.com`. Request URLs are relative to it. */\n baseUrl: string;\n /** Current tokens, typically read from the Redux state (`context.getState()`) or a {@link TokenStorage}. */\n getTokens: (context: DddRequestContext) => MaybePromise<Partial<DddTokens> | null | undefined>;\n /** Stores a freshly refreshed token pair (dispatch a Redux action, write storage, …). */\n setTokens: (tokens: DddTokens, api: BaseQueryApi) => MaybePromise<void>;\n /** Called once when the session cannot be recovered (no refresh token, or the refresh was rejected). */\n onLogout: (api: BaseQueryApi) => MaybePromise<void>;\n /** Custom refresh. Default: {@link createDddRefresh} on `refreshPath`. */\n refresh?: DddRefreshFn;\n /** Refresh endpoint for the default refresh, e.g. `/api/admin/common/auth/refresh`. Required without `refresh`. */\n refreshPath?: string;\n /**\n * Re-opens the session when the refresh cannot: no refresh token is stored (guest, impersonation or device\n * sessions), or the refresh token was rejected. Return the new tokens, or `null` to end the session (`onLogout`).\n * Without it a refresh-worthy failure without refresh token logs out directly.\n *\n * @example\n * // A guest session is re-opened from its stored credential:\n * relogin: async ({ baseQuery, api, extraOptions }) => {\n * const credential = readGuestCredential();\n * if (!credential) return null;\n * const result = await baseQuery({ url: '/api/public/common/auth/guest', method: 'POST', body: { credential } }, api, extraOptions as {});\n * const data = result.data as { accessToken?: string; refreshToken?: string | null } | undefined;\n * return data?.accessToken ? { accessToken: data.accessToken, refreshToken: data.refreshToken ?? null } : null;\n * },\n */\n relogin?: DddReloginFn;\n /** Creates the request object of an upload. Default `new XMLHttpRequest()`. */\n createUploadRequest?: () => XMLHttpRequest;\n /**\n * Adds or changes headers after the Bearer header is set; return value as in RTK's `prepareHeaders`.\n * `context.type` tells reads (`query`) from writes (`mutation`).\n */\n headers?: (headers: Headers, context: DddHeadersContext) => MaybePromise<Headers | void>;\n /**\n * Shortcut for the DDD `languageCode` header. Return e.g. the form's editing language for mutations and the UI\n * language for queries; a falsy value sends no header.\n */\n languageCode?: (context: DddHeadersContext) => string | null | undefined;\n /**\n * Decides whether a failed request triggers a refresh and one retry. Default {@link defaultShouldRefresh}\n * (status 401, auth endpoints excluded).\n *\n * @example\n * // Also refresh on 403, except for 403s that are business refusals:\n * shouldRefresh: (error, request) =>\n * (error.status === 401 || error.status === 403) && !isBusinessRefusal(error) && !isDddAuthRequest(request)\n */\n shouldRefresh?: DddShouldRefresh;\n /** Debug passthrough of page URL flags (`?debug`, `?noCache`, `?xdebug`, `?errorsAsJson`). Default off. */\n debug?: boolean | DddDebugOptions;\n /** Further `fetchBaseQuery` options (`fetchFn`, `timeout`, `credentials`, `paramsSerializer`, …). */\n fetchOptions?: Omit<FetchBaseQueryArgs, 'baseUrl' | 'prepareHeaders'>;\n}\n\n/** URL path of a request argument. */\nexport const getRequestUrl = (request: string | FetchArgs): string =>\n typeof request === 'string' ? request : request.url;\n\n/** True for the DDD auth endpoints (`…/common/auth/…`); they never trigger a refresh, they ARE the recovery. */\nexport const isDddAuthRequest = (request: string | FetchArgs): boolean =>\n getRequestUrl(request).includes('/common/auth/');\n\n/** Default refresh decision: HTTP 401 on anything but an auth endpoint. */\nexport const defaultShouldRefresh: DddShouldRefresh = (error, request) =>\n error.status === 401 && !isDddAuthRequest(request);\n\n/**\n * Query-string serializer that skips `null` / `undefined` values (the generated SDK passes every optional parameter).\n */\nexport const dddParamsSerializer = (params: Record<string, unknown>): string =>\n Object.entries(params)\n .filter(([, value]) => value !== null && value !== undefined)\n .map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(String(value))}`)\n .join('&');\n\nconst toFetchArgs = (args: string | FetchArgs): FetchArgs => (typeof args === 'string' ? { url: args } : args);\n\nconst withBearer = (args: FetchArgs, accessToken: string | null | undefined): FetchArgs => {\n if (!accessToken) return args;\n const headers = new Headers();\n const source = args.headers;\n if (source instanceof Headers) source.forEach((value, key) => headers.set(key, value));\n else if (Array.isArray(source)) source.forEach(([key, value]) => key !== undefined && headers.set(key, value ?? ''));\n else if (source) Object.entries(source).forEach(([key, value]) => value !== undefined && headers.set(key, value));\n if (!headers.has('authorization')) headers.set('authorization', `Bearer ${accessToken}`);\n return { ...args, headers };\n};\n\n/**\n * Creates the RTK Query base query for a DDD backend.\n *\n * - Sends `Authorization: Bearer <accessToken>` from `getTokens()`.\n * - On a refresh-worthy failure (`shouldRefresh`, default 401) runs ONE shared refresh and retries the request exactly\n * once. Concurrent failures share that refresh and its result; a request whose failure predates a refresh that\n * finished meanwhile reuses that refresh's result instead of refreshing again.\n * - No refresh token, or a rejected refresh → `relogin()` when given; without it, or when it returns `null`,\n * `onLogout()` once for that session and the original error is returned.\n * - A refresh whose session was logged out or replaced while it ran is discarded (no `setTokens`, no retry).\n *\n * @example\n * export const baseApi = createApi({\n * baseQuery: createDddBaseQuery({\n * baseUrl: 'https://api.example.com',\n * refreshPath: '/api/admin/common/auth/refresh',\n * getTokens: ({ getState }) => (getState() as RootState).auth,\n * setTokens: (tokens, { dispatch }) => dispatch(authActions.updateTokens(tokens)),\n * onLogout: ({ dispatch }) => dispatch(authActions.logout()),\n * }),\n * endpoints: () => ({}),\n * });\n */\nexport function createDddBaseQuery(options: DddBaseQueryOptions): DddUploadingBaseQuery {\n const { getTokens, setTokens, onLogout, headers: headersHook, languageCode, fetchOptions, relogin } = options;\n const shouldRefresh = options.shouldRefresh ?? defaultShouldRefresh;\n if (!options.refresh && !options.refreshPath) {\n throw new Error('createDddBaseQuery: pass either `refresh` or `refreshPath`.');\n }\n const refresh = options.refresh ?? createDddRefresh(options.refreshPath as string);\n const debugOptions: DddDebugOptions | null =\n options.debug === true ? {} : options.debug ? options.debug : null;\n\n const fetchQuery = fetchBaseQuery({\n paramsSerializer: dddParamsSerializer,\n ...fetchOptions,\n baseUrl: options.baseUrl,\n prepareHeaders: async (headers, context) => {\n const language = languageCode?.(context);\n if (language) headers.set('languageCode', language);\n if (debugOptions && readDebugFlags(debugOptions).debug) headers.set('x-debug', 'true');\n return (await headersHook?.(headers, context)) ?? headers;\n },\n });\n\n /** One request without auth recovery: debug passthrough + fetch. */\n const rawBaseQuery: DddRawBaseQuery = (args, api, extraOptions) => {\n const finalArgs = debugOptions\n ? applyDebugParams(args, readDebugFlags(debugOptions), debugOptions.xdebugSessionKey)\n : args;\n return fetchQuery(finalArgs, api, extraOptions as {});\n };\n\n /**\n * Refresh coordination. Every finished refresh attempt starts a new session generation and records its outcome; a\n * request remembers the generation it started in. A refresh-worthy failure in the current generation runs (or\n * joins) the one refresh of that generation; a failure from an older generation reuses the recorded outcome, so a\n * late 401 after a failed refresh neither refreshes nor logs out again.\n */\n let generation = 0;\n let lastOutcome: RefreshOutcome | null = null;\n let inflight: Promise<void> | null = null;\n\n const currentAccessToken = async (api: BaseQueryApi): Promise<string | null> =>\n (await getTokens(api))?.accessToken ?? null;\n\n const runRefresh = async (api: BaseQueryApi, extraOptions: unknown): Promise<RefreshOutcome> => {\n const before = await getTokens(api);\n const refreshToken = before?.refreshToken ?? null;\n const accessTokenBefore = before?.accessToken ?? null;\n let pair = refreshToken ? await refresh({ refreshToken, baseQuery: rawBaseQuery, api, extraOptions }) : null;\n if (!pair?.accessToken && relogin) {\n pair = await relogin({\n reason: refreshToken ? 'refresh-rejected' : 'no-refresh-token',\n baseQuery: rawBaseQuery,\n api,\n extraOptions,\n });\n }\n // The session may have ended (logout) or changed (another login) while the refresh ran: its result belongs to\n // a session that is gone and must not be stored.\n const after = await getTokens(api);\n if ((after?.refreshToken ?? null) !== refreshToken) return 'superseded';\n // A session without refresh token is identified by its access token.\n if (refreshToken === null && (after?.accessToken ?? null) !== accessTokenBefore) return 'superseded';\n if (!pair?.accessToken) {\n await onLogout(api);\n return 'failed';\n }\n await setTokens({ accessToken: pair.accessToken, refreshToken: pair.refreshToken ?? refreshToken }, api);\n return 'refreshed';\n };\n\n /** Runs or joins the refresh of `startGeneration`; returns the outcome that applies to a request of that generation. */\n const recover = async (startGeneration: number, api: BaseQueryApi, extraOptions: unknown): Promise<RefreshOutcome | null> => {\n if (generation === startGeneration && !inflight) {\n inflight = (async () => {\n try {\n lastOutcome = await runRefresh(api, extraOptions);\n } catch (error) {\n lastOutcome = 'error';\n throw error;\n } finally {\n generation++;\n inflight = null;\n }\n })();\n }\n if (inflight) await inflight;\n return lastOutcome;\n };\n\n const baseQuery: DddBaseQuery = async (args, api, extraOptions) => {\n // A request started during a refresh waits for it and then sends the current token.\n while (inflight) await inflight.catch(() => undefined);\n const startGeneration = generation;\n const request = toFetchArgs(args);\n const result = await rawBaseQuery(withBearer(request, await currentAccessToken(api)), api, extraOptions);\n if (!result.error || !shouldRefresh(result.error, request)) return result;\n if ((await recover(startGeneration, api, extraOptions)) !== 'refreshed') return result;\n return rawBaseQuery(withBearer(request, await currentAccessToken(api)), api, extraOptions);\n };\n\n /** Headers of an upload: Bearer, then the same hooks as a fetch request. No content type: the runtime sets it. */\n const uploadHeaders = async (request: DddUploadRequest, api: BaseQueryApi, extraOptions: unknown): Promise<Headers> => {\n const headers = new Headers();\n const accessToken = await currentAccessToken(api);\n if (accessToken) headers.set('authorization', `Bearer ${accessToken}`);\n const context = {\n getState: api.getState,\n extra: api.extra,\n endpoint: api.endpoint,\n type: api.type,\n forced: api.forced,\n arg: { url: request.url, method: request.method ?? 'POST' },\n extraOptions,\n } as DddHeadersContext;\n const language = languageCode?.(context);\n if (language) headers.set('languageCode', language);\n if (debugOptions && readDebugFlags(debugOptions).debug) headers.set('x-debug', 'true');\n return (await headersHook?.(headers, context)) ?? headers;\n };\n\n const sendUpload = async (request: DddUploadRequest, api: BaseQueryApi, extraOptions: unknown): Promise<DddUploadResult> => {\n const headers = await uploadHeaders(request, api, extraOptions);\n const query = request.params ? dddParamsSerializer(request.params) : '';\n const url = `${options.baseUrl.replace(/\\/+$/, '')}/${request.url.replace(/^\\/+/, '')}${query ? `${request.url.includes('?') ? '&' : '?'}${query}` : ''}`;\n return new Promise<DddUploadResult>((resolve) => {\n const { signal, onProgress } = request;\n const aborted: DddUploadResult = { error: { status: 'CUSTOM_ERROR', error: DDD_UPLOAD_ABORTED } };\n if (signal?.aborted) return resolve(aborted);\n const xhr = options.createUploadRequest ? options.createUploadRequest() : new XMLHttpRequest();\n const onAbort = (): void => xhr.abort();\n signal?.addEventListener('abort', onAbort, { once: true });\n const finish = (result: DddUploadResult): void => {\n signal?.removeEventListener('abort', onAbort);\n resolve(result);\n };\n xhr.open(request.method ?? 'POST', url);\n headers.forEach((value, name) => xhr.setRequestHeader(name, value));\n if (onProgress && xhr.upload) {\n xhr.upload.onprogress = (event) => {\n if (event.lengthComputable) onProgress(event.loaded, event.total);\n };\n }\n xhr.onload = () => {\n const text = xhr.responseText;\n let data: unknown;\n try {\n data = text ? JSON.parse(text) : undefined;\n } catch {\n data = text;\n }\n if (xhr.status >= 200 && xhr.status < 300) finish({ data: data ?? null });\n else finish({ error: { status: xhr.status, data } });\n };\n xhr.onerror = () => finish({ error: { status: 'FETCH_ERROR', error: 'The upload did not reach the server.' } });\n xhr.onabort = () => finish(aborted);\n xhr.send(buildDddFormData(request.body, request.files));\n });\n };\n\n const upload: DddUploadingBaseQuery['upload'] = async (request, api, extraOptions) => {\n while (inflight) await inflight.catch(() => undefined);\n const startGeneration = generation;\n const result = await sendUpload(request, api, extraOptions);\n if (!result.error || !shouldRefresh(result.error, { url: request.url, method: request.method ?? 'POST' })) return result;\n if ((await recover(startGeneration, api, extraOptions)) !== 'refreshed') return result;\n return sendUpload(request, api, extraOptions);\n };\n\n return Object.assign(baseQuery, { upload });\n}\n","import type { FetchArgs } from '@reduxjs/toolkit/query';\n\n/**\n * Debug passthrough: flags present in the page URL (`?debug`, `?noCache`, `?xdebug`, `?errorsAsJson`) are forwarded to\n * every API request as the query parameters a DDD backend understands.\n */\nexport interface DddDebugOptions {\n /** Where the flags come from. Default: `window.location.search` (nothing outside a browser). */\n searchParams?: () => URLSearchParams | null | undefined;\n /** Value of `XDEBUG_SESSION` when `?xdebug` is set. Default `1`. */\n xdebugSessionKey?: string;\n}\n\n/** The debug flags active for one request. */\nexport interface DddDebugFlags {\n debug: boolean;\n noCache: boolean;\n xdebug: boolean;\n errorsAsJson: boolean;\n}\n\nconst defaultSearchParams = (): URLSearchParams | null =>\n typeof window !== 'undefined' && window.location ? new URLSearchParams(window.location.search) : null;\n\n/** Reads the active debug flags. */\nexport function readDebugFlags(options: DddDebugOptions = {}): DddDebugFlags {\n const params = (options.searchParams ?? defaultSearchParams)() ?? null;\n return {\n debug: params?.has('debug') ?? false,\n noCache: params?.has('noCache') ?? false,\n xdebug: params?.has('xdebug') ?? false,\n errorsAsJson: params?.has('errorsAsJson') ?? false,\n };\n}\n\nconst appendToUrl = (url: string, key: string, value: string): string =>\n new RegExp(`[?&]${key}=`, 'i').test(url)\n ? url\n : `${url}${url.includes('?') ? '&' : '?'}${encodeURIComponent(key)}=${encodeURIComponent(value)}`;\n\n/**\n * Adds the query parameters for the active debug flags to a request, never overwriting a parameter the caller set.\n */\nexport function applyDebugParams(\n args: string | FetchArgs,\n flags: DddDebugFlags,\n xdebugSessionKey = '1',\n): string | FetchArgs {\n const extra: Array<[string, string]> = [];\n if (flags.debug) extra.push(['debug', 'true']);\n if (flags.noCache) extra.push(['noCache', 'true']);\n if (flags.xdebug) extra.push(['XDEBUG_SESSION', xdebugSessionKey]);\n if (flags.errorsAsJson) extra.push(['errors_as_json', '1']);\n if (extra.length === 0) return args;\n\n if (typeof args === 'string') {\n return extra.reduce((url, [key, value]) => appendToUrl(url, key, value), args);\n }\n const params: Record<string, unknown> = { ...(args.params ?? {}) };\n for (const [key, value] of extra) {\n if (params[key] === undefined && !new RegExp(`[?&]${key}=`, 'i').test(args.url)) params[key] = value;\n }\n return { ...args, params };\n}\n","/**\n * One file part: a `File` / `Blob` in a browser, or React Native's `{ uri, name, type }` file reference.\n */\nexport type DddFilePart = Blob | { uri: string; name: string; type: string };\n\n/** File parts per form field of a DDD request DTO (its `Parameter::FILES` properties). */\nexport type DddMultipartFiles<Field extends string = string> = Partial<\n Record<Field, readonly DddFilePart[] | DddFilePart | null | undefined>\n>;\n\n/** Form field a DDD backend reads the JSON envelope of a multipart request from. */\nexport const DDD_MULTIPART_BODY_FIELD = 'body';\n\nconst partsOf = (value: readonly DddFilePart[] | DddFilePart | null | undefined): readonly DddFilePart[] => {\n if (value === null || value === undefined) return [];\n return Array.isArray(value) ? (value as readonly DddFilePart[]) : [value as DddFilePart];\n};\n\n/** True when at least one file part is present. */\nexport function hasDddMultipartFiles(files: DddMultipartFiles | null | undefined): boolean {\n return !!files && Object.values(files).some((value) => partsOf(value).length > 0);\n}\n\n/**\n * The `multipart/form-data` body of a DDD request: the JSON envelope in the form field `body` (left out when\n * `body` is `undefined`) and every file as a part named `<field>[]`. No `Content-Type` header must be set for it: the\n * runtime adds the multipart boundary itself.\n */\nexport function buildDddFormData(body: unknown, files: DddMultipartFiles | null | undefined): FormData {\n const formData = new FormData();\n if (body !== undefined) formData.append(DDD_MULTIPART_BODY_FIELD, JSON.stringify(body));\n for (const [field, value] of Object.entries(files ?? {})) {\n for (const part of partsOf(value)) {\n const name = typeof (part as { name?: unknown }).name === 'string' ? (part as { name: string }).name : '';\n // A React Native file reference is appended as it is; a Blob without a name gets the field name.\n if (typeof Blob !== 'undefined' && part instanceof Blob) formData.append(`${field}[]`, part, name || field);\n else formData.append(`${field}[]`, part as unknown as Blob);\n }\n }\n return formData;\n}\n\n/**\n * Request body of an endpoint that accepts JSON and file parts: `body` itself while no file is given (a plain JSON\n * request), else the multipart form of {@link buildDddFormData}. Generated endpoints of operations with a\n * `multipart/form-data` request body call it with their `multipartFiles` argument.\n */\nexport function buildDddMultipartBody<Body>(body: Body, files: DddMultipartFiles | null | undefined): Body | FormData {\n return hasDddMultipartFiles(files) ? buildDddFormData(body, files) : body;\n}\n","import type { BaseQueryApi, BaseQueryFn, FetchArgs, FetchBaseQueryError, FetchBaseQueryMeta } from '@reduxjs/toolkit/query';\nimport type { DddAuthResponse, DddTokens } from '../auth/types';\n\n/** The raw (non-refreshing) base query handed to a refresh function. */\nexport type DddRawBaseQuery = BaseQueryFn<string | FetchArgs, unknown, FetchBaseQueryError, {}, FetchBaseQueryMeta>;\n\n/** Everything a refresh function needs. */\nexport interface DddRefreshContext {\n /** The refresh token currently stored. */\n refreshToken: string;\n /** The underlying fetch base query (no auth retry, Bearer of the current access token still applied). */\n baseQuery: DddRawBaseQuery;\n api: BaseQueryApi;\n extraOptions: unknown;\n}\n\n/**\n * Exchanges a refresh token for a new token pair.\n *\n * @returns the new pair, or `null` when the refresh token was rejected (the base query then logs out).\n * A missing `refreshToken` in the result keeps the stored one.\n */\nexport type DddRefreshFn = (context: DddRefreshContext) => Promise<DddTokens | null>;\n\n/** Everything a re-login function needs. */\nexport interface DddReloginContext {\n /** Why the refresh could not recover the session. */\n reason: 'no-refresh-token' | 'refresh-rejected';\n /** The underlying fetch base query (no auth retry, Bearer of the current access token still applied). */\n baseQuery: DddRawBaseQuery;\n api: BaseQueryApi;\n extraOptions: unknown;\n}\n\n/**\n * Re-opens a session without a usable refresh token (guest credential, device id, impersonation through another\n * session, …).\n *\n * @returns the new tokens (`refreshToken: null` for a session that has none), or `null` to end the session.\n */\nexport type DddReloginFn = (context: DddReloginContext) => Promise<DddTokens | null>;\n\n/**\n * The default {@link DddRefreshFn}: `POST <path>` with `{ refreshToken }`, expecting the DDD `AuthPostResponseDto`\n * `{ accessToken, refreshToken }`. DDD refresh tokens are stateless and re-issued with a renewed lifetime.\n *\n * @param path refresh endpoint relative to the base URL, e.g. `/api/admin/common/auth/refresh`\n */\nexport function createDddRefresh(path: string): DddRefreshFn {\n return async ({ refreshToken, baseQuery, api, extraOptions }) => {\n const result = await baseQuery({ url: path, method: 'POST', body: { refreshToken } }, api, extraOptions as {});\n const payload = result.data as DddAuthResponse | undefined;\n if (result.error || !payload?.accessToken) return null;\n return { accessToken: payload.accessToken, refreshToken: payload.refreshToken ?? refreshToken };\n };\n}\n","/** The tags of `Extra` that differ from a tag of `Generated` only by case. */\ntype DddTagCaseConflict<Extra extends string, Generated extends string> = Extra extends Generated\n ? never\n : Lowercase<Extra> extends Lowercase<Generated>\n ? Extra\n : never;\n\ntype DddTagCheck<Generated extends readonly string[], Extra extends readonly string[]> = [\n DddTagCaseConflict<Extra[number], Generated[number]>,\n] extends [never]\n ? unknown\n : { 'tag differs from a generated tag only by case': DddTagCaseConflict<Extra[number], Generated[number]> };\n\n/**\n * The `tagTypes` of a base api: the generated tag lists (`<stem>TagTypes` of the `<stem>Tags.ts` files) plus the\n * app's own tags. With this list every `providesTags` / `invalidatesTags` of a hand-written endpoint and every\n * `api.util.invalidateTags()` is checked against the generated names, so a mistyped tag does not compile. An own tag\n * that differs from a generated one only by case (`ProspectActivities` next to the generated `Prospectactivities`)\n * is rejected here: it would be a second tag that no generated endpoint provides.\n *\n * @example\n * export const baseApi = createApi({\n * baseQuery,\n * tagTypes: mergeDddTagTypes([...adminApiTagTypes, ...clientApiTagTypes], ['Session']),\n * endpoints: () => ({}),\n * });\n */\nexport function mergeDddTagTypes<const Generated extends readonly string[], const Extra extends readonly string[] = readonly []>(\n generated: Generated,\n extra?: Extra & DddTagCheck<Generated, Extra>,\n): (Generated[number] | Extra[number])[] {\n return [...new Set<string>([...generated, ...(extra ?? [])])] as (Generated[number] | Extra[number])[];\n}\n","import type { DddErrorBody, DddExceptionDetail } from '../contract/errors';\n\n/** A DDD API error in one predictable shape, whatever produced it (RTK Query, a thrown Error, a raw body). */\nexport interface DddNormalizedError {\n /**\n * HTTP status, or RTK Query's string status for non-HTTP failures (`FETCH_ERROR`, `TIMEOUT_ERROR`,\n * `CUSTOM_ERROR`); a `PARSING_ERROR` reports the original HTTP status. `null` when unknown.\n */\n status: number | string | null;\n /** Human-readable message: the backend's `error` key first, then a text body, then generic fallbacks. */\n message: string;\n /** The backend's `validationErrors` exactly as received (present on validation 400s), else `null`. */\n validationErrors: unknown;\n /** `exceptionDetails.elements` of the backend body; empty when absent. */\n details: DddExceptionDetail[];\n /** The raw response body (parsed JSON, text, or `undefined`). */\n body: unknown;\n}\n\n/** Message used when an error carries no message at all. */\nexport const DEFAULT_ERROR_MESSAGE = 'Request failed';\n\n/**\n * Messages for failures that carry no usable backend message. Pass your own (e.g. translated) texts as the third\n * argument of {@link normalizeDddError} / {@link getErrorMessage}.\n */\nexport interface DddErrorMessages {\n /** A response that is not JSON (an HTML error page, a PHP fatal) with an HTTP status ≥ 500. */\n serverError: (status: number) => string;\n /** A response that is not JSON with an HTTP status < 500. */\n httpError: (status: number) => string;\n /** The request never reached the server or got no response (`FETCH_ERROR`). */\n networkError: string;\n /** The request timed out (`TIMEOUT_ERROR`). */\n timeoutError: string;\n}\n\n/** The default {@link DddErrorMessages}. */\nexport const DEFAULT_ERROR_MESSAGES: DddErrorMessages = {\n serverError: (status) => `Server error (HTTP ${status})`,\n httpError: (status) => `Request failed (HTTP ${status})`,\n networkError: 'The server could not be reached',\n timeoutError: 'The request timed out',\n};\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n value !== null && typeof value === 'object' && !Array.isArray(value);\n\nconst nonEmptyString = (value: unknown): string | null =>\n typeof value === 'string' && value.trim() !== '' ? value : null;\n\n/** Unwraps the places a response body can sit: RTK `data`, an Error's `responseBody`, or the value itself. */\nconst extractBody = (error: Record<string, unknown>): unknown => {\n if ('data' in error) return error.data;\n if ('responseBody' in error) return error.responseBody;\n if ('error' in error || 'validationErrors' in error || 'exceptionDetails' in error) return error;\n return undefined;\n};\n\nconst extractStatus = (error: Record<string, unknown>): number | string | null => {\n if (error.status === 'PARSING_ERROR' && typeof error.originalStatus === 'number') return error.originalStatus;\n if (typeof error.status === 'number' || typeof error.status === 'string') return error.status;\n if (typeof error.statusCode === 'number') return error.statusCode;\n return null;\n};\n\n/**\n * The message of an RTK Query failure that is not a DDD response: an unparsable body (`PARSING_ERROR`), no response\n * (`FETCH_ERROR`), a timeout (`TIMEOUT_ERROR`); `null` for everything else.\n */\nconst transportFailureMessage = (\n error: Record<string, unknown>,\n texts: DddErrorMessages,\n fallbackMessage: string,\n): string | null => {\n switch (error.status) {\n case 'PARSING_ERROR': {\n const status = typeof error.originalStatus === 'number' ? error.originalStatus : null;\n if (status === null) return fallbackMessage;\n return status >= 500 ? texts.serverError(status) : texts.httpError(status);\n }\n case 'FETCH_ERROR':\n return texts.networkError;\n case 'TIMEOUT_ERROR':\n return texts.timeoutError;\n default:\n return null;\n }\n};\n\n/**\n * Normalises any API error into {@link DddNormalizedError}.\n *\n * Understands RTK Query's `FetchBaseQueryError` (`{ status, data }`, `{ status: 'FETCH_ERROR', error }`, …),\n * `SerializedError` / `Error` (`message`), errors carrying a parsed `responseBody`, and a bare DDD error body.\n * DDD error bodies put the message under `error` (not `message`).\n *\n * A response the client could not parse (`PARSING_ERROR`: an HTML error page, a PHP fatal, a proxy's 502) is an HTTP\n * error: `status` is the HTTP status and the message is {@link DddErrorMessages.serverError} /\n * {@link DddErrorMessages.httpError} — never the parser's `SyntaxError` text and never the raw body, which may show\n * internals (the body stays available in `body`). `FETCH_ERROR` and `TIMEOUT_ERROR` get\n * {@link DddErrorMessages.networkError} / {@link DddErrorMessages.timeoutError} instead of the browser's text.\n *\n * @param error whatever a request rejected with\n * @param fallbackMessage message when nothing usable is found\n * @param messages texts for failures without a backend message (default {@link DEFAULT_ERROR_MESSAGES})\n */\nexport function normalizeDddError(\n error: unknown,\n fallbackMessage: string = DEFAULT_ERROR_MESSAGE,\n messages: Partial<DddErrorMessages> = {},\n): DddNormalizedError {\n const texts: DddErrorMessages = { ...DEFAULT_ERROR_MESSAGES, ...messages };\n if (!isRecord(error)) {\n return {\n status: null,\n message: nonEmptyString(error) ?? fallbackMessage,\n validationErrors: null,\n details: [],\n body: undefined,\n };\n }\n\n const body = extractBody(error);\n const failure = transportFailureMessage(error, texts, fallbackMessage);\n if (failure !== null) {\n return { status: extractStatus(error), message: failure, validationErrors: null, details: [], body };\n }\n const dddBody: DddErrorBody | null = isRecord(body) ? (body as DddErrorBody) : null;\n const bodyRecord: Record<string, unknown> | null = isRecord(body) ? body : null;\n\n const message =\n nonEmptyString(dddBody?.error) ??\n nonEmptyString(bodyRecord?.message) ??\n // RTK's non-HTTP errors carry the reason in `error` (e.g. \"TypeError: Failed to fetch\").\n (body === undefined || typeof body === 'string' ? nonEmptyString(error.error) : null) ??\n // A non-JSON error body (e.g. a download endpoint answering with plain text) is the message itself.\n nonEmptyString(body)?.trim() ??\n nonEmptyString(error.message) ??\n fallbackMessage;\n\n return {\n status: extractStatus(error),\n message,\n validationErrors: dddBody?.validationErrors ?? null,\n details: dddBody?.exceptionDetails?.elements ?? [],\n body,\n };\n}\n\n/**\n * The message to show for an API error (`normalizeDddError(error).message`).\n *\n * @param error whatever a request rejected with\n * @param fallbackMessage message when nothing usable is found\n * @param messages texts for failures without a backend message\n */\nexport function getErrorMessage(\n error: unknown,\n fallbackMessage: string = DEFAULT_ERROR_MESSAGE,\n messages: Partial<DddErrorMessages> = {},\n): string {\n return normalizeDddError(error, fallbackMessage, messages).message;\n}\n\n/** HTTP status of an API error (also of an unparsable response), or `null` for non-HTTP failures. */\nexport function getErrorStatus(error: unknown): number | null {\n const status = normalizeDddError(error).status;\n return typeof status === 'number' ? status : null;\n}\n","/** A binary response decoded by {@link blobResponseHandler}. */\nexport interface DddFileResponse {\n blob: Blob;\n /** File name from `Content-Disposition`, else `null`. */\n filename: string | null;\n /** `Content-Type` of the response, else `null`. */\n contentType: string | null;\n}\n\n/** Serializable summary returned by {@link createDownloadResponseHandler} (safe to keep in the Redux store). */\nexport interface DddDownloadedFile {\n filename: string;\n contentType: string | null;\n size: number;\n}\n\n/**\n * Reads the file name from a `Content-Disposition` header. Prefers RFC 5987 `filename*=UTF-8''…` over `filename=`.\n *\n * @returns the decoded file name, or `null` when the header has none.\n */\nexport function filenameFromContentDisposition(header: string | null | undefined): string | null {\n if (!header) return null;\n const extended = /filename\\*\\s*=\\s*([^']*)'[^']*'([^;]+)/i.exec(header);\n if (extended?.[2]) {\n try {\n return decodeURIComponent(extended[2].trim().replace(/^\"|\"$/g, ''));\n } catch {\n // Malformed percent-encoding: fall back to the plain parameter.\n }\n }\n const plain = /filename\\s*=\\s*(\"([^\"]*)\"|[^;]*)/i.exec(header);\n const value = (plain?.[2] ?? plain?.[1] ?? '').trim();\n if (!value) return null;\n try {\n return decodeURIComponent(value);\n } catch {\n return value;\n }\n}\n\n/**\n * Triggers a browser download for an in-memory blob. No-op outside a browser.\n *\n * The anchor is attached before clicking (some browsers ignore detached anchors) and the object URL is revoked on the\n * next macrotask (revoking in the same task can cancel the download).\n */\nexport function downloadBlob(blob: Blob, filename: string): void {\n if (typeof document === 'undefined' || typeof URL.createObjectURL !== 'function') return;\n const url = URL.createObjectURL(blob);\n const anchor = document.createElement('a');\n anchor.href = url;\n anchor.download = filename;\n anchor.rel = 'noopener';\n document.body.appendChild(anchor);\n anchor.click();\n anchor.remove();\n setTimeout(() => URL.revokeObjectURL(url), 0);\n}\n\n/** Parses an error response as JSON when possible, else as text, so error normalisation keeps working. */\nconst parseErrorBody = async (response: Response): Promise<unknown> => {\n const text = await response.text();\n if (!text) return undefined;\n try {\n return JSON.parse(text);\n } catch {\n return text;\n }\n};\n\n/**\n * RTK Query `responseHandler` for binary endpoints: a successful response becomes a {@link DddFileResponse}, an error\n * response is parsed as JSON/text like any other error.\n *\n * Blobs are not serializable; keep such endpoints out of the cache (e.g. use a mutation or `keepUnusedDataFor: 0`) or\n * use {@link createDownloadResponseHandler}.\n *\n * @example\n * build.query<DddFileResponse, void>({ query: () => ({ url: '/export', responseHandler: blobResponseHandler }) })\n */\nexport async function blobResponseHandler(response: Response): Promise<DddFileResponse | unknown> {\n if (!response.ok) return parseErrorBody(response);\n return {\n blob: await response.blob(),\n filename: filenameFromContentDisposition(response.headers.get('content-disposition')),\n contentType: response.headers.get('content-type'),\n } satisfies DddFileResponse;\n}\n\n/**\n * Builds an RTK Query `responseHandler` that downloads a successful binary response right away and resolves to a\n * serializable {@link DddDownloadedFile}. Error responses are parsed as JSON/text.\n *\n * @param fallbackFilename used when the response has no `Content-Disposition` file name\n */\nexport function createDownloadResponseHandler(fallbackFilename = 'download') {\n return async (response: Response): Promise<DddDownloadedFile | unknown> => {\n if (!response.ok) return parseErrorBody(response);\n const blob = await response.blob();\n const filename = filenameFromContentDisposition(response.headers.get('content-disposition')) ?? fallbackFilename;\n downloadBlob(blob, filename);\n return { filename, contentType: response.headers.get('content-type'), size: blob.size } satisfies DddDownloadedFile;\n };\n}\n","import type { Api, ApiModules, EndpointDefinitions } from '@reduxjs/toolkit/query';\nimport type { DddBaseQuery } from './baseQuery';\nimport type { DddAuthResponse, DddLoginRequest, DddRefreshRequest } from '../auth/types';\n\n/** Options of {@link createAuthEndpoints}. */\nexport interface DddAuthEndpointsOptions {\n /** e.g. `/api/admin/common/auth/login` */\n loginPath: string;\n /** e.g. `/api/admin/common/auth/refresh` */\n refreshPath: string;\n}\n\n/**\n * Injects `authLogin` and `authRefresh` mutations for the DDD auth endpoints into an existing API.\n * Pure `injectEndpoints`, no React; with an API created by `@reduxjs/toolkit/query/react` the usual hooks\n * (`useAuthLoginMutation`, …) are generated as for any endpoint.\n *\n * The API must use the base query from {@link createDddBaseQuery}.\n *\n * Prefer the endpoints of your generated SDK when it already has them; this is for apps without one.\n */\nexport function createAuthEndpoints<\n Definitions extends EndpointDefinitions,\n ReducerPath extends string,\n TagTypes extends string,\n Enhancers extends keyof ApiModules<any, any, any, any>,\n>(api: Api<DddBaseQuery, Definitions, ReducerPath, TagTypes, Enhancers>, options: DddAuthEndpointsOptions) {\n return api.injectEndpoints({\n endpoints: (build) => ({\n authLogin: build.mutation<DddAuthResponse, DddLoginRequest>({\n query: (body) => ({ url: options.loginPath, method: 'POST', body }),\n }),\n authRefresh: build.mutation<DddAuthResponse, DddRefreshRequest>({\n query: (body) => ({ url: options.refreshPath, method: 'POST', body }),\n }),\n }),\n });\n}\n"],"mappings":";AAAA;AAAA,EACE;AAAA,OAOK;;;ACaP,IAAM,sBAAsB,MAC1B,OAAO,WAAW,eAAe,OAAO,WAAW,IAAI,gBAAgB,OA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AAS,KAAK;AACjC,MAAI,CAAC,KAAM,QAAO;AAClB,MAAI;AACF,WAAO,KAAK,MAAM,IAAI;AAAA,EACxB,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAYA,eAAsB,oBAAoB,UAAwD;AAChG,MAAI,CAAC,SAAS,GAAI,QAAO,eAAe,QAAQ;AAChD,SAAO;AAAA,IACL,MAAM,MAAM,SAAS,KAAK;AAAA,IAC1B,UAAU,+BAA+B,SAAS,QAAQ,IAAI,qBAAqB,CAAC;AAAA,IACpF,aAAa,SAAS,QAAQ,IAAI,cAAc;AAAA,EAClD;AACF;AAQO,SAAS,8BAA8B,mBAAmB,YAAY;AAC3E,SAAO,OAAO,aAA6D;AACzE,QAAI,CAAC,SAAS,GAAI,QAAO,eAAe,QAAQ;AAChD,UAAM,OAAO,MAAM,SAAS,KAAK;AACjC,UAAM,WAAW,+BAA+B,SAAS,QAAQ,IAAI,qBAAqB,CAAC,KAAK;AAChG,iBAAa,MAAM,QAAQ;AAC3B,WAAO,EAAE,UAAU,aAAa,SAAS,QAAQ,IAAI,cAAc,GAAG,MAAM,KAAK,KAAK;AAAA,EACxF;AACF;;;ACnFO,SAAS,oBAKd,KAAuE,SAAkC;AACzG,SAAO,IAAI,gBAAgB;AAAA,IACzB,WAAW,CAAC,WAAW;AAAA,MACrB,WAAW,MAAM,SAA2C;AAAA,QAC1D,OAAO,CAAC,UAAU,EAAE,KAAK,QAAQ,WAAW,QAAQ,QAAQ,KAAK;AAAA,MACnE,CAAC;AAAA,MACD,aAAa,MAAM,SAA6C;AAAA,QAC9D,OAAO,CAAC,UAAU,EAAE,KAAK,QAAQ,aAAa,QAAQ,QAAQ,KAAK;AAAA,MACrE,CAAC;AAAA,IACH;AAAA,EACF,CAAC;AACH;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../../src/api/baseQuery.ts","../../src/api/debug.ts","../../src/api/multipart.ts","../../src/api/refresh.ts","../../src/api/tags.ts","../../src/api/errors.ts","../../src/api/download.ts","../../src/api/endpoints.ts"],"sourcesContent":["import {\n fetchBaseQuery,\n type BaseQueryApi,\n type BaseQueryFn,\n type FetchArgs,\n type FetchBaseQueryArgs,\n type FetchBaseQueryError,\n type FetchBaseQueryMeta,\n} from '@reduxjs/toolkit/query';\nimport type { DddTokens } from '../auth/types';\nimport { applyDebugParams, readDebugFlags, type DddDebugOptions } from './debug';\nimport { buildDddFormData, type DddMultipartFiles } from './multipart';\nimport { createDddRefresh, type DddRawBaseQuery, type DddRefreshFn, type DddReloginFn } from './refresh';\n\ntype MaybePromise<T> = T | Promise<T>;\n\n/** Result of one refresh attempt: new tokens stored, session ended, session replaced while refreshing, or thrown. */\ntype RefreshOutcome = 'refreshed' | 'failed' | 'superseded' | 'error';\n\n/** What `getTokens` can see: the request's Redux context (no dispatch). */\nexport type DddRequestContext = Pick<BaseQueryApi, 'getState' | 'extra' | 'endpoint' | 'type'>;\n\n/** Context of the `headers` / `languageCode` hooks (RTK's `prepareHeaders` context). */\nexport type DddHeadersContext = Parameters<NonNullable<FetchBaseQueryArgs['prepareHeaders']>>[1];\n\n/** Decides whether a failed request is worth a token refresh and one retry. */\nexport type DddShouldRefresh = (error: FetchBaseQueryError, request: FetchArgs) => boolean;\n\n/** The base query type of a DDD api (what {@link createAuthEndpoints} and wrappers accept). */\nexport type DddBaseQuery = BaseQueryFn<string | FetchArgs, unknown, FetchBaseQueryError, {}, FetchBaseQueryMeta>;\n\n/** One upload sent by {@link DddUploadingBaseQuery.upload}. */\nexport interface DddUploadRequest {\n /** Path relative to the base URL. */\n url: string;\n /** Default `POST`. */\n method?: string;\n /** JSON envelope, sent in the form field `body`; left out when `undefined`. */\n body?: unknown;\n /** File parts per form field (the `Parameter::FILES` properties of the request DTO). */\n files: DddMultipartFiles;\n /** Query parameters; `null` / `undefined` values are skipped. */\n params?: Record<string, unknown>;\n /** Bytes of the request body sent so far. Called again from 0 when the upload is repeated after a refresh. */\n onProgress?: (loaded: number, total: number) => void;\n /** Aborting cancels the request; the result is then the error of {@link isDddUploadAborted}. */\n signal?: AbortSignal;\n /**\n * Session this upload belongs to (see {@link DddBaseQueryOptions.getSessionKey}): it is only sent, and only\n * repeated after a refresh, while that session is the current one.\n */\n expectedSessionKey?: string | number;\n}\n\n/** Result of an upload: the shape an RTK `queryFn` returns. */\nexport type DddUploadResult = { data: unknown; error?: undefined } | { data?: undefined; error: FetchBaseQueryError };\n\n/** The base query returned by {@link createDddBaseQuery}: a {@link DddBaseQuery} that can also upload with progress. */\nexport type DddUploadingBaseQuery = DddBaseQuery & {\n /**\n * Sends a multipart upload with progress (XMLHttpRequest: `fetch` reports no upload progress) through the same\n * session as every request: Bearer, `headers` / `languageCode` hooks, one shared refresh and one retry.\n *\n * @example\n * uploadAttachment: build.mutation<AttachmentResponse, { id: number; file: File; onProgress?: (loaded: number, total: number) => void }>({\n * queryFn: ({ id, file, onProgress }, api, extraOptions) =>\n * dddBaseQuery.upload({ url: `/api/client/items/${id}/attachments`, files: { attachmentFiles: [file] }, onProgress }, api, extraOptions) as\n * Promise<{ data: AttachmentResponse } | { error: FetchBaseQueryError }>,\n * }),\n */\n upload: (request: DddUploadRequest, api: BaseQueryApi, extraOptions?: unknown) => Promise<DddUploadResult>;\n};\n\n/** `error.error` of an upload cancelled through its `signal`. */\nexport const DDD_UPLOAD_ABORTED = 'DDD_UPLOAD_ABORTED';\n\n/** True for the error of an upload that was cancelled through its `signal`. */\nexport const isDddUploadAborted = (error: unknown): boolean =>\n !!error && typeof error === 'object' && (error as { status?: unknown; error?: unknown }).status === 'CUSTOM_ERROR' &&\n (error as { error?: unknown }).error === DDD_UPLOAD_ABORTED;\n\n/** `error.error` of a request that was not sent because it was bound to a session that is no longer the current one. */\nexport const DDD_SESSION_CHANGED = 'DDD_SESSION_CHANGED';\n\n/** True for the error of a request that was not sent because its session is no longer the current one. */\nexport const isDddSessionChanged = (error: unknown): boolean =>\n !!error && typeof error === 'object' && (error as { status?: unknown }).status === 'CUSTOM_ERROR' &&\n (error as { error?: unknown }).error === DDD_SESSION_CHANGED;\n\n/** Request header that carries the expected session key to the base query; it is removed before the request is sent. */\nexport const DDD_EXPECTED_SESSION_KEY_HEADER = 'x-ddd-expected-session-key';\n\n/**\n * `extraOptions` the base query reads: what binds the requests of an endpoint to a session (see\n * {@link DddBaseQueryOptions.getSessionKey}).\n */\nexport interface DddSessionBindingOptions {\n /** Binds each request to the session that is current when the request starts. */\n bindToSession?: boolean;\n /** Binds the request to this session (a `queryFn` passes it on to the base query). */\n expectedSessionKey?: string | number;\n}\n\n/** Options of {@link createDddBaseQuery}. */\nexport interface DddBaseQueryOptions {\n /** API origin, e.g. `https://api.example.com`. Request URLs are relative to it. */\n baseUrl: string;\n /** Current tokens, typically read from the Redux state (`context.getState()`) or a {@link TokenStorage}. */\n getTokens: (context: DddRequestContext) => MaybePromise<Partial<DddTokens> | null | undefined>;\n /** Stores a freshly refreshed token pair (dispatch a Redux action, write storage, …). */\n setTokens: (tokens: DddTokens, api: BaseQueryApi) => MaybePromise<void>;\n /** Called once when the session cannot be recovered (no refresh token, or the refresh was rejected). */\n onLogout: (api: BaseQueryApi) => MaybePromise<void>;\n /**\n * Identifies the current session by a value that survives a token refresh: the account id, or a counter the app\n * raises on every login and logout; `null` without a session. Never the access token: it changes with each refresh.\n *\n * With it a request can be bound to a session. A bound request is sent, and repeated after a refresh, only while\n * that session is the current one; otherwise it is answered with the error of {@link isDddSessionChanged}, without\n * a network call, a refresh or a logout. A request is bound by one of:\n * - {@link withDddExpectedSessionKey} in the endpoint's `query` (the session the caller prepared the request for),\n * - `expectedSessionKey` of an upload ({@link DddUploadRequest}),\n * - `extraOptions: { bindToSession: true }` on the endpoint: the session that is current when the request starts.\n *\n * Requests that are not bound are sent as without this option.\n *\n * @example\n * getSessionKey: ({ getState }) => (getState() as RootState).auth.accountId,\n *\n * // An endpoint whose body belongs to the account it was prepared for:\n * saveDraft: build.mutation<void, { accountId: number; draft: Draft }>({\n * query: ({ accountId, draft }) =>\n * withDddExpectedSessionKey({ url: '/api/client/drafts', method: 'POST', body: { draft } }, accountId),\n * }),\n */\n getSessionKey?: (context: DddRequestContext) => MaybePromise<string | number | null | undefined>;\n /** Custom refresh. Default: {@link createDddRefresh} on `refreshPath`. */\n refresh?: DddRefreshFn;\n /** Refresh endpoint for the default refresh, e.g. `/api/admin/common/auth/refresh`. Required without `refresh`. */\n refreshPath?: string;\n /**\n * Re-opens the session when the refresh cannot: no refresh token is stored (guest, impersonation or device\n * sessions), or the refresh token was rejected. Return the new tokens, or `null` to end the session (`onLogout`).\n * Without it a refresh-worthy failure without refresh token logs out directly.\n *\n * @example\n * // A guest session is re-opened from its stored credential:\n * relogin: async ({ baseQuery, api, extraOptions }) => {\n * const credential = readGuestCredential();\n * if (!credential) return null;\n * const result = await baseQuery({ url: '/api/public/common/auth/guest', method: 'POST', body: { credential } }, api, extraOptions as {});\n * const data = result.data as { accessToken?: string; refreshToken?: string | null } | undefined;\n * return data?.accessToken ? { accessToken: data.accessToken, refreshToken: data.refreshToken ?? null } : null;\n * },\n */\n relogin?: DddReloginFn;\n /** Creates the request object of an upload. Default `new XMLHttpRequest()`. */\n createUploadRequest?: () => XMLHttpRequest;\n /**\n * Adds or changes headers after the Bearer header is set; return value as in RTK's `prepareHeaders`.\n * `context.type` tells reads (`query`) from writes (`mutation`).\n */\n headers?: (headers: Headers, context: DddHeadersContext) => MaybePromise<Headers | void>;\n /**\n * Shortcut for the DDD `languageCode` header. Return e.g. the form's editing language for mutations and the UI\n * language for queries; a falsy value sends no header.\n */\n languageCode?: (context: DddHeadersContext) => string | null | undefined;\n /**\n * Decides whether a failed request triggers a refresh and one retry. Default {@link defaultShouldRefresh}\n * (status 401, auth endpoints excluded).\n *\n * @example\n * // Also refresh on 403, except for 403s that are business refusals:\n * shouldRefresh: (error, request) =>\n * (error.status === 401 || error.status === 403) && !isBusinessRefusal(error) && !isDddAuthRequest(request)\n */\n shouldRefresh?: DddShouldRefresh;\n /** Debug passthrough of page URL flags (`?debug`, `?noCache`, `?xdebug`, `?errorsAsJson`). Default off. */\n debug?: boolean | DddDebugOptions;\n /** Further `fetchBaseQuery` options (`fetchFn`, `timeout`, `credentials`, `paramsSerializer`, …). */\n fetchOptions?: Omit<FetchBaseQueryArgs, 'baseUrl' | 'prepareHeaders'>;\n}\n\n/** URL path of a request argument. */\nexport const getRequestUrl = (request: string | FetchArgs): string =>\n typeof request === 'string' ? request : request.url;\n\n/** True for the DDD auth endpoints (`…/common/auth/…`); they never trigger a refresh, they ARE the recovery. */\nexport const isDddAuthRequest = (request: string | FetchArgs): boolean =>\n getRequestUrl(request).includes('/common/auth/');\n\n/** Default refresh decision: HTTP 401 on anything but an auth endpoint. */\nexport const defaultShouldRefresh: DddShouldRefresh = (error, request) =>\n error.status === 401 && !isDddAuthRequest(request);\n\n/**\n * Query-string serializer that skips `null` / `undefined` values (the generated SDK passes every optional parameter).\n */\nexport const dddParamsSerializer = (params: Record<string, unknown>): string =>\n Object.entries(params)\n .filter(([, value]) => value !== null && value !== undefined)\n .map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(String(value))}`)\n .join('&');\n\nconst toFetchArgs = (args: string | FetchArgs): FetchArgs => (typeof args === 'string' ? { url: args } : args);\n\nconst toHeaders = (source: FetchArgs['headers']): Headers => {\n const headers = new Headers();\n if (source instanceof Headers) source.forEach((value, key) => headers.set(key, value));\n else if (Array.isArray(source)) source.forEach(([key, value]) => key !== undefined && headers.set(key, value ?? ''));\n else if (source) Object.entries(source).forEach(([key, value]) => value !== undefined && headers.set(key, value));\n return headers;\n};\n\nconst withBearer = (args: FetchArgs, accessToken: string | null | undefined): FetchArgs => {\n if (!accessToken) return args;\n const headers = toHeaders(args.headers);\n if (!headers.has('authorization')) headers.set('authorization', `Bearer ${accessToken}`);\n return { ...args, headers };\n};\n\n/**\n * Binds a request to a session: the base query sends it, and repeats it after a refresh, only while\n * `expectedSessionKey` is the key of the current session ({@link DddBaseQueryOptions.getSessionKey}). The key travels\n * in a request header that the base query removes before sending.\n */\nexport const withDddExpectedSessionKey = (request: string | FetchArgs, expectedSessionKey: string | number): FetchArgs => {\n const args = toFetchArgs(request);\n const headers = toHeaders(args.headers);\n headers.set(DDD_EXPECTED_SESSION_KEY_HEADER, String(expectedSessionKey));\n return { ...args, headers };\n};\n\n/** Splits the expected session key off a request; the returned request no longer carries the header. */\nconst takeExpectedSessionKey = (args: FetchArgs): { request: FetchArgs; expectedSessionKey: string | null } => {\n if (!args.headers) return { request: args, expectedSessionKey: null };\n const headers = toHeaders(args.headers);\n const expectedSessionKey = headers.get(DDD_EXPECTED_SESSION_KEY_HEADER);\n if (expectedSessionKey === null) return { request: args, expectedSessionKey: null };\n headers.delete(DDD_EXPECTED_SESSION_KEY_HEADER);\n return { request: { ...args, headers }, expectedSessionKey };\n};\n\n/**\n * Creates the RTK Query base query for a DDD backend.\n *\n * - Sends `Authorization: Bearer <accessToken>` from `getTokens()`.\n * - On a refresh-worthy failure (`shouldRefresh`, default 401) runs ONE shared refresh and retries the request exactly\n * once. Concurrent failures share that refresh and its result; a request whose failure predates a refresh that\n * finished meanwhile reuses that refresh's result instead of refreshing again.\n * - No refresh token, or a rejected refresh → `relogin()` when given; without it, or when it returns `null`,\n * `onLogout()` once for that session and the original error is returned.\n * - A refresh whose session was logged out or replaced while it ran is discarded (no `setTokens`, no retry).\n * - A request bound to a session (`getSessionKey`) is not sent once another session is the current one.\n *\n * @example\n * export const baseApi = createApi({\n * baseQuery: createDddBaseQuery({\n * baseUrl: 'https://api.example.com',\n * refreshPath: '/api/admin/common/auth/refresh',\n * getTokens: ({ getState }) => (getState() as RootState).auth,\n * setTokens: (tokens, { dispatch }) => dispatch(authActions.updateTokens(tokens)),\n * onLogout: ({ dispatch }) => dispatch(authActions.logout()),\n * }),\n * endpoints: () => ({}),\n * });\n */\nexport function createDddBaseQuery(options: DddBaseQueryOptions): DddUploadingBaseQuery {\n const { getTokens, setTokens, onLogout, getSessionKey, headers: headersHook, languageCode, fetchOptions, relogin } = options;\n const shouldRefresh = options.shouldRefresh ?? defaultShouldRefresh;\n if (!options.refresh && !options.refreshPath) {\n throw new Error('createDddBaseQuery: pass either `refresh` or `refreshPath`.');\n }\n const refresh = options.refresh ?? createDddRefresh(options.refreshPath as string);\n const debugOptions: DddDebugOptions | null =\n options.debug === true ? {} : options.debug ? options.debug : null;\n\n const fetchQuery = fetchBaseQuery({\n paramsSerializer: dddParamsSerializer,\n ...fetchOptions,\n baseUrl: options.baseUrl,\n prepareHeaders: async (headers, context) => {\n const language = languageCode?.(context);\n if (language) headers.set('languageCode', language);\n if (debugOptions && readDebugFlags(debugOptions).debug) headers.set('x-debug', 'true');\n return (await headersHook?.(headers, context)) ?? headers;\n },\n });\n\n /** One request without auth recovery: debug passthrough + fetch. */\n const rawBaseQuery: DddRawBaseQuery = (args, api, extraOptions) => {\n const finalArgs = debugOptions\n ? applyDebugParams(args, readDebugFlags(debugOptions), debugOptions.xdebugSessionKey)\n : args;\n return fetchQuery(finalArgs, api, extraOptions as {});\n };\n\n /**\n * Refresh coordination. Every finished refresh attempt starts a new session generation and records its outcome; a\n * request remembers the generation it started in. A refresh-worthy failure in the current generation runs (or\n * joins) the one refresh of that generation; a failure from an older generation reuses the recorded outcome, so a\n * late 401 after a failed refresh neither refreshes nor logs out again.\n */\n let generation = 0;\n let lastOutcome: RefreshOutcome | null = null;\n let inflight: Promise<void> | null = null;\n\n const currentAccessToken = async (api: BaseQueryApi): Promise<string | null> =>\n (await getTokens(api))?.accessToken ?? null;\n\n const currentSessionKey = async (api: BaseQueryApi): Promise<string | null> => {\n const sessionKey = await (getSessionKey as NonNullable<typeof getSessionKey>)(api);\n return sessionKey === null || sessionKey === undefined ? null : String(sessionKey);\n };\n\n /**\n * The session a request is bound to, or `undefined` for a request that is not bound. Called when the request\n * starts, before it waits for a running refresh.\n */\n const resolveBoundSessionKey = async (\n requestSessionKey: string | number | null | undefined,\n api: BaseQueryApi,\n extraOptions: unknown,\n ): Promise<string | null | undefined> => {\n const binding = (extraOptions ?? {}) as DddSessionBindingOptions;\n const expectedSessionKey = requestSessionKey ?? binding.expectedSessionKey ?? null;\n if (expectedSessionKey === null && !binding.bindToSession) return undefined;\n if (!getSessionKey) {\n throw new Error('createDddBaseQuery: a request is bound to a session, pass `getSessionKey`.');\n }\n return expectedSessionKey === null ? currentSessionKey(api) : String(expectedSessionKey);\n };\n\n /** True when the request may be sent now: it is not bound, or its session is still the current one. */\n const isBoundSessionCurrent = async (boundSessionKey: string | null | undefined, api: BaseQueryApi): Promise<boolean> =>\n boundSessionKey === undefined || (await currentSessionKey(api)) === boundSessionKey;\n\n const sessionChanged = { error: { status: 'CUSTOM_ERROR' as const, error: DDD_SESSION_CHANGED } };\n\n const runRefresh = async (api: BaseQueryApi, extraOptions: unknown): Promise<RefreshOutcome> => {\n const before = await getTokens(api);\n const refreshToken = before?.refreshToken ?? null;\n const accessTokenBefore = before?.accessToken ?? null;\n let pair = refreshToken ? await refresh({ refreshToken, baseQuery: rawBaseQuery, api, extraOptions }) : null;\n if (!pair?.accessToken && relogin) {\n pair = await relogin({\n reason: refreshToken ? 'refresh-rejected' : 'no-refresh-token',\n baseQuery: rawBaseQuery,\n api,\n extraOptions,\n });\n }\n // The session may have ended (logout) or changed (another login) while the refresh ran: its result belongs to\n // a session that is gone and must not be stored.\n const after = await getTokens(api);\n if ((after?.refreshToken ?? null) !== refreshToken) return 'superseded';\n // A session without refresh token is identified by its access token.\n if (refreshToken === null && (after?.accessToken ?? null) !== accessTokenBefore) return 'superseded';\n if (!pair?.accessToken) {\n await onLogout(api);\n return 'failed';\n }\n await setTokens({ accessToken: pair.accessToken, refreshToken: pair.refreshToken ?? refreshToken }, api);\n return 'refreshed';\n };\n\n /** Runs or joins the refresh of `startGeneration`; returns the outcome that applies to a request of that generation. */\n const recover = async (startGeneration: number, api: BaseQueryApi, extraOptions: unknown): Promise<RefreshOutcome | null> => {\n if (generation === startGeneration && !inflight) {\n inflight = (async () => {\n try {\n lastOutcome = await runRefresh(api, extraOptions);\n } catch (error) {\n lastOutcome = 'error';\n throw error;\n } finally {\n generation++;\n inflight = null;\n }\n })();\n }\n if (inflight) await inflight;\n return lastOutcome;\n };\n\n /**\n * One attempt: reads the token, then checks the bound session as the last step before sending, so a session that\n * changed while the request waited is seen.\n */\n const sendRequest = async (\n request: FetchArgs,\n boundSessionKey: string | null | undefined,\n api: BaseQueryApi,\n extraOptions: {},\n ): Promise<Awaited<ReturnType<DddRawBaseQuery>>> => {\n const authorizedRequest = withBearer(request, await currentAccessToken(api));\n if (!(await isBoundSessionCurrent(boundSessionKey, api))) return sessionChanged;\n return rawBaseQuery(authorizedRequest, api, extraOptions);\n };\n\n const baseQuery: DddBaseQuery = async (args, api, extraOptions) => {\n const { request, expectedSessionKey } = takeExpectedSessionKey(toFetchArgs(args));\n const boundSessionKey = await resolveBoundSessionKey(expectedSessionKey, api, extraOptions);\n // A request started during a refresh waits for it and then sends the current token.\n while (inflight) await inflight.catch(() => undefined);\n const startGeneration = generation;\n const result = await sendRequest(request, boundSessionKey, api, extraOptions);\n if (!result.error || isDddSessionChanged(result.error) || !shouldRefresh(result.error, request)) return result;\n if ((await recover(startGeneration, api, extraOptions)) !== 'refreshed') return result;\n return sendRequest(request, boundSessionKey, api, extraOptions);\n };\n\n /** Headers of an upload: Bearer, then the same hooks as a fetch request. No content type: the runtime sets it. */\n const uploadHeaders = async (request: DddUploadRequest, api: BaseQueryApi, extraOptions: unknown): Promise<Headers> => {\n const headers = new Headers();\n const accessToken = await currentAccessToken(api);\n if (accessToken) headers.set('authorization', `Bearer ${accessToken}`);\n const context = {\n getState: api.getState,\n extra: api.extra,\n endpoint: api.endpoint,\n type: api.type,\n forced: api.forced,\n arg: { url: request.url, method: request.method ?? 'POST' },\n extraOptions,\n } as DddHeadersContext;\n const language = languageCode?.(context);\n if (language) headers.set('languageCode', language);\n if (debugOptions && readDebugFlags(debugOptions).debug) headers.set('x-debug', 'true');\n return (await headersHook?.(headers, context)) ?? headers;\n };\n\n const sendUpload = async (\n request: DddUploadRequest,\n boundSessionKey: string | null | undefined,\n api: BaseQueryApi,\n extraOptions: unknown,\n ): Promise<DddUploadResult> => {\n const headers = await uploadHeaders(request, api, extraOptions);\n if (!(await isBoundSessionCurrent(boundSessionKey, api))) return sessionChanged;\n const query = request.params ? dddParamsSerializer(request.params) : '';\n const url = `${options.baseUrl.replace(/\\/+$/, '')}/${request.url.replace(/^\\/+/, '')}${query ? `${request.url.includes('?') ? '&' : '?'}${query}` : ''}`;\n return new Promise<DddUploadResult>((resolve) => {\n const { signal, onProgress } = request;\n const aborted: DddUploadResult = { error: { status: 'CUSTOM_ERROR', error: DDD_UPLOAD_ABORTED } };\n if (signal?.aborted) return resolve(aborted);\n const xhr = options.createUploadRequest ? options.createUploadRequest() : new XMLHttpRequest();\n const onAbort = (): void => xhr.abort();\n signal?.addEventListener('abort', onAbort, { once: true });\n const finish = (result: DddUploadResult): void => {\n signal?.removeEventListener('abort', onAbort);\n resolve(result);\n };\n xhr.open(request.method ?? 'POST', url);\n headers.forEach((value, name) => xhr.setRequestHeader(name, value));\n if (onProgress && xhr.upload) {\n xhr.upload.onprogress = (event) => {\n if (event.lengthComputable) onProgress(event.loaded, event.total);\n };\n }\n xhr.onload = () => {\n const text = xhr.responseText;\n let data: unknown;\n try {\n data = text ? JSON.parse(text) : undefined;\n } catch {\n data = text;\n }\n if (xhr.status >= 200 && xhr.status < 300) finish({ data: data ?? null });\n else finish({ error: { status: xhr.status, data } });\n };\n xhr.onerror = () => finish({ error: { status: 'FETCH_ERROR', error: 'The upload did not reach the server.' } });\n xhr.onabort = () => finish(aborted);\n xhr.send(buildDddFormData(request.body, request.files));\n });\n };\n\n const upload: DddUploadingBaseQuery['upload'] = async (request, api, extraOptions) => {\n const boundSessionKey = await resolveBoundSessionKey(request.expectedSessionKey, api, extraOptions);\n while (inflight) await inflight.catch(() => undefined);\n const startGeneration = generation;\n const result = await sendUpload(request, boundSessionKey, api, extraOptions);\n if (!result.error || isDddSessionChanged(result.error)) return result;\n if (!shouldRefresh(result.error, { url: request.url, method: request.method ?? 'POST' })) return result;\n if ((await recover(startGeneration, api, extraOptions)) !== 'refreshed') return result;\n return sendUpload(request, boundSessionKey, api, extraOptions);\n };\n\n return Object.assign(baseQuery, { upload });\n}\n","import type { FetchArgs } from '@reduxjs/toolkit/query';\n\n/**\n * Debug passthrough: flags present in the page URL (`?debug`, `?noCache`, `?xdebug`, `?errorsAsJson`) are forwarded to\n * every API request as the query parameters a DDD backend understands.\n */\nexport interface DddDebugOptions {\n /** Where the flags come from. Default: `window.location.search` (nothing outside a browser). */\n searchParams?: () => URLSearchParams | null | undefined;\n /** Value of `XDEBUG_SESSION` when `?xdebug` is set. Default `1`. */\n xdebugSessionKey?: string;\n}\n\n/** The debug flags active for one request. */\nexport interface DddDebugFlags {\n debug: boolean;\n noCache: boolean;\n xdebug: boolean;\n errorsAsJson: boolean;\n}\n\nconst defaultSearchParams = (): URLSearchParams | null =>\n typeof window !== 'undefined' && window.location ? new URLSearchParams(window.location.search) : null;\n\n/** Reads the active debug flags. */\nexport function readDebugFlags(options: DddDebugOptions = {}): DddDebugFlags {\n const params = (options.searchParams ?? defaultSearchParams)() ?? null;\n return {\n debug: params?.has('debug') ?? false,\n noCache: params?.has('noCache') ?? false,\n xdebug: params?.has('xdebug') ?? false,\n errorsAsJson: params?.has('errorsAsJson') ?? false,\n };\n}\n\nconst appendToUrl = (url: string, key: string, value: string): string =>\n new RegExp(`[?&]${key}=`, 'i').test(url)\n ? url\n : `${url}${url.includes('?') ? '&' : '?'}${encodeURIComponent(key)}=${encodeURIComponent(value)}`;\n\n/**\n * Adds the query parameters for the active debug flags to a request, never overwriting a parameter the caller set.\n */\nexport function applyDebugParams(\n args: string | FetchArgs,\n flags: DddDebugFlags,\n xdebugSessionKey = '1',\n): string | FetchArgs {\n const extra: Array<[string, string]> = [];\n if (flags.debug) extra.push(['debug', 'true']);\n if (flags.noCache) extra.push(['noCache', 'true']);\n if (flags.xdebug) extra.push(['XDEBUG_SESSION', xdebugSessionKey]);\n if (flags.errorsAsJson) extra.push(['errors_as_json', '1']);\n if (extra.length === 0) return args;\n\n if (typeof args === 'string') {\n return extra.reduce((url, [key, value]) => appendToUrl(url, key, value), args);\n }\n const params: Record<string, unknown> = { ...(args.params ?? {}) };\n for (const [key, value] of extra) {\n if (params[key] === undefined && !new RegExp(`[?&]${key}=`, 'i').test(args.url)) params[key] = value;\n }\n return { ...args, params };\n}\n","/**\n * One file part: a `File` / `Blob` in a browser, or React Native's `{ uri, name, type }` file reference.\n */\nexport type DddFilePart = Blob | { uri: string; name: string; type: string };\n\n/** File parts per form field of a DDD request DTO (its `Parameter::FILES` properties). */\nexport type DddMultipartFiles<Field extends string = string> = Partial<\n Record<Field, readonly DddFilePart[] | DddFilePart | null | undefined>\n>;\n\n/** Form field a DDD backend reads the JSON envelope of a multipart request from. */\nexport const DDD_MULTIPART_BODY_FIELD = 'body';\n\nconst partsOf = (value: readonly DddFilePart[] | DddFilePart | null | undefined): readonly DddFilePart[] => {\n if (value === null || value === undefined) return [];\n return Array.isArray(value) ? (value as readonly DddFilePart[]) : [value as DddFilePart];\n};\n\n/** True when at least one file part is present. */\nexport function hasDddMultipartFiles(files: DddMultipartFiles | null | undefined): boolean {\n return !!files && Object.values(files).some((value) => partsOf(value).length > 0);\n}\n\n/**\n * The `multipart/form-data` body of a DDD request: the JSON envelope in the form field `body` (left out when\n * `body` is `undefined`) and every file as a part named `<field>[]`. No `Content-Type` header must be set for it: the\n * runtime adds the multipart boundary itself.\n */\nexport function buildDddFormData(body: unknown, files: DddMultipartFiles | null | undefined): FormData {\n const formData = new FormData();\n if (body !== undefined) formData.append(DDD_MULTIPART_BODY_FIELD, JSON.stringify(body));\n for (const [field, value] of Object.entries(files ?? {})) {\n for (const part of partsOf(value)) {\n const name = typeof (part as { name?: unknown }).name === 'string' ? (part as { name: string }).name : '';\n // A React Native file reference is appended as it is; a Blob without a name gets the field name.\n if (typeof Blob !== 'undefined' && part instanceof Blob) formData.append(`${field}[]`, part, name || field);\n else formData.append(`${field}[]`, part as unknown as Blob);\n }\n }\n return formData;\n}\n\n/**\n * Request body of an endpoint that accepts JSON and file parts: `body` itself while no file is given (a plain JSON\n * request), else the multipart form of {@link buildDddFormData}. Generated endpoints of operations with a\n * `multipart/form-data` request body call it with their `multipartFiles` argument.\n */\nexport function buildDddMultipartBody<Body>(body: Body, files: DddMultipartFiles | null | undefined): Body | FormData {\n return hasDddMultipartFiles(files) ? buildDddFormData(body, files) : body;\n}\n","import type { BaseQueryApi, BaseQueryFn, FetchArgs, FetchBaseQueryError, FetchBaseQueryMeta } from '@reduxjs/toolkit/query';\nimport type { DddAuthResponse, DddTokens } from '../auth/types';\n\n/** The raw (non-refreshing) base query handed to a refresh function. */\nexport type DddRawBaseQuery = BaseQueryFn<string | FetchArgs, unknown, FetchBaseQueryError, {}, FetchBaseQueryMeta>;\n\n/** Everything a refresh function needs. */\nexport interface DddRefreshContext {\n /** The refresh token currently stored. */\n refreshToken: string;\n /** The underlying fetch base query (no auth retry, Bearer of the current access token still applied). */\n baseQuery: DddRawBaseQuery;\n api: BaseQueryApi;\n extraOptions: unknown;\n}\n\n/**\n * Exchanges a refresh token for a new token pair.\n *\n * @returns the new pair, or `null` when the refresh token was rejected (the base query then logs out).\n * A missing `refreshToken` in the result keeps the stored one.\n */\nexport type DddRefreshFn = (context: DddRefreshContext) => Promise<DddTokens | null>;\n\n/** Everything a re-login function needs. */\nexport interface DddReloginContext {\n /** Why the refresh could not recover the session. */\n reason: 'no-refresh-token' | 'refresh-rejected';\n /** The underlying fetch base query (no auth retry, Bearer of the current access token still applied). */\n baseQuery: DddRawBaseQuery;\n api: BaseQueryApi;\n extraOptions: unknown;\n}\n\n/**\n * Re-opens a session without a usable refresh token (guest credential, device id, impersonation through another\n * session, …).\n *\n * @returns the new tokens (`refreshToken: null` for a session that has none), or `null` to end the session.\n */\nexport type DddReloginFn = (context: DddReloginContext) => Promise<DddTokens | null>;\n\n/**\n * The default {@link DddRefreshFn}: `POST <path>` with `{ refreshToken }`, expecting the DDD `AuthPostResponseDto`\n * `{ accessToken, refreshToken }`. DDD refresh tokens are stateless and re-issued with a renewed lifetime.\n *\n * @param path refresh endpoint relative to the base URL, e.g. `/api/admin/common/auth/refresh`\n */\nexport function createDddRefresh(path: string): DddRefreshFn {\n return async ({ refreshToken, baseQuery, api, extraOptions }) => {\n const result = await baseQuery({ url: path, method: 'POST', body: { refreshToken } }, api, extraOptions as {});\n const payload = result.data as DddAuthResponse | undefined;\n if (result.error || !payload?.accessToken) return null;\n return { accessToken: payload.accessToken, refreshToken: payload.refreshToken ?? refreshToken };\n };\n}\n","/** The tags of `Extra` that differ from a tag of `Generated` only by case. */\ntype DddTagCaseConflict<Extra extends string, Generated extends string> = Extra extends Generated\n ? never\n : Lowercase<Extra> extends Lowercase<Generated>\n ? Extra\n : never;\n\ntype DddTagCheck<Generated extends readonly string[], Extra extends readonly string[]> = [\n DddTagCaseConflict<Extra[number], Generated[number]>,\n] extends [never]\n ? unknown\n : { 'tag differs from a generated tag only by case': DddTagCaseConflict<Extra[number], Generated[number]> };\n\n/**\n * The `tagTypes` of a base api: the generated tag lists (`<stem>TagTypes` of the `<stem>Tags.ts` files) plus the\n * app's own tags. With this list every `providesTags` / `invalidatesTags` of a hand-written endpoint and every\n * `api.util.invalidateTags()` is checked against the generated names, so a mistyped tag does not compile. An own tag\n * that differs from a generated one only by case (`ProspectActivities` next to the generated `Prospectactivities`)\n * is rejected here: it would be a second tag that no generated endpoint provides.\n *\n * @example\n * export const baseApi = createApi({\n * baseQuery,\n * tagTypes: mergeDddTagTypes([...adminApiTagTypes, ...clientApiTagTypes], ['Session']),\n * endpoints: () => ({}),\n * });\n */\nexport function mergeDddTagTypes<const Generated extends readonly string[], const Extra extends readonly string[] = readonly []>(\n generated: Generated,\n extra?: Extra & DddTagCheck<Generated, Extra>,\n): (Generated[number] | Extra[number])[] {\n return [...new Set<string>([...generated, ...(extra ?? [])])] as (Generated[number] | Extra[number])[];\n}\n","import type { DddErrorBody, DddExceptionDetail } from '../contract/errors';\n\n/** A DDD API error in one predictable shape, whatever produced it (RTK Query, a thrown Error, a raw body). */\nexport interface DddNormalizedError {\n /**\n * HTTP status, or RTK Query's string status for non-HTTP failures (`FETCH_ERROR`, `TIMEOUT_ERROR`,\n * `CUSTOM_ERROR`); a `PARSING_ERROR` reports the original HTTP status. `null` when unknown.\n */\n status: number | string | null;\n /** Human-readable message: the backend's `error` key first, then a text body, then generic fallbacks. */\n message: string;\n /** The backend's `validationErrors` exactly as received (present on validation 400s), else `null`. */\n validationErrors: unknown;\n /** `exceptionDetails.elements` of the backend body; empty when absent. */\n details: DddExceptionDetail[];\n /** The raw response body (parsed JSON, text, or `undefined`). */\n body: unknown;\n}\n\n/** Message used when an error carries no message at all. */\nexport const DEFAULT_ERROR_MESSAGE = 'Request failed';\n\n/**\n * Messages for failures that carry no usable backend message. Pass your own (e.g. translated) texts as the third\n * argument of {@link normalizeDddError} / {@link getErrorMessage}.\n */\nexport interface DddErrorMessages {\n /** A response that is not JSON (an HTML error page, a PHP fatal) with an HTTP status ≥ 500. */\n serverError: (status: number) => string;\n /** A response that is not JSON with an HTTP status < 500. */\n httpError: (status: number) => string;\n /** The request never reached the server or got no response (`FETCH_ERROR`). */\n networkError: string;\n /** The request timed out (`TIMEOUT_ERROR`). */\n timeoutError: string;\n}\n\n/** The default {@link DddErrorMessages}. */\nexport const DEFAULT_ERROR_MESSAGES: DddErrorMessages = {\n serverError: (status) => `Server error (HTTP ${status})`,\n httpError: (status) => `Request failed (HTTP ${status})`,\n networkError: 'The server could not be reached',\n timeoutError: 'The request timed out',\n};\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n value !== null && typeof value === 'object' && !Array.isArray(value);\n\nconst nonEmptyString = (value: unknown): string | null =>\n typeof value === 'string' && value.trim() !== '' ? value : null;\n\n/** Unwraps the places a response body can sit: RTK `data`, an Error's `responseBody`, or the value itself. */\nconst extractBody = (error: Record<string, unknown>): unknown => {\n if ('data' in error) return error.data;\n if ('responseBody' in error) return error.responseBody;\n if ('error' in error || 'validationErrors' in error || 'exceptionDetails' in error) return error;\n return undefined;\n};\n\nconst extractStatus = (error: Record<string, unknown>): number | string | null => {\n if (error.status === 'PARSING_ERROR' && typeof error.originalStatus === 'number') return error.originalStatus;\n if (typeof error.status === 'number' || typeof error.status === 'string') return error.status;\n if (typeof error.statusCode === 'number') return error.statusCode;\n return null;\n};\n\n/**\n * The message of an RTK Query failure that is not a DDD response: an unparsable body (`PARSING_ERROR`), no response\n * (`FETCH_ERROR`), a timeout (`TIMEOUT_ERROR`); `null` for everything else.\n */\nconst transportFailureMessage = (\n error: Record<string, unknown>,\n texts: DddErrorMessages,\n fallbackMessage: string,\n): string | null => {\n switch (error.status) {\n case 'PARSING_ERROR': {\n const status = typeof error.originalStatus === 'number' ? error.originalStatus : null;\n if (status === null) return fallbackMessage;\n return status >= 500 ? texts.serverError(status) : texts.httpError(status);\n }\n case 'FETCH_ERROR':\n return texts.networkError;\n case 'TIMEOUT_ERROR':\n return texts.timeoutError;\n default:\n return null;\n }\n};\n\n/**\n * Normalises any API error into {@link DddNormalizedError}.\n *\n * Understands RTK Query's `FetchBaseQueryError` (`{ status, data }`, `{ status: 'FETCH_ERROR', error }`, …),\n * `SerializedError` / `Error` (`message`), errors carrying a parsed `responseBody`, and a bare DDD error body.\n * DDD error bodies put the message under `error` (not `message`).\n *\n * A response the client could not parse (`PARSING_ERROR`: an HTML error page, a PHP fatal, a proxy's 502) is an HTTP\n * error: `status` is the HTTP status and the message is {@link DddErrorMessages.serverError} /\n * {@link DddErrorMessages.httpError} — never the parser's `SyntaxError` text and never the raw body, which may show\n * internals (the body stays available in `body`). `FETCH_ERROR` and `TIMEOUT_ERROR` get\n * {@link DddErrorMessages.networkError} / {@link DddErrorMessages.timeoutError} instead of the browser's text.\n *\n * @param error whatever a request rejected with\n * @param fallbackMessage message when nothing usable is found\n * @param messages texts for failures without a backend message (default {@link DEFAULT_ERROR_MESSAGES})\n */\nexport function normalizeDddError(\n error: unknown,\n fallbackMessage: string = DEFAULT_ERROR_MESSAGE,\n messages: Partial<DddErrorMessages> = {},\n): DddNormalizedError {\n const texts: DddErrorMessages = { ...DEFAULT_ERROR_MESSAGES, ...messages };\n if (!isRecord(error)) {\n return {\n status: null,\n message: nonEmptyString(error) ?? fallbackMessage,\n validationErrors: null,\n details: [],\n body: undefined,\n };\n }\n\n const body = extractBody(error);\n const failure = transportFailureMessage(error, texts, fallbackMessage);\n if (failure !== null) {\n return { status: extractStatus(error), message: failure, validationErrors: null, details: [], body };\n }\n const dddBody: DddErrorBody | null = isRecord(body) ? (body as DddErrorBody) : null;\n const bodyRecord: Record<string, unknown> | null = isRecord(body) ? body : null;\n\n const message =\n nonEmptyString(dddBody?.error) ??\n nonEmptyString(bodyRecord?.message) ??\n // RTK's non-HTTP errors carry the reason in `error` (e.g. \"TypeError: Failed to fetch\").\n (body === undefined || typeof body === 'string' ? nonEmptyString(error.error) : null) ??\n // A non-JSON error body (e.g. a download endpoint answering with plain text) is the message itself.\n nonEmptyString(body)?.trim() ??\n nonEmptyString(error.message) ??\n fallbackMessage;\n\n return {\n status: extractStatus(error),\n message,\n validationErrors: dddBody?.validationErrors ?? null,\n details: dddBody?.exceptionDetails?.elements ?? [],\n body,\n };\n}\n\n/**\n * The message to show for an API error (`normalizeDddError(error).message`).\n *\n * @param error whatever a request rejected with\n * @param fallbackMessage message when nothing usable is found\n * @param messages texts for failures without a backend message\n */\nexport function getErrorMessage(\n error: unknown,\n fallbackMessage: string = DEFAULT_ERROR_MESSAGE,\n messages: Partial<DddErrorMessages> = {},\n): string {\n return normalizeDddError(error, fallbackMessage, messages).message;\n}\n\n/** HTTP status of an API error (also of an unparsable response), or `null` for non-HTTP failures. */\nexport function getErrorStatus(error: unknown): number | null {\n const status = normalizeDddError(error).status;\n return typeof status === 'number' ? status : null;\n}\n","/** A binary response decoded by {@link blobResponseHandler}. */\nexport interface DddFileResponse {\n blob: Blob;\n /** File name from `Content-Disposition`, else `null`. */\n filename: string | null;\n /** `Content-Type` of the response, else `null`. */\n contentType: string | null;\n}\n\n/** Serializable summary returned by {@link createDownloadResponseHandler} (safe to keep in the Redux store). */\nexport interface DddDownloadedFile {\n filename: string;\n contentType: string | null;\n size: number;\n}\n\n/**\n * Reads the file name from a `Content-Disposition` header. Prefers RFC 5987 `filename*=UTF-8''…` over `filename=`.\n *\n * @returns the decoded file name, or `null` when the header has none.\n */\nexport function filenameFromContentDisposition(header: string | null | undefined): string | null {\n if (!header) return null;\n const extended = /filename\\*\\s*=\\s*([^']*)'[^']*'([^;]+)/i.exec(header);\n if (extended?.[2]) {\n try {\n return decodeURIComponent(extended[2].trim().replace(/^\"|\"$/g, ''));\n } catch {\n // Malformed percent-encoding: fall back to the plain parameter.\n }\n }\n const plain = /filename\\s*=\\s*(\"([^\"]*)\"|[^;]*)/i.exec(header);\n const value = (plain?.[2] ?? plain?.[1] ?? '').trim();\n if (!value) return null;\n try {\n return decodeURIComponent(value);\n } catch {\n return value;\n }\n}\n\n/**\n * Triggers a browser download for an in-memory blob. No-op outside a browser.\n *\n * The anchor is attached before clicking (some browsers ignore detached anchors) and the object URL is revoked on the\n * next macrotask (revoking in the same task can cancel the download).\n */\nexport function downloadBlob(blob: Blob, filename: string): void {\n if (typeof document === 'undefined' || typeof URL.createObjectURL !== 'function') return;\n const url = URL.createObjectURL(blob);\n const anchor = document.createElement('a');\n anchor.href = url;\n anchor.download = filename;\n anchor.rel = 'noopener';\n document.body.appendChild(anchor);\n anchor.click();\n anchor.remove();\n setTimeout(() => URL.revokeObjectURL(url), 0);\n}\n\n/** Parses an error response as JSON when possible, else as text, so error normalisation keeps working. */\nconst parseErrorBody = async (response: Response): Promise<unknown> => {\n const text = await response.text();\n if (!text) return undefined;\n try {\n return JSON.parse(text);\n } catch {\n return text;\n }\n};\n\n/**\n * RTK Query `responseHandler` for binary endpoints: a successful response becomes a {@link DddFileResponse}, an error\n * response is parsed as JSON/text like any other error.\n *\n * Blobs are not serializable; keep such endpoints out of the cache (e.g. use a mutation or `keepUnusedDataFor: 0`) or\n * use {@link createDownloadResponseHandler}.\n *\n * @example\n * build.query<DddFileResponse, void>({ query: () => ({ url: '/export', responseHandler: blobResponseHandler }) })\n */\nexport async function blobResponseHandler(response: Response): Promise<DddFileResponse | unknown> {\n if (!response.ok) return parseErrorBody(response);\n return {\n blob: await response.blob(),\n filename: filenameFromContentDisposition(response.headers.get('content-disposition')),\n contentType: response.headers.get('content-type'),\n } satisfies DddFileResponse;\n}\n\n/**\n * Builds an RTK Query `responseHandler` that downloads a successful binary response right away and resolves to a\n * serializable {@link DddDownloadedFile}. Error responses are parsed as JSON/text.\n *\n * @param fallbackFilename used when the response has no `Content-Disposition` file name\n */\nexport function createDownloadResponseHandler(fallbackFilename = 'download') {\n return async (response: Response): Promise<DddDownloadedFile | unknown> => {\n if (!response.ok) return parseErrorBody(response);\n const blob = await response.blob();\n const filename = filenameFromContentDisposition(response.headers.get('content-disposition')) ?? fallbackFilename;\n downloadBlob(blob, filename);\n return { filename, contentType: response.headers.get('content-type'), size: blob.size } satisfies DddDownloadedFile;\n };\n}\n","import type { Api, ApiModules, EndpointDefinitions } from '@reduxjs/toolkit/query';\nimport type { DddBaseQuery } from './baseQuery';\nimport type { DddAuthResponse, DddLoginRequest, DddRefreshRequest } from '../auth/types';\n\n/** Options of {@link createAuthEndpoints}. */\nexport interface DddAuthEndpointsOptions {\n /** e.g. `/api/admin/common/auth/login` */\n loginPath: string;\n /** e.g. `/api/admin/common/auth/refresh` */\n refreshPath: string;\n}\n\n/**\n * Injects `authLogin` and `authRefresh` mutations for the DDD auth endpoints into an existing API.\n * Pure `injectEndpoints`, no React; with an API created by `@reduxjs/toolkit/query/react` the usual hooks\n * (`useAuthLoginMutation`, …) are generated as for any endpoint.\n *\n * The API must use the base query from {@link createDddBaseQuery}.\n *\n * Prefer the endpoints of your generated SDK when it already has them; this is for apps without one.\n */\nexport function createAuthEndpoints<\n Definitions extends EndpointDefinitions,\n ReducerPath extends string,\n TagTypes extends string,\n Enhancers extends keyof ApiModules<any, any, any, any>,\n>(api: Api<DddBaseQuery, Definitions, ReducerPath, TagTypes, Enhancers>, options: DddAuthEndpointsOptions) {\n return api.injectEndpoints({\n endpoints: (build) => ({\n authLogin: build.mutation<DddAuthResponse, DddLoginRequest>({\n query: (body) => ({ url: options.loginPath, method: 'POST', body }),\n }),\n authRefresh: build.mutation<DddAuthResponse, DddRefreshRequest>({\n query: (body) => ({ url: options.refreshPath, method: 'POST', body }),\n }),\n }),\n });\n}\n"],"mappings":";AAAA;AAAA,EACE;AAAA,OAOK;;;ACaP,IAAM,sBAAsB,MAC1B,OAAO,WAAW,eAAe,OAAO,WAAW,IAAI,gBAAgB,OAAO,SAAS,MAAM,IAAI;AAG5F,SAAS,eAAe,UAA2B,CAAC,GAAkB;AAC3E,QAAM,UAAU,QAAQ,gBAAgB,qBAAqB,KAAK;AAClE,SAAO;AAAA,IACL,OAAO,QAAQ,IAAI,OAAO,KAAK;AAAA,IAC/B,SAAS,QAAQ,IAAI,SAAS,KAAK;AAAA,IACnC,QAAQ,QAAQ,IAAI,QAAQ,KAAK;AAAA,IACjC,cAAc,QAAQ,IAAI,cAAc,KAAK;AAAA,EAC/C;AACF;AAEA,IAAM,cAAc,CAAC,KAAa,KAAa,UAC7C,IAAI,OAAO,OAAO,GAAG,KAAK,GAAG,EAAE,KAAK,GAAG,IACnC,MACA,GAAG,GAAG,GAAG,IAAI,SAAS,GAAG,IAAI,MAAM,GAAG,GAAG,mBAAmB,GAAG,CAAC,IAAI,mBAAmB,KAAK,CAAC;AAK5F,SAAS,iBACd,MACA,OACA,mBAAmB,KACC;AACpB,QAAM,QAAiC,CAAC;AACxC,MAAI,MAAM,MAAO,OAAM,KAAK,CAAC,SAAS,MAAM,CAAC;AAC7C,MAAI,MAAM,QAAS,OAAM,KAAK,CAAC,WAAW,MAAM,CAAC;AACjD,MAAI,MAAM,OAAQ,OAAM,KAAK,CAAC,kBAAkB,gBAA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CAAC,SAAS,GAAI,QAAO,eAAe,QAAQ;AAChD,SAAO;AAAA,IACL,MAAM,MAAM,SAAS,KAAK;AAAA,IAC1B,UAAU,+BAA+B,SAAS,QAAQ,IAAI,qBAAqB,CAAC;AAAA,IACpF,aAAa,SAAS,QAAQ,IAAI,cAAc;AAAA,EAClD;AACF;AAQO,SAAS,8BAA8B,mBAAmB,YAAY;AAC3E,SAAO,OAAO,aAA6D;AACzE,QAAI,CAAC,SAAS,GAAI,QAAO,eAAe,QAAQ;AAChD,UAAM,OAAO,MAAM,SAAS,KAAK;AACjC,UAAM,WAAW,+BAA+B,SAAS,QAAQ,IAAI,qBAAqB,CAAC,KAAK;AAChG,iBAAa,MAAM,QAAQ;AAC3B,WAAO,EAAE,UAAU,aAAa,SAAS,QAAQ,IAAI,cAAc,GAAG,MAAM,KAAK,KAAK;AAAA,EACxF;AACF;;;ACnFO,SAAS,oBAKd,KAAuE,SAAkC;AACzG,SAAO,IAAI,gBAAgB;AAAA,IACzB,WAAW,CAAC,WAAW;AAAA,MACrB,WAAW,MAAM,SAA2C;AAAA,QAC1D,OAAO,CAAC,UAAU,EAAE,KAAK,QAAQ,WAAW,QAAQ,QAAQ,KAAK;AAAA,MACnE,CAAC;AAAA,MACD,aAAa,MAAM,SAA6C;AAAA,QAC9D,OAAO,CAAC,UAAU,EAAE,KAAK,QAAQ,aAAa,QAAQ,QAAQ,KAAK;AAAA,MACrE,CAAC;AAAA,IACH;AAAA,EACF,CAAC;AACH;","names":[]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@mgamadeus/ddd-web",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.5.0",
|
|
4
4
|
"description": "TypeScript web client for backends built with mgamadeus/ddd, the DDD entity framework for Symfony and Doctrine (Composer/Packagist). Generates a typed RTK Query SDK from the backend's OpenAPI document, builds DDD QueryOptions (filters, orderBy, expand, select, paging) and handles JWT auth with token refresh.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"ddd",
|