@mgamadeus/ddd-web 0.15.0 → 0.16.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: openapi-config.ts with defineConfig (schemaFile, sideEffects, responseHandlers, invalidation), the RTK Query SDK from ddd-web-sdk (Enhanced/Tags files, cache tags by entity identity, mergeDddTagTypes, blobResponseHandler downloads, multipartFiles uploads, upload/download progress via baseQuery.upload), QueryOptions builders (buildQueryOptions, combineFilters, buildInFilter), createDddBaseQuery (Bearer, shared refresh + retry, relogin, session-bound requests, shouldRefresh, normalizeDddError), token storage, JWT helpers, foreign global Request (MooTools: dddFetchApiRequestPlugin), link-skills, release. Use when wiring a frontend to a DDD backend, regenerating the SDK, building filters, uploading files, FormData, upload or download progress, fixing token refresh, guest login, a request sent under the wrong account after a switch, stale cache tags, downloading an export, requests failing in a legacy page, or releasing ddd-web."
3
+ description: "Use and maintain @mgamadeus/ddd-web, the TS client of mgamadeus/ddd: openapi-config.ts defineConfig (schemaFile, sideEffects, responseHandlers, invalidation), the RTK Query SDK from ddd-web-sdk (cache tags by entity identity, mergeDddTagTypes, blob downloads, multipartFiles uploads, progress via baseQuery.upload), QueryOptions builders, createDddBaseQuery (Bearer, shared refresh + retry, relogin, session-bound requests, normalizeDddError), token storage, JWT helpers, foreign global Request (MooTools: dddFetchApiRequestPlugin), the client-errors reporter /issues (browser, Node, React Native), link-skills, release. Use when wiring a frontend to a DDD backend, regenerating the SDK, building filters, uploading files, FormData, upload or download progress, fixing token refresh, guest login, a request sent under the wrong account after a switch, stale cache tags, downloading an export, requests failing in a legacy page, reporting web, server or mobile errors to the issues log, or releasing ddd-web."
4
4
  metadata:
5
5
  author: mgamadeus
6
- version: "1.4.2"
6
+ version: "1.5.0"
7
7
  package: "@mgamadeus/ddd-web"
8
8
  ---
9
9
 
@@ -24,6 +24,10 @@ frontend code. No UI components, no domain logic — apps bring their own design
24
24
  | `@mgamadeus/ddd-web/api` | needs `@reduxjs/toolkit` 2 (peer) | `createDddBaseQuery` (+ `upload()`, `relogin`, `getSessionKey`), `createDddRefresh`, `normalizeDddError`, downloads, multipart (`buildDddMultipartBody`), `mergeDddTagTypes`, `createAuthEndpoints` |
25
25
  | `@mgamadeus/ddd-web/auth` | anywhere | `TokenStorage` adapters, `decodeJwt`, `isExpired`, SSR-safe storage |
26
26
  | `@mgamadeus/ddd-web/contract` | types + small helpers | `x-ddd-*` types, error body, DDD date-time, translations, operators, `normalizeDddError` / `getErrorMessage` / `getErrorStatus` (also without RTK) |
27
+ | `@mgamadeus/ddd-web/issues` | anywhere (no DOM, no Node API: browser, Node, React Native) | client-errors reporter core: `createIssuesReporter`, normalise, redact, fingerprint, limits, drop rules, breadcrumbs, `buildRoutePattern` / `createIssuesRouteTracker`, `createFetchIssuesTransport` |
28
+ | `@mgamadeus/ddd-web/issues/browser` | browser | `createBrowserIssuesReporter`, `installBrowserIssueCapture`, `createBeaconIssuesTransport`, `createBrowserIssuesRouteTracker`, `captureRenderError` |
29
+ | `@mgamadeus/ddd-web/issues/node` | Node ≥ 20 | `createNodeIssuesReporter`, `createServerRequestErrorHandler` (`onRequestError` shape), `installNodeIssueCapture` |
30
+ | `@mgamadeus/ddd-web/issues/wire` | types + adapter | the `ClientIssueReport` wire types, `dddIssuesWireAdapter`, `DDD_ISSUES_REPORT_PATH` |
27
31
 
28
32
  ESM only, Node ≥ 20. Consumers may use npm or pnpm.
29
33
 
@@ -116,10 +120,15 @@ const { data } = useGetApiAdminLibraryBooksListQuery({
116
120
  `invalidation` resolver in the config (`broadInvalidation` = the 0.2 behaviour). A spec without
117
121
  `info.x-ddd-contract` is read as a pre-contract DDD spec (warning); an unsupported contract number aborts.
118
122
 
123
+ - **Client errors go through `/issues`** to the application's client-errors endpoint (`logClientIssue`, Core ≥ 3.10.0):
124
+ one reporter per runtime, the route PATTERN set on every navigation, never a hand-written `window.onerror` + `fetch`.
125
+ Keep `/issues` free of DOM and Node APIs (`tsconfig.issues-core.json` checks it); platform code goes into
126
+ `/issues/browser` or `/issues/node`.
127
+
119
128
  ## References
120
129
 
121
130
  - [references/consumer.md](references/consumer.md) — every config option, CLI flag, generated file and cache-tag rule;
122
- the query builders and validators; base query, refresh, errors, downloads; token storage; contract helpers;
123
- troubleshooting.
131
+ the query builders and validators; base query, refresh, errors, downloads; the client-errors reporter; token storage;
132
+ contract helpers; troubleshooting.
124
133
  - [references/maintaining.md](references/maintaining.md) — repository layout, build and tests, the consumer check, the
125
134
  `x-ddd` contract and how it stays in step with `mgamadeus/ddd`, release workflow, versioning.
@@ -11,6 +11,7 @@
11
11
  7. Contract helpers (`/contract`)
12
12
  8. Agent skills (`link-skills`)
13
13
  5a. Pages with a foreign global `Request` (`/fetch-api-request`, `/vite`)
14
+ 5b. Client errors (`/issues`, `/issues/browser`, `/issues/node`, `/issues/wire`)
14
15
  9. Troubleshooting
15
16
 
16
17
  ## 1. Configuration (`openapi-config.ts`)
@@ -412,6 +413,98 @@ export default defineConfig({ plugins: [react(), dddFetchApiRequestPlugin()] });
412
413
  - `isFetchApiRequest` / `isFetchApiRequestConstructor` check the `[object Request]` tag, not `instanceof`: a request from
413
414
  the frame is no instance of the page's `Request`.
414
415
 
416
+ ## 5b. Client errors (`/issues`, `/issues/browser`, `/issues/node`, `/issues/wire`)
417
+
418
+ One reporter for a browser, the app's Node server and a React Native app. It sends to the client-errors endpoint of
419
+ a mgamadeus/ddd backend: the application's controller hands the body to `IssuesLogService::logClientIssue()` (Core
420
+ 3.10.0 or newer), and the events land in the issues log with the backend's errors (sections WEB, WEB_SERVER).
421
+
422
+ **Server contract.** `POST` (default path `DDD_ISSUES_REPORT_PATH` = `/api/public/common/issues/report`, the route of
423
+ the issues-log guide; the application owns it) with the body `{ report: { client, events } }`:
424
+ `client` = `ClientIssueContext` (`runtime` `browser` · `node` · `react-native`, `app`, `release`, `tabId`,
425
+ `userAgent` (node / RN only), `viewportWidth`, `viewportHeight`, `locale`); `events.elements` = 1–10
426
+ `ClientIssueEvent` (`occurredAt`, `kind` `error` · `unhandledrejection` · `react-render` · `server-request` · `manual`,
427
+ `level` `error` · `warning`, `name`, `message`, `frames.elements` (innermost first), `rawStack` (only without frames),
428
+ `url`, `routePattern`, `requestMethod`, `httpStatus`, `breadcrumbs.elements`, `tags.elements`, `count`,
429
+ `clientFingerprint`). Answer: `ClientIssueIngestResult` (`accepted`, `dropped`, `dropReasons`). Headers:
430
+ `Authorization: Bearer …` when `getAuthorization` returns a token (the controller attributes the account), the server
431
+ token (`X-Issues-Server-Token` by default, `serverTokenHeader`) from the app's own server (section WEB_SERVER). The
432
+ reporter's caps equal the backend's; the backend enforces them again.
433
+
434
+ **Browser** (in the client entry, before hydration):
435
+
436
+ ```ts
437
+ import { createBrowserIssuesReporter, installBrowserIssueCapture, captureRenderError } from '@mgamadeus/ddd-web/issues/browser';
438
+
439
+ export const issuesReporter = createBrowserIssuesReporter({
440
+ app: 'web',
441
+ endpoint: `${apiBaseUrl}/api/public/common/issues/report`, // default: that path on the page's origin
442
+ release: () => document.documentElement.dataset.release ?? null, // the key the source maps are uploaded under
443
+ getAuthorization: () => tokenStorage.read().accessToken, // or later: issuesReporter.setAuthorizationReader(…)
444
+ }); // null during SSR
445
+ if (issuesReporter) installBrowserIssueCapture(issuesReporter); // error, unhandledrejection, breadcrumbs, pagehide flush
446
+
447
+ // error boundary: an error with a `digest` came from the server and is reported there
448
+ captureRenderError(issuesReporter, error);
449
+ ```
450
+
451
+ Route tracking: `createBrowserIssuesRouteTracker(reporter).trackRoute(pathname, params)` on every route change (e.g.
452
+ an effect on the router's path and params). It sets the route PATTERN (`/books/[bookId]`), which names the issue on
453
+ the backend, and adds a navigation breadcrumb.
454
+
455
+ **Node server:**
456
+
457
+ ```ts
458
+ import { createNodeIssuesReporter, createServerRequestErrorHandler } from '@mgamadeus/ddd-web/issues/node';
459
+
460
+ const serverIssuesReporter = createNodeIssuesReporter({
461
+ app: 'web',
462
+ apiBaseUrl: process.env.API_INTERNAL_URL, // + DDD_ISSUES_REPORT_PATH
463
+ serverToken: process.env.ISSUES_INGEST_SERVER_TOKEN, // → section WEB_SERVER
464
+ release: () => process.env.WEB_RELEASE ?? null,
465
+ });
466
+ export const onRequestError = createServerRequestErrorHandler(() => serverIssuesReporter); // Next.js instrumentation.ts
467
+ ```
468
+
469
+ `installNodeIssueCapture(reporter)` adds `uncaughtExceptionMonitor` (observes only) and a flush on `beforeExit`;
470
+ `{ unhandledRejections: true }` also reports rejections — that listener stops Node from exiting on one.
471
+
472
+ **React Native / anything else:** the core directly, with `createFetchIssuesTransport()`:
473
+
474
+ ```ts
475
+ import { createIssuesReporter, createFetchIssuesTransport, createIssuesRouteTracker } from '@mgamadeus/ddd-web/issues';
476
+
477
+ const reporter = createIssuesReporter({
478
+ runtime: 'react-native', app: 'mobile',
479
+ endpoint: () => `${apiBaseUrl}/api/public/common/issues/report`,
480
+ transport: createFetchIssuesTransport({ timeoutMs: 10_000 }),
481
+ context: () => ({ release: appVersion, userAgent: `ExampleApp/${appVersion} (${platform})`, locale }),
482
+ });
483
+ ErrorUtils.setGlobalHandler((error) => reporter.captureError(error, 'error'));
484
+ ```
485
+
486
+ Behaviour:
487
+ - **Redaction** before anything leaves the device: token path segments (default = the backend's
488
+ `redactPathSegments`; `createIssuesRedactor({ tokenPathSegments, additionalRules })` for the app's own), `*token*`
489
+ query values, e-mails, bearer / JWT tokens, UUIDs, international phone numbers, long hex path segments.
490
+ - **Drops** what the backend drops anyway (chunk loads, `Script error.`, `ResizeObserver loop`) plus extension errors,
491
+ `window.ethereum`, `AbortError` and automated browsers; `dropRules: [...ISSUE_DROP_RULES, own]` extends the list.
492
+ - **De-duplication:** a repeat of a queued event raises its `count`; `clientFingerprint` = `name | normalised message
493
+ | top frame` (informational — the backend builds its own hashes).
494
+ - **Caps:** `rateLimitMode` `session` (browser default: 3 per fingerprint, 25 per page session, stop after 3 failed
495
+ sends) or `windowed` (node / react-native default: 3 per fingerprint per 5 min, 60 per minute, exponential backoff).
496
+ Batches of ≤ 10 events / 48 KB after 2 s or at 5 events; an event over 16 KB loses breadcrumbs, then frames beyond
497
+ 10, the raw stack and the message beyond 256 characters. One retry on a network error or 5xx, none on a 4xx.
498
+ `limits` overrides any of it.
499
+ - **Breadcrumbs** (≤ 20, newest kept): failed requests, `console.error`, clicks (`data-issues-action`, else tag and
500
+ role — never text), navigations; not attached on `node` (a server's trail mixes requests).
501
+ - **Transports:** browser = fetch with `keepalive`, `credentials: 'omit'`, the fetch from before the capture wrapped
502
+ it; on `flush({ unloading: true })` a beacon (`text/plain`, no preflight) unless the request carries `Authorization`
503
+ or a server token (a beacon has no headers).
504
+ - **Typed body from the app's own SDK:** pass `wire: { toWireEvent, toRequestBody }` built from the generated
505
+ `ClientIssueEvent` / request DTO models; the default `dddIssuesWireAdapter` writes the same shape.
506
+ - The reporter never throws into its caller and never reports its own failures.
507
+
415
508
  ## 6. Tokens (`/auth`)
416
509
 
417
510
  - `TokenStorage` = `read()` / `write({ accessToken?, refreshToken? })` (`undefined` keeps, `null` removes) /
@@ -19,6 +19,10 @@ src/
19
19
  definition-driven validators (definition.ts) — no React, no RTK
20
20
  api/ createDddBaseQuery, refresh coordination, errors, downloads, debug passthrough, auth endpoints
21
21
  auth/ token storage adapters, JWT helpers, SSR-safe storage
22
+ issues/ client-errors reporter: core (capture model, normalize, redact, fingerprint, limits, filters,
23
+ breadcrumbs, route pattern, transport, reporter) — no DOM, no Node API, checked by
24
+ tsconfig.issues-core.json and test/issues/core-without-dom.test.ts; wire/ (DDD ClientIssueReport shape),
25
+ browser/, node/ (adapters)
22
26
  codegen/ cli.ts (bins), config.ts (defineConfig, loadConfig), generate.ts (pipeline), spec.ts (load + validate),
23
27
  registry / models / rtk / endpoints / enhance / tags / response-handlers (text + file detection,
24
28
  AST-based injection that aborts on a miss) / repair / output (atomic commit),
package/CHANGELOG.md CHANGED
@@ -1,5 +1,28 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.16.0
4
+
5
+ ### Added
6
+ - Client-errors reporter for the issues log of a mgamadeus/ddd backend (`IssuesLogService::logClientIssue`, Core
7
+ 3.10.0 or newer; body `{ report: { client, events } }` of the `ClientIssueReport` value objects, default path
8
+ `/api/public/common/issues/report`):
9
+ - `@mgamadeus/ddd-web/issues`: the platform-free core — `createIssuesReporter` (redact, drop, de-duplicate by
10
+ `clientFingerprint` into `count`, session or windowed caps, batching ≤ 10 events / 48 KB, size shrinking, one retry,
11
+ backoff, bearer and server-token headers), `normalizeError` / `parseStack` (V8, SpiderMonkey, JavaScriptCore),
12
+ `createIssuesRedactor` / `redactUrl` / `redactText`, `buildClientFingerprint`, `ISSUES_LIMITS` /
13
+ `mergeIssuesLimits`, `ISSUE_DROP_RULES` / `findIssueDropRule`, breadcrumb builders and trail, `buildRoutePattern`
14
+ / `createIssuesRouteTracker`, `createFetchIssuesTransport`. No DOM, no Node API, no global read at import time:
15
+ loads in React Native.
16
+ - `@mgamadeus/ddd-web/issues/browser`: `createBrowserIssuesReporter`, `installBrowserIssueCapture` (uncaught errors,
17
+ unhandled rejections; breadcrumbs from failed requests, `console.error` and clicks; flush on `pagehide`),
18
+ `createBeaconIssuesTransport`, `createBrowserIssuesRouteTracker`, `captureRenderError`, `readOrCreateIssuesTabId`.
19
+ - `@mgamadeus/ddd-web/issues/node`: `createNodeIssuesReporter`, `createServerRequestErrorHandler` (the shape of an
20
+ `onRequestError` hook), `installNodeIssueCapture`.
21
+ - `@mgamadeus/ddd-web/issues/wire`: the wire types (`DddClientIssueReport`, `DddClientIssueEvent`, …,
22
+ `DddClientIssueIngestResult`), `dddIssuesWireAdapter`, `DDD_ISSUES_REPORT_PATH`.
23
+ - `pnpm typecheck` also checks the issues core without the DOM lib and without Node types
24
+ (`tsconfig.issues-core.json`).
25
+
3
26
  ## 0.15.0
4
27
 
5
28
  ### Added
package/README.md CHANGED
@@ -17,6 +17,8 @@ those conventions into frontend code:
17
17
  file downloads
18
18
  - **auth**: token-pair utilities and a pluggable storage adapter
19
19
  - **contract**: TypeScript types for the DDD wire format
20
+ - **issues**: a client-errors reporter for browsers, Node servers and React Native apps that sends to the backend's
21
+ issues log
20
22
 
21
23
  It contains no UI components and no domain logic; apps bring their own design system and business screens.
22
24
  Works with the OpenAPI output of current mgamadeus/ddd backends. The `x-ddd-*` extensions (contract version 1) are used
@@ -48,8 +50,9 @@ pnpm exec ddd-web-sdk # generate the SDK
48
50
  pnpm exec ddd-web link-skills # link the package's agent skills into .claude/skills
49
51
  ```
50
52
 
51
- Subpaths: `@mgamadeus/ddd-web/codegen`, `/query`, `/api`, `/auth`, `/contract`, `/fetch-api-request` and `/vite`
52
- (pages whose global `Request` is not the Fetch API's, e.g. MooTools or Prototype: `dddFetchApiRequestPlugin()`).
53
+ Subpaths: `@mgamadeus/ddd-web/codegen`, `/query`, `/api`, `/auth`, `/contract`, `/fetch-api-request`, `/vite`
54
+ (pages whose global `Request` is not the Fetch API's, e.g. MooTools or Prototype: `dddFetchApiRequestPlugin()`) and
55
+ `/issues`, `/issues/browser`, `/issues/node`, `/issues/wire` (client errors, below).
53
56
 
54
57
  ### File downloads
55
58
 
@@ -146,6 +149,51 @@ export default defineConfig({
146
149
  });
147
150
  ```
148
151
 
152
+ ### Client errors
153
+
154
+ `@mgamadeus/ddd-web/issues` reports the errors of a browser, the app's Node server or a React Native app to the
155
+ client-errors endpoint of a mgamadeus/ddd backend (`IssuesLogService::logClientIssue`, Core 3.10.0 or newer; the
156
+ application declares the route, by default `POST /api/public/common/issues/report`). The core has no DOM, framework
157
+ or Node dependency; the platform adapters are separate entries.
158
+
159
+ ```ts
160
+ // browser, before hydration
161
+ import {
162
+ createBrowserIssuesReporter,
163
+ createBrowserIssuesRouteTracker,
164
+ installBrowserIssueCapture,
165
+ } from '@mgamadeus/ddd-web/issues/browser';
166
+
167
+ const issuesReporter = createBrowserIssuesReporter({
168
+ app: 'web',
169
+ endpoint: 'https://api.example.com/api/public/common/issues/report',
170
+ release: () => document.documentElement.dataset.release ?? null,
171
+ getAuthorization: () => tokenStorage.read().accessToken,
172
+ });
173
+ if (issuesReporter) installBrowserIssueCapture(issuesReporter); // uncaught errors, rejections, breadcrumbs, unload flush
174
+ const issuesRouteTracker = issuesReporter && createBrowserIssuesRouteTracker(issuesReporter);
175
+
176
+ // on every route change: the route PATTERN names the issue on the backend
177
+ issuesRouteTracker?.trackRoute(pathname, params); // → /books/[bookId]
178
+ ```
179
+
180
+ ```ts
181
+ // Node server (e.g. Next.js instrumentation.ts)
182
+ import { createNodeIssuesReporter, createServerRequestErrorHandler } from '@mgamadeus/ddd-web/issues/node';
183
+
184
+ const serverIssuesReporter = createNodeIssuesReporter({
185
+ app: 'web',
186
+ apiBaseUrl: process.env.API_INTERNAL_URL,
187
+ serverToken: process.env.ISSUES_INGEST_SERVER_TOKEN, // the backend files these as WEB_SERVER
188
+ });
189
+ export const onRequestError = createServerRequestErrorHandler(() => serverIssuesReporter);
190
+ ```
191
+
192
+ React Native and other runtimes use `createIssuesReporter` from `/issues` with `createFetchIssuesTransport()`.
193
+ Everything is redacted on the device (tokens in paths and queries, e-mails, bearer / JWT tokens, UUIDs, phone numbers),
194
+ known noise is dropped, repeats are folded into `count`, and caps, batching, retry and backoff keep a broken page from
195
+ flooding the endpoint. Details: the agent skill, `references/consumer.md` › Client errors.
196
+
149
197
  ## Agent skill
150
198
 
151
199
  The package ships the agent skill `ddd-web-specialist` (consumer guide + maintaining guide). Link it into an app's