@marktiderman/genesis-native 0.4.4 → 0.5.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.
Files changed (49) hide show
  1. package/README.md +98 -6
  2. package/dist/{block-Onqx7NiK.d.ts → block-DFnC8j5U.d.ts} +53 -3
  3. package/dist/{blocks-C2RDpvaN.d.ts → blocks-CyXjSGwV.d.ts} +12 -93
  4. package/dist/{chunk-75YP72G6.js → chunk-6L36FQBX.js} +95 -7
  5. package/dist/chunk-6L36FQBX.js.map +1 -0
  6. package/dist/chunk-C54LIT4N.js +73 -0
  7. package/dist/chunk-C54LIT4N.js.map +1 -0
  8. package/dist/chunk-MFHOHSEQ.js +249 -0
  9. package/dist/chunk-MFHOHSEQ.js.map +1 -0
  10. package/dist/chunk-VIC2KXMA.js +35 -0
  11. package/dist/chunk-VIC2KXMA.js.map +1 -0
  12. package/dist/devtools.d.ts +5 -4
  13. package/dist/devtools.js +3 -1
  14. package/dist/devtools.js.map +1 -1
  15. package/dist/index.d.ts +28 -4
  16. package/dist/index.js +13 -192
  17. package/dist/index.js.map +1 -1
  18. package/dist/observability.d.ts +33 -7
  19. package/dist/observability.js +20 -7
  20. package/dist/observability.js.map +1 -1
  21. package/dist/persist.d.ts +2 -1
  22. package/dist/persist.js +1 -1
  23. package/dist/push.d.ts +3 -3
  24. package/dist/query-DobJyRvs.d.ts +208 -0
  25. package/dist/screen-boundary-BlT6KBpa.d.ts +43 -0
  26. package/dist/updates.d.ts +2 -2
  27. package/dist/updates.js +3 -0
  28. package/dist/updates.js.map +1 -1
  29. package/dist/web-handoff.d.ts +88 -0
  30. package/dist/web-handoff.js +78 -0
  31. package/dist/web-handoff.js.map +1 -0
  32. package/package.json +9 -4
  33. package/src/app.tsx +16 -2
  34. package/src/errors.tsx +46 -7
  35. package/src/index.ts +24 -0
  36. package/src/observability/block.tsx +132 -5
  37. package/src/observability/index.ts +2 -0
  38. package/src/observability/sentry.ts +41 -6
  39. package/src/observability/sink.ts +30 -1
  40. package/src/query.ts +67 -1
  41. package/src/reload.ts +56 -0
  42. package/src/screen-boundary.tsx +116 -0
  43. package/src/updates/channels.ts +3 -0
  44. package/src/updates/checker.ts +3 -0
  45. package/src/web-handoff.ts +165 -0
  46. package/dist/chunk-75YP72G6.js.map +0 -1
  47. package/dist/chunk-VTJDIKFC.js +0 -39
  48. package/dist/chunk-VTJDIKFC.js.map +0 -1
  49. package/dist/query-DUmVAfsF.d.ts +0 -70
package/README.md CHANGED
@@ -303,10 +303,15 @@ export const observability = createObservability({
303
303
  dsn: process.env.EXPO_PUBLIC_SENTRY_DSN,
304
304
  signature: versionSignature({ application: Application, updates: Updates, platform: Platform.OS }),
305
305
  applicationId: Application.applicationId,
306
+ // Only your own hosts get Sentry's trace headers (default: none).
307
+ tracePropagationTargets: [process.env.EXPO_PUBLIC_SUPABASE_URL!],
306
308
  }),
307
309
  ],
308
310
  });
309
311
 
312
+ // One screen boundary for every route that exports it (see "Screen errors" below).
313
+ export const ScreenErrorBoundary = observability.screenBoundary();
314
+
310
315
  // app/_layout.tsx
311
316
  function RootLayout() {
312
317
  return <GenesisNativeApp {...shell} blocks={[observability]}>…</GenesisNativeApp>;
@@ -315,9 +320,31 @@ export default observability.wrap(RootLayout); // Sentry.wrap: touch and profile
315
320
  ```
316
321
 
317
322
  - **One error path.** Every error the shell catches (a render error in either boundary, a global
318
- error, a failed boot, an unhandled rejection) goes to the block's `onError` and then to yours.
319
- A sink that throws is reported to `onProblem` and never stops the other sinks or the fatal screen.
320
- `observability.captureError(error, { source: "sync" })` reports one you caught yourself.
323
+ error, a failed boot, an unhandled rejection, a query or mutation that failed unexpectedly) goes
324
+ to the block's `onError` and then to yours. A sink that throws is reported to `onProblem` and
325
+ never stops the other sinks or the fatal screen. `observability.captureError(error, { source:
326
+ "sync" })` reports one you caught yourself.
327
+ - **Packages report through one seam.** Creating the block makes it genesis-core's error reporter
328
+ (`setErrorReporter`), so a package's `reportError(error, "chat:attachment-action")` (a card's
329
+ action that failed, a draft that couldn't be saved, a realtime subscription that threw) reaches
330
+ the sinks as a non-fatal error with that source. Without the block, `reportError` writes to the
331
+ console in development and does nothing in production. `reportErrors: false` opts out.
332
+ - **Failed queries and mutations.** The shell watches its QueryClient's caches (yours too, when you
333
+ pass `queryClient.client`) and reports a query or mutation that failed for good (after its
334
+ retries) as `query` / `mutation`, tagged `query.key` / `mutation.key` with the key's first
335
+ segment only (`["tasks", id]` → `tasks`; a segment that looks like an id is left out). Only
336
+ unexpected errors (`classifyError(e).report`): offline, signed out, a record that's gone and the
337
+ server's expected refusals (forbidden, a conflict, a rejected value) are the screen's to show.
338
+ Opt one out with `meta: { reportErrors: false }`, or all of them with
339
+ `<GenesisNativeApp reportQueryErrors={false}>`. `reportQueryErrors(client, report)` is exported
340
+ for a client outside the shell.
341
+ - **What kind of error.** `classifyError(error)` (from `@marktiderman/genesis-native`, or
342
+ `@marktiderman/genesis-core/errors`) returns `{ kind, message, report }`: `kind` is `offline`,
343
+ `unauthenticated`, `forbidden`, `not-found`, `conflict`, `invalid` or `unexpected`; `message` is
344
+ a safe sentence from the catalogue (`errorMessages`, reworded with `{ messages }`), never the
345
+ error's own text; `report` says whether it is worth a crash report. Use it in a toast:
346
+ `toast.error(classifyError(e).message)`. The fatal and screen errors show the same sentence in
347
+ a release build, and the error's own text only in development.
321
348
  - **Init order.** `sentrySink` runs `Sentry.init` when it is called, so build the block at module
322
349
  scope, in a module the root layout imports before anything else: errors while the app's modules
323
350
  load are caught too. A second call in the same process (Fast Refresh) reuses the client.
@@ -350,8 +377,20 @@ export default observability.wrap(RootLayout); // Sentry.wrap: touch and profile
350
377
  (`/(app)/clients/[id]`), never the values in it. Sentry's `expoRouterIntegration` (on by
351
378
  default in `sentrySink`) records its own navigation spans and time to initial display, so the
352
379
  Sentry sink skips the block's navigation breadcrumbs.
353
- - **Crashes count.** A fatal error (the fatal screen, a failed boot) is sent as unhandled,
354
- so Sentry's release health counts it as a crash; a non-fatal one as handled.
380
+ - **Crashes count.** A fatal error (the fatal screen, a failed boot) and an unhandled promise
381
+ rejection are sent as unhandled, so Sentry's release health counts them; everything else as
382
+ handled.
383
+ - **Trace headers.** `tracePropagationTargets` (strings matched anywhere in the URL, or regular
384
+ expressions) lists the hosts that get Sentry's `sentry-trace` and `baggage` headers: your
385
+ Supabase project and your own API. Default none, so a third-party host never sees your trace
386
+ ids and its CORS never trips on them. It wins over `init.tracePropagationTargets`.
387
+ - **Flush before an update reloads.** The block registers a before-reload hook
388
+ (`onBeforeReload`): the updates block's banner reload and channel switch await it, so queued
389
+ events are sent before `reloadAsync` throws the runtime away. It waits at most
390
+ `flushBeforeReloadMs` (2000; 0 turns it off). `observability.flush(ms)` flushes on demand.
391
+ - **Point a support request at the event.** `observability.lastEventId()` is the id of the last
392
+ error event a sink sent, and `observability.replayId()` the session replay's id when replay is
393
+ on; a feedback or support screen attaches them.
355
394
  - **Environments.** `development` in `__DEV__`; otherwise one per kind of build from the channel:
356
395
  `production`, `preview` (`preview` and `pr-<number>`), `development`. Override with `environment`.
357
396
  - **Releases.** `sentrySink` sets `release` to `<applicationId>@<version>+<build>` and `dist` to the
@@ -360,6 +399,23 @@ export default observability.wrap(RootLayout); // Sentry.wrap: touch and profile
360
399
  told apart from the binary it runs on. Without an application id or version, it leaves the
361
400
  release to Sentry rather than guess.
362
401
  - **Without a DSN** `sentrySink` starts nothing (a warning outside development).
402
+
403
+ **Screen errors.** The shell's boundary is fatal: it replaces the whole app. For one screen that
404
+ throws, export a screen boundary from a route or layout file as Expo Router's `ErrorBoundary`:
405
+
406
+ ```tsx
407
+ // app/(app)/messages/_layout.tsx: a screen in this tab that throws shows "This screen hit a
408
+ // problem" with Try again; the tab bar and the other tabs keep working.
409
+ export { ScreenErrorBoundary as ErrorBoundary } from "@/lib/observability";
410
+ ```
411
+
412
+ `observability.screenBoundary(fallback?)` reports the error once, non-fatal (source `screen`),
413
+ shows `fallback` (default `ScreenErrorScreen`, Genesis UI) with "Try again" (Expo Router's
414
+ `retry`), and is wrapped with each sink's route wrapper: the Sentry sink uses
415
+ `Sentry.wrapExpoRouterErrorBoundary` when this Sentry has it (8.17+), and since that wrapper
416
+ reports the error itself (with the route attached), the block doesn't send it to Sentry twice.
417
+ Without the block, `createScreenErrorBoundary()` reports through `reportError`. Outside Expo
418
+ Router, wrap a subtree in `<ScreenErrorBoundary>`.
363
419
  - `useRecentActivity()` gives the last breadcrumbs and errors, scrubbed (the devtools overlay
364
420
  shows them).
365
421
 
@@ -683,6 +739,41 @@ increment reaches the extension (its `CURRENT_PROJECT_VERSION` is set at
683
739
  prebuild) hasn't been checked either. Donated conversations stay in Siri's
684
740
  suggestions after a person turns previews off.
685
741
 
742
+ ## Continue on the web: openOnWeb
743
+
744
+ `openOnWeb(path, options)` from `/web-handoff` opens a page of the web app signed in as the
745
+ person using the app, for work the app leaves to the web. It asks the app's server for a
746
+ single-use, 60-second link (genesis-supabase's `createWebHandoff`; the whole flow, its threats
747
+ and its lifetimes are in that package's README under "Continue on the web") and opens it.
748
+
749
+ ```ts
750
+ import * as WebBrowser from "expo-web-browser";
751
+ import { openOnWeb } from "@marktiderman/genesis-native/web-handoff";
752
+
753
+ await openOnWeb("/clients/1/forms", {
754
+ endpoint: "https://app.example.com/api/auth/handoff",
755
+ getAccessToken: async () => (await supabase.auth.getSession()).data.session?.access_token,
756
+ browser: WebBrowser,
757
+ browserOptions: { presentationStyle: WebBrowser.WebBrowserPresentationStyle.PAGE_SHEET },
758
+ });
759
+ ```
760
+
761
+ - It throws for anything but a path on the web app (`https://…`, `//host`, `/\host`); the
762
+ server checks again.
763
+ - Without a session, with the server unreachable (8 seconds), for an account without an email
764
+ or after too many links in a minute, it opens the page signed out (`{ signedIn: false, reason }`):
765
+ the person signs in there and lands on the path. It never opens a URL on another origin.
766
+ - **Signing out:** call `signOutOnWeb({ endpoint: "https://app.example.com/api/auth/handoff-signout",
767
+ getAccessToken })` just before the app's own sign-out. It ends the web sessions this app
768
+ session handed off (only those) and never throws, so it can't block signing out.
769
+ - **The browser:** `openBrowserAsync` (SFSafariViewController on iOS, a Custom Tab on Android),
770
+ not `Linking.openURL`. The person stays in the app, and Done brings them back. The in-app
771
+ browser keeps its website data between openings, separate from Safari, so the first handoff
772
+ asks "Continue as {email}?" once and later ones go straight to the page. Safari might be signed
773
+ in as someone else and ask every time. Not `openAuthSessionAsync`: it shows the system
774
+ "wants to use … to sign in" alert on every open. On Android a Custom Tab shares Chrome's
775
+ storage; the page asks before switching people there too.
776
+
686
777
  ## Blocks
687
778
 
688
779
  `blocks` takes `defineBlock` declarations (`@marktiderman/genesis-features/blocks`) a native shell
@@ -749,6 +840,7 @@ TanStack persister packages, for `/updates` `react-native-safe-area-context`
749
840
  (with `expo-updates` and `expo-application` passed in), and for `/push`
750
841
  `expo-notifications`, passed in too.
751
842
  `/observability` takes `@sentry/react-native` and `expo-observe` passed in;
752
- `/devtools` takes expo-sensors' `Accelerometer` and React Native's `DevSettings` passed in.
843
+ `/devtools` takes expo-sensors' `Accelerometer` and React Native's `DevSettings` passed in;
844
+ `/web-handoff` takes `expo-web-browser` passed in.
753
845
 
754
846
  @stability Beta
@@ -1,6 +1,8 @@
1
1
  import * as react from 'react';
2
2
  import { ComponentType, ReactNode } from 'react';
3
- import { N as NativeBlock, n as ErrorReport, x as NativeBlockRootProps } from './blocks-C2RDpvaN.js';
3
+ import { c as ScreenErrorProps } from './screen-boundary-BlT6KBpa.js';
4
+ import { N as NativeBlock, r as NativeBlockRootProps } from './blocks-CyXjSGwV.js';
5
+ import { b as ErrorReport } from './query-DobJyRvs.js';
4
6
 
5
7
  /**
6
8
  * Typed analytics events: the app lists every event and the props each may
@@ -64,11 +66,22 @@ declare function checkEvent(schema: EventSchema, name: string, props: Readonly<R
64
66
  interface ErrorContext {
65
67
  /** True when the app could not go on (a render error, a failed boot, a fatal global error). */
66
68
  fatal: boolean;
67
- /** `boundary`, `global`, `boot`, `rejection` (the shell's), or the app's own (`updates:policy`, `sync`). */
69
+ /**
70
+ * `boundary`, `global`, `boot`, `rejection`, `screen`, `query`, `mutation`
71
+ * (the shell's), a package's (`chat:attachment-action`, through
72
+ * `reportError` from genesis-core) or the app's own (`updates:policy`, `sync`).
73
+ */
68
74
  source: string;
69
75
  componentStack?: string;
70
76
  /** The route pattern on screen (`/(app)/settings`), when known. */
71
77
  route?: string | null;
78
+ /**
79
+ * False when nothing caught it (an unhandled promise rejection): release
80
+ * health counts it. Default: handled unless `fatal`.
81
+ */
82
+ handled?: boolean;
83
+ /** Low-cardinality labels (`query.key: "tasks"`), scrubbed like everything else. */
84
+ tags?: Readonly<Record<string, string>>;
72
85
  }
73
86
  type BreadcrumbLevel = "debug" | "info" | "warning" | "error";
74
87
  /** One step that led up to an error: a navigation, a tap, a request. */
@@ -104,6 +117,23 @@ interface ObservabilitySink {
104
117
  timing?(name: string, ms: number, tags?: TimingTags): void;
105
118
  /** Wraps the root layout (Sentry's `wrap`, EAS Observe's `ObserveRoot.wrap`). */
106
119
  wrap?<P extends Record<string, unknown>>(root: ComponentType<P>): ComponentType<P>;
120
+ /**
121
+ * Wraps an Expo Router per-route `ErrorBoundary` (Sentry's
122
+ * `wrapExpoRouterErrorBoundary`). A sink that wraps reports the route's
123
+ * error itself, so the block's screen boundary doesn't send it to that sink again.
124
+ */
125
+ wrapRouteErrorBoundary?(boundary: ComponentType<RouteErrorBoundaryProps>): ComponentType<RouteErrorBoundaryProps>;
126
+ /** Send what is queued, within `timeoutMs`; resolves false when it didn't finish. Called before an update reloads the app. */
127
+ flush?(timeoutMs: number): PromiseLike<boolean> | boolean | void;
128
+ /** The id of the last error event this sink sent, for a support request or feedback. */
129
+ lastEventId?(): string | undefined;
130
+ /** The current session replay's id, when replay is on. */
131
+ replayId?(): string | undefined;
132
+ }
133
+ /** What Expo Router gives a route's `ErrorBoundary`: the error, and `retry` to render the route again. */
134
+ interface RouteErrorBoundaryProps {
135
+ error: Error;
136
+ retry: () => Promise<void>;
107
137
  }
108
138
  /** A copy of `error` whose message and stack have been scrubbed (for sinks that don't scrub themselves). */
109
139
  declare function scrubbedError(error: Error): Error;
@@ -187,6 +217,13 @@ interface ObservabilityOptions<E extends EventSchema = EventSchema> {
187
217
  };
188
218
  /** A sink threw, or `track` was called with something the schema doesn't allow. Default `console.warn` in development. */
189
219
  onProblem?: (problem: string, error?: unknown) => void;
220
+ /**
221
+ * Become genesis-core's error reporter, so packages' `reportError` calls
222
+ * reach the sinks. Default true; the last block created wins.
223
+ */
224
+ reportErrors?: boolean;
225
+ /** Flush the sinks before an update reloads the app, within this many milliseconds. Default 2000; 0 turns it off. */
226
+ flushBeforeReloadMs?: number;
190
227
  now?: () => number;
191
228
  }
192
229
  interface ObservabilityBlock<E extends EventSchema = EventSchema> extends NativeBlock<typeof OBSERVABILITY_BLOCK_ID> {
@@ -204,6 +241,19 @@ interface ObservabilityBlock<E extends EventSchema = EventSchema> extends Native
204
241
  wrap<P extends Record<string, unknown>>(root: ComponentType<P>): ComponentType<P>;
205
242
  /** The last breadcrumbs and errors, scrubbed, for the devtools overlay. */
206
243
  readonly recent: RecentStore;
244
+ /** Send what every sink has queued; resolves false when one didn't finish within `timeoutMs` (default 2000). */
245
+ flush(timeoutMs?: number): Promise<boolean>;
246
+ /** The id of the last error event a sink sent (Sentry's), for a support request or feedback. */
247
+ lastEventId(): string | undefined;
248
+ /** The current session replay's id, when a sink records replays. */
249
+ replayId(): string | undefined;
250
+ /**
251
+ * An Expo Router `ErrorBoundary` for a route: reports the error non-fatal
252
+ * (source `screen`), shows `fallback` (default `ScreenErrorScreen`) with
253
+ * "Try again", and is wrapped by each sink's route wrapper (Sentry's
254
+ * `wrapExpoRouterErrorBoundary`). Build it once, at module scope.
255
+ */
256
+ screenBoundary(fallback?: ComponentType<ScreenErrorProps>): ComponentType<ScreenErrorProps>;
207
257
  /** For the shell: every error it catches. */
208
258
  readonly onError: (error: Error, report: ErrorReport) => void;
209
259
  readonly Root: ComponentType<NativeBlockRootProps>;
@@ -220,4 +270,4 @@ declare function useObservability(): ObservabilityBlock | null;
220
270
  /** The last breadcrumbs and errors, scrubbed; empty when the block is off. @stability Beta */
221
271
  declare function useRecentActivity(block?: ObservabilityBlock | null): RecentActivity;
222
272
 
223
- export { type Breadcrumb as B, type ConsoleSinkOptions as C, type ErrorContext as E, type ObservabilityBlock as O, type RecentActivity as R, type TimingTags as T, type ObservabilitySink as a, type BreadcrumbLevel as b, type EventCheck as c, type EventPropSpec as d, type EventProps as e, type EventSchema as f, type EventValues as g, OBSERVABILITY_BLOCK_ID as h, type ObservabilityOptions as i, ObservabilityProvider as j, type ObserveLike as k, type ObserveSinkOptions as l, type RecentError as m, type RecentStore as n, checkEvent as o, consoleSink as p, createObservability as q, defineEvents as r, observeSink as s, scrubBreadcrumb as t, scrubbedError as u, useObservability as v, useRecentActivity as w };
273
+ export { type Breadcrumb as B, type ConsoleSinkOptions as C, type ErrorContext as E, type ObservabilityBlock as O, type RecentActivity as R, type TimingTags as T, type RouteErrorBoundaryProps as a, type ObservabilitySink as b, type BreadcrumbLevel as c, type EventCheck as d, type EventPropSpec as e, type EventProps as f, type EventSchema as g, type EventValues as h, OBSERVABILITY_BLOCK_ID as i, type ObservabilityOptions as j, ObservabilityProvider as k, type ObserveLike as l, type ObserveSinkOptions as m, type RecentError as n, type RecentStore as o, checkEvent as p, consoleSink as q, createObservability as r, defineEvents as s, observeSink as t, scrubBreadcrumb as u, scrubbedError as v, useObservability as w, useRecentActivity as x };
@@ -1,13 +1,13 @@
1
1
  import * as react from 'react';
2
- import { ReactNode, ComponentType, Component, ErrorInfo } from 'react';
2
+ import { ReactNode, ComponentType } from 'react';
3
3
  import { Slots, SlotPropsFor } from '@marktiderman/genesis-core/slots';
4
4
  import { BlockDef, Contributed, BlockSettingsRow, ResolvedBlocks } from '@marktiderman/genesis-features/blocks';
5
+ import { d as FatalScreenProps, e as GenesisErrorBoundaryProps, h as QueryPersistence, c as ErrorUtilsLike, E as EnableRejectionTracker, g as QueryLifecycleOptions, O as OnError, b as ErrorReport } from './query-DobJyRvs.js';
5
6
  import { QueryClient, QueryClientConfig } from '@tanstack/react-query';
6
7
  import { CanonicalBrand } from '@marktiderman/genesis-design-system';
7
8
  import { SupabaseClientInput, DataProvider } from '@marktiderman/genesis-core/provider';
8
9
  import { KeyboardScrollProps, KeyboardToolbarProps } from '@marktiderman/genesis-ui-native/layouts';
9
10
  import { GenesisModules, NativeSheetLibrary, NativeToastProviderProps } from '@marktiderman/genesis-ui-native/components';
10
- import { b as QueryPersistence, Q as QueryLifecycleOptions } from './query-DUmVAfsF.js';
11
11
 
12
12
  interface BootStepContext {
13
13
  /**
@@ -65,96 +65,6 @@ interface UseBootReturn extends BootState {
65
65
  /** The boot's status, and `retry` after a failure. Inside `GenesisNativeApp` or a `BootProvider`. */
66
66
  declare function useBoot(): UseBootReturn;
67
67
 
68
- interface FatalScreenProps {
69
- error: Error;
70
- /** Clears the error and remounts the app below the shell (and re-runs a failed boot). */
71
- retry: () => void;
72
- }
73
- /** The default fatal screen: what went wrong and "Try again". */
74
- declare function FatalScreen({ error, retry }: FatalScreenProps): react.JSX.Element;
75
- /**
76
- * The last-resort fatal screen: React Native primitives only, no theme, no
77
- * context, nothing that can itself fail. Shown when the providers could not
78
- * start, or when the `fatal` slot threw.
79
- */
80
- declare function PlainFatalScreen({ error, retry }: FatalScreenProps): react.JSX.Element;
81
- interface ErrorReport {
82
- /** True when the app could not go on (a render error, a failed boot, a fatal global error). */
83
- fatal: boolean;
84
- source: "boundary" | "global" | "boot" | "rejection";
85
- componentStack?: string;
86
- }
87
- type OnError = (error: Error, report: ErrorReport) => void;
88
- interface GenesisErrorBoundaryProps {
89
- children?: ReactNode;
90
- /** What to render instead of the tree that threw. */
91
- fallback: ComponentType<FatalScreenProps>;
92
- onError?: OnError;
93
- /** Change it to clear a caught error (the tree remounts). */
94
- resetKey?: unknown;
95
- /** Called by the fallback's retry, after the error is cleared. */
96
- onRetry?: () => void;
97
- }
98
- interface BoundaryState {
99
- error: Error | null;
100
- }
101
- /** An error boundary whose fallback gets `{ error, retry }`. */
102
- declare class GenesisErrorBoundary extends Component<GenesisErrorBoundaryProps, BoundaryState> {
103
- state: BoundaryState;
104
- static getDerivedStateFromError(error: unknown): BoundaryState;
105
- componentDidCatch(error: unknown, info: ErrorInfo): void;
106
- componentDidUpdate(previous: GenesisErrorBoundaryProps): void;
107
- retry: () => void;
108
- render(): string | number | bigint | boolean | Iterable<ReactNode> | Promise<string | number | bigint | boolean | react.ReactPortal | react.ReactElement<unknown, string | react.JSXElementConstructor<any>> | Iterable<ReactNode> | null | undefined> | react.JSX.Element | null;
109
- }
110
- /** React Native's `ErrorUtils` (a global in every RN app), or a stand-in. */
111
- interface ErrorUtilsLike {
112
- getGlobalHandler(): ((error: unknown, isFatal?: boolean) => void) | undefined;
113
- setGlobalHandler(handler: (error: unknown, isFatal?: boolean) => void): void;
114
- }
115
- interface GlobalErrorHandlerOptions {
116
- errorUtils: ErrorUtilsLike;
117
- onError?: OnError;
118
- /** A fatal error: show the fatal screen. The previous handler (which would end the app) is not called. */
119
- onFatal: (error: Error) => void;
120
- /**
121
- * True while a fatal screen is already up. Another fatal error then goes to
122
- * the previous handler, which ends the app (it restarts clean) rather than
123
- * leaving it stuck behind a screen that may itself be broken.
124
- */
125
- alreadyFatal?: () => boolean;
126
- }
127
- /**
128
- * Route global errors to `onError`. A fatal one goes to `onFatal` instead of
129
- * React Native's default handler, which would close the app; a non-fatal one
130
- * still reaches the previous handler (LogBox in development). Returns a
131
- * function that puts the previous handler back.
132
- */
133
- declare function installGlobalErrorHandler({ errorUtils, onError, onFatal, alreadyFatal }: GlobalErrorHandlerOptions): () => void;
134
- /** `globalThis.ErrorUtils` in a React Native runtime, undefined elsewhere. */
135
- declare function defaultErrorUtils(): ErrorUtilsLike | undefined;
136
- /** Hermes's `HermesInternal.enablePromiseRejectionTracker`, or a stand-in. */
137
- type EnableRejectionTracker = (options: {
138
- allRejections: boolean;
139
- onUnhandled: (id: number, rejection: unknown) => void;
140
- onHandled: (id: number) => void;
141
- }) => void;
142
- /**
143
- * Hermes's rejection tracker, when the app runs on Hermes. React Native sends
144
- * unhandled rejections to `ExceptionsManager` (LogBox in development), never
145
- * to `ErrorUtils`' global handler, so without this they never reach `onError`.
146
- */
147
- declare function defaultRejectionTracker(): EnableRejectionTracker | undefined;
148
- /**
149
- * Report unhandled promise rejections to `onError` (non-fatal). This replaces
150
- * React Native's own tracker, so each rejection is also written with
151
- * `console.warn`, which LogBox shows in development as before.
152
- */
153
- declare function installRejectionTracker({ enable, onError }: {
154
- enable: EnableRejectionTracker;
155
- onError: OnError;
156
- }): void;
157
-
158
68
  /** The parts of a Supabase client the gate uses; a `SupabaseClient` fits. */
159
69
  interface AuthClientLike<S = unknown> {
160
70
  auth: {
@@ -1479,6 +1389,15 @@ interface GenesisNativeAppProps {
1479
1389
  rejectionTracker?: EnableRejectionTracker | null;
1480
1390
  /** `AppState` and NetInfo, so queries refetch on focus and know the network. */
1481
1391
  lifecycle?: QueryLifecycleOptions;
1392
+ /**
1393
+ * Report queries and mutations that failed for good to `onError` (and so
1394
+ * to the observability block), non-fatal, as `query` / `mutation` with the
1395
+ * key's first segment as a tag. Only unexpected errors: offline, signed
1396
+ * out, not found and the server's expected refusals are left to the
1397
+ * screen. One query opts out with `meta: { reportErrors: false }`.
1398
+ * Default true. Read once.
1399
+ */
1400
+ reportQueryErrors?: boolean;
1482
1401
  /**
1483
1402
  * Every caught error, after the blocks' own `onError` (the observability
1484
1403
  * block, `createObservability` from `/observability`, reports to Sentry
@@ -1592,4 +1511,4 @@ declare function useBlockSettings<R extends SettingsRowLike>(sections: readonly
1592
1511
  /** The merge `useBlockSettings` does, without hooks (subtitles already read). @stability Beta */
1593
1512
  declare function mergeBlockSettings<R extends SettingsRowLike>(sections: readonly BlockSettingsSection<R>[], rows: readonly Contributed<BlockSettingsRow>[], subtitles?: readonly (string | null | undefined)[], options?: UseBlockSettingsOptions): BlockSettingsSection<R | SettingsRowLike>[];
1594
1513
 
1595
- export { defaultRejectionTracker as $, type AuthClientLike as A, type BlockSettingsSection as B, type SessionStatus as C, type DevtoolsFeedbackProps as D, type EnableRejectionTracker as E, FatalScreen as F, GenesisErrorBoundary as G, type HeldLinkAuth as H, type SessionStore as I, type SessionStoreOptions as J, type SettingsRowLike as K, type LinkHold as L, type SignedOutProps as M, type NativeBlock as N, type OnError as O, PlainFatalScreen as P, type SplashModule as Q, type UseBlockSettingsOptions as R, SessionProvider as S, type UseBootReturn as T, type UpdatesBlock as U, type VersionSignature as V, type UseHeldLinkOptions as W, createBoot as X, createLinkHold as Y, createSessionStore as Z, defaultErrorUtils as _, type DevtoolsSlots as a, usePush as a$, installGlobalErrorHandler as a0, installRejectionTracker as a1, mergeBlockSettings as a2, normalizeLink as a3, useBlockSettings as a4, useBlocks as a5, useBoot as a6, useHeldLink as a7, useSession as a8, type PushPermissionStatus as a9, type PushDeviceCategory as aA, type PushErrorSource as aB, type PushOnError as aC, type PushOptions as aD, type PushPromptProps as aE, PushPromptSheet as aF, PushProvider as aG, PushRoot as aH, type PushRootProps as aI, type PushSlots as aJ, type PushStorageLike as aK, type PushSupabaseLike as aL, type Registration as aM, type RegistrationState as aN, type RegistrationStatus as aO, type SubscriptionLike as aP, canPush as aQ, createPermissionStore as aR, createPreferencesStore as aS, createPromptStore as aT, createPush as aU, createRegistration as aV, statusOf as aW, supabasePushBackend as aX, useBadge as aY, useNotificationPreferences as aZ, useOptionalPush as a_, type NotificationResponseLike as aa, type NotificationLike as ab, type QuietHours as ac, type ChannelImportance as ad, type ChannelInputLike as ae, DEFAULT_PREFERENCES as af, type NotificationActionLike as ag, type NotificationBehaviorLike as ah, type NotificationCategory as ai, type NotificationPreferences as aj, type NotificationsModuleLike as ak, type PermissionRequestLike as al, type PermissionState as am, type PermissionStatusLike as an, type PermissionStore as ao, type PreferencesState as ap, type PreferencesStatus as aq, type PreferencesStore as ar, type PromptOptions as as, type PromptState as at, type PromptStore as au, type PushAppStateLike as av, type PushBackend as aw, PushBackendError as ax, type PushBlock as ay, type PushChannel as az, AuthGate as b, useCanReload as b$, usePushPermissionState as b0, usePushPrompt as b1, usePushRegistration as b2, useSuppressNotifications as b3, validPreferences as b4, type ApplicationLike as b5, CLOCK_SKEW_MS as b6, type ChannelSwitchResult as b7, type ChannelSwitcher as b8, type ChannelSwitcherOptions as b9, type UpdatesModuleLike as bA, type UpdatesOnError as bB, type UpdatesOptions as bC, UpdatesProvider as bD, UpdatesRoot as bE, type UpdatesRootProps as bF, type UpdatesSlots as bG, type UpdatesStorageLike as bH, type VersionSignatureInput as bI, WEEK_MS as bJ, type WhatsNewOptions as bK, type WhatsNewProps as bL, WhatsNewSheet as bM, type WhatsNewState as bN, type WhatsNewStore as bO, createChannelSwitcher as bP, createPolicyStore as bQ, createReloadGuard as bR, createUpdateChecker as bS, createUpdates as bT, createWhatsNewStore as bU, evaluatePolicy as bV, notesSince as bW, sanitizePolicy as bX, staticPolicySource as bY, supabasePolicySource as bZ, useBlockReload as b_, type EvaluatePolicyOptions as ba, type ForceUpgradeProps as bb, ForceUpgradeScreen as bc, type MaintenanceProps as bd, MaintenanceScreen as be, type PolicyClientLike as bf, type PolicyOrigin as bg, type PolicyState as bh, type PolicyStore as bi, type PolicyStoreOptions as bj, type ReleaseNote as bk, type ReloadGuard as bl, type SupabasePolicySourceOptions as bm, UPDATES_BLOCK_ID as bn, UpdateBanner as bo, type UpdateBannerProps as bp, type UpdateCheckState as bq, type UpdateCheckStatus as br, type UpdateChecker as bs, type UpdateCheckerOptions as bt, type UpdatePlatform as bu, type UpdatePolicy as bv, type UpdatePolicySource as bw, type UpdateVerdict as bx, type UpdatesAppStateLike as by, type UpdatesErrorSource as bz, type AuthGateProps as c, useForceUpgrade as c0, useMaintenance as c1, useUpdateBanner as c2, useUpdateCheck as c3, useUpdatePolicy as c4, useUpdateVerdict as c5, useUpdates as c6, useVersionSignature as c7, useWhatsNew as c8, versionSignature as c9, type BootController as d, type BootOptions as e, BootProvider as f, BootScreen as g, type BootScreenProps as h, type BootState as i, type BootStatus as j, type BootStep as k, type BootStepContext as l, BootTimeoutError as m, type ErrorReport as n, type ErrorUtilsLike as o, type FatalScreenProps as p, type GenesisErrorBoundaryProps as q, GenesisNativeApp as r, type GenesisNativeAppProps as s, type GlobalErrorHandlerOptions as t, type LinkOptions as u, type LinkTarget as v, type NativeAppSlots as w, type NativeBlockRootProps as x, type NativeQueryClientOptions as y, type SessionState as z };
1514
+ export { type ChannelImportance as $, type AuthClientLike as A, type BlockSettingsSection as B, type UseBlockSettingsOptions as C, type DevtoolsFeedbackProps as D, type UseBootReturn as E, type UseHeldLinkOptions as F, GenesisNativeApp as G, type HeldLinkAuth as H, createBoot as I, createLinkHold as J, createSessionStore as K, type LinkHold as L, mergeBlockSettings as M, type NativeBlock as N, normalizeLink as O, useBlockSettings as P, useBlocks as Q, useBoot as R, SessionProvider as S, useHeldLink as T, type UpdatesBlock as U, type VersionSignature as V, useSession as W, type PushPermissionStatus as X, type NotificationResponseLike as Y, type NotificationLike as Z, type QuietHours as _, type DevtoolsSlots as a, type MaintenanceProps as a$, type ChannelInputLike as a0, DEFAULT_PREFERENCES as a1, type NotificationActionLike as a2, type NotificationBehaviorLike as a3, type NotificationCategory as a4, type NotificationPreferences as a5, type NotificationsModuleLike as a6, type PermissionRequestLike as a7, type PermissionState as a8, type PermissionStatusLike as a9, type RegistrationStatus as aA, type SubscriptionLike as aB, canPush as aC, createPermissionStore as aD, createPreferencesStore as aE, createPromptStore as aF, createPush as aG, createRegistration as aH, statusOf as aI, supabasePushBackend as aJ, useBadge as aK, useNotificationPreferences as aL, useOptionalPush as aM, usePush as aN, usePushPermissionState as aO, usePushPrompt as aP, usePushRegistration as aQ, useSuppressNotifications as aR, validPreferences as aS, type ApplicationLike as aT, CLOCK_SKEW_MS as aU, type ChannelSwitchResult as aV, type ChannelSwitcher as aW, type ChannelSwitcherOptions as aX, type EvaluatePolicyOptions as aY, type ForceUpgradeProps as aZ, ForceUpgradeScreen as a_, type PermissionStore as aa, type PreferencesState as ab, type PreferencesStatus as ac, type PreferencesStore as ad, type PromptOptions as ae, type PromptState as af, type PromptStore as ag, type PushAppStateLike as ah, type PushBackend as ai, PushBackendError as aj, type PushBlock as ak, type PushChannel as al, type PushDeviceCategory as am, type PushErrorSource as an, type PushOnError as ao, type PushOptions as ap, type PushPromptProps as aq, PushPromptSheet as ar, PushProvider as as, PushRoot as at, type PushRootProps as au, type PushSlots as av, type PushStorageLike as aw, type PushSupabaseLike as ax, type Registration as ay, type RegistrationState as az, AuthGate as b, MaintenanceScreen as b0, type PolicyClientLike as b1, type PolicyOrigin as b2, type PolicyState as b3, type PolicyStore as b4, type PolicyStoreOptions as b5, type ReleaseNote as b6, type ReloadGuard as b7, type SupabasePolicySourceOptions as b8, UPDATES_BLOCK_ID as b9, type WhatsNewStore as bA, createChannelSwitcher as bB, createPolicyStore as bC, createReloadGuard as bD, createUpdateChecker as bE, createUpdates as bF, createWhatsNewStore as bG, evaluatePolicy as bH, notesSince as bI, sanitizePolicy as bJ, staticPolicySource as bK, supabasePolicySource as bL, useBlockReload as bM, useCanReload as bN, useForceUpgrade as bO, useMaintenance as bP, useUpdateBanner as bQ, useUpdateCheck as bR, useUpdatePolicy as bS, useUpdateVerdict as bT, useUpdates as bU, useVersionSignature as bV, useWhatsNew as bW, versionSignature as bX, UpdateBanner as ba, type UpdateBannerProps as bb, type UpdateCheckState as bc, type UpdateCheckStatus as bd, type UpdateChecker as be, type UpdateCheckerOptions as bf, type UpdatePlatform as bg, type UpdatePolicy as bh, type UpdatePolicySource as bi, type UpdateVerdict as bj, type UpdatesAppStateLike as bk, type UpdatesErrorSource as bl, type UpdatesModuleLike as bm, type UpdatesOnError as bn, type UpdatesOptions as bo, UpdatesProvider as bp, UpdatesRoot as bq, type UpdatesRootProps as br, type UpdatesSlots as bs, type UpdatesStorageLike as bt, type VersionSignatureInput as bu, WEEK_MS as bv, type WhatsNewOptions as bw, type WhatsNewProps as bx, WhatsNewSheet as by, type WhatsNewState as bz, type AuthGateProps as c, type BootController as d, type BootOptions as e, BootProvider as f, BootScreen as g, type BootScreenProps as h, type BootState as i, type BootStatus as j, type BootStep as k, type BootStepContext as l, BootTimeoutError as m, type GenesisNativeAppProps as n, type LinkOptions as o, type LinkTarget as p, type NativeAppSlots as q, type NativeBlockRootProps as r, type NativeQueryClientOptions as s, type SessionState as t, type SessionStatus as u, type SessionStore as v, type SessionStoreOptions as w, type SettingsRowLike as x, type SignedOutProps as y, type SplashModule as z };
@@ -1,6 +1,9 @@
1
+ import { createScreenErrorBoundary } from './chunk-MFHOHSEQ.js';
2
+ import { onBeforeReload } from './chunk-VIC2KXMA.js';
1
3
  import { useSession } from './chunk-NGYNYJPL.js';
2
4
  import { createContext, useContext, useSyncExternalStore, useEffect, useRef } from 'react';
3
5
  import { defineBlock } from '@marktiderman/genesis-features/blocks';
6
+ import { setErrorReporter } from '@marktiderman/genesis-core/errors';
4
7
  import { jsx, jsxs } from 'react/jsx-runtime';
5
8
 
6
9
  // src/observability/events.ts
@@ -185,6 +188,7 @@ function scrubBreadcrumb(crumb) {
185
188
  };
186
189
  }
187
190
  var OBSERVABILITY_BLOCK_ID = "observability";
191
+ var releaseReloadHook;
188
192
  var TIMING_NAME = /^[a-z][a-z0-9_]*(?:\.[a-z][a-z0-9_]*)*$/;
189
193
  function createRecentStore(maxCrumbs, maxErrors) {
190
194
  let state = { breadcrumbs: [], errors: [] };
@@ -246,17 +250,67 @@ function createObservability(options) {
246
250
  recent.addCrumb(crumb);
247
251
  each("breadcrumb", (s) => s.breadcrumb?.(crumb));
248
252
  };
249
- const captureError = (value, context = {}) => {
253
+ const captureError = (value, context = {}, skip) => {
250
254
  const error = toError(value);
251
- const full = { fatal: context.fatal ?? false, source: context.source ?? "app", route: context.route ?? route, componentStack: context.componentStack };
255
+ const full = {
256
+ fatal: context.fatal ?? false,
257
+ source: context.source ?? "app",
258
+ route: context.route ?? route,
259
+ componentStack: context.componentStack,
260
+ ...context.handled !== void 0 ? { handled: context.handled } : {},
261
+ ...context.tags ? { tags: context.tags } : {}
262
+ };
252
263
  let safe;
253
264
  const scrubbed = () => safe ??= scrubbedError(error);
254
265
  try {
255
266
  recent.addError({ at: now(), name: error.name, message: scrubString(error.message), source: full.source, fatal: full.fatal });
256
267
  } catch {
257
268
  }
258
- const forSinks = full.componentStack ? { ...full, componentStack: scrubString(full.componentStack) } : full;
259
- each("captureError", (s) => s.captureError?.(s.scrubsErrors ? error : scrubbed(), s.scrubsErrors ? full : forSinks));
269
+ let forSinks = full;
270
+ try {
271
+ forSinks = {
272
+ ...full,
273
+ ...full.componentStack ? { componentStack: scrubString(full.componentStack) } : {},
274
+ ...full.tags ? { tags: scrubValue(full.tags) } : {}
275
+ };
276
+ } catch {
277
+ forSinks = { ...full, componentStack: void 0, tags: void 0 };
278
+ }
279
+ each("captureError", (s) => {
280
+ if (skip?.has(s)) return;
281
+ s.captureError?.(s.scrubsErrors ? error : scrubbed(), s.scrubsErrors ? full : forSinks);
282
+ });
283
+ };
284
+ const flush = async (timeoutMs = 2e3) => {
285
+ const results = sinks.map(async (sink) => {
286
+ if (!sink.flush) return true;
287
+ try {
288
+ return await sink.flush(timeoutMs) !== false;
289
+ } catch (error) {
290
+ problem(`${sink.name}.flush threw`, error);
291
+ return false;
292
+ }
293
+ });
294
+ let timer;
295
+ const deadline = new Promise((resolve) => {
296
+ timer = setTimeout(() => resolve(false), timeoutMs);
297
+ });
298
+ try {
299
+ return await Promise.race([Promise.all(results).then((all) => all.every(Boolean)), deadline]);
300
+ } finally {
301
+ if (timer !== void 0) clearTimeout(timer);
302
+ }
303
+ };
304
+ const firstOf = (read) => {
305
+ for (const sink of sinks) {
306
+ try {
307
+ const value = read(sink);
308
+ if (value) return value;
309
+ } catch (error) {
310
+ problem(`${sink.name} threw reading an id`, error);
311
+ }
312
+ }
313
+ return void 0;
260
314
  };
261
315
  const setUser = (id) => {
262
316
  if (id === user) return;
@@ -342,7 +396,33 @@ function createObservability(options) {
342
396
  wrap(root) {
343
397
  return sinks.reduce((wrapped, sink) => sink.wrap ? sink.wrap(wrapped) : wrapped, root);
344
398
  },
345
- onError: (error, report) => captureError(error, { fatal: report.fatal, source: report.source, componentStack: report.componentStack }),
399
+ onError: (error, report) => captureError(error, {
400
+ fatal: report.fatal,
401
+ source: report.source,
402
+ componentStack: report.componentStack,
403
+ ...report.handled !== void 0 ? { handled: report.handled } : {},
404
+ ...report.tags ? { tags: report.tags } : {}
405
+ }),
406
+ flush,
407
+ lastEventId: () => firstOf((s) => s.lastEventId?.()),
408
+ replayId: () => firstOf((s) => s.replayId?.()),
409
+ screenBoundary(fallback) {
410
+ const wrapping = sinks.filter((s) => s.wrapRouteErrorBoundary);
411
+ const skip = new Set(wrapping);
412
+ return createScreenErrorBoundary({
413
+ fallback,
414
+ onError: (error, report) => captureError(error, { fatal: report.fatal, source: report.source }, skip),
415
+ wrap: wrapping.map((sink) => (boundary) => {
416
+ try {
417
+ return sink.wrapRouteErrorBoundary(boundary);
418
+ } catch (error) {
419
+ problem(`${sink.name}.wrapRouteErrorBoundary threw`, error);
420
+ skip.delete(sink);
421
+ return boundary;
422
+ }
423
+ })
424
+ });
425
+ },
346
426
  Root: function ObservabilityRoot({ children }) {
347
427
  return /* @__PURE__ */ jsxs(ObservabilityContext.Provider, { value: block, children: [
348
428
  /* @__PURE__ */ jsx(UserTracker, {}),
@@ -351,6 +431,14 @@ function createObservability(options) {
351
431
  ] });
352
432
  }
353
433
  };
434
+ if (options.reportErrors !== false) {
435
+ setErrorReporter(
436
+ (value, context) => captureError(value, { fatal: context.fatal ?? false, source: context.source, ...context.tags ? { tags: context.tags } : {} })
437
+ );
438
+ }
439
+ const flushMs = options.flushBeforeReloadMs ?? 2e3;
440
+ releaseReloadHook?.();
441
+ releaseReloadHook = flushMs > 0 && sinks.some((s) => s.flush) ? onBeforeReload(() => flush(flushMs)) : void 0;
354
442
  return block;
355
443
  }
356
444
  var ObservabilityContext = createContext(null);
@@ -370,5 +458,5 @@ var EMPTY_STORE = { getState: () => EMPTY, subscribe: () => () => {
370
458
  }};
371
459
 
372
460
  export { FILTERED, OBSERVABILITY_BLOCK_ID, ObservabilityProvider, checkEvent, consoleSink, createObservability, defineEvents, isSecretKey, observeSink, scrubBreadcrumb, scrubEvent, scrubRecord, scrubString, scrubUrl, scrubValue, scrubbedError, useObservability, useRecentActivity };
373
- //# sourceMappingURL=chunk-75YP72G6.js.map
374
- //# sourceMappingURL=chunk-75YP72G6.js.map
461
+ //# sourceMappingURL=chunk-6L36FQBX.js.map
462
+ //# sourceMappingURL=chunk-6L36FQBX.js.map