@mgamadeus/ddd-web 0.11.0 → 0.13.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.
@@ -23,7 +23,7 @@ frontend code. No UI components, no domain logic — apps bring their own design
23
23
  | `@mgamadeus/ddd-web/query` | anywhere, no React | QueryOptions builders and definition-driven validators |
24
24
  | `@mgamadeus/ddd-web/api` | needs `@reduxjs/toolkit` 2 (peer) | `createDddBaseQuery` (+ `upload()`, `relogin`, `getSessionKey`), `createDddRefresh`, `normalizeDddError`, downloads, multipart (`buildDddMultipartBody`), `mergeDddTagTypes`, `createAuthEndpoints` |
25
25
  | `@mgamadeus/ddd-web/auth` | anywhere | `TokenStorage` adapters, `decodeJwt`, `isExpired`, SSR-safe storage |
26
- | `@mgamadeus/ddd-web/contract` | types + small helpers | `x-ddd-*` types, error body, DDD date-time, translations, operators |
26
+ | `@mgamadeus/ddd-web/contract` | types + small helpers | `x-ddd-*` types, error body, DDD date-time, translations, operators, `normalizeDddError` / `getErrorMessage` / `getErrorStatus` (also without RTK) |
27
27
 
28
28
  ESM only, Node ≥ 20. Consumers may use npm or pnpm.
29
29
 
@@ -51,7 +51,7 @@ too). A plain RTK-codegen file with `export const apis = [...]` is accepted as w
51
51
  | `workspace` | `{ envVar, envFiles?, urlKeys?, prompt? }`: resolves a workspace / subdomain value (CLI `--workspace` → env → URL sniffed from `.env` / `.env.local` → TTY prompt) into `process.env[envVar]` before the config is evaluated again. |
52
52
  | `tsconfig` | tsconfig of the final type check. Default `tsconfig.json` next to the config. |
53
53
  | `endpoints` | How endpoints and their body argument are named; off by default. `naming: 'path'`: a pure function of verb and path — `stripPathPrefix` (default `/api` or `/app/api`) cut, every `{param}/` cut out and only the LAST one kept, the rest split on `/ _ - .` and capitalised behind the verb, `By<LastInner>` appended, a trailing `{param}` becomes `By<Param>` where it stands (`POST /api/client/ai/conversations/{locationId}/purposed/{purposeName}` → `postClientAiConversationsPurposedByPurposeNameByLocationId`; `buildEndpointNameFromPath` is exported). `naming` may be a function `({ method, path, operation }) => name`. The built name is used verbatim (no second camel-casing); your `filterEndpoints` / `endpointOverrides` match it. Two operations with one name stop the run. `bodyArg: 'requestBody'`: the body is the argument's `requestBody`, whatever its DTO is called. Query and path parameters stay flat in the argument. |
54
- | `models` | How the models of the component schemas are written; every option off by default. `naming: 'document'`: the model is named by the schema name's last dot segment exactly (`AIConversationMessage`, not `AiConversationMessage`), the segments before it are its folders — a neighbour namespace that prefixes the name never splits it. `enums: 'const'` (needs `naming: 'document'`): an enum property becomes `export const <Model><Property> = {…}` and `<Model><Property>Strict = {…} as const` in the model's file, the property typed `(typeof XStrict)[keyof typeof XStrict]` (`\| null` when nullable; `Array<…>` for an enum of array items); keys are the values with spaces, `/`, `\` as `_`, `""` as `EMPTY`. `nullableRefs: true`: `\| null` beside a nullable `$ref`. `idType: 'number' \| 'string'`: an `id` declared `string \| integer` gets that type. With `naming: 'document'` every file exports its own schema's name, also when another folder holds it too; importers alias it, the barrel leaves such a name out, and the api file imports each model by its path. `index: false`: no barrel. `enumPropertyType: 'wide'`: the property typed from the plain object (`string` in effect) instead of the Strict one. `objectType: 'const'`: a string `objectType` gets the one-value const of its schema name (`.` → `\\`, key `.` → `_`) and is required. Enum keys camel-case a dash (`gpt-realtime` → `gptRealtime`); an enum on an array schema stays an array. |
54
+ | `models` | How the models of the component schemas are written; every option off by default. `naming: 'document'`: the model is named by the schema name's last dot segment exactly (`AIConversationMessage`, not `AiConversationMessage`), the segments before it are its folders — a neighbour namespace that prefixes the name never splits it. `enums: 'const'` (needs `naming: 'document'`): an enum property becomes `export const <Model><Property> = {…}` and `<Model><Property>Strict = {…} as const` in the model's file, the property typed `(typeof XStrict)[keyof typeof XStrict]` (`\| null` when nullable; `Array<…>` for an enum of array items); keys are the values with spaces, `/`, `\` as `_`, `""` as `EMPTY`. `nullableRefs: true`: `\| null` beside a nullable `$ref`. `idType: 'number' \| 'string'`: an `id` declared `string \| integer` gets that type. With `naming: 'document'` every file exports its own schema's name, also when another folder holds it too; importers alias it, the barrel leaves such a name out, and the api file imports each model by its path. `index: false`: no barrel. `enumPropertyType: 'wide'`: the property typed from the plain object (`string` in effect) instead of the Strict one. `objectType: 'const'`: a string `objectType` gets the one-value const of its schema name (`.` → `\\`, key `.` → `_`) and is required. Enum keys camel-case a dash (`gpt-realtime` → `gptRealtime`); a value that still gives no identifier is its own quoted key; an enum on an array schema stays an array. `scope: 'all'`: the models of every operation are written also when `filterEndpoints` keeps them out of the api file (their argument types are not). With several documents a shared model and its enum consts come from the first-listed one. |
55
55
 
56
56
  ```ts
57
57
  export default defineConfig({
@@ -365,7 +365,7 @@ shouldRefresh: (error, request) =>
365
365
  (error.status === 401 || error.status === 403) && !isBusinessRefusal(error) && !isDddAuthRequest(request),
366
366
  ```
367
367
 
368
- Errors: `normalizeDddError(error)` → `{ status, message, validationErrors, details, body }` from an RTK error, a thrown
368
+ Errors (from `/api`, or from `/contract` in code that loads no RTK Query): `normalizeDddError(error)` → `{ status, message, validationErrors, details, body }` from an RTK error, a thrown
369
369
  `Error` or a raw body (`error` key first, then a text body); `getErrorMessage`, `getErrorStatus` for UI code. A
370
370
  response that is not JSON (an HTML error page, a PHP fatal, a proxy 502 — RTK's `PARSING_ERROR`) counts as an HTTP
371
371
  error: `status` is the HTTP status, the message `Server error (HTTP 500)` / `Request failed (HTTP 404)`, never the
package/CHANGELOG.md CHANGED
@@ -1,5 +1,25 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.13.0
4
+
5
+ ### Added
6
+ - `@mgamadeus/ddd-web/contract` exports `normalizeDddError`, `getErrorMessage`, `getErrorStatus`,
7
+ `DEFAULT_ERROR_MESSAGE`, `DEFAULT_ERROR_MESSAGES` and the types `DddNormalizedError`, `DddErrorMessages`: code that
8
+ loads no RTK Query runtime (a logic layer without Redux) normalizes DDD errors too. `/api` exports the same
9
+ functions as before.
10
+
11
+ ## 0.12.0
12
+
13
+ ### Added
14
+ - `models.scope: 'all'`: every schema an operation of the document reaches is written, also when `filterEndpoints`
15
+ leaves the operation out of the api file (a models-only pass; its argument and response types are not written).
16
+ Default `reachable` (as before).
17
+
18
+ ### Fixed
19
+ - With several documents, the enum consts of a shared model came from the LAST document while its type came from the
20
+ first: both come from the first-listed document now.
21
+ - An enum value that gives no identifier after the key rules (`gemini/gemini-3.1-flash`) is its own quoted key.
22
+
3
23
  ## 0.11.0
4
24
 
5
25
  ### Added
@@ -2,7 +2,7 @@ import * as _reduxjs_toolkit_query from '@reduxjs/toolkit/query';
2
2
  import { FetchArgs, BaseQueryFn, FetchBaseQueryError, FetchBaseQueryMeta, BaseQueryApi, FetchBaseQueryArgs, EndpointDefinitions, ApiModules, Api } from '@reduxjs/toolkit/query';
3
3
  import { D as DddTokens } from '../types-BhDMN3ZS.js';
4
4
  import { DddLoginRequest, DddAuthResponse, DddRefreshRequest } from '../auth/index.js';
5
- import { DddExceptionDetail } from '../contract/index.js';
5
+ export { D as DEFAULT_ERROR_MESSAGE, a as DEFAULT_ERROR_MESSAGES, b as DddErrorMessages, c as DddNormalizedError, g as getErrorMessage, d as getErrorStatus, n as normalizeDddError } from '../error-normalization-ytMgz5HP.js';
6
6
 
7
7
  /**
8
8
  * Debug passthrough: flags present in the page URL (`?debug`, `?noCache`, `?xdebug`, `?errorsAsJson`) are forwarded to
@@ -340,69 +340,6 @@ type DddTagCheck<Generated extends readonly string[], Extra extends readonly str
340
340
  */
341
341
  declare function mergeDddTagTypes<const Generated extends readonly string[], const Extra extends readonly string[] = readonly []>(generated: Generated, extra?: Extra & DddTagCheck<Generated, Extra>): (Generated[number] | Extra[number])[];
342
342
 
343
- /** A DDD API error in one predictable shape, whatever produced it (RTK Query, a thrown Error, a raw body). */
344
- interface DddNormalizedError {
345
- /**
346
- * HTTP status, or RTK Query's string status for non-HTTP failures (`FETCH_ERROR`, `TIMEOUT_ERROR`,
347
- * `CUSTOM_ERROR`); a `PARSING_ERROR` reports the original HTTP status. `null` when unknown.
348
- */
349
- status: number | string | null;
350
- /** Human-readable message: the backend's `error` key first, then a text body, then generic fallbacks. */
351
- message: string;
352
- /** The backend's `validationErrors` exactly as received (present on validation 400s), else `null`. */
353
- validationErrors: unknown;
354
- /** `exceptionDetails.elements` of the backend body; empty when absent. */
355
- details: DddExceptionDetail[];
356
- /** The raw response body (parsed JSON, text, or `undefined`). */
357
- body: unknown;
358
- }
359
- /** Message used when an error carries no message at all. */
360
- declare const DEFAULT_ERROR_MESSAGE = "Request failed";
361
- /**
362
- * Messages for failures that carry no usable backend message. Pass your own (e.g. translated) texts as the third
363
- * argument of {@link normalizeDddError} / {@link getErrorMessage}.
364
- */
365
- interface DddErrorMessages {
366
- /** A response that is not JSON (an HTML error page, a PHP fatal) with an HTTP status ≥ 500. */
367
- serverError: (status: number) => string;
368
- /** A response that is not JSON with an HTTP status < 500. */
369
- httpError: (status: number) => string;
370
- /** The request never reached the server or got no response (`FETCH_ERROR`). */
371
- networkError: string;
372
- /** The request timed out (`TIMEOUT_ERROR`). */
373
- timeoutError: string;
374
- }
375
- /** The default {@link DddErrorMessages}. */
376
- declare const DEFAULT_ERROR_MESSAGES: DddErrorMessages;
377
- /**
378
- * Normalises any API error into {@link DddNormalizedError}.
379
- *
380
- * Understands RTK Query's `FetchBaseQueryError` (`{ status, data }`, `{ status: 'FETCH_ERROR', error }`, …),
381
- * `SerializedError` / `Error` (`message`), errors carrying a parsed `responseBody`, and a bare DDD error body.
382
- * DDD error bodies put the message under `error` (not `message`).
383
- *
384
- * A response the client could not parse (`PARSING_ERROR`: an HTML error page, a PHP fatal, a proxy's 502) is an HTTP
385
- * error: `status` is the HTTP status and the message is {@link DddErrorMessages.serverError} /
386
- * {@link DddErrorMessages.httpError} — never the parser's `SyntaxError` text and never the raw body, which may show
387
- * internals (the body stays available in `body`). `FETCH_ERROR` and `TIMEOUT_ERROR` get
388
- * {@link DddErrorMessages.networkError} / {@link DddErrorMessages.timeoutError} instead of the browser's text.
389
- *
390
- * @param error whatever a request rejected with
391
- * @param fallbackMessage message when nothing usable is found
392
- * @param messages texts for failures without a backend message (default {@link DEFAULT_ERROR_MESSAGES})
393
- */
394
- declare function normalizeDddError(error: unknown, fallbackMessage?: string, messages?: Partial<DddErrorMessages>): DddNormalizedError;
395
- /**
396
- * The message to show for an API error (`normalizeDddError(error).message`).
397
- *
398
- * @param error whatever a request rejected with
399
- * @param fallbackMessage message when nothing usable is found
400
- * @param messages texts for failures without a backend message
401
- */
402
- declare function getErrorMessage(error: unknown, fallbackMessage?: string, messages?: Partial<DddErrorMessages>): string;
403
- /** HTTP status of an API error (also of an unparsable response), or `null` for non-HTTP failures. */
404
- declare function getErrorStatus(error: unknown): number | null;
405
-
406
343
  /** A binary response decoded by {@link blobResponseHandler}. */
407
344
  interface DddFileResponse {
408
345
  blob: Blob;
@@ -470,5 +407,5 @@ declare function createAuthEndpoints<Definitions extends EndpointDefinitions, Re
470
407
  authRefresh: _reduxjs_toolkit_query.MutationDefinition<DddRefreshRequest, DddBaseQuery, TagTypes, DddAuthResponse, ReducerPath, unknown>;
471
408
  }, ReducerPath, TagTypes, Enhancers>;
472
409
 
473
- 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 };
474
- 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 };
410
+ export { DDD_EXPECTED_SESSION_KEY_HEADER, DDD_FOREIGN_GLOBAL_REQUEST_MESSAGE, DDD_MULTIPART_BODY_FIELD, DDD_SESSION_CHANGED, DDD_UPLOAD_ABORTED, DddTokens, applyDebugParams, blobResponseHandler, buildDddFormData, buildDddMultipartBody, createAuthEndpoints, createDddBaseQuery, createDddRefresh, createDownloadResponseHandler, dddParamsSerializer, defaultShouldRefresh, downloadBlob, filenameFromContentDisposition, getRequestUrl, guardFetchApiRequest, hasDddMultipartFiles, isDddAuthRequest, isDddSessionChanged, isDddUploadAborted, mergeDddTagTypes, readDebugFlags, withDddExpectedSessionKey };
411
+ export type { DddAuthEndpointsOptions, DddBaseQuery, DddBaseQueryOptions, DddDebugFlags, DddDebugOptions, DddDownloadedFile, DddFilePart, DddFileResponse, DddHeadersContext, DddMultipartFiles, DddRawBaseQuery, DddRefreshContext, DddRefreshFn, DddReloginContext, DddReloginFn, DddRequestContext, DddSessionBindingOptions, DddShouldRefresh, DddUploadRequest, DddUploadResult, DddUploadingBaseQuery };
package/dist/api/index.js CHANGED
@@ -1,3 +1,10 @@
1
+ import {
2
+ DEFAULT_ERROR_MESSAGE,
3
+ DEFAULT_ERROR_MESSAGES,
4
+ getErrorMessage,
5
+ getErrorStatus,
6
+ normalizeDddError
7
+ } from "../chunk-WZTEQOE6.js";
1
8
  import {
2
9
  isFetchApiRequest
3
10
  } from "../chunk-QEKNFJYZ.js";
@@ -305,80 +312,6 @@ function mergeDddTagTypes(generated, extra) {
305
312
  return [.../* @__PURE__ */ new Set([...generated, ...extra ?? []])];
306
313
  }
307
314
 
308
- // src/api/errors.ts
309
- var DEFAULT_ERROR_MESSAGE = "Request failed";
310
- var DEFAULT_ERROR_MESSAGES = {
311
- serverError: (status) => `Server error (HTTP ${status})`,
312
- httpError: (status) => `Request failed (HTTP ${status})`,
313
- networkError: "The server could not be reached",
314
- timeoutError: "The request timed out"
315
- };
316
- var isRecord = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
317
- var nonEmptyString = (value) => typeof value === "string" && value.trim() !== "" ? value : null;
318
- var extractBody = (error) => {
319
- if ("data" in error) return error.data;
320
- if ("responseBody" in error) return error.responseBody;
321
- if ("error" in error || "validationErrors" in error || "exceptionDetails" in error) return error;
322
- return void 0;
323
- };
324
- var extractStatus = (error) => {
325
- if (error.status === "PARSING_ERROR" && typeof error.originalStatus === "number") return error.originalStatus;
326
- if (typeof error.status === "number" || typeof error.status === "string") return error.status;
327
- if (typeof error.statusCode === "number") return error.statusCode;
328
- return null;
329
- };
330
- var transportFailureMessage = (error, texts, fallbackMessage) => {
331
- switch (error.status) {
332
- case "PARSING_ERROR": {
333
- const status = typeof error.originalStatus === "number" ? error.originalStatus : null;
334
- if (status === null) return fallbackMessage;
335
- return status >= 500 ? texts.serverError(status) : texts.httpError(status);
336
- }
337
- case "FETCH_ERROR":
338
- return texts.networkError;
339
- case "TIMEOUT_ERROR":
340
- return texts.timeoutError;
341
- default:
342
- return null;
343
- }
344
- };
345
- function normalizeDddError(error, fallbackMessage = DEFAULT_ERROR_MESSAGE, messages = {}) {
346
- const texts = { ...DEFAULT_ERROR_MESSAGES, ...messages };
347
- if (!isRecord(error)) {
348
- return {
349
- status: null,
350
- message: nonEmptyString(error) ?? fallbackMessage,
351
- validationErrors: null,
352
- details: [],
353
- body: void 0
354
- };
355
- }
356
- const body = extractBody(error);
357
- const failure = transportFailureMessage(error, texts, fallbackMessage);
358
- if (failure !== null) {
359
- return { status: extractStatus(error), message: failure, validationErrors: null, details: [], body };
360
- }
361
- const dddBody = isRecord(body) ? body : null;
362
- const bodyRecord = isRecord(body) ? body : null;
363
- const message = nonEmptyString(dddBody?.error) ?? nonEmptyString(bodyRecord?.message) ?? // RTK's non-HTTP errors carry the reason in `error` (e.g. "TypeError: Failed to fetch").
364
- (body === void 0 || typeof body === "string" ? nonEmptyString(error.error) : null) ?? // A non-JSON error body (e.g. a download endpoint answering with plain text) is the message itself.
365
- nonEmptyString(body)?.trim() ?? nonEmptyString(error.message) ?? fallbackMessage;
366
- return {
367
- status: extractStatus(error),
368
- message,
369
- validationErrors: dddBody?.validationErrors ?? null,
370
- details: dddBody?.exceptionDetails?.elements ?? [],
371
- body
372
- };
373
- }
374
- function getErrorMessage(error, fallbackMessage = DEFAULT_ERROR_MESSAGE, messages = {}) {
375
- return normalizeDddError(error, fallbackMessage, messages).message;
376
- }
377
- function getErrorStatus(error) {
378
- const status = normalizeDddError(error).status;
379
- return typeof status === "number" ? status : null;
380
- }
381
-
382
315
  // src/api/download.ts
383
316
  function filenameFromContentDisposition(header) {
384
317
  if (!header) return null;
@@ -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';\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 /**\n * With `files`: the JSON envelope, sent in the form field `body` (left out when `undefined`). Without `files` and\n * `formData`: the JSON body of the request (`content-type: application/json`); `undefined` sends no body.\n */\n body?: unknown;\n /** File parts per form field (the `Parameter::FILES` properties of the request DTO): the DDD multipart form. */\n files?: DddMultipartFiles;\n /** A form the caller built, sent as it is (wins over `body` and `files`). */\n formData?: FormData;\n /**\n * Query parameters; `null` / `undefined` values are skipped. Serialized by `fetchOptions.paramsSerializer` when the\n * base query has one, else by the DDD serializer.\n */\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 /** Bytes of the response received so far; `total` is 0 when the server sends no length. */\n onDownloadProgress?: (loaded: number, total: number) => void;\n /**\n * How the response becomes `data` (and an error's `data`): `json` (default; a body that is no JSON stays text),\n * `text`, or `blob` (a download).\n */\n responseType?: 'json' | 'text' | 'blob';\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 request with progress (XMLHttpRequest: `fetch` reports no upload progress) through the same session as\n * every request: Bearer, `headers` / `languageCode` hooks, one shared refresh and one retry. The body is the DDD\n * multipart form (`files`), a form the caller built (`formData`) or JSON (`body` alone); `onDownloadProgress` with\n * `responseType: 'blob'` serves a download.\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/** The body an upload sends and its content type (none for a form: the runtime sets the boundary). */\nfunction buildUploadBody(request: DddUploadRequest): { body: FormData | string | null; contentType?: string } {\n if (request.formData) return { body: request.formData };\n if (request.files) return { body: buildDddFormData(request.body, request.files) };\n if (request.body === undefined) return { body: null };\n return { body: JSON.stringify(request.body), contentType: 'application/json' };\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 ? (fetchOptions?.paramsSerializer ?? 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, onDownloadProgress } = request;\n const responseType = request.responseType ?? 'json';\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 const sentBody = buildUploadBody(request);\n xhr.open(request.method ?? 'POST', url);\n if (responseType === 'blob') xhr.responseType = 'blob';\n if (sentBody.contentType) headers.set('content-type', sentBody.contentType);\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 if (onDownloadProgress) {\n xhr.onprogress = (event) => onDownloadProgress(event.loaded, event.lengthComputable ? event.total : 0);\n }\n xhr.onload = () => {\n let data: unknown;\n if (responseType === 'blob') {\n data = xhr.response;\n } else {\n const text = xhr.responseText;\n if (responseType === 'text') {\n data = text;\n } else {\n try {\n data = text ? JSON.parse(text) : undefined;\n } catch {\n data = text;\n }\n }\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(sentBody.body);\n });\n };\n\n const upload: DddUploadingBaseQuery['upload'] = async (request, api, extraOptions) => {\n const boundSessionKey = await resolveBoundSessionKey(request.expectedSessionKey, api, extraOptions);\n while (inflight) await inflight.catch(() => undefined);\n const startGeneration = generation;\n const result = await sendUpload(request, boundSessionKey, api, extraOptions);\n if (!result.error || isDddSessionChanged(result.error)) return result;\n if (!shouldRefresh(result.error, { url: request.url, method: request.method ?? 'POST' })) return result;\n if ((await recover(startGeneration, api, extraOptions)) !== 'refreshed') return result;\n return sendUpload(request, boundSessionKey, api, extraOptions);\n };\n\n return Object.assign(baseQuery, { upload });\n}\n","import type { FetchArgs } from '@reduxjs/toolkit/query';\n\n/**\n * Debug passthrough: flags present in the page URL (`?debug`, `?noCache`, `?xdebug`, `?errorsAsJson`) are forwarded to\n * every API request as the query parameters a DDD backend understands.\n */\nexport interface DddDebugOptions {\n /** Where the flags come from. Default: `window.location.search` (nothing outside a browser). */\n searchParams?: () => URLSearchParams | null | undefined;\n /** Value of `XDEBUG_SESSION` when `?xdebug` is set. Default `1`. */\n xdebugSessionKey?: string;\n}\n\n/** The debug flags active for one request. */\nexport interface DddDebugFlags {\n debug: boolean;\n noCache: boolean;\n xdebug: boolean;\n errorsAsJson: boolean;\n}\n\nconst defaultSearchParams = (): URLSearchParams | null =>\n typeof window !== 'undefined' && window.location ? new URLSearchParams(window.location.search) : null;\n\n/** Reads the active debug flags. */\nexport function readDebugFlags(options: DddDebugOptions = {}): DddDebugFlags {\n const params = (options.searchParams ?? defaultSearchParams)() ?? null;\n return {\n debug: params?.has('debug') ?? false,\n noCache: params?.has('noCache') ?? false,\n xdebug: params?.has('xdebug') ?? false,\n errorsAsJson: params?.has('errorsAsJson') ?? false,\n };\n}\n\nconst appendToUrl = (url: string, key: string, value: string): string =>\n new RegExp(`[?&]${key}=`, 'i').test(url)\n ? url\n : `${url}${url.includes('?') ? '&' : '?'}${encodeURIComponent(key)}=${encodeURIComponent(value)}`;\n\n/**\n * Adds the query parameters for the active debug flags to a request, never overwriting a parameter the caller set.\n */\nexport function applyDebugParams(\n args: string | FetchArgs,\n flags: DddDebugFlags,\n xdebugSessionKey = '1',\n): string | FetchArgs {\n const extra: Array<[string, string]> = [];\n if (flags.debug) extra.push(['debug', 'true']);\n if (flags.noCache) extra.push(['noCache', 'true']);\n if (flags.xdebug) extra.push(['XDEBUG_SESSION', xdebugSessionKey]);\n if (flags.errorsAsJson) extra.push(['errors_as_json', '1']);\n if (extra.length === 0) return args;\n\n if (typeof args === 'string') {\n return extra.reduce((url, [key, value]) => appendToUrl(url, key, value), args);\n }\n const params: Record<string, unknown> = { ...(args.params ?? {}) };\n for (const [key, value] of extra) {\n if (params[key] === undefined && !new RegExp(`[?&]${key}=`, 'i').test(args.url)) params[key] = value;\n }\n return { ...args, params };\n}\n","/**\n * One file part: a `File` / `Blob` in a browser, or React Native's `{ uri, name, type }` file reference.\n */\nexport type DddFilePart = Blob | { uri: string; name: string; type: string };\n\n/** File parts per form field of a DDD request DTO (its `Parameter::FILES` properties). */\nexport type DddMultipartFiles<Field extends string = string> = Partial<\n Record<Field, readonly DddFilePart[] | DddFilePart | null | undefined>\n>;\n\n/** Form field a DDD backend reads the JSON envelope of a multipart request from. */\nexport const DDD_MULTIPART_BODY_FIELD = 'body';\n\nconst partsOf = (value: readonly DddFilePart[] | DddFilePart | null | undefined): readonly DddFilePart[] => {\n if (value === null || value === undefined) return [];\n return Array.isArray(value) ? (value as readonly DddFilePart[]) : [value as DddFilePart];\n};\n\n/** True when at least one file part is present. */\nexport function hasDddMultipartFiles(files: DddMultipartFiles | null | undefined): boolean {\n return !!files && Object.values(files).some((value) => partsOf(value).length > 0);\n}\n\n/**\n * The `multipart/form-data` body of a DDD request: the JSON envelope in the form field `body` (left out when\n * `body` is `undefined`) and every file as a part named `<field>[]`. No `Content-Type` header must be set for it: the\n * runtime adds the multipart boundary itself.\n */\nexport function buildDddFormData(body: unknown, files: DddMultipartFiles | null | undefined): FormData {\n const formData = new FormData();\n if (body !== undefined) formData.append(DDD_MULTIPART_BODY_FIELD, JSON.stringify(body));\n for (const [field, value] of Object.entries(files ?? {})) {\n for (const part of partsOf(value)) {\n const name = typeof (part as { name?: unknown }).name === 'string' ? (part as { name: string }).name : '';\n // A React Native file reference is appended as it is; a Blob without a name gets the field name.\n if (typeof Blob !== 'undefined' && part instanceof Blob) formData.append(`${field}[]`, part, name || field);\n else formData.append(`${field}[]`, part as unknown as Blob);\n }\n }\n return formData;\n}\n\n/**\n * Request body of an endpoint that accepts JSON and file parts: `body` itself while no file is given (a plain JSON\n * request), else the multipart form of {@link buildDddFormData}. Generated endpoints of operations with a\n * `multipart/form-data` request body call it with their `multipartFiles` argument.\n */\nexport function buildDddMultipartBody<Body>(body: Body, files: DddMultipartFiles | null | undefined): Body | FormData {\n return hasDddMultipartFiles(files) ? buildDddFormData(body, files) : body;\n}\n","import type { BaseQueryApi, BaseQueryFn, FetchArgs, FetchBaseQueryError, FetchBaseQueryMeta } from '@reduxjs/toolkit/query';\nimport type { DddAuthResponse, DddTokens } from '../auth/types';\n\n/** The raw (non-refreshing) base query handed to a refresh function. */\nexport type DddRawBaseQuery = BaseQueryFn<string | FetchArgs, unknown, FetchBaseQueryError, {}, FetchBaseQueryMeta>;\n\n/** Everything a refresh function needs. */\nexport interface DddRefreshContext {\n /** The refresh token currently stored. */\n refreshToken: string;\n /** The underlying fetch base query (no auth retry, Bearer of the current access token still applied). */\n baseQuery: DddRawBaseQuery;\n api: BaseQueryApi;\n extraOptions: unknown;\n}\n\n/**\n * Exchanges a refresh token for a new token pair.\n *\n * @returns the new pair, or `null` when the refresh token was rejected (the base query then logs out).\n * A missing `refreshToken` in the result keeps the stored one.\n */\nexport type DddRefreshFn = (context: DddRefreshContext) => Promise<DddTokens | null>;\n\n/** Everything a re-login function needs. */\nexport interface DddReloginContext {\n /** Why the refresh could not recover the session. */\n reason: 'no-refresh-token' | 'refresh-rejected';\n /** The underlying fetch base query (no auth retry, Bearer of the current access token still applied). */\n baseQuery: DddRawBaseQuery;\n api: BaseQueryApi;\n extraOptions: unknown;\n}\n\n/**\n * Re-opens a session without a usable refresh token (guest credential, device id, impersonation through another\n * session, …).\n *\n * @returns the new tokens (`refreshToken: null` for a session that has none), or `null` to end the session.\n */\nexport type DddReloginFn = (context: DddReloginContext) => Promise<DddTokens | null>;\n\n/**\n * The default {@link DddRefreshFn}: `POST <path>` with `{ refreshToken }`, expecting the DDD `AuthPostResponseDto`\n * `{ accessToken, refreshToken }`. DDD refresh tokens are stateless and re-issued with a renewed lifetime.\n *\n * @param path refresh endpoint relative to the base URL, e.g. `/api/admin/common/auth/refresh`\n */\nexport function createDddRefresh(path: string): DddRefreshFn {\n return async ({ refreshToken, baseQuery, api, extraOptions }) => {\n const result = await baseQuery({ url: path, method: 'POST', body: { refreshToken } }, api, extraOptions as {});\n const payload = result.data as DddAuthResponse | undefined;\n if (result.error || !payload?.accessToken) return null;\n return { accessToken: payload.accessToken, refreshToken: payload.refreshToken ?? refreshToken };\n };\n}\n","/** The tags of `Extra` that differ from a tag of `Generated` only by case. */\ntype DddTagCaseConflict<Extra extends string, Generated extends string> = Extra extends Generated\n ? never\n : Lowercase<Extra> extends Lowercase<Generated>\n ? Extra\n : never;\n\ntype DddTagCheck<Generated extends readonly string[], Extra extends readonly string[]> = [\n DddTagCaseConflict<Extra[number], Generated[number]>,\n] extends [never]\n ? unknown\n : { 'tag differs from a generated tag only by case': DddTagCaseConflict<Extra[number], Generated[number]> };\n\n/**\n * The `tagTypes` of a base api: the generated tag lists (`<stem>TagTypes` of the `<stem>Tags.ts` files) plus the\n * app's own tags. With this list every `providesTags` / `invalidatesTags` of a hand-written endpoint and every\n * `api.util.invalidateTags()` is checked against the generated names, so a mistyped tag does not compile. An own tag\n * that differs from a generated one only by case (`ProspectActivities` next to the generated `Prospectactivities`)\n * is rejected here: it would be a second tag that no generated endpoint provides.\n *\n * @example\n * export const baseApi = createApi({\n * baseQuery,\n * tagTypes: mergeDddTagTypes([...adminApiTagTypes, ...clientApiTagTypes], ['Session']),\n * endpoints: () => ({}),\n * });\n */\nexport function mergeDddTagTypes<const Generated extends readonly string[], const Extra extends readonly string[] = readonly []>(\n generated: Generated,\n extra?: Extra & DddTagCheck<Generated, Extra>,\n): (Generated[number] | Extra[number])[] {\n return [...new Set<string>([...generated, ...(extra ?? [])])] as (Generated[number] | Extra[number])[];\n}\n","import type { DddErrorBody, DddExceptionDetail } from '../contract/errors';\n\n/** A DDD API error in one predictable shape, whatever produced it (RTK Query, a thrown Error, a raw body). */\nexport interface DddNormalizedError {\n /**\n * HTTP status, or RTK Query's string status for non-HTTP failures (`FETCH_ERROR`, `TIMEOUT_ERROR`,\n * `CUSTOM_ERROR`); a `PARSING_ERROR` reports the original HTTP status. `null` when unknown.\n */\n status: number | string | null;\n /** Human-readable message: the backend's `error` key first, then a text body, then generic fallbacks. */\n message: string;\n /** The backend's `validationErrors` exactly as received (present on validation 400s), else `null`. */\n validationErrors: unknown;\n /** `exceptionDetails.elements` of the backend body; empty when absent. */\n details: DddExceptionDetail[];\n /** The raw response body (parsed JSON, text, or `undefined`). */\n body: unknown;\n}\n\n/** Message used when an error carries no message at all. */\nexport const DEFAULT_ERROR_MESSAGE = 'Request failed';\n\n/**\n * Messages for failures that carry no usable backend message. Pass your own (e.g. translated) texts as the third\n * argument of {@link normalizeDddError} / {@link getErrorMessage}.\n */\nexport interface DddErrorMessages {\n /** A response that is not JSON (an HTML error page, a PHP fatal) with an HTTP status ≥ 500. */\n serverError: (status: number) => string;\n /** A response that is not JSON with an HTTP status < 500. */\n httpError: (status: number) => string;\n /** The request never reached the server or got no response (`FETCH_ERROR`). */\n networkError: string;\n /** The request timed out (`TIMEOUT_ERROR`). */\n timeoutError: string;\n}\n\n/** The default {@link DddErrorMessages}. */\nexport const DEFAULT_ERROR_MESSAGES: DddErrorMessages = {\n serverError: (status) => `Server error (HTTP ${status})`,\n httpError: (status) => `Request failed (HTTP ${status})`,\n networkError: 'The server could not be reached',\n timeoutError: 'The request timed out',\n};\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n value !== null && typeof value === 'object' && !Array.isArray(value);\n\nconst nonEmptyString = (value: unknown): string | null =>\n typeof value === 'string' && value.trim() !== '' ? value : null;\n\n/** Unwraps the places a response body can sit: RTK `data`, an Error's `responseBody`, or the value itself. */\nconst extractBody = (error: Record<string, unknown>): unknown => {\n if ('data' in error) return error.data;\n if ('responseBody' in error) return error.responseBody;\n if ('error' in error || 'validationErrors' in error || 'exceptionDetails' in error) return error;\n return undefined;\n};\n\nconst extractStatus = (error: Record<string, unknown>): number | string | null => {\n if (error.status === 'PARSING_ERROR' && typeof error.originalStatus === 'number') return error.originalStatus;\n if (typeof error.status === 'number' || typeof error.status === 'string') return error.status;\n if (typeof error.statusCode === 'number') return error.statusCode;\n return null;\n};\n\n/**\n * The message of an RTK Query failure that is not a DDD response: an unparsable body (`PARSING_ERROR`), no response\n * (`FETCH_ERROR`), a timeout (`TIMEOUT_ERROR`); `null` for everything else.\n */\nconst transportFailureMessage = (\n error: Record<string, unknown>,\n texts: DddErrorMessages,\n fallbackMessage: string,\n): string | null => {\n switch (error.status) {\n case 'PARSING_ERROR': {\n const status = typeof error.originalStatus === 'number' ? error.originalStatus : null;\n if (status === null) return fallbackMessage;\n return status >= 500 ? texts.serverError(status) : texts.httpError(status);\n }\n case 'FETCH_ERROR':\n return texts.networkError;\n case 'TIMEOUT_ERROR':\n return texts.timeoutError;\n default:\n return null;\n }\n};\n\n/**\n * Normalises any API error into {@link DddNormalizedError}.\n *\n * Understands RTK Query's `FetchBaseQueryError` (`{ status, data }`, `{ status: 'FETCH_ERROR', error }`, …),\n * `SerializedError` / `Error` (`message`), errors carrying a parsed `responseBody`, and a bare DDD error body.\n * DDD error bodies put the message under `error` (not `message`).\n *\n * A response the client could not parse (`PARSING_ERROR`: an HTML error page, a PHP fatal, a proxy's 502) is an HTTP\n * error: `status` is the HTTP status and the message is {@link DddErrorMessages.serverError} /\n * {@link DddErrorMessages.httpError} — never the parser's `SyntaxError` text and never the raw body, which may show\n * internals (the body stays available in `body`). `FETCH_ERROR` and `TIMEOUT_ERROR` get\n * {@link DddErrorMessages.networkError} / {@link DddErrorMessages.timeoutError} instead of the browser's text.\n *\n * @param error whatever a request rejected with\n * @param fallbackMessage message when nothing usable is found\n * @param messages texts for failures without a backend message (default {@link DEFAULT_ERROR_MESSAGES})\n */\nexport function normalizeDddError(\n error: unknown,\n fallbackMessage: string = DEFAULT_ERROR_MESSAGE,\n messages: Partial<DddErrorMessages> = {},\n): DddNormalizedError {\n const texts: DddErrorMessages = { ...DEFAULT_ERROR_MESSAGES, ...messages };\n if (!isRecord(error)) {\n return {\n status: null,\n message: nonEmptyString(error) ?? fallbackMessage,\n validationErrors: null,\n details: [],\n body: undefined,\n };\n }\n\n const body = extractBody(error);\n const failure = transportFailureMessage(error, texts, fallbackMessage);\n if (failure !== null) {\n return { status: extractStatus(error), message: failure, validationErrors: null, details: [], body };\n }\n const dddBody: DddErrorBody | null = isRecord(body) ? (body as DddErrorBody) : null;\n const bodyRecord: Record<string, unknown> | null = isRecord(body) ? body : null;\n\n const message =\n nonEmptyString(dddBody?.error) ??\n nonEmptyString(bodyRecord?.message) ??\n // RTK's non-HTTP errors carry the reason in `error` (e.g. \"TypeError: Failed to fetch\").\n (body === undefined || typeof body === 'string' ? nonEmptyString(error.error) : null) ??\n // A non-JSON error body (e.g. a download endpoint answering with plain text) is the message itself.\n nonEmptyString(body)?.trim() ??\n nonEmptyString(error.message) ??\n fallbackMessage;\n\n return {\n status: extractStatus(error),\n message,\n validationErrors: dddBody?.validationErrors ?? null,\n details: dddBody?.exceptionDetails?.elements ?? [],\n body,\n };\n}\n\n/**\n * The message to show for an API error (`normalizeDddError(error).message`).\n *\n * @param error whatever a request rejected with\n * @param fallbackMessage message when nothing usable is found\n * @param messages texts for failures without a backend message\n */\nexport function getErrorMessage(\n error: unknown,\n fallbackMessage: string = DEFAULT_ERROR_MESSAGE,\n messages: Partial<DddErrorMessages> = {},\n): string {\n return normalizeDddError(error, fallbackMessage, messages).message;\n}\n\n/** HTTP status of an API error (also of an unparsable response), or `null` for non-HTTP failures. */\nexport function getErrorStatus(error: unknown): number | null {\n const status = normalizeDddError(error).status;\n return typeof status === 'number' ? status : null;\n}\n","/** A binary response decoded by {@link blobResponseHandler}. */\nexport interface DddFileResponse {\n blob: Blob;\n /** File name from `Content-Disposition`, else `null`. */\n filename: string | null;\n /** `Content-Type` of the response, else `null`. */\n contentType: string | null;\n}\n\n/** Serializable summary returned by {@link createDownloadResponseHandler} (safe to keep in the Redux store). */\nexport interface DddDownloadedFile {\n filename: string;\n contentType: string | null;\n size: number;\n}\n\n/**\n * Reads the file name from a `Content-Disposition` header. Prefers RFC 5987 `filename*=UTF-8''…` over `filename=`.\n *\n * @returns the decoded file name, or `null` when the header has none.\n */\nexport function filenameFromContentDisposition(header: string | null | undefined): string | null {\n if (!header) return null;\n const extended = /filename\\*\\s*=\\s*([^']*)'[^']*'([^;]+)/i.exec(header);\n if (extended?.[2]) {\n try {\n return decodeURIComponent(extended[2].trim().replace(/^\"|\"$/g, ''));\n } catch {\n // Malformed percent-encoding: fall back to the plain parameter.\n }\n }\n const plain = /filename\\s*=\\s*(\"([^\"]*)\"|[^;]*)/i.exec(header);\n const value = (plain?.[2] ?? plain?.[1] ?? '').trim();\n if (!value) return null;\n try {\n return decodeURIComponent(value);\n } catch {\n return value;\n }\n}\n\n/**\n * Triggers a browser download for an in-memory blob. No-op outside a browser.\n *\n * The anchor is attached before clicking (some browsers ignore detached anchors) and the object URL is revoked on the\n * next macrotask (revoking in the same task can cancel the download).\n */\nexport function downloadBlob(blob: Blob, filename: string): void {\n if (typeof document === 'undefined' || typeof URL.createObjectURL !== 'function') return;\n const url = URL.createObjectURL(blob);\n const anchor = document.createElement('a');\n anchor.href = url;\n anchor.download = filename;\n anchor.rel = 'noopener';\n document.body.appendChild(anchor);\n anchor.click();\n anchor.remove();\n setTimeout(() => URL.revokeObjectURL(url), 0);\n}\n\n/** Parses an error response as JSON when possible, else as text, so error normalisation keeps working. */\nconst parseErrorBody = async (response: Response): Promise<unknown> => {\n const text = await response.text();\n if (!text) return undefined;\n try {\n return JSON.parse(text);\n } catch {\n return text;\n }\n};\n\n/**\n * RTK Query `responseHandler` for binary endpoints: a successful response becomes a {@link DddFileResponse}, an error\n * response is parsed as JSON/text like any other error.\n *\n * Blobs are not serializable; keep such endpoints out of the cache (e.g. use a mutation or `keepUnusedDataFor: 0`) or\n * use {@link createDownloadResponseHandler}.\n *\n * @example\n * build.query<DddFileResponse, void>({ query: () => ({ url: '/export', responseHandler: blobResponseHandler }) })\n */\nexport async function blobResponseHandler(response: Response): Promise<DddFileResponse | unknown> {\n if (!response.ok) return parseErrorBody(response);\n return {\n blob: await response.blob(),\n filename: filenameFromContentDisposition(response.headers.get('content-disposition')),\n contentType: response.headers.get('content-type'),\n } satisfies DddFileResponse;\n}\n\n/**\n * Builds an RTK Query `responseHandler` that downloads a successful binary response right away and resolves to a\n * serializable {@link DddDownloadedFile}. Error responses are parsed as JSON/text.\n *\n * @param fallbackFilename used when the response has no `Content-Disposition` file name\n */\nexport function createDownloadResponseHandler(fallbackFilename = 'download') {\n return async (response: Response): Promise<DddDownloadedFile | unknown> => {\n if (!response.ok) return parseErrorBody(response);\n const blob = await response.blob();\n const filename = filenameFromContentDisposition(response.headers.get('content-disposition')) ?? fallbackFilename;\n downloadBlob(blob, filename);\n return { filename, contentType: response.headers.get('content-type'), size: blob.size } satisfies DddDownloadedFile;\n };\n}\n","import type { Api, ApiModules, EndpointDefinitions } from '@reduxjs/toolkit/query';\nimport type { DddBaseQuery } from './baseQuery';\nimport type { DddAuthResponse, DddLoginRequest, DddRefreshRequest } from '../auth/types';\n\n/** Options of {@link createAuthEndpoints}. */\nexport interface DddAuthEndpointsOptions {\n /** e.g. `/api/admin/common/auth/login` */\n loginPath: string;\n /** e.g. `/api/admin/common/auth/refresh` */\n refreshPath: string;\n}\n\n/**\n * Injects `authLogin` and `authRefresh` mutations for the DDD auth endpoints into an existing API.\n * Pure `injectEndpoints`, no React; with an API created by `@reduxjs/toolkit/query/react` the usual hooks\n * (`useAuthLoginMutation`, …) are generated as for any endpoint.\n *\n * The API must use the base query from {@link createDddBaseQuery}.\n *\n * Prefer the endpoints of your generated SDK when it already has them; this is for apps without one.\n */\nexport function createAuthEndpoints<\n Definitions extends EndpointDefinitions,\n ReducerPath extends string,\n TagTypes extends string,\n Enhancers extends keyof ApiModules<any, any, any, any>,\n>(api: Api<DddBaseQuery, Definitions, ReducerPath, TagTypes, Enhancers>, options: DddAuthEndpointsOptions) {\n return api.injectEndpoints({\n endpoints: (build) => ({\n authLogin: build.mutation<DddAuthResponse, DddLoginRequest>({\n query: (body) => ({ url: options.loginPath, method: 'POST', body }),\n }),\n authRefresh: build.mutation<DddAuthResponse, DddRefreshRequest>({\n query: (body) => ({ url: options.refreshPath, method: 'POST', body }),\n }),\n }),\n });\n}\n"],"mappings":";;;;;AAAA;AAAA,EACE;AAAA,OAOK;;;ACaP,IAAM,sBAAsB,MAC1B,OAAO,WAAW,eAAe,OAAO,WAAW,IAAI,gBAAgB,OAAO,SAAS,MAAM,IAAI;AAG5F,SAAS,eAAe,UAA2B,CAAC,GAAkB;AAC3E,QAAM,UAAU,QAAQ,gBAAgB,qBAAqB,KAAK;AAClE,SAAO;AAAA,IACL,OAAO,QAAQ,IAAI,OAAO,KAAK;AAAA,IAC/B,SAAS,QAAQ,IAAI,SAAS,KAAK;AAAA,IACnC,QAAQ,QAAQ,IAAI,QAAQ,KAAK;AAAA,IACjC,cAAc,QAAQ,IAAI,cAAc,KAAK;AAAA,EAC/C;AACF;AAEA,IAAM,cAAc,CAAC,KAAa,KAAa,UAC7C,IAAI,OAAO,OAAO,GAAG,KAAK,GAAG,EAAE,KAAK,GAAG,IACnC,MACA,GAAG,GAAG,GAAG,IAAI,SAAS,GAAG,IAAI,MAAM,GAAG,GAAG,mBAAmB,GAAG,CAAC,IAAI,mBAAmB,KAAK,CAAC;AAK5F,SAAS,iBACd,MACA,OACA,mBAAmB,KACC;AACpB,QAAM,QAAiC,CAAC;AACxC,MAAI,MAAM,MAAO,OAAM,KAAK,CAAC,SAAS,MAAM,CAAC;AAC7C,MAAI,MAAM,QAAS,OAAM,KAAK,CAAC,WAAW,MAAM,CAAC;AACjD,MAAI,MAAM,OAAQ,OAAM,KAAK,CAAC,kBAAkB,gBAAgB,CAAC;AACjE,MAAI,MAAM,aAAc,OAAM,KAAK,CAAC,kBAAkB,GAAG,CAAC;AAC1D,MAAI,MAAM,WAAW,EAAG,QA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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/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 /**\n * With `files`: the JSON envelope, sent in the form field `body` (left out when `undefined`). Without `files` and\n * `formData`: the JSON body of the request (`content-type: application/json`); `undefined` sends no body.\n */\n body?: unknown;\n /** File parts per form field (the `Parameter::FILES` properties of the request DTO): the DDD multipart form. */\n files?: DddMultipartFiles;\n /** A form the caller built, sent as it is (wins over `body` and `files`). */\n formData?: FormData;\n /**\n * Query parameters; `null` / `undefined` values are skipped. Serialized by `fetchOptions.paramsSerializer` when the\n * base query has one, else by the DDD serializer.\n */\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 /** Bytes of the response received so far; `total` is 0 when the server sends no length. */\n onDownloadProgress?: (loaded: number, total: number) => void;\n /**\n * How the response becomes `data` (and an error's `data`): `json` (default; a body that is no JSON stays text),\n * `text`, or `blob` (a download).\n */\n responseType?: 'json' | 'text' | 'blob';\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 request with progress (XMLHttpRequest: `fetch` reports no upload progress) through the same session as\n * every request: Bearer, `headers` / `languageCode` hooks, one shared refresh and one retry. The body is the DDD\n * multipart form (`files`), a form the caller built (`formData`) or JSON (`body` alone); `onDownloadProgress` with\n * `responseType: 'blob'` serves a download.\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/** The body an upload sends and its content type (none for a form: the runtime sets the boundary). */\nfunction buildUploadBody(request: DddUploadRequest): { body: FormData | string | null; contentType?: string } {\n if (request.formData) return { body: request.formData };\n if (request.files) return { body: buildDddFormData(request.body, request.files) };\n if (request.body === undefined) return { body: null };\n return { body: JSON.stringify(request.body), contentType: 'application/json' };\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 ? (fetchOptions?.paramsSerializer ?? 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, onDownloadProgress } = request;\n const responseType = request.responseType ?? 'json';\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 const sentBody = buildUploadBody(request);\n xhr.open(request.method ?? 'POST', url);\n if (responseType === 'blob') xhr.responseType = 'blob';\n if (sentBody.contentType) headers.set('content-type', sentBody.contentType);\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 if (onDownloadProgress) {\n xhr.onprogress = (event) => onDownloadProgress(event.loaded, event.lengthComputable ? event.total : 0);\n }\n xhr.onload = () => {\n let data: unknown;\n if (responseType === 'blob') {\n data = xhr.response;\n } else {\n const text = xhr.responseText;\n if (responseType === 'text') {\n data = text;\n } else {\n try {\n data = text ? JSON.parse(text) : undefined;\n } catch {\n data = text;\n }\n }\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(sentBody.body);\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","/** A binary response decoded by {@link blobResponseHandler}. */\nexport interface DddFileResponse {\n blob: Blob;\n /** File name from `Content-Disposition`, else `null`. */\n filename: string | null;\n /** `Content-Type` of the response, else `null`. */\n contentType: string | null;\n}\n\n/** Serializable summary returned by {@link createDownloadResponseHandler} (safe to keep in the Redux store). */\nexport interface DddDownloadedFile {\n filename: string;\n contentType: string | null;\n size: number;\n}\n\n/**\n * Reads the file name from a `Content-Disposition` header. Prefers RFC 5987 `filename*=UTF-8''…` over `filename=`.\n *\n * @returns the decoded file name, or `null` when the header has none.\n */\nexport function filenameFromContentDisposition(header: string | null | undefined): string | null {\n if (!header) return null;\n const extended = /filename\\*\\s*=\\s*([^']*)'[^']*'([^;]+)/i.exec(header);\n if (extended?.[2]) {\n try {\n return decodeURIComponent(extended[2].trim().replace(/^\"|\"$/g, ''));\n } catch {\n // Malformed percent-encoding: fall back to the plain parameter.\n }\n }\n const plain = /filename\\s*=\\s*(\"([^\"]*)\"|[^;]*)/i.exec(header);\n const value = (plain?.[2] ?? plain?.[1] ?? '').trim();\n if (!value) return null;\n try {\n return decodeURIComponent(value);\n } catch {\n return value;\n }\n}\n\n/**\n * Triggers a browser download for an in-memory blob. No-op outside a browser.\n *\n * The anchor is attached before clicking (some browsers ignore detached anchors) and the object URL is revoked on the\n * next macrotask (revoking in the same task can cancel the download).\n */\nexport function downloadBlob(blob: Blob, filename: string): void {\n if (typeof document === 'undefined' || typeof URL.createObjectURL !== 'function') return;\n const url = URL.createObjectURL(blob);\n const anchor = document.createElement('a');\n anchor.href = url;\n anchor.download = filename;\n anchor.rel = 'noopener';\n document.body.appendChild(anchor);\n anchor.click();\n anchor.remove();\n setTimeout(() => URL.revokeObjectURL(url), 0);\n}\n\n/** Parses an error response as JSON when possible, else as text, so error normalisation keeps working. */\nconst parseErrorBody = async (response: Response): Promise<unknown> => {\n const text = await response.text();\n if (!text) return undefined;\n try {\n return JSON.parse(text);\n } catch {\n return text;\n }\n};\n\n/**\n * RTK Query `responseHandler` for binary endpoints: a successful response becomes a {@link DddFileResponse}, an error\n * response is parsed as JSON/text like any other error.\n *\n * Blobs are not serializable; keep such endpoints out of the cache (e.g. use a mutation or `keepUnusedDataFor: 0`) or\n * use {@link createDownloadResponseHandler}.\n *\n * @example\n * build.query<DddFileResponse, void>({ query: () => ({ url: '/export', responseHandler: blobResponseHandler }) })\n */\nexport async function blobResponseHandler(response: Response): Promise<DddFileResponse | unknown> {\n if (!response.ok) return parseErrorBody(response);\n return {\n blob: await response.blob(),\n filename: filenameFromContentDisposition(response.headers.get('content-disposition')),\n contentType: response.headers.get('content-type'),\n } satisfies DddFileResponse;\n}\n\n/**\n * Builds an RTK Query `responseHandler` that downloads a successful binary response right away and resolves to a\n * serializable {@link DddDownloadedFile}. Error responses are parsed as JSON/text.\n *\n * @param fallbackFilename used when the response has no `Content-Disposition` file name\n */\nexport function createDownloadResponseHandler(fallbackFilename = 'download') {\n return async (response: Response): Promise<DddDownloadedFile | unknown> => {\n if (!response.ok) return parseErrorBody(response);\n const blob = await response.blob();\n const filename = filenameFromContentDisposition(response.headers.get('content-disposition')) ?? fallbackFilename;\n downloadBlob(blob, filename);\n return { filename, contentType: response.headers.get('content-type'), size: blob.size } satisfies DddDownloadedFile;\n };\n}\n","import type { Api, ApiModules, EndpointDefinitions } from '@reduxjs/toolkit/query';\nimport type { DddBaseQuery } from './baseQuery';\nimport type { DddAuthResponse, DddLoginRequest, DddRefreshRequest } from '../auth/types';\n\n/** Options of {@link createAuthEndpoints}. */\nexport interface DddAuthEndpointsOptions {\n /** e.g. `/api/admin/common/auth/login` */\n loginPath: string;\n /** e.g. `/api/admin/common/auth/refresh` */\n refreshPath: string;\n}\n\n/**\n * Injects `authLogin` and `authRefresh` mutations for the DDD auth endpoints into an existing API.\n * Pure `injectEndpoints`, no React; with an API created by `@reduxjs/toolkit/query/react` the usual hooks\n * (`useAuthLoginMutation`, …) are generated as for any endpoint.\n *\n * The API must use the base query from {@link createDddBaseQuery}.\n *\n * Prefer the endpoints of your generated SDK when it already has them; this is for apps without one.\n */\nexport function createAuthEndpoints<\n Definitions extends EndpointDefinitions,\n ReducerPath extends string,\n TagTypes extends string,\n Enhancers extends keyof ApiModules<any, any, any, any>,\n>(api: Api<DddBaseQuery, Definitions, ReducerPath, TagTypes, Enhancers>, options: DddAuthEndpointsOptions) {\n return api.injectEndpoints({\n endpoints: (build) => ({\n authLogin: build.mutation<DddAuthResponse, DddLoginRequest>({\n query: (body) => ({ url: options.loginPath, method: 'POST', body }),\n }),\n authRefresh: build.mutation<DddAuthResponse, DddRefreshRequest>({\n query: (body) => ({ url: options.refreshPath, method: 'POST', body }),\n }),\n }),\n });\n}\n"],"mappings":";;;;;;;;;;;;AAAA;AAAA,EACE;AAAA,OAOK;;;ACaP,IAAM,sBAAsB,MAC1B,OAAO,WAAW,eAAe,OAAO,WAAW,IAAI,gBAAgB,OAAO,SAAS,MAAM,IAAI;AAG5F,SAAS,eAAe,UAA2B,CAAC,GAAkB;AAC3E,QAAM,UAAU,QAAQ,gBAAgB,qBAAqB,KAAK;AAClE,SAAO;AAAA,IACL,OAAO,QAAQ,IAAI,OAAO,KAAK;AAAA,IAC/B,SAAS,QAAQ,IAAI,SAAS,KAAK;AAAA,IACnC,QAAQ,QAAQ,IAAI,QAAQ,KAAK;AAAA,IACjC,cAAc,QAAQ,IAAI,cAAc,KAAK;AAAA,EAC/C;AACF;AAEA,IAAM,cAAc,CAAC,KAAa,KAAa,UAC7C,IAAI,OAAO,OAAO,GAAG,KAAK,GAAG,EAAE,KAAK,GAAG,IACnC,MACA,GAAG,GAAG,GAAG,IAAI,SAAS,GAAG,IAAI,MAAM,GAAG,GAAG,mBAAmB,GAAG,CAAC,IAAI,mBAAmB,KAAK,CAAC;AAK5F,SAAS,iBACd,MACA,OACA,mBAAmB,KACC;AACpB,QAAM,QAAiC,CAAC;AACxC,MAAI,MAAM,MAAO,OAAM,KAAK,CAAC,SAAS,MAAM,CAAC;AAC7C,MAAI,MAAM,QAAS,OAAM,KAAK,CAAC,WAAW,MAAM,CAAC;AACjD,MAAI,MAAM,OAAQ,OAAM,KAAK,CAAC,kBAAkB,gBAAgB,CAAC;AACjE,MAAI,MAAM,aAAc,OAAM,KAAK,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