@flare-engine/errors 0.4.7 → 0.4.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.mts.map +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +34 -28
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +34 -28
- package/dist/index.mjs.map +1 -1
- package/package.json +1 -1
package/dist/index.d.mts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.mts","names":[],"sources":["../src/crash-payload.ts","../src/transport.ts","../src/compose.ts","../src/error-boundary.tsx","../src/global-capture.ts","../src/transports/sentry.ts"],"mappings":";;;;;UAIiB;;EAEf;;EAEA;;EAEA;;EAEA;;EAEA,SAAS;;;;;;wBAOK,mBACd,gBACA,UAAS,0BACR;;;;;UClBc;EACf,OAAO,SAAS,sBAAsB;;;
|
|
1
|
+
{"version":3,"file":"index.d.mts","names":[],"sources":["../src/crash-payload.ts","../src/transport.ts","../src/compose.ts","../src/error-boundary.tsx","../src/global-capture.ts","../src/transports/sentry.ts"],"mappings":";;;;;UAIiB;;EAEf;;EAEA;;EAEA;;EAEA;;EAEA,SAAS;;;;;;wBAOK,mBACd,gBACA,UAAS,0BACR;;;;;UClBc;EACf,OAAO,SAAS,sBAAsB;;;wBAyBxB,uBAAuB;;;;;wBAYvB,0BAA0B;wBC1C1B,qBAAqB,YAAY,mBAAmB;UCEnD;EACf,UAAU;;EAEV,WAAW,SAAS,cAAc,sBAAsB;;EAExD,YAAY;;EAEZ,UAAU;;EAEV,WAAW,gBAAgB,SAAS;;UAG5B;EACR,SAAS;;;;;;;qBAQE,sBAAsB,UAAU,oBAAoB;EAC/D,OAAO;SAEA,yBAAyB,iBAAiB;EAIjD,kBAAkB,gBAAgB,MAAM;EAYxC;EAIA,UAAU;;;;;;UCzCK;EACf,uBAAuB,gBAAgB;EACvC,iBAAiB,UAAU,gBAAgB;;;;;;;;;;UAW5B;EACf,kBAAkB,cAAc,WAAW;EAC3C,qBAAqB,cAAc,WAAW;EAC9C,aAAa;;;UAIE;;;;;;EAMf,YAAY;;;;;;EAMZ;;EAEA,UAAU;;;UAIK;;;;;EAKf;;EAEA,aAAa,WAAW;;WAEf;;;;;;;;;;;;;;;;;;;;;;;wBAqCK,0BACd,QAAQ,mBACR,UAAU,uBACT;;;;;UAuEc;EACf,iBAAiB,gBAAgB;;;;;;;;;;;;;;;;;;;;wBAqBnB,sBAAsB,QAAQ,kBAAkB;UCtL/C;EACf;EACA;EACA;EACA;EACA;;wBAyBc,sBAAsB,MAAM,yBAAyB"}
|
package/dist/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","names":[],"sources":["../src/crash-payload.ts","../src/transport.ts","../src/compose.ts","../src/error-boundary.tsx","../src/global-capture.ts","../src/transports/sentry.ts"],"mappings":";;;;;UAIiB;;EAEf;;EAEA;;EAEA;;EAEA;;EAEA,SAAS;;;;;;wBAOK,mBACd,gBACA,UAAS,0BACR;;;;;UClBc;EACf,OAAO,SAAS,sBAAsB;;;
|
|
1
|
+
{"version":3,"file":"index.d.ts","names":[],"sources":["../src/crash-payload.ts","../src/transport.ts","../src/compose.ts","../src/error-boundary.tsx","../src/global-capture.ts","../src/transports/sentry.ts"],"mappings":";;;;;UAIiB;;EAEf;;EAEA;;EAEA;;EAEA;;EAEA,SAAS;;;;;;wBAOK,mBACd,gBACA,UAAS,0BACR;;;;;UClBc;EACf,OAAO,SAAS,sBAAsB;;;wBAyBxB,uBAAuB;;;;;wBAYvB,0BAA0B;wBC1C1B,qBAAqB,YAAY,mBAAmB;UCEnD;EACf,UAAU;;EAEV,WAAW,SAAS,cAAc,sBAAsB;;EAExD,YAAY;;EAEZ,UAAU;;EAEV,WAAW,gBAAgB,SAAS;;UAG5B;EACR,SAAS;;;;;;;qBAQE,sBAAsB,UAAU,oBAAoB;EAC/D,OAAO;SAEA,yBAAyB,iBAAiB;EAIjD,kBAAkB,gBAAgB,MAAM;EAYxC;EAIA,UAAU;;;;;;UCzCK;EACf,uBAAuB,gBAAgB;EACvC,iBAAiB,UAAU,gBAAgB;;;;;;;;;;UAW5B;EACf,kBAAkB,cAAc,WAAW;EAC3C,qBAAqB,cAAc,WAAW;EAC9C,aAAa;;;UAIE;;;;;;EAMf,YAAY;;;;;;EAMZ;;EAEA,UAAU;;;UAIK;;;;;EAKf;;EAEA,aAAa,WAAW;;WAEf;;;;;;;;;;;;;;;;;;;;;;;wBAqCK,0BACd,QAAQ,mBACR,UAAU,uBACT;;;;;UAuEc;EACf,iBAAiB,gBAAgB;;;;;;;;;;;;;;;;;;;;wBAqBnB,sBAAsB,QAAQ,kBAAkB;UCtL/C;EACf;EACA;EACA;EACA;EACA;;wBAyBc,sBAAsB,MAAM,yBAAyB"}
|
package/dist/index.js
CHANGED
|
@@ -44,6 +44,36 @@ function createCrashPayload(error, context = {}) {
|
|
|
44
44
|
context
|
|
45
45
|
};
|
|
46
46
|
}
|
|
47
|
+
// src/transport.ts
|
|
48
|
+
/**
|
|
49
|
+
* Call `transport.report` so that neither a synchronous throw nor a rejected
|
|
50
|
+
* promise escapes. Left unhandled, a rejection surfaces on the global as an
|
|
51
|
+
* `unhandledrejection` that `installGlobalErrorCapture` listens for, so each
|
|
52
|
+
* failed report would trigger the next for as long as the transport is down.
|
|
53
|
+
*/
|
|
54
|
+
function reportSafely(transport, payload, stage) {
|
|
55
|
+
const onFailure = (err) => {
|
|
56
|
+
console.error(`[@flare-engine/errors] transport threw while ${stage}`, err);
|
|
57
|
+
};
|
|
58
|
+
try {
|
|
59
|
+
Promise.resolve(transport.report(payload)).catch(onFailure);
|
|
60
|
+
} catch (err) {
|
|
61
|
+
onFailure(err);
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
/** Transport that discards every payload. The default. */
|
|
65
|
+
function createNoopTransport() {
|
|
66
|
+
return { report() {} };
|
|
67
|
+
}
|
|
68
|
+
/**
|
|
69
|
+
* Transport that logs payloads via `console.error`. Useful in development and
|
|
70
|
+
* as a wrapper around another transport when debugging.
|
|
71
|
+
*/
|
|
72
|
+
function createConsoleTransport() {
|
|
73
|
+
return { report(payload) {
|
|
74
|
+
console.error("[@flare-engine/errors]", payload);
|
|
75
|
+
} };
|
|
76
|
+
}
|
|
47
77
|
// src/error-boundary.tsx
|
|
48
78
|
/**
|
|
49
79
|
* React error boundary that captures render-phase errors into a structured
|
|
@@ -61,7 +91,8 @@ var ErrorBoundary = class extends react.Component {
|
|
|
61
91
|
componentStack: info.componentStack ?? null
|
|
62
92
|
});
|
|
63
93
|
this.setState({ payload });
|
|
64
|
-
this.props
|
|
94
|
+
const { transport } = this.props;
|
|
95
|
+
if (transport !== void 0) reportSafely(transport, payload, "reporting");
|
|
65
96
|
this.props.onError?.(error, payload);
|
|
66
97
|
}
|
|
67
98
|
reset = () => {
|
|
@@ -120,11 +151,7 @@ function installGlobalErrorCapture(target, options) {
|
|
|
120
151
|
pending.push(payload);
|
|
121
152
|
return;
|
|
122
153
|
}
|
|
123
|
-
|
|
124
|
-
transport.report(payload);
|
|
125
|
-
} catch (err) {
|
|
126
|
-
console.error("[@flare-engine/errors] transport threw while reporting", err);
|
|
127
|
-
}
|
|
154
|
+
reportSafely(transport, payload, "reporting");
|
|
128
155
|
};
|
|
129
156
|
const onError = (event) => {
|
|
130
157
|
emit(unwrapEvent(event, "error"), { source: "error" });
|
|
@@ -158,14 +185,7 @@ function installGlobalErrorCapture(target, options) {
|
|
|
158
185
|
},
|
|
159
186
|
setTransport(next) {
|
|
160
187
|
transport = next;
|
|
161
|
-
while (pending.length > 0)
|
|
162
|
-
const payload = pending.shift();
|
|
163
|
-
try {
|
|
164
|
-
next.report(payload);
|
|
165
|
-
} catch (err) {
|
|
166
|
-
console.error("[@flare-engine/errors] transport threw while draining", err);
|
|
167
|
-
}
|
|
168
|
-
}
|
|
188
|
+
while (pending.length > 0) reportSafely(next, pending.shift(), "draining");
|
|
169
189
|
},
|
|
170
190
|
get buffered() {
|
|
171
191
|
return pending.length;
|
|
@@ -202,20 +222,6 @@ function createClientTransport(client) {
|
|
|
202
222
|
}
|
|
203
223
|
} };
|
|
204
224
|
}
|
|
205
|
-
// src/transport.ts
|
|
206
|
-
/** Transport that discards every payload. The default. */
|
|
207
|
-
function createNoopTransport() {
|
|
208
|
-
return { report() {} };
|
|
209
|
-
}
|
|
210
|
-
/**
|
|
211
|
-
* Transport that logs payloads via `console.error`. Useful in development and
|
|
212
|
-
* as a wrapper around another transport when debugging.
|
|
213
|
-
*/
|
|
214
|
-
function createConsoleTransport() {
|
|
215
|
-
return { report(payload) {
|
|
216
|
-
console.error("[@flare-engine/errors]", payload);
|
|
217
|
-
} };
|
|
218
|
-
}
|
|
219
225
|
// src/transports/sentry.ts
|
|
220
226
|
const KEPT_INTEGRATIONS = /* @__PURE__ */ new Set([
|
|
221
227
|
"RewriteFrames",
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["Component"],"sources":["../src/compose.ts","../src/crash-payload.ts","../src/error-boundary.tsx","../src/global-capture.ts","../src/transport.ts","../src/transports/sentry.ts"],"sourcesContent":["import type { CrashTransport } from './transport.js';\n\nexport function composeTransports(...transports: CrashTransport[]): CrashTransport {\n return {\n async report(payload) {\n for (const t of transports) {\n try {\n await t.report(payload);\n } catch (err) {\n console.error('[@flare-engine/errors] composeTransports: child transport threw', err);\n }\n }\n },\n };\n}\n","/**\n * Serializable crash payload. Everything here is JSON-safe so transports can\n * post it to Sentry / Crashlytics / a custom HTTP endpoint without extra work.\n */\nexport interface CrashPayload {\n /** Error message. */\n message: string;\n /** Error name (e.g., `TypeError`). */\n name: string;\n /** Captured stack trace, if available. */\n stack: string | null;\n /** Monotonic ms timestamp — `Date.now()` at capture. */\n timestamp: number;\n /** Optional free-form context supplied by the caller. */\n context: Record<string, unknown>;\n}\n\n/**\n * Capture an unknown thrown value as a serializable crash payload. Handles\n * `Error` instances, string throws, and arbitrary values.\n */\nexport function createCrashPayload(\n error: unknown,\n context: Record<string, unknown> = {},\n): CrashPayload {\n if (error instanceof Error) {\n return {\n message: error.message,\n name: error.name,\n stack: error.stack ?? null,\n timestamp: Date.now(),\n context,\n };\n }\n if (typeof error === 'string') {\n return { message: error, name: 'Error', stack: null, timestamp: Date.now(), context };\n }\n let message: string;\n try {\n message = JSON.stringify(error);\n } catch {\n message = String(error);\n }\n return { message, name: 'NonError', stack: null, timestamp: Date.now(), context };\n}\n","import { Component, type ErrorInfo, type ReactNode } from 'react';\nimport { type CrashPayload, createCrashPayload } from './crash-payload.js';\nimport type { CrashTransport } from './transport.js';\n\nexport interface ErrorBoundaryProps {\n children: ReactNode;\n /** Rendered when an error is caught. Receives the payload + a reset callback. */\n fallback: (payload: CrashPayload, reset: () => void) => ReactNode;\n /** Transport invoked once per caught error. */\n transport?: CrashTransport;\n /** Additional context merged into every payload captured by this boundary. */\n context?: Record<string, unknown>;\n /** Called with both the raw error and the payload for custom side effects. */\n onError?: (error: unknown, payload: CrashPayload) => void;\n}\n\ninterface ErrorBoundaryState {\n payload: CrashPayload | null;\n}\n\n/**\n * React error boundary that captures render-phase errors into a structured\n * `CrashPayload`, forwards it to an optional transport, and renders the\n * caller-supplied fallback.\n */\nexport class ErrorBoundary extends Component<ErrorBoundaryProps, ErrorBoundaryState> {\n state: ErrorBoundaryState = { payload: null };\n\n static getDerivedStateFromError(error: unknown): ErrorBoundaryState {\n return { payload: createCrashPayload(error) };\n }\n\n componentDidCatch(error: unknown, info: ErrorInfo): void {\n const context = {\n ...this.props.context,\n componentStack: info.componentStack ?? null,\n };\n const payload = createCrashPayload(error, context);\n this.setState({ payload });\n this.props.transport?.report(payload);\n this.props.onError?.(error, payload);\n }\n\n reset = (): void => {\n this.setState({ payload: null });\n };\n\n render(): ReactNode {\n if (this.state.payload !== null) {\n return this.props.fallback(this.state.payload, this.reset);\n }\n return this.props.children;\n }\n}\n","import { createCrashPayload } from './crash-payload.js';\nimport type { CrashTransport } from './transport.js';\n\n/**\n * React Native's `global.ErrorUtils`, described structurally so this package\n * needs no React Native dependency or types.\n */\nexport interface ErrorUtilsLike {\n getGlobalHandler?(): ((error: unknown, isFatal?: boolean) => void) | undefined;\n setGlobalHandler(handler: (error: unknown, isFatal?: boolean) => void): void;\n}\n\n/**\n * What `installGlobalErrorCapture` needs from a global object.\n *\n * Both members are optional and independent, so one call handles either\n * platform: on web `globalThis` supplies `addEventListener`, on React Native it\n * supplies `ErrorUtils`, and in a test you pass a hand-built fake. Nothing here\n * references `window`, `document` or any RN type.\n */\nexport interface GlobalErrorTarget {\n addEventListener?(type: string, listener: (event: unknown) => void): void;\n removeEventListener?(type: string, listener: (event: unknown) => void): void;\n ErrorUtils?: ErrorUtilsLike;\n}\n\n/** Options for `installGlobalErrorCapture`. */\nexport interface GlobalCaptureOptions {\n /**\n * Where captured errors go. May be omitted at install and attached later with\n * `setTransport` — errors raised in between are held in the buffer below\n * rather than dropped.\n */\n transport?: CrashTransport;\n /**\n * How many pre-transport errors to retain. Default 20. The oldest is dropped\n * once full: a boot loop should not grow memory without bound, and the first\n * errors are the ones worth keeping.\n */\n bufferSize?: number;\n /** Context merged into every payload this capture produces. */\n context?: Record<string, unknown>;\n}\n\n/** Handle returned by `installGlobalErrorCapture`. */\nexport interface GlobalCaptureHandle {\n /**\n * Detach every handler this call installed and restore whatever was there\n * before. Safe to call more than once.\n */\n uninstall(): void;\n /** Attach or replace the transport, draining any buffered errors into it. */\n setTransport(transport: CrashTransport): void;\n /** How many errors are currently held awaiting a transport. */\n readonly buffered: number;\n}\n\n/** Pull the underlying error out of a structurally-typed DOM-ish event. */\nfunction unwrapEvent(event: unknown, key: 'error' | 'reason'): unknown {\n if (typeof event === 'object' && event !== null && key in event) {\n const value = (event as Record<string, unknown>)[key];\n if (value !== undefined && value !== null) return value;\n }\n // An ErrorEvent with no `.error` still carries a message worth reporting.\n if (typeof event === 'object' && event !== null && 'message' in event) {\n return (event as Record<string, unknown>).message;\n }\n return event;\n}\n\n/**\n * Route uncaught errors and unhandled rejections into a `CrashTransport`.\n *\n * `ErrorBoundary` only sees errors thrown during React's render phase. The\n * majority of a game's crashes are not there — they are in the update loop, in\n * an asset load, in a promise nobody awaited — and before this nothing carried\n * them to a transport.\n *\n * Both platforms are handled through the same call:\n *\n * ```ts\n * const capture = installGlobalErrorCapture(globalThis, { transport });\n * // ...\n * capture.uninstall();\n * ```\n *\n * The React Native handler is **chained, not replaced**: whatever handler was\n * installed before still runs, because on RN that handler is what shows the\n * red box in dev and terminates the app on a fatal. Swallowing it would convert\n * a visible crash into a silent one.\n */\nexport function installGlobalErrorCapture(\n target: GlobalErrorTarget,\n options?: GlobalCaptureOptions,\n): GlobalCaptureHandle {\n const bufferSize = Math.max(0, options?.bufferSize ?? 20);\n const context = options?.context ?? {};\n let transport: CrashTransport | null = options?.transport ?? null;\n const pending: ReturnType<typeof createCrashPayload>[] = [];\n let installed = true;\n\n const emit = (error: unknown, extra?: Record<string, unknown>): void => {\n const payload = createCrashPayload(error, extra ? { ...context, ...extra } : { ...context });\n if (transport === null) {\n if (bufferSize === 0) return;\n if (pending.length === bufferSize) pending.shift();\n pending.push(payload);\n return;\n }\n try {\n void transport.report(payload);\n } catch (err) {\n console.error('[@flare-engine/errors] transport threw while reporting', err);\n }\n };\n\n const onError = (event: unknown): void => {\n emit(unwrapEvent(event, 'error'), { source: 'error' });\n };\n const onRejection = (event: unknown): void => {\n emit(unwrapEvent(event, 'reason'), { source: 'unhandledrejection' });\n };\n\n const canListen =\n typeof target.addEventListener === 'function' &&\n typeof target.removeEventListener === 'function';\n if (canListen) {\n target.addEventListener?.('error', onError);\n target.addEventListener?.('unhandledrejection', onRejection);\n }\n\n const errorUtils = target.ErrorUtils;\n const previousHandler = errorUtils?.getGlobalHandler?.();\n if (errorUtils !== undefined) {\n errorUtils.setGlobalHandler((error: unknown, isFatal?: boolean) => {\n emit(error, { source: 'errorUtils', isFatal: isFatal ?? false });\n // Chain, so the platform's own reporting still happens.\n previousHandler?.(error, isFatal);\n });\n }\n\n return {\n uninstall(): void {\n if (!installed) return;\n installed = false;\n if (canListen) {\n target.removeEventListener?.('error', onError);\n target.removeEventListener?.('unhandledrejection', onRejection);\n }\n if (errorUtils !== undefined && previousHandler !== undefined) {\n errorUtils.setGlobalHandler(previousHandler);\n }\n },\n setTransport(next: CrashTransport): void {\n transport = next;\n while (pending.length > 0) {\n const payload = pending.shift()!;\n try {\n void next.report(payload);\n } catch (err) {\n console.error('[@flare-engine/errors] transport threw while draining', err);\n }\n }\n },\n get buffered(): number {\n return pending.length;\n },\n };\n}\n\n/**\n * A Sentry-browser-shaped client, described structurally so this package takes\n * no dependency on `@sentry/browser` (or on any particular client).\n */\nexport interface ErrorClientLike {\n captureException(error: unknown, hint?: unknown): unknown;\n}\n\n/**\n * Transport over an injected browser error client.\n *\n * `createSentryTransport` is native-only — it dynamically imports\n * `@sentry/react-native`, which does not resolve on web. This is the web half:\n * the caller supplies an already-initialised client, so this package neither\n * imports nor initialises one.\n *\n * ```ts\n * import * as Sentry from '@sentry/browser';\n * Sentry.init({ dsn });\n * const transport = createClientTransport(Sentry);\n * ```\n *\n * The payload is rebuilt into an `Error` because that is what such clients\n * group by; the original stack is preserved rather than replaced with this\n * function's own.\n */\nexport function createClientTransport(client: ErrorClientLike): CrashTransport {\n return {\n report(payload): void {\n const error = new Error(payload.message);\n error.name = payload.name;\n if (payload.stack !== null) error.stack = payload.stack;\n try {\n client.captureException(error, { extra: payload.context });\n } catch (err) {\n console.error('[@flare-engine/errors] client.captureException threw', err);\n }\n },\n };\n}\n","import type { CrashPayload } from './crash-payload.js';\n\n/**\n * Pluggable transport for reporting crashes. Implementations send the payload\n * wherever they need — Sentry, Crashlytics, an HTTP endpoint, or nowhere.\n */\nexport interface CrashTransport {\n report(payload: CrashPayload): void | Promise<void>;\n}\n\n/** Transport that discards every payload. The default. */\nexport function createNoopTransport(): CrashTransport {\n return {\n report() {\n /* no-op */\n },\n };\n}\n\n/**\n * Transport that logs payloads via `console.error`. Useful in development and\n * as a wrapper around another transport when debugging.\n */\nexport function createConsoleTransport(): CrashTransport {\n return {\n report(payload) {\n console.error('[@flare-engine/errors]', payload);\n },\n };\n}\n","import type { Integration } from '@sentry/react-native';\nimport type { CrashPayload } from '../crash-payload.js';\nimport type { CrashTransport } from '../transport.js';\nimport { createNoopTransport } from '../transport.js';\n\nexport interface SentryTransportOptions {\n dsn?: string;\n environment?: string;\n release?: string;\n sampleRate?: number;\n enabled?: boolean;\n}\n\n// Sentry must send only what `report()` hands it (ADR-0008). The SDK's default\n// integrations include its own global error/rejection handlers, which report\n// outside the transport and so outside any consent check placed in front of\n// it, plus collectors (breadcrumbs, device context) that attach data to every\n// event. Only event processors that enrich an event already in flight are kept.\n// Fail-safe: a name that does not match on some SDK major only loses that\n// enrichment; an unknown name can never add a capture path.\nconst KEPT_INTEGRATIONS: ReadonlySet<string> = new Set([\n 'RewriteFrames',\n 'Release',\n 'DebugMeta',\n 'SdkInfo',\n 'Dedupe',\n 'InboundFilters',\n 'NativeLinkedErrors',\n 'EventOrigin',\n]);\n\nfunction keepEventProcessors(defaults: Integration[]): Integration[] {\n return defaults.filter((integration) => KEPT_INTEGRATIONS.has(integration.name));\n}\n\nexport function createSentryTransport(opts: SentryTransportOptions): CrashTransport {\n if (!opts.dsn || opts.enabled === false) {\n return createNoopTransport();\n }\n\n const dsn = opts.dsn;\n type SentryMod = typeof import('@sentry/react-native');\n let mod: SentryMod | null = null;\n let loadFailed = false;\n\n return {\n async report(payload: CrashPayload): Promise<void> {\n if (loadFailed) return;\n\n if (mod === null) {\n try {\n mod = await import('@sentry/react-native');\n mod.init({\n dsn,\n environment: opts.environment,\n release: opts.release,\n sampleRate: opts.sampleRate,\n integrations: keepEventProcessors,\n enableAutoSessionTracking: false,\n enableNativeCrashHandling: false,\n enableAppHangTracking: false,\n enableWatchdogTerminationTracking: false,\n sendClientReports: false,\n });\n } catch {\n console.error(\n '[@flare-engine/errors] Failed to load @sentry/react-native — degrading to noop',\n );\n loadFailed = true;\n return;\n }\n }\n\n try {\n const err = Object.assign(new Error(payload.message), { name: payload.name });\n if (payload.stack !== null) err.stack = payload.stack;\n mod.captureException(err, {\n extra: { ...payload.context, capturedAt: payload.timestamp },\n });\n } catch {\n console.error('[@flare-engine/errors] Sentry captureException failed');\n }\n },\n };\n}\n"],"mappings":";;;AAEA,SAAgB,kBAAkB,GAAG,YAA8C;CACjF,OAAO,EACL,MAAM,OAAO,SAAS;EACpB,KAAK,MAAM,KAAK,YACd,IAAI;GACF,MAAM,EAAE,OAAO,OAAO;EACxB,SAAS,KAAK;GACZ,QAAQ,MAAM,mEAAmE,GAAG;EACtF;CAEJ,EACF;AACF;;;;;;ACOA,SAAgB,mBACd,OACA,UAAmC,CAAC,GACtB;CACd,IAAI,iBAAiB,OACnB,OAAO;EACL,SAAS,MAAM;EACf,MAAM,MAAM;EACZ,OAAO,MAAM,SAAS;EACtB,WAAW,KAAK,IAAI;EACpB;CACF;CAEF,IAAI,OAAO,UAAU,UACnB,OAAO;EAAE,SAAS;EAAO,MAAM;EAAS,OAAO;EAAM,WAAW,KAAK,IAAI;EAAG;CAAQ;CAEtF,IAAI;CACJ,IAAI;EACF,UAAU,KAAK,UAAU,KAAK;CAChC,QAAQ;EACN,UAAU,OAAO,KAAK;CACxB;CACA,OAAO;EAAE;EAAS,MAAM;EAAY,OAAO;EAAM,WAAW,KAAK,IAAI;EAAG;CAAQ;AAClF;;;;;;;ACnBA,IAAa,gBAAb,cAAmCA,MAAAA,UAAkD;CACnF,QAA4B,EAAE,SAAS,KAAK;CAE5C,OAAO,yBAAyB,OAAoC;EAClE,OAAO,EAAE,SAAS,mBAAmB,KAAK,EAAE;CAC9C;CAEA,kBAAkB,OAAgB,MAAuB;EAKvD,MAAM,UAAU,mBAAmB,OAAO;GAHxC,GAAG,KAAK,MAAM;GACd,gBAAgB,KAAK,kBAAkB;EAEC,CAAO;EACjD,KAAK,SAAS,EAAE,QAAQ,CAAC;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3,"file":"index.js","names":["Component"],"sources":["../src/compose.ts","../src/crash-payload.ts","../src/transport.ts","../src/error-boundary.tsx","../src/global-capture.ts","../src/transports/sentry.ts"],"sourcesContent":["import type { CrashTransport } from './transport.js';\n\nexport function composeTransports(...transports: CrashTransport[]): CrashTransport {\n return {\n async report(payload) {\n for (const t of transports) {\n try {\n await t.report(payload);\n } catch (err) {\n console.error('[@flare-engine/errors] composeTransports: child transport threw', err);\n }\n }\n },\n };\n}\n","/**\n * Serializable crash payload. Everything here is JSON-safe so transports can\n * post it to Sentry / Crashlytics / a custom HTTP endpoint without extra work.\n */\nexport interface CrashPayload {\n /** Error message. */\n message: string;\n /** Error name (e.g., `TypeError`). */\n name: string;\n /** Captured stack trace, if available. */\n stack: string | null;\n /** Monotonic ms timestamp — `Date.now()` at capture. */\n timestamp: number;\n /** Optional free-form context supplied by the caller. */\n context: Record<string, unknown>;\n}\n\n/**\n * Capture an unknown thrown value as a serializable crash payload. Handles\n * `Error` instances, string throws, and arbitrary values.\n */\nexport function createCrashPayload(\n error: unknown,\n context: Record<string, unknown> = {},\n): CrashPayload {\n if (error instanceof Error) {\n return {\n message: error.message,\n name: error.name,\n stack: error.stack ?? null,\n timestamp: Date.now(),\n context,\n };\n }\n if (typeof error === 'string') {\n return { message: error, name: 'Error', stack: null, timestamp: Date.now(), context };\n }\n let message: string;\n try {\n message = JSON.stringify(error);\n } catch {\n message = String(error);\n }\n return { message, name: 'NonError', stack: null, timestamp: Date.now(), context };\n}\n","import type { CrashPayload } from './crash-payload.js';\n\n/**\n * Pluggable transport for reporting crashes. Implementations send the payload\n * wherever they need — Sentry, Crashlytics, an HTTP endpoint, or nowhere.\n */\nexport interface CrashTransport {\n report(payload: CrashPayload): void | Promise<void>;\n}\n\n/**\n * Call `transport.report` so that neither a synchronous throw nor a rejected\n * promise escapes. Left unhandled, a rejection surfaces on the global as an\n * `unhandledrejection` that `installGlobalErrorCapture` listens for, so each\n * failed report would trigger the next for as long as the transport is down.\n */\nexport function reportSafely(\n transport: CrashTransport,\n payload: CrashPayload,\n stage: 'reporting' | 'draining',\n): void {\n const onFailure = (err: unknown): void => {\n console.error(`[@flare-engine/errors] transport threw while ${stage}`, err);\n };\n try {\n void Promise.resolve(transport.report(payload)).catch(onFailure);\n } catch (err) {\n onFailure(err);\n }\n}\n\n/** Transport that discards every payload. The default. */\nexport function createNoopTransport(): CrashTransport {\n return {\n report() {\n /* no-op */\n },\n };\n}\n\n/**\n * Transport that logs payloads via `console.error`. Useful in development and\n * as a wrapper around another transport when debugging.\n */\nexport function createConsoleTransport(): CrashTransport {\n return {\n report(payload) {\n console.error('[@flare-engine/errors]', payload);\n },\n };\n}\n","import { Component, type ErrorInfo, type ReactNode } from 'react';\nimport { type CrashPayload, createCrashPayload } from './crash-payload.js';\nimport { type CrashTransport, reportSafely } from './transport.js';\n\nexport interface ErrorBoundaryProps {\n children: ReactNode;\n /** Rendered when an error is caught. Receives the payload + a reset callback. */\n fallback: (payload: CrashPayload, reset: () => void) => ReactNode;\n /** Transport invoked once per caught error. */\n transport?: CrashTransport;\n /** Additional context merged into every payload captured by this boundary. */\n context?: Record<string, unknown>;\n /** Called with both the raw error and the payload for custom side effects. */\n onError?: (error: unknown, payload: CrashPayload) => void;\n}\n\ninterface ErrorBoundaryState {\n payload: CrashPayload | null;\n}\n\n/**\n * React error boundary that captures render-phase errors into a structured\n * `CrashPayload`, forwards it to an optional transport, and renders the\n * caller-supplied fallback.\n */\nexport class ErrorBoundary extends Component<ErrorBoundaryProps, ErrorBoundaryState> {\n state: ErrorBoundaryState = { payload: null };\n\n static getDerivedStateFromError(error: unknown): ErrorBoundaryState {\n return { payload: createCrashPayload(error) };\n }\n\n componentDidCatch(error: unknown, info: ErrorInfo): void {\n const context = {\n ...this.props.context,\n componentStack: info.componentStack ?? null,\n };\n const payload = createCrashPayload(error, context);\n this.setState({ payload });\n const { transport } = this.props;\n if (transport !== undefined) reportSafely(transport, payload, 'reporting');\n this.props.onError?.(error, payload);\n }\n\n reset = (): void => {\n this.setState({ payload: null });\n };\n\n render(): ReactNode {\n if (this.state.payload !== null) {\n return this.props.fallback(this.state.payload, this.reset);\n }\n return this.props.children;\n }\n}\n","import { createCrashPayload } from './crash-payload.js';\nimport { type CrashTransport, reportSafely } from './transport.js';\n\n/**\n * React Native's `global.ErrorUtils`, described structurally so this package\n * needs no React Native dependency or types.\n */\nexport interface ErrorUtilsLike {\n getGlobalHandler?(): ((error: unknown, isFatal?: boolean) => void) | undefined;\n setGlobalHandler(handler: (error: unknown, isFatal?: boolean) => void): void;\n}\n\n/**\n * What `installGlobalErrorCapture` needs from a global object.\n *\n * Both members are optional and independent, so one call handles either\n * platform: on web `globalThis` supplies `addEventListener`, on React Native it\n * supplies `ErrorUtils`, and in a test you pass a hand-built fake. Nothing here\n * references `window`, `document` or any RN type.\n */\nexport interface GlobalErrorTarget {\n addEventListener?(type: string, listener: (event: unknown) => void): void;\n removeEventListener?(type: string, listener: (event: unknown) => void): void;\n ErrorUtils?: ErrorUtilsLike;\n}\n\n/** Options for `installGlobalErrorCapture`. */\nexport interface GlobalCaptureOptions {\n /**\n * Where captured errors go. May be omitted at install and attached later with\n * `setTransport` — errors raised in between are held in the buffer below\n * rather than dropped.\n */\n transport?: CrashTransport;\n /**\n * How many pre-transport errors to retain. Default 20. The oldest is dropped\n * once full: a boot loop should not grow memory without bound, and the first\n * errors are the ones worth keeping.\n */\n bufferSize?: number;\n /** Context merged into every payload this capture produces. */\n context?: Record<string, unknown>;\n}\n\n/** Handle returned by `installGlobalErrorCapture`. */\nexport interface GlobalCaptureHandle {\n /**\n * Detach every handler this call installed and restore whatever was there\n * before. Safe to call more than once.\n */\n uninstall(): void;\n /** Attach or replace the transport, draining any buffered errors into it. */\n setTransport(transport: CrashTransport): void;\n /** How many errors are currently held awaiting a transport. */\n readonly buffered: number;\n}\n\n/** Pull the underlying error out of a structurally-typed DOM-ish event. */\nfunction unwrapEvent(event: unknown, key: 'error' | 'reason'): unknown {\n if (typeof event === 'object' && event !== null && key in event) {\n const value = (event as Record<string, unknown>)[key];\n if (value !== undefined && value !== null) return value;\n }\n // An ErrorEvent with no `.error` still carries a message worth reporting.\n if (typeof event === 'object' && event !== null && 'message' in event) {\n return (event as Record<string, unknown>).message;\n }\n return event;\n}\n\n/**\n * Route uncaught errors and unhandled rejections into a `CrashTransport`.\n *\n * `ErrorBoundary` only sees errors thrown during React's render phase. The\n * majority of a game's crashes are not there — they are in the update loop, in\n * an asset load, in a promise nobody awaited — and before this nothing carried\n * them to a transport.\n *\n * Both platforms are handled through the same call:\n *\n * ```ts\n * const capture = installGlobalErrorCapture(globalThis, { transport });\n * // ...\n * capture.uninstall();\n * ```\n *\n * The React Native handler is **chained, not replaced**: whatever handler was\n * installed before still runs, because on RN that handler is what shows the\n * red box in dev and terminates the app on a fatal. Swallowing it would convert\n * a visible crash into a silent one.\n */\nexport function installGlobalErrorCapture(\n target: GlobalErrorTarget,\n options?: GlobalCaptureOptions,\n): GlobalCaptureHandle {\n const bufferSize = Math.max(0, options?.bufferSize ?? 20);\n const context = options?.context ?? {};\n let transport: CrashTransport | null = options?.transport ?? null;\n const pending: ReturnType<typeof createCrashPayload>[] = [];\n let installed = true;\n\n const emit = (error: unknown, extra?: Record<string, unknown>): void => {\n const payload = createCrashPayload(error, extra ? { ...context, ...extra } : { ...context });\n if (transport === null) {\n if (bufferSize === 0) return;\n if (pending.length === bufferSize) pending.shift();\n pending.push(payload);\n return;\n }\n reportSafely(transport, payload, 'reporting');\n };\n\n const onError = (event: unknown): void => {\n emit(unwrapEvent(event, 'error'), { source: 'error' });\n };\n const onRejection = (event: unknown): void => {\n emit(unwrapEvent(event, 'reason'), { source: 'unhandledrejection' });\n };\n\n const canListen =\n typeof target.addEventListener === 'function' &&\n typeof target.removeEventListener === 'function';\n if (canListen) {\n target.addEventListener?.('error', onError);\n target.addEventListener?.('unhandledrejection', onRejection);\n }\n\n const errorUtils = target.ErrorUtils;\n const previousHandler = errorUtils?.getGlobalHandler?.();\n if (errorUtils !== undefined) {\n errorUtils.setGlobalHandler((error: unknown, isFatal?: boolean) => {\n emit(error, { source: 'errorUtils', isFatal: isFatal ?? false });\n // Chain, so the platform's own reporting still happens.\n previousHandler?.(error, isFatal);\n });\n }\n\n return {\n uninstall(): void {\n if (!installed) return;\n installed = false;\n if (canListen) {\n target.removeEventListener?.('error', onError);\n target.removeEventListener?.('unhandledrejection', onRejection);\n }\n if (errorUtils !== undefined && previousHandler !== undefined) {\n errorUtils.setGlobalHandler(previousHandler);\n }\n },\n setTransport(next: CrashTransport): void {\n transport = next;\n while (pending.length > 0) {\n reportSafely(next, pending.shift()!, 'draining');\n }\n },\n get buffered(): number {\n return pending.length;\n },\n };\n}\n\n/**\n * A Sentry-browser-shaped client, described structurally so this package takes\n * no dependency on `@sentry/browser` (or on any particular client).\n */\nexport interface ErrorClientLike {\n captureException(error: unknown, hint?: unknown): unknown;\n}\n\n/**\n * Transport over an injected browser error client.\n *\n * `createSentryTransport` is native-only — it dynamically imports\n * `@sentry/react-native`, which does not resolve on web. This is the web half:\n * the caller supplies an already-initialised client, so this package neither\n * imports nor initialises one.\n *\n * ```ts\n * import * as Sentry from '@sentry/browser';\n * Sentry.init({ dsn });\n * const transport = createClientTransport(Sentry);\n * ```\n *\n * The payload is rebuilt into an `Error` because that is what such clients\n * group by; the original stack is preserved rather than replaced with this\n * function's own.\n */\nexport function createClientTransport(client: ErrorClientLike): CrashTransport {\n return {\n report(payload): void {\n const error = new Error(payload.message);\n error.name = payload.name;\n if (payload.stack !== null) error.stack = payload.stack;\n try {\n client.captureException(error, { extra: payload.context });\n } catch (err) {\n console.error('[@flare-engine/errors] client.captureException threw', err);\n }\n },\n };\n}\n","import type { Integration } from '@sentry/react-native';\nimport type { CrashPayload } from '../crash-payload.js';\nimport type { CrashTransport } from '../transport.js';\nimport { createNoopTransport } from '../transport.js';\n\nexport interface SentryTransportOptions {\n dsn?: string;\n environment?: string;\n release?: string;\n sampleRate?: number;\n enabled?: boolean;\n}\n\n// Sentry must send only what `report()` hands it (ADR-0008). The SDK's default\n// integrations include its own global error/rejection handlers, which report\n// outside the transport and so outside any consent check placed in front of\n// it, plus collectors (breadcrumbs, device context) that attach data to every\n// event. Only event processors that enrich an event already in flight are kept.\n// Fail-safe: a name that does not match on some SDK major only loses that\n// enrichment; an unknown name can never add a capture path.\nconst KEPT_INTEGRATIONS: ReadonlySet<string> = new Set([\n 'RewriteFrames',\n 'Release',\n 'DebugMeta',\n 'SdkInfo',\n 'Dedupe',\n 'InboundFilters',\n 'NativeLinkedErrors',\n 'EventOrigin',\n]);\n\nfunction keepEventProcessors(defaults: Integration[]): Integration[] {\n return defaults.filter((integration) => KEPT_INTEGRATIONS.has(integration.name));\n}\n\nexport function createSentryTransport(opts: SentryTransportOptions): CrashTransport {\n if (!opts.dsn || opts.enabled === false) {\n return createNoopTransport();\n }\n\n const dsn = opts.dsn;\n type SentryMod = typeof import('@sentry/react-native');\n let mod: SentryMod | null = null;\n let loadFailed = false;\n\n return {\n async report(payload: CrashPayload): Promise<void> {\n if (loadFailed) return;\n\n if (mod === null) {\n try {\n mod = await import('@sentry/react-native');\n mod.init({\n dsn,\n environment: opts.environment,\n release: opts.release,\n sampleRate: opts.sampleRate,\n integrations: keepEventProcessors,\n enableAutoSessionTracking: false,\n enableNativeCrashHandling: false,\n enableAppHangTracking: false,\n enableWatchdogTerminationTracking: false,\n sendClientReports: false,\n });\n } catch {\n console.error(\n '[@flare-engine/errors] Failed to load @sentry/react-native — degrading to noop',\n );\n loadFailed = true;\n return;\n }\n }\n\n try {\n const err = Object.assign(new Error(payload.message), { name: payload.name });\n if (payload.stack !== null) err.stack = payload.stack;\n mod.captureException(err, {\n extra: { ...payload.context, capturedAt: payload.timestamp },\n });\n } catch {\n console.error('[@flare-engine/errors] Sentry captureException failed');\n }\n },\n };\n}\n"],"mappings":";;;AAEA,SAAgB,kBAAkB,GAAG,YAA8C;CACjF,OAAO,EACL,MAAM,OAAO,SAAS;EACpB,KAAK,MAAM,KA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,GAAG;EAC3E;CACF,EACF;AACF;;ACpLA,MAAM,oCAAyC,IAAI,IAAI;CACrD;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;AAED,SAAS,oBAAoB,UAAwC;CACnE,OAAO,SAAS,QAAQ,gBAAgB,kBAAkB,IAAI,YAAY,IAAI,CAAC;AACjF;AAEA,SAAgB,sBAAsB,MAA8C;CAClF,IAAI,CAAC,KAAK,OAAO,KAAK,YAAY,OAChC,OAAO,oBAAoB;CAG7B,MAAM,MAAM,KAAK;CAEjB,IAAI,MAAwB;CAC5B,IAAI,aAAa;CAEjB,OAAO,EACL,MAAM,OAAO,SAAsC;EACjD,IAAI,YAAY;EAEhB,IAAI,QAAQ,MACV,IAAI;GACF,MAAM,MAAM,OAAO;GACnB,IAAI,KAAK;IACP;IACA,aAAa,KAAK;IAClB,SAAS,KAAK;IACd,YAAY,KAAK;IACjB,cAAc;IACd,2BAA2B;IAC3B,2BAA2B;IAC3B,uBAAuB;IACvB,mCAAmC;IACnC,mBAAmB;GACrB,CAAC;EACH,QAAQ;GACN,QAAQ,MACN,gFACF;GACA,aAAa;GACb;EACF;EAGF,IAAI;GACF,MAAM,MAAM,OAAO,OAAO,IAAI,MAAM,QAAQ,OAAO,GAAG,EAAE,MAAM,QAAQ,KAAK,CAAC;GAC5E,IAAI,QAAQ,UAAU,MAAM,IAAI,QAAQ,QAAQ;GAChD,IAAI,iBAAiB,KAAK,EACxB,OAAO;IAAE,GAAG,QAAQ;IAAS,YAAY,QAAQ;GAAU,EAC7D,CAAC;EACH,QAAQ;GACN,QAAQ,MAAM,uDAAuD;EACvE;CACF,EACF;AACF"}
|
package/dist/index.mjs
CHANGED
|
@@ -43,6 +43,36 @@ function createCrashPayload(error, context = {}) {
|
|
|
43
43
|
context
|
|
44
44
|
};
|
|
45
45
|
}
|
|
46
|
+
// src/transport.ts
|
|
47
|
+
/**
|
|
48
|
+
* Call `transport.report` so that neither a synchronous throw nor a rejected
|
|
49
|
+
* promise escapes. Left unhandled, a rejection surfaces on the global as an
|
|
50
|
+
* `unhandledrejection` that `installGlobalErrorCapture` listens for, so each
|
|
51
|
+
* failed report would trigger the next for as long as the transport is down.
|
|
52
|
+
*/
|
|
53
|
+
function reportSafely(transport, payload, stage) {
|
|
54
|
+
const onFailure = (err) => {
|
|
55
|
+
console.error(`[@flare-engine/errors] transport threw while ${stage}`, err);
|
|
56
|
+
};
|
|
57
|
+
try {
|
|
58
|
+
Promise.resolve(transport.report(payload)).catch(onFailure);
|
|
59
|
+
} catch (err) {
|
|
60
|
+
onFailure(err);
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
/** Transport that discards every payload. The default. */
|
|
64
|
+
function createNoopTransport() {
|
|
65
|
+
return { report() {} };
|
|
66
|
+
}
|
|
67
|
+
/**
|
|
68
|
+
* Transport that logs payloads via `console.error`. Useful in development and
|
|
69
|
+
* as a wrapper around another transport when debugging.
|
|
70
|
+
*/
|
|
71
|
+
function createConsoleTransport() {
|
|
72
|
+
return { report(payload) {
|
|
73
|
+
console.error("[@flare-engine/errors]", payload);
|
|
74
|
+
} };
|
|
75
|
+
}
|
|
46
76
|
// src/error-boundary.tsx
|
|
47
77
|
/**
|
|
48
78
|
* React error boundary that captures render-phase errors into a structured
|
|
@@ -60,7 +90,8 @@ var ErrorBoundary = class extends Component {
|
|
|
60
90
|
componentStack: info.componentStack ?? null
|
|
61
91
|
});
|
|
62
92
|
this.setState({ payload });
|
|
63
|
-
this.props
|
|
93
|
+
const { transport } = this.props;
|
|
94
|
+
if (transport !== void 0) reportSafely(transport, payload, "reporting");
|
|
64
95
|
this.props.onError?.(error, payload);
|
|
65
96
|
}
|
|
66
97
|
reset = () => {
|
|
@@ -119,11 +150,7 @@ function installGlobalErrorCapture(target, options) {
|
|
|
119
150
|
pending.push(payload);
|
|
120
151
|
return;
|
|
121
152
|
}
|
|
122
|
-
|
|
123
|
-
transport.report(payload);
|
|
124
|
-
} catch (err) {
|
|
125
|
-
console.error("[@flare-engine/errors] transport threw while reporting", err);
|
|
126
|
-
}
|
|
153
|
+
reportSafely(transport, payload, "reporting");
|
|
127
154
|
};
|
|
128
155
|
const onError = (event) => {
|
|
129
156
|
emit(unwrapEvent(event, "error"), { source: "error" });
|
|
@@ -157,14 +184,7 @@ function installGlobalErrorCapture(target, options) {
|
|
|
157
184
|
},
|
|
158
185
|
setTransport(next) {
|
|
159
186
|
transport = next;
|
|
160
|
-
while (pending.length > 0)
|
|
161
|
-
const payload = pending.shift();
|
|
162
|
-
try {
|
|
163
|
-
next.report(payload);
|
|
164
|
-
} catch (err) {
|
|
165
|
-
console.error("[@flare-engine/errors] transport threw while draining", err);
|
|
166
|
-
}
|
|
167
|
-
}
|
|
187
|
+
while (pending.length > 0) reportSafely(next, pending.shift(), "draining");
|
|
168
188
|
},
|
|
169
189
|
get buffered() {
|
|
170
190
|
return pending.length;
|
|
@@ -201,20 +221,6 @@ function createClientTransport(client) {
|
|
|
201
221
|
}
|
|
202
222
|
} };
|
|
203
223
|
}
|
|
204
|
-
// src/transport.ts
|
|
205
|
-
/** Transport that discards every payload. The default. */
|
|
206
|
-
function createNoopTransport() {
|
|
207
|
-
return { report() {} };
|
|
208
|
-
}
|
|
209
|
-
/**
|
|
210
|
-
* Transport that logs payloads via `console.error`. Useful in development and
|
|
211
|
-
* as a wrapper around another transport when debugging.
|
|
212
|
-
*/
|
|
213
|
-
function createConsoleTransport() {
|
|
214
|
-
return { report(payload) {
|
|
215
|
-
console.error("[@flare-engine/errors]", payload);
|
|
216
|
-
} };
|
|
217
|
-
}
|
|
218
224
|
// src/transports/sentry.ts
|
|
219
225
|
const KEPT_INTEGRATIONS = /* @__PURE__ */ new Set([
|
|
220
226
|
"RewriteFrames",
|
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":[],"sources":["../src/compose.ts","../src/crash-payload.ts","../src/error-boundary.tsx","../src/global-capture.ts","../src/transport.ts","../src/transports/sentry.ts"],"sourcesContent":["import type { CrashTransport } from './transport.js';\n\nexport function composeTransports(...transports: CrashTransport[]): CrashTransport {\n return {\n async report(payload) {\n for (const t of transports) {\n try {\n await t.report(payload);\n } catch (err) {\n console.error('[@flare-engine/errors] composeTransports: child transport threw', err);\n }\n }\n },\n };\n}\n","/**\n * Serializable crash payload. Everything here is JSON-safe so transports can\n * post it to Sentry / Crashlytics / a custom HTTP endpoint without extra work.\n */\nexport interface CrashPayload {\n /** Error message. */\n message: string;\n /** Error name (e.g., `TypeError`). */\n name: string;\n /** Captured stack trace, if available. */\n stack: string | null;\n /** Monotonic ms timestamp — `Date.now()` at capture. */\n timestamp: number;\n /** Optional free-form context supplied by the caller. */\n context: Record<string, unknown>;\n}\n\n/**\n * Capture an unknown thrown value as a serializable crash payload. Handles\n * `Error` instances, string throws, and arbitrary values.\n */\nexport function createCrashPayload(\n error: unknown,\n context: Record<string, unknown> = {},\n): CrashPayload {\n if (error instanceof Error) {\n return {\n message: error.message,\n name: error.name,\n stack: error.stack ?? null,\n timestamp: Date.now(),\n context,\n };\n }\n if (typeof error === 'string') {\n return { message: error, name: 'Error', stack: null, timestamp: Date.now(), context };\n }\n let message: string;\n try {\n message = JSON.stringify(error);\n } catch {\n message = String(error);\n }\n return { message, name: 'NonError', stack: null, timestamp: Date.now(), context };\n}\n","import { Component, type ErrorInfo, type ReactNode } from 'react';\nimport { type CrashPayload, createCrashPayload } from './crash-payload.js';\nimport type { CrashTransport } from './transport.js';\n\nexport interface ErrorBoundaryProps {\n children: ReactNode;\n /** Rendered when an error is caught. Receives the payload + a reset callback. */\n fallback: (payload: CrashPayload, reset: () => void) => ReactNode;\n /** Transport invoked once per caught error. */\n transport?: CrashTransport;\n /** Additional context merged into every payload captured by this boundary. */\n context?: Record<string, unknown>;\n /** Called with both the raw error and the payload for custom side effects. */\n onError?: (error: unknown, payload: CrashPayload) => void;\n}\n\ninterface ErrorBoundaryState {\n payload: CrashPayload | null;\n}\n\n/**\n * React error boundary that captures render-phase errors into a structured\n * `CrashPayload`, forwards it to an optional transport, and renders the\n * caller-supplied fallback.\n */\nexport class ErrorBoundary extends Component<ErrorBoundaryProps, ErrorBoundaryState> {\n state: ErrorBoundaryState = { payload: null };\n\n static getDerivedStateFromError(error: unknown): ErrorBoundaryState {\n return { payload: createCrashPayload(error) };\n }\n\n componentDidCatch(error: unknown, info: ErrorInfo): void {\n const context = {\n ...this.props.context,\n componentStack: info.componentStack ?? null,\n };\n const payload = createCrashPayload(error, context);\n this.setState({ payload });\n this.props.transport?.report(payload);\n this.props.onError?.(error, payload);\n }\n\n reset = (): void => {\n this.setState({ payload: null });\n };\n\n render(): ReactNode {\n if (this.state.payload !== null) {\n return this.props.fallback(this.state.payload, this.reset);\n }\n return this.props.children;\n }\n}\n","import { createCrashPayload } from './crash-payload.js';\nimport type { CrashTransport } from './transport.js';\n\n/**\n * React Native's `global.ErrorUtils`, described structurally so this package\n * needs no React Native dependency or types.\n */\nexport interface ErrorUtilsLike {\n getGlobalHandler?(): ((error: unknown, isFatal?: boolean) => void) | undefined;\n setGlobalHandler(handler: (error: unknown, isFatal?: boolean) => void): void;\n}\n\n/**\n * What `installGlobalErrorCapture` needs from a global object.\n *\n * Both members are optional and independent, so one call handles either\n * platform: on web `globalThis` supplies `addEventListener`, on React Native it\n * supplies `ErrorUtils`, and in a test you pass a hand-built fake. Nothing here\n * references `window`, `document` or any RN type.\n */\nexport interface GlobalErrorTarget {\n addEventListener?(type: string, listener: (event: unknown) => void): void;\n removeEventListener?(type: string, listener: (event: unknown) => void): void;\n ErrorUtils?: ErrorUtilsLike;\n}\n\n/** Options for `installGlobalErrorCapture`. */\nexport interface GlobalCaptureOptions {\n /**\n * Where captured errors go. May be omitted at install and attached later with\n * `setTransport` — errors raised in between are held in the buffer below\n * rather than dropped.\n */\n transport?: CrashTransport;\n /**\n * How many pre-transport errors to retain. Default 20. The oldest is dropped\n * once full: a boot loop should not grow memory without bound, and the first\n * errors are the ones worth keeping.\n */\n bufferSize?: number;\n /** Context merged into every payload this capture produces. */\n context?: Record<string, unknown>;\n}\n\n/** Handle returned by `installGlobalErrorCapture`. */\nexport interface GlobalCaptureHandle {\n /**\n * Detach every handler this call installed and restore whatever was there\n * before. Safe to call more than once.\n */\n uninstall(): void;\n /** Attach or replace the transport, draining any buffered errors into it. */\n setTransport(transport: CrashTransport): void;\n /** How many errors are currently held awaiting a transport. */\n readonly buffered: number;\n}\n\n/** Pull the underlying error out of a structurally-typed DOM-ish event. */\nfunction unwrapEvent(event: unknown, key: 'error' | 'reason'): unknown {\n if (typeof event === 'object' && event !== null && key in event) {\n const value = (event as Record<string, unknown>)[key];\n if (value !== undefined && value !== null) return value;\n }\n // An ErrorEvent with no `.error` still carries a message worth reporting.\n if (typeof event === 'object' && event !== null && 'message' in event) {\n return (event as Record<string, unknown>).message;\n }\n return event;\n}\n\n/**\n * Route uncaught errors and unhandled rejections into a `CrashTransport`.\n *\n * `ErrorBoundary` only sees errors thrown during React's render phase. The\n * majority of a game's crashes are not there — they are in the update loop, in\n * an asset load, in a promise nobody awaited — and before this nothing carried\n * them to a transport.\n *\n * Both platforms are handled through the same call:\n *\n * ```ts\n * const capture = installGlobalErrorCapture(globalThis, { transport });\n * // ...\n * capture.uninstall();\n * ```\n *\n * The React Native handler is **chained, not replaced**: whatever handler was\n * installed before still runs, because on RN that handler is what shows the\n * red box in dev and terminates the app on a fatal. Swallowing it would convert\n * a visible crash into a silent one.\n */\nexport function installGlobalErrorCapture(\n target: GlobalErrorTarget,\n options?: GlobalCaptureOptions,\n): GlobalCaptureHandle {\n const bufferSize = Math.max(0, options?.bufferSize ?? 20);\n const context = options?.context ?? {};\n let transport: CrashTransport | null = options?.transport ?? null;\n const pending: ReturnType<typeof createCrashPayload>[] = [];\n let installed = true;\n\n const emit = (error: unknown, extra?: Record<string, unknown>): void => {\n const payload = createCrashPayload(error, extra ? { ...context, ...extra } : { ...context });\n if (transport === null) {\n if (bufferSize === 0) return;\n if (pending.length === bufferSize) pending.shift();\n pending.push(payload);\n return;\n }\n try {\n void transport.report(payload);\n } catch (err) {\n console.error('[@flare-engine/errors] transport threw while reporting', err);\n }\n };\n\n const onError = (event: unknown): void => {\n emit(unwrapEvent(event, 'error'), { source: 'error' });\n };\n const onRejection = (event: unknown): void => {\n emit(unwrapEvent(event, 'reason'), { source: 'unhandledrejection' });\n };\n\n const canListen =\n typeof target.addEventListener === 'function' &&\n typeof target.removeEventListener === 'function';\n if (canListen) {\n target.addEventListener?.('error', onError);\n target.addEventListener?.('unhandledrejection', onRejection);\n }\n\n const errorUtils = target.ErrorUtils;\n const previousHandler = errorUtils?.getGlobalHandler?.();\n if (errorUtils !== undefined) {\n errorUtils.setGlobalHandler((error: unknown, isFatal?: boolean) => {\n emit(error, { source: 'errorUtils', isFatal: isFatal ?? false });\n // Chain, so the platform's own reporting still happens.\n previousHandler?.(error, isFatal);\n });\n }\n\n return {\n uninstall(): void {\n if (!installed) return;\n installed = false;\n if (canListen) {\n target.removeEventListener?.('error', onError);\n target.removeEventListener?.('unhandledrejection', onRejection);\n }\n if (errorUtils !== undefined && previousHandler !== undefined) {\n errorUtils.setGlobalHandler(previousHandler);\n }\n },\n setTransport(next: CrashTransport): void {\n transport = next;\n while (pending.length > 0) {\n const payload = pending.shift()!;\n try {\n void next.report(payload);\n } catch (err) {\n console.error('[@flare-engine/errors] transport threw while draining', err);\n }\n }\n },\n get buffered(): number {\n return pending.length;\n },\n };\n}\n\n/**\n * A Sentry-browser-shaped client, described structurally so this package takes\n * no dependency on `@sentry/browser` (or on any particular client).\n */\nexport interface ErrorClientLike {\n captureException(error: unknown, hint?: unknown): unknown;\n}\n\n/**\n * Transport over an injected browser error client.\n *\n * `createSentryTransport` is native-only — it dynamically imports\n * `@sentry/react-native`, which does not resolve on web. This is the web half:\n * the caller supplies an already-initialised client, so this package neither\n * imports nor initialises one.\n *\n * ```ts\n * import * as Sentry from '@sentry/browser';\n * Sentry.init({ dsn });\n * const transport = createClientTransport(Sentry);\n * ```\n *\n * The payload is rebuilt into an `Error` because that is what such clients\n * group by; the original stack is preserved rather than replaced with this\n * function's own.\n */\nexport function createClientTransport(client: ErrorClientLike): CrashTransport {\n return {\n report(payload): void {\n const error = new Error(payload.message);\n error.name = payload.name;\n if (payload.stack !== null) error.stack = payload.stack;\n try {\n client.captureException(error, { extra: payload.context });\n } catch (err) {\n console.error('[@flare-engine/errors] client.captureException threw', err);\n }\n },\n };\n}\n","import type { CrashPayload } from './crash-payload.js';\n\n/**\n * Pluggable transport for reporting crashes. Implementations send the payload\n * wherever they need — Sentry, Crashlytics, an HTTP endpoint, or nowhere.\n */\nexport interface CrashTransport {\n report(payload: CrashPayload): void | Promise<void>;\n}\n\n/** Transport that discards every payload. The default. */\nexport function createNoopTransport(): CrashTransport {\n return {\n report() {\n /* no-op */\n },\n };\n}\n\n/**\n * Transport that logs payloads via `console.error`. Useful in development and\n * as a wrapper around another transport when debugging.\n */\nexport function createConsoleTransport(): CrashTransport {\n return {\n report(payload) {\n console.error('[@flare-engine/errors]', payload);\n },\n };\n}\n","import type { Integration } from '@sentry/react-native';\nimport type { CrashPayload } from '../crash-payload.js';\nimport type { CrashTransport } from '../transport.js';\nimport { createNoopTransport } from '../transport.js';\n\nexport interface SentryTransportOptions {\n dsn?: string;\n environment?: string;\n release?: string;\n sampleRate?: number;\n enabled?: boolean;\n}\n\n// Sentry must send only what `report()` hands it (ADR-0008). The SDK's default\n// integrations include its own global error/rejection handlers, which report\n// outside the transport and so outside any consent check placed in front of\n// it, plus collectors (breadcrumbs, device context) that attach data to every\n// event. Only event processors that enrich an event already in flight are kept.\n// Fail-safe: a name that does not match on some SDK major only loses that\n// enrichment; an unknown name can never add a capture path.\nconst KEPT_INTEGRATIONS: ReadonlySet<string> = new Set([\n 'RewriteFrames',\n 'Release',\n 'DebugMeta',\n 'SdkInfo',\n 'Dedupe',\n 'InboundFilters',\n 'NativeLinkedErrors',\n 'EventOrigin',\n]);\n\nfunction keepEventProcessors(defaults: Integration[]): Integration[] {\n return defaults.filter((integration) => KEPT_INTEGRATIONS.has(integration.name));\n}\n\nexport function createSentryTransport(opts: SentryTransportOptions): CrashTransport {\n if (!opts.dsn || opts.enabled === false) {\n return createNoopTransport();\n }\n\n const dsn = opts.dsn;\n type SentryMod = typeof import('@sentry/react-native');\n let mod: SentryMod | null = null;\n let loadFailed = false;\n\n return {\n async report(payload: CrashPayload): Promise<void> {\n if (loadFailed) return;\n\n if (mod === null) {\n try {\n mod = await import('@sentry/react-native');\n mod.init({\n dsn,\n environment: opts.environment,\n release: opts.release,\n sampleRate: opts.sampleRate,\n integrations: keepEventProcessors,\n enableAutoSessionTracking: false,\n enableNativeCrashHandling: false,\n enableAppHangTracking: false,\n enableWatchdogTerminationTracking: false,\n sendClientReports: false,\n });\n } catch {\n console.error(\n '[@flare-engine/errors] Failed to load @sentry/react-native — degrading to noop',\n );\n loadFailed = true;\n return;\n }\n }\n\n try {\n const err = Object.assign(new Error(payload.message), { name: payload.name });\n if (payload.stack !== null) err.stack = payload.stack;\n mod.captureException(err, {\n extra: { ...payload.context, capturedAt: payload.timestamp },\n });\n } catch {\n console.error('[@flare-engine/errors] Sentry captureException failed');\n }\n },\n };\n}\n"],"mappings":";;AAEA,SAAgB,kBAAkB,GAAG,YAA8C;CACjF,OAAO,EACL,MAAM,OAAO,SAAS;EACpB,KAAK,MAAM,KAAK,YACd,IAAI;GACF,MAAM,EAAE,OAAO,OAAO;EACxB,SAAS,KAAK;GACZ,QAAQ,MAAM,mEAAmE,GAAG;EACtF;CAEJ,EACF;AACF;;;;;;ACOA,SAAgB,mBACd,OACA,UAAmC,CAAC,GACtB;CACd,IAAI,iBAAiB,OACnB,OAAO;EACL,SAAS,MAAM;EACf,MAAM,MAAM;EACZ,OAAO,MAAM,SAAS;EACtB,WAAW,KAAK,IAAI;EACpB;CACF;CAEF,IAAI,OAAO,UAAU,UACnB,OAAO;EAAE,SAAS;EAAO,MAAM;EAAS,OAAO;EAAM,WAAW,KAAK,IAAI;EAAG;CAAQ;CAE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YAAY,KAAK;IACjB,cAAc;IACd,2BAA2B;IAC3B,2BAA2B;IAC3B,uBAAuB;IACvB,mCAAmC;IACnC,mBAAmB;GACrB,CAAC;EACH,QAAQ;GACN,QAAQ,MACN,gFACF;GACA,aAAa;GACb;EACF;EAGF,IAAI;GACF,MAAM,MAAM,OAAO,OAAO,IAAI,MAAM,QAAQ,OAAO,GAAG,EAAE,MAAM,QAAQ,KAAK,CAAC;GAC5E,IAAI,QAAQ,UAAU,MAAM,IAAI,QAAQ,QAAQ;GAChD,IAAI,iBAAiB,KAAK,EACxB,OAAO;IAAE,GAAG,QAAQ;IAAS,YAAY,QAAQ;GAAU,EAC7D,CAAC;EACH,QAAQ;GACN,QAAQ,MAAM,uDAAuD;EACvE;CACF,EACF;AACF"}
|
|
1
|
+
{"version":3,"file":"index.mjs","names":[],"sources":["../src/compose.ts","../src/crash-payload.ts","../src/transport.ts","../src/error-boundary.tsx","../src/global-capture.ts","../src/transports/sentry.ts"],"sourcesContent":["import type { CrashTransport } from './transport.js';\n\nexport function composeTransports(...transports: CrashTransport[]): CrashTransport {\n return {\n async report(payload) {\n for (const t of transports) {\n try {\n await t.report(payload);\n } catch (err) {\n console.error('[@flare-engine/errors] composeTransports: child transport threw', err);\n }\n }\n },\n };\n}\n","/**\n * Serializable crash payload. Everything here is JSON-safe so transports can\n * post it to Sentry / Crashlytics / a custom HTTP endpoint without extra work.\n */\nexport interface CrashPayload {\n /** Error message. */\n message: string;\n /** Error name (e.g., `TypeError`). */\n name: string;\n /** Captured stack trace, if available. */\n stack: string | null;\n /** Monotonic ms timestamp — `Date.now()` at capture. */\n timestamp: number;\n /** Optional free-form context supplied by the caller. */\n context: Record<string, unknown>;\n}\n\n/**\n * Capture an unknown thrown value as a serializable crash payload. Handles\n * `Error` instances, string throws, and arbitrary values.\n */\nexport function createCrashPayload(\n error: unknown,\n context: Record<string, unknown> = {},\n): CrashPayload {\n if (error instanceof Error) {\n return {\n message: error.message,\n name: error.name,\n stack: error.stack ?? null,\n timestamp: Date.now(),\n context,\n };\n }\n if (typeof error === 'string') {\n return { message: error, name: 'Error', stack: null, timestamp: Date.now(), context };\n }\n let message: string;\n try {\n message = JSON.stringify(error);\n } catch {\n message = String(error);\n }\n return { message, name: 'NonError', stack: null, timestamp: Date.now(), context };\n}\n","import type { CrashPayload } from './crash-payload.js';\n\n/**\n * Pluggable transport for reporting crashes. Implementations send the payload\n * wherever they need — Sentry, Crashlytics, an HTTP endpoint, or nowhere.\n */\nexport interface CrashTransport {\n report(payload: CrashPayload): void | Promise<void>;\n}\n\n/**\n * Call `transport.report` so that neither a synchronous throw nor a rejected\n * promise escapes. Left unhandled, a rejection surfaces on the global as an\n * `unhandledrejection` that `installGlobalErrorCapture` listens for, so each\n * failed report would trigger the next for as long as the transport is down.\n */\nexport function reportSafely(\n transport: CrashTransport,\n payload: CrashPayload,\n stage: 'reporting' | 'draining',\n): void {\n const onFailure = (err: unknown): void => {\n console.error(`[@flare-engine/errors] transport threw while ${stage}`, err);\n };\n try {\n void Promise.resolve(transport.report(payload)).catch(onFailure);\n } catch (err) {\n onFailure(err);\n }\n}\n\n/** Transport that discards every payload. The default. */\nexport function createNoopTransport(): CrashTransport {\n return {\n report() {\n /* no-op */\n },\n };\n}\n\n/**\n * Transport that logs payloads via `console.error`. Useful in development and\n * as a wrapper around another transport when debugging.\n */\nexport function createConsoleTransport(): CrashTransport {\n return {\n report(payload) {\n console.error('[@flare-engine/errors]', payload);\n },\n };\n}\n","import { Component, type ErrorInfo, type ReactNode } from 'react';\nimport { type CrashPayload, createCrashPayload } from './crash-payload.js';\nimport { type CrashTransport, reportSafely } from './transport.js';\n\nexport interface ErrorBoundaryProps {\n children: ReactNode;\n /** Rendered when an error is caught. Receives the payload + a reset callback. */\n fallback: (payload: CrashPayload, reset: () => void) => ReactNode;\n /** Transport invoked once per caught error. */\n transport?: CrashTransport;\n /** Additional context merged into every payload captured by this boundary. */\n context?: Record<string, unknown>;\n /** Called with both the raw error and the payload for custom side effects. */\n onError?: (error: unknown, payload: CrashPayload) => void;\n}\n\ninterface ErrorBoundaryState {\n payload: CrashPayload | null;\n}\n\n/**\n * React error boundary that captures render-phase errors into a structured\n * `CrashPayload`, forwards it to an optional transport, and renders the\n * caller-supplied fallback.\n */\nexport class ErrorBoundary extends Component<ErrorBoundaryProps, ErrorBoundaryState> {\n state: ErrorBoundaryState = { payload: null };\n\n static getDerivedStateFromError(error: unknown): ErrorBoundaryState {\n return { payload: createCrashPayload(error) };\n }\n\n componentDidCatch(error: unknown, info: ErrorInfo): void {\n const context = {\n ...this.props.context,\n componentStack: info.componentStack ?? null,\n };\n const payload = createCrashPayload(error, context);\n this.setState({ payload });\n const { transport } = this.props;\n if (transport !== undefined) reportSafely(transport, payload, 'reporting');\n this.props.onError?.(error, payload);\n }\n\n reset = (): void => {\n this.setState({ payload: null });\n };\n\n render(): ReactNode {\n if (this.state.payload !== null) {\n return this.props.fallback(this.state.payload, this.reset);\n }\n return this.props.children;\n }\n}\n","import { createCrashPayload } from './crash-payload.js';\nimport { type CrashTransport, reportSafely } from './transport.js';\n\n/**\n * React Native's `global.ErrorUtils`, described structurally so this package\n * needs no React Native dependency or types.\n */\nexport interface ErrorUtilsLike {\n getGlobalHandler?(): ((error: unknown, isFatal?: boolean) => void) | undefined;\n setGlobalHandler(handler: (error: unknown, isFatal?: boolean) => void): void;\n}\n\n/**\n * What `installGlobalErrorCapture` needs from a global object.\n *\n * Both members are optional and independent, so one call handles either\n * platform: on web `globalThis` supplies `addEventListener`, on React Native it\n * supplies `ErrorUtils`, and in a test you pass a hand-built fake. Nothing here\n * references `window`, `document` or any RN type.\n */\nexport interface GlobalErrorTarget {\n addEventListener?(type: string, listener: (event: unknown) => void): void;\n removeEventListener?(type: string, listener: (event: unknown) => void): void;\n ErrorUtils?: ErrorUtilsLike;\n}\n\n/** Options for `installGlobalErrorCapture`. */\nexport interface GlobalCaptureOptions {\n /**\n * Where captured errors go. May be omitted at install and attached later with\n * `setTransport` — errors raised in between are held in the buffer below\n * rather than dropped.\n */\n transport?: CrashTransport;\n /**\n * How many pre-transport errors to retain. Default 20. The oldest is dropped\n * once full: a boot loop should not grow memory without bound, and the first\n * errors are the ones worth keeping.\n */\n bufferSize?: number;\n /** Context merged into every payload this capture produces. */\n context?: Record<string, unknown>;\n}\n\n/** Handle returned by `installGlobalErrorCapture`. */\nexport interface GlobalCaptureHandle {\n /**\n * Detach every handler this call installed and restore whatever was there\n * before. Safe to call more than once.\n */\n uninstall(): void;\n /** Attach or replace the transport, draining any buffered errors into it. */\n setTransport(transport: CrashTransport): void;\n /** How many errors are currently held awaiting a transport. */\n readonly buffered: number;\n}\n\n/** Pull the underlying error out of a structurally-typed DOM-ish event. */\nfunction unwrapEvent(event: unknown, key: 'error' | 'reason'): unknown {\n if (typeof event === 'object' && event !== null && key in event) {\n const value = (event as Record<string, unknown>)[key];\n if (value !== undefined && value !== null) return value;\n }\n // An ErrorEvent with no `.error` still carries a message worth reporting.\n if (typeof event === 'object' && event !== null && 'message' in event) {\n return (event as Record<string, unknown>).message;\n }\n return event;\n}\n\n/**\n * Route uncaught errors and unhandled rejections into a `CrashTransport`.\n *\n * `ErrorBoundary` only sees errors thrown during React's render phase. The\n * majority of a game's crashes are not there — they are in the update loop, in\n * an asset load, in a promise nobody awaited — and before this nothing carried\n * them to a transport.\n *\n * Both platforms are handled through the same call:\n *\n * ```ts\n * const capture = installGlobalErrorCapture(globalThis, { transport });\n * // ...\n * capture.uninstall();\n * ```\n *\n * The React Native handler is **chained, not replaced**: whatever handler was\n * installed before still runs, because on RN that handler is what shows the\n * red box in dev and terminates the app on a fatal. Swallowing it would convert\n * a visible crash into a silent one.\n */\nexport function installGlobalErrorCapture(\n target: GlobalErrorTarget,\n options?: GlobalCaptureOptions,\n): GlobalCaptureHandle {\n const bufferSize = Math.max(0, options?.bufferSize ?? 20);\n const context = options?.context ?? {};\n let transport: CrashTransport | null = options?.transport ?? null;\n const pending: ReturnType<typeof createCrashPayload>[] = [];\n let installed = true;\n\n const emit = (error: unknown, extra?: Record<string, unknown>): void => {\n const payload = createCrashPayload(error, extra ? { ...context, ...extra } : { ...context });\n if (transport === null) {\n if (bufferSize === 0) return;\n if (pending.length === bufferSize) pending.shift();\n pending.push(payload);\n return;\n }\n reportSafely(transport, payload, 'reporting');\n };\n\n const onError = (event: unknown): void => {\n emit(unwrapEvent(event, 'error'), { source: 'error' });\n };\n const onRejection = (event: unknown): void => {\n emit(unwrapEvent(event, 'reason'), { source: 'unhandledrejection' });\n };\n\n const canListen =\n typeof target.addEventListener === 'function' &&\n typeof target.removeEventListener === 'function';\n if (canListen) {\n target.addEventListener?.('error', onError);\n target.addEventListener?.('unhandledrejection', onRejection);\n }\n\n const errorUtils = target.ErrorUtils;\n const previousHandler = errorUtils?.getGlobalHandler?.();\n if (errorUtils !== undefined) {\n errorUtils.setGlobalHandler((error: unknown, isFatal?: boolean) => {\n emit(error, { source: 'errorUtils', isFatal: isFatal ?? false });\n // Chain, so the platform's own reporting still happens.\n previousHandler?.(error, isFatal);\n });\n }\n\n return {\n uninstall(): void {\n if (!installed) return;\n installed = false;\n if (canListen) {\n target.removeEventListener?.('error', onError);\n target.removeEventListener?.('unhandledrejection', onRejection);\n }\n if (errorUtils !== undefined && previousHandler !== undefined) {\n errorUtils.setGlobalHandler(previousHandler);\n }\n },\n setTransport(next: CrashTransport): void {\n transport = next;\n while (pending.length > 0) {\n reportSafely(next, pending.shift()!, 'draining');\n }\n },\n get buffered(): number {\n return pending.length;\n },\n };\n}\n\n/**\n * A Sentry-browser-shaped client, described structurally so this package takes\n * no dependency on `@sentry/browser` (or on any particular client).\n */\nexport interface ErrorClientLike {\n captureException(error: unknown, hint?: unknown): unknown;\n}\n\n/**\n * Transport over an injected browser error client.\n *\n * `createSentryTransport` is native-only — it dynamically imports\n * `@sentry/react-native`, which does not resolve on web. This is the web half:\n * the caller supplies an already-initialised client, so this package neither\n * imports nor initialises one.\n *\n * ```ts\n * import * as Sentry from '@sentry/browser';\n * Sentry.init({ dsn });\n * const transport = createClientTransport(Sentry);\n * ```\n *\n * The payload is rebuilt into an `Error` because that is what such clients\n * group by; the original stack is preserved rather than replaced with this\n * function's own.\n */\nexport function createClientTransport(client: ErrorClientLike): CrashTransport {\n return {\n report(payload): void {\n const error = new Error(payload.message);\n error.name = payload.name;\n if (payload.stack !== null) error.stack = payload.stack;\n try {\n client.captureException(error, { extra: payload.context });\n } catch (err) {\n console.error('[@flare-engine/errors] client.captureException threw', err);\n }\n },\n };\n}\n","import type { Integration } from '@sentry/react-native';\nimport type { CrashPayload } from '../crash-payload.js';\nimport type { CrashTransport } from '../transport.js';\nimport { createNoopTransport } from '../transport.js';\n\nexport interface SentryTransportOptions {\n dsn?: string;\n environment?: string;\n release?: string;\n sampleRate?: number;\n enabled?: boolean;\n}\n\n// Sentry must send only what `report()` hands it (ADR-0008). The SDK's default\n// integrations include its own global error/rejection handlers, which report\n// outside the transport and so outside any consent check placed in front of\n// it, plus collectors (breadcrumbs, device context) that attach data to every\n// event. Only event processors that enrich an event already in flight are kept.\n// Fail-safe: a name that does not match on some SDK major only loses that\n// enrichment; an unknown name can never add a capture path.\nconst KEPT_INTEGRATIONS: ReadonlySet<string> = new Set([\n 'RewriteFrames',\n 'Release',\n 'DebugMeta',\n 'SdkInfo',\n 'Dedupe',\n 'InboundFilters',\n 'NativeLinkedErrors',\n 'EventOrigin',\n]);\n\nfunction keepEventProcessors(defaults: Integration[]): Integration[] {\n return defaults.filter((integration) => KEPT_INTEGRATIONS.has(integration.name));\n}\n\nexport function createSentryTransport(opts: SentryTransportOptions): CrashTransport {\n if (!opts.dsn || opts.enabled === false) {\n return createNoopTransport();\n }\n\n const dsn = opts.dsn;\n type SentryMod = typeof import('@sentry/react-native');\n let mod: SentryMod | null = null;\n let loadFailed = false;\n\n return {\n async report(payload: CrashPayload): Promise<void> {\n if (loadFailed) return;\n\n if (mod === null) {\n try {\n mod = await import('@sentry/react-native');\n mod.init({\n dsn,\n environment: opts.environment,\n release: opts.release,\n sampleRate: opts.sampleRate,\n integrations: keepEventProcessors,\n enableAutoSessionTracking: false,\n enableNativeCrashHandling: false,\n enableAppHangTracking: false,\n enableWatchdogTerminationTracking: false,\n sendClientReports: false,\n });\n } catch {\n console.error(\n '[@flare-engine/errors] Failed to load @sentry/react-native — degrading to noop',\n );\n loadFailed = true;\n return;\n }\n }\n\n try {\n const err = Object.assign(new Error(payload.message), { name: payload.name });\n if (payload.stack !== null) err.stack = payload.stack;\n mod.captureException(err, {\n extra: { ...payload.context, capturedAt: payload.timestamp },\n });\n } catch {\n console.error('[@flare-engine/errors] Sentry captureException failed');\n }\n },\n };\n}\n"],"mappings":";;AAEA,SAAgB,kBAAkB,GAAG,YAA8C;CACjF,OAAO,EACL,MAAM,OAAO,SAAS;EACpB,KAAK,MAAM,KAAK,YACd,IAAI;GACF,MAAM,EAAE,OAAO,OAAO;EACxB,SAAS,KAAK;GACZ,QAAQ,MAAM,mEAAmE,GAAG;EACtF;CAEJ,EACF;AACF;;;;;;ACOA,SAAgB,mBACd,OACA,UAAmC,CAAC,GACtB;CACd,IAAI,iBAAiB,OACnB,OAAO;EACL,SAAS,MAAM;EACf,MAAM,MAAM;EACZ,OAAO,MAAM,SAAS;EACtB,WAAW,KAAK,IAAI;EACpB;CACF;CAEF,IAAI,OAAO,UAAU,UACnB,OAAO;EAAE,SAAS;EAAO,MAAM;EAAS,OAAO;EAAM,WAAW,KAAK,IAAI;EAAG;CAAQ;CAEtF,IAAI;CACJ,IAAI;EACF,UAAU,KAAK,UAAU,KAAK;CAChC,QAAQ;EACN,UAAU,OAAO,KAAK;CACxB;CACA,OAAO;EAAE;EAAS,MAAM;EAAY,OAAO;EAAM,WAAW,KAAK,IAAI;EAAG;CAAQ;AAClF;;;;;;;;AC5BA,SAAgB,aACd,WACA,SACA,OACM;CACN,MAAM,aAAa,QAAuB;EACxC,QAAQ,MAAM,gDAAgD,SAAS,GAAG;CAC5E;CACA,IAAI;EACF,QAAa,QAAQ,UAAU,OAAO,OAA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IAAI,MAAM,QAAQ,OAAO,GAAG,EAAE,MAAM,QAAQ,KAAK,CAAC;GAC5E,IAAI,QAAQ,UAAU,MAAM,IAAI,QAAQ,QAAQ;GAChD,IAAI,iBAAiB,KAAK,EACxB,OAAO;IAAE,GAAG,QAAQ;IAAS,YAAY,QAAQ;GAAU,EAC7D,CAAC;EACH,QAAQ;GACN,QAAQ,MAAM,uDAAuD;EACvE;CACF,EACF;AACF"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@flare-engine/errors",
|
|
3
|
-
"version": "0.4.
|
|
3
|
+
"version": "0.4.8",
|
|
4
4
|
"description": "React error boundary, structured crash payload, pluggable crash transport",
|
|
5
5
|
"keywords": ["flare-engine", "errors", "error-boundary", "crash-report", "sentry"],
|
|
6
6
|
"license": "Apache-2.0",
|