@mgamadeus/ddd-web 0.0.0-stage → 0.2.1

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.
@@ -0,0 +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\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 * 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 * @param error whatever a request rejected with\n * @param fallbackMessage message when nothing usable is found\n */\nexport function normalizeDddError(error: unknown, fallbackMessage: string = DEFAULT_ERROR_MESSAGE): DddNormalizedError {\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 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 */\nexport function getErrorMessage(error: unknown, fallbackMessage: string = DEFAULT_ERROR_MESSAGE): string {\n return normalizeDddError(error, fallbackMessage).message;\n}\n\n/** HTTP status of an API error, 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,GAA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AmB,YAAY;AAC3E,SAAO,OAAO,aAA6D;AACzE,QAAI,CAAC,SAAS,GAAI,QAAO,eAAe,QAAQ;AAChD,UAAM,OAAO,MAAM,SAAS,KAAK;AACjC,UAAM,WAAW,+BAA+B,SAAS,QAAQ,IAAI,qBAAqB,CAAC,KAAK;AAChG,iBAAa,MAAM,QAAQ;AAC3B,WAAO,EAAE,UAAU,aAAa,SAAS,QAAQ,IAAI,cAAc,GAAG,MAAM,KAAK,KAAK;AAAA,EACxF;AACF;;;ACnFO,SAAS,oBAKd,KAAuE,SAAkC;AACzG,SAAO,IAAI,gBAAgB;AAAA,IACzB,WAAW,CAAC,WAAW;AAAA,MACrB,WAAW,MAAM,SAA2C;AAAA,QAC1D,OAAO,CAAC,UAAU,EAAE,KAAK,QAAQ,WAAW,QAAQ,QAAQ,KAAK;AAAA,MACnE,CAAC;AAAA,MACD,aAAa,MAAM,SAA6C;AAAA,QAC9D,OAAO,CAAC,UAAU,EAAE,KAAK,QAAQ,aAAa,QAAQ,QAAQ,KAAK;AAAA,MACrE,CAAC;AAAA,IACH;AAAA,EACF,CAAC;AACH;","names":[]}
@@ -0,0 +1,109 @@
1
+ import { D as DddTokens, d as DddTokensUpdate } from '../types-BhDMN3ZS.js';
2
+ export { b as DddAuthResponse, a as DddLoginRequest, c as DddRefreshRequest } from '../types-BhDMN3ZS.js';
3
+
4
+ /**
5
+ * JWT helpers. They DECODE only — no signature verification; never base an authorisation decision on them.
6
+ */
7
+ /** Claims of a decoded JWT. DDD tokens carry `accountId` and `expiresAt` (unix seconds). */
8
+ interface DddJwtClaims {
9
+ accountId?: number | string;
10
+ /** Unix timestamp in seconds, set by the DDD backend on every token. */
11
+ expiresAt?: number;
12
+ /** Standard JWT expiry (unix seconds); used when `expiresAt` is absent. */
13
+ exp?: number;
14
+ [claim: string]: unknown;
15
+ }
16
+ /**
17
+ * Decodes the payload of a JWT without verifying it.
18
+ *
19
+ * @returns the claims, or `null` when the token is missing or malformed.
20
+ */
21
+ declare function decodeJwt<T extends object = DddJwtClaims>(token: string | null | undefined): T | null;
22
+ /**
23
+ * Expiry of a token in unix seconds, read from `expiresAt` (DDD) or else `exp` (standard claim).
24
+ *
25
+ * @param tokenOrClaims a raw JWT or already decoded claims
26
+ * @returns the expiry, or `null` when the token is malformed or carries no expiry claim.
27
+ */
28
+ declare function getTokenExpiry(tokenOrClaims: string | DddJwtClaims | null | undefined): number | null;
29
+ /**
30
+ * True when the token is expired or expires within `skewSeconds`.
31
+ *
32
+ * A missing or malformed token counts as expired, and so does a token whose expiry claim is present but not a valid
33
+ * number. A well-formed token without any expiry claim never expires.
34
+ *
35
+ * @param token raw JWT
36
+ * @param skewSeconds safety margin; e.g. `30` treats a token that expires in 20 s as expired
37
+ * @param now current time in milliseconds (injectable for tests)
38
+ */
39
+ declare function isExpired(token: string | null | undefined, skewSeconds?: number, now?: number): boolean;
40
+
41
+ /**
42
+ * Web Storage wrappers that never throw: they return `null` / do nothing when `window` is undefined (SSR, workers,
43
+ * tests) or when the browser blocks storage (privacy mode, quota exceeded, sandboxed iframe).
44
+ */
45
+ /** The subset of the Web Storage API the helpers use. */
46
+ interface DddStorageLike {
47
+ getItem(key: string): string | null;
48
+ setItem(key: string, value: string): void;
49
+ removeItem(key: string): void;
50
+ }
51
+ /** True in an environment with a `window` object. */
52
+ declare const isBrowser: () => boolean;
53
+ /**
54
+ * Wraps a lazily resolved storage so every access is guarded by try/catch.
55
+ *
56
+ * @param resolve returns the backing storage; called on every access, may throw or return `null`
57
+ */
58
+ declare function createSafeStorage(resolve: () => DddStorageLike | null | undefined): DddStorageLike;
59
+ /** SSR-safe `window.localStorage`. */
60
+ declare const safeLocalStorage: DddStorageLike;
61
+ /** SSR-safe `window.sessionStorage`. */
62
+ declare const safeSessionStorage: DddStorageLike;
63
+
64
+ /** Persists the token pair. Implementations must never throw. */
65
+ interface TokenStorage {
66
+ /** Reads both tokens; a missing token is `null`. */
67
+ read(): DddTokens;
68
+ /** Writes the given tokens; `undefined` leaves a value untouched, `null` removes it. */
69
+ write(tokens: DddTokensUpdate): void;
70
+ /** Removes both tokens. */
71
+ clear(): void;
72
+ }
73
+ /** Options of {@link createLocalStorageTokenStorage}. */
74
+ interface LocalStorageTokenStorageOptions {
75
+ /** Storage key of the access token. Default `accessToken`. */
76
+ accessKey?: string;
77
+ /** Storage key of the refresh token. Default `refreshToken`. */
78
+ refreshKey?: string;
79
+ /**
80
+ * Turns the access token into the stored string. Receives the currently stored raw value so a format that keeps more
81
+ * than the token (e.g. `{ user, jwt }`) can preserve the other fields. Default: the token itself.
82
+ */
83
+ serialize?: (accessToken: string, previous: string | null) => string;
84
+ /**
85
+ * Extracts the access token from the stored string. May throw or return `null` for an unreadable value; that counts
86
+ * as "no token". Default: the raw value.
87
+ */
88
+ deserialize?: (raw: string) => string | null | undefined;
89
+ /** Backing storage. Default: SSR-safe `localStorage`. */
90
+ storage?: DddStorageLike;
91
+ }
92
+ /**
93
+ * A {@link TokenStorage} over Web Storage that can keep an app's existing storage format.
94
+ *
95
+ * @example
96
+ * // Access token kept inside a JSON object `{ user, jwt }`, refresh token stored raw:
97
+ * const storage = createLocalStorageTokenStorage({
98
+ * accessKey: 'session',
99
+ * refreshKey: 'session_refresh',
100
+ * serialize: (jwt, previous) => JSON.stringify({ ...(previous ? JSON.parse(previous) : {}), jwt }),
101
+ * deserialize: (raw) => JSON.parse(raw).jwt,
102
+ * });
103
+ */
104
+ declare function createLocalStorageTokenStorage(options?: LocalStorageTokenStorageOptions): TokenStorage;
105
+ /** A non-persistent {@link TokenStorage} (tests, SSR, short-lived sessions). */
106
+ declare function createMemoryTokenStorage(initial?: DddTokensUpdate): TokenStorage;
107
+
108
+ export { DddTokens, DddTokensUpdate, createLocalStorageTokenStorage, createMemoryTokenStorage, createSafeStorage, decodeJwt, getTokenExpiry, isBrowser, isExpired, safeLocalStorage, safeSessionStorage };
109
+ export type { DddJwtClaims, DddStorageLike, LocalStorageTokenStorageOptions, TokenStorage };
@@ -0,0 +1,146 @@
1
+ // src/auth/jwt.ts
2
+ var decodeBase64Url = (segment) => {
3
+ const base64 = segment.replace(/-/g, "+").replace(/_/g, "/");
4
+ const padded = base64 + "=".repeat((4 - base64.length % 4) % 4);
5
+ const binary = atob(padded);
6
+ const bytes = Uint8Array.from(binary, (char) => char.charCodeAt(0));
7
+ return new TextDecoder().decode(bytes);
8
+ };
9
+ function decodeJwt(token) {
10
+ if (!token) return null;
11
+ const payload = token.split(".")[1];
12
+ if (!payload) return null;
13
+ try {
14
+ const claims = JSON.parse(decodeBase64Url(payload));
15
+ return claims !== null && typeof claims === "object" && !Array.isArray(claims) ? claims : null;
16
+ } catch {
17
+ return null;
18
+ }
19
+ }
20
+ function getTokenExpiry(tokenOrClaims) {
21
+ const claims = typeof tokenOrClaims === "string" ? decodeJwt(tokenOrClaims) : tokenOrClaims ?? null;
22
+ return claims ? readExpiry(claims).seconds : null;
23
+ }
24
+ function readExpiry(claims) {
25
+ const expiry = claims.expiresAt ?? claims.exp;
26
+ if (expiry === void 0 || expiry === null) return { present: false, seconds: null };
27
+ const raw = expiry;
28
+ const seconds = typeof raw === "string" && raw.trim() !== "" ? Number(raw) : raw;
29
+ return { present: true, seconds: typeof seconds === "number" && Number.isFinite(seconds) ? seconds : null };
30
+ }
31
+ function isExpired(token, skewSeconds = 0, now = Date.now()) {
32
+ const claims = decodeJwt(token);
33
+ if (!claims) return true;
34
+ const expiry = readExpiry(claims);
35
+ if (!expiry.present) return false;
36
+ if (expiry.seconds === null) return true;
37
+ return now / 1e3 + skewSeconds >= expiry.seconds;
38
+ }
39
+
40
+ // src/auth/safeStorage.ts
41
+ var isBrowser = () => typeof window !== "undefined";
42
+ function createSafeStorage(resolve) {
43
+ const storage = () => {
44
+ try {
45
+ return resolve() ?? null;
46
+ } catch {
47
+ return null;
48
+ }
49
+ };
50
+ return {
51
+ getItem(key) {
52
+ try {
53
+ return storage()?.getItem(key) ?? null;
54
+ } catch {
55
+ return null;
56
+ }
57
+ },
58
+ setItem(key, value) {
59
+ try {
60
+ storage()?.setItem(key, value);
61
+ } catch {
62
+ }
63
+ },
64
+ removeItem(key) {
65
+ try {
66
+ storage()?.removeItem(key);
67
+ } catch {
68
+ }
69
+ }
70
+ };
71
+ }
72
+ var safeLocalStorage = createSafeStorage(() => isBrowser() ? window.localStorage : null);
73
+ var safeSessionStorage = createSafeStorage(() => isBrowser() ? window.sessionStorage : null);
74
+
75
+ // src/auth/tokenStorage.ts
76
+ function createLocalStorageTokenStorage(options = {}) {
77
+ const {
78
+ accessKey = "accessToken",
79
+ refreshKey = "refreshToken",
80
+ serialize = (accessToken) => accessToken,
81
+ deserialize = (raw) => raw
82
+ } = options;
83
+ const injected = options.storage;
84
+ const storage = injected ? createSafeStorage(() => injected) : safeLocalStorage;
85
+ const readAccess = () => {
86
+ const raw = storage.getItem(accessKey);
87
+ if (!raw) return null;
88
+ try {
89
+ return deserialize(raw) || null;
90
+ } catch {
91
+ return null;
92
+ }
93
+ };
94
+ const trySerialize = (accessToken, previous) => {
95
+ try {
96
+ return serialize(accessToken, previous);
97
+ } catch {
98
+ return null;
99
+ }
100
+ };
101
+ const writeAccess = (accessToken) => {
102
+ const value = trySerialize(accessToken, storage.getItem(accessKey)) ?? trySerialize(accessToken, null);
103
+ if (value === null) storage.removeItem(accessKey);
104
+ else storage.setItem(accessKey, value);
105
+ };
106
+ return {
107
+ read: () => ({ accessToken: readAccess(), refreshToken: storage.getItem(refreshKey) || null }),
108
+ write(tokens) {
109
+ if (tokens.accessToken === null) storage.removeItem(accessKey);
110
+ else if (tokens.accessToken !== void 0) writeAccess(tokens.accessToken);
111
+ if (tokens.refreshToken === null) storage.removeItem(refreshKey);
112
+ else if (tokens.refreshToken !== void 0) storage.setItem(refreshKey, tokens.refreshToken);
113
+ },
114
+ clear() {
115
+ storage.removeItem(accessKey);
116
+ storage.removeItem(refreshKey);
117
+ }
118
+ };
119
+ }
120
+ function createMemoryTokenStorage(initial = {}) {
121
+ let tokens = { accessToken: initial.accessToken ?? null, refreshToken: initial.refreshToken ?? null };
122
+ return {
123
+ read: () => ({ ...tokens }),
124
+ write(update) {
125
+ tokens = {
126
+ accessToken: update.accessToken === void 0 ? tokens.accessToken : update.accessToken,
127
+ refreshToken: update.refreshToken === void 0 ? tokens.refreshToken : update.refreshToken
128
+ };
129
+ },
130
+ clear() {
131
+ tokens = { accessToken: null, refreshToken: null };
132
+ }
133
+ };
134
+ }
135
+ export {
136
+ createLocalStorageTokenStorage,
137
+ createMemoryTokenStorage,
138
+ createSafeStorage,
139
+ decodeJwt,
140
+ getTokenExpiry,
141
+ isBrowser,
142
+ isExpired,
143
+ safeLocalStorage,
144
+ safeSessionStorage
145
+ };
146
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/auth/jwt.ts","../../src/auth/safeStorage.ts","../../src/auth/tokenStorage.ts"],"sourcesContent":["/**\n * JWT helpers. They DECODE only — no signature verification; never base an authorisation decision on them.\n */\n\n/** Claims of a decoded JWT. DDD tokens carry `accountId` and `expiresAt` (unix seconds). */\nexport interface DddJwtClaims {\n accountId?: number | string;\n /** Unix timestamp in seconds, set by the DDD backend on every token. */\n expiresAt?: number;\n /** Standard JWT expiry (unix seconds); used when `expiresAt` is absent. */\n exp?: number;\n [claim: string]: unknown;\n}\n\nconst decodeBase64Url = (segment: string): string => {\n const base64 = segment.replace(/-/g, '+').replace(/_/g, '/');\n const padded = base64 + '='.repeat((4 - (base64.length % 4)) % 4);\n const binary = atob(padded);\n const bytes = Uint8Array.from(binary, (char) => char.charCodeAt(0));\n return new TextDecoder().decode(bytes);\n};\n\n/**\n * Decodes the payload of a JWT without verifying it.\n *\n * @returns the claims, or `null` when the token is missing or malformed.\n */\nexport function decodeJwt<T extends object = DddJwtClaims>(token: string | null | undefined): T | null {\n if (!token) return null;\n const payload = token.split('.')[1];\n if (!payload) return null;\n try {\n const claims: unknown = JSON.parse(decodeBase64Url(payload));\n return claims !== null && typeof claims === 'object' && !Array.isArray(claims) ? (claims as T) : null;\n } catch {\n return null;\n }\n}\n\n/**\n * Expiry of a token in unix seconds, read from `expiresAt` (DDD) or else `exp` (standard claim).\n *\n * @param tokenOrClaims a raw JWT or already decoded claims\n * @returns the expiry, or `null` when the token is malformed or carries no expiry claim.\n */\nexport function getTokenExpiry(tokenOrClaims: string | DddJwtClaims | null | undefined): number | null {\n const claims = typeof tokenOrClaims === 'string' ? decodeJwt(tokenOrClaims) : (tokenOrClaims ?? null);\n return claims ? readExpiry(claims).seconds : null;\n}\n\n/** The expiry claim (`expiresAt`, else `exp`): whether one is present and, if valid, its value in unix seconds. */\nfunction readExpiry(claims: DddJwtClaims): { present: boolean; seconds: number | null } {\n const expiry = claims.expiresAt ?? claims.exp;\n if (expiry === undefined || expiry === null) return { present: false, seconds: null };\n const raw: unknown = expiry;\n const seconds = typeof raw === 'string' && raw.trim() !== '' ? Number(raw) : raw;\n return { present: true, seconds: typeof seconds === 'number' && Number.isFinite(seconds) ? seconds : null };\n}\n\n/**\n * True when the token is expired or expires within `skewSeconds`.\n *\n * A missing or malformed token counts as expired, and so does a token whose expiry claim is present but not a valid\n * number. A well-formed token without any expiry claim never expires.\n *\n * @param token raw JWT\n * @param skewSeconds safety margin; e.g. `30` treats a token that expires in 20 s as expired\n * @param now current time in milliseconds (injectable for tests)\n */\nexport function isExpired(token: string | null | undefined, skewSeconds = 0, now: number = Date.now()): boolean {\n const claims = decodeJwt(token);\n if (!claims) return true;\n const expiry = readExpiry(claims);\n if (!expiry.present) return false;\n if (expiry.seconds === null) return true;\n return now / 1000 + skewSeconds >= expiry.seconds;\n}\n","/**\n * Web Storage wrappers that never throw: they return `null` / do nothing when `window` is undefined (SSR, workers,\n * tests) or when the browser blocks storage (privacy mode, quota exceeded, sandboxed iframe).\n */\n\n/** The subset of the Web Storage API the helpers use. */\nexport interface DddStorageLike {\n getItem(key: string): string | null;\n setItem(key: string, value: string): void;\n removeItem(key: string): void;\n}\n\n/** True in an environment with a `window` object. */\nexport const isBrowser = (): boolean => typeof window !== 'undefined';\n\n/**\n * Wraps a lazily resolved storage so every access is guarded by try/catch.\n *\n * @param resolve returns the backing storage; called on every access, may throw or return `null`\n */\nexport function createSafeStorage(resolve: () => DddStorageLike | null | undefined): DddStorageLike {\n const storage = (): DddStorageLike | null => {\n try {\n return resolve() ?? null;\n } catch {\n return null;\n }\n };\n return {\n getItem(key) {\n try {\n return storage()?.getItem(key) ?? null;\n } catch {\n return null;\n }\n },\n setItem(key, value) {\n try {\n storage()?.setItem(key, value);\n } catch {\n // Storage blocked or full: the value simply is not persisted.\n }\n },\n removeItem(key) {\n try {\n storage()?.removeItem(key);\n } catch {\n // Storage blocked: nothing to remove.\n }\n },\n };\n}\n\n/** SSR-safe `window.localStorage`. */\nexport const safeLocalStorage: DddStorageLike = createSafeStorage(() => (isBrowser() ? window.localStorage : null));\n\n/** SSR-safe `window.sessionStorage`. */\nexport const safeSessionStorage: DddStorageLike = createSafeStorage(() => (isBrowser() ? window.sessionStorage : null));\n","import { createSafeStorage, safeLocalStorage, type DddStorageLike } from './safeStorage';\nimport type { DddTokens, DddTokensUpdate } from './types';\n\n/** Persists the token pair. Implementations must never throw. */\nexport interface TokenStorage {\n /** Reads both tokens; a missing token is `null`. */\n read(): DddTokens;\n /** Writes the given tokens; `undefined` leaves a value untouched, `null` removes it. */\n write(tokens: DddTokensUpdate): void;\n /** Removes both tokens. */\n clear(): void;\n}\n\n/** Options of {@link createLocalStorageTokenStorage}. */\nexport interface LocalStorageTokenStorageOptions {\n /** Storage key of the access token. Default `accessToken`. */\n accessKey?: string;\n /** Storage key of the refresh token. Default `refreshToken`. */\n refreshKey?: string;\n /**\n * Turns the access token into the stored string. Receives the currently stored raw value so a format that keeps more\n * than the token (e.g. `{ user, jwt }`) can preserve the other fields. Default: the token itself.\n */\n serialize?: (accessToken: string, previous: string | null) => string;\n /**\n * Extracts the access token from the stored string. May throw or return `null` for an unreadable value; that counts\n * as \"no token\". Default: the raw value.\n */\n deserialize?: (raw: string) => string | null | undefined;\n /** Backing storage. Default: SSR-safe `localStorage`. */\n storage?: DddStorageLike;\n}\n\n/**\n * A {@link TokenStorage} over Web Storage that can keep an app's existing storage format.\n *\n * @example\n * // Access token kept inside a JSON object `{ user, jwt }`, refresh token stored raw:\n * const storage = createLocalStorageTokenStorage({\n * accessKey: 'session',\n * refreshKey: 'session_refresh',\n * serialize: (jwt, previous) => JSON.stringify({ ...(previous ? JSON.parse(previous) : {}), jwt }),\n * deserialize: (raw) => JSON.parse(raw).jwt,\n * });\n */\nexport function createLocalStorageTokenStorage(options: LocalStorageTokenStorageOptions = {}): TokenStorage {\n const {\n accessKey = 'accessToken',\n refreshKey = 'refreshToken',\n serialize = (accessToken: string) => accessToken,\n deserialize = (raw: string) => raw,\n } = options;\n // An injected storage may throw as well; the TokenStorage contract says never throw.\n const injected = options.storage;\n const storage = injected ? createSafeStorage(() => injected) : safeLocalStorage;\n\n const readAccess = (): string | null => {\n const raw = storage.getItem(accessKey);\n if (!raw) return null;\n try {\n return deserialize(raw) || null;\n } catch {\n return null;\n }\n };\n\n const trySerialize = (accessToken: string, previous: string | null): string | null => {\n try {\n return serialize(accessToken, previous);\n } catch {\n return null;\n }\n };\n\n const writeAccess = (accessToken: string): void => {\n // An unreadable stored value: start from scratch. A serializer that fails on both: the old (stale) token is\n // removed rather than kept as if it were the new one.\n const value = trySerialize(accessToken, storage.getItem(accessKey)) ?? trySerialize(accessToken, null);\n if (value === null) storage.removeItem(accessKey);\n else storage.setItem(accessKey, value);\n };\n\n return {\n read: () => ({ accessToken: readAccess(), refreshToken: storage.getItem(refreshKey) || null }),\n write(tokens) {\n if (tokens.accessToken === null) storage.removeItem(accessKey);\n else if (tokens.accessToken !== undefined) writeAccess(tokens.accessToken);\n if (tokens.refreshToken === null) storage.removeItem(refreshKey);\n else if (tokens.refreshToken !== undefined) storage.setItem(refreshKey, tokens.refreshToken);\n },\n clear() {\n storage.removeItem(accessKey);\n storage.removeItem(refreshKey);\n },\n };\n}\n\n/** A non-persistent {@link TokenStorage} (tests, SSR, short-lived sessions). */\nexport function createMemoryTokenStorage(initial: DddTokensUpdate = {}): TokenStorage {\n let tokens: DddTokens = { accessToken: initial.accessToken ?? null, refreshToken: initial.refreshToken ?? null };\n return {\n read: () => ({ ...tokens }),\n write(update) {\n tokens = {\n accessToken: update.accessToken === undefined ? tokens.accessToken : update.accessToken,\n refreshToken: update.refreshToken === undefined ? tokens.refreshToken : update.refreshToken,\n };\n },\n clear() {\n tokens = { accessToken: null, refreshToken: null };\n },\n };\n}\n"],"mappings":";AAcA,IAAM,kBAAkB,CAAC,YAA4B;AACnD,QAAM,SAAS,QAAQ,QAAQ,MAAM,GAAG,EAAE,QAAQ,MAAM,GAAG;AAC3D,QAAM,SAAS,SAAS,IAAI,QAAQ,IAAK,OAAO,SAAS,KAAM,CAAC;AAChE,QAAM,SAAS,KAAK,MAAM;AAC1B,QAAM,QAAQ,WAAW,KAAK,QAAQ,CAAC,SAAS,KAAK,WAAW,CAAC,CAAC;AAClE,SAAO,IAAI,YAAY,EAAE,OAAO,KAAK;AACvC;AAOO,SAAS,UAA2C,OAA4C;AACrG,MAAI,CAAC,MAAO,QAAO;AACnB,QAAM,UAAU,MAAM,MAAM,GAAG,EAAE,CAAC;AAClC,MAAI,CAAC,QAAS,QAAO;AACrB,MAAI;AACF,UAAM,SAAkB,KAAK,MAAM,gBAAgB,OAAO,CAAC;AAC3D,WAAO,WAAW,QAAQ,OAAO,WAAW,YAAY,CAAC,MAAM,QAAQ,MAAM,IAAK,SAAe;AAAA,EACnG,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAQO,SAAS,eAAe,eAAwE;AACrG,QAAM,SAAS,OAAO,kBAAkB,WAAW,UAAU,aAAa,IAAK,iBAAiB;AAChG,SAAO,SAAS,WAAW,MAAM,EAAE,UAAU;AAC/C;AAGA,SAAS,WAAW,QAAoE;AACtF,QAAM,SAAS,OAAO,aAAa,OAAO;AAC1C,MAAI,WAAW,UAAa,WAAW,KAAM,QAAO,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