@sincpro/web-framework 3.9.0 → 3.11.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.
package/README.md CHANGED
@@ -399,7 +399,7 @@ and where the context lives, once, in `main`; without them, everything runs the
399
399
  ```ts
400
400
  // entrypoints/main.tsx
401
401
  import { configureProcess, processContext } from "@sincpro/client-framework";
402
- import { glitchtipReporter } from "@sincpro/web-framework/errors"; // optional
402
+ import { glitchtipReporter, reportUncaught } from "@sincpro/web-framework/errors"; // optional
403
403
  import { browserTracer } from "@sincpro/web-framework/telemetry"; // optional
404
404
 
405
405
  const release = "my-app:1.0.0"; // <name>:<version>, the backend's APP_RELEASE
@@ -408,9 +408,15 @@ configureProcess({
408
408
  tracer: browserTracer({ endpoint: settings.otlp, release }),
409
409
  reporter: glitchtipReporter({ dsn: settings.glitchtip, release }),
410
410
  });
411
+ reportUncaught(); // optional: what nobody caught — a click handler, a promise nobody waited for
411
412
  processContext.set({ tenant_id: session.tenant }); // every use case runs with it and sends it
412
413
  ```
413
414
 
415
+ `reportUncaught()` listens to `window`'s `error` and `unhandledrejection` and hands each to the
416
+ process's `reportError`: a cancellation or a refusal is not a fault, and a use case's failure
417
+ already reported is not reported again. Without it, only what the process decides is unexpected
418
+ reaches the reporter, as before.
419
+
414
420
  ```tsx
415
421
  function CloseButton({ issueId }: { issueId: string }) {
416
422
  const close = useService(project.Issues.close); // run · busy · answer · error
@@ -488,6 +494,28 @@ const balance = useServiceReading(project.Accounts.balance, [{ member_id: member
488
494
  });
489
495
  ```
490
496
 
497
+ A record screen starts the same way. `readRecordOnServer` reads the record and its model with the
498
+ transport the provider is given — plain JSON (`RecordRead`), `undefined` and one line on the log
499
+ when it fails — and `useRecord` starts `ready` from it (so do `useRecordScreen` and
500
+ `EntityRecord`, by `initial`): the HTML carries the record, not a skeleton, and the browser asks
501
+ nothing for it on mount. Only for the record it was read for; editing, previews, drafts and
502
+ saving stay the browser's, as always. Give the provider the business's `timeZone` and `locale`:
503
+ without them an instant is written on the server's clock and then on the browser's, and the HTML
504
+ does not match:
505
+
506
+ ```tsx
507
+ // the Server Component
508
+ import { readRecordOnServer } from "@sincpro/web-framework/core";
509
+ const invoice = await readRecordOnServer(transport, invoices, params.id);
510
+ return <InvoicePage id={params.id} initial={invoice} />;
511
+
512
+ // the page ("use client"), under <FrameworkProvider timeZone="America/La_Paz" locale="es">
513
+ function InvoicePage({ id, initial }: { id: string; initial?: RecordRead<Invoice> }) {
514
+ const invoice = useRecord(invoices, id, { initial }); // ready on the server already
515
+ …
516
+ }
517
+ ```
518
+
491
519
  The server's use cases are traced like the browser's and their `traceparent` reaches the API —
492
520
  the counterpart of `browserTracer`, in its own optional entry. The provider is registered once
493
521
  per process, where the SSR framework's own spans land too; the process is configured once per
@@ -500,7 +528,7 @@ export async function register() {
500
528
  if (process.env.NEXT_RUNTIME !== "nodejs") return;
501
529
  const { registerServerTracing } = await import("@sincpro/web-framework/telemetry/server");
502
530
  const endpoint = process.env.OTEL_EXPORTER_OTLP_TRACES_ENDPOINT; // none: tracing stays off
503
- await registerServerTracing({ endpoint, release, environment });
531
+ await registerServerTracing({ endpoint, release, environment, oneTreePerRequest: true });
504
532
  }
505
533
 
506
534
  // where the server runs use cases — once per realm; in a browser it does nothing
@@ -508,6 +536,20 @@ import { configureServerProcess } from "@sincpro/web-framework/telemetry/server"
508
536
  configureServerProcess({ identity: { release } });
509
537
  ```
510
538
 
539
+ With `oneTreePerRequest`, each request is one trace: the request the SSR framework traced, its
540
+ renders, the use cases its page read and what the API did with them. It registers Node's
541
+ `AsyncLocalStorage` context manager (the optional peer `@opentelemetry/context-async-hooks`),
542
+ unless the platform registered one first, and a use case with no parent of its own starts under
543
+ the active span (client-framework 2.5's `adoptActiveSpan`). Without it — the default — each use
544
+ case's span starts a trace of its own, as before.
545
+
546
+ `registerServerTracing` also registers the W3C trace-context propagator (no baggage), unless the
547
+ platform registered one: an SSR framework reads and writes `traceparent` only through it. With it
548
+ and `oneTreePerRequest`, a request that arrives with a `traceparent` continues that trace, and
549
+ Next writes the request's own into the page (`experimental.clientTraceMetadata: ["traceparent"]`,
550
+ `<meta name="traceparent">` — on dynamic pages only: a cached page would hand every visitor one
551
+ trace).
552
+
511
553
  A page that broke while drawing shows the route's error screen instead of the framework's generic
512
554
  one: plain words, the code the server logged it with (Next's `digest`), «try again» and «home»,
513
555
  reported once through the process:
@@ -521,6 +563,48 @@ export default function PortalError({ error, reset }: { error: Error; reset: ()
521
563
  }
522
564
  ```
523
565
 
566
+ What fails on the server reaches GlitchTip too, with its real stack — the browser only ever gets
567
+ Next's generic message and the `digest`. `./errors/server` keeps one Sentry-compatible client per
568
+ process (`@sentry/core`'s server client, not `@sentry/node`, which would set up an OpenTelemetry
569
+ of its own); a request's report carries the same `digest` the visitor sees, its route and its
570
+ trace:
571
+
572
+ ```ts
573
+ // instrumentation.ts (Next) — once per process, and each request that failed
574
+ export async function register() {
575
+ if (process.env.NEXT_RUNTIME !== "nodejs") return;
576
+ const { registerServerErrors } = await import("@sincpro/web-framework/errors/server");
577
+ await registerServerErrors({ dsn: process.env.SENTRY_DSN, release, environment }); // none: off
578
+ }
579
+ export async function onRequestError(error, request, context) {
580
+ const { reportRequestError } = await import("@sincpro/web-framework/errors/server");
581
+ reportRequestError(error, {
582
+ method: request.method,
583
+ path: request.path,
584
+ route: context.routePath,
585
+ });
586
+ }
587
+
588
+ // where the server runs use cases: what fails unexpectedly there is reported, with its trace
589
+ import { serverReporter } from "@sincpro/web-framework/errors/server";
590
+ configureServerProcess({ identity: { release }, reporter: serverReporter() });
591
+ ```
592
+
593
+ **Readable stacks.** A production stack points at built bundles (`page.js:1:4313`). On the server
594
+ nothing has to be uploaded: build the server with its source maps and run Node with its own
595
+ (`experimental.serverSourceMaps: true` in Next, `NODE_OPTIONS=--enable-source-maps`), and each
596
+ reported frame says where it was in the source (`app/cursos/page.tsx:12`) — Next prints its
597
+ stacks mapped but hands over errors whose `stack` is not, so `./errors/server` maps them itself
598
+ with `node:module`. In the browser the maps must never be served: inject debug IDs at build and
599
+ upload them to GlitchTip with its CLI, then drop them from what is deployed:
600
+
601
+ ```sh
602
+ # the application's build (Next: productionBrowserSourceMaps: true)
603
+ glitchtip-cli sourcemaps inject .next/static
604
+ glitchtip-cli sourcemaps upload .next/static --release "$RELEASE" # SENTRY_URL, SENTRY_AUTH_TOKEN, SENTRY_ORG, SENTRY_PROJECT
605
+ find .next/static -name '*.map' -delete
606
+ ```
607
+
524
608
  ## The abstractions
525
609
 
526
610
  Each answers one question, and each comes in the three levels — use the component, drop to the
@@ -532,9 +616,11 @@ hook and draw your own, or go straight to the loose piece.
532
616
  | The application's logic | its `Feature`s and `ApplicationService`s (client-framework) | `useService` | `project.Issues.close(…)` |
533
617
  | Read through a use case | its `Feature`s (client-framework) | `useServiceReading` | `project.Accounts.balance(…)` |
534
618
  | Read it on the server first | the same use case, before the page is drawn | `useServiceReading(…, { initial })` | `readOnServer`, `ServerRead` |
619
+ | A record read on the server | `EntityRecord initial` | `useRecord(…, { initial })` | `readRecordOnServer`, `RecordRead` |
535
620
  | What every use case runs with | `processContext`, `project.context` (client-framework) | `useContextValues` | `ContextStore` |
536
621
  | What happened, what broke | `./telemetry`, `./errors` (optional) | — | `configureProcess({ tracer, reporter })` |
537
622
  | What happened, on the server | `configureServerProcess` (`./telemetry/server`, optional) | — | `registerServerTracing`, `serverTracer` |
623
+ | What broke, on the server | `reportRequestError` (`./errors/server`, optional) | — | `registerServerErrors`, `serverReporter` |
538
624
  | A page that broke | `RouteError`, in the route's error boundary | — | `reportError` (client-framework) |
539
625
  | What is each field? | `Meta` from the server, or `defineMeta` | — | `textOf`, `viewOf`, `metaFromSchema` |
540
626
  | A value outside a model | — | `useTextOf` | `moneyTextOf`, `dayTextOf`, `instantTextOf`, `numberTextOf` |
@@ -611,6 +697,7 @@ Three levels, one direction, and optional entries — `make doctor` keeps the ar
611
697
  | `web/workspace` | the composer: `entityView`, `openIn`, `RelatedRecord`, `<SincproApp>` | where it opens, the application context |
612
698
  | `telemetry`, `errors` | `browserTracer`, `glitchtipReporter`: built from the application's settings | optional peers, loaded after the first render; nothing else imports them |
613
699
  | `telemetry/server` | `registerServerTracing`, `configureServerProcess`: a server's use cases traced | optional peers too; Node only — a browser never loads it |
700
+ | `errors/server` | `registerServerErrors`, `serverReporter`, `reportRequestError`: to GlitchTip | optional peer `@sentry/core`; a browser never loads it |
614
701
 
615
702
  Screens import from `@sincpro/web-framework`. What every platform shares — the transport,
616
703
  `entity()`, model definitions, `Feature` and `ApplicationService`, the generated client — is
@@ -651,8 +738,10 @@ moves to the generated one — is [`docs/ADOPTION.md`](docs/ADOPTION.md).
651
738
  | `defineMeta`, `metaFromSchema` | A model by hand, or completed from OpenAPI (client-framework) | ✅ |
652
739
  | `useService` | A screen runs one of the application's use cases: run, busy, answer, error | ✅ |
653
740
  | `readOnServer` | A page read on the server by the browser's use case: plain JSON, a failure left to the browser | ✅ |
741
+ | `readRecordOnServer` | A record screen filled in the server's HTML: `useRecord` starts from it, nothing asked on mount | ✅ |
654
742
  | `./telemetry`, `./errors` | Optional: the application's traces to its OTLP endpoint, its errors to GlitchTip | ✅ |
655
743
  | `./telemetry/server` | Optional: a rendering server's use cases on its OTLP provider, their trace continued by the API | ✅ |
744
+ | `./errors/server` | Optional: what fails on a rendering server to GlitchTip, with the visitor's digest and trace | ✅ |
656
745
  | `RouteError` | A page that broke: plain words, the server's code, retry and home; reported once | ✅ |
657
746
  | `selection` | Filters named as criteria 2.0 and the backend read them, the search bar's included | ✅ |
658
747
  | `useListing`, `EntityList` | N records: criteria, search bar, builder, paging | ✅ |
@@ -23,6 +23,6 @@ export { detailOf, measuresOf, sumsOf, type Total, totalOf, } from "./measure.js
23
23
  export { BOOKKEEPING, currencyNow, type DateStyle, dateStyleNow, dayTextOf, defaultFields, fieldAt, fieldMetaOf, type FieldView, installCurrency, installDateStyle, instantTextOf, moneyTextOf, numberTextOf, shortTextOf, sortKeyOf, STAMPS, textOf, valueAt, viewOf, } from "./present.js";
24
24
  export { type Related, relatedOf } from "./related.js";
25
25
  export { backReference, entityFor, relatedScope, type RelationField, relationFieldOf, } from "./relation.js";
26
- export { readOnServer, type ServerRead } from "./server.js";
26
+ export { readOnServer, readRecordOnServer, type RecordRead, type ServerRead, } from "./server.js";
27
27
  export { type RecordSummary, summaryFieldsOf, summaryOf, } from "./summary.js";
28
28
  export { placeOf, stepIn, type Trail } from "./trail.js";
@@ -23,6 +23,6 @@ export { detailOf, measuresOf, sumsOf, totalOf, } from "./measure.js";
23
23
  export { BOOKKEEPING, currencyNow, dateStyleNow, dayTextOf, defaultFields, fieldAt, fieldMetaOf, installCurrency, installDateStyle, instantTextOf, moneyTextOf, numberTextOf, shortTextOf, sortKeyOf, STAMPS, textOf, valueAt, viewOf, } from "./present.js";
24
24
  export { relatedOf } from "./related.js";
25
25
  export { backReference, entityFor, relatedScope, relationFieldOf, } from "./relation.js";
26
- export { readOnServer } from "./server.js";
26
+ export { readOnServer, readRecordOnServer, } from "./server.js";
27
27
  export { summaryFieldsOf, summaryOf, } from "./summary.js";
28
28
  export { placeOf, stepIn } from "./trail.js";
@@ -1,3 +1,5 @@
1
+ import { type Draft, type Entity, type ResourceRef, type Transport } from "@sincpro/client-framework";
2
+ import type { AnyRecord, Meta } from "@sincpro/criteria";
1
3
  /**
2
4
  * A use case's answer read on the server that renders a page, before it is drawn — the very use
3
5
  * case the page reads with in the browser (`useServiceReading`), so the page arrives with its
@@ -42,3 +44,56 @@ export declare function readOnServer<A extends unknown[], R>(useCase: (...args:
42
44
  * type Props = { initial?: ServerRead<typeof project.Accounts.balance> };
43
45
  */
44
46
  export type ServerRead<U extends (...args: never[]) => unknown> = Awaited<ReturnType<U>> | undefined;
47
+ /**
48
+ * One record of an entity and its model, as the server that renders a page read it: what
49
+ * `useRecord(entity, opened, { initial })` starts from — `readRecordOnServer`'s answer.
50
+ *
51
+ * Context: plain JSON, as everything that crosses from the server to the browser. It says what
52
+ * it was read FOR — the entity's key and the record's id — because a screen must never show it
53
+ * under another: `useRecord` takes it only when it opens that same record.
54
+ */
55
+ export type RecordRead<T> = {
56
+ /** The entity's key (`entity.key`) it was read for. */
57
+ entity: string;
58
+ /** The record's key it was read for — `""` for a record that does not exist yet. */
59
+ id: string;
60
+ /** The record as the server answered it — `null` for a new one: the screen starts it from
61
+ * its model's defaults (and what its reference carries), as in the browser. */
62
+ record: T | null;
63
+ /** Its model's definition, when the server published one. */
64
+ meta: Meta | null;
65
+ /** What the caller kept of an edit between requests (sincpro_framework's `Drafts`). */
66
+ draft: Draft | null;
67
+ };
68
+ /**
69
+ * One record and its model, read on the server that renders the page — the same question
70
+ * `useRecord` asks in the browser, through the same transport the `FrameworkProvider` is given —,
71
+ * so its screen arrives FILLED in the HTML, not as a skeleton, and the browser does not ask
72
+ * again on mount.
73
+ *
74
+ * // a route's loader or a Server Component — plain logic, no screen loaded
75
+ * const invoice = await readRecordOnServer(transport, invoices, params.id);
76
+ * return <InvoicePage id={params.id} initial={invoice} />;
77
+ *
78
+ * // the page, rendered there and hydrated in the browser
79
+ * const invoice = useRecord(invoices, id, { initial });
80
+ *
81
+ * `opened` is what the screen opens: a record's id, `""` for a new one — only its model is read,
82
+ * as `useRecord` reads it (the list, one row) — or the reference the screen receives.
83
+ *
84
+ * Context: it asks through the screens' use case (`screensTransport`), as `useRecord` and
85
+ * `readListing` do — traced like the browser's reads, with the process's context — and answers
86
+ * plain JSON (`RecordRead`): a Client Component is handed data, never instances. A read that
87
+ * fails never refuses the page, as `readOnServer`: it answers `undefined` and one WARN line on
88
+ * the process's log — `what` (the entity's key when not given), the failure's type and kind, and
89
+ * never a refusal's message (a 404, a permission) —, the page is drawn without it and the
90
+ * browser reads the record on mount, as a single-page application does. A read the caller
91
+ * aborted (`signal`: nobody waits for the page any more) answers `undefined` without a line.
92
+ *
93
+ * Plain logic, without React or the DOM (`core/`): a route's loader, a Server Component and a
94
+ * script import it from `@sincpro/web-framework/core` without loading any screen.
95
+ */
96
+ export declare function readRecordOnServer<T extends AnyRecord>(transport: Transport, entity: Entity<T>, opened: string | ResourceRef, options?: {
97
+ what?: string;
98
+ signal?: AbortSignal;
99
+ }): Promise<RecordRead<T> | undefined>;
@@ -1,4 +1,4 @@
1
- import { describeFailure, logger, outcomeOf } from "@sincpro/client-framework";
1
+ import { describeFailure, logger, outcomeOf, screensTransport, } from "@sincpro/client-framework";
2
2
  /**
3
3
  * A use case's answer read on the server that renders a page, before it is drawn — the very use
4
4
  * case the page reads with in the browser (`useServiceReading`), so the page arrives with its
@@ -42,13 +42,80 @@ export async function readOnServer(useCase, args, options = {}) {
42
42
  return JSON.parse(JSON.stringify(answer));
43
43
  }
44
44
  catch (error) {
45
- const failure = describeFailure(error, outcomeOf(error));
46
- logger.warn("read on the server failed: the page is drawn without it", {
47
- what: options.what ?? (useCase.name || "a use case"),
48
- "error.type": failure.type,
49
- "error.kind": failure.kind,
50
- ...(failure.message === undefined ? {} : { "error.message": failure.message }),
45
+ notRead(options.what ?? (useCase.name || "a use case"), error);
46
+ return undefined;
47
+ }
48
+ }
49
+ /** The one line a read on the server that failed leaves on the process's log (WARN: it always
50
+ * speaks): what was not read, and the failure's type and kind — a refusal never its message. */
51
+ function notRead(what, error) {
52
+ const failure = describeFailure(error, outcomeOf(error));
53
+ logger.warn("read on the server failed: the page is drawn without it", {
54
+ what,
55
+ "error.type": failure.type,
56
+ "error.kind": failure.kind,
57
+ ...(failure.message === undefined ? {} : { "error.message": failure.message }),
58
+ });
59
+ }
60
+ /**
61
+ * One record and its model, read on the server that renders the page — the same question
62
+ * `useRecord` asks in the browser, through the same transport the `FrameworkProvider` is given —,
63
+ * so its screen arrives FILLED in the HTML, not as a skeleton, and the browser does not ask
64
+ * again on mount.
65
+ *
66
+ * // a route's loader or a Server Component — plain logic, no screen loaded
67
+ * const invoice = await readRecordOnServer(transport, invoices, params.id);
68
+ * return <InvoicePage id={params.id} initial={invoice} />;
69
+ *
70
+ * // the page, rendered there and hydrated in the browser
71
+ * const invoice = useRecord(invoices, id, { initial });
72
+ *
73
+ * `opened` is what the screen opens: a record's id, `""` for a new one — only its model is read,
74
+ * as `useRecord` reads it (the list, one row) — or the reference the screen receives.
75
+ *
76
+ * Context: it asks through the screens' use case (`screensTransport`), as `useRecord` and
77
+ * `readListing` do — traced like the browser's reads, with the process's context — and answers
78
+ * plain JSON (`RecordRead`): a Client Component is handed data, never instances. A read that
79
+ * fails never refuses the page, as `readOnServer`: it answers `undefined` and one WARN line on
80
+ * the process's log — `what` (the entity's key when not given), the failure's type and kind, and
81
+ * never a refusal's message (a 404, a permission) —, the page is drawn without it and the
82
+ * browser reads the record on mount, as a single-page application does. A read the caller
83
+ * aborted (`signal`: nobody waits for the page any more) answers `undefined` without a line.
84
+ *
85
+ * Plain logic, without React or the DOM (`core/`): a route's loader, a Server Component and a
86
+ * script import it from `@sincpro/web-framework/core` without loading any screen.
87
+ */
88
+ export async function readRecordOnServer(transport, entity, opened, options = {}) {
89
+ const id = typeof opened === "string" ? opened : (opened.id ?? "");
90
+ const screens = screensTransport(transport);
91
+ try {
92
+ if (id === "") {
93
+ // Nothing to read but the model: asked of the list with no rows, as `useRecord` asks it.
94
+ const page = await screens.list(entity.list, { pagination: { limit: 1 } }, options.signal);
95
+ return plain({
96
+ entity: entity.key,
97
+ id,
98
+ record: null,
99
+ meta: page.meta ?? null,
100
+ draft: null,
101
+ });
102
+ }
103
+ const answer = await screens.one(entity.one(id), options.signal);
104
+ return plain({
105
+ entity: entity.key,
106
+ id,
107
+ record: answer.record,
108
+ meta: answer.meta ?? null,
109
+ draft: answer.draft ?? null,
51
110
  });
111
+ }
112
+ catch (error) {
113
+ if (options.signal?.aborted !== true)
114
+ notRead(options.what ?? entity.key, error);
52
115
  return undefined;
53
116
  }
54
117
  }
118
+ /** Written and read back as JSON: what a server hands a page crosses that way. */
119
+ function plain(read) {
120
+ return JSON.parse(JSON.stringify(read));
121
+ }
@@ -29,6 +29,17 @@ export type Trail = {
29
29
  /** How many there are in all, when the server counted them. */
30
30
  total: number | null;
31
31
  };
32
+ /**
33
+ * The key a list's trail is kept by — and the `from` the records opened from it carry in their
34
+ * link: the list's React id (`useId()`), marked with this page load.
35
+ *
36
+ * Context: React's ids start over on every load, and a workspace restores its links from the
37
+ * URL. Unmarked, a record restored after a reload could name the trail of whichever new list
38
+ * happened to get the same id, and show its «3 / 64» and walk its rows. Marked, an old link
39
+ * names no trail of this load, and the record simply shows none. The key never reaches the
40
+ * HTML (a row opens its record on a click), so it cannot differ between server and browser.
41
+ */
42
+ export declare function trailKeyOf(listId: string): string;
32
43
  /** Where a record stands in its trail: «3 of 64», 1-based. */
33
44
  export declare function placeOf(trail: Trail, id: string): {
34
45
  index: number;
@@ -1,5 +1,20 @@
1
1
  import {} from "@sincpro/client-framework";
2
2
  import { resumingFrom } from "@sincpro/criteria";
3
+ /** This page load's mark: drawn once per load of this module, never sent anywhere. */
4
+ const PAGE_LOAD = Math.random().toString(36).slice(2, 8);
5
+ /**
6
+ * The key a list's trail is kept by — and the `from` the records opened from it carry in their
7
+ * link: the list's React id (`useId()`), marked with this page load.
8
+ *
9
+ * Context: React's ids start over on every load, and a workspace restores its links from the
10
+ * URL. Unmarked, a record restored after a reload could name the trail of whichever new list
11
+ * happened to get the same id, and show its «3 / 64» and walk its rows. Marked, an old link
12
+ * names no trail of this load, and the record simply shows none. The key never reaches the
13
+ * HTML (a row opens its record on a click), so it cannot differ between server and browser.
14
+ */
15
+ export function trailKeyOf(listId) {
16
+ return `trail:${PAGE_LOAD}${listId}`;
17
+ }
3
18
  /** Where a record stands in its trail: «3 of 64», 1-based. */
4
19
  export function placeOf(trail, id) {
5
20
  const at = trail.ids.indexOf(id);
@@ -1,4 +1,7 @@
1
1
  import type { ErrorReporter } from "@sincpro/client-framework";
2
+ import { type SentEvent } from "./narrowed.js";
3
+ export type { SentEvent };
4
+ export { reportUncaught } from "./uncaught.js";
2
5
  /**
3
6
  * An `ErrorReporter` for the browser, built from the application's own settings: a
4
7
  * Sentry-compatible client — GlitchTip, where the backend reports too — with the application's
@@ -20,7 +23,8 @@ import type { ErrorReporter } from "@sincpro/client-framework";
20
23
  *
21
24
  * What it sends is narrow by default, because in an ERP a request body is an invoice and a
22
25
  * customer: no breadcrumbs or default integrations, and every event leaves without cookies,
23
- * headers, request bodies, query strings or the user's address. `beforeSend` is the
26
+ * headers, request bodies, query strings or the user's address — of the person, only their id,
27
+ * what GlitchTip counts «users affected» by. `beforeSend` is the
24
28
  * application's, run after that.
25
29
  */
26
30
  export type GlitchtipOptions = {
@@ -34,16 +38,4 @@ export type GlitchtipOptions = {
34
38
  /** The application's last word on an event: change it, or answer `null` to drop it. */
35
39
  beforeSend?: (event: SentEvent) => SentEvent | null;
36
40
  };
37
- /** The parts of an event this reporter narrows; the rest passes as the SDK built it. */
38
- export type SentEvent = {
39
- request?: {
40
- url?: string;
41
- cookies?: unknown;
42
- headers?: unknown;
43
- data?: unknown;
44
- query_string?: unknown;
45
- };
46
- user?: unknown;
47
- [key: string]: unknown;
48
- };
49
41
  export declare function glitchtipReporter(options: GlitchtipOptions): ErrorReporter;
@@ -1,15 +1,6 @@
1
+ import { narrowed } from "./narrowed.js";
2
+ export { reportUncaught } from "./uncaught.js";
1
3
  const WAITING_AT_MOST = 20;
2
- /** Every event leaves without what may carry a person's or a customer's data. */
3
- function narrowed(event) {
4
- const { user: _user, ...rest } = event;
5
- if (rest.request === undefined)
6
- return rest;
7
- const { cookies: _c, headers: _h, data: _d, query_string: _q, ...request } = rest.request;
8
- return {
9
- ...rest,
10
- request: { ...request, ...(request.url ? { url: request.url.split("?")[0] } : {}) },
11
- };
12
- }
13
4
  export function glitchtipReporter(options) {
14
5
  let ready = null;
15
6
  let failed = false;
@@ -0,0 +1,18 @@
1
+ /**
2
+ * What every reported event leaves without — the browser's (`./errors`) and the server's
3
+ * (`./errors/server`) alike: in an ERP a request body is an invoice and a customer.
4
+ */
5
+ /** The parts of an event the reporters narrow; the rest passes as the SDK built it. */
6
+ export type SentEvent = {
7
+ request?: {
8
+ url?: string;
9
+ cookies?: unknown;
10
+ headers?: unknown;
11
+ data?: unknown;
12
+ query_string?: unknown;
13
+ };
14
+ user?: unknown;
15
+ [key: string]: unknown;
16
+ };
17
+ /** Every event leaves without what may carry a person's or a customer's data. */
18
+ export declare function narrowed(event: SentEvent): SentEvent;
@@ -0,0 +1,25 @@
1
+ /**
2
+ * What every reported event leaves without — the browser's (`./errors`) and the server's
3
+ * (`./errors/server`) alike: in an ERP a request body is an invoice and a customer.
4
+ */
5
+ /** The person's id — what GlitchTip counts «users affected» by, and what already travels as the
6
+ * `user_id` tag —; nothing else of the person (email, name, IP…). */
7
+ function idOf(user) {
8
+ if (typeof user !== "object" || user === null || !("id" in user))
9
+ return undefined;
10
+ const id = user.id;
11
+ return typeof id === "string" || typeof id === "number" ? { id: String(id) } : undefined;
12
+ }
13
+ /** Every event leaves without what may carry a person's or a customer's data. */
14
+ export function narrowed(event) {
15
+ const { user, ...others } = event;
16
+ const person = idOf(user);
17
+ const rest = person === undefined ? others : { ...others, user: person };
18
+ if (rest.request === undefined)
19
+ return rest;
20
+ const { cookies: _c, headers: _h, data: _d, query_string: _q, ...request } = rest.request;
21
+ return {
22
+ ...rest,
23
+ request: { ...request, ...(request.url ? { url: request.url.split("?")[0] } : {}) },
24
+ };
25
+ }
@@ -0,0 +1,92 @@
1
+ import { type ErrorReporter } from "@sincpro/client-framework";
2
+ import { type SentEvent } from "./narrowed.js";
3
+ /**
4
+ * The server's side of `./errors`: what a server that renders pages — Next.js, TanStack Start,
5
+ * Remix, a Node process of one's own — needs so what fails there reaches GlitchTip like what
6
+ * fails in the browser and in the backend.
7
+ *
8
+ * // once per process — Next's instrumentation.ts (no Next here: the application wires it)
9
+ * export async function register() {
10
+ * if (process.env.NEXT_RUNTIME !== "nodejs") return;
11
+ * const { registerServerErrors } = await import("./server.js");
12
+ * await registerServerErrors({ dsn: process.env.SENTRY_DSN, release, environment });
13
+ * }
14
+ *
15
+ * // a request that failed on the server: the page that broke while drawing
16
+ * export async function onRequestError(error, request, context) {
17
+ * const { reportRequestError } = await import("./server.js");
18
+ * reportRequestError(error, { method: request.method, path: request.path, route: context.routePath });
19
+ * }
20
+ *
21
+ * // once per realm, where the server runs use cases
22
+ * configureServerProcess({ identity: { release }, reporter: serverReporter() });
23
+ *
24
+ * Context: one client per PROCESS, kept on `globalThis`, because a server that renders loads
25
+ * this package once per realm (Next: instrumentation, Server Components, the server render of
26
+ * Client Components) and every realm reports through the one `register` built. The client is
27
+ * `@sentry/core`'s server client — not `@sentry/node`, which sets up its own OpenTelemetry,
28
+ * instrumentation and bundler plugins and would clash with `./telemetry/server`. Nothing global
29
+ * besides it: no `Sentry.init`, no handlers on `process`; only what the process decides is
30
+ * unexpected, and the requests the application hands over, reach it.
31
+ *
32
+ * A request's report carries the `digest` — the code the visitor's `RouteError` shows and the
33
+ * browser's own report carries —, the route and the active span's trace: the three reports of
34
+ * one failure (browser, server, trace) find each other. A use case that failed and also broke
35
+ * the page is two events of one issue — the use case's and the request's —, in one trace.
36
+ *
37
+ * Optional on every count, like `./errors`: an entry of its own that nothing else imports,
38
+ * `@sentry/core` an optional peer loaded with `import()`, and nothing throws: without a DSN
39
+ * nothing loads; if the SDK does not load, that is said once and reports are dropped. What it
40
+ * sends is narrowed as the browser's: no cookies, headers, bodies, query strings, and of the
41
+ * person only their id.
42
+ */
43
+ export type ServerErrorsOptions = {
44
+ /** The application's DSN, from its settings. None — an empty setting — and reporting is off. */
45
+ dsn: string | undefined;
46
+ /** `<name>:<version>` as deployed, the same text as `configureProcess({ identity })`. */
47
+ release?: string;
48
+ /** `production`, `staging`… */
49
+ environment?: string;
50
+ /** Fraction of errors sent, 0 to 1. Default 1. */
51
+ sampling?: number;
52
+ /** The application's last word on an event: change it, or answer `null` to drop it. */
53
+ beforeSend?: (event: SentEvent) => SentEvent | null;
54
+ };
55
+ /** The process's reporting, once registered. */
56
+ export type ServerErrors = {
57
+ /** Sends what is queued now: a script that ends, a test. */
58
+ flush: (timeoutMs?: number) => Promise<boolean>;
59
+ /** Sends what is queued and stops: a server shutting down. */
60
+ close: (timeoutMs?: number) => Promise<boolean>;
61
+ };
62
+ /** What a failed request was, for its report — never its headers, cookies, body or query. */
63
+ export type FailedRequest = {
64
+ /** The code the SSR framework gave the failure (Next's `digest`); read from the error if absent. */
65
+ digest?: string;
66
+ method?: string;
67
+ /** The path asked for; its query string is dropped. */
68
+ path?: string;
69
+ /** The route that drew it (`/cursos/[id]`). */
70
+ route?: string;
71
+ };
72
+ /**
73
+ * The process's error reporting: a Sentry-compatible client — GlitchTip — with the application's
74
+ * DSN, kept for every realm. Once per process: a second call, from any realm, answers the
75
+ * first's. It answers `undefined` when reporting stays off — no DSN, or the SDK did not load.
76
+ */
77
+ export declare function registerServerErrors(options: ServerErrorsOptions): Promise<ServerErrors | undefined>;
78
+ /**
79
+ * An `ErrorReporter` over the process's client — what `configureServerProcess({ reporter })`
80
+ * plugs, so a use case that fails unexpectedly on the server is reported with its trace, as
81
+ * the browser's are. Before `registerServerErrors` (or without a DSN) it reports nothing.
82
+ */
83
+ export declare function serverReporter(): ErrorReporter;
84
+ /**
85
+ * A request that failed on the server — a page that broke while drawing —, reported with what
86
+ * finds it again: its `digest`, its route, its method and path (without the query), and
87
+ * the trace it failed in. What the server already explained (a refusal, a cancellation) is not
88
+ * a fault and is not reported. One error handed over twice (two phases of one render) is one
89
+ * event: the client marks what it captured. Before `registerServerErrors` (or without a DSN) it
90
+ * does nothing.
91
+ */
92
+ export declare function reportRequestError(error: unknown, request?: FailedRequest): void;
@@ -0,0 +1,170 @@
1
+ import { outcomeOf } from "@sincpro/client-framework";
2
+ import { narrowed } from "./narrowed.js";
3
+ const HELD = Symbol.for("@sincpro/web-framework/errors/server");
4
+ const WHO = "@sincpro/web-framework/errors/server";
5
+ function held() {
6
+ const global = globalThis;
7
+ return (global[HELD] ??= {});
8
+ }
9
+ /**
10
+ * The process's error reporting: a Sentry-compatible client — GlitchTip — with the application's
11
+ * DSN, kept for every realm. Once per process: a second call, from any realm, answers the
12
+ * first's. It answers `undefined` when reporting stays off — no DSN, or the SDK did not load.
13
+ */
14
+ export function registerServerErrors(options) {
15
+ const dsn = options.dsn;
16
+ if (!dsn)
17
+ return Promise.resolve(undefined);
18
+ const shared = held();
19
+ shared.registered ??= started({ ...options, dsn });
20
+ return shared.registered;
21
+ }
22
+ /** A transport over `fetch` — Node 18+, an edge runtime, Bun: whatever the server runs on. */
23
+ function overFetch(transportOver) {
24
+ return (transportOptions) => transportOver(transportOptions, async (request) => {
25
+ const response = await fetch(transportOptions.url, {
26
+ method: "POST",
27
+ body: request.body,
28
+ ...(transportOptions.headers ? { headers: transportOptions.headers } : {}),
29
+ });
30
+ return {
31
+ statusCode: response.status,
32
+ headers: {
33
+ "x-sentry-rate-limits": response.headers.get("X-Sentry-Rate-Limits"),
34
+ "retry-after": response.headers.get("Retry-After"),
35
+ },
36
+ };
37
+ });
38
+ }
39
+ /**
40
+ * Each frame where it was in the source — `app/cursos/page.tsx:12:7`, not a built bundle's
41
+ * `page.js:1:4313` —, when the built file has a source map Node loaded (the server built with
42
+ * its source maps, Node run with `--enable-source-maps`). An SSR framework may print its stacks
43
+ * mapped and still hand over an error whose `stack` is not (Next replaces Node's formatter): the
44
+ * report is mapped here, with nothing uploaded anywhere.
45
+ */
46
+ function readable(event, findSourceMap) {
47
+ if (findSourceMap === undefined)
48
+ return event;
49
+ const exception = event["exception"];
50
+ for (const value of exception?.values ?? []) {
51
+ for (const frame of value.stacktrace?.frames ?? []) {
52
+ const file = (frame.abs_path ?? frame.filename)?.replace(/^file:\/\//, "");
53
+ if (!file || frame.lineno === undefined || frame.colno === undefined)
54
+ continue;
55
+ let origin;
56
+ try {
57
+ origin = findSourceMap(file)?.findOrigin(frame.lineno, frame.colno);
58
+ }
59
+ catch {
60
+ continue;
61
+ }
62
+ if (!origin?.fileName || origin.lineNumber === undefined)
63
+ continue;
64
+ frame.filename = origin.fileName;
65
+ frame.abs_path = origin.fileName;
66
+ frame.lineno = origin.lineNumber;
67
+ if (origin.columnNumber !== undefined)
68
+ frame.colno = origin.columnNumber;
69
+ frame.in_app = !origin.fileName.includes("node_modules");
70
+ }
71
+ }
72
+ return event;
73
+ }
74
+ async function started(options) {
75
+ try {
76
+ const [core, { ServerRuntimeClient, nodeStackLineParser }, { sentryReporter }] = await Promise.all([
77
+ import("@sentry/core"),
78
+ import("@sentry/core/server"),
79
+ import("@sincpro/client-framework/sentry"),
80
+ ]);
81
+ const runtime = globalThis.process?.version;
82
+ // An edge runtime has no `node:module`: its frames stay as they are.
83
+ // A bundler may hand a builtin over as its `default` (webpack does).
84
+ const findSourceMap = await import("node:module").then((module) => (module.findSourceMap ??
85
+ module.default
86
+ ?.findSourceMap), () => undefined);
87
+ const client = new ServerRuntimeClient({
88
+ dsn: options.dsn,
89
+ transport: overFetch(core.createTransport),
90
+ stackParser: core.createStackParser(nodeStackLineParser()),
91
+ integrations: [],
92
+ platform: "node",
93
+ runtime: { name: "node", ...(runtime ? { version: runtime } : {}) },
94
+ ...(options.release ? { release: options.release } : {}),
95
+ ...(options.environment ? { environment: options.environment } : {}),
96
+ ...(options.sampling === undefined ? {} : { sampleRate: options.sampling }),
97
+ beforeSend: (event) => {
98
+ const own = narrowed(readable(event, findSourceMap));
99
+ const kept = options.beforeSend ? options.beforeSend(own) : own;
100
+ return kept;
101
+ },
102
+ });
103
+ client.init();
104
+ const shared = held();
105
+ shared.client = client;
106
+ shared.reporter = sentryReporter(client);
107
+ shared.spans = await import("@opentelemetry/api").then(({ trace }) => trace, () => undefined);
108
+ return {
109
+ flush: async (timeoutMs) => client.flush(timeoutMs),
110
+ close: async (timeoutMs) => client.close(timeoutMs),
111
+ };
112
+ }
113
+ catch (error) {
114
+ console.warn(`${WHO}: error reporting is off — @sentry/core did not load`, error);
115
+ return undefined;
116
+ }
117
+ }
118
+ /**
119
+ * An `ErrorReporter` over the process's client — what `configureServerProcess({ reporter })`
120
+ * plugs, so a use case that fails unexpectedly on the server is reported with its trace, as
121
+ * the browser's are. Before `registerServerErrors` (or without a DSN) it reports nothing.
122
+ */
123
+ export function serverReporter() {
124
+ return { report: (error, about) => held().reporter?.report(error, about) };
125
+ }
126
+ function digestOf(error) {
127
+ if (typeof error !== "object" || error === null || !("digest" in error))
128
+ return undefined;
129
+ const digest = error.digest;
130
+ return typeof digest === "string" && digest !== "" ? digest : undefined;
131
+ }
132
+ /**
133
+ * A request that failed on the server — a page that broke while drawing —, reported with what
134
+ * finds it again: its `digest`, its route, its method and path (without the query), and
135
+ * the trace it failed in. What the server already explained (a refusal, a cancellation) is not
136
+ * a fault and is not reported. One error handed over twice (two phases of one render) is one
137
+ * event: the client marks what it captured. Before `registerServerErrors` (or without a DSN) it
138
+ * does nothing.
139
+ */
140
+ export function reportRequestError(error, request = {}) {
141
+ const shared = held();
142
+ const client = shared.client;
143
+ if (client === undefined)
144
+ return;
145
+ try {
146
+ if (outcomeOf(error) !== "failed")
147
+ return;
148
+ }
149
+ catch {
150
+ // An outcome that cannot be told is a failure.
151
+ }
152
+ const digest = request.digest ?? digestOf(error);
153
+ const path = request.path?.split("?")[0];
154
+ const span = shared.spans?.getActiveSpan()?.spanContext();
155
+ client.captureException(error, {
156
+ captureContext: {
157
+ tags: {
158
+ "sincpro.layer": "request",
159
+ ...(digest ? { digest } : {}),
160
+ ...(request.route ? { route: request.route } : {}),
161
+ ...(request.method ? { "http.method": request.method } : {}),
162
+ ...(path ? { "url.path": path } : {}),
163
+ ...(span ? { trace_id: span.traceId } : {}),
164
+ },
165
+ ...(span
166
+ ? { contexts: { trace: { trace_id: span.traceId, span_id: span.spanId } } }
167
+ : {}),
168
+ },
169
+ });
170
+ }
@@ -0,0 +1,16 @@
1
+ /**
2
+ * What nobody caught in the browser — an error thrown in an event handler outside a use case, a
3
+ * promise nobody waited for —, reported through the process's reporter like everything else:
4
+ *
5
+ * configureProcess({ identity: { release }, reporter: glitchtipReporter({ dsn, release }) });
6
+ * reportUncaught(); // entrypoints/main.tsx, opt-in
7
+ *
8
+ * Context: it listens to `window`'s `error` and `unhandledrejection` and hands each over to
9
+ * client-framework's `reportError`, so the process's rules apply: whichever reporter it has
10
+ * (GlitchTip or another), a cancellation or a refusal the server explained is not a fault, and
11
+ * an error already reported — a use case's, the one that also went unhandled — is not reported
12
+ * again. A script of another origin says only «Script error.», with nothing to find it by: it
13
+ * is skipped, as is anything thrown without an error. On the server there is no `window` and it
14
+ * does nothing. Called again, it answers the same stop; nothing else is registered.
15
+ */
16
+ export declare function reportUncaught(): () => void;
@@ -0,0 +1,41 @@
1
+ import { reportError } from "@sincpro/client-framework";
2
+ /**
3
+ * What nobody caught in the browser — an error thrown in an event handler outside a use case, a
4
+ * promise nobody waited for —, reported through the process's reporter like everything else:
5
+ *
6
+ * configureProcess({ identity: { release }, reporter: glitchtipReporter({ dsn, release }) });
7
+ * reportUncaught(); // entrypoints/main.tsx, opt-in
8
+ *
9
+ * Context: it listens to `window`'s `error` and `unhandledrejection` and hands each over to
10
+ * client-framework's `reportError`, so the process's rules apply: whichever reporter it has
11
+ * (GlitchTip or another), a cancellation or a refusal the server explained is not a fault, and
12
+ * an error already reported — a use case's, the one that also went unhandled — is not reported
13
+ * again. A script of another origin says only «Script error.», with nothing to find it by: it
14
+ * is skipped, as is anything thrown without an error. On the server there is no `window` and it
15
+ * does nothing. Called again, it answers the same stop; nothing else is registered.
16
+ */
17
+ export function reportUncaught() {
18
+ const target = globalThis.window;
19
+ if (target === undefined)
20
+ return () => undefined;
21
+ return (listening ??= listen(target));
22
+ }
23
+ let listening;
24
+ function listen(target) {
25
+ const onError = (event) => {
26
+ const error = event.error;
27
+ if (error === undefined || error === null)
28
+ return;
29
+ reportError(error, "uncaught error");
30
+ };
31
+ const onRejection = (event) => {
32
+ reportError(event.reason, "unhandled rejection");
33
+ };
34
+ target.addEventListener("error", onError);
35
+ target.addEventListener("unhandledrejection", onRejection);
36
+ return () => {
37
+ target.removeEventListener("error", onError);
38
+ target.removeEventListener("unhandledrejection", onRejection);
39
+ listening = undefined;
40
+ };
41
+ }
@@ -1,6 +1,7 @@
1
1
  import { type Draft, type Entity, type ResourceRef } from "@sincpro/client-framework";
2
2
  import type { AnyRecord, Meta } from "@sincpro/criteria";
3
3
  import { type Advice, type FieldState } from "../core/edit.js";
4
+ import type { RecordRead } from "../core/server.js";
4
5
  /**
5
6
  * ONE record of an entity, with the definition of its model — read, and edited.
6
7
  *
@@ -36,9 +37,18 @@ import { type Advice, type FieldState } from "../core/edit.js";
36
37
  * that key — a retry names the same record, never a second one — and the hook becomes it.
37
38
  * Its `id` stays `""` until it is stored: until then it does not exist.
38
39
  *
40
+ * - **read on the server** — a page rendered on a server hands it what `readRecordOnServer`
41
+ * read there (`initial`): the hook starts `ready` with it — the screen is filled in the HTML,
42
+ * not a skeleton — and its model goes into the provider's `metas`; in the browser nothing is
43
+ * asked on mount. Only for the record it was read for (the entity's key and the id it opens
44
+ * with), and only when it mounts, as `useState`'s first value: another record afterwards, a
45
+ * `reload()`, a write or another company read as always, and editing, previews, drafts,
46
+ * conflicts and saving are the browser's, the same as without it.
47
+ *
39
48
  * const invoice = useRecord(invoices, ""); // a new one
40
49
  * const invoice = useRecord(invoices, "F-2026-7"); // an existing one
41
50
  * const invoice = useRecord(invoices, resource); // what the workspace opened
51
+ * const invoice = useRecord(invoices, id, { initial }); // what the server already read
42
52
  */
43
53
  export type RecordState<T> = {
44
54
  status: "loading";
@@ -104,4 +114,8 @@ export type RecordReading<T> = RecordState<T> & {
104
114
  reload: () => void;
105
115
  edit: Editing;
106
116
  };
107
- export declare function useRecord<T extends AnyRecord>(entity: Entity<T>, opened: string | ResourceRef): RecordReading<T>;
117
+ export declare function useRecord<T extends AnyRecord>(entity: Entity<T>, opened: string | ResourceRef, options?: {
118
+ /** The record and its model already read on the server that renders the screen
119
+ * (`readRecordOnServer`): the hook starts from it when it mounts on that same record. */
120
+ initial?: RecordRead<T> | undefined;
121
+ }): RecordReading<T>;
@@ -7,12 +7,36 @@ import { useWrites } from "./useWrites.js";
7
7
  import { useCallback, useEffect, useMemo, useRef, useState } from "react";
8
8
  /** How long typing has to pause before the server is asked what the record becomes. */
9
9
  const PREVIEW_PAUSE = 300;
10
- export function useRecord(entity, opened) {
10
+ export function useRecord(entity, opened, options = {}) {
11
11
  const { transport, locale, metas, context } = useFramework();
12
12
  const given = typeof opened === "string" ? opened : (opened.id ?? "");
13
13
  // As written in the reference: a text compares by value, so a new render with the same
14
14
  // reference is not a new start.
15
15
  const start = typeof opened === "string" ? undefined : opened.params?.[WITH_PARAM];
16
+ // What the server read, when it is THIS record — the entity and the id it opens with, a stored
17
+ // one with its record. Read only by the first render's initial values: an `initial` that
18
+ // arrives later, or one read for another record, is never shown.
19
+ const initial = options.initial;
20
+ const served = initial !== undefined &&
21
+ initial.entity === entity.key &&
22
+ initial.id === given &&
23
+ (given === "" || initial.record !== null)
24
+ ? initial
25
+ : undefined;
26
+ /** The state a read answered with: the record (a new one from its model's defaults and what
27
+ * its reference carries), its model — the same the effect below sets. */
28
+ const startedFrom = (read) => {
29
+ if (read.meta)
30
+ metas.set(entity.key, read.meta);
31
+ const meta = read.meta ?? metas.get(entity.key) ?? null;
32
+ const starting = start === undefined ? {} : startingValuesOf({ params: { [WITH_PARAM]: start } });
33
+ return {
34
+ status: "ready",
35
+ record: read.id === "" ? { ...defaultsOf(meta), ...starting } : read.record,
36
+ meta,
37
+ error: null,
38
+ };
39
+ };
16
40
  // A create that answered its identity turns this into that record — until the screen asks
17
41
  // for another one.
18
42
  const [born, setBorn] = useState(null);
@@ -23,17 +47,21 @@ export function useRecord(entity, opened) {
23
47
  // The key a new record is born under when it is created by `Edit`: minted once per new
24
48
  // record, on the first gesture that needs it, and kept for every draft save and the save.
25
49
  const minted = useRef(null);
26
- const [state, setState] = useState({
27
- status: "loading",
28
- record: null,
29
- meta: null,
30
- error: null,
31
- });
50
+ const [state, setState] = useState(() => served === undefined
51
+ ? { status: "loading", record: null, meta: null, error: null }
52
+ : startedFrom(served));
32
53
  // Which record `state` was read for: the render after the id changed — a create that answered,
33
54
  // another record asked — must not show the previous one under the new id.
34
- const [readFor, setReadFor] = useState(null);
55
+ const [readFor, setReadFor] = useState(served === undefined ? null : given);
35
56
  const [round, setRound] = useState(0);
36
- const [typed, setTyped] = useState({});
57
+ // The question the server already answered, as the read below asks it (its dependencies, in
58
+ // their order): on mount it is not asked again — nor in React's second mount of the same
59
+ // question (StrictMode). Any other question (a `reload()`, another id, another transport)
60
+ // reads as always.
61
+ const answered = useRef(served === undefined ? null : [transport, metas, entity, given, given === "", start, 0]);
62
+ // A server that answers the record FROM the draft (sincpro_framework) sends no values apart:
63
+ // the record is the draft. One that sends them apart, they are what was typed.
64
+ const [typed, setTyped] = useState(() => served?.draft?.values ?? {});
37
65
  const typedNow = useRef(typed);
38
66
  typedNow.current = typed;
39
67
  const [computed, setComputed] = useState({});
@@ -42,7 +70,7 @@ export function useRecord(entity, opened) {
42
70
  const [saving, setSaving] = useState(false);
43
71
  const [failure, setFailure] = useState(null);
44
72
  const [conflict, setConflict] = useState(false);
45
- const [draft, setDraft] = useState(null);
73
+ const [draft, setDraft] = useState(served?.draft ?? null);
46
74
  const pause = useRef(null);
47
75
  // The preview in flight. A newer one cancels it, and so do a save, a discard and leaving:
48
76
  // an answer about values that are no longer on screen must never land on them.
@@ -64,6 +92,12 @@ export function useRecord(entity, opened) {
64
92
  setConflict(false);
65
93
  };
66
94
  useEffect(() => {
95
+ // The server's question (`initial`) is answered already: nothing to read.
96
+ const asked = [transport, metas, entity, id, isNew, start, round];
97
+ const before = answered.current;
98
+ if (before !== null && asked.every((one, at) => Object.is(one, before[at])))
99
+ return;
100
+ answered.current = null;
67
101
  const aborter = new AbortController();
68
102
  // Read again — after a save, a reload — the record on screen STAYS until the answer: a form
69
103
  // that blinked through a skeleton lost its focus, its scroll and the click that landed then.
@@ -9,7 +9,7 @@ import { type Attributes, type ProcessOptions, type Tracer } from "@sincpro/clie
9
9
  * if (process.env.NEXT_RUNTIME !== "nodejs") return;
10
10
  * const { registerServerTracing } = await import("./server.js");
11
11
  * const endpoint = process.env.OTEL_EXPORTER_OTLP_TRACES_ENDPOINT; // from its settings
12
- * await registerServerTracing({ endpoint, release, environment });
12
+ * await registerServerTracing({ endpoint, release, environment, oneTreePerRequest: true });
13
13
  * }
14
14
  *
15
15
  * // once per realm, where the server runs use cases — a module that reads on the server
@@ -26,7 +26,8 @@ import { type Attributes, type ProcessOptions, type Tracer } from "@sincpro/clie
26
26
  *
27
27
  * Optional on every count, like `./telemetry`: an entry of its own that nothing else imports,
28
28
  * the same optional peers (`@opentelemetry/api`, `@opentelemetry/sdk-trace`,
29
- * `@opentelemetry/exporter-trace-otlp-http`, `@opentelemetry/resources`) loaded with `import()`,
29
+ * `@opentelemetry/exporter-trace-otlp-http`, `@opentelemetry/resources`, `@opentelemetry/core`, and
30
+ * `@opentelemetry/context-async-hooks` for `oneTreePerRequest`) loaded with `import()`,
30
31
  * and nothing throws: without an endpoint nothing loads and nothing is registered; if the SDK
31
32
  * is not installed or fails, that is said once on the console and use cases run untraced,
32
33
  * sending no `traceparent`. Node only — an edge runtime skips it (its exporter speaks `http`).
@@ -49,6 +50,18 @@ export type ServerTracingOptions = {
49
50
  sampling?: number;
50
51
  /** More resource attributes (`tenant.group`, …). */
51
52
  attributes?: Attributes;
53
+ /**
54
+ * Each request one tree — the request the SSR framework traces, its renders, the use cases a
55
+ * page reads and what the backend did with them. Node's AsyncLocalStorage carries the active
56
+ * span through each request's awaits (registered here, unless the platform registered a
57
+ * context manager of its own first), and a use case run with no parent of its own starts
58
+ * under it (client-framework's `adoptActiveSpan`, 2.5+).
59
+ *
60
+ * Default `false`, as before: a use case's span is the root of its trace. Turning it on loads
61
+ * one more optional peer, `@opentelemetry/context-async-hooks`; if it does not load, that is
62
+ * said once and the rest works as without it.
63
+ */
64
+ oneTreePerRequest?: boolean;
52
65
  };
53
66
  /** The process's tracing, once registered. */
54
67
  export type ServerTracing = {
@@ -19,18 +19,55 @@ export function registerServerTracing(options) {
19
19
  if (!endpoint)
20
20
  return Promise.resolve(undefined);
21
21
  const shared = held();
22
- shared.registered ??= started({ ...options, endpoint });
22
+ if (shared.registered === undefined) {
23
+ // Before the first page: every realm's tracer reads it when it is first asked for.
24
+ shared.adoptActiveSpan = options.oneTreePerRequest === true;
25
+ shared.registered = started({ ...options, endpoint });
26
+ }
23
27
  return shared.registered;
24
28
  }
29
+ /** A tracer of client-framework's over OpenTelemetry's, as this process's registration asked. */
30
+ function tracerOver(trace, overOpenTelemetry) {
31
+ return (name) => overOpenTelemetry(trace.getTracer(name), {
32
+ adoptActiveSpan: held().adoptActiveSpan === true,
33
+ });
34
+ }
35
+ /**
36
+ * What is active follows each request through its awaits: Node's AsyncLocalStorage, registered
37
+ * with OpenTelemetry's API — unless the platform registered a context manager first, which then
38
+ * carries it.
39
+ */
40
+ async function followEachRequest() {
41
+ try {
42
+ const [{ context }, { AsyncLocalStorageContextManager }] = await Promise.all([
43
+ import("@opentelemetry/api"),
44
+ import("@opentelemetry/context-async-hooks"),
45
+ ]);
46
+ const manager = new AsyncLocalStorageContextManager().enable();
47
+ if (!context.setGlobalContextManager(manager))
48
+ manager.disable();
49
+ }
50
+ catch (error) {
51
+ console.warn(`${WHO}: a request is not one tree — @opentelemetry/context-async-hooks did not load`, error);
52
+ }
53
+ }
25
54
  async function started(options) {
26
55
  try {
27
- const [{ trace }, { TracerProvider, BatchSpanProcessor, TraceIdRatioBasedSampler, ParentBasedSampler }, { OTLPTraceExporter }, { resourceFromAttributes }, { openTelemetryTracer },] = await Promise.all([
56
+ const [{ trace, propagation }, { TracerProvider, BatchSpanProcessor, TraceIdRatioBasedSampler, ParentBasedSampler }, { OTLPTraceExporter }, { resourceFromAttributes }, { W3CTraceContextPropagator }, { openTelemetryTracer },] = await Promise.all([
28
57
  import("@opentelemetry/api"),
29
58
  import("@opentelemetry/sdk-trace"),
30
59
  import("@opentelemetry/exporter-trace-otlp-http"),
31
60
  import("@opentelemetry/resources"),
61
+ import("@opentelemetry/core"),
32
62
  import("@sincpro/client-framework/opentelemetry"),
33
63
  ]);
64
+ // An SSR framework reads and writes `traceparent` only through the global propagator: with
65
+ // it Next continues a request's incoming trace and can write it into the page
66
+ // (`experimental.clientTraceMetadata`); without one, both are silently nothing. W3C trace
67
+ // context only — no baggage —, unless the platform registered a propagator first.
68
+ propagation.setGlobalPropagator(new W3CTraceContextPropagator());
69
+ if (options.oneTreePerRequest === true)
70
+ await followEachRequest();
34
71
  const exporter = new OTLPTraceExporter({
35
72
  url: options.endpoint,
36
73
  ...(options.headers ? { headers: { ...options.headers } } : {}),
@@ -42,7 +79,7 @@ async function started(options) {
42
79
  }),
43
80
  spanProcessors: [new BatchSpanProcessor({ exporter })],
44
81
  });
45
- held().tracerOf ??= (name) => openTelemetryTracer(trace.getTracer(name));
82
+ held().tracerOf ??= tracerOver(trace, openTelemetryTracer);
46
83
  if (!trace.setGlobalTracerProvider(provider)) {
47
84
  await provider.shutdown();
48
85
  console.warn(`${WHO}: another provider was registered first — use cases trace on it`);
@@ -64,7 +101,7 @@ function loadApi() {
64
101
  import("@opentelemetry/api"),
65
102
  import("@sincpro/client-framework/opentelemetry"),
66
103
  ]);
67
- held().tracerOf ??= (name) => openTelemetryTracer(trace.getTracer(name));
104
+ held().tracerOf ??= tracerOver(trace, openTelemetryTracer);
68
105
  }
69
106
  catch (error) {
70
107
  console.warn(`${WHO}: tracing is off — @opentelemetry/api did not load`, error);
@@ -9,6 +9,7 @@ import { explain } from "../../core/explain.js";
9
9
  import { choosesMany, } from "../../core/list.js";
10
10
  import { textOf, viewOf } from "../../core/present.js";
11
11
  import { summaryFieldsOf } from "../../core/summary.js";
12
+ import { trailKeyOf } from "../../core/trail.js";
12
13
  import { useFramework } from "../../react/context.js";
13
14
  import { useGroups } from "../../react/useGroups.js";
14
15
  import { usePivot } from "../../react/usePivot.js";
@@ -81,7 +82,7 @@ export function EntityList({ listing, api, columns: askedColumns, cells, yesNo,
81
82
  const ticking = selectable || choosingMany || selectionActions !== undefined;
82
83
  // The record opened from a row knows the page it came from: «3 / 64» and its neighbours.
83
84
  const { trails, dateStyle } = useFramework();
84
- const trailKey = `trail:${useId()}`;
85
+ const trailKey = trailKeyOf(useId());
85
86
  // Kept current with the page on screen: the row and its name (`RecordLink`) open the same
86
87
  // reference, and whichever opens it, the record finds where it came from.
87
88
  useEffect(() => {
@@ -1,6 +1,7 @@
1
1
  import { type Entity } from "@sincpro/client-framework";
2
2
  import type { AnyRecord } from "@sincpro/criteria";
3
3
  import { type ViewProps } from "@sincpro/web-composer";
4
+ import type { RecordRead } from "../../core/server.js";
4
5
  import { type RecordReading } from "../../react/useRecord.js";
5
6
  import { type ScreenActions } from "../list/dock.js";
6
7
  /** Who made a record, or changed it last, and when: `Record.Audit`'s. */
@@ -41,6 +42,9 @@ export declare function useRecordScreen<T extends AnyRecord>(entity: Entity<T>,
41
42
  title?: ((record: T) => string | null) | undefined;
42
43
  /** `false`: the screen draws its own history — it is not read here. */
43
44
  history?: boolean | undefined;
45
+ /** The record and its model already read on the server that renders the screen
46
+ * (`readRecordOnServer`): it starts from it, filled in the HTML (`useRecord`). */
47
+ initial?: RecordRead<T> | undefined;
44
48
  }): {
45
49
  reading: RecordReading<T>;
46
50
  crumbs: readonly import("@sincpro/web-composer").Crumb[];
@@ -73,8 +77,11 @@ export declare function useRecordScreen<T extends AnyRecord>(entity: Entity<T>,
73
77
  created?: Stamp | undefined;
74
78
  } | undefined;
75
79
  };
76
- export declare function EntityRecord<T extends AnyRecord>({ api, resource, entity, fields, pages, actions, title, }: ViewProps & {
80
+ export declare function EntityRecord<T extends AnyRecord>({ api, resource, entity, fields, pages, actions, title, initial, }: ViewProps & {
77
81
  entity: Entity<T>;
82
+ /** The record and its model already read on the server that renders the screen
83
+ * (`readRecordOnServer`): drawn filled there, and not asked again in the browser. */
84
+ initial?: RecordRead<T> | undefined;
78
85
  /** Its name, the screen's way — for a record whose model has no display field. */
79
86
  title?: (record: T) => string | null;
80
87
  /** The fields, in this order. Without it, the model's (`formOf`). */
@@ -71,7 +71,7 @@ function refusalOf(failure) {
71
71
  * carried these 150 lines itself (`shared/record_screen.tsx`).
72
72
  */
73
73
  export function useRecordScreen(entity, { api, resource }, options = {}) {
74
- const reading = useRecord(entity, resource);
74
+ const reading = useRecord(entity, resource, { initial: options.initial });
75
75
  const crumbs = useCrumbs(api);
76
76
  useRecordInWorkspace(api, reading, options);
77
77
  const look = presentationOf(entity);
@@ -151,8 +151,8 @@ export function useRecordScreen(entity, { api, resource }, options = {}) {
151
151
  },
152
152
  };
153
153
  }
154
- export function EntityRecord({ api, resource, entity, fields, pages, actions, title, }) {
155
- const screen = useRecordScreen(entity, { api, resource }, { title });
154
+ export function EntityRecord({ api, resource, entity, fields, pages, actions, title, initial, }) {
155
+ const screen = useRecordScreen(entity, { api, resource }, { title, initial });
156
156
  const { reading, crumbs, history, pager } = screen;
157
157
  const [page, setPage] = useState(undefined);
158
158
  const copy = frameworkCopy().record;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sincpro/web-framework",
3
- "version": "3.9.0",
3
+ "version": "3.11.0",
4
4
  "description": "The web client of sincpro_framework: entities, lists and records bound to the metadata the server publishes, drawn with @sincpro/web-ui and arranged with @sincpro/web-composer.",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -25,6 +25,10 @@
25
25
  "./errors": {
26
26
  "types": "./dist/errors/index.d.ts",
27
27
  "default": "./dist/errors/index.js"
28
+ },
29
+ "./errors/server": {
30
+ "types": "./dist/errors/server.d.ts",
31
+ "default": "./dist/errors/server.js"
28
32
  }
29
33
  },
30
34
  "publishConfig": {
@@ -40,10 +44,13 @@
40
44
  },
41
45
  "peerDependencies": {
42
46
  "@opentelemetry/api": "^1.10.0",
47
+ "@opentelemetry/context-async-hooks": "^3.1.0",
48
+ "@opentelemetry/core": "^3.1.0",
43
49
  "@opentelemetry/exporter-trace-otlp-http": "^0.301.0",
44
50
  "@opentelemetry/resources": "^3.1.0",
45
51
  "@opentelemetry/sdk-trace": "^3.1.0",
46
52
  "@sentry/browser": "^11.11.0",
53
+ "@sentry/core": "^11.11.0",
47
54
  "@sincpro/client-framework": "^2.3.0",
48
55
  "@sincpro/criteria": "^2.4.0",
49
56
  "@sincpro/criteria-react": "^2.4.0",
@@ -56,6 +63,12 @@
56
63
  "@opentelemetry/api": {
57
64
  "optional": true
58
65
  },
66
+ "@opentelemetry/context-async-hooks": {
67
+ "optional": true
68
+ },
69
+ "@opentelemetry/core": {
70
+ "optional": true
71
+ },
59
72
  "@opentelemetry/exporter-trace-otlp-http": {
60
73
  "optional": true
61
74
  },
@@ -67,16 +80,22 @@
67
80
  },
68
81
  "@sentry/browser": {
69
82
  "optional": true
83
+ },
84
+ "@sentry/core": {
85
+ "optional": true
70
86
  }
71
87
  },
72
88
  "devDependencies": {
73
89
  "@eslint/js": "^10.0.1",
74
90
  "@opentelemetry/api": "1.10.0",
91
+ "@opentelemetry/context-async-hooks": "3.1.1",
92
+ "@opentelemetry/core": "3.1.0",
75
93
  "@opentelemetry/exporter-trace-otlp-http": "0.301.0",
76
94
  "@opentelemetry/resources": "3.1.0",
77
95
  "@opentelemetry/sdk-trace": "3.1.0",
78
96
  "@sentry/browser": "11.11.0",
79
- "@sincpro/client-framework": "^2.3.0",
97
+ "@sentry/core": "11.11.0",
98
+ "@sincpro/client-framework": "^2.5.0",
80
99
  "@sincpro/criteria": "^2.4.0",
81
100
  "@sincpro/criteria-react": "^2.4.0",
82
101
  "@sincpro/web-composer": "^1.8.0",