@marktiderman/genesis-native 0.8.0 → 0.10.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 (40) hide show
  1. package/README.md +22 -14
  2. package/dist/{block-q6_CV0WK.d.ts → block-CQz1pOnm.d.ts} +4 -4
  3. package/dist/{blocks-ByVBKaQW.d.ts → blocks-dppiMmy-.d.ts} +7 -4
  4. package/dist/{chunk-6L36FQBX.js → chunk-EWHO5WQU.js} +3 -3
  5. package/dist/{chunk-6L36FQBX.js.map → chunk-EWHO5WQU.js.map} +1 -1
  6. package/dist/{chunk-C54LIT4N.js → chunk-FKDZP3RJ.js} +2 -2
  7. package/dist/chunk-FKDZP3RJ.js.map +1 -0
  8. package/dist/{chunk-MFHOHSEQ.js → chunk-YIF4BFQH.js} +33 -28
  9. package/dist/chunk-YIF4BFQH.js.map +1 -0
  10. package/dist/devtools.d.ts +5 -5
  11. package/dist/devtools.js +2 -2
  12. package/dist/index.d.ts +4 -4
  13. package/dist/index.js +9 -8
  14. package/dist/index.js.map +1 -1
  15. package/dist/observability.d.ts +5 -5
  16. package/dist/observability.js +3 -3
  17. package/dist/offline.d.ts +40 -0
  18. package/dist/offline.js +118 -0
  19. package/dist/offline.js.map +1 -0
  20. package/dist/persist.d.ts +11 -3
  21. package/dist/persist.js +6 -3
  22. package/dist/persist.js.map +1 -1
  23. package/dist/push.d.ts +3 -3
  24. package/dist/{query-DobJyRvs.d.ts → query--ihYsJWC.d.ts} +31 -9
  25. package/dist/{screen-boundary-BlT6KBpa.d.ts → screen-boundary-B8DlsLwb.d.ts} +8 -4
  26. package/dist/updates.d.ts +2 -2
  27. package/dist/updates.js +10 -10
  28. package/dist/updates.js.map +1 -1
  29. package/package.json +15 -10
  30. package/src/app.tsx +9 -6
  31. package/src/errors.tsx +56 -22
  32. package/src/index.ts +2 -0
  33. package/src/observability/block.tsx +1 -1
  34. package/src/offline/sqlite-local-cache.ts +161 -0
  35. package/src/persist.ts +16 -4
  36. package/src/query.ts +5 -2
  37. package/src/screen-boundary.tsx +13 -21
  38. package/src/updates/screens.tsx +10 -22
  39. package/dist/chunk-C54LIT4N.js.map +0 -1
  40. package/dist/chunk-MFHOHSEQ.js.map +0 -1
package/README.md CHANGED
@@ -105,23 +105,30 @@ From the outside in:
105
105
  network is back, and stale queries refetch on reconnect. Offline, saved
106
106
  data stays on screen; a query with nothing saved is `pending` with
107
107
  `isPaused` (show "offline", not a spinner); a mutation fails at once (no
108
- retries by default). With `persist`, the query-key roots you list are saved to the
109
- phone for 24 hours (`maxAge`), discarded when `buster` (your app version)
110
- changes, and **scoped to the signed-in user**: the user id is part of what
111
- is saved, a cache saved for anyone else is deleted instead of restored, and
112
- the cache (in memory and on disk) is cleared whenever the user changes:
113
- sign-out, a session that ended while the app was closed, an account switch.
108
+ retries by default). With `persist`, the reads of the resources you list are kept
109
+ on the phone, **per record**, in SQLite, and restored before the screens first
110
+ render, so lists and records open at once and then refresh. They're kept for 7
111
+ days (`maxAge`), discarded when `buster` (your app version) changes, and
112
+ **scoped to the signed-in user**: another user's are never restored, and the cache
113
+ (in memory and on disk) is cleared whenever the user changes: sign-out, a session
114
+ that ended while the app was closed, an account switch. Only reads that came back
115
+ from the provider are kept, never an unsaved change.
114
116
 
115
117
  ```ts
116
- import { persistQueries } from "@marktiderman/genesis-native/persist";
117
- export const persist = persistQueries({ storage: AsyncStorage, keys: ["clients", "me"], buster: version });
118
+ import * as SQLite from "expo-sqlite";
119
+ import { persistOffline, sqliteLocalCache } from "@marktiderman/genesis-native/offline";
120
+
121
+ const db = SQLite.openDatabaseSync("genesis-offline.db");
122
+ export const persist = persistOffline({ cache: sqliteLocalCache({ db }), resources: ["clients", "me"], buster: version });
118
123
  ```
119
124
 
120
- Persistence is its own entry point: an app that saves nothing doesn't need
121
- `@tanstack/query-persist-client-core` or
122
- `@tanstack/query-async-storage-persister`. If you do, install them at the
123
- same version as your `@tanstack/react-query`: they pin `@tanstack/query-core`
124
- exactly, and two copies of it don't share a cache.
125
+ List only resources whose rows may sit on the phone unencrypted (the OS keeps app
126
+ storage private, but the app doesn't encrypt it). The device cache is its own entry
127
+ point (`/offline`): an app that keeps nothing doesn't need expo-sqlite.
128
+ expo-sqlite is a native module: an app whose builds don't have it needs a new native build,
129
+ not an OTA update, to start using this.
130
+ `persistQueries` (`/persist`, one AsyncStorage blob) is **deprecated**: see
131
+ [the migration guide](https://github.com/marktiderman/genesis/blob/main/docs/MIGRATION.md).
125
132
 
126
133
  Pass `lifecycle={{ appState: AppState, netInfo: NetInfo }}` to refetch on
127
134
  focus and follow the network.
@@ -832,7 +839,8 @@ a set-up mistake, found at launch.
832
839
  `createBoot` + `BootProvider` + `useBoot`; `GenesisErrorBoundary` +
833
840
  `installGlobalErrorHandler` + `installRejectionTracker` + `FatalScreen` +
834
841
  `PlainFatalScreen`; `createNativeQueryClient` + `connectQueryLifecycle`, and
835
- `createQueryPersistence` / `persistQueries` from `/persist`;
842
+ `persistOffline` + `sqliteLocalCache` from `/offline` (and the deprecated
843
+ `createQueryPersistence` / `persistQueries` from `/persist`);
836
844
  `createSessionStore` + `SessionProvider` + `useSession` + `AuthGate`;
837
845
  `normalizeLink`; `createLinkHold` + `useHeldLink`.
838
846
 
@@ -1,8 +1,8 @@
1
1
  import * as react from 'react';
2
2
  import { ComponentType, ReactNode } from 'react';
3
- import { c as ScreenErrorProps } from './screen-boundary-BlT6KBpa.js';
4
- import { N as NativeBlock, r as NativeBlockRootProps } from './blocks-ByVBKaQW.js';
5
- import { b as ErrorReport } from './query-DobJyRvs.js';
3
+ import { c as ScreenErrorProps } from './screen-boundary-B8DlsLwb.js';
4
+ import { N as NativeBlock, r as NativeBlockRootProps } from './blocks-dppiMmy-.js';
5
+ import { b as ErrorReport } from './query--ihYsJWC.js';
6
6
 
7
7
  /**
8
8
  * Typed analytics events: the app lists every event and the props each may
@@ -249,7 +249,7 @@ interface ObservabilityBlock<E extends EventSchema = EventSchema> extends Native
249
249
  replayId(): string | undefined;
250
250
  /**
251
251
  * An Expo Router `ErrorBoundary` for a route: reports the error non-fatal
252
- * (source `screen`), shows `fallback` (default `ScreenErrorScreen`) with
252
+ * (source `screen`), shows `fallback` (default `<FatalScreen kind="screen" />`) with
253
253
  * "Try again", and is wrapped by each sink's route wrapper (Sentry's
254
254
  * `wrapExpoRouterErrorBoundary`). Build it once, at module scope.
255
255
  */
@@ -2,7 +2,7 @@ import * as react from 'react';
2
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
+ import { e as FatalScreenProps, g as GenesisErrorBoundaryProps, j as QueryPersistence, c as ErrorUtilsLike, E as EnableRejectionTracker, i as QueryLifecycleOptions, O as OnError, b as ErrorReport } from './query--ihYsJWC.js';
6
6
  import { QueryClient, QueryClientConfig } from '@tanstack/react-query';
7
7
  import { CanonicalBrand } from '@marktiderman/genesis-design-system';
8
8
  import { SupabaseClientInput, DataProvider } from '@marktiderman/genesis-core/provider';
@@ -597,7 +597,10 @@ interface WhatsNewProps {
597
597
  /** Close and remember this version. */
598
598
  dismiss: () => void;
599
599
  }
600
- /** The release notes for this version, once, in a sheet. */
600
+ /**
601
+ * The release notes for this version, once, in a sheet: the updates block's slot, drawn by
602
+ * genesis-ui-native's `NativeWhatsNewSheet` (the same sheet genesis-product's uses).
603
+ */
601
604
  declare function WhatsNewSheet({ notes, dismiss }: WhatsNewProps): react.JSX.Element;
602
605
 
603
606
  type UpdatesSlots = {
@@ -1322,8 +1325,8 @@ interface GenesisNativeAppProps {
1322
1325
  provider?: DataProvider;
1323
1326
  queryClient?: NativeQueryClientOptions;
1324
1327
  /**
1325
- * Save queries to the phone: `persistQueries({ storage, keys, buster })`
1326
- * from `@marktiderman/genesis-native/persist`. The saved cache belongs to
1328
+ * Keep reads on the phone: `persistOffline({ cache: sqliteLocalCache({ db }), resources, buster })`
1329
+ * from `@marktiderman/genesis-native/offline`. The saved cache belongs to
1327
1330
  * one user: it is restored only for that user and cleared when the user
1328
1331
  * changes (sign-out, a session that ended while the app was closed, an
1329
1332
  * account switch).
@@ -1,4 +1,4 @@
1
- import { createScreenErrorBoundary } from './chunk-MFHOHSEQ.js';
1
+ import { createScreenErrorBoundary } from './chunk-YIF4BFQH.js';
2
2
  import { onBeforeReload } from './chunk-VIC2KXMA.js';
3
3
  import { useSession } from './chunk-NGYNYJPL.js';
4
4
  import { createContext, useContext, useSyncExternalStore, useEffect, useRef } from 'react';
@@ -458,5 +458,5 @@ var EMPTY_STORE = { getState: () => EMPTY, subscribe: () => () => {
458
458
  }};
459
459
 
460
460
  export { FILTERED, OBSERVABILITY_BLOCK_ID, ObservabilityProvider, checkEvent, consoleSink, createObservability, defineEvents, isSecretKey, observeSink, scrubBreadcrumb, scrubEvent, scrubRecord, scrubString, scrubUrl, scrubValue, scrubbedError, useObservability, useRecentActivity };
461
- //# sourceMappingURL=chunk-6L36FQBX.js.map
462
- //# sourceMappingURL=chunk-6L36FQBX.js.map
461
+ //# sourceMappingURL=chunk-EWHO5WQU.js.map
462
+ //# sourceMappingURL=chunk-EWHO5WQU.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/observability/events.ts","../src/observability/scrub.ts","../src/observability/sink.ts","../src/observability/block.tsx"],"names":[],"mappings":";;;;;;;;;AAkCA,IAAM,UAAA,GAAa,yCAAA;AACnB,IAAM,SAAA,GAAY,mBAAA;AAClB,IAAM,SAAA,GAAY,EAAA;AAClB,IAAM,WAAA,GAAc,EAAA;AASb,SAAS,aAA0C,MAAA,EAAc;AACtE,EAAA,MAAM,WAAqB,EAAC;AAC5B,EAAA,KAAA,MAAW,CAAC,IAAA,EAA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,mBAAA,IAAuB,GAAA;AAE/C,EAAA,iBAAA,IAAoB;AACpB,EAAA,iBAAA,GAAoB,OAAA,GAAU,CAAA,IAAK,KAAA,CAAM,IAAA,CAAK,CAAC,CAAA,KAAM,CAAA,CAAE,KAAK,CAAA,GAAI,cAAA,CAAe,MAAM,KAAA,CAAM,OAAO,CAAC,CAAA,GAAI,MAAA;AACvG,EAAA,OAAO,KAAA;AACT;AAEA,IAAM,oBAAA,GAAuB,cAAyC,IAAI,CAAA;AAGnE,SAAS,qBAAA,CAAsB,EAAE,KAAA,EAAO,QAAA,EAAS,EAAwD;AAC9G,EAAA,2BAAQ,oBAAA,CAAqB,QAAA,EAArB,EAA8B,KAAA,EAAO,OAAQ,QAAA,EAAS,CAAA;AAChE;AAGO,SAAS,gBAAA,GAA8C;AAC5D,EAAA,OAAO,WAAW,oBAAoB,CAAA;AACxC;AAGO,SAAS,kBAAkB,KAAA,EAAmD;AACnF,EAAA,MAAM,cAAc,gBAAA,EAAiB;AACrC,EAAA,MAAM,KAAA,GAAA,CAAS,KAAA,IAAS,WAAA,GAAc,MAAA,IAAU,WAAA;AAChD,EAAA,OAAO,qBAAqB,KAAA,CAAM,SAAA,EAAW,KAAA,CAAM,QAAA,EAAU,MAAM,QAAQ,CAAA;AAC7E;AAEA,IAAM,QAAwB,EAAE,WAAA,EAAa,EAAC,EAAG,MAAA,EAAQ,EAAC,EAAE;AAC5D,IAAM,cAA2B,EAAE,QAAA,EAAU,MAAM,KAAA,EAAO,SAAA,EAAW,MAAM,MAAM;AAAC,CAAmB,CAAA","file":"chunk-6L36FQBX.js","sourcesContent":["/**\n * Typed analytics events: the app lists every event and the props each may\n * carry once, and `track(name, props)` accepts nothing else. A prop is a\n * closed list of strings, a number or a boolean, never free text, so an\n * event can't carry a name, an email or a message someone typed.\n *\n * ```ts\n * export const events = defineEvents({\n * \"auth.signed_in\": { method: [\"email\", \"apple\"] },\n * \"settings.opened\": {},\n * \"checkin.saved\": { mood: \"number\", first: \"boolean\" },\n * });\n * ```\n *\n * At run time an unknown event, an unknown prop or a value outside its list\n * is dropped and reported (a `console.warn` in development, `onInvalid`\n * always), so a bad call is loud and still sends nothing.\n */\n\n/** A closed list of strings, `\"number\"` (finite) or `\"boolean\"`. */\nexport type EventPropSpec = readonly string[] | \"number\" | \"boolean\";\n\n/** Every event, by name, with the props it may carry. */\nexport type EventSchema = Readonly<Record<string, Readonly<Record<string, EventPropSpec>>>>;\n\ntype PropValue<S> = S extends readonly (infer L)[] ? L : S extends \"number\" ? number : S extends \"boolean\" ? boolean : never;\n\n/** The props of one event: every prop optional, each its spec's type. */\nexport type EventProps<S extends Readonly<Record<string, EventPropSpec>>> = { readonly [K in keyof S]?: PropValue<S[K]> };\n\n/** What a sink receives: the checked props. */\nexport type EventValues = Readonly<Record<string, string | number | boolean>>;\n\n// Lower-case words joined by `.` or `_`: `auth.signed_in`, `checkin.saved`.\nconst EVENT_NAME = /^[a-z][a-z0-9_]*(?:\\.[a-z][a-z0-9_]*)*$/;\nconst PROP_NAME = /^[a-z][a-z0-9_]*$/;\nconst MAX_PROPS = 25;\nconst MAX_LITERAL = 64;\n\n/**\n * Declare the app's events. Checks names (lower-case, dot-separated), prop\n * names, and that each list has at least one short value, and throws listing\n * every problem, so a bad schema fails where it is written.\n *\n * @stability Beta\n */\nexport function defineEvents<const E extends EventSchema>(schema: E): E {\n const problems: string[] = [];\n for (const [name, props] of Object.entries(schema)) {\n if (!EVENT_NAME.test(name)) problems.push(`\"${name}\": an event name is lower-case words joined by \".\" (auth.signed_in)`);\n const keys = Object.keys(props);\n if (keys.length > MAX_PROPS) problems.push(`\"${name}\": at most ${MAX_PROPS} props`);\n for (const key of keys) {\n const spec = props[key];\n if (!PROP_NAME.test(key)) problems.push(`\"${name}\".${key}: a prop name is lower-case letters, digits and \"_\"`);\n if (Array.isArray(spec)) {\n if (spec.length === 0) problems.push(`\"${name}\".${key}: an empty list allows nothing`);\n for (const v of spec) if (typeof v !== \"string\" || v.length === 0 || v.length > MAX_LITERAL) problems.push(`\"${name}\".${key}: \"${String(v)}\" must be 1-${MAX_LITERAL} characters`);\n } else if (spec !== \"number\" && spec !== \"boolean\") {\n problems.push(`\"${name}\".${key}: a prop is a list of strings, \"number\" or \"boolean\" (free text is not allowed)`);\n }\n }\n }\n if (problems.length) throw new Error(`Invalid events:\\n${problems.map((p) => ` - ${p}`).join(\"\\n\")}`);\n return Object.freeze(schema);\n}\n\nexport type EventCheck = { ok: true; props: EventValues } | { ok: false; problem: string };\n\n/** Check one call against the schema: the props to send, or why nothing is sent. */\nexport function checkEvent(schema: EventSchema, name: string, props: Readonly<Record<string, unknown>> | undefined): EventCheck {\n if (!Object.prototype.hasOwnProperty.call(schema, name)) return { ok: false, problem: `\"${name}\" is not in the event schema` };\n const specs = schema[name] ?? {};\n const out: Record<string, string | number | boolean> = {};\n for (const [key, value] of Object.entries(props ?? {})) {\n if (value === undefined) continue;\n if (!Object.prototype.hasOwnProperty.call(specs, key)) return { ok: false, problem: `\"${name}\" has no prop \"${key}\"` };\n const spec = specs[key];\n const fits =\n spec === \"number\"\n ? typeof value === \"number\" && Number.isFinite(value)\n : spec === \"boolean\"\n ? typeof value === \"boolean\"\n : typeof value === \"string\" && (spec as readonly string[]).includes(value);\n if (!fits) return { ok: false, problem: `\"${name}\".${key}: ${JSON.stringify(value)} is not allowed` };\n out[key] = value as string | number | boolean;\n }\n return { ok: true, props: out };\n}\n","/**\n * The PII scrubber every sink's input goes through by default: text is\n * rewritten by pattern (an email, a phone number, a JWT, a Supabase key, a\n * bearer token, a token in a query string, row values in a database error),\n * values under a key that names a secret or a contact detail are replaced\n * whole, and URLs lose their query and fragment (PostgREST filters carry\n * record ids, auth callbacks carry codes). Strings are cut at 4 KB first, so\n * a huge log line can't stall the JS thread.\n *\n * What it can't know: a person's name in free text. Keep names out of error\n * messages and breadcrumbs; touch breadcrumbs lose their labels in\n * `sentrySink` for this reason.\n *\n * Pattern-based on values, not an allowlist of keys: a key allowlist misses\n * `refresh failed: eyJhbGciOi…`, which is the shape that actually occurs.\n *\n * Fail closed: `scrubEvent` and `scrubRecord` return `null` (drop it) when\n * scrubbing itself throws, never the unscrubbed input.\n */\n\n/** What replaces a value under a secret-looking key. */\nexport const FILTERED = \"[Filtered]\";\n\n// Keys whose value is a secret (or a contact detail) whatever it looks like.\n// Matched case-insensitively with `-`, `_`, `.` and spaces removed: exactly\n// for the short, ambiguous ones, as a part of the key for the rest\n// (`x-supabase-api-key`, `user.email`, `refresh_token_hash`).\nconst SECRET_KEY_EXACT = /^(session|sessionid|dsn|otp|code|verifier|codeverifier|privatekey|refresh|pwd|key)$/;\nconst SECRET_KEY_PART = /(authoriz|cookie|passw|secret|token|apikey|credential|jwt|email|phone|servicerole)/;\n\n/** True when a value under `key` is a secret (or contact detail) whatever it looks like. */\nexport function isSecretKey(key: string): boolean {\n const k = key.replace(/[-_.\\s]/g, \"\").toLowerCase();\n return SECRET_KEY_EXACT.test(k) || SECRET_KEY_PART.test(k);\n}\n\n// Sentry's own ids and envelope fields: 32-hex values the hex rule would break, never PII.\nconst ID_KEY = /^(event_id|trace_id|span_id|parent_span_id|profile_id|replay_id|debug_id|code_id|public_key|segment_id|sampled|release|dist|environment)$/;\n\n// Fields dropped whole: query strings travel as their own fields too (Sentry's http breadcrumbs,\n// spans and requests), and bodies and PostgREST `details` carry row values.\nconst DROPPED_KEY = /^(query_string|http\\.query|http\\.fragment|url\\.query|url\\.fragment|request_body|response_body|body|cookies|details)$/i;\n\n/** Longest string scrubbed in full; the rest is cut off (the patterns stay fast on huge logs). */\nexport const MAX_STRING = 4096;\n\nconst PATTERNS: readonly [RegExp, string][] = [\n // The query string and fragment of a URL with a scheme anywhere in text (a span's\n // \"GET https://…?id=eq.42\", a deep link \"myapp://reset?token_hash=…\").\n [/\\b([a-z][a-z0-9+.-]{0,31}:\\/\\/[^\\s?#\"'<>]{0,2048})[?#][^\\s\"'<>]*/gi, \"$1\"],\n // …and of a path (\"POST /rest/v1/rpc/find?email=eq.…\").\n [/(^|[\\s\"'(=])(\\/[^\\s?#\"'<>]{0,2048})\\?[^\\s\"'<>]*/g, \"$1$2\"],\n // JWTs: Supabase access tokens and the legacy anon / service_role keys.\n [/\\beyJ[A-Za-z0-9_-]{5,}\\.[A-Za-z0-9_-]{5,}\\.[A-Za-z0-9_-]*/g, \"[jwt]\"],\n // Supabase's API keys (sb_secret_…, sb_publishable_…).\n [/\\bsb_(?:secret|publishable)_[A-Za-z0-9_-]{8,}/g, \"[supabase-key]\"],\n // `Authorization: Bearer …` copied into a message.\n [/\\b(Bearer|Basic)\\s+[A-Za-z0-9._~+/=-]+/gi, \"$1 [token]\"],\n // Tokens in a query string or a fragment left without a scheme.\n [\n /([?&#](?:access_token|refresh_token|id_token|provider_token|provider_refresh_token|token|token_hash|code|apikey|api_key|key|password|secret|email|phone)=)[^&#\\s\"']+/gi,\n \"$1[Filtered]\",\n ],\n // Row values in PostgreSQL errors: `Failing row contains (…)`, `Key (email)=(…)`.\n [/(Failing row contains )\\([^)]*\\)/g, \"$1(…)\"],\n [/(Key \\([^)]{0,256}\\)=)\\([^)]*\\)/g, \"$1(…)\"],\n // Email addresses, also percent-encoded (`a%40b.co`). Bounded, so a long run of letters can't backtrack.\n [/[A-Za-z0-9._%+-]{1,64}(?:@|%40)(?:[A-Za-z0-9-]{1,63}\\.){1,8}[A-Za-z]{2,24}/g, \"[email]\"],\n // Phone numbers: international (`+1 555 555 0101`) and North American (`555-555-0101`).\n [/\\+\\d[\\d\\s().-]{6,18}\\d/g, \"[phone]\"],\n [/\\b\\(?\\d{3}\\)?[-.\\s]\\d{3}[-.\\s]\\d{4}\\b/g, \"[phone]\"],\n // Long opaque hex runs: API keys, refresh tokens, DSN secrets. Linear: a run starts only after a non-hex character.\n [/(^|[^A-Fa-f0-9])[A-Fa-f0-9]{32,}(?![A-Fa-f0-9])/g, \"$1[hex]\"],\n];\n\n/** A string with every URL query, email, phone number, JWT, Supabase key, bearer token and query-string token replaced. */\nexport function scrubString(value: string): string {\n let out = value.length > MAX_STRING ? `${value.slice(0, MAX_STRING)}…[truncated]` : value;\n for (const [pattern, replacement] of PATTERNS) out = out.replace(pattern, replacement);\n return out;\n}\n\n/** A URL without its query string and fragment, then scrubbed (an email in a path). */\nexport function scrubUrl(value: string): string {\n const cut = value.search(/[?#]/);\n return scrubString(cut === -1 ? value : value.slice(0, cut));\n}\n\n// Keys whose string value is cut at `?` when it is a URL.\nconst URL_KEY = /^(url|href|from|to|uri|description|http\\.url|url\\.full)$/i;\nconst MAX_DEPTH = 8;\n\n/**\n * A deep copy of `value` with every string scrubbed and every value under a\n * secret key replaced. Cycles become `\"[Circular]\"`; past 8 levels,\n * `\"[Truncated]\"`. Errors become `{ name, message }`. Header lists\n * (`[[\"authorization\", \"…\"]]`) are treated like objects.\n */\nexport function scrubValue(value: unknown, key = \"\", depth = 0, seen: WeakSet<object> = new WeakSet()): unknown {\n if (key && isSecretKey(key)) return value === undefined || value === null || value === \"\" ? value : FILTERED;\n if (typeof value === \"string\") {\n if (key && ID_KEY.test(key)) return value;\n return URL_KEY.test(key) ? scrubUrl(value) : scrubString(value);\n }\n if (value === null || typeof value !== \"object\") return value;\n if (seen.has(value)) return \"[Circular]\";\n if (depth >= MAX_DEPTH) return \"[Truncated]\";\n seen.add(value);\n if (value instanceof Error) return { name: value.name, message: scrubString(value.message) };\n if (Array.isArray(value)) {\n // A `[name, value]` pair (fetch's header lists): the name decides, as for an object key.\n if (value.length === 2 && typeof value[0] === \"string\" && isSecretKey(value[0])) return [value[0], FILTERED];\n return value.map((item) => scrubValue(item, \"\", depth + 1, seen));\n }\n const out: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(value)) {\n if (DROPPED_KEY.test(k)) continue;\n out[k] = scrubValue(v, k, depth + 1, seen);\n }\n return out;\n}\n\n/** The fields of a Sentry-shaped event `scrubEvent` treats specially. Anything else is scrubbed by value. */\nexport interface ScrubbableEvent {\n user?: { id?: unknown; [key: string]: unknown } | null;\n request?: { url?: unknown; method?: unknown; headers?: unknown; [key: string]: unknown };\n [key: string]: unknown;\n}\n\n/**\n * The event with the user reduced to its id, the request reduced to its\n * method, URL (cut at `?`) and scrubbed headers, and every other value\n * scrubbed. `null` when scrubbing threw: fail closed, send nothing rather\n * than PII.\n */\nexport function scrubEvent<E extends ScrubbableEvent>(event: E): E | null {\n try {\n // Sentry's processing metadata (scopes, the sampling context its envelope header is built\n // from) is never sent as part of the event: pass it through, or the envelope breaks.\n const { user, request, sdkProcessingMetadata, ...rest } = event;\n const out = scrubValue(rest) as E;\n if (sdkProcessingMetadata !== undefined) (out as ScrubbableEvent).sdkProcessingMetadata = sdkProcessingMetadata;\n if (user !== undefined) {\n (out as ScrubbableEvent).user = user && user.id !== undefined && user.id !== null ? { id: scrubString(String(user.id)) } : null;\n }\n if (request && typeof request === \"object\") {\n const safe: Record<string, unknown> = {};\n if (typeof request.url === \"string\") safe.url = scrubUrl(request.url);\n if (typeof request.method === \"string\") safe.method = request.method;\n if (request.headers && typeof request.headers === \"object\") safe.headers = scrubValue(request.headers);\n (out as ScrubbableEvent).request = safe;\n }\n return out;\n } catch {\n return null;\n }\n}\n\n/** A breadcrumb, span or any record, scrubbed by value. `null` when scrubbing threw (fail closed). */\nexport function scrubRecord<R extends object>(record: R): R | null {\n try {\n return scrubValue(record) as R;\n } catch {\n return null;\n }\n}\n","/**\n * The vendor-neutral seam: a sink is where errors, breadcrumbs, the user id,\n * analytics events and timings go. `createObservability` fans every call out\n * to its sinks, scrubbed first; a sink that throws is reported to\n * `onSinkError` and never takes the others (or the app) down with it.\n *\n * Shipped sinks: `sentrySink` (Sentry), `observeSink` (EAS Observe) and\n * `consoleSink` (development). A vendor adapter (PostHog, Datadog…) is one\n * object with the methods it supports.\n */\nimport type { ComponentType } from \"react\";\nimport { scrubString, scrubValue } from \"./scrub\";\nimport type { EventValues } from \"./events\";\n\n/** Where a caught error came from and whether the app could go on. */\nexport interface ErrorContext {\n /** True when the app could not go on (a render error, a failed boot, a fatal global error). */\n fatal: boolean;\n /**\n * `boundary`, `global`, `boot`, `rejection`, `screen`, `query`, `mutation`\n * (the shell's), a package's (`chat:attachment-action`, through\n * `reportError` from genesis-core) or the app's own (`updates:policy`, `sync`).\n */\n source: string;\n componentStack?: string;\n /** The route pattern on screen (`/(app)/settings`), when known. */\n route?: string | null;\n /**\n * False when nothing caught it (an unhandled promise rejection): release\n * health counts it. Default: handled unless `fatal`.\n */\n handled?: boolean;\n /** Low-cardinality labels (`query.key: \"tasks\"`), scrubbed like everything else. */\n tags?: Readonly<Record<string, string>>;\n}\n\nexport type BreadcrumbLevel = \"debug\" | \"info\" | \"warning\" | \"error\";\n\n/** One step that led up to an error: a navigation, a tap, a request. */\nexport interface Breadcrumb {\n /** `navigation`, `ui`, `http`, `event`, or the app's own. */\n category: string;\n message?: string;\n level?: BreadcrumbLevel;\n data?: Readonly<Record<string, unknown>>;\n /** Milliseconds since the epoch. Default now. */\n timestamp?: number;\n}\n\n/** Low-cardinality labels on a timing (`route`, `step`), never ids or text someone typed. */\nexport type TimingTags = Readonly<Record<string, string>>;\n\n/**\n * One destination. Every method is optional: a sink takes what its vendor\n * supports. Errors arrive as an `Error` whose message is already scrubbed,\n * unless the sink sets `scrubsErrors` (it scrubs the whole event itself and\n * needs the original object, as Sentry does to deduplicate).\n *\n * @stability Beta\n */\nexport interface ObservabilitySink {\n readonly name: string;\n /** The sink scrubs error events itself; give it the original `Error`. */\n readonly scrubsErrors?: boolean;\n captureError?(error: Error, context: ErrorContext): void;\n breadcrumb?(crumb: Breadcrumb): void;\n /** The signed-in login's id, or `null` when signed out. Never an email or a name. */\n setUser?(id: string | null): void;\n /** An analytics event, its props checked against the schema. */\n event?(name: string, props: EventValues): void;\n timing?(name: string, ms: number, tags?: TimingTags): void;\n /** Wraps the root layout (Sentry's `wrap`, EAS Observe's `ObserveRoot.wrap`). */\n wrap?<P extends Record<string, unknown>>(root: ComponentType<P>): ComponentType<P>;\n /**\n * Wraps an Expo Router per-route `ErrorBoundary` (Sentry's\n * `wrapExpoRouterErrorBoundary`). A sink that wraps reports the route's\n * error itself, so the block's screen boundary doesn't send it to that sink again.\n */\n wrapRouteErrorBoundary?(boundary: ComponentType<RouteErrorBoundaryProps>): ComponentType<RouteErrorBoundaryProps>;\n /** Send what is queued, within `timeoutMs`; resolves false when it didn't finish. Called before an update reloads the app. */\n flush?(timeoutMs: number): PromiseLike<boolean> | boolean | void;\n /** The id of the last error event this sink sent, for a support request or feedback. */\n lastEventId?(): string | undefined;\n /** The current session replay's id, when replay is on. */\n replayId?(): string | undefined;\n}\n\n/** What Expo Router gives a route's `ErrorBoundary`: the error, and `retry` to render the route again. */\nexport interface RouteErrorBoundaryProps {\n error: Error;\n retry: () => Promise<void>;\n}\n\n/** A copy of `error` whose message and stack have been scrubbed (for sinks that don't scrub themselves). */\nexport function scrubbedError(error: Error): Error {\n const copy = new Error(scrubString(error.message));\n copy.name = error.name;\n if (error.stack) copy.stack = scrubString(error.stack);\n return copy;\n}\n\nexport interface ConsoleSinkOptions {\n /** Default `console`. */\n console?: Pick<Console, \"log\" | \"warn\" | \"error\">;\n /** Also log breadcrumbs (noisy). Default false. */\n breadcrumbs?: boolean;\n}\n\n/**\n * Logs what would be sent, for development: fatal errors with `console.error`, others with `console.warn`,\n * events and timings with `console.log`. Already scrubbed, so what you read\n * is what a vendor sink would get.\n *\n * @stability Beta\n */\nexport function consoleSink(options: ConsoleSinkOptions = {}): ObservabilitySink {\n const out = options.console ?? console;\n return {\n name: \"console\",\n // `warn` for what the app survives: `console.error` would raise a LogBox error for every one in development.\n captureError: (error, context) => {\n const line = `[observability] ${context.fatal ? \"fatal \" : \"\"}${context.source}: ${error.message}`;\n if (context.fatal) out.error(line);\n else out.warn(line);\n },\n breadcrumb: options.breadcrumbs ? (crumb) => out.log(`[observability] · ${crumb.category} ${crumb.message ?? \"\"}`) : undefined,\n setUser: (id) => out.log(`[observability] user ${id ?? \"(signed out)\"}`),\n event: (name, props) => out.log(`[observability] event ${name}`, props),\n timing: (name, ms, tags) => out.log(`[observability] timing ${name} ${Math.round(ms)}ms`, tags ?? {}),\n };\n}\n\n/**\n * `expo-observe`'s `Observe` (SDK 56+), or a stand-in: the calls `observeSink`\n * uses. Pass `import { Observe } from \"expo-observe\"`.\n */\nexport interface ObserveLike {\n logEvent(name: string, options?: { severity?: \"debug\" | \"info\" | \"warn\" | \"error\"; body?: string; attributes?: Record<string, unknown> }): void;\n /** Error reporting, in preview on SDK 57+. */\n reportError?(error: unknown): void;\n}\n\nexport interface ObserveSinkOptions {\n /** Report caught errors with `Observe.reportError` (in preview). Default false: Sentry is the error tracker. */\n errors?: boolean;\n}\n\n/**\n * EAS Observe. It measures launch (cold, warm, bundle load, first render),\n * time to interactive and, with its Expo Router integration, per-route\n * render times on its own; it has no API for a custom timing metric, so\n * `timing` is logged as an event (`timing.<name>` with `duration_ms`) and\n * shows on the Events page, not as a metric. Analytics events go to\n * `Observe.logEvent` as they are.\n *\n * @stability Beta\n */\nexport function observeSink(observe: ObserveLike, options: ObserveSinkOptions = {}): ObservabilitySink {\n return {\n name: \"eas-observe\",\n event: (name, props) => observe.logEvent(name, { attributes: { ...props } }),\n timing: (name, ms, tags) => observe.logEvent(`timing.${name}`, { severity: \"info\", attributes: { duration_ms: Math.round(ms), ...(tags ?? {}) } }),\n captureError: options.errors && observe.reportError ? (error) => observe.reportError?.(error) : undefined,\n };\n}\n\n/** Breadcrumb data scrubbed and made plain (for sinks and the devtools overlay). */\nexport function scrubBreadcrumb(crumb: Breadcrumb): Breadcrumb {\n return {\n category: scrubString(crumb.category),\n level: crumb.level,\n timestamp: crumb.timestamp,\n ...(crumb.message !== undefined ? { message: scrubString(crumb.message) } : {}),\n ...(crumb.data ? { data: scrubValue(crumb.data) as Record<string, unknown> } : {}),\n };\n}\n","/**\n * `createObservability(options)`: the observability block. Build it once at\n * module scope (it starts the sinks, Sentry's `init` included), then:\n *\n * <GenesisNativeApp blocks={[observability]}> every error the shell catches → captureError\n * export default observability.wrap(RootLayout) Sentry's `wrap` (touch and profiler boundaries)\n * observability.track(\"auth.signed_in\", { method: \"email\" })\n *\n * Its root (inside the shell) sets the user to the signed-in login's id and,\n * with `useSegments` from expo-router, leaves a breadcrumb per route change\n * and a `route.time_on_screen` timing for the route left. Route patterns\n * (`/(app)/clients/[id]`) are used, never the values in them.\n *\n * Creating it also:\n * - registers it as genesis-core's error reporter (`setErrorReporter`), so a\n * package's `reportError(e, \"chat:…\")` reaches the sinks as a non-fatal error;\n * - registers a before-reload hook (`onBeforeReload`) that flushes the sinks\n * before an update reloads the app.\n *\n * `observability.screenBoundary()` is an Expo Router `ErrorBoundary` for a\n * route (reported non-fatal, wrapped by Sentry's route wrapper), and\n * `lastEventId()` / `replayId()` let a support or feedback screen point at\n * the event.\n *\n * Everything a sink receives has been scrubbed (see `scrub.ts`), and the\n * last breadcrumbs and errors are kept, scrubbed, for the devtools overlay\n * (`recent`).\n */\nimport { createContext, useContext, useEffect, useRef, useSyncExternalStore, type ComponentType, type ReactNode } from \"react\";\nimport { defineBlock } from \"@marktiderman/genesis-features/blocks\";\nimport { setErrorReporter } from \"@marktiderman/genesis-core/errors\";\nimport { useSession } from \"../auth\";\nimport { onBeforeReload } from \"../reload\";\nimport { createScreenErrorBoundary, type ScreenErrorProps } from \"../screen-boundary\";\nimport type { NativeBlock, NativeBlockRootProps } from \"../blocks\";\nimport type { ErrorReport } from \"../errors\";\nimport { checkEvent, type EventProps, type EventSchema } from \"./events\";\nimport { scrubString, scrubValue } from \"./scrub\";\nimport { scrubBreadcrumb, scrubbedError, type Breadcrumb, type ErrorContext, type ObservabilitySink, type TimingTags } from \"./sink\";\n\n/** The FeatureId of the observability block. */\nexport const OBSERVABILITY_BLOCK_ID = \"observability\";\n\n/** A caught error as the devtools overlay shows it (scrubbed). */\nexport interface RecentError {\n at: number;\n name: string;\n message: string;\n source: string;\n fatal: boolean;\n}\n\nexport interface RecentActivity {\n /** Oldest first. Navigation, events and the app's breadcrumbs. */\n breadcrumbs: readonly Breadcrumb[];\n /** Oldest first. */\n errors: readonly RecentError[];\n}\n\nexport interface RecentStore {\n getState(): RecentActivity;\n subscribe(listener: () => void): () => void;\n clear(): void;\n}\n\nexport interface ObservabilityOptions<E extends EventSchema = EventSchema> {\n /** Where everything goes: `sentrySink(Sentry, …)`, `consoleSink()` in development, `observeSink(Observe)`. */\n sinks: readonly (ObservabilitySink | null | undefined | false)[];\n /** The app's analytics events (`defineEvents`). Without it, `track` accepts nothing. */\n events?: E;\n /** `useSegments` from expo-router: route breadcrumbs and `route.time_on_screen` timings. */\n useSegments?: () => readonly string[];\n /** How many breadcrumbs and errors `recent` keeps. Default 50 and 20. */\n recent?: { breadcrumbs?: number; errors?: number };\n /** A sink threw, or `track` was called with something the schema doesn't allow. Default `console.warn` in development. */\n onProblem?: (problem: string, error?: unknown) => void;\n /**\n * Become genesis-core's error reporter, so packages' `reportError` calls\n * reach the sinks. Default true; the last block created wins.\n */\n reportErrors?: boolean;\n /** Flush the sinks before an update reloads the app, within this many milliseconds. Default 2000; 0 turns it off. */\n flushBeforeReloadMs?: number;\n now?: () => number;\n}\n\nexport interface ObservabilityBlock<E extends EventSchema = EventSchema> extends NativeBlock<typeof OBSERVABILITY_BLOCK_ID> {\n readonly sinks: readonly ObservabilitySink[];\n readonly events: E | undefined;\n /** Report an error. The shell calls it for every error it catches. */\n captureError(error: unknown, context?: Partial<ErrorContext>): void;\n breadcrumb(crumb: Breadcrumb): void;\n /** The login's id only. The block's root sets it from the session. */\n setUser(id: string | null): void;\n /** An analytics event from the schema. Anything else is dropped and reported. */\n track<N extends keyof E & string>(name: N, props?: EventProps<E[N]>): void;\n timing(name: string, ms: number, tags?: TimingTags): void;\n /** The root layout wrapped by each sink that wraps (Sentry's `wrap`). Use once: `export default observability.wrap(RootLayout)`. */\n wrap<P extends Record<string, unknown>>(root: ComponentType<P>): ComponentType<P>;\n /** The last breadcrumbs and errors, scrubbed, for the devtools overlay. */\n readonly recent: RecentStore;\n /** Send what every sink has queued; resolves false when one didn't finish within `timeoutMs` (default 2000). */\n flush(timeoutMs?: number): Promise<boolean>;\n /** The id of the last error event a sink sent (Sentry's), for a support request or feedback. */\n lastEventId(): string | undefined;\n /** The current session replay's id, when a sink records replays. */\n replayId(): string | undefined;\n /**\n * An Expo Router `ErrorBoundary` for a route: reports the error non-fatal\n * (source `screen`), shows `fallback` (default `ScreenErrorScreen`) with\n * \"Try again\", and is wrapped by each sink's route wrapper (Sentry's\n * `wrapExpoRouterErrorBoundary`). Build it once, at module scope.\n */\n screenBoundary(fallback?: ComponentType<ScreenErrorProps>): ComponentType<ScreenErrorProps>;\n /** For the shell: every error it catches. */\n readonly onError: (error: Error, report: ErrorReport) => void;\n readonly Root: ComponentType<NativeBlockRootProps>;\n}\n\ndeclare const __DEV__: boolean | undefined;\n\nlet releaseReloadHook: (() => void) | undefined;\n\nconst TIMING_NAME = /^[a-z][a-z0-9_]*(?:\\.[a-z][a-z0-9_]*)*$/;\n\nfunction createRecentStore(maxCrumbs: number, maxErrors: number): RecentStore & { addCrumb(c: Breadcrumb): void; addError(e: RecentError): void } {\n let state: RecentActivity = { breadcrumbs: [], errors: [] };\n const listeners = new Set<() => void>();\n const emit = () => listeners.forEach((l) => l());\n const push = <T,>(list: readonly T[], item: T, max: number) => (list.length >= max ? [...list.slice(list.length - max + 1), item] : [...list, item]);\n return {\n getState: () => state,\n subscribe(listener) {\n listeners.add(listener);\n return () => listeners.delete(listener);\n },\n clear() {\n state = { breadcrumbs: [], errors: [] };\n emit();\n },\n addCrumb(crumb) {\n state = { ...state, breadcrumbs: push(state.breadcrumbs, crumb, maxCrumbs) };\n emit();\n },\n addError(error) {\n state = { ...state, errors: push(state.errors, error, maxErrors) };\n emit();\n },\n };\n}\n\nfunction toError(value: unknown): Error {\n return value instanceof Error ? value : new Error(typeof value === \"string\" ? value : \"Unknown error\");\n}\n\n/** Build the block once, at module scope, before the root layout renders. @stability Beta */\nexport function createObservability<const E extends EventSchema = EventSchema>(options: ObservabilityOptions<E>): ObservabilityBlock<E> {\n const sinks = options.sinks.filter((s): s is ObservabilitySink => Boolean(s));\n const now = options.now ?? Date.now;\n const problem =\n options.onProblem ??\n ((message: string, error?: unknown) => {\n // genesis-allow-console: the block's own development warning; it can't report to itself.\n if (typeof __DEV__ !== \"undefined\" && __DEV__) console.warn(`[observability] ${message}`, error ?? \"\");\n });\n const recent = createRecentStore(options.recent?.breadcrumbs ?? 50, options.recent?.errors ?? 20);\n let route: string | null = null;\n let user: string | null | undefined;\n\n // One sink failing never stops the others, and never throws into the caller (an error handler, a render).\n const each = (method: string, call: (sink: ObservabilitySink) => void) => {\n for (const sink of sinks) {\n try {\n call(sink);\n } catch (error) {\n try {\n problem(`${sink.name}.${method} threw`, error);\n } catch {\n // ignore a failing reporter\n }\n }\n }\n };\n\n // Never throws into the caller (an effect, a handler): a record that can't be scrubbed is dropped.\n const breadcrumb = (input: Breadcrumb) => {\n let crumb: Breadcrumb;\n try {\n crumb = scrubBreadcrumb({ ...input, timestamp: input.timestamp ?? now() });\n } catch (error) {\n problem(\"breadcrumb dropped: it could not be scrubbed\", error);\n return;\n }\n recent.addCrumb(crumb);\n each(\"breadcrumb\", (s) => s.breadcrumb?.(crumb));\n };\n\n const captureError = (value: unknown, context: Partial<ErrorContext> = {}, skip?: ReadonlySet<ObservabilitySink>) => {\n const error = toError(value);\n const full: ErrorContext = {\n fatal: context.fatal ?? false,\n source: context.source ?? \"app\",\n route: context.route ?? route,\n componentStack: context.componentStack,\n ...(context.handled !== undefined ? { handled: context.handled } : {}),\n ...(context.tags ? { tags: context.tags } : {}),\n };\n let safe: Error | undefined;\n const scrubbed = () => (safe ??= scrubbedError(error));\n try {\n recent.addError({ at: now(), name: error.name, message: scrubString(error.message), source: full.source, fatal: full.fatal });\n } catch {\n // never let the overlay's list stop a report\n }\n let forSinks: ErrorContext = full;\n try {\n forSinks = {\n ...full,\n ...(full.componentStack ? { componentStack: scrubString(full.componentStack) } : {}),\n ...(full.tags ? { tags: scrubValue(full.tags) as Record<string, string> } : {}),\n };\n } catch {\n // Tags that can't be scrubbed are dropped, never sent raw.\n forSinks = { ...full, componentStack: undefined, tags: undefined };\n }\n each(\"captureError\", (s) => {\n if (skip?.has(s)) return;\n s.captureError?.(s.scrubsErrors ? error : scrubbed(), s.scrubsErrors ? full : forSinks);\n });\n };\n\n const flush = async (timeoutMs = 2000): Promise<boolean> => {\n const results = sinks.map(async (sink) => {\n if (!sink.flush) return true;\n try {\n return (await sink.flush(timeoutMs)) !== false;\n } catch (error) {\n problem(`${sink.name}.flush threw`, error);\n return false;\n }\n });\n let timer: ReturnType<typeof setTimeout> | undefined;\n const deadline = new Promise<boolean>((resolve) => {\n timer = setTimeout(() => resolve(false), timeoutMs);\n });\n try {\n return await Promise.race([Promise.all(results).then((all) => all.every(Boolean)), deadline]);\n } finally {\n if (timer !== undefined) clearTimeout(timer);\n }\n };\n\n const firstOf = (read: (sink: ObservabilitySink) => string | undefined): string | undefined => {\n for (const sink of sinks) {\n try {\n const value = read(sink);\n if (value) return value;\n } catch (error) {\n problem(`${sink.name} threw reading an id`, error);\n }\n }\n return undefined;\n };\n\n const setUser = (id: string | null) => {\n if (id === user) return;\n user = id;\n each(\"setUser\", (s) => s.setUser?.(id));\n };\n\n const track = (name: string, props?: Readonly<Record<string, unknown>>) => {\n const check = options.events ? checkEvent(options.events, name, props) : ({ ok: false, problem: \"no event schema: pass `events: defineEvents({…})`\" } as const);\n if (!check.ok) {\n problem(`track dropped: ${check.problem}`);\n return;\n }\n recent.addCrumb({ category: \"event\", message: name, level: \"info\", data: check.props, timestamp: now() });\n each(\"event\", (s) => s.event?.(name, check.props));\n };\n\n const timing = (name: string, ms: number, tags?: TimingTags) => {\n if (!Number.isFinite(ms) || ms < 0) return;\n // A name like an event's (`route.time_on_screen`), never text with values in it.\n if (!TIMING_NAME.test(name)) {\n problem(`timing dropped: \"${scrubString(name)}\" is not lower-case words joined by \".\"`);\n return;\n }\n let safeTags: TimingTags | undefined;\n try {\n safeTags = tags ? (scrubValue(tags) as TimingTags) : undefined;\n } catch (error) {\n problem(\"timing dropped: its tags could not be scrubbed\", error);\n return;\n }\n each(\"timing\", (s) => s.timing?.(name, ms, safeTags));\n };\n\n const declaration = defineBlock<typeof OBSERVABILITY_BLOCK_ID, ComponentType<never>>({\n id: OBSERVABILITY_BLOCK_ID,\n platforms: [\"native\"],\n contributes: {\n privacy: {\n collects: [\n // genesis-cli's PRIVACY_BLOCKS.observability mirrors this (with events) for the iOS\n // privacy manifest; observability/block.test.tsx keeps the two the same.\n { type: \"crash data\", purposes: [\"app functionality\"], linked: true, tracking: false },\n { type: \"performance data\", purposes: [\"app functionality\"], linked: true, tracking: false },\n // Sentry's device and OS details, breadcrumbs and sessions.\n { type: \"other diagnostic data\", purposes: [\"app functionality\"], linked: true, tracking: false },\n { type: \"user id\", purposes: options.events ? [\"app functionality\", \"analytics\"] : [\"app functionality\"], linked: true, tracking: false },\n ...(options.events ? [{ type: \"product interaction\", purposes: [\"analytics\"], linked: true, tracking: false }] : []),\n ],\n notes: [\n \"Crash reports, timings and analytics events carry the login's id only; emails, tokens, keys and query strings are removed on the device before anything is sent.\",\n ],\n },\n },\n });\n\n const useSegments = options.useSegments;\n function RouteTracker() {\n const segments = (useSegments as () => readonly string[])();\n const path = `/${segments.join(\"/\")}`;\n const last = useRef<{ path: string; at: number } | null>(null);\n useEffect(() => {\n const at = now();\n const previous = last.current;\n if (previous?.path === path) return;\n route = path;\n breadcrumb({ category: \"navigation\", message: path, data: previous ? { from: previous.path } : undefined, timestamp: at });\n if (previous) timing(\"route.time_on_screen\", at - previous.at, { route: previous.path });\n last.current = { path, at };\n }, [path]);\n return null;\n }\n\n function UserTracker() {\n const { userId } = useSession();\n useEffect(() => setUser(userId ?? null), [userId]);\n return null;\n }\n\n const block: ObservabilityBlock<E> = {\n ...declaration,\n sinks,\n events: options.events,\n captureError,\n breadcrumb,\n setUser,\n track: track as ObservabilityBlock<E>[\"track\"],\n timing,\n recent,\n wrap(root) {\n return sinks.reduce((wrapped, sink) => (sink.wrap ? sink.wrap(wrapped) : wrapped), root);\n },\n onError: (error, report) =>\n captureError(error, {\n fatal: report.fatal,\n source: report.source,\n componentStack: report.componentStack,\n ...(report.handled !== undefined ? { handled: report.handled } : {}),\n ...(report.tags ? { tags: report.tags } : {}),\n }),\n flush,\n lastEventId: () => firstOf((s) => s.lastEventId?.()),\n replayId: () => firstOf((s) => s.replayId?.()),\n screenBoundary(fallback) {\n const wrapping = sinks.filter((s) => s.wrapRouteErrorBoundary);\n // A sink whose wrapper reports the route's error (Sentry's) isn't sent it a second time.\n const skip = new Set(wrapping);\n return createScreenErrorBoundary({\n fallback,\n onError: (error, report) => captureError(error, { fatal: report.fatal, source: report.source }, skip),\n wrap: wrapping.map((sink) => (boundary: ComponentType<ScreenErrorProps>) => {\n try {\n return sink.wrapRouteErrorBoundary!(boundary);\n } catch (error) {\n problem(`${sink.name}.wrapRouteErrorBoundary threw`, error);\n skip.delete(sink);\n return boundary;\n }\n }),\n });\n },\n Root: function ObservabilityRoot({ children }: NativeBlockRootProps) {\n return (\n <ObservabilityContext.Provider value={block as ObservabilityBlock}>\n <UserTracker />\n {useSegments ? <RouteTracker /> : null}\n {children}\n </ObservabilityContext.Provider>\n );\n },\n };\n if (options.reportErrors !== false) {\n setErrorReporter((value, context) =>\n captureError(value, { fatal: context.fatal ?? false, source: context.source, ...(context.tags ? { tags: context.tags } : {}) }),\n );\n }\n const flushMs = options.flushBeforeReloadMs ?? 2000;\n // The newest block replaces the last one's hook (Fast Refresh builds the block again).\n releaseReloadHook?.();\n releaseReloadHook = flushMs > 0 && sinks.some((s) => s.flush) ? onBeforeReload(() => flush(flushMs)) : undefined;\n return block;\n}\n\nconst ObservabilityContext = createContext<ObservabilityBlock | null>(null);\n\n/** Provides a block to the hooks without its root (rung 4). @stability Beta */\nexport function ObservabilityProvider({ block, children }: { block: ObservabilityBlock; children?: ReactNode }) {\n return <ObservabilityContext.Provider value={block}>{children}</ObservabilityContext.Provider>;\n}\n\n/** The block, or `null` when it is off (so a screen can call it whether or not the block is on). @stability Beta */\nexport function useObservability(): ObservabilityBlock | null {\n return useContext(ObservabilityContext);\n}\n\n/** The last breadcrumbs and errors, scrubbed; empty when the block is off. @stability Beta */\nexport function useRecentActivity(block?: ObservabilityBlock | null): RecentActivity {\n const fromContext = useObservability();\n const store = (block ?? fromContext)?.recent ?? EMPTY_STORE;\n return useSyncExternalStore(store.subscribe, store.getState, store.getState);\n}\n\nconst EMPTY: RecentActivity = { breadcrumbs: [], errors: [] };\nconst EMPTY_STORE: RecentStore = { getState: () => EMPTY, subscribe: () => () => {}, clear: () => {} };\n"]}
1
+ {"version":3,"sources":["../src/observability/events.ts","../src/observability/scrub.ts","../src/observability/sink.ts","../src/observability/block.tsx"],"names":[],"mappings":";;;;;;;;;AAkCA,IAAM,UAAA,GAAa,yCAAA;AACnB,IAAM,SAAA,GAAY,mBAAA;AAClB,IAAM,SAAA,GAAY,EAAA;AAClB,IAAM,WAAA,GAAc,EAAA;AASb,SAAS,aAA0C,MAAA,EAAc;AACtE,EAAA,MAAM,WAAqB,EAAC;AAC5B,EAAA,KAAA,MAAW,CAAC,IAAA,EAAM,KAAK,KAAK,MAAA,CAAO,OAAA,CAAQ,MAAM,CAAA,EAAG;AAClD,IAAA,IAAI,CAAC,WAAW,IAAA,CAAK,IAAI,GAAG,QAAA,CAAS,IAAA,CAAK,CAAA,CAAA,EAAI,IAAI,CAAA,mEAAA,CAAqE,CAAA;AACvH,IAAA,MAAM,IAAA,GAAO,MAAA,CAAO,IAAA,CAAK,KAAK,CAAA;AAC9B,IAAA,IAAI,IAAA,CAAK,SAAS,SAAA,EAAW,QAAA,CAAS,KAAK,CAAA,CAAA,EAAI,IAAI,CAAA,WAAA,EAAc,SAAS,CAAA,MAAA,CAAQ,CAAA;AAClF,IAAA,KAAA,MAAW,OAAO,IAAA,EAAM;AACtB,MAAA,MAAM,IAAA,GAAO,MAAM,GAAG,CAAA;AACtB,MAAA,IAAI,CAAC,SAA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OAAO,WAAW,oBAAoB,CAAA;AACxC;AAGO,SAAS,kBAAkB,KAAA,EAAmD;AACnF,EAAA,MAAM,cAAc,gBAAA,EAAiB;AACrC,EAAA,MAAM,KAAA,GAAA,CAAS,KAAA,IAAS,WAAA,GAAc,MAAA,IAAU,WAAA;AAChD,EAAA,OAAO,qBAAqB,KAAA,CAAM,SAAA,EAAW,KAAA,CAAM,QAAA,EAAU,MAAM,QAAQ,CAAA;AAC7E;AAEA,IAAM,QAAwB,EAAE,WAAA,EAAa,EAAC,EAAG,MAAA,EAAQ,EAAC,EAAE;AAC5D,IAAM,cAA2B,EAAE,QAAA,EAAU,MAAM,KAAA,EAAO,SAAA,EAAW,MAAM,MAAM;AAAC,CAAmB,CAAA","file":"chunk-EWHO5WQU.js","sourcesContent":["/**\n * Typed analytics events: the app lists every event and the props each may\n * carry once, and `track(name, props)` accepts nothing else. A prop is a\n * closed list of strings, a number or a boolean, never free text, so an\n * event can't carry a name, an email or a message someone typed.\n *\n * ```ts\n * export const events = defineEvents({\n * \"auth.signed_in\": { method: [\"email\", \"apple\"] },\n * \"settings.opened\": {},\n * \"checkin.saved\": { mood: \"number\", first: \"boolean\" },\n * });\n * ```\n *\n * At run time an unknown event, an unknown prop or a value outside its list\n * is dropped and reported (a `console.warn` in development, `onInvalid`\n * always), so a bad call is loud and still sends nothing.\n */\n\n/** A closed list of strings, `\"number\"` (finite) or `\"boolean\"`. */\nexport type EventPropSpec = readonly string[] | \"number\" | \"boolean\";\n\n/** Every event, by name, with the props it may carry. */\nexport type EventSchema = Readonly<Record<string, Readonly<Record<string, EventPropSpec>>>>;\n\ntype PropValue<S> = S extends readonly (infer L)[] ? L : S extends \"number\" ? number : S extends \"boolean\" ? boolean : never;\n\n/** The props of one event: every prop optional, each its spec's type. */\nexport type EventProps<S extends Readonly<Record<string, EventPropSpec>>> = { readonly [K in keyof S]?: PropValue<S[K]> };\n\n/** What a sink receives: the checked props. */\nexport type EventValues = Readonly<Record<string, string | number | boolean>>;\n\n// Lower-case words joined by `.` or `_`: `auth.signed_in`, `checkin.saved`.\nconst EVENT_NAME = /^[a-z][a-z0-9_]*(?:\\.[a-z][a-z0-9_]*)*$/;\nconst PROP_NAME = /^[a-z][a-z0-9_]*$/;\nconst MAX_PROPS = 25;\nconst MAX_LITERAL = 64;\n\n/**\n * Declare the app's events. Checks names (lower-case, dot-separated), prop\n * names, and that each list has at least one short value, and throws listing\n * every problem, so a bad schema fails where it is written.\n *\n * @stability Beta\n */\nexport function defineEvents<const E extends EventSchema>(schema: E): E {\n const problems: string[] = [];\n for (const [name, props] of Object.entries(schema)) {\n if (!EVENT_NAME.test(name)) problems.push(`\"${name}\": an event name is lower-case words joined by \".\" (auth.signed_in)`);\n const keys = Object.keys(props);\n if (keys.length > MAX_PROPS) problems.push(`\"${name}\": at most ${MAX_PROPS} props`);\n for (const key of keys) {\n const spec = props[key];\n if (!PROP_NAME.test(key)) problems.push(`\"${name}\".${key}: a prop name is lower-case letters, digits and \"_\"`);\n if (Array.isArray(spec)) {\n if (spec.length === 0) problems.push(`\"${name}\".${key}: an empty list allows nothing`);\n for (const v of spec) if (typeof v !== \"string\" || v.length === 0 || v.length > MAX_LITERAL) problems.push(`\"${name}\".${key}: \"${String(v)}\" must be 1-${MAX_LITERAL} characters`);\n } else if (spec !== \"number\" && spec !== \"boolean\") {\n problems.push(`\"${name}\".${key}: a prop is a list of strings, \"number\" or \"boolean\" (free text is not allowed)`);\n }\n }\n }\n if (problems.length) throw new Error(`Invalid events:\\n${problems.map((p) => ` - ${p}`).join(\"\\n\")}`);\n return Object.freeze(schema);\n}\n\nexport type EventCheck = { ok: true; props: EventValues } | { ok: false; problem: string };\n\n/** Check one call against the schema: the props to send, or why nothing is sent. */\nexport function checkEvent(schema: EventSchema, name: string, props: Readonly<Record<string, unknown>> | undefined): EventCheck {\n if (!Object.prototype.hasOwnProperty.call(schema, name)) return { ok: false, problem: `\"${name}\" is not in the event schema` };\n const specs = schema[name] ?? {};\n const out: Record<string, string | number | boolean> = {};\n for (const [key, value] of Object.entries(props ?? {})) {\n if (value === undefined) continue;\n if (!Object.prototype.hasOwnProperty.call(specs, key)) return { ok: false, problem: `\"${name}\" has no prop \"${key}\"` };\n const spec = specs[key];\n const fits =\n spec === \"number\"\n ? typeof value === \"number\" && Number.isFinite(value)\n : spec === \"boolean\"\n ? typeof value === \"boolean\"\n : typeof value === \"string\" && (spec as readonly string[]).includes(value);\n if (!fits) return { ok: false, problem: `\"${name}\".${key}: ${JSON.stringify(value)} is not allowed` };\n out[key] = value as string | number | boolean;\n }\n return { ok: true, props: out };\n}\n","/**\n * The PII scrubber every sink's input goes through by default: text is\n * rewritten by pattern (an email, a phone number, a JWT, a Supabase key, a\n * bearer token, a token in a query string, row values in a database error),\n * values under a key that names a secret or a contact detail are replaced\n * whole, and URLs lose their query and fragment (PostgREST filters carry\n * record ids, auth callbacks carry codes). Strings are cut at 4 KB first, so\n * a huge log line can't stall the JS thread.\n *\n * What it can't know: a person's name in free text. Keep names out of error\n * messages and breadcrumbs; touch breadcrumbs lose their labels in\n * `sentrySink` for this reason.\n *\n * Pattern-based on values, not an allowlist of keys: a key allowlist misses\n * `refresh failed: eyJhbGciOi…`, which is the shape that actually occurs.\n *\n * Fail closed: `scrubEvent` and `scrubRecord` return `null` (drop it) when\n * scrubbing itself throws, never the unscrubbed input.\n */\n\n/** What replaces a value under a secret-looking key. */\nexport const FILTERED = \"[Filtered]\";\n\n// Keys whose value is a secret (or a contact detail) whatever it looks like.\n// Matched case-insensitively with `-`, `_`, `.` and spaces removed: exactly\n// for the short, ambiguous ones, as a part of the key for the rest\n// (`x-supabase-api-key`, `user.email`, `refresh_token_hash`).\nconst SECRET_KEY_EXACT = /^(session|sessionid|dsn|otp|code|verifier|codeverifier|privatekey|refresh|pwd|key)$/;\nconst SECRET_KEY_PART = /(authoriz|cookie|passw|secret|token|apikey|credential|jwt|email|phone|servicerole)/;\n\n/** True when a value under `key` is a secret (or contact detail) whatever it looks like. */\nexport function isSecretKey(key: string): boolean {\n const k = key.replace(/[-_.\\s]/g, \"\").toLowerCase();\n return SECRET_KEY_EXACT.test(k) || SECRET_KEY_PART.test(k);\n}\n\n// Sentry's own ids and envelope fields: 32-hex values the hex rule would break, never PII.\nconst ID_KEY = /^(event_id|trace_id|span_id|parent_span_id|profile_id|replay_id|debug_id|code_id|public_key|segment_id|sampled|release|dist|environment)$/;\n\n// Fields dropped whole: query strings travel as their own fields too (Sentry's http breadcrumbs,\n// spans and requests), and bodies and PostgREST `details` carry row values.\nconst DROPPED_KEY = /^(query_string|http\\.query|http\\.fragment|url\\.query|url\\.fragment|request_body|response_body|body|cookies|details)$/i;\n\n/** Longest string scrubbed in full; the rest is cut off (the patterns stay fast on huge logs). */\nexport const MAX_STRING = 4096;\n\nconst PATTERNS: readonly [RegExp, string][] = [\n // The query string and fragment of a URL with a scheme anywhere in text (a span's\n // \"GET https://…?id=eq.42\", a deep link \"myapp://reset?token_hash=…\").\n [/\\b([a-z][a-z0-9+.-]{0,31}:\\/\\/[^\\s?#\"'<>]{0,2048})[?#][^\\s\"'<>]*/gi, \"$1\"],\n // …and of a path (\"POST /rest/v1/rpc/find?email=eq.…\").\n [/(^|[\\s\"'(=])(\\/[^\\s?#\"'<>]{0,2048})\\?[^\\s\"'<>]*/g, \"$1$2\"],\n // JWTs: Supabase access tokens and the legacy anon / service_role keys.\n [/\\beyJ[A-Za-z0-9_-]{5,}\\.[A-Za-z0-9_-]{5,}\\.[A-Za-z0-9_-]*/g, \"[jwt]\"],\n // Supabase's API keys (sb_secret_…, sb_publishable_…).\n [/\\bsb_(?:secret|publishable)_[A-Za-z0-9_-]{8,}/g, \"[supabase-key]\"],\n // `Authorization: Bearer …` copied into a message.\n [/\\b(Bearer|Basic)\\s+[A-Za-z0-9._~+/=-]+/gi, \"$1 [token]\"],\n // Tokens in a query string or a fragment left without a scheme.\n [\n /([?&#](?:access_token|refresh_token|id_token|provider_token|provider_refresh_token|token|token_hash|code|apikey|api_key|key|password|secret|email|phone)=)[^&#\\s\"']+/gi,\n \"$1[Filtered]\",\n ],\n // Row values in PostgreSQL errors: `Failing row contains (…)`, `Key (email)=(…)`.\n [/(Failing row contains )\\([^)]*\\)/g, \"$1(…)\"],\n [/(Key \\([^)]{0,256}\\)=)\\([^)]*\\)/g, \"$1(…)\"],\n // Email addresses, also percent-encoded (`a%40b.co`). Bounded, so a long run of letters can't backtrack.\n [/[A-Za-z0-9._%+-]{1,64}(?:@|%40)(?:[A-Za-z0-9-]{1,63}\\.){1,8}[A-Za-z]{2,24}/g, \"[email]\"],\n // Phone numbers: international (`+1 555 555 0101`) and North American (`555-555-0101`).\n [/\\+\\d[\\d\\s().-]{6,18}\\d/g, \"[phone]\"],\n [/\\b\\(?\\d{3}\\)?[-.\\s]\\d{3}[-.\\s]\\d{4}\\b/g, \"[phone]\"],\n // Long opaque hex runs: API keys, refresh tokens, DSN secrets. Linear: a run starts only after a non-hex character.\n [/(^|[^A-Fa-f0-9])[A-Fa-f0-9]{32,}(?![A-Fa-f0-9])/g, \"$1[hex]\"],\n];\n\n/** A string with every URL query, email, phone number, JWT, Supabase key, bearer token and query-string token replaced. */\nexport function scrubString(value: string): string {\n let out = value.length > MAX_STRING ? `${value.slice(0, MAX_STRING)}…[truncated]` : value;\n for (const [pattern, replacement] of PATTERNS) out = out.replace(pattern, replacement);\n return out;\n}\n\n/** A URL without its query string and fragment, then scrubbed (an email in a path). */\nexport function scrubUrl(value: string): string {\n const cut = value.search(/[?#]/);\n return scrubString(cut === -1 ? value : value.slice(0, cut));\n}\n\n// Keys whose string value is cut at `?` when it is a URL.\nconst URL_KEY = /^(url|href|from|to|uri|description|http\\.url|url\\.full)$/i;\nconst MAX_DEPTH = 8;\n\n/**\n * A deep copy of `value` with every string scrubbed and every value under a\n * secret key replaced. Cycles become `\"[Circular]\"`; past 8 levels,\n * `\"[Truncated]\"`. Errors become `{ name, message }`. Header lists\n * (`[[\"authorization\", \"…\"]]`) are treated like objects.\n */\nexport function scrubValue(value: unknown, key = \"\", depth = 0, seen: WeakSet<object> = new WeakSet()): unknown {\n if (key && isSecretKey(key)) return value === undefined || value === null || value === \"\" ? value : FILTERED;\n if (typeof value === \"string\") {\n if (key && ID_KEY.test(key)) return value;\n return URL_KEY.test(key) ? scrubUrl(value) : scrubString(value);\n }\n if (value === null || typeof value !== \"object\") return value;\n if (seen.has(value)) return \"[Circular]\";\n if (depth >= MAX_DEPTH) return \"[Truncated]\";\n seen.add(value);\n if (value instanceof Error) return { name: value.name, message: scrubString(value.message) };\n if (Array.isArray(value)) {\n // A `[name, value]` pair (fetch's header lists): the name decides, as for an object key.\n if (value.length === 2 && typeof value[0] === \"string\" && isSecretKey(value[0])) return [value[0], FILTERED];\n return value.map((item) => scrubValue(item, \"\", depth + 1, seen));\n }\n const out: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(value)) {\n if (DROPPED_KEY.test(k)) continue;\n out[k] = scrubValue(v, k, depth + 1, seen);\n }\n return out;\n}\n\n/** The fields of a Sentry-shaped event `scrubEvent` treats specially. Anything else is scrubbed by value. */\nexport interface ScrubbableEvent {\n user?: { id?: unknown; [key: string]: unknown } | null;\n request?: { url?: unknown; method?: unknown; headers?: unknown; [key: string]: unknown };\n [key: string]: unknown;\n}\n\n/**\n * The event with the user reduced to its id, the request reduced to its\n * method, URL (cut at `?`) and scrubbed headers, and every other value\n * scrubbed. `null` when scrubbing threw: fail closed, send nothing rather\n * than PII.\n */\nexport function scrubEvent<E extends ScrubbableEvent>(event: E): E | null {\n try {\n // Sentry's processing metadata (scopes, the sampling context its envelope header is built\n // from) is never sent as part of the event: pass it through, or the envelope breaks.\n const { user, request, sdkProcessingMetadata, ...rest } = event;\n const out = scrubValue(rest) as E;\n if (sdkProcessingMetadata !== undefined) (out as ScrubbableEvent).sdkProcessingMetadata = sdkProcessingMetadata;\n if (user !== undefined) {\n (out as ScrubbableEvent).user = user && user.id !== undefined && user.id !== null ? { id: scrubString(String(user.id)) } : null;\n }\n if (request && typeof request === \"object\") {\n const safe: Record<string, unknown> = {};\n if (typeof request.url === \"string\") safe.url = scrubUrl(request.url);\n if (typeof request.method === \"string\") safe.method = request.method;\n if (request.headers && typeof request.headers === \"object\") safe.headers = scrubValue(request.headers);\n (out as ScrubbableEvent).request = safe;\n }\n return out;\n } catch {\n return null;\n }\n}\n\n/** A breadcrumb, span or any record, scrubbed by value. `null` when scrubbing threw (fail closed). */\nexport function scrubRecord<R extends object>(record: R): R | null {\n try {\n return scrubValue(record) as R;\n } catch {\n return null;\n }\n}\n","/**\n * The vendor-neutral seam: a sink is where errors, breadcrumbs, the user id,\n * analytics events and timings go. `createObservability` fans every call out\n * to its sinks, scrubbed first; a sink that throws is reported to\n * `onSinkError` and never takes the others (or the app) down with it.\n *\n * Shipped sinks: `sentrySink` (Sentry), `observeSink` (EAS Observe) and\n * `consoleSink` (development). A vendor adapter (PostHog, Datadog…) is one\n * object with the methods it supports.\n */\nimport type { ComponentType } from \"react\";\nimport { scrubString, scrubValue } from \"./scrub\";\nimport type { EventValues } from \"./events\";\n\n/** Where a caught error came from and whether the app could go on. */\nexport interface ErrorContext {\n /** True when the app could not go on (a render error, a failed boot, a fatal global error). */\n fatal: boolean;\n /**\n * `boundary`, `global`, `boot`, `rejection`, `screen`, `query`, `mutation`\n * (the shell's), a package's (`chat:attachment-action`, through\n * `reportError` from genesis-core) or the app's own (`updates:policy`, `sync`).\n */\n source: string;\n componentStack?: string;\n /** The route pattern on screen (`/(app)/settings`), when known. */\n route?: string | null;\n /**\n * False when nothing caught it (an unhandled promise rejection): release\n * health counts it. Default: handled unless `fatal`.\n */\n handled?: boolean;\n /** Low-cardinality labels (`query.key: \"tasks\"`), scrubbed like everything else. */\n tags?: Readonly<Record<string, string>>;\n}\n\nexport type BreadcrumbLevel = \"debug\" | \"info\" | \"warning\" | \"error\";\n\n/** One step that led up to an error: a navigation, a tap, a request. */\nexport interface Breadcrumb {\n /** `navigation`, `ui`, `http`, `event`, or the app's own. */\n category: string;\n message?: string;\n level?: BreadcrumbLevel;\n data?: Readonly<Record<string, unknown>>;\n /** Milliseconds since the epoch. Default now. */\n timestamp?: number;\n}\n\n/** Low-cardinality labels on a timing (`route`, `step`), never ids or text someone typed. */\nexport type TimingTags = Readonly<Record<string, string>>;\n\n/**\n * One destination. Every method is optional: a sink takes what its vendor\n * supports. Errors arrive as an `Error` whose message is already scrubbed,\n * unless the sink sets `scrubsErrors` (it scrubs the whole event itself and\n * needs the original object, as Sentry does to deduplicate).\n *\n * @stability Beta\n */\nexport interface ObservabilitySink {\n readonly name: string;\n /** The sink scrubs error events itself; give it the original `Error`. */\n readonly scrubsErrors?: boolean;\n captureError?(error: Error, context: ErrorContext): void;\n breadcrumb?(crumb: Breadcrumb): void;\n /** The signed-in login's id, or `null` when signed out. Never an email or a name. */\n setUser?(id: string | null): void;\n /** An analytics event, its props checked against the schema. */\n event?(name: string, props: EventValues): void;\n timing?(name: string, ms: number, tags?: TimingTags): void;\n /** Wraps the root layout (Sentry's `wrap`, EAS Observe's `ObserveRoot.wrap`). */\n wrap?<P extends Record<string, unknown>>(root: ComponentType<P>): ComponentType<P>;\n /**\n * Wraps an Expo Router per-route `ErrorBoundary` (Sentry's\n * `wrapExpoRouterErrorBoundary`). A sink that wraps reports the route's\n * error itself, so the block's screen boundary doesn't send it to that sink again.\n */\n wrapRouteErrorBoundary?(boundary: ComponentType<RouteErrorBoundaryProps>): ComponentType<RouteErrorBoundaryProps>;\n /** Send what is queued, within `timeoutMs`; resolves false when it didn't finish. Called before an update reloads the app. */\n flush?(timeoutMs: number): PromiseLike<boolean> | boolean | void;\n /** The id of the last error event this sink sent, for a support request or feedback. */\n lastEventId?(): string | undefined;\n /** The current session replay's id, when replay is on. */\n replayId?(): string | undefined;\n}\n\n/** What Expo Router gives a route's `ErrorBoundary`: the error, and `retry` to render the route again. */\nexport interface RouteErrorBoundaryProps {\n error: Error;\n retry: () => Promise<void>;\n}\n\n/** A copy of `error` whose message and stack have been scrubbed (for sinks that don't scrub themselves). */\nexport function scrubbedError(error: Error): Error {\n const copy = new Error(scrubString(error.message));\n copy.name = error.name;\n if (error.stack) copy.stack = scrubString(error.stack);\n return copy;\n}\n\nexport interface ConsoleSinkOptions {\n /** Default `console`. */\n console?: Pick<Console, \"log\" | \"warn\" | \"error\">;\n /** Also log breadcrumbs (noisy). Default false. */\n breadcrumbs?: boolean;\n}\n\n/**\n * Logs what would be sent, for development: fatal errors with `console.error`, others with `console.warn`,\n * events and timings with `console.log`. Already scrubbed, so what you read\n * is what a vendor sink would get.\n *\n * @stability Beta\n */\nexport function consoleSink(options: ConsoleSinkOptions = {}): ObservabilitySink {\n const out = options.console ?? console;\n return {\n name: \"console\",\n // `warn` for what the app survives: `console.error` would raise a LogBox error for every one in development.\n captureError: (error, context) => {\n const line = `[observability] ${context.fatal ? \"fatal \" : \"\"}${context.source}: ${error.message}`;\n if (context.fatal) out.error(line);\n else out.warn(line);\n },\n breadcrumb: options.breadcrumbs ? (crumb) => out.log(`[observability] · ${crumb.category} ${crumb.message ?? \"\"}`) : undefined,\n setUser: (id) => out.log(`[observability] user ${id ?? \"(signed out)\"}`),\n event: (name, props) => out.log(`[observability] event ${name}`, props),\n timing: (name, ms, tags) => out.log(`[observability] timing ${name} ${Math.round(ms)}ms`, tags ?? {}),\n };\n}\n\n/**\n * `expo-observe`'s `Observe` (SDK 56+), or a stand-in: the calls `observeSink`\n * uses. Pass `import { Observe } from \"expo-observe\"`.\n */\nexport interface ObserveLike {\n logEvent(name: string, options?: { severity?: \"debug\" | \"info\" | \"warn\" | \"error\"; body?: string; attributes?: Record<string, unknown> }): void;\n /** Error reporting, in preview on SDK 57+. */\n reportError?(error: unknown): void;\n}\n\nexport interface ObserveSinkOptions {\n /** Report caught errors with `Observe.reportError` (in preview). Default false: Sentry is the error tracker. */\n errors?: boolean;\n}\n\n/**\n * EAS Observe. It measures launch (cold, warm, bundle load, first render),\n * time to interactive and, with its Expo Router integration, per-route\n * render times on its own; it has no API for a custom timing metric, so\n * `timing` is logged as an event (`timing.<name>` with `duration_ms`) and\n * shows on the Events page, not as a metric. Analytics events go to\n * `Observe.logEvent` as they are.\n *\n * @stability Beta\n */\nexport function observeSink(observe: ObserveLike, options: ObserveSinkOptions = {}): ObservabilitySink {\n return {\n name: \"eas-observe\",\n event: (name, props) => observe.logEvent(name, { attributes: { ...props } }),\n timing: (name, ms, tags) => observe.logEvent(`timing.${name}`, { severity: \"info\", attributes: { duration_ms: Math.round(ms), ...(tags ?? {}) } }),\n captureError: options.errors && observe.reportError ? (error) => observe.reportError?.(error) : undefined,\n };\n}\n\n/** Breadcrumb data scrubbed and made plain (for sinks and the devtools overlay). */\nexport function scrubBreadcrumb(crumb: Breadcrumb): Breadcrumb {\n return {\n category: scrubString(crumb.category),\n level: crumb.level,\n timestamp: crumb.timestamp,\n ...(crumb.message !== undefined ? { message: scrubString(crumb.message) } : {}),\n ...(crumb.data ? { data: scrubValue(crumb.data) as Record<string, unknown> } : {}),\n };\n}\n","/**\n * `createObservability(options)`: the observability block. Build it once at\n * module scope (it starts the sinks, Sentry's `init` included), then:\n *\n * <GenesisNativeApp blocks={[observability]}> every error the shell catches → captureError\n * export default observability.wrap(RootLayout) Sentry's `wrap` (touch and profiler boundaries)\n * observability.track(\"auth.signed_in\", { method: \"email\" })\n *\n * Its root (inside the shell) sets the user to the signed-in login's id and,\n * with `useSegments` from expo-router, leaves a breadcrumb per route change\n * and a `route.time_on_screen` timing for the route left. Route patterns\n * (`/(app)/clients/[id]`) are used, never the values in them.\n *\n * Creating it also:\n * - registers it as genesis-core's error reporter (`setErrorReporter`), so a\n * package's `reportError(e, \"chat:…\")` reaches the sinks as a non-fatal error;\n * - registers a before-reload hook (`onBeforeReload`) that flushes the sinks\n * before an update reloads the app.\n *\n * `observability.screenBoundary()` is an Expo Router `ErrorBoundary` for a\n * route (reported non-fatal, wrapped by Sentry's route wrapper), and\n * `lastEventId()` / `replayId()` let a support or feedback screen point at\n * the event.\n *\n * Everything a sink receives has been scrubbed (see `scrub.ts`), and the\n * last breadcrumbs and errors are kept, scrubbed, for the devtools overlay\n * (`recent`).\n */\nimport { createContext, useContext, useEffect, useRef, useSyncExternalStore, type ComponentType, type ReactNode } from \"react\";\nimport { defineBlock } from \"@marktiderman/genesis-features/blocks\";\nimport { setErrorReporter } from \"@marktiderman/genesis-core/errors\";\nimport { useSession } from \"../auth\";\nimport { onBeforeReload } from \"../reload\";\nimport { createScreenErrorBoundary, type ScreenErrorProps } from \"../screen-boundary\";\nimport type { NativeBlock, NativeBlockRootProps } from \"../blocks\";\nimport type { ErrorReport } from \"../errors\";\nimport { checkEvent, type EventProps, type EventSchema } from \"./events\";\nimport { scrubString, scrubValue } from \"./scrub\";\nimport { scrubBreadcrumb, scrubbedError, type Breadcrumb, type ErrorContext, type ObservabilitySink, type TimingTags } from \"./sink\";\n\n/** The FeatureId of the observability block. */\nexport const OBSERVABILITY_BLOCK_ID = \"observability\";\n\n/** A caught error as the devtools overlay shows it (scrubbed). */\nexport interface RecentError {\n at: number;\n name: string;\n message: string;\n source: string;\n fatal: boolean;\n}\n\nexport interface RecentActivity {\n /** Oldest first. Navigation, events and the app's breadcrumbs. */\n breadcrumbs: readonly Breadcrumb[];\n /** Oldest first. */\n errors: readonly RecentError[];\n}\n\nexport interface RecentStore {\n getState(): RecentActivity;\n subscribe(listener: () => void): () => void;\n clear(): void;\n}\n\nexport interface ObservabilityOptions<E extends EventSchema = EventSchema> {\n /** Where everything goes: `sentrySink(Sentry, …)`, `consoleSink()` in development, `observeSink(Observe)`. */\n sinks: readonly (ObservabilitySink | null | undefined | false)[];\n /** The app's analytics events (`defineEvents`). Without it, `track` accepts nothing. */\n events?: E;\n /** `useSegments` from expo-router: route breadcrumbs and `route.time_on_screen` timings. */\n useSegments?: () => readonly string[];\n /** How many breadcrumbs and errors `recent` keeps. Default 50 and 20. */\n recent?: { breadcrumbs?: number; errors?: number };\n /** A sink threw, or `track` was called with something the schema doesn't allow. Default `console.warn` in development. */\n onProblem?: (problem: string, error?: unknown) => void;\n /**\n * Become genesis-core's error reporter, so packages' `reportError` calls\n * reach the sinks. Default true; the last block created wins.\n */\n reportErrors?: boolean;\n /** Flush the sinks before an update reloads the app, within this many milliseconds. Default 2000; 0 turns it off. */\n flushBeforeReloadMs?: number;\n now?: () => number;\n}\n\nexport interface ObservabilityBlock<E extends EventSchema = EventSchema> extends NativeBlock<typeof OBSERVABILITY_BLOCK_ID> {\n readonly sinks: readonly ObservabilitySink[];\n readonly events: E | undefined;\n /** Report an error. The shell calls it for every error it catches. */\n captureError(error: unknown, context?: Partial<ErrorContext>): void;\n breadcrumb(crumb: Breadcrumb): void;\n /** The login's id only. The block's root sets it from the session. */\n setUser(id: string | null): void;\n /** An analytics event from the schema. Anything else is dropped and reported. */\n track<N extends keyof E & string>(name: N, props?: EventProps<E[N]>): void;\n timing(name: string, ms: number, tags?: TimingTags): void;\n /** The root layout wrapped by each sink that wraps (Sentry's `wrap`). Use once: `export default observability.wrap(RootLayout)`. */\n wrap<P extends Record<string, unknown>>(root: ComponentType<P>): ComponentType<P>;\n /** The last breadcrumbs and errors, scrubbed, for the devtools overlay. */\n readonly recent: RecentStore;\n /** Send what every sink has queued; resolves false when one didn't finish within `timeoutMs` (default 2000). */\n flush(timeoutMs?: number): Promise<boolean>;\n /** The id of the last error event a sink sent (Sentry's), for a support request or feedback. */\n lastEventId(): string | undefined;\n /** The current session replay's id, when a sink records replays. */\n replayId(): string | undefined;\n /**\n * An Expo Router `ErrorBoundary` for a route: reports the error non-fatal\n * (source `screen`), shows `fallback` (default `<FatalScreen kind=\"screen\" />`) with\n * \"Try again\", and is wrapped by each sink's route wrapper (Sentry's\n * `wrapExpoRouterErrorBoundary`). Build it once, at module scope.\n */\n screenBoundary(fallback?: ComponentType<ScreenErrorProps>): ComponentType<ScreenErrorProps>;\n /** For the shell: every error it catches. */\n readonly onError: (error: Error, report: ErrorReport) => void;\n readonly Root: ComponentType<NativeBlockRootProps>;\n}\n\ndeclare const __DEV__: boolean | undefined;\n\nlet releaseReloadHook: (() => void) | undefined;\n\nconst TIMING_NAME = /^[a-z][a-z0-9_]*(?:\\.[a-z][a-z0-9_]*)*$/;\n\nfunction createRecentStore(maxCrumbs: number, maxErrors: number): RecentStore & { addCrumb(c: Breadcrumb): void; addError(e: RecentError): void } {\n let state: RecentActivity = { breadcrumbs: [], errors: [] };\n const listeners = new Set<() => void>();\n const emit = () => listeners.forEach((l) => l());\n const push = <T,>(list: readonly T[], item: T, max: number) => (list.length >= max ? [...list.slice(list.length - max + 1), item] : [...list, item]);\n return {\n getState: () => state,\n subscribe(listener) {\n listeners.add(listener);\n return () => listeners.delete(listener);\n },\n clear() {\n state = { breadcrumbs: [], errors: [] };\n emit();\n },\n addCrumb(crumb) {\n state = { ...state, breadcrumbs: push(state.breadcrumbs, crumb, maxCrumbs) };\n emit();\n },\n addError(error) {\n state = { ...state, errors: push(state.errors, error, maxErrors) };\n emit();\n },\n };\n}\n\nfunction toError(value: unknown): Error {\n return value instanceof Error ? value : new Error(typeof value === \"string\" ? value : \"Unknown error\");\n}\n\n/** Build the block once, at module scope, before the root layout renders. @stability Beta */\nexport function createObservability<const E extends EventSchema = EventSchema>(options: ObservabilityOptions<E>): ObservabilityBlock<E> {\n const sinks = options.sinks.filter((s): s is ObservabilitySink => Boolean(s));\n const now = options.now ?? Date.now;\n const problem =\n options.onProblem ??\n ((message: string, error?: unknown) => {\n // genesis-allow-console: the block's own development warning; it can't report to itself.\n if (typeof __DEV__ !== \"undefined\" && __DEV__) console.warn(`[observability] ${message}`, error ?? \"\");\n });\n const recent = createRecentStore(options.recent?.breadcrumbs ?? 50, options.recent?.errors ?? 20);\n let route: string | null = null;\n let user: string | null | undefined;\n\n // One sink failing never stops the others, and never throws into the caller (an error handler, a render).\n const each = (method: string, call: (sink: ObservabilitySink) => void) => {\n for (const sink of sinks) {\n try {\n call(sink);\n } catch (error) {\n try {\n problem(`${sink.name}.${method} threw`, error);\n } catch {\n // ignore a failing reporter\n }\n }\n }\n };\n\n // Never throws into the caller (an effect, a handler): a record that can't be scrubbed is dropped.\n const breadcrumb = (input: Breadcrumb) => {\n let crumb: Breadcrumb;\n try {\n crumb = scrubBreadcrumb({ ...input, timestamp: input.timestamp ?? now() });\n } catch (error) {\n problem(\"breadcrumb dropped: it could not be scrubbed\", error);\n return;\n }\n recent.addCrumb(crumb);\n each(\"breadcrumb\", (s) => s.breadcrumb?.(crumb));\n };\n\n const captureError = (value: unknown, context: Partial<ErrorContext> = {}, skip?: ReadonlySet<ObservabilitySink>) => {\n const error = toError(value);\n const full: ErrorContext = {\n fatal: context.fatal ?? false,\n source: context.source ?? \"app\",\n route: context.route ?? route,\n componentStack: context.componentStack,\n ...(context.handled !== undefined ? { handled: context.handled } : {}),\n ...(context.tags ? { tags: context.tags } : {}),\n };\n let safe: Error | undefined;\n const scrubbed = () => (safe ??= scrubbedError(error));\n try {\n recent.addError({ at: now(), name: error.name, message: scrubString(error.message), source: full.source, fatal: full.fatal });\n } catch {\n // never let the overlay's list stop a report\n }\n let forSinks: ErrorContext = full;\n try {\n forSinks = {\n ...full,\n ...(full.componentStack ? { componentStack: scrubString(full.componentStack) } : {}),\n ...(full.tags ? { tags: scrubValue(full.tags) as Record<string, string> } : {}),\n };\n } catch {\n // Tags that can't be scrubbed are dropped, never sent raw.\n forSinks = { ...full, componentStack: undefined, tags: undefined };\n }\n each(\"captureError\", (s) => {\n if (skip?.has(s)) return;\n s.captureError?.(s.scrubsErrors ? error : scrubbed(), s.scrubsErrors ? full : forSinks);\n });\n };\n\n const flush = async (timeoutMs = 2000): Promise<boolean> => {\n const results = sinks.map(async (sink) => {\n if (!sink.flush) return true;\n try {\n return (await sink.flush(timeoutMs)) !== false;\n } catch (error) {\n problem(`${sink.name}.flush threw`, error);\n return false;\n }\n });\n let timer: ReturnType<typeof setTimeout> | undefined;\n const deadline = new Promise<boolean>((resolve) => {\n timer = setTimeout(() => resolve(false), timeoutMs);\n });\n try {\n return await Promise.race([Promise.all(results).then((all) => all.every(Boolean)), deadline]);\n } finally {\n if (timer !== undefined) clearTimeout(timer);\n }\n };\n\n const firstOf = (read: (sink: ObservabilitySink) => string | undefined): string | undefined => {\n for (const sink of sinks) {\n try {\n const value = read(sink);\n if (value) return value;\n } catch (error) {\n problem(`${sink.name} threw reading an id`, error);\n }\n }\n return undefined;\n };\n\n const setUser = (id: string | null) => {\n if (id === user) return;\n user = id;\n each(\"setUser\", (s) => s.setUser?.(id));\n };\n\n const track = (name: string, props?: Readonly<Record<string, unknown>>) => {\n const check = options.events ? checkEvent(options.events, name, props) : ({ ok: false, problem: \"no event schema: pass `events: defineEvents({…})`\" } as const);\n if (!check.ok) {\n problem(`track dropped: ${check.problem}`);\n return;\n }\n recent.addCrumb({ category: \"event\", message: name, level: \"info\", data: check.props, timestamp: now() });\n each(\"event\", (s) => s.event?.(name, check.props));\n };\n\n const timing = (name: string, ms: number, tags?: TimingTags) => {\n if (!Number.isFinite(ms) || ms < 0) return;\n // A name like an event's (`route.time_on_screen`), never text with values in it.\n if (!TIMING_NAME.test(name)) {\n problem(`timing dropped: \"${scrubString(name)}\" is not lower-case words joined by \".\"`);\n return;\n }\n let safeTags: TimingTags | undefined;\n try {\n safeTags = tags ? (scrubValue(tags) as TimingTags) : undefined;\n } catch (error) {\n problem(\"timing dropped: its tags could not be scrubbed\", error);\n return;\n }\n each(\"timing\", (s) => s.timing?.(name, ms, safeTags));\n };\n\n const declaration = defineBlock<typeof OBSERVABILITY_BLOCK_ID, ComponentType<never>>({\n id: OBSERVABILITY_BLOCK_ID,\n platforms: [\"native\"],\n contributes: {\n privacy: {\n collects: [\n // genesis-cli's PRIVACY_BLOCKS.observability mirrors this (with events) for the iOS\n // privacy manifest; observability/block.test.tsx keeps the two the same.\n { type: \"crash data\", purposes: [\"app functionality\"], linked: true, tracking: false },\n { type: \"performance data\", purposes: [\"app functionality\"], linked: true, tracking: false },\n // Sentry's device and OS details, breadcrumbs and sessions.\n { type: \"other diagnostic data\", purposes: [\"app functionality\"], linked: true, tracking: false },\n { type: \"user id\", purposes: options.events ? [\"app functionality\", \"analytics\"] : [\"app functionality\"], linked: true, tracking: false },\n ...(options.events ? [{ type: \"product interaction\", purposes: [\"analytics\"], linked: true, tracking: false }] : []),\n ],\n notes: [\n \"Crash reports, timings and analytics events carry the login's id only; emails, tokens, keys and query strings are removed on the device before anything is sent.\",\n ],\n },\n },\n });\n\n const useSegments = options.useSegments;\n function RouteTracker() {\n const segments = (useSegments as () => readonly string[])();\n const path = `/${segments.join(\"/\")}`;\n const last = useRef<{ path: string; at: number } | null>(null);\n useEffect(() => {\n const at = now();\n const previous = last.current;\n if (previous?.path === path) return;\n route = path;\n breadcrumb({ category: \"navigation\", message: path, data: previous ? { from: previous.path } : undefined, timestamp: at });\n if (previous) timing(\"route.time_on_screen\", at - previous.at, { route: previous.path });\n last.current = { path, at };\n }, [path]);\n return null;\n }\n\n function UserTracker() {\n const { userId } = useSession();\n useEffect(() => setUser(userId ?? null), [userId]);\n return null;\n }\n\n const block: ObservabilityBlock<E> = {\n ...declaration,\n sinks,\n events: options.events,\n captureError,\n breadcrumb,\n setUser,\n track: track as ObservabilityBlock<E>[\"track\"],\n timing,\n recent,\n wrap(root) {\n return sinks.reduce((wrapped, sink) => (sink.wrap ? sink.wrap(wrapped) : wrapped), root);\n },\n onError: (error, report) =>\n captureError(error, {\n fatal: report.fatal,\n source: report.source,\n componentStack: report.componentStack,\n ...(report.handled !== undefined ? { handled: report.handled } : {}),\n ...(report.tags ? { tags: report.tags } : {}),\n }),\n flush,\n lastEventId: () => firstOf((s) => s.lastEventId?.()),\n replayId: () => firstOf((s) => s.replayId?.()),\n screenBoundary(fallback) {\n const wrapping = sinks.filter((s) => s.wrapRouteErrorBoundary);\n // A sink whose wrapper reports the route's error (Sentry's) isn't sent it a second time.\n const skip = new Set(wrapping);\n return createScreenErrorBoundary({\n fallback,\n onError: (error, report) => captureError(error, { fatal: report.fatal, source: report.source }, skip),\n wrap: wrapping.map((sink) => (boundary: ComponentType<ScreenErrorProps>) => {\n try {\n return sink.wrapRouteErrorBoundary!(boundary);\n } catch (error) {\n problem(`${sink.name}.wrapRouteErrorBoundary threw`, error);\n skip.delete(sink);\n return boundary;\n }\n }),\n });\n },\n Root: function ObservabilityRoot({ children }: NativeBlockRootProps) {\n return (\n <ObservabilityContext.Provider value={block as ObservabilityBlock}>\n <UserTracker />\n {useSegments ? <RouteTracker /> : null}\n {children}\n </ObservabilityContext.Provider>\n );\n },\n };\n if (options.reportErrors !== false) {\n setErrorReporter((value, context) =>\n captureError(value, { fatal: context.fatal ?? false, source: context.source, ...(context.tags ? { tags: context.tags } : {}) }),\n );\n }\n const flushMs = options.flushBeforeReloadMs ?? 2000;\n // The newest block replaces the last one's hook (Fast Refresh builds the block again).\n releaseReloadHook?.();\n releaseReloadHook = flushMs > 0 && sinks.some((s) => s.flush) ? onBeforeReload(() => flush(flushMs)) : undefined;\n return block;\n}\n\nconst ObservabilityContext = createContext<ObservabilityBlock | null>(null);\n\n/** Provides a block to the hooks without its root (rung 4). @stability Beta */\nexport function ObservabilityProvider({ block, children }: { block: ObservabilityBlock; children?: ReactNode }) {\n return <ObservabilityContext.Provider value={block}>{children}</ObservabilityContext.Provider>;\n}\n\n/** The block, or `null` when it is off (so a screen can call it whether or not the block is on). @stability Beta */\nexport function useObservability(): ObservabilityBlock | null {\n return useContext(ObservabilityContext);\n}\n\n/** The last breadcrumbs and errors, scrubbed; empty when the block is off. @stability Beta */\nexport function useRecentActivity(block?: ObservabilityBlock | null): RecentActivity {\n const fromContext = useObservability();\n const store = (block ?? fromContext)?.recent ?? EMPTY_STORE;\n return useSyncExternalStore(store.subscribe, store.getState, store.getState);\n}\n\nconst EMPTY: RecentActivity = { breadcrumbs: [], errors: [] };\nconst EMPTY_STORE: RecentStore = { getState: () => EMPTY, subscribe: () => () => {}, clear: () => {} };\n"]}
@@ -69,5 +69,5 @@ function reportQueryErrors(client, report, options = {}) {
69
69
  }
70
70
 
71
71
  export { DAY_MS, connectQueryLifecycle, createNativeQueryClient, queryKeyName, reportQueryErrors };
72
- //# sourceMappingURL=chunk-C54LIT4N.js.map
73
- //# sourceMappingURL=chunk-C54LIT4N.js.map
72
+ //# sourceMappingURL=chunk-FKDZP3RJ.js.map
73
+ //# sourceMappingURL=chunk-FKDZP3RJ.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/query.ts"],"names":[],"mappings":";;;;AAkBO,IAAM,MAAA,GAAS,EAAA,GAAK,EAAA,GAAK,EAAA,GAAK;AAc9B,SAAS,uBAAA,CAAwB,MAAA,GAA4B,EAAC,EAAgB;AACnF,EAAA,MAAM,EAAE,SAAS,SAAA,EAAW,GAAG,MAAK,GAAI,MAAA,CAAO,kBAAkB,EAAC;AAClE,EAAA,OAAO,IAAI,WAAA,CAAY;AAAA,IACrB,GAAG,MAAA;AAAA,IACH,cAAA,EAAgB;AAAA,MACd,GAAG,IAAA;AAAA,MACH,OAAA,EAAS,EAAE,WAAA,EAAa,cAAA,EAAgB,QAAQ,MAAA,EAAQ,SAAA,EAAW,GAAA,EAAQ,GAAG,OAAA,EAAQ;AAAA,MACtF,SAAA,EAAW,EAAE,WAAA,EAAa,cAAA,EAAgB,GAAG,SAAA;AAAU;AACzD,GACD,CAAA;AACH;AA0CO,SAAS,qBAAA,CAAsB,EAAE,QAAA,EAAU,OAAA,EAAQ,EAAsC;AAC9F,EAAA,IAAI,QAAA,EAAU;AACZ,IAAA,YAAA,CAAa,gBAAA,CAAiB,CAAC,UAAA,KAAe;AAC5C,MAAA,MAAM,YAAA,GAAe,SAAS,gBAAA,CAAiB,QAAA,EAAU,CAAC,KAAA,KAAU,UAAA,CAAW,KAAA,KAAU,QAAQ,CAAC,CAAA;AAClG,MAAA,OAAO,MAAM,aAAa,MAAA,EAAO;AAAA,IACnC,CAAC,CAAA;AAAA,EACH;AACA,EAAA,IAAI,OAAA,EAAS;AACX,IAAA,aAAA,CAAc,gBAAA,CAAiB,CAAC,SAAA,KAAc,OAAA,CAAQ,gBAAA,CAAiB,CAAC,KAAA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saving it to the phone. The persister itself is in\n * `@marktiderman/genesis-native/persist`, so an app that saves nothing doesn't\n * install TanStack's persister packages.\n */\nimport { QueryClient, focusManager, isCancelledError, onlineManager, type QueryClientConfig } from \"@tanstack/react-query\";\nimport { classifyError } from \"@marktiderman/genesis-core/errors\";\nimport type { ErrorReport } from \"./errors\";\n\n/** The part of AsyncStorage (or any async key-value store) Genesis uses. */\nexport interface AsyncStorageLike {\n getItem(key: string): Promise<string | null>;\n setItem(key: string, value: string): Promise<void>;\n removeItem(key: string): Promise<void>;\n}\n\n/** One day in milliseconds: the default max age of the saved query cache. */\nexport const DAY_MS = 24 * 60 * 60 * 1000;\n\n/**\n * A QueryClient for a phone. `networkMode: \"offlineFirst\"` runs a query or\n * mutation once whatever the network says, then pauses its retries while the\n * device is offline (`onlineManager`, which `connectQueryLifecycle` feeds from\n * NetInfo), continues them when it is back, and refetches stale queries on\n * reconnect. So offline, a query with saved data keeps showing it\n * (`fetchStatus: \"paused\"`); one with nothing saved stays `pending` and paused\n * until the network returns (check `isPaused`, not only `isPending`, before\n * showing a spinner); and a mutation, which TanStack doesn't retry by default,\n * fails at once instead of waiting. `gcTime` matches the persisted max age, or\n * restored queries would be collected before they are used. Your `config` wins.\n */\nexport function createNativeQueryClient(config: QueryClientConfig = {}): QueryClient {\n const { queries, mutations, ...rest } = config.defaultOptions ?? {};\n return new QueryClient({\n ...config,\n defaultOptions: {\n ...rest,\n queries: { networkMode: \"offlineFirst\", gcTime: DAY_MS, staleTime: 60_000, ...queries },\n mutations: { networkMode: \"offlineFirst\", ...mutations },\n },\n });\n}\n\n/**\n * The saved query cache. A `scope` (the signed-in user's id, `\"\"` for nobody)\n * is part of what is saved: a cache saved for one user is discarded, on disk\n * too, when another scope restores it.\n */\nexport interface QueryPersistence {\n /** Load the saved cache into the client, if it was saved for `scope`. */\n restore(scope: string): Promise<void>;\n /**\n * Save on every cache change, for `scope`; returns the unsubscribe. `adopt`: the reads already\n * in the client are this scope's too (the app empties the client whenever the person changes).\n */\n subscribe(scope: string, options?: { adopt?: boolean }): () => void;\n /**\n * Delete the saved cache. Clear the QueryClient first: the subscription\n * then saves the empty cache, so a save already in flight can't leave the\n * old queries on disk.\n */\n clear(): Promise<void>;\n}\n\n/** React Native's `AppState`, or a stand-in. */\nexport interface AppStateLike {\n addEventListener(type: \"change\", listener: (state: string) => void): { remove(): void };\n}\n\n/** `@react-native-community/netinfo`'s default export, or a stand-in. */\nexport interface NetInfoLike {\n addEventListener(listener: (state: { isConnected: boolean | null }) => void): () => void;\n}\n\nexport interface QueryLifecycleOptions {\n appState?: AppStateLike;\n netInfo?: NetInfoLike;\n}\n\n/**\n * Tell TanStack Query when the app comes to the front (refetch stale\n * queries) and when the network comes and goes. Returns the cleanup.\n */\nexport function connectQueryLifecycle({ appState, netInfo }: QueryLifecycleOptions): () => void {\n if (appState) {\n focusManager.setEventListener((setFocused) => {\n const subscription = appState.addEventListener(\"change\", (state) => setFocused(state === \"active\"));\n return () => subscription.remove();\n });\n }\n if (netInfo) {\n onlineManager.setEventListener((setOnline) => netInfo.addEventListener((state) => setOnline(state.isConnected !== false)));\n }\n return () => {\n // Replacing the listener runs the cleanup of the one set above.\n if (appState) focusManager.setEventListener(() => () => {});\n if (netInfo) {\n onlineManager.setEventListener(() => () => {});\n // Nothing reports the network any more: don't leave paused queries waiting on the last\n // \"offline\" NetInfo said (offlineFirst pauses retries while offline).\n onlineManager.setOnline(true);\n }\n };\n}\n\n/** A failed query or mutation, as `reportQueryErrors` hands it on. */\nexport type QueryErrorReporter = (error: Error, report: ErrorReport) => void;\n\nexport interface ReportQueryErrorsOptions {\n /** True when the device is offline. Default TanStack's `onlineManager`. */\n isOffline?: () => boolean;\n}\n\n// A key segment that is a name (`tasks`, `chat.messages`), not an id or text.\nconst KEY_NAME = /^[A-Za-z][A-Za-z0-9_.:-]{0,63}$/;\nconst LOOKS_LIKE_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-|^\\d+$|[0-9a-f]{20,}/i;\n\n/** The first segment of a query or mutation key, when it is a name; never the ids after it. */\nexport function queryKeyName(key: readonly unknown[] | undefined): string | undefined {\n const first = key?.[0];\n return typeof first === \"string\" && KEY_NAME.test(first) && !LOOKS_LIKE_ID.test(first) ? first : undefined;\n}\n\nfunction toError(value: unknown): Error {\n return value instanceof Error ? value : new Error(typeof value === \"string\" ? value : \"Unknown error\");\n}\n\n/**\n * Hand every query and mutation that failed for good (after its retries) to\n * `report`, as a non-fatal `query` or `mutation` error tagged with the key's\n * first segment (`query.key: \"tasks\"`), never the ids after it.\n *\n * Only errors worth a report (`classifyError(e).report`): being offline,\n * signed out, a record that's gone and the server's expected refusals\n * (forbidden, conflict, a rejected value) are the screen's to show, not\n * bugs. A cancelled query is never reported. One query or mutation opts out\n * with `meta: { reportErrors: false }`.\n *\n * Works on any client (it subscribes to the caches), so it covers a client\n * the app passed in too. Returns the unsubscribe.\n *\n * @stability Beta\n */\nexport function reportQueryErrors(client: QueryClient, report: QueryErrorReporter, options: ReportQueryErrorsOptions = {}): () => void {\n const isOffline = options.isOffline ?? (() => !onlineManager.isOnline());\n const send = (raw: unknown, source: \"query\" | \"mutation\", key: readonly unknown[] | undefined, meta: Record<string, unknown> | undefined) => {\n if (meta?.reportErrors === false || isCancelledError(raw)) return;\n if (!classifyError(raw, { isOffline }).report) return;\n const name = queryKeyName(key);\n try {\n report(toError(raw), { fatal: false, source, ...(name ? { tags: { [`${source}.key`]: name } } : {}) });\n } catch {\n // A failing reporter must not break the cache's listeners.\n }\n };\n const offQueries = client.getQueryCache().subscribe((event) => {\n if (event.type !== \"updated\" || event.action.type !== \"error\") return;\n send(event.action.error, \"query\", event.query.queryKey, event.query.meta);\n });\n const offMutations = client.getMutationCache().subscribe((event) => {\n if (event.type !== \"updated\" || event.action.type !== \"error\") return;\n send(event.action.error, \"mutation\", event.mutation.options.mutationKey, event.mutation.meta);\n });\n return () => {\n offQueries();\n offMutations();\n };\n}\n"]}
@@ -114,25 +114,39 @@ function errorDetails(error) {
114
114
  const classified = classifyError(error);
115
115
  return classified.kind === "unexpected" ? void 0 : classified.message;
116
116
  }
117
- function FatalScreen({ error, retry }) {
117
+ var runRetry = (retry, source) => () => {
118
+ void Promise.resolve(retry()).catch((e) => reportError(e, source));
119
+ };
120
+ function FatalScreen({ error, retry, kind = "app" }) {
121
+ if (kind === "plain") {
122
+ return /* @__PURE__ */ jsxs(View, { testID: "genesis-fatal-plain", style: { flex: 1, justifyContent: "center", alignItems: "center", padding: 24, gap: 12 }, children: [
123
+ /* @__PURE__ */ jsx(Text, { accessibilityRole: "header", style: { fontSize: 17, fontWeight: "600" }, children: "Something went wrong" }),
124
+ /* @__PURE__ */ jsx(Text, { style: { textAlign: "center" }, children: errorDetails(error) ?? "Try again, and if it keeps happening, close and reopen the app." }),
125
+ /* @__PURE__ */ jsx(Pressable, { accessibilityRole: "button", onPress: () => void retry(), testID: "genesis-fatal-plain-retry", style: { padding: 12 }, children: /* @__PURE__ */ jsx(Text, { style: { fontSize: 17 }, children: "Try again" }) })
126
+ ] });
127
+ }
128
+ const screen = kind === "screen";
118
129
  return /* @__PURE__ */ jsx(
119
130
  NativeEmptyState,
120
131
  {
121
132
  variant: "error",
122
- title: "Something went wrong",
123
- body: "The app hit a problem. Try again, and if it keeps happening, close and reopen the app.",
133
+ title: screen ? "This screen hit a problem" : "Something went wrong",
134
+ body: screen ? "The rest of the app still works. Try again, or go back." : "The app hit a problem. Try again, and if it keeps happening, close and reopen the app.",
124
135
  details: errorDetails(error),
125
- primaryAction: /* @__PURE__ */ jsx(NativeButton, { onPress: retry, testID: "genesis-fatal-retry", children: "Try again" }),
126
- testID: "genesis-fatal"
136
+ primaryAction: /* @__PURE__ */ jsx(
137
+ NativeButton,
138
+ {
139
+ onPress: screen ? runRetry(retry, "native:screen-retry") : () => void retry(),
140
+ testID: screen ? "genesis-screen-error-retry" : "genesis-fatal-retry",
141
+ children: "Try again"
142
+ }
143
+ ),
144
+ testID: screen ? "genesis-screen-error" : "genesis-fatal"
127
145
  }
128
146
  );
129
147
  }
130
- function PlainFatalScreen({ error, retry }) {
131
- return /* @__PURE__ */ jsxs(View, { testID: "genesis-fatal-plain", style: { flex: 1, justifyContent: "center", alignItems: "center", padding: 24, gap: 12 }, children: [
132
- /* @__PURE__ */ jsx(Text, { accessibilityRole: "header", style: { fontSize: 17, fontWeight: "600" }, children: "Something went wrong" }),
133
- /* @__PURE__ */ jsx(Text, { style: { textAlign: "center" }, children: errorDetails(error) ?? "Try again, and if it keeps happening, close and reopen the app." }),
134
- /* @__PURE__ */ jsx(Pressable, { accessibilityRole: "button", onPress: retry, testID: "genesis-fatal-plain-retry", style: { padding: 12 }, children: /* @__PURE__ */ jsx(Text, { style: { fontSize: 17 }, children: "Try again" }) })
135
- ] });
148
+ function PlainFatalScreen(props) {
149
+ return /* @__PURE__ */ jsx(FatalScreen, { ...props, kind: "plain" });
136
150
  }
137
151
  var GenesisErrorBoundary = class extends Component {
138
152
  state = { error: null };
@@ -202,22 +216,13 @@ function installRejectionTracker({ enable, onError }) {
202
216
  }
203
217
  });
204
218
  }
205
- function ScreenErrorScreen({ error, retry }) {
206
- return /* @__PURE__ */ jsx(
207
- NativeEmptyState,
208
- {
209
- variant: "error",
210
- title: "This screen hit a problem",
211
- body: "The rest of the app still works. Try again, or go back.",
212
- details: errorDetails(error),
213
- primaryAction: /* @__PURE__ */ jsx(NativeButton, { onPress: () => void Promise.resolve(retry()).catch((e) => reportError(e, "native:screen-retry")), testID: "genesis-screen-error-retry", children: "Try again" }),
214
- testID: "genesis-screen-error"
215
- }
216
- );
219
+ function ScreenErrorScreen(props) {
220
+ return /* @__PURE__ */ jsx(FatalScreen, { ...props, kind: "screen" });
217
221
  }
222
+ var ScreenFallback = (props) => /* @__PURE__ */ jsx(FatalScreen, { ...props, kind: "screen" });
218
223
  var reportThroughCore = (error, report) => reportError(error, { source: report.source, fatal: report.fatal, ...report.tags ? { tags: report.tags } : {} });
219
224
  function createScreenErrorBoundary(options = {}) {
220
- const Fallback = options.fallback ?? ScreenErrorScreen;
225
+ const Fallback = options.fallback ?? ScreenFallback;
221
226
  const onError = options.onError ?? reportThroughCore;
222
227
  function GenesisScreenErrorBoundary(props) {
223
228
  const reported = useRef(null);
@@ -234,9 +239,9 @@ function createScreenErrorBoundary(options = {}) {
234
239
  return (options.wrap ?? []).reduce((inner, wrap) => wrap(inner), GenesisScreenErrorBoundary);
235
240
  }
236
241
  function ScreenErrorBoundary({ children, fallback, onError, resetKey }) {
237
- const Screen = fallback ?? ScreenErrorScreen;
242
+ const Screen = fallback ?? ScreenFallback;
238
243
  const Fallback = useMemo(
239
- () => function ScreenFallback({ error, retry }) {
244
+ () => function ScreenFallback2({ error, retry }) {
240
245
  return /* @__PURE__ */ jsx(Screen, { error, retry: async () => retry() });
241
246
  },
242
247
  [Screen]
@@ -245,5 +250,5 @@ function ScreenErrorBoundary({ children, fallback, onError, resetKey }) {
245
250
  }
246
251
 
247
252
  export { BootProvider, BootTimeoutError, FatalScreen, GenesisErrorBoundary, PlainFatalScreen, ScreenErrorBoundary, ScreenErrorScreen, createBoot, createScreenErrorBoundary, defaultErrorUtils, defaultRejectionTracker, errorDetails, installGlobalErrorHandler, installRejectionTracker, useBoot };
248
- //# sourceMappingURL=chunk-MFHOHSEQ.js.map
249
- //# sourceMappingURL=chunk-MFHOHSEQ.js.map
253
+ //# sourceMappingURL=chunk-YIF4BFQH.js.map
254
+ //# sourceMappingURL=chunk-YIF4BFQH.js.map