@mgamadeus/ddd-web 0.6.1 → 0.7.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.
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: ddd-web-specialist
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."
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, mergeDddTagTypes, blobResponseHandler downloads, multipartFiles uploads, upload progress via baseQuery.upload), QueryOptions builders (buildQueryOptions, combineFilters, buildInFilter), createDddBaseQuery (Bearer, shared refresh + retry, relogin without refresh token, session-bound requests (getSessionKey), shouldRefresh, normalizeDddError), token storage, JWT helpers, foreign global Request (MooTools: dddFetchApiRequestPlugin), 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 a switch, stale cache tags, downloading an export, requests failing in a legacy page, or releasing ddd-web."
4
4
  metadata:
5
5
  author: mgamadeus
6
6
  version: "1.4.2"
@@ -10,6 +10,7 @@
10
10
  6. Tokens (`/auth`)
11
11
  7. Contract helpers (`/contract`)
12
12
  8. Agent skills (`link-skills`)
13
+ 5a. Pages with a foreign global `Request` (`/fetch-api-request`, `/vite`)
13
14
  9. Troubleshooting
14
15
 
15
16
  ## 1. Configuration (`openapi-config.ts`)
@@ -364,6 +365,37 @@ contentType }` instead; `downloadBlob`, `filenameFromContentDisposition` (RFC 59
364
365
  handlers. Apps without a generated auth endpoint: `createAuthEndpoints(api, { loginPath, refreshPath })` injects
365
366
  `authLogin` / `authRefresh`.
366
367
 
368
+ ## 5a. Pages with a foreign global `Request` (`/fetch-api-request`, `/vite`)
369
+
370
+ RTK Query's `fetchBaseQuery` builds every request with the GLOBAL `Request`. Pages that load MooTools 1.x or Prototype
371
+ replace `window.Request` with their Ajax class, and RTK offers no option that names another constructor. In such a page
372
+ the base query refuses each request with a `FETCH_ERROR` whose `error` names the cause
373
+ (`DDD_FOREIGN_GLOBAL_REQUEST_MESSAGE`, from the `fetchFn` guard `guardFetchApiRequest`). Without the guard the request
374
+ would go to `<page>/[object Object]` and fail as `PARSING_ERROR`.
375
+
376
+ The fix is a build step that hands the toolkit's query module the Fetch API's constructor:
377
+
378
+ ```ts
379
+ // vite.config.ts
380
+ import { dddFetchApiRequestPlugin } from '@mgamadeus/ddd-web/vite';
381
+ export default defineConfig({ plugins: [react(), dddFetchApiRequestPlugin()] });
382
+ ```
383
+
384
+ - The plugin prepends `import { FetchApiRequest as Request } from '@mgamadeus/ddd-web/fetch-api-request'` to the
385
+ toolkit's query module. The page's own scripts keep their `Request`.
386
+ - The build fails when the toolkit's query module is in the build but not bound, so a toolkit update cannot silently
387
+ bring the defect back.
388
+ - The plugin covers builds only, watch builds included. The dev server pre-bundles the toolkit untransformed, so for
389
+ such a page use a built bundle.
390
+ - `FetchApiRequest` / `resolveFetchApiRequest()` use the page's constructor when it is genuine. Otherwise they use the
391
+ constructor of a hidden frame without an address that the module adds. The frame stays in the document and is
392
+ re-added if a script removed it.
393
+ - Relative addresses are resolved against the page (`document.baseURI`). The request is still sent by the page's
394
+ `fetch`, with the page's cookies.
395
+ - Other bundlers: alias `Request` in that one module the same way.
396
+ - `isFetchApiRequest` / `isFetchApiRequestConstructor` check the `[object Request]` tag, not `instanceof`: a request from
397
+ the frame is no instance of the page's `Request`.
398
+
367
399
  ## 6. Tokens (`/auth`)
368
400
 
369
401
  - `TokenStorage` = `read()` / `write({ accessToken?, refreshToken? })` (`undefined` keeps, `null` removes) /
@@ -412,6 +444,10 @@ Idempotent; an existing symlink is repointed, a real file or directory is never
412
444
  | `No tag for <endpoint> — no cache tags generated` | Operation without a matching tag: add a tag on the backend controller or an `endpointOverrides` |
413
445
  | `--schema needs exactly one api` | Combine with `--api <exportName>` |
414
446
  | `All apis must share one output directory when modelsDir is not set` | Set `modelsDir` |
447
+ | `Cannot find module 'ajv/dist/core'` (or another ajv 8 module) while the generator loads | A consumer with `legacy-peer-deps` and an `ajv` 6 at the top of `node_modules`: since 0.6.2 the generator answers the parser's `ajv` from its own `ajv` 8 — update the package |
448
+ | The type check is slow or reports errors your compiler does not | It ran another compiler: since 0.6.2 it takes the project's `typescript` through its package.json `bin` (TypeScript 7 included) and logs `Type check with TypeScript <version> (the project's compiler)` |
449
+ | A polling read aborts with no visible reason (`subscribe: false`, `keepUnusedDataFor: 0`) | The removal timer of the previous answer removes the cache entry and aborts the next identical read. Subscribe while the read runs and unsubscribe after the answer: `const read = dispatch(api.endpoints.x.initiate(arg, { forceRefetch: true })); try { return await read.unwrap(); } finally { read.unsubscribe(); }` |
450
+ | Every request fails with `FETCH_ERROR` "RTK Query built it with the global \`Request\`…" (before 0.7.0: `PARSING_ERROR`, HTML from `<page>/[object Object]`) | The page replaced the global `Request` (MooTools, Prototype): add `dddFetchApiRequestPlugin()` — section 5a |
415
451
  | `type check failed — previous output restored` | Fix the reported type error (often app code using a renamed hook), or `--skip-tsc` to inspect |
416
452
  | A list does not refresh after a write | `<stem>Enhanced.ts` not imported; or the write has no tag — see section 3 |
417
453
  | 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 |
package/CHANGELOG.md CHANGED
@@ -1,5 +1,31 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.7.0
4
+
5
+ ### Added
6
+ - `@mgamadeus/ddd-web/fetch-api-request`: `FetchApiRequest`, `resolveFetchApiRequest()`, `isFetchApiRequest`,
7
+ `isFetchApiRequestConstructor`. They provide the Fetch API's `Request` constructor in pages whose global `Request` was
8
+ replaced (MooTools 1.x, Prototype), taking it from a hidden frame when the page's constructor is not genuine.
9
+ - `@mgamadeus/ddd-web/vite`: `dddFetchApiRequestPlugin()` binds the `Request` of RTK Query's `fetchBaseQuery` to
10
+ `FetchApiRequest` in builds, and fails the build when the toolkit's query module stays unbound.
11
+
12
+ ### Fixed
13
+ - `createDddBaseQuery`: in such a page a request is refused with a `FETCH_ERROR` that names the cause
14
+ (`DDD_FOREIGN_GLOBAL_REQUEST_MESSAGE`). Before, it was sent to `<page>/[object Object]` and failed as `PARSING_ERROR`.
15
+ Your own `fetchOptions.fetchFn` is wrapped by the same check (`guardFetchApiRequest`).
16
+
17
+ ## 0.6.2
18
+
19
+ ### Fixed
20
+ - The generator loads in a consumer that installs with `legacy-peer-deps` and has `ajv` 6 at the top of
21
+ `node_modules`: the `ajv` lookups of `ajv-draft-04` (the OpenAPI parser's) are answered from the parser's own `ajv`
22
+ 8, and the codegen is loaded after that hook.
23
+ - The closing type check runs the PROJECT's compiler, found through `typescript/package.json` `bin` (TypeScript 7
24
+ exports no `typescript/bin/tsc`; the check fell back silently to the codegen's older TypeScript), and logs which one
25
+ ran. The generator's own compiler only when the project has no `typescript`.
26
+ - Troubleshooting: a polling read with `subscribe: false` and `keepUnusedDataFor: 0` is aborted by the removal timer of
27
+ the previous answer — subscribe while the read runs, unsubscribe after the answer.
28
+
3
29
  ## 0.6.1
4
30
 
5
31
  ### Fixed
package/README.md CHANGED
@@ -48,7 +48,8 @@ pnpm exec ddd-web-sdk # generate the SDK
48
48
  pnpm exec ddd-web link-skills # link the package's agent skills into .claude/skills
49
49
  ```
50
50
 
51
- Subpaths: `@mgamadeus/ddd-web/codegen`, `/query`, `/api`, `/auth`, `/contract`.
51
+ Subpaths: `@mgamadeus/ddd-web/codegen`, `/query`, `/api`, `/auth`, `/contract`, `/fetch-api-request` and `/vite`
52
+ (pages whose global `Request` is not the Fetch API's, e.g. MooTools or Prototype: `dddFetchApiRequestPlugin()`).
52
53
 
53
54
  ### File downloads
54
55
 
@@ -261,6 +261,13 @@ declare const defaultShouldRefresh: DddShouldRefresh;
261
261
  * Query-string serializer that skips `null` / `undefined` values (the generated SDK passes every optional parameter).
262
262
  */
263
263
  declare const dddParamsSerializer: (params: Record<string, unknown>) => string;
264
+ /** Error text of a request RTK built with a global `Request` that is not the Fetch API's. */
265
+ declare const DDD_FOREIGN_GLOBAL_REQUEST_MESSAGE: string;
266
+ /**
267
+ * Wraps a `fetchFn`: an object that is neither a Fetch API request nor a URL is refused with
268
+ * {@link DDD_FOREIGN_GLOBAL_REQUEST_MESSAGE} (a `FETCH_ERROR`) instead of being sent to `<page>/[object Object]`.
269
+ */
270
+ declare const guardFetchApiRequest: (fetchFn: (input: RequestInfo, init?: RequestInit) => Promise<Response>) => (input: RequestInfo, init?: RequestInit) => Promise<Response>;
264
271
  /**
265
272
  * Binds a request to a session: the base query sends it, and repeats it after a refresh, only while
266
273
  * `expectedSessionKey` is the key of the current session ({@link DddBaseQueryOptions.getSessionKey}). The key travels
@@ -446,5 +453,5 @@ declare function createAuthEndpoints<Definitions extends EndpointDefinitions, Re
446
453
  authRefresh: _reduxjs_toolkit_query.MutationDefinition<DddRefreshRequest, DddBaseQuery, TagTypes, DddAuthResponse, ReducerPath, unknown>;
447
454
  }, ReducerPath, TagTypes, Enhancers>;
448
455
 
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 };
456
+ export { DDD_EXPECTED_SESSION_KEY_HEADER, DDD_FOREIGN_GLOBAL_REQUEST_MESSAGE, 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, guardFetchApiRequest, hasDddMultipartFiles, isDddAuthRequest, isDddSessionChanged, isDddUploadAborted, mergeDddTagTypes, normalizeDddError, readDebugFlags, withDddExpectedSessionKey };
450
457
  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
@@ -1,3 +1,7 @@
1
+ import {
2
+ isFetchApiRequest
3
+ } from "../chunk-QEKNFJYZ.js";
4
+
1
5
  // src/api/baseQuery.ts
2
6
  import {
3
7
  fetchBaseQuery
@@ -91,6 +95,8 @@ var withBearer = (args, accessToken) => {
91
95
  if (!headers.has("authorization")) headers.set("authorization", `Bearer ${accessToken}`);
92
96
  return { ...args, headers };
93
97
  };
98
+ var DDD_FOREIGN_GLOBAL_REQUEST_MESSAGE = "ddd-web: the request was not sent. RTK Query built it with the global `Request`, which on this page is not the Fetch API's (MooTools or Prototype replace it). Hand the toolkit `FetchApiRequest` from `@mgamadeus/ddd-web/fetch-api-request` (`dddFetchApiRequestPlugin()` from `@mgamadeus/ddd-web/vite`).";
99
+ var guardFetchApiRequest = (fetchFn) => (input, init) => typeof input === "string" || input instanceof URL || isFetchApiRequest(input) ? fetchFn(input, init) : Promise.reject(new TypeError(DDD_FOREIGN_GLOBAL_REQUEST_MESSAGE));
94
100
  var withDddExpectedSessionKey = (request, expectedSessionKey) => {
95
101
  const args = toFetchArgs(request);
96
102
  const headers = toHeaders(args.headers);
@@ -116,6 +122,7 @@ function createDddBaseQuery(options) {
116
122
  const fetchQuery = fetchBaseQuery({
117
123
  paramsSerializer: dddParamsSerializer,
118
124
  ...fetchOptions,
125
+ fetchFn: guardFetchApiRequest(fetchOptions?.fetchFn ?? ((input, init) => fetch(input, init))),
119
126
  baseUrl: options.baseUrl,
120
127
  prepareHeaders: async (headers, context) => {
121
128
  const language = languageCode?.(context);
@@ -424,6 +431,7 @@ function createAuthEndpoints(api, options) {
424
431
  }
425
432
  export {
426
433
  DDD_EXPECTED_SESSION_KEY_HEADER,
434
+ DDD_FOREIGN_GLOBAL_REQUEST_MESSAGE,
427
435
  DDD_MULTIPART_BODY_FIELD,
428
436
  DDD_SESSION_CHANGED,
429
437
  DDD_UPLOAD_ABORTED,
@@ -444,6 +452,7 @@ export {
444
452
  getErrorMessage,
445
453
  getErrorStatus,
446
454
  getRequestUrl,
455
+ guardFetchApiRequest,
447
456
  hasDddMultipartFiles,
448
457
  isDddAuthRequest,
449
458
  isDddSessionChanged,
@@ -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 * 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,O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AAI;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';\nimport { isFetchApiRequest } from '../fetch-api-request';\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/** Error text of a request RTK built with a global `Request` that is not the Fetch API's. */\nexport const DDD_FOREIGN_GLOBAL_REQUEST_MESSAGE =\n \"ddd-web: the request was not sent. RTK Query built it with the global `Request`, which on this page is not the Fetch API's \" +\n '(MooTools or Prototype replace it). Hand the toolkit `FetchApiRequest` from `@mgamadeus/ddd-web/fetch-api-request` ' +\n '(`dddFetchApiRequestPlugin()` from `@mgamadeus/ddd-web/vite`).';\n\n/**\n * Wraps a `fetchFn`: an object that is neither a Fetch API request nor a URL is refused with\n * {@link DDD_FOREIGN_GLOBAL_REQUEST_MESSAGE} (a `FETCH_ERROR`) instead of being sent to `<page>/[object Object]`.\n */\nexport const guardFetchApiRequest =\n (fetchFn: (input: RequestInfo, init?: RequestInit) => Promise<Response>) =>\n (input: RequestInfo, init?: RequestInit): Promise<Response> =>\n typeof input === 'string' || input instanceof URL || isFetchApiRequest(input)\n ? fetchFn(input, init)\n : Promise.reject(new TypeError(DDD_FOREIGN_GLOBAL_REQUEST_MESSAGE));\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 fetchFn: guardFetchApiRequest(fetchOptions?.fetchFn ?? ((input, init) => fetch(input, init))),\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,Q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AAO,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":[]}
@@ -0,0 +1,60 @@
1
+ // src/fetch-api-request/index.ts
2
+ var isFetchApiRequest = (candidate) => !!candidate && typeof candidate === "object" && Object.prototype.toString.call(candidate) === "[object Request]";
3
+ var isFetchApiRequestConstructor = (candidate) => typeof candidate === "function" && !!candidate.prototype && Object.prototype.toString.call(candidate.prototype) === "[object Request]";
4
+ var resolvedRequestConstructor = null;
5
+ var resolvedRequestFrame = null;
6
+ var readRequestConstructorOfFrame = (frame) => frame.contentWindow?.Request;
7
+ var addFrameWithFetchApiRequestConstructor = () => {
8
+ const document = globalThis.document;
9
+ if (!document?.createElement || !(document.body || document.documentElement)) return null;
10
+ const frame = document.createElement("iframe");
11
+ frame.hidden = true;
12
+ frame.tabIndex = -1;
13
+ frame.setAttribute("aria-hidden", "true");
14
+ (document.body ?? document.documentElement).appendChild(frame);
15
+ if (isFetchApiRequestConstructor(readRequestConstructorOfFrame(frame))) return frame;
16
+ frame.remove();
17
+ return null;
18
+ };
19
+ function resolveFetchApiRequest() {
20
+ const isFrameStillInPage = resolvedRequestFrame === null || resolvedRequestFrame.isConnected;
21
+ if (resolvedRequestConstructor && isFrameStillInPage) return resolvedRequestConstructor;
22
+ resolvedRequestConstructor = null;
23
+ resolvedRequestFrame = null;
24
+ const globalRequest = globalThis.Request;
25
+ if (isFetchApiRequestConstructor(globalRequest)) {
26
+ resolvedRequestConstructor = globalRequest;
27
+ return globalRequest;
28
+ }
29
+ const frame = addFrameWithFetchApiRequestConstructor();
30
+ if (!frame) {
31
+ throw new Error(
32
+ "ddd-web: the global `Request` is not the Fetch API's (a library such as MooTools or Prototype replaced it), and no frame provides one."
33
+ );
34
+ }
35
+ resolvedRequestFrame = frame;
36
+ resolvedRequestConstructor = readRequestConstructorOfFrame(frame);
37
+ return resolvedRequestConstructor;
38
+ }
39
+ var forgetFetchApiRequest = () => {
40
+ resolvedRequestConstructor = null;
41
+ resolvedRequestFrame = null;
42
+ };
43
+ var resolveAgainstPage = (input) => {
44
+ if (typeof input !== "string") return input;
45
+ const baseUri = globalThis.document?.baseURI;
46
+ return baseUri ? new URL(input, baseUri).href : input;
47
+ };
48
+ var FetchApiRequest = function FetchApiRequest2(input, init) {
49
+ const RequestConstructor = resolveFetchApiRequest();
50
+ return new RequestConstructor(RequestConstructor === globalThis.Request ? input : resolveAgainstPage(input), init);
51
+ };
52
+
53
+ export {
54
+ isFetchApiRequest,
55
+ isFetchApiRequestConstructor,
56
+ resolveFetchApiRequest,
57
+ forgetFetchApiRequest,
58
+ FetchApiRequest
59
+ };
60
+ //# sourceMappingURL=chunk-QEKNFJYZ.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/fetch-api-request/index.ts"],"sourcesContent":["/**\n * The Fetch API's `Request` constructor for pages whose global `Request` is something else (MooTools 1.x and Prototype\n * replace `window.Request` with their Ajax class). RTK Query's `fetchBaseQuery` builds every request with the global\n * `Request`; in such a page the request leaves for `<page>/[object Object]`. A build step that hands the toolkit's query\n * module {@link FetchApiRequest} instead fixes it (see `@mgamadeus/ddd-web/vite`).\n *\n * This module imports nothing from Redux Toolkit, so the toolkit's own module can import it without a cycle.\n */\n\n/** True for a Request object of the Fetch API, from this window or another one (a frame). */\nexport const isFetchApiRequest = (candidate: unknown): candidate is Request =>\n !!candidate && typeof candidate === 'object' && Object.prototype.toString.call(candidate) === '[object Request]';\n\n/** True for the Fetch API's `Request` constructor (its prototype says `[object Request]`), from any window. */\nexport const isFetchApiRequestConstructor = (candidate: unknown): candidate is typeof Request =>\n typeof candidate === 'function' &&\n !!(candidate as { prototype?: unknown }).prototype &&\n Object.prototype.toString.call((candidate as { prototype: unknown }).prototype) === '[object Request]';\n\nlet resolvedRequestConstructor: typeof Request | null = null;\n/** The frame the resolved constructor belongs to; null while the global constructor is the Fetch API's. */\nlet resolvedRequestFrame: HTMLIFrameElement | null = null;\n\nconst readRequestConstructorOfFrame = (frame: HTMLIFrameElement): unknown =>\n (frame.contentWindow as { Request?: unknown } | null)?.Request;\n\n/**\n * Adds a hidden frame without an address, whose globals no script of the page has replaced. The frame stays in the\n * document: the constructors of a removed frame are not guaranteed to keep working.\n */\nconst addFrameWithFetchApiRequestConstructor = (): HTMLIFrameElement | null => {\n const document = (globalThis as { document?: Document }).document;\n if (!document?.createElement || !(document.body || document.documentElement)) return null;\n const frame = document.createElement('iframe');\n frame.hidden = true;\n frame.tabIndex = -1;\n frame.setAttribute('aria-hidden', 'true');\n (document.body ?? document.documentElement).appendChild(frame);\n if (isFetchApiRequestConstructor(readRequestConstructorOfFrame(frame))) return frame;\n frame.remove();\n return null;\n};\n\n/**\n * The Fetch API's `Request` constructor: the global one when it is genuine, else the one of a hidden frame without an\n * address that this module adds (same origin). Resolved once per page, again when a script removed the frame. A request\n * built with it is still sent by the page's `fetch`, so cookies and referrer are the page's.\n *\n * @throws Error when neither the global nor a frame provides one (no DOM, or the frame offers none).\n */\nexport function resolveFetchApiRequest(): typeof Request {\n const isFrameStillInPage = resolvedRequestFrame === null || resolvedRequestFrame.isConnected;\n if (resolvedRequestConstructor && isFrameStillInPage) return resolvedRequestConstructor;\n resolvedRequestConstructor = null;\n resolvedRequestFrame = null;\n const globalRequest = (globalThis as { Request?: unknown }).Request;\n if (isFetchApiRequestConstructor(globalRequest)) {\n resolvedRequestConstructor = globalRequest;\n return globalRequest;\n }\n const frame = addFrameWithFetchApiRequestConstructor();\n if (!frame) {\n throw new Error(\n \"ddd-web: the global `Request` is not the Fetch API's (a library such as MooTools or Prototype replaced it), and no frame provides one.\",\n );\n }\n resolvedRequestFrame = frame;\n resolvedRequestConstructor = readRequestConstructorOfFrame(frame) as typeof Request;\n return resolvedRequestConstructor;\n}\n\n/** Forgets the resolved constructor: the next request resolves it again (tests). */\nexport const forgetFetchApiRequest = (): void => {\n resolvedRequestConstructor = null;\n resolvedRequestFrame = null;\n};\n\n/**\n * A relative address resolved against the page: a frame's constructor would resolve it against the frame's\n * `about:blank`.\n */\nconst resolveAgainstPage = (input: RequestInfo | URL): RequestInfo | URL => {\n if (typeof input !== 'string') return input;\n const baseUri = (globalThis as { document?: Document }).document?.baseURI;\n return baseUri ? new URL(input, baseUri).href : input;\n};\n\n/**\n * Drop-in for the global `Request` that always builds a Fetch API request ({@link resolveFetchApiRequest}); the\n * constructor is resolved on the first `new`, not when the module loads.\n *\n * @example\n * const request = new FetchApiRequest('/api/client/items', { method: 'GET' });\n */\nexport const FetchApiRequest = function FetchApiRequest(input: RequestInfo | URL, init?: RequestInit): Request {\n const RequestConstructor = resolveFetchApiRequest();\n return new RequestConstructor(RequestConstructor === (globalThis as { Request?: unknown }).Request ? input : resolveAgainstPage(input), init);\n} as unknown as typeof Request;\n"],"mappings":";AAUO,IAAM,oBAAoB,CAAC,cAChC,CAAC,CAAC,aAAa,OAAO,cAAc,YAAY,OAAO,UAAU,SAAS,KAAK,SAAS,MAAM;AAGzF,IAAM,+BAA+B,CAAC,cAC3C,OAAO,cAAc,cACrB,CAAC,CAAE,UAAsC,aACzC,OAAO,UAAU,SAAS,KAAM,UAAqC,SAAS,MAAM;AAEtF,IA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