@mgamadeus/ddd-web 0.3.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/api/baseQuery.ts","../../src/api/debug.ts","../../src/api/refresh.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 { createDddRefresh, type DddRawBaseQuery, type DddRefreshFn } from './refresh';\n\ntype MaybePromise<T> = T | Promise<T>;\n\n/** Result of one refresh attempt: new tokens stored, session ended, session replaced while refreshing, or thrown. */\ntype RefreshOutcome = 'refreshed' | 'failed' | 'superseded' | 'error';\n\n/** What `getTokens` can see: the request's Redux context (no dispatch). */\nexport type DddRequestContext = Pick<BaseQueryApi, 'getState' | 'extra' | 'endpoint' | 'type'>;\n\n/** Context of the `headers` / `languageCode` hooks (RTK's `prepareHeaders` context). */\nexport type DddHeadersContext = Parameters<NonNullable<FetchBaseQueryArgs['prepareHeaders']>>[1];\n\n/** Decides whether a failed request is worth a token refresh and one retry. */\nexport type DddShouldRefresh = (error: FetchBaseQueryError, request: FetchArgs) => boolean;\n\n/** The base query returned by {@link createDddBaseQuery}. */\nexport type DddBaseQuery = BaseQueryFn<string | FetchArgs, unknown, FetchBaseQueryError, {}, FetchBaseQueryMeta>;\n\n/** Options of {@link createDddBaseQuery}. */\nexport interface DddBaseQueryOptions {\n /** API origin, e.g. `https://api.example.com`. Request URLs are relative to it. */\n baseUrl: string;\n /** Current tokens, typically read from the Redux state (`context.getState()`) or a {@link TokenStorage}. */\n getTokens: (context: DddRequestContext) => MaybePromise<Partial<DddTokens> | null | undefined>;\n /** Stores a freshly refreshed token pair (dispatch a Redux action, write storage, …). */\n setTokens: (tokens: DddTokens, api: BaseQueryApi) => MaybePromise<void>;\n /** Called once when the session cannot be recovered (no refresh token, or the refresh was rejected). */\n onLogout: (api: BaseQueryApi) => MaybePromise<void>;\n /** Custom refresh. Default: {@link createDddRefresh} on `refreshPath`. */\n refresh?: DddRefreshFn;\n /** Refresh endpoint for the default refresh, e.g. `/api/admin/common/auth/refresh`. Required without `refresh`. */\n refreshPath?: string;\n /**\n * Adds or changes headers after the Bearer header is set; return value as in RTK's `prepareHeaders`.\n * `context.type` tells reads (`query`) from writes (`mutation`).\n */\n headers?: (headers: Headers, context: DddHeadersContext) => MaybePromise<Headers | void>;\n /**\n * Shortcut for the DDD `languageCode` header. Return e.g. the form's editing language for mutations and the UI\n * language for queries; a falsy value sends no header.\n */\n languageCode?: (context: DddHeadersContext) => string | null | undefined;\n /**\n * Decides whether a failed request triggers a refresh and one retry. Default {@link defaultShouldRefresh}\n * (status 401, auth endpoints excluded).\n *\n * @example\n * // Also refresh on 403, except for 403s that are business refusals:\n * shouldRefresh: (error, request) =>\n * (error.status === 401 || error.status === 403) && !isBusinessRefusal(error) && !isDddAuthRequest(request)\n */\n shouldRefresh?: DddShouldRefresh;\n /** Debug passthrough of page URL flags (`?debug`, `?noCache`, `?xdebug`, `?errorsAsJson`). Default off. */\n debug?: boolean | DddDebugOptions;\n /** Further `fetchBaseQuery` options (`fetchFn`, `timeout`, `credentials`, `paramsSerializer`, …). */\n fetchOptions?: Omit<FetchBaseQueryArgs, 'baseUrl' | 'prepareHeaders'>;\n}\n\n/** URL path of a request argument. */\nexport const getRequestUrl = (request: string | FetchArgs): string =>\n typeof request === 'string' ? request : request.url;\n\n/** True for the DDD auth endpoints (`…/common/auth/…`); they never trigger a refresh, they ARE the recovery. */\nexport const isDddAuthRequest = (request: string | FetchArgs): boolean =>\n getRequestUrl(request).includes('/common/auth/');\n\n/** Default refresh decision: HTTP 401 on anything but an auth endpoint. */\nexport const defaultShouldRefresh: DddShouldRefresh = (error, request) =>\n error.status === 401 && !isDddAuthRequest(request);\n\n/**\n * Query-string serializer that skips `null` / `undefined` values (the generated SDK passes every optional parameter).\n */\nexport const dddParamsSerializer = (params: Record<string, unknown>): string =>\n Object.entries(params)\n .filter(([, value]) => value !== null && value !== undefined)\n .map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(String(value))}`)\n .join('&');\n\nconst toFetchArgs = (args: string | FetchArgs): FetchArgs => (typeof args === 'string' ? { url: args } : args);\n\nconst withBearer = (args: FetchArgs, accessToken: string | null | undefined): FetchArgs => {\n if (!accessToken) return args;\n const headers = new Headers();\n const source = args.headers;\n if (source instanceof Headers) source.forEach((value, key) => headers.set(key, value));\n else if (Array.isArray(source)) source.forEach(([key, value]) => key !== undefined && headers.set(key, value ?? ''));\n else if (source) Object.entries(source).forEach(([key, value]) => value !== undefined && headers.set(key, value));\n if (!headers.has('authorization')) headers.set('authorization', `Bearer ${accessToken}`);\n return { ...args, headers };\n};\n\n/**\n * Creates the RTK Query base query for a DDD backend.\n *\n * - Sends `Authorization: Bearer <accessToken>` from `getTokens()`.\n * - On a refresh-worthy failure (`shouldRefresh`, default 401) runs ONE shared refresh and retries the request exactly\n * once. Concurrent failures share that refresh and its result; a request whose failure predates a refresh that\n * finished meanwhile reuses that refresh's result instead of refreshing again.\n * - No refresh token, or a rejected refresh → `onLogout()` once for that session and the original error is returned.\n * - A refresh whose session was logged out or replaced while it ran is discarded (no `setTokens`, no retry).\n *\n * @example\n * export const baseApi = createApi({\n * baseQuery: createDddBaseQuery({\n * baseUrl: 'https://api.example.com',\n * refreshPath: '/api/admin/common/auth/refresh',\n * getTokens: ({ getState }) => (getState() as RootState).auth,\n * setTokens: (tokens, { dispatch }) => dispatch(authActions.updateTokens(tokens)),\n * onLogout: ({ dispatch }) => dispatch(authActions.logout()),\n * }),\n * endpoints: () => ({}),\n * });\n */\nexport function createDddBaseQuery(options: DddBaseQueryOptions): DddBaseQuery {\n const { getTokens, setTokens, onLogout, headers: headersHook, languageCode, fetchOptions } = options;\n const shouldRefresh = options.shouldRefresh ?? defaultShouldRefresh;\n if (!options.refresh && !options.refreshPath) {\n throw new Error('createDddBaseQuery: pass either `refresh` or `refreshPath`.');\n }\n const refresh = options.refresh ?? createDddRefresh(options.refreshPath as string);\n const debugOptions: DddDebugOptions | null =\n options.debug === true ? {} : options.debug ? options.debug : null;\n\n const fetchQuery = fetchBaseQuery({\n paramsSerializer: dddParamsSerializer,\n ...fetchOptions,\n baseUrl: options.baseUrl,\n prepareHeaders: async (headers, context) => {\n const language = languageCode?.(context);\n if (language) headers.set('languageCode', language);\n if (debugOptions && readDebugFlags(debugOptions).debug) headers.set('x-debug', 'true');\n return (await headersHook?.(headers, context)) ?? headers;\n },\n });\n\n /** One request without auth recovery: debug passthrough + fetch. */\n const rawBaseQuery: DddRawBaseQuery = (args, api, extraOptions) => {\n const finalArgs = debugOptions\n ? applyDebugParams(args, readDebugFlags(debugOptions), debugOptions.xdebugSessionKey)\n : args;\n return fetchQuery(finalArgs, api, extraOptions as {});\n };\n\n /**\n * Refresh coordination. Every finished refresh attempt starts a new session generation and records its outcome; a\n * request remembers the generation it started in. A refresh-worthy failure in the current generation runs (or\n * joins) the one refresh of that generation; a failure from an older generation reuses the recorded outcome, so a\n * late 401 after a failed refresh neither refreshes nor logs out again.\n */\n let generation = 0;\n let lastOutcome: RefreshOutcome | null = null;\n let inflight: Promise<void> | null = null;\n\n const currentAccessToken = async (api: BaseQueryApi): Promise<string | null> =>\n (await getTokens(api))?.accessToken ?? null;\n\n const runRefresh = async (api: BaseQueryApi, extraOptions: unknown): Promise<RefreshOutcome> => {\n const refreshToken = (await getTokens(api))?.refreshToken ?? null;\n const pair = refreshToken ? await refresh({ refreshToken, baseQuery: rawBaseQuery, api, extraOptions }) : null;\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 if (((await getTokens(api))?.refreshToken ?? null) !== refreshToken) 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 return async (args, api, extraOptions) => {\n // A request started during a refresh waits for it and then sends the current token.\n while (inflight) await inflight.catch(() => undefined);\n const startGeneration = generation;\n const request = toFetchArgs(args);\n const result = await rawBaseQuery(withBearer(request, await currentAccessToken(api)), api, extraOptions);\n if (!result.error || !shouldRefresh(result.error, request)) return result;\n if ((await recover(startGeneration, api, extraOptions)) !== 'refreshed') return result;\n return rawBaseQuery(withBearer(request, await currentAccessToken(api)), api, extraOptions);\n };\n}\n","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","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/**\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","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,IA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AAO,EAAE,UAAU,aAAa,SAAS,QAAQ,IAAI,cAAc,GAAG,MAAM,KAAK,KAAK;AAAA,EACxF;AACF;;;ACnFO,SAAS,oBAKd,KAAuE,SAAkC;AACzG,SAAO,IAAI,gBAAgB;AAAA,IACzB,WAAW,CAAC,WAAW;AAAA,MACrB,WAAW,MAAM,SAA2C;AAAA,QAC1D,OAAO,CAAC,UAAU,EAAE,KAAK,QAAQ,WAAW,QAAQ,QAAQ,KAAK;AAAA,MACnE,CAAC;AAAA,MACD,aAAa,MAAM,SAA6C;AAAA,QAC9D,OAAO,CAAC,UAAU,EAAE,KAAK,QAAQ,aAAa,QAAQ,QAAQ,KAAK;AAAA,MACrE,CAAC;AAAA,IACH;AAAA,EACF,CAAC;AACH;","names":[]}
1
+ {"version":3,"sources":["../../src/api/baseQuery.ts","../../src/api/debug.ts","../../src/api/multipart.ts","../../src/api/refresh.ts","../../src/api/tags.ts","../../src/api/errors.ts","../../src/api/download.ts","../../src/api/endpoints.ts"],"sourcesContent":["import {\n fetchBaseQuery,\n type BaseQueryApi,\n type BaseQueryFn,\n type FetchArgs,\n type FetchBaseQueryArgs,\n type FetchBaseQueryError,\n type FetchBaseQueryMeta,\n} from '@reduxjs/toolkit/query';\nimport type { DddTokens } from '../auth/types';\nimport { applyDebugParams, readDebugFlags, type DddDebugOptions } from './debug';\nimport { buildDddFormData, type DddMultipartFiles } from './multipart';\nimport { createDddRefresh, type DddRawBaseQuery, type DddRefreshFn, type DddReloginFn } from './refresh';\n\ntype MaybePromise<T> = T | Promise<T>;\n\n/** Result of one refresh attempt: new tokens stored, session ended, session replaced while refreshing, or thrown. */\ntype RefreshOutcome = 'refreshed' | 'failed' | 'superseded' | 'error';\n\n/** What `getTokens` can see: the request's Redux context (no dispatch). */\nexport type DddRequestContext = Pick<BaseQueryApi, 'getState' | 'extra' | 'endpoint' | 'type'>;\n\n/** Context of the `headers` / `languageCode` hooks (RTK's `prepareHeaders` context). */\nexport type DddHeadersContext = Parameters<NonNullable<FetchBaseQueryArgs['prepareHeaders']>>[1];\n\n/** Decides whether a failed request is worth a token refresh and one retry. */\nexport type DddShouldRefresh = (error: FetchBaseQueryError, request: FetchArgs) => boolean;\n\n/** The base query type of a DDD api (what {@link createAuthEndpoints} and wrappers accept). */\nexport type DddBaseQuery = BaseQueryFn<string | FetchArgs, unknown, FetchBaseQueryError, {}, FetchBaseQueryMeta>;\n\n/** One upload sent by {@link DddUploadingBaseQuery.upload}. */\nexport interface DddUploadRequest {\n /** Path relative to the base URL. */\n url: string;\n /** Default `POST`. */\n method?: string;\n /** JSON envelope, sent in the form field `body`; left out when `undefined`. */\n body?: unknown;\n /** File parts per form field (the `Parameter::FILES` properties of the request DTO). */\n files: DddMultipartFiles;\n /** Query parameters; `null` / `undefined` values are skipped. */\n params?: Record<string, unknown>;\n /** Bytes of the request body sent so far. Called again from 0 when the upload is repeated after a refresh. */\n onProgress?: (loaded: number, total: number) => void;\n /** Aborting cancels the request; the result is then the error of {@link isDddUploadAborted}. */\n signal?: AbortSignal;\n}\n\n/** Result of an upload: the shape an RTK `queryFn` returns. */\nexport type DddUploadResult = { data: unknown; error?: undefined } | { data?: undefined; error: FetchBaseQueryError };\n\n/** The base query returned by {@link createDddBaseQuery}: a {@link DddBaseQuery} that can also upload with progress. */\nexport type DddUploadingBaseQuery = DddBaseQuery & {\n /**\n * Sends a multipart upload with progress (XMLHttpRequest: `fetch` reports no upload progress) through the same\n * session as every request: Bearer, `headers` / `languageCode` hooks, one shared refresh and one retry.\n *\n * @example\n * uploadAttachment: build.mutation<AttachmentResponse, { id: number; file: File; onProgress?: (loaded: number, total: number) => void }>({\n * queryFn: ({ id, file, onProgress }, api, extraOptions) =>\n * dddBaseQuery.upload({ url: `/api/client/items/${id}/attachments`, files: { attachmentFiles: [file] }, onProgress }, api, extraOptions) as\n * Promise<{ data: AttachmentResponse } | { error: FetchBaseQueryError }>,\n * }),\n */\n upload: (request: DddUploadRequest, api: BaseQueryApi, extraOptions?: unknown) => Promise<DddUploadResult>;\n};\n\n/** `error.error` of an upload cancelled through its `signal`. */\nexport const DDD_UPLOAD_ABORTED = 'DDD_UPLOAD_ABORTED';\n\n/** True for the error of an upload that was cancelled through its `signal`. */\nexport const isDddUploadAborted = (error: unknown): boolean =>\n !!error && typeof error === 'object' && (error as { status?: unknown; error?: unknown }).status === 'CUSTOM_ERROR' &&\n (error as { error?: unknown }).error === DDD_UPLOAD_ABORTED;\n\n/** Options of {@link createDddBaseQuery}. */\nexport interface DddBaseQueryOptions {\n /** API origin, e.g. `https://api.example.com`. Request URLs are relative to it. */\n baseUrl: string;\n /** Current tokens, typically read from the Redux state (`context.getState()`) or a {@link TokenStorage}. */\n getTokens: (context: DddRequestContext) => MaybePromise<Partial<DddTokens> | null | undefined>;\n /** Stores a freshly refreshed token pair (dispatch a Redux action, write storage, …). */\n setTokens: (tokens: DddTokens, api: BaseQueryApi) => MaybePromise<void>;\n /** Called once when the session cannot be recovered (no refresh token, or the refresh was rejected). */\n onLogout: (api: BaseQueryApi) => MaybePromise<void>;\n /** Custom refresh. Default: {@link createDddRefresh} on `refreshPath`. */\n refresh?: DddRefreshFn;\n /** Refresh endpoint for the default refresh, e.g. `/api/admin/common/auth/refresh`. Required without `refresh`. */\n refreshPath?: string;\n /**\n * Re-opens the session when the refresh cannot: no refresh token is stored (guest, impersonation or device\n * sessions), or the refresh token was rejected. Return the new tokens, or `null` to end the session (`onLogout`).\n * Without it a refresh-worthy failure without refresh token logs out directly.\n *\n * @example\n * // A guest session is re-opened from its stored credential:\n * relogin: async ({ baseQuery, api, extraOptions }) => {\n * const credential = readGuestCredential();\n * if (!credential) return null;\n * const result = await baseQuery({ url: '/api/public/common/auth/guest', method: 'POST', body: { credential } }, api, extraOptions as {});\n * const data = result.data as { accessToken?: string; refreshToken?: string | null } | undefined;\n * return data?.accessToken ? { accessToken: data.accessToken, refreshToken: data.refreshToken ?? null } : null;\n * },\n */\n relogin?: DddReloginFn;\n /** Creates the request object of an upload. Default `new XMLHttpRequest()`. */\n createUploadRequest?: () => XMLHttpRequest;\n /**\n * Adds or changes headers after the Bearer header is set; return value as in RTK's `prepareHeaders`.\n * `context.type` tells reads (`query`) from writes (`mutation`).\n */\n headers?: (headers: Headers, context: DddHeadersContext) => MaybePromise<Headers | void>;\n /**\n * Shortcut for the DDD `languageCode` header. Return e.g. the form's editing language for mutations and the UI\n * language for queries; a falsy value sends no header.\n */\n languageCode?: (context: DddHeadersContext) => string | null | undefined;\n /**\n * Decides whether a failed request triggers a refresh and one retry. Default {@link defaultShouldRefresh}\n * (status 401, auth endpoints excluded).\n *\n * @example\n * // Also refresh on 403, except for 403s that are business refusals:\n * shouldRefresh: (error, request) =>\n * (error.status === 401 || error.status === 403) && !isBusinessRefusal(error) && !isDddAuthRequest(request)\n */\n shouldRefresh?: DddShouldRefresh;\n /** Debug passthrough of page URL flags (`?debug`, `?noCache`, `?xdebug`, `?errorsAsJson`). Default off. */\n debug?: boolean | DddDebugOptions;\n /** Further `fetchBaseQuery` options (`fetchFn`, `timeout`, `credentials`, `paramsSerializer`, …). */\n fetchOptions?: Omit<FetchBaseQueryArgs, 'baseUrl' | 'prepareHeaders'>;\n}\n\n/** URL path of a request argument. */\nexport const getRequestUrl = (request: string | FetchArgs): string =>\n typeof request === 'string' ? request : request.url;\n\n/** True for the DDD auth endpoints (`…/common/auth/…`); they never trigger a refresh, they ARE the recovery. */\nexport const isDddAuthRequest = (request: string | FetchArgs): boolean =>\n getRequestUrl(request).includes('/common/auth/');\n\n/** Default refresh decision: HTTP 401 on anything but an auth endpoint. */\nexport const defaultShouldRefresh: DddShouldRefresh = (error, request) =>\n error.status === 401 && !isDddAuthRequest(request);\n\n/**\n * Query-string serializer that skips `null` / `undefined` values (the generated SDK passes every optional parameter).\n */\nexport const dddParamsSerializer = (params: Record<string, unknown>): string =>\n Object.entries(params)\n .filter(([, value]) => value !== null && value !== undefined)\n .map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(String(value))}`)\n .join('&');\n\nconst toFetchArgs = (args: string | FetchArgs): FetchArgs => (typeof args === 'string' ? { url: args } : args);\n\nconst withBearer = (args: FetchArgs, accessToken: string | null | undefined): FetchArgs => {\n if (!accessToken) return args;\n const headers = new Headers();\n const source = args.headers;\n if (source instanceof Headers) source.forEach((value, key) => headers.set(key, value));\n else if (Array.isArray(source)) source.forEach(([key, value]) => key !== undefined && headers.set(key, value ?? ''));\n else if (source) Object.entries(source).forEach(([key, value]) => value !== undefined && headers.set(key, value));\n if (!headers.has('authorization')) headers.set('authorization', `Bearer ${accessToken}`);\n return { ...args, headers };\n};\n\n/**\n * Creates the RTK Query base query for a DDD backend.\n *\n * - Sends `Authorization: Bearer <accessToken>` from `getTokens()`.\n * - On a refresh-worthy failure (`shouldRefresh`, default 401) runs ONE shared refresh and retries the request exactly\n * once. Concurrent failures share that refresh and its result; a request whose failure predates a refresh that\n * finished meanwhile reuses that refresh's result instead of refreshing again.\n * - No refresh token, or a rejected refresh → `relogin()` when given; without it, or when it returns `null`,\n * `onLogout()` once for that session and the original error is returned.\n * - A refresh whose session was logged out or replaced while it ran is discarded (no `setTokens`, no retry).\n *\n * @example\n * export const baseApi = createApi({\n * baseQuery: createDddBaseQuery({\n * baseUrl: 'https://api.example.com',\n * refreshPath: '/api/admin/common/auth/refresh',\n * getTokens: ({ getState }) => (getState() as RootState).auth,\n * setTokens: (tokens, { dispatch }) => dispatch(authActions.updateTokens(tokens)),\n * onLogout: ({ dispatch }) => dispatch(authActions.logout()),\n * }),\n * endpoints: () => ({}),\n * });\n */\nexport function createDddBaseQuery(options: DddBaseQueryOptions): DddUploadingBaseQuery {\n const { getTokens, setTokens, onLogout, headers: headersHook, languageCode, fetchOptions, relogin } = options;\n const shouldRefresh = options.shouldRefresh ?? defaultShouldRefresh;\n if (!options.refresh && !options.refreshPath) {\n throw new Error('createDddBaseQuery: pass either `refresh` or `refreshPath`.');\n }\n const refresh = options.refresh ?? createDddRefresh(options.refreshPath as string);\n const debugOptions: DddDebugOptions | null =\n options.debug === true ? {} : options.debug ? options.debug : null;\n\n const fetchQuery = fetchBaseQuery({\n paramsSerializer: dddParamsSerializer,\n ...fetchOptions,\n baseUrl: options.baseUrl,\n prepareHeaders: async (headers, context) => {\n const language = languageCode?.(context);\n if (language) headers.set('languageCode', language);\n if (debugOptions && readDebugFlags(debugOptions).debug) headers.set('x-debug', 'true');\n return (await headersHook?.(headers, context)) ?? headers;\n },\n });\n\n /** One request without auth recovery: debug passthrough + fetch. */\n const rawBaseQuery: DddRawBaseQuery = (args, api, extraOptions) => {\n const finalArgs = debugOptions\n ? applyDebugParams(args, readDebugFlags(debugOptions), debugOptions.xdebugSessionKey)\n : args;\n return fetchQuery(finalArgs, api, extraOptions as {});\n };\n\n /**\n * Refresh coordination. Every finished refresh attempt starts a new session generation and records its outcome; a\n * request remembers the generation it started in. A refresh-worthy failure in the current generation runs (or\n * joins) the one refresh of that generation; a failure from an older generation reuses the recorded outcome, so a\n * late 401 after a failed refresh neither refreshes nor logs out again.\n */\n let generation = 0;\n let lastOutcome: RefreshOutcome | null = null;\n let inflight: Promise<void> | null = null;\n\n const currentAccessToken = async (api: BaseQueryApi): Promise<string | null> =>\n (await getTokens(api))?.accessToken ?? null;\n\n const runRefresh = async (api: BaseQueryApi, extraOptions: unknown): Promise<RefreshOutcome> => {\n const before = await getTokens(api);\n const refreshToken = before?.refreshToken ?? null;\n const accessTokenBefore = before?.accessToken ?? null;\n let pair = refreshToken ? await refresh({ refreshToken, baseQuery: rawBaseQuery, api, extraOptions }) : null;\n if (!pair?.accessToken && relogin) {\n pair = await relogin({\n reason: refreshToken ? 'refresh-rejected' : 'no-refresh-token',\n baseQuery: rawBaseQuery,\n api,\n extraOptions,\n });\n }\n // The session may have ended (logout) or changed (another login) while the refresh ran: its result belongs to\n // a session that is gone and must not be stored.\n const after = await getTokens(api);\n if ((after?.refreshToken ?? null) !== refreshToken) return 'superseded';\n // A session without refresh token is identified by its access token.\n if (refreshToken === null && (after?.accessToken ?? null) !== accessTokenBefore) return 'superseded';\n if (!pair?.accessToken) {\n await onLogout(api);\n return 'failed';\n }\n await setTokens({ accessToken: pair.accessToken, refreshToken: pair.refreshToken ?? refreshToken }, api);\n return 'refreshed';\n };\n\n /** Runs or joins the refresh of `startGeneration`; returns the outcome that applies to a request of that generation. */\n const recover = async (startGeneration: number, api: BaseQueryApi, extraOptions: unknown): Promise<RefreshOutcome | null> => {\n if (generation === startGeneration && !inflight) {\n inflight = (async () => {\n try {\n lastOutcome = await runRefresh(api, extraOptions);\n } catch (error) {\n lastOutcome = 'error';\n throw error;\n } finally {\n generation++;\n inflight = null;\n }\n })();\n }\n if (inflight) await inflight;\n return lastOutcome;\n };\n\n const baseQuery: DddBaseQuery = async (args, api, extraOptions) => {\n // A request started during a refresh waits for it and then sends the current token.\n while (inflight) await inflight.catch(() => undefined);\n const startGeneration = generation;\n const request = toFetchArgs(args);\n const result = await rawBaseQuery(withBearer(request, await currentAccessToken(api)), api, extraOptions);\n if (!result.error || !shouldRefresh(result.error, request)) return result;\n if ((await recover(startGeneration, api, extraOptions)) !== 'refreshed') return result;\n return rawBaseQuery(withBearer(request, await currentAccessToken(api)), api, extraOptions);\n };\n\n /** Headers of an upload: Bearer, then the same hooks as a fetch request. No content type: the runtime sets it. */\n const uploadHeaders = async (request: DddUploadRequest, api: BaseQueryApi, extraOptions: unknown): Promise<Headers> => {\n const headers = new Headers();\n const accessToken = await currentAccessToken(api);\n if (accessToken) headers.set('authorization', `Bearer ${accessToken}`);\n const context = {\n getState: api.getState,\n extra: api.extra,\n endpoint: api.endpoint,\n type: api.type,\n forced: api.forced,\n arg: { url: request.url, method: request.method ?? 'POST' },\n extraOptions,\n } as DddHeadersContext;\n const language = languageCode?.(context);\n if (language) headers.set('languageCode', language);\n if (debugOptions && readDebugFlags(debugOptions).debug) headers.set('x-debug', 'true');\n return (await headersHook?.(headers, context)) ?? headers;\n };\n\n const sendUpload = async (request: DddUploadRequest, api: BaseQueryApi, extraOptions: unknown): Promise<DddUploadResult> => {\n const headers = await uploadHeaders(request, api, extraOptions);\n const query = request.params ? dddParamsSerializer(request.params) : '';\n const url = `${options.baseUrl.replace(/\\/+$/, '')}/${request.url.replace(/^\\/+/, '')}${query ? `${request.url.includes('?') ? '&' : '?'}${query}` : ''}`;\n return new Promise<DddUploadResult>((resolve) => {\n const { signal, onProgress } = request;\n const aborted: DddUploadResult = { error: { status: 'CUSTOM_ERROR', error: DDD_UPLOAD_ABORTED } };\n if (signal?.aborted) return resolve(aborted);\n const xhr = options.createUploadRequest ? options.createUploadRequest() : new XMLHttpRequest();\n const onAbort = (): void => xhr.abort();\n signal?.addEventListener('abort', onAbort, { once: true });\n const finish = (result: DddUploadResult): void => {\n signal?.removeEventListener('abort', onAbort);\n resolve(result);\n };\n xhr.open(request.method ?? 'POST', url);\n headers.forEach((value, name) => xhr.setRequestHeader(name, value));\n if (onProgress && xhr.upload) {\n xhr.upload.onprogress = (event) => {\n if (event.lengthComputable) onProgress(event.loaded, event.total);\n };\n }\n xhr.onload = () => {\n const text = xhr.responseText;\n let data: unknown;\n try {\n data = text ? JSON.parse(text) : undefined;\n } catch {\n data = text;\n }\n if (xhr.status >= 200 && xhr.status < 300) finish({ data: data ?? null });\n else finish({ error: { status: xhr.status, data } });\n };\n xhr.onerror = () => finish({ error: { status: 'FETCH_ERROR', error: 'The upload did not reach the server.' } });\n xhr.onabort = () => finish(aborted);\n xhr.send(buildDddFormData(request.body, request.files));\n });\n };\n\n const upload: DddUploadingBaseQuery['upload'] = async (request, api, extraOptions) => {\n while (inflight) await inflight.catch(() => undefined);\n const startGeneration = generation;\n const result = await sendUpload(request, api, extraOptions);\n if (!result.error || !shouldRefresh(result.error, { url: request.url, method: request.method ?? 'POST' })) return result;\n if ((await recover(startGeneration, api, extraOptions)) !== 'refreshed') return result;\n return sendUpload(request, api, extraOptions);\n };\n\n return Object.assign(baseQuery, { upload });\n}\n","import type { FetchArgs } from '@reduxjs/toolkit/query';\n\n/**\n * Debug passthrough: flags present in the page URL (`?debug`, `?noCache`, `?xdebug`, `?errorsAsJson`) are forwarded to\n * every API request as the query parameters a DDD backend understands.\n */\nexport interface DddDebugOptions {\n /** Where the flags come from. Default: `window.location.search` (nothing outside a browser). */\n searchParams?: () => URLSearchParams | null | undefined;\n /** Value of `XDEBUG_SESSION` when `?xdebug` is set. Default `1`. */\n xdebugSessionKey?: string;\n}\n\n/** The debug flags active for one request. */\nexport interface DddDebugFlags {\n debug: boolean;\n noCache: boolean;\n xdebug: boolean;\n errorsAsJson: boolean;\n}\n\nconst defaultSearchParams = (): URLSearchParams | null =>\n typeof window !== 'undefined' && window.location ? new URLSearchParams(window.location.search) : null;\n\n/** Reads the active debug flags. */\nexport function readDebugFlags(options: DddDebugOptions = {}): DddDebugFlags {\n const params = (options.searchParams ?? defaultSearchParams)() ?? null;\n return {\n debug: params?.has('debug') ?? false,\n noCache: params?.has('noCache') ?? false,\n xdebug: params?.has('xdebug') ?? false,\n errorsAsJson: params?.has('errorsAsJson') ?? false,\n };\n}\n\nconst appendToUrl = (url: string, key: string, value: string): string =>\n new RegExp(`[?&]${key}=`, 'i').test(url)\n ? url\n : `${url}${url.includes('?') ? '&' : '?'}${encodeURIComponent(key)}=${encodeURIComponent(value)}`;\n\n/**\n * Adds the query parameters for the active debug flags to a request, never overwriting a parameter the caller set.\n */\nexport function applyDebugParams(\n args: string | FetchArgs,\n flags: DddDebugFlags,\n xdebugSessionKey = '1',\n): string | FetchArgs {\n const extra: Array<[string, string]> = [];\n if (flags.debug) extra.push(['debug', 'true']);\n if (flags.noCache) extra.push(['noCache', 'true']);\n if (flags.xdebug) extra.push(['XDEBUG_SESSION', xdebugSessionKey]);\n if (flags.errorsAsJson) extra.push(['errors_as_json', '1']);\n if (extra.length === 0) return args;\n\n if (typeof args === 'string') {\n return extra.reduce((url, [key, value]) => appendToUrl(url, key, value), args);\n }\n const params: Record<string, unknown> = { ...(args.params ?? {}) };\n for (const [key, value] of extra) {\n if (params[key] === undefined && !new RegExp(`[?&]${key}=`, 'i').test(args.url)) params[key] = value;\n }\n return { ...args, params };\n}\n","/**\n * One file part: a `File` / `Blob` in a browser, or React Native's `{ uri, name, type }` file reference.\n */\nexport type DddFilePart = Blob | { uri: string; name: string; type: string };\n\n/** File parts per form field of a DDD request DTO (its `Parameter::FILES` properties). */\nexport type DddMultipartFiles<Field extends string = string> = Partial<\n Record<Field, readonly DddFilePart[] | DddFilePart | null | undefined>\n>;\n\n/** Form field a DDD backend reads the JSON envelope of a multipart request from. */\nexport const DDD_MULTIPART_BODY_FIELD = 'body';\n\nconst partsOf = (value: readonly DddFilePart[] | DddFilePart | null | undefined): readonly DddFilePart[] => {\n if (value === null || value === undefined) return [];\n return Array.isArray(value) ? (value as readonly DddFilePart[]) : [value as DddFilePart];\n};\n\n/** True when at least one file part is present. */\nexport function hasDddMultipartFiles(files: DddMultipartFiles | null | undefined): boolean {\n return !!files && Object.values(files).some((value) => partsOf(value).length > 0);\n}\n\n/**\n * The `multipart/form-data` body of a DDD request: the JSON envelope in the form field `body` (left out when\n * `body` is `undefined`) and every file as a part named `<field>[]`. No `Content-Type` header must be set for it: the\n * runtime adds the multipart boundary itself.\n */\nexport function buildDddFormData(body: unknown, files: DddMultipartFiles | null | undefined): FormData {\n const formData = new FormData();\n if (body !== undefined) formData.append(DDD_MULTIPART_BODY_FIELD, JSON.stringify(body));\n for (const [field, value] of Object.entries(files ?? {})) {\n for (const part of partsOf(value)) {\n const name = typeof (part as { name?: unknown }).name === 'string' ? (part as { name: string }).name : '';\n // A React Native file reference is appended as it is; a Blob without a name gets the field name.\n if (typeof Blob !== 'undefined' && part instanceof Blob) formData.append(`${field}[]`, part, name || field);\n else formData.append(`${field}[]`, part as unknown as Blob);\n }\n }\n return formData;\n}\n\n/**\n * Request body of an endpoint that accepts JSON and file parts: `body` itself while no file is given (a plain JSON\n * request), else the multipart form of {@link buildDddFormData}. Generated endpoints of operations with a\n * `multipart/form-data` request body call it with their `multipartFiles` argument.\n */\nexport function buildDddMultipartBody<Body>(body: Body, files: DddMultipartFiles | null | undefined): Body | FormData {\n return hasDddMultipartFiles(files) ? buildDddFormData(body, files) : body;\n}\n","import type { BaseQueryApi, BaseQueryFn, FetchArgs, FetchBaseQueryError, FetchBaseQueryMeta } from '@reduxjs/toolkit/query';\nimport type { DddAuthResponse, DddTokens } from '../auth/types';\n\n/** The raw (non-refreshing) base query handed to a refresh function. */\nexport type DddRawBaseQuery = BaseQueryFn<string | FetchArgs, unknown, FetchBaseQueryError, {}, FetchBaseQueryMeta>;\n\n/** Everything a refresh function needs. */\nexport interface DddRefreshContext {\n /** The refresh token currently stored. */\n refreshToken: string;\n /** The underlying fetch base query (no auth retry, Bearer of the current access token still applied). */\n baseQuery: DddRawBaseQuery;\n api: BaseQueryApi;\n extraOptions: unknown;\n}\n\n/**\n * Exchanges a refresh token for a new token pair.\n *\n * @returns the new pair, or `null` when the refresh token was rejected (the base query then logs out).\n * A missing `refreshToken` in the result keeps the stored one.\n */\nexport type DddRefreshFn = (context: DddRefreshContext) => Promise<DddTokens | null>;\n\n/** Everything a re-login function needs. */\nexport interface DddReloginContext {\n /** Why the refresh could not recover the session. */\n reason: 'no-refresh-token' | 'refresh-rejected';\n /** The underlying fetch base query (no auth retry, Bearer of the current access token still applied). */\n baseQuery: DddRawBaseQuery;\n api: BaseQueryApi;\n extraOptions: unknown;\n}\n\n/**\n * Re-opens a session without a usable refresh token (guest credential, device id, impersonation through another\n * session, …).\n *\n * @returns the new tokens (`refreshToken: null` for a session that has none), or `null` to end the session.\n */\nexport type DddReloginFn = (context: DddReloginContext) => Promise<DddTokens | null>;\n\n/**\n * The default {@link DddRefreshFn}: `POST <path>` with `{ refreshToken }`, expecting the DDD `AuthPostResponseDto`\n * `{ accessToken, refreshToken }`. DDD refresh tokens are stateless and re-issued with a renewed lifetime.\n *\n * @param path refresh endpoint relative to the base URL, e.g. `/api/admin/common/auth/refresh`\n */\nexport function createDddRefresh(path: string): DddRefreshFn {\n return async ({ refreshToken, baseQuery, api, extraOptions }) => {\n const result = await baseQuery({ url: path, method: 'POST', body: { refreshToken } }, api, extraOptions as {});\n const payload = result.data as DddAuthResponse | undefined;\n if (result.error || !payload?.accessToken) return null;\n return { accessToken: payload.accessToken, refreshToken: payload.refreshToken ?? refreshToken };\n };\n}\n","/** The tags of `Extra` that differ from a tag of `Generated` only by case. */\ntype DddTagCaseConflict<Extra extends string, Generated extends string> = Extra extends Generated\n ? never\n : Lowercase<Extra> extends Lowercase<Generated>\n ? Extra\n : never;\n\ntype DddTagCheck<Generated extends readonly string[], Extra extends readonly string[]> = [\n DddTagCaseConflict<Extra[number], Generated[number]>,\n] extends [never]\n ? unknown\n : { 'tag differs from a generated tag only by case': DddTagCaseConflict<Extra[number], Generated[number]> };\n\n/**\n * The `tagTypes` of a base api: the generated tag lists (`<stem>TagTypes` of the `<stem>Tags.ts` files) plus the\n * app's own tags. With this list every `providesTags` / `invalidatesTags` of a hand-written endpoint and every\n * `api.util.invalidateTags()` is checked against the generated names, so a mistyped tag does not compile. An own tag\n * that differs from a generated one only by case (`ProspectActivities` next to the generated `Prospectactivities`)\n * is rejected here: it would be a second tag that no generated endpoint provides.\n *\n * @example\n * export const baseApi = createApi({\n * baseQuery,\n * tagTypes: mergeDddTagTypes([...adminApiTagTypes, ...clientApiTagTypes], ['Session']),\n * endpoints: () => ({}),\n * });\n */\nexport function mergeDddTagTypes<const Generated extends readonly string[], const Extra extends readonly string[] = readonly []>(\n generated: Generated,\n extra?: Extra & DddTagCheck<Generated, Extra>,\n): (Generated[number] | Extra[number])[] {\n return [...new Set<string>([...generated, ...(extra ?? [])])] as (Generated[number] | Extra[number])[];\n}\n","import type { DddErrorBody, DddExceptionDetail } from '../contract/errors';\n\n/** A DDD API error in one predictable shape, whatever produced it (RTK Query, a thrown Error, a raw body). */\nexport interface DddNormalizedError {\n /**\n * HTTP status, or RTK Query's string status for non-HTTP failures (`FETCH_ERROR`, `TIMEOUT_ERROR`,\n * `CUSTOM_ERROR`); a `PARSING_ERROR` reports the original HTTP status. `null` when unknown.\n */\n status: number | string | null;\n /** Human-readable message: the backend's `error` key first, then a text body, then generic fallbacks. */\n message: string;\n /** The backend's `validationErrors` exactly as received (present on validation 400s), else `null`. */\n validationErrors: unknown;\n /** `exceptionDetails.elements` of the backend body; empty when absent. */\n details: DddExceptionDetail[];\n /** The raw response body (parsed JSON, text, or `undefined`). */\n body: unknown;\n}\n\n/** Message used when an error carries no message at all. */\nexport const DEFAULT_ERROR_MESSAGE = 'Request failed';\n\n/**\n * Messages for failures that carry no usable backend message. Pass your own (e.g. translated) texts as the third\n * argument of {@link normalizeDddError} / {@link getErrorMessage}.\n */\nexport interface DddErrorMessages {\n /** A response that is not JSON (an HTML error page, a PHP fatal) with an HTTP status ≥ 500. */\n serverError: (status: number) => string;\n /** A response that is not JSON with an HTTP status < 500. */\n httpError: (status: number) => string;\n /** The request never reached the server or got no response (`FETCH_ERROR`). */\n networkError: string;\n /** The request timed out (`TIMEOUT_ERROR`). */\n timeoutError: string;\n}\n\n/** The default {@link DddErrorMessages}. */\nexport const DEFAULT_ERROR_MESSAGES: DddErrorMessages = {\n serverError: (status) => `Server error (HTTP ${status})`,\n httpError: (status) => `Request failed (HTTP ${status})`,\n networkError: 'The server could not be reached',\n timeoutError: 'The request timed out',\n};\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n value !== null && typeof value === 'object' && !Array.isArray(value);\n\nconst nonEmptyString = (value: unknown): string | null =>\n typeof value === 'string' && value.trim() !== '' ? value : null;\n\n/** Unwraps the places a response body can sit: RTK `data`, an Error's `responseBody`, or the value itself. */\nconst extractBody = (error: Record<string, unknown>): unknown => {\n if ('data' in error) return error.data;\n if ('responseBody' in error) return error.responseBody;\n if ('error' in error || 'validationErrors' in error || 'exceptionDetails' in error) return error;\n return undefined;\n};\n\nconst extractStatus = (error: Record<string, unknown>): number | string | null => {\n if (error.status === 'PARSING_ERROR' && typeof error.originalStatus === 'number') return error.originalStatus;\n if (typeof error.status === 'number' || typeof error.status === 'string') return error.status;\n if (typeof error.statusCode === 'number') return error.statusCode;\n return null;\n};\n\n/**\n * The message of an RTK Query failure that is not a DDD response: an unparsable body (`PARSING_ERROR`), no response\n * (`FETCH_ERROR`), a timeout (`TIMEOUT_ERROR`); `null` for everything else.\n */\nconst transportFailureMessage = (\n error: Record<string, unknown>,\n texts: DddErrorMessages,\n fallbackMessage: string,\n): string | null => {\n switch (error.status) {\n case 'PARSING_ERROR': {\n const status = typeof error.originalStatus === 'number' ? error.originalStatus : null;\n if (status === null) return fallbackMessage;\n return status >= 500 ? texts.serverError(status) : texts.httpError(status);\n }\n case 'FETCH_ERROR':\n return texts.networkError;\n case 'TIMEOUT_ERROR':\n return texts.timeoutError;\n default:\n return null;\n }\n};\n\n/**\n * Normalises any API error into {@link DddNormalizedError}.\n *\n * Understands RTK Query's `FetchBaseQueryError` (`{ status, data }`, `{ status: 'FETCH_ERROR', error }`, …),\n * `SerializedError` / `Error` (`message`), errors carrying a parsed `responseBody`, and a bare DDD error body.\n * DDD error bodies put the message under `error` (not `message`).\n *\n * A response the client could not parse (`PARSING_ERROR`: an HTML error page, a PHP fatal, a proxy's 502) is an HTTP\n * error: `status` is the HTTP status and the message is {@link DddErrorMessages.serverError} /\n * {@link DddErrorMessages.httpError} — never the parser's `SyntaxError` text and never the raw body, which may show\n * internals (the body stays available in `body`). `FETCH_ERROR` and `TIMEOUT_ERROR` get\n * {@link DddErrorMessages.networkError} / {@link DddErrorMessages.timeoutError} instead of the browser's text.\n *\n * @param error whatever a request rejected with\n * @param fallbackMessage message when nothing usable is found\n * @param messages texts for failures without a backend message (default {@link DEFAULT_ERROR_MESSAGES})\n */\nexport function normalizeDddError(\n error: unknown,\n fallbackMessage: string = DEFAULT_ERROR_MESSAGE,\n messages: Partial<DddErrorMessages> = {},\n): DddNormalizedError {\n const texts: DddErrorMessages = { ...DEFAULT_ERROR_MESSAGES, ...messages };\n if (!isRecord(error)) {\n return {\n status: null,\n message: nonEmptyString(error) ?? fallbackMessage,\n validationErrors: null,\n details: [],\n body: undefined,\n };\n }\n\n const body = extractBody(error);\n const failure = transportFailureMessage(error, texts, fallbackMessage);\n if (failure !== null) {\n return { status: extractStatus(error), message: failure, validationErrors: null, details: [], body };\n }\n const dddBody: DddErrorBody | null = isRecord(body) ? (body as DddErrorBody) : null;\n const bodyRecord: Record<string, unknown> | null = isRecord(body) ? body : null;\n\n const message =\n nonEmptyString(dddBody?.error) ??\n nonEmptyString(bodyRecord?.message) ??\n // RTK's non-HTTP errors carry the reason in `error` (e.g. \"TypeError: Failed to fetch\").\n (body === undefined || typeof body === 'string' ? nonEmptyString(error.error) : null) ??\n // A non-JSON error body (e.g. a download endpoint answering with plain text) is the message itself.\n nonEmptyString(body)?.trim() ??\n nonEmptyString(error.message) ??\n fallbackMessage;\n\n return {\n status: extractStatus(error),\n message,\n validationErrors: dddBody?.validationErrors ?? null,\n details: dddBody?.exceptionDetails?.elements ?? [],\n body,\n };\n}\n\n/**\n * The message to show for an API error (`normalizeDddError(error).message`).\n *\n * @param error whatever a request rejected with\n * @param fallbackMessage message when nothing usable is found\n * @param messages texts for failures without a backend message\n */\nexport function getErrorMessage(\n error: unknown,\n fallbackMessage: string = DEFAULT_ERROR_MESSAGE,\n messages: Partial<DddErrorMessages> = {},\n): string {\n return normalizeDddError(error, fallbackMessage, messages).message;\n}\n\n/** HTTP status of an API error (also of an unparsable response), or `null` for non-HTTP failures. */\nexport function getErrorStatus(error: unknown): number | null {\n const status = normalizeDddError(error).status;\n return typeof status === 'number' ? status : null;\n}\n","/** A binary response decoded by {@link blobResponseHandler}. */\nexport interface DddFileResponse {\n blob: Blob;\n /** File name from `Content-Disposition`, else `null`. */\n filename: string | null;\n /** `Content-Type` of the response, else `null`. */\n contentType: string | null;\n}\n\n/** Serializable summary returned by {@link createDownloadResponseHandler} (safe to keep in the Redux store). */\nexport interface DddDownloadedFile {\n filename: string;\n contentType: string | null;\n size: number;\n}\n\n/**\n * Reads the file name from a `Content-Disposition` header. Prefers RFC 5987 `filename*=UTF-8''…` over `filename=`.\n *\n * @returns the decoded file name, or `null` when the header has none.\n */\nexport function filenameFromContentDisposition(header: string | null | undefined): string | null {\n if (!header) return null;\n const extended = /filename\\*\\s*=\\s*([^']*)'[^']*'([^;]+)/i.exec(header);\n if (extended?.[2]) {\n try {\n return decodeURIComponent(extended[2].trim().replace(/^\"|\"$/g, ''));\n } catch {\n // Malformed percent-encoding: fall back to the plain parameter.\n }\n }\n const plain = /filename\\s*=\\s*(\"([^\"]*)\"|[^;]*)/i.exec(header);\n const value = (plain?.[2] ?? plain?.[1] ?? '').trim();\n if (!value) return null;\n try {\n return decodeURIComponent(value);\n } catch {\n return value;\n }\n}\n\n/**\n * Triggers a browser download for an in-memory blob. No-op outside a browser.\n *\n * The anchor is attached before clicking (some browsers ignore detached anchors) and the object URL is revoked on the\n * next macrotask (revoking in the same task can cancel the download).\n */\nexport function downloadBlob(blob: Blob, filename: string): void {\n if (typeof document === 'undefined' || typeof URL.createObjectURL !== 'function') return;\n const url = URL.createObjectURL(blob);\n const anchor = document.createElement('a');\n anchor.href = url;\n anchor.download = filename;\n anchor.rel = 'noopener';\n document.body.appendChild(anchor);\n anchor.click();\n anchor.remove();\n setTimeout(() => URL.revokeObjectURL(url), 0);\n}\n\n/** Parses an error response as JSON when possible, else as text, so error normalisation keeps working. */\nconst parseErrorBody = async (response: Response): Promise<unknown> => {\n const text = await response.text();\n if (!text) return undefined;\n try {\n return JSON.parse(text);\n } catch {\n return text;\n }\n};\n\n/**\n * RTK Query `responseHandler` for binary endpoints: a successful response becomes a {@link DddFileResponse}, an error\n * response is parsed as JSON/text like any other error.\n *\n * Blobs are not serializable; keep such endpoints out of the cache (e.g. use a mutation or `keepUnusedDataFor: 0`) or\n * use {@link createDownloadResponseHandler}.\n *\n * @example\n * build.query<DddFileResponse, void>({ query: () => ({ url: '/export', responseHandler: blobResponseHandler }) })\n */\nexport async function blobResponseHandler(response: Response): Promise<DddFileResponse | unknown> {\n if (!response.ok) return parseErrorBody(response);\n return {\n blob: await response.blob(),\n filename: filenameFromContentDisposition(response.headers.get('content-disposition')),\n contentType: response.headers.get('content-type'),\n } satisfies DddFileResponse;\n}\n\n/**\n * Builds an RTK Query `responseHandler` that downloads a successful binary response right away and resolves to a\n * serializable {@link DddDownloadedFile}. Error responses are parsed as JSON/text.\n *\n * @param fallbackFilename used when the response has no `Content-Disposition` file name\n */\nexport function createDownloadResponseHandler(fallbackFilename = 'download') {\n return async (response: Response): Promise<DddDownloadedFile | unknown> => {\n if (!response.ok) return parseErrorBody(response);\n const blob = await response.blob();\n const filename = filenameFromContentDisposition(response.headers.get('content-disposition')) ?? fallbackFilename;\n downloadBlob(blob, filename);\n return { filename, contentType: response.headers.get('content-type'), size: blob.size } satisfies DddDownloadedFile;\n };\n}\n","import type { Api, ApiModules, EndpointDefinitions } from '@reduxjs/toolkit/query';\nimport type { DddBaseQuery } from './baseQuery';\nimport type { DddAuthResponse, DddLoginRequest, DddRefreshRequest } from '../auth/types';\n\n/** Options of {@link createAuthEndpoints}. */\nexport interface DddAuthEndpointsOptions {\n /** e.g. `/api/admin/common/auth/login` */\n loginPath: string;\n /** e.g. `/api/admin/common/auth/refresh` */\n refreshPath: string;\n}\n\n/**\n * Injects `authLogin` and `authRefresh` mutations for the DDD auth endpoints into an existing API.\n * Pure `injectEndpoints`, no React; with an API created by `@reduxjs/toolkit/query/react` the usual hooks\n * (`useAuthLoginMutation`, …) are generated as for any endpoint.\n *\n * The API must use the base query from {@link createDddBaseQuery}.\n *\n * Prefer the endpoints of your generated SDK when it already has them; this is for apps without one.\n */\nexport function createAuthEndpoints<\n Definitions extends EndpointDefinitions,\n ReducerPath extends string,\n TagTypes extends string,\n Enhancers extends keyof ApiModules<any, any, any, any>,\n>(api: Api<DddBaseQuery, Definitions, ReducerPath, TagTypes, Enhancers>, options: DddAuthEndpointsOptions) {\n return api.injectEndpoints({\n endpoints: (build) => ({\n authLogin: build.mutation<DddAuthResponse, DddLoginRequest>({\n query: (body) => ({ url: options.loginPath, method: 'POST', body }),\n }),\n authRefresh: build.mutation<DddAuthResponse, DddRefreshRequest>({\n query: (body) => ({ url: options.refreshPath, method: 'POST', body }),\n }),\n }),\n });\n}\n"],"mappings":";AAAA;AAAA,EACE;AAAA,OAOK;;;ACaP,IAAM,sBAAsB,MAC1B,OAAO,WAAW,eAAe,OAAO,WAAW,IAAI,gBAAgB,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,QAAO;AAE/B,MAAI,OAAO,SAAS,UAAU;AAC5B,WAAO,MAAM,OAAO,CAAC,KAAK,CAAC,KAAK,KAAK,MAAM,YAAY,KAAK,KA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AAE,KAAK,QAAQ,aAAa,QAAQ,QAAQ,KAAK;AAAA,MACrE,CAAC;AAAA,IACH;AAAA,EACF,CAAC;AACH;","names":[]}
@@ -1219,6 +1219,136 @@ function writeBarrel(files, indexPath, newEntries) {
1219
1219
  `);
1220
1220
  }
1221
1221
 
1222
+ // src/codegen/multipart.ts
1223
+ var MULTIPART_FILES_ARG = "multipartFiles";
1224
+ var BODY_FIELD = "body";
1225
+ var FILE_PART_TYPE = "(Blob | { uri: string; name: string; type: string })";
1226
+ var isObject = (value) => !!value && typeof value === "object" && !Array.isArray(value);
1227
+ function resolveRef(doc, value) {
1228
+ let current = value;
1229
+ for (let depth = 0; depth < 5 && isObject(current) && typeof current.$ref === "string"; depth++) {
1230
+ const segments = current.$ref.replace(/^#\//, "").split("/");
1231
+ let target = doc;
1232
+ for (const segment of segments) target = isObject(target) ? target[segment.replace(/~1/g, "/").replace(/~0/g, "~")] : void 0;
1233
+ current = target;
1234
+ }
1235
+ return isObject(current) ? current : void 0;
1236
+ }
1237
+ var isJsonMediaType = (type) => /(^|\/|\+)json$/.test(type.split(";")[0].trim().toLowerCase());
1238
+ function readMultipartOperation(doc, requestBody) {
1239
+ const content = resolveRef(doc, requestBody)?.content;
1240
+ if (!isObject(content)) return null;
1241
+ const multipartKey = Object.keys(content).find((type) => type.split(";")[0].trim().toLowerCase() === "multipart/form-data");
1242
+ if (!multipartKey || !isObject(content[multipartKey])) return null;
1243
+ const schema = resolveRef(doc, content[multipartKey].schema);
1244
+ const properties = isObject(schema?.properties) ? schema.properties : {};
1245
+ const fields = Object.keys(properties).filter((name) => name !== BODY_FIELD);
1246
+ if (fields.length === 0) return null;
1247
+ const requiredList = Array.isArray(schema?.required) ? schema.required.filter((name) => typeof name === "string") : [];
1248
+ return {
1249
+ fields,
1250
+ required: fields.filter((name) => requiredList.includes(name)),
1251
+ multipartOnly: !Object.keys(content).some(isJsonMediaType)
1252
+ };
1253
+ }
1254
+ function detectMultipartEndpoints(doc, endpoints) {
1255
+ const byOperation = /* @__PURE__ */ new Map();
1256
+ for (const { method, path: path10, operation } of listOperations(doc)) {
1257
+ const multipart = readMultipartOperation(doc, operation.requestBody);
1258
+ if (multipart) byOperation.set(operationKey(method, path10), multipart);
1259
+ }
1260
+ const keys = /* @__PURE__ */ new Map();
1261
+ if (byOperation.size === 0) return keys;
1262
+ for (const endpoint of endpoints) {
1263
+ const multipart = byOperation.get(operationKey(endpoint.method, endpoint.path));
1264
+ if (multipart) keys.set(endpoint.key, multipart);
1265
+ }
1266
+ return keys;
1267
+ }
1268
+ var quoteKey = (name) => /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(name) ? name : JSON.stringify(name);
1269
+ function filesMember(multipart) {
1270
+ const members = multipart.fields.map((field) => {
1271
+ const required2 = multipart.multipartOnly && multipart.required.includes(field);
1272
+ return `${quoteKey(field)}${required2 ? "" : "?"}: readonly ${FILE_PART_TYPE}[]${required2 ? "" : " | null"}`;
1273
+ }).join("; ");
1274
+ const required = multipart.multipartOnly && multipart.required.length > 0;
1275
+ const doc = multipart.multipartOnly ? "/** File parts of the multipart request. */" : "/** File parts: with at least one file the request is sent as multipart/form-data (JSON envelope in the field `body`), else as JSON. */";
1276
+ return `${doc}
1277
+ ${MULTIPART_FILES_ARG}${required ? "" : "?"}: { ${members} };`;
1278
+ }
1279
+ function injectMultipartBodies(source, endpoints, logger) {
1280
+ if (endpoints.size === 0) return { source, injected: [] };
1281
+ const ts = loadTypeScript();
1282
+ const file = ts.createSourceFile("api.ts", source, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS);
1283
+ const typeAliases = /* @__PURE__ */ new Map();
1284
+ for (const statement of file.statements) if (ts.isTypeAliasDeclaration(statement)) typeAliases.set(statement.name.text, statement);
1285
+ const edits = [];
1286
+ const injected = [];
1287
+ const skip = (key, reason) => logger.warn(` ${key}: multipart body not generated (${reason}) \u2014 the endpoint sends JSON only.`);
1288
+ const visit = (node) => {
1289
+ if (ts.isPropertyAssignment(node)) {
1290
+ const key = propertyName(ts, node.name);
1291
+ const multipart = key === void 0 ? void 0 : endpoints.get(key);
1292
+ if (key !== void 0 && multipart && isBuildCall(ts, node.initializer)) {
1293
+ const call = node.initializer;
1294
+ const returned = queryReturnObject(ts, call);
1295
+ if (typeof returned === "string") return skip(key, returned);
1296
+ const definition = call.arguments[0];
1297
+ const query = definition.properties.find((property) => property.name !== void 0 && propertyName(ts, property.name) === "query");
1298
+ const fn = query && ts.isPropertyAssignment(query) ? query.initializer : void 0;
1299
+ const parameter = fn && (ts.isArrowFunction(fn) || ts.isFunctionExpression(fn)) ? fn.parameters[0] : void 0;
1300
+ if (!parameter || !ts.isIdentifier(parameter.name)) return skip(key, "the endpoint takes no argument");
1301
+ const argName = parameter.name.text;
1302
+ const argTypeNode = call.typeArguments?.[1];
1303
+ const alias = argTypeNode && ts.isTypeReferenceNode(argTypeNode) && ts.isIdentifier(argTypeNode.typeName) ? typeAliases.get(argTypeNode.typeName.text) : void 0;
1304
+ if (!alias || !ts.isTypeLiteralNode(alias.type)) return skip(key, "its argument type is not an object type (flattenArg?)");
1305
+ const literal = alias.type;
1306
+ const memberName = (member) => member.name ? propertyName(ts, member.name) : void 0;
1307
+ if (literal.members.some((member) => memberName(member) === MULTIPART_FILES_ARG)) {
1308
+ return skip(key, `the argument already has a member "${MULTIPART_FILES_ARG}"`);
1309
+ }
1310
+ const body = returned.properties.find((property) => property.name !== void 0 && propertyName(ts, property.name) === "body");
1311
+ let jsonBody = "undefined";
1312
+ if (body) {
1313
+ if (!ts.isPropertyAssignment(body)) return skip(key, "unexpected `body` member");
1314
+ const text = body.initializer.getText(file);
1315
+ if (text === argName) return skip(key, "the argument is the request body itself (flattenArg)");
1316
+ if (multipart.multipartOnly) {
1317
+ const accessor = new RegExp(`^${argName}\\.([A-Za-z_$][A-Za-z0-9_$]*)$`).exec(text)?.[1];
1318
+ const member = accessor ? literal.members.find((candidate) => memberName(candidate) === accessor) : void 0;
1319
+ if (member) edits.push({ start: member.getFullStart(), end: member.getEnd(), text: "" });
1320
+ } else {
1321
+ jsonBody = text;
1322
+ }
1323
+ edits.push({
1324
+ start: body.initializer.getStart(file),
1325
+ end: body.initializer.getEnd(),
1326
+ text: `buildDddMultipartBody(${jsonBody}, ${argName}.${MULTIPART_FILES_ARG})`
1327
+ });
1328
+ } else {
1329
+ const close2 = returned.end - 1;
1330
+ const separator = returned.properties.length > 0 && !returned.properties.hasTrailingComma ? ", " : " ";
1331
+ edits.push({ start: close2, end: close2, text: `${separator}body: buildDddMultipartBody(undefined, ${argName}.${MULTIPART_FILES_ARG}) ` });
1332
+ }
1333
+ const close = literal.end - 1;
1334
+ edits.push({ start: close, end: close, text: `
1335
+ ${filesMember(multipart)}
1336
+ ` });
1337
+ injected.push(key);
1338
+ return;
1339
+ }
1340
+ }
1341
+ ts.forEachChild(node, visit);
1342
+ };
1343
+ visit(file);
1344
+ let result = source;
1345
+ for (const { start, end, text } of edits.sort((a, b) => b.start - a.start || b.end - a.end)) {
1346
+ result = result.slice(0, start) + text + result.slice(end);
1347
+ }
1348
+ return { source: result, injected };
1349
+ }
1350
+ var MULTIPART_IMPORT = `import { buildDddMultipartBody } from '${DDD_WEB_API_IMPORT}';`;
1351
+
1222
1352
  // src/codegen/output.ts
1223
1353
  import * as fs5 from "fs";
1224
1354
  import * as path5 from "path";
@@ -1596,9 +1726,11 @@ async function generateSdk(options = {}) {
1596
1726
  }
1597
1727
  const fileCount = [...handlerEndpoints.values()].filter((kind) => kind === "blob").length;
1598
1728
  if (fileCount > 0) logger.info(` ${fileCount} file download endpoint(s) (blobResponseHandler)`);
1729
+ const multipart = injectMultipartBodies(rtk.code, detectMultipartEndpoints(doc, endpoints), logger);
1730
+ if (multipart.injected.length > 0) logger.info(` ${multipart.injected.length} multipart endpoint(s) (multipartFiles)`);
1599
1731
  const esm = api.config.esmExtensions === true;
1600
1732
  const apiSource = extractModels({
1601
- apiSource: rtk.code,
1733
+ apiSource: multipart.source,
1602
1734
  apiFilePath: api.outputFile,
1603
1735
  modelsDir,
1604
1736
  registry,
@@ -1608,7 +1740,9 @@ async function generateSdk(options = {}) {
1608
1740
  responseKinds
1609
1741
  });
1610
1742
  if (!write) continue;
1611
- files.set(api.outputFile, injectResponseHandlers(apiSource, handlerEndpoints));
1743
+ const withHandlers = injectResponseHandlers(apiSource, handlerEndpoints);
1744
+ files.set(api.outputFile, multipart.injected.length > 0 ? `${MULTIPART_IMPORT}
1745
+ ${withHandlers}` : withHandlers);
1612
1746
  const withExtension = (specifier) => esm ? `${specifier}.js` : specifier;
1613
1747
  const enhanced = buildEnhancedEndpoints({
1614
1748
  stem: api.stem,
@@ -1719,4 +1853,4 @@ export {
1719
1853
  generateSdk,
1720
1854
  linkSkills
1721
1855
  };
1722
- //# sourceMappingURL=chunk-VJ2CHVSL.js.map
1856
+ //# sourceMappingURL=chunk-6PDXSGVW.js.map