@mgamadeus/ddd-web 0.4.0 → 0.6.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,9 +1,9 @@
1
1
  ---
2
2
  name: ddd-web-specialist
3
- description: "Use and maintain @mgamadeus/ddd-web, the TS client of mgamadeus/ddd. Covers openapi-config.ts with defineConfig (schemaFile URL or local file, sideEffects, responseHandlers, invalidation), the RTK Query SDK from ddd-web-sdk (Enhanced/Tags files, cache tags by entity identity, typed tagTypes via mergeDddTagTypes, file downloads via blobResponseHandler, file uploads: generated multipartFiles argument, buildDddMultipartBody, upload with progress via baseQuery.upload), QueryOptions builders (buildQueryOptions, combineFilters, buildInFilter), createDddBaseQuery (Bearer, shared refresh + retry, relogin for guest or device sessions without refresh token, shouldRefresh, normalizeDddError), token storage, JWT helpers, contract types, link-skills, release. Use when wiring a frontend to a DDD backend, regenerating the SDK, building filters, uploading files, multipart, FormData, upload progress, fixing token refresh, guest login, cache tags that invalidate nothing, downloading an export, or releasing ddd-web."
3
+ description: "Use and maintain @mgamadeus/ddd-web, the TS client of mgamadeus/ddd: openapi-config.ts with defineConfig (schemaFile, sideEffects, responseHandlers, invalidation), the RTK Query SDK from ddd-web-sdk (Enhanced/Tags files, cache tags by entity identity, typed tagTypes via mergeDddTagTypes, downloads via blobResponseHandler, file uploads: multipartFiles argument, buildDddMultipartBody, upload with progress via baseQuery.upload), QueryOptions builders (buildQueryOptions, combineFilters, buildInFilter), createDddBaseQuery (Bearer, shared refresh + retry, relogin for sessions without refresh token, session-bound requests via getSessionKey, shouldRefresh, normalizeDddError), token storage, JWT helpers, link-skills, release. Use when wiring a frontend to a DDD backend, regenerating the SDK, building filters, uploading files, FormData, upload progress, fixing token refresh, guest login, a request sent under the wrong account after an account switch, stale cache tags, downloading an export, or releasing ddd-web."
4
4
  metadata:
5
5
  author: mgamadeus
6
- version: "1.3.0"
6
+ version: "1.4.1"
7
7
  package: "@mgamadeus/ddd-web"
8
8
  ---
9
9
 
@@ -21,7 +21,7 @@ frontend code. No UI components, no domain logic — apps bring their own design
21
21
  |---|---|---|
22
22
  | `@mgamadeus/ddd-web/codegen` | Node only (never in a browser bundle) | `defineConfig`, `generateSdk`, `linkSkills`, `loadSpec` / `validateSpec`; bins `ddd-web-sdk`, `ddd-web` |
23
23
  | `@mgamadeus/ddd-web/query` | anywhere, no React | QueryOptions builders and definition-driven validators |
24
- | `@mgamadeus/ddd-web/api` | needs `@reduxjs/toolkit` 2 (peer) | `createDddBaseQuery` (+ `upload()`, `relogin`), `createDddRefresh`, `normalizeDddError`, downloads, multipart (`buildDddMultipartBody`), `mergeDddTagTypes`, `createAuthEndpoints` |
24
+ | `@mgamadeus/ddd-web/api` | needs `@reduxjs/toolkit` 2 (peer) | `createDddBaseQuery` (+ `upload()`, `relogin`, `getSessionKey`), `createDddRefresh`, `normalizeDddError`, downloads, multipart (`buildDddMultipartBody`), `mergeDddTagTypes`, `createAuthEndpoints` |
25
25
  | `@mgamadeus/ddd-web/auth` | anywhere | `TokenStorage` adapters, `decodeJwt`, `isExpired`, SSR-safe storage |
26
26
  | `@mgamadeus/ddd-web/contract` | types + small helpers | `x-ddd-*` types, error body, DDD date-time, translations, operators |
27
27
 
@@ -97,6 +97,9 @@ const { data } = useGetApiAdminLibraryBooksListQuery({
97
97
  `fetch` / `XMLHttpRequest` and an own token: it bypasses the session, the refresh and the headers hooks.
98
98
  - **Sessions without refresh token** (guest, device, impersonation) recover through the `relogin` option — never a
99
99
  placeholder refresh token.
100
+ - **A request whose body belongs to one account is bound to that session**: `getSessionKey` on the base query and
101
+ `withDddExpectedSessionKey` (or `expectedSessionKey` of an upload). A check before `dispatch()` does not cover the
102
+ wait for a running refresh or the retry after it.
100
103
  - **Tag names come from the generated `<stem>Tags.ts`**: build `tagTypes` with `mergeDddTagTypes`, never retype a tag.
101
104
  - **A route missing from the deployed spec** is generated from a local spec file or local backend (`schemaFile`,
102
105
  `--schema`), not injected by hand.
@@ -35,6 +35,7 @@ too). A plain RTK-codegen file with `export const apis = [...]` is accepted as w
35
35
  | `responseHandlers` | Overrides checked before the global ones (first match wins). |
36
36
  | `invalidation` | Resolver checked before the global one (see section 3). |
37
37
  | `esmExtensions` | `true` for `moduleResolution: nodenext`: generated relative imports end in `.js`. |
38
+ | `encodePathParams` | Default `true`: a path parameter is passed through `encodeURIComponent` in the generated URL — callers pass the raw value and never encode it themselves (it would be encoded twice). `false` restores the plain interpolation. |
38
39
  | any other key | Passed to RTK codegen (`argSuffix`, `flattenArg`, `endpointOverrides`, `filterEndpoints`, …). |
39
40
 
40
41
  **Global options:**
@@ -286,6 +287,7 @@ DDD date-time otherwise.
286
287
  | `onLogout(api)` | once, when the session cannot be recovered |
287
288
  | `refreshPath` / `refresh` | default refresh = `POST refreshPath { refreshToken }` → `{ accessToken, refreshToken }`; or a custom `DddRefreshFn` |
288
289
  | `relogin(context)` | re-opens the session when the refresh cannot: `context.reason` is `'no-refresh-token'` (guest, device, impersonation sessions) or `'refresh-rejected'`; return the new tokens (`refreshToken: null` allowed) or `null` to log out |
290
+ | `getSessionKey(context)` | key of the current session that survives a token refresh (account id, or a counter raised on login and logout; `null` without a session); needed to bind requests to a session, see below |
289
291
  | `createUploadRequest()` | the request object of `upload()`; default `new XMLHttpRequest()` |
290
292
  | `shouldRefresh(error, request)` | default `defaultShouldRefresh`: status 401 and not an auth route (`…/common/auth/…`, `isDddAuthRequest`) |
291
293
  | `languageCode(context)` | value of the DDD `languageCode` header; `context.type` tells queries from mutations (e.g. editing language on writes, UI language on reads) |
@@ -310,6 +312,36 @@ relogin: async ({ reason, baseQuery, api, extraOptions }) => {
310
312
  },
311
313
  ```
312
314
 
315
+ **Requests bound to a session.** The Bearer token is read when a request is sent: after the wait for a running
316
+ refresh, and again for the retry. A request prepared for account A (an offline queue, an upload, an import) can
317
+ therefore leave with the token of account B when the user switched in between; a check before `dispatch()` does not
318
+ cover that. Give the base query a `getSessionKey` and bind such requests: a bound request is sent, and retried, only
319
+ while its session is the current one. Otherwise it ends with `{ error: { status: 'CUSTOM_ERROR', error:
320
+ 'DDD_SESSION_CHANGED' } }` (`isDddSessionChanged(error)`) without a network call, a refresh or a logout. Requests that
321
+ are not bound behave as before.
322
+
323
+ ```ts
324
+ createDddBaseQuery({ /* … */ getSessionKey: ({ getState }) => (getState() as RootState).auth.accountId });
325
+
326
+ // The session the caller prepared the request for (strictest form): the key is part of the endpoint's argument.
327
+ saveDraft: build.mutation<void, { accountId: number; draft: Draft }>({
328
+ query: ({ accountId, draft }) =>
329
+ withDddExpectedSessionKey({ url: '/api/client/drafts', method: 'POST', body: { draft } }, accountId),
330
+ }),
331
+
332
+ // An upload:
333
+ dddBaseQuery.upload({ url, files, expectedSessionKey: accountId }, api, extraOptions);
334
+
335
+ // The session that is current when the request starts (also for generated endpoints, through enhanceEndpoints):
336
+ api.enhanceEndpoints({ endpoints: { postClientDrafts: { extraOptions: { bindToSession: true } } } });
337
+ ```
338
+
339
+ - The key must survive a token refresh: an account id or an app-side counter, never the access token (a refresh of
340
+ the same session would block the retry).
341
+ - `withDddExpectedSessionKey` carries the key in the header `x-ddd-expected-session-key`; the base query removes it
342
+ before sending. A `queryFn` can pass `{ expectedSessionKey }` as `extraOptions` instead.
343
+ - Treat `DDD_SESSION_CHANGED` like "not sent": a queued item stays queued for its own account.
344
+
313
345
  It runs inside the shared refresh, so concurrent failures trigger it once.
314
346
 
315
347
  ```ts
@@ -383,6 +415,8 @@ Idempotent; an existing symlink is repointed, a real file or directory is never
383
415
  | `type check failed — previous output restored` | Fix the reported type error (often app code using a renamed hook), or `--skip-tsc` to inspect |
384
416
  | A list does not refresh after a write | `<stem>Enhanced.ts` not imported; or the write has no tag — see section 3 |
385
417
  | A screen shows stale data after a write that changes more than its own entity | Writes invalidate by identity since 0.3 — add an `invalidation` resolver for that endpoint (section 3), or `broadInvalidation` for the 0.2 behaviour |
418
+ | After an account switch a queued request was stored under the new account | Bind it to its session: `getSessionKey` + `withDddExpectedSessionKey` (section 5) |
419
+ | `a request is bound to a session, pass getSessionKey` | The base query has no `getSessionKey` option |
386
420
  | A guest / device session logs out at the first 401 | It has no refresh token: pass `relogin` (section 5) |
387
421
  | `multipart body not generated (…flattenArg…)` | The endpoint's argument is the body itself; drop `flattenArg` for it or send the files with `upload()` |
388
422
  | An invalidation of a hand-written endpoint does nothing | Tag name in another case than the generated one: build `tagTypes` with `mergeDddTagTypes` (section 3) |
package/CHANGELOG.md CHANGED
@@ -1,5 +1,31 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.6.0
4
+
5
+ ### Changed
6
+ - codegen: path parameters are encoded in the generated URL (`encodeURIComponent(String(queryArg.x))`); the api
7
+ config option `encodePathParams` now defaults to `true`. A value with `/`, `?`, `#` or a space no longer changes
8
+ the route. **After regenerating, remove your own `encodeURIComponent()` around path arguments** — the value would
9
+ be encoded twice — or set `encodePathParams: false` for that api to keep the previous output.
10
+
11
+ ## 0.5.0
12
+
13
+ Requests can be bound to the session they were prepared for. Additive: without `getSessionKey` nothing changes.
14
+
15
+ ### Added
16
+ - api: option `getSessionKey` of `createDddBaseQuery` and three ways to bind a request to a session:
17
+ `withDddExpectedSessionKey(request, key)` in an endpoint's `query`, `expectedSessionKey` of an upload, and
18
+ `extraOptions: { bindToSession: true }` (the session that is current when the request starts;
19
+ `{ expectedSessionKey }` for a `queryFn`). A bound request is sent, and repeated after a refresh, only while that
20
+ session is the current one; otherwise it ends with the error of `isDddSessionChanged` (`DDD_SESSION_CHANGED`)
21
+ without a network call, a refresh or a logout. Type `DddSessionBindingOptions`, constant
22
+ `DDD_EXPECTED_SESSION_KEY_HEADER`.
23
+
24
+ ### Fixed by binding
25
+ - A request that waited for a running refresh, or was repeated after one, was sent with the token of whatever
26
+ session was current at that moment: after an account switch a body prepared for one account could be stored under
27
+ another. Bind requests whose body belongs to an account (offline queues, uploads, imports).
28
+
3
29
  ## 0.4.0
4
30
 
5
31
  File uploads, sessions without refresh token and typed cache tags. Minor release: the generated arguments of multipart
package/README.md CHANGED
@@ -99,6 +99,21 @@ queryFn: ({ file, onProgress }, api, extraOptions) =>
99
99
  createDddBaseQuery({ /* … */ relogin: async ({ reason, baseQuery, api, extraOptions }) => reopenGuestSession(baseQuery, api, extraOptions) });
100
100
  ```
101
101
 
102
+ ### Requests bound to a session
103
+
104
+ A request prepared for one account must not leave with another account's token after an account switch (the token is
105
+ read when the request is sent, after a running refresh, and again for the retry):
106
+
107
+ ```ts
108
+ createDddBaseQuery({ /* … */ getSessionKey: ({ getState }) => (getState() as RootState).auth.accountId });
109
+
110
+ query: ({ accountId, draft }) => withDddExpectedSessionKey({ url: '/api/client/drafts', method: 'POST', body: { draft } }, accountId),
111
+ ```
112
+
113
+ A bound request whose session is no longer the current one is not sent: `isDddSessionChanged(result.error)`. Uploads
114
+ take `expectedSessionKey`; `extraOptions: { bindToSession: true }` binds an endpoint's requests to the session they
115
+ start in.
116
+
102
117
  ### Typed cache tags
103
118
 
104
119
  ```ts
@@ -122,6 +122,11 @@ interface DddUploadRequest {
122
122
  onProgress?: (loaded: number, total: number) => void;
123
123
  /** Aborting cancels the request; the result is then the error of {@link isDddUploadAborted}. */
124
124
  signal?: AbortSignal;
125
+ /**
126
+ * Session this upload belongs to (see {@link DddBaseQueryOptions.getSessionKey}): it is only sent, and only
127
+ * repeated after a refresh, while that session is the current one.
128
+ */
129
+ expectedSessionKey?: string | number;
125
130
  }
126
131
  /** Result of an upload: the shape an RTK `queryFn` returns. */
127
132
  type DddUploadResult = {
@@ -150,6 +155,22 @@ type DddUploadingBaseQuery = DddBaseQuery & {
150
155
  declare const DDD_UPLOAD_ABORTED = "DDD_UPLOAD_ABORTED";
151
156
  /** True for the error of an upload that was cancelled through its `signal`. */
152
157
  declare const isDddUploadAborted: (error: unknown) => boolean;
158
+ /** `error.error` of a request that was not sent because it was bound to a session that is no longer the current one. */
159
+ declare const DDD_SESSION_CHANGED = "DDD_SESSION_CHANGED";
160
+ /** True for the error of a request that was not sent because its session is no longer the current one. */
161
+ declare const isDddSessionChanged: (error: unknown) => boolean;
162
+ /** Request header that carries the expected session key to the base query; it is removed before the request is sent. */
163
+ declare const DDD_EXPECTED_SESSION_KEY_HEADER = "x-ddd-expected-session-key";
164
+ /**
165
+ * `extraOptions` the base query reads: what binds the requests of an endpoint to a session (see
166
+ * {@link DddBaseQueryOptions.getSessionKey}).
167
+ */
168
+ interface DddSessionBindingOptions {
169
+ /** Binds each request to the session that is current when the request starts. */
170
+ bindToSession?: boolean;
171
+ /** Binds the request to this session (a `queryFn` passes it on to the base query). */
172
+ expectedSessionKey?: string | number;
173
+ }
153
174
  /** Options of {@link createDddBaseQuery}. */
154
175
  interface DddBaseQueryOptions {
155
176
  /** API origin, e.g. `https://api.example.com`. Request URLs are relative to it. */
@@ -160,6 +181,29 @@ interface DddBaseQueryOptions {
160
181
  setTokens: (tokens: DddTokens, api: BaseQueryApi) => MaybePromise<void>;
161
182
  /** Called once when the session cannot be recovered (no refresh token, or the refresh was rejected). */
162
183
  onLogout: (api: BaseQueryApi) => MaybePromise<void>;
184
+ /**
185
+ * Identifies the current session by a value that survives a token refresh: the account id, or a counter the app
186
+ * raises on every login and logout; `null` without a session. Never the access token: it changes with each refresh.
187
+ *
188
+ * With it a request can be bound to a session. A bound request is sent, and repeated after a refresh, only while
189
+ * that session is the current one; otherwise it is answered with the error of {@link isDddSessionChanged}, without
190
+ * a network call, a refresh or a logout. A request is bound by one of:
191
+ * - {@link withDddExpectedSessionKey} in the endpoint's `query` (the session the caller prepared the request for),
192
+ * - `expectedSessionKey` of an upload ({@link DddUploadRequest}),
193
+ * - `extraOptions: { bindToSession: true }` on the endpoint: the session that is current when the request starts.
194
+ *
195
+ * Requests that are not bound are sent as without this option.
196
+ *
197
+ * @example
198
+ * getSessionKey: ({ getState }) => (getState() as RootState).auth.accountId,
199
+ *
200
+ * // An endpoint whose body belongs to the account it was prepared for:
201
+ * saveDraft: build.mutation<void, { accountId: number; draft: Draft }>({
202
+ * query: ({ accountId, draft }) =>
203
+ * withDddExpectedSessionKey({ url: '/api/client/drafts', method: 'POST', body: { draft } }, accountId),
204
+ * }),
205
+ */
206
+ getSessionKey?: (context: DddRequestContext) => MaybePromise<string | number | null | undefined>;
163
207
  /** Custom refresh. Default: {@link createDddRefresh} on `refreshPath`. */
164
208
  refresh?: DddRefreshFn;
165
209
  /** Refresh endpoint for the default refresh, e.g. `/api/admin/common/auth/refresh`. Required without `refresh`. */
@@ -217,6 +261,12 @@ declare const defaultShouldRefresh: DddShouldRefresh;
217
261
  * Query-string serializer that skips `null` / `undefined` values (the generated SDK passes every optional parameter).
218
262
  */
219
263
  declare const dddParamsSerializer: (params: Record<string, unknown>) => string;
264
+ /**
265
+ * Binds a request to a session: the base query sends it, and repeats it after a refresh, only while
266
+ * `expectedSessionKey` is the key of the current session ({@link DddBaseQueryOptions.getSessionKey}). The key travels
267
+ * in a request header that the base query removes before sending.
268
+ */
269
+ declare const withDddExpectedSessionKey: (request: string | FetchArgs, expectedSessionKey: string | number) => FetchArgs;
220
270
  /**
221
271
  * Creates the RTK Query base query for a DDD backend.
222
272
  *
@@ -227,6 +277,7 @@ declare const dddParamsSerializer: (params: Record<string, unknown>) => string;
227
277
  * - No refresh token, or a rejected refresh → `relogin()` when given; without it, or when it returns `null`,
228
278
  * `onLogout()` once for that session and the original error is returned.
229
279
  * - A refresh whose session was logged out or replaced while it ran is discarded (no `setTokens`, no retry).
280
+ * - A request bound to a session (`getSessionKey`) is not sent once another session is the current one.
230
281
  *
231
282
  * @example
232
283
  * export const baseApi = createApi({
@@ -395,5 +446,5 @@ declare function createAuthEndpoints<Definitions extends EndpointDefinitions, Re
395
446
  authRefresh: _reduxjs_toolkit_query.MutationDefinition<DddRefreshRequest, DddBaseQuery, TagTypes, DddAuthResponse, ReducerPath, unknown>;
396
447
  }, ReducerPath, TagTypes, Enhancers>;
397
448
 
398
- export { DDD_MULTIPART_BODY_FIELD, DDD_UPLOAD_ABORTED, DEFAULT_ERROR_MESSAGE, DEFAULT_ERROR_MESSAGES, DddTokens, applyDebugParams, blobResponseHandler, buildDddFormData, buildDddMultipartBody, createAuthEndpoints, createDddBaseQuery, createDddRefresh, createDownloadResponseHandler, dddParamsSerializer, defaultShouldRefresh, downloadBlob, filenameFromContentDisposition, getErrorMessage, getErrorStatus, getRequestUrl, hasDddMultipartFiles, isDddAuthRequest, isDddUploadAborted, mergeDddTagTypes, normalizeDddError, readDebugFlags };
399
- export type { DddAuthEndpointsOptions, DddBaseQuery, DddBaseQueryOptions, DddDebugFlags, DddDebugOptions, DddDownloadedFile, DddErrorMessages, DddFilePart, DddFileResponse, DddHeadersContext, DddMultipartFiles, DddNormalizedError, DddRawBaseQuery, DddRefreshContext, DddRefreshFn, DddReloginContext, DddReloginFn, DddRequestContext, DddShouldRefresh, DddUploadRequest, DddUploadResult, DddUploadingBaseQuery };
449
+ export { DDD_EXPECTED_SESSION_KEY_HEADER, DDD_MULTIPART_BODY_FIELD, DDD_SESSION_CHANGED, DDD_UPLOAD_ABORTED, DEFAULT_ERROR_MESSAGE, DEFAULT_ERROR_MESSAGES, DddTokens, applyDebugParams, blobResponseHandler, buildDddFormData, buildDddMultipartBody, createAuthEndpoints, createDddBaseQuery, createDddRefresh, createDownloadResponseHandler, dddParamsSerializer, defaultShouldRefresh, downloadBlob, filenameFromContentDisposition, getErrorMessage, getErrorStatus, getRequestUrl, hasDddMultipartFiles, isDddAuthRequest, isDddSessionChanged, isDddUploadAborted, mergeDddTagTypes, normalizeDddError, readDebugFlags, withDddExpectedSessionKey };
450
+ export type { DddAuthEndpointsOptions, DddBaseQuery, DddBaseQueryOptions, DddDebugFlags, DddDebugOptions, DddDownloadedFile, DddErrorMessages, DddFilePart, DddFileResponse, DddHeadersContext, DddMultipartFiles, DddNormalizedError, DddRawBaseQuery, DddRefreshContext, DddRefreshFn, DddReloginContext, DddReloginFn, DddRequestContext, DddSessionBindingOptions, DddShouldRefresh, DddUploadRequest, DddUploadResult, DddUploadingBaseQuery };
package/dist/api/index.js CHANGED
@@ -70,23 +70,43 @@ function createDddRefresh(path) {
70
70
  // src/api/baseQuery.ts
71
71
  var DDD_UPLOAD_ABORTED = "DDD_UPLOAD_ABORTED";
72
72
  var isDddUploadAborted = (error) => !!error && typeof error === "object" && error.status === "CUSTOM_ERROR" && error.error === DDD_UPLOAD_ABORTED;
73
+ var DDD_SESSION_CHANGED = "DDD_SESSION_CHANGED";
74
+ var isDddSessionChanged = (error) => !!error && typeof error === "object" && error.status === "CUSTOM_ERROR" && error.error === DDD_SESSION_CHANGED;
75
+ var DDD_EXPECTED_SESSION_KEY_HEADER = "x-ddd-expected-session-key";
73
76
  var getRequestUrl = (request) => typeof request === "string" ? request : request.url;
74
77
  var isDddAuthRequest = (request) => getRequestUrl(request).includes("/common/auth/");
75
78
  var defaultShouldRefresh = (error, request) => error.status === 401 && !isDddAuthRequest(request);
76
79
  var dddParamsSerializer = (params) => Object.entries(params).filter(([, value]) => value !== null && value !== void 0).map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(String(value))}`).join("&");
77
80
  var toFetchArgs = (args) => typeof args === "string" ? { url: args } : args;
78
- var withBearer = (args, accessToken) => {
79
- if (!accessToken) return args;
81
+ var toHeaders = (source) => {
80
82
  const headers = new Headers();
81
- const source = args.headers;
82
83
  if (source instanceof Headers) source.forEach((value, key) => headers.set(key, value));
83
84
  else if (Array.isArray(source)) source.forEach(([key, value]) => key !== void 0 && headers.set(key, value ?? ""));
84
85
  else if (source) Object.entries(source).forEach(([key, value]) => value !== void 0 && headers.set(key, value));
86
+ return headers;
87
+ };
88
+ var withBearer = (args, accessToken) => {
89
+ if (!accessToken) return args;
90
+ const headers = toHeaders(args.headers);
85
91
  if (!headers.has("authorization")) headers.set("authorization", `Bearer ${accessToken}`);
86
92
  return { ...args, headers };
87
93
  };
94
+ var withDddExpectedSessionKey = (request, expectedSessionKey) => {
95
+ const args = toFetchArgs(request);
96
+ const headers = toHeaders(args.headers);
97
+ headers.set(DDD_EXPECTED_SESSION_KEY_HEADER, String(expectedSessionKey));
98
+ return { ...args, headers };
99
+ };
100
+ var takeExpectedSessionKey = (args) => {
101
+ if (!args.headers) return { request: args, expectedSessionKey: null };
102
+ const headers = toHeaders(args.headers);
103
+ const expectedSessionKey = headers.get(DDD_EXPECTED_SESSION_KEY_HEADER);
104
+ if (expectedSessionKey === null) return { request: args, expectedSessionKey: null };
105
+ headers.delete(DDD_EXPECTED_SESSION_KEY_HEADER);
106
+ return { request: { ...args, headers }, expectedSessionKey };
107
+ };
88
108
  function createDddBaseQuery(options) {
89
- const { getTokens, setTokens, onLogout, headers: headersHook, languageCode, fetchOptions, relogin } = options;
109
+ const { getTokens, setTokens, onLogout, getSessionKey, headers: headersHook, languageCode, fetchOptions, relogin } = options;
90
110
  const shouldRefresh = options.shouldRefresh ?? defaultShouldRefresh;
91
111
  if (!options.refresh && !options.refreshPath) {
92
112
  throw new Error("createDddBaseQuery: pass either `refresh` or `refreshPath`.");
@@ -112,6 +132,21 @@ function createDddBaseQuery(options) {
112
132
  let lastOutcome = null;
113
133
  let inflight = null;
114
134
  const currentAccessToken = async (api) => (await getTokens(api))?.accessToken ?? null;
135
+ const currentSessionKey = async (api) => {
136
+ const sessionKey = await getSessionKey(api);
137
+ return sessionKey === null || sessionKey === void 0 ? null : String(sessionKey);
138
+ };
139
+ const resolveBoundSessionKey = async (requestSessionKey, api, extraOptions) => {
140
+ const binding = extraOptions ?? {};
141
+ const expectedSessionKey = requestSessionKey ?? binding.expectedSessionKey ?? null;
142
+ if (expectedSessionKey === null && !binding.bindToSession) return void 0;
143
+ if (!getSessionKey) {
144
+ throw new Error("createDddBaseQuery: a request is bound to a session, pass `getSessionKey`.");
145
+ }
146
+ return expectedSessionKey === null ? currentSessionKey(api) : String(expectedSessionKey);
147
+ };
148
+ const isBoundSessionCurrent = async (boundSessionKey, api) => boundSessionKey === void 0 || await currentSessionKey(api) === boundSessionKey;
149
+ const sessionChanged = { error: { status: "CUSTOM_ERROR", error: DDD_SESSION_CHANGED } };
115
150
  const runRefresh = async (api, extraOptions) => {
116
151
  const before = await getTokens(api);
117
152
  const refreshToken = before?.refreshToken ?? null;
@@ -152,14 +187,20 @@ function createDddBaseQuery(options) {
152
187
  if (inflight) await inflight;
153
188
  return lastOutcome;
154
189
  };
190
+ const sendRequest = async (request, boundSessionKey, api, extraOptions) => {
191
+ const authorizedRequest = withBearer(request, await currentAccessToken(api));
192
+ if (!await isBoundSessionCurrent(boundSessionKey, api)) return sessionChanged;
193
+ return rawBaseQuery(authorizedRequest, api, extraOptions);
194
+ };
155
195
  const baseQuery = async (args, api, extraOptions) => {
196
+ const { request, expectedSessionKey } = takeExpectedSessionKey(toFetchArgs(args));
197
+ const boundSessionKey = await resolveBoundSessionKey(expectedSessionKey, api, extraOptions);
156
198
  while (inflight) await inflight.catch(() => void 0);
157
199
  const startGeneration = generation;
158
- const request = toFetchArgs(args);
159
- const result = await rawBaseQuery(withBearer(request, await currentAccessToken(api)), api, extraOptions);
160
- if (!result.error || !shouldRefresh(result.error, request)) return result;
200
+ const result = await sendRequest(request, boundSessionKey, api, extraOptions);
201
+ if (!result.error || isDddSessionChanged(result.error) || !shouldRefresh(result.error, request)) return result;
161
202
  if (await recover(startGeneration, api, extraOptions) !== "refreshed") return result;
162
- return rawBaseQuery(withBearer(request, await currentAccessToken(api)), api, extraOptions);
203
+ return sendRequest(request, boundSessionKey, api, extraOptions);
163
204
  };
164
205
  const uploadHeaders = async (request, api, extraOptions) => {
165
206
  const headers = new Headers();
@@ -179,8 +220,9 @@ function createDddBaseQuery(options) {
179
220
  if (debugOptions && readDebugFlags(debugOptions).debug) headers.set("x-debug", "true");
180
221
  return await headersHook?.(headers, context) ?? headers;
181
222
  };
182
- const sendUpload = async (request, api, extraOptions) => {
223
+ const sendUpload = async (request, boundSessionKey, api, extraOptions) => {
183
224
  const headers = await uploadHeaders(request, api, extraOptions);
225
+ if (!await isBoundSessionCurrent(boundSessionKey, api)) return sessionChanged;
184
226
  const query = request.params ? dddParamsSerializer(request.params) : "";
185
227
  const url = `${options.baseUrl.replace(/\/+$/, "")}/${request.url.replace(/^\/+/, "")}${query ? `${request.url.includes("?") ? "&" : "?"}${query}` : ""}`;
186
228
  return new Promise((resolve) => {
@@ -218,12 +260,14 @@ function createDddBaseQuery(options) {
218
260
  });
219
261
  };
220
262
  const upload = async (request, api, extraOptions) => {
263
+ const boundSessionKey = await resolveBoundSessionKey(request.expectedSessionKey, api, extraOptions);
221
264
  while (inflight) await inflight.catch(() => void 0);
222
265
  const startGeneration = generation;
223
- const result = await sendUpload(request, api, extraOptions);
224
- if (!result.error || !shouldRefresh(result.error, { url: request.url, method: request.method ?? "POST" })) return result;
266
+ const result = await sendUpload(request, boundSessionKey, api, extraOptions);
267
+ if (!result.error || isDddSessionChanged(result.error)) return result;
268
+ if (!shouldRefresh(result.error, { url: request.url, method: request.method ?? "POST" })) return result;
225
269
  if (await recover(startGeneration, api, extraOptions) !== "refreshed") return result;
226
- return sendUpload(request, api, extraOptions);
270
+ return sendUpload(request, boundSessionKey, api, extraOptions);
227
271
  };
228
272
  return Object.assign(baseQuery, { upload });
229
273
  }
@@ -379,7 +423,9 @@ function createAuthEndpoints(api, options) {
379
423
  });
380
424
  }
381
425
  export {
426
+ DDD_EXPECTED_SESSION_KEY_HEADER,
382
427
  DDD_MULTIPART_BODY_FIELD,
428
+ DDD_SESSION_CHANGED,
383
429
  DDD_UPLOAD_ABORTED,
384
430
  DEFAULT_ERROR_MESSAGE,
385
431
  DEFAULT_ERROR_MESSAGES,
@@ -400,9 +446,11 @@ export {
400
446
  getRequestUrl,
401
447
  hasDddMultipartFiles,
402
448
  isDddAuthRequest,
449
+ isDddSessionChanged,
403
450
  isDddUploadAborted,
404
451
  mergeDddTagTypes,
405
452
  normalizeDddError,
406
- readDebugFlags
453
+ readDebugFlags,
454
+ withDddExpectedSessionKey
407
455
  };
408
456
  //# sourceMappingURL=index.js.map