@blipit/react-native 0.4.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -6,9 +6,411 @@ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require
6
6
  });
7
7
 
8
8
  // src/index.ts
9
- import * as Sentry from "@sentry/react-native";
10
9
  import { AppState, Dimensions, Platform as Platform2 } from "react-native";
11
10
 
11
+ // src/nuggets.ts
12
+ var VERSION = "0.5.0";
13
+ var SDK_NAME = "@blipit/react-native";
14
+ var DEFAULT_ENDPOINT = "https://in.blipit.io";
15
+ var CATEGORIES = /* @__PURE__ */ new Set(["ui.click", "ui.input", "navigation", "http", "console", "query", "custom"]);
16
+ var CRUMB_LEVELS = /* @__PURE__ */ new Set(["error", "warning", "info", "debug"]);
17
+ var TAG_KEY = /[^a-zA-Z0-9_.-]/g;
18
+ var SENSITIVE = /\b((?:[a-zA-Z0-9_-]*(?:token|key|password|secret|auth|session|passwd|api)[a-zA-Z0-9_-]*)=)[^&\s"']+/gi;
19
+ var QUEUE_MAX = 30;
20
+ var truncate = (v, max) => v.length > max ? v.slice(0, max) : v;
21
+ var scrub = (text2) => text2.replace(SENSITIVE, "$1[redacted]");
22
+ function uuid32() {
23
+ let out = "";
24
+ for (let i = 0; i < 32; i++) out += Math.floor(Math.random() * 16).toString(16);
25
+ return `${out.slice(0, 12)}4${out.slice(13, 16)}${"89ab"[Math.floor(Math.random() * 4)]}${out.slice(17)}`;
26
+ }
27
+ var HERMES = /^\s*at (?:(.+?) \()?(?:address at )?(.+?):(\d+):(\d+)\)?\s*$/;
28
+ var JSC = /^\s*(?:(.*?)@)?(.+?):(\d+):(\d+)\s*$/;
29
+ function parseStack(stack) {
30
+ if (!stack) return [];
31
+ const frames = [];
32
+ for (const line of stack.split("\n")) {
33
+ const m = HERMES.exec(line) ?? (/^\s*at /.test(line) ? null : JSC.exec(line));
34
+ if (!m) continue;
35
+ const file = m[2].replace(/\?.*$/, "");
36
+ const frame = { filename: truncate(file, 1024), lineno: Number(m[3]), colno: Number(m[4]), in_app: !/node_modules|\[native code\]/.test(file) };
37
+ if (m[1]) frame.function = truncate(m[1], 512);
38
+ frames.push(frame);
39
+ }
40
+ return frames.reverse().slice(-128);
41
+ }
42
+ function cleanCrumb(c, at) {
43
+ const ts = typeof c.timestamp === "number" ? new Date(c.timestamp < 1e12 ? c.timestamp * 1e3 : c.timestamp).toISOString() : c.timestamp ?? at;
44
+ const out = { timestamp: ts, category: c.category && CATEGORIES.has(c.category) ? c.category : "custom" };
45
+ if (c.message) out.message = truncate(scrub(String(c.message)), 1024);
46
+ if (c.level && CRUMB_LEVELS.has(c.level)) out.level = c.level;
47
+ if (c.data && typeof c.data === "object") out.data = typeof c.data.url === "string" ? { ...c.data, url: scrub(c.data.url) } : c.data;
48
+ return out;
49
+ }
50
+ var Nuggets = class {
51
+ endpoint;
52
+ key;
53
+ user;
54
+ tags = {};
55
+ lastEventId;
56
+ enabled;
57
+ onError;
58
+ crumbs = [];
59
+ queue = [];
60
+ captured = /* @__PURE__ */ new WeakSet();
61
+ timer;
62
+ sending;
63
+ pausedUntil = 0;
64
+ fetcher;
65
+ now;
66
+ options;
67
+ constructor(options) {
68
+ this.options = options;
69
+ this.endpoint = (options.endpoint ?? DEFAULT_ENDPOINT).replace(/\/api\/v1\/events.*$/, "").replace(/\/+$/, "");
70
+ this.key = options.key;
71
+ this.enabled = options.enabled !== false;
72
+ this.fetcher = options.fetch ?? ((...a) => fetch(...a));
73
+ this.now = options.now ?? Date.now;
74
+ try {
75
+ const saved = JSON.parse(options.store?.load() ?? "[]");
76
+ if (Array.isArray(saved)) this.queue = saved.slice(-QUEUE_MAX);
77
+ } catch {
78
+ }
79
+ }
80
+ get pending() {
81
+ return this.queue.length;
82
+ }
83
+ url(path) {
84
+ return `${this.endpoint}${path}`;
85
+ }
86
+ setEnabled(on) {
87
+ this.enabled = on;
88
+ if (!on) {
89
+ this.queue = [];
90
+ this.crumbs = [];
91
+ this.persist();
92
+ }
93
+ }
94
+ setUser(user) {
95
+ if (!user) return void (this.user = void 0);
96
+ const u = {};
97
+ if (user.id !== void 0 && user.id !== null) u.id = truncate(String(user.id), 128);
98
+ if (user.email) u.email = truncate(user.email, 256);
99
+ if (user.username) u.username = truncate(user.username, 128);
100
+ this.user = Object.keys(u).length ? u : void 0;
101
+ }
102
+ setTag(key, value) {
103
+ const k = truncate(String(key).replace(TAG_KEY, "_"), 64);
104
+ if (k && (k in this.tags || Object.keys(this.tags).length < 32)) this.tags[k] = truncate(String(value), 256);
105
+ }
106
+ addBreadcrumb(crumb) {
107
+ if (!this.enabled) return;
108
+ this.crumbs.push(cleanCrumb(crumb, new Date(this.now()).toISOString()));
109
+ const max = Math.min(this.options.maxBreadcrumbs ?? 50, 100);
110
+ while (this.crumbs.length > max) this.crumbs.shift();
111
+ }
112
+ captureException(error, handled = true, level = "error") {
113
+ if (error && typeof error === "object") {
114
+ if (this.captured.has(error)) return void 0;
115
+ this.captured.add(error);
116
+ }
117
+ const err = error instanceof Error ? error : new Error(typeof error === "string" ? error : safeJson(error));
118
+ const exception = { type: truncate(err.name || "Error", 256), value: truncate(scrub(err.message || String(err)), 4096), handled };
119
+ const frames = parseStack(err.stack);
120
+ if (frames.length) exception.stacktrace = { frames };
121
+ return this.capture({ exception, level });
122
+ }
123
+ captureMessage(message, level = "info") {
124
+ return this.capture({ message: truncate(scrub(String(message)), 8192), level });
125
+ }
126
+ captureSecurity(kind, message, level, security) {
127
+ return this.capture({ message: truncate(message, 8192), level, ...security ? { security } : {}, tags: { "security.kind": truncate(kind, 256) } }, false);
128
+ }
129
+ capture(partial, filter = true) {
130
+ if (!this.enabled) return void 0;
131
+ if (filter && this.options.sampleRate !== void 0 && Math.random() >= this.options.sampleRate) return void 0;
132
+ const text2 = partial.exception?.value ?? partial.message ?? "";
133
+ if (filter && (this.options.ignoreErrors ?? []).some((p) => typeof p === "string" ? text2.includes(p) : p.test(text2))) return void 0;
134
+ let event = {
135
+ event_id: uuid32(),
136
+ timestamp: new Date(this.now()).toISOString(),
137
+ platform: "react-native",
138
+ level: "error",
139
+ environment: this.options.environment ?? "production",
140
+ sdk: { name: SDK_NAME, version: VERSION },
141
+ ...partial
142
+ };
143
+ if (this.options.release) event.release = truncate(this.options.release, 256);
144
+ if (this.user) event.user = { ...this.user };
145
+ const tags = { ...this.tags, ...partial.tags };
146
+ if (Object.keys(tags).length) event.tags = tags;
147
+ if (this.crumbs.length) event.breadcrumbs = [...this.crumbs];
148
+ const contexts2 = this.options.contexts?.();
149
+ if (contexts2 && Object.keys(contexts2).length) event.contexts = contexts2;
150
+ if (this.options.beforeSend) {
151
+ const out = this.options.beforeSend(event);
152
+ if (!out) return void 0;
153
+ event = out;
154
+ }
155
+ this.enqueue(event);
156
+ this.lastEventId = event.event_id;
157
+ if (event.exception) this.onError?.(!event.exception.handled);
158
+ return event.event_id;
159
+ }
160
+ enqueue(event) {
161
+ if (!this.enabled) return false;
162
+ this.queue.push(event);
163
+ while (this.queue.length > QUEUE_MAX) this.queue.shift();
164
+ this.persist();
165
+ this.schedule(1e3);
166
+ return true;
167
+ }
168
+ persist() {
169
+ try {
170
+ this.options.store?.save(JSON.stringify(this.queue));
171
+ } catch {
172
+ }
173
+ }
174
+ schedule(ms) {
175
+ if (this.timer) return;
176
+ this.timer = setTimeout(() => {
177
+ this.timer = void 0;
178
+ void this.flush();
179
+ }, Math.max(ms, this.pausedUntil - this.now()));
180
+ this.timer.unref?.();
181
+ }
182
+ async flush() {
183
+ while (this.sending) await this.sending;
184
+ this.sending = this.drain().finally(() => this.sending = void 0);
185
+ return this.sending;
186
+ }
187
+ async drain() {
188
+ while (this.queue.length && this.enabled && this.now() >= this.pausedUntil) {
189
+ const event = this.queue[0];
190
+ const verdict = await this.send(event);
191
+ if (verdict === "retry") return this.schedule(3e4);
192
+ if (verdict === "wait") return this.schedule(0);
193
+ if (this.queue[0] === event) this.queue.shift();
194
+ this.persist();
195
+ }
196
+ }
197
+ post(path, body) {
198
+ return this.fetcher(this.url(path), { method: "POST", headers: { "Content-Type": "application/json", "X-Blipit-Key": this.key }, body: JSON.stringify(body) });
199
+ }
200
+ async send(event) {
201
+ try {
202
+ const res = await this.post("/api/v1/events", event);
203
+ if (res.status === 429) {
204
+ const header = Number(res.headers?.get?.("retry-after"));
205
+ let seconds = Number.isFinite(header) && header > 0 ? header : 0;
206
+ if (!seconds) {
207
+ try {
208
+ seconds = Number(JSON.parse(await res.text()).retry_after) || 60;
209
+ } catch {
210
+ seconds = 60;
211
+ }
212
+ }
213
+ this.pausedUntil = this.now() + Math.min(seconds, 3600) * 1e3;
214
+ return "wait";
215
+ }
216
+ if (res.status >= 500) return "retry";
217
+ if (res.status >= 400 && this.options.debug) console.warn("[blipit] event rejected", res.status);
218
+ return "done";
219
+ } catch {
220
+ return "retry";
221
+ }
222
+ }
223
+ };
224
+ var RANK = { ok: 0, errored: 1, crashed: 2 };
225
+ var Session = class {
226
+ sid = "";
227
+ started = "";
228
+ status = "ok";
229
+ errors = 0;
230
+ core;
231
+ release;
232
+ environment;
233
+ constructor(core2, release, environment) {
234
+ this.core = core2;
235
+ this.release = release;
236
+ this.environment = environment;
237
+ }
238
+ start() {
239
+ if (this.sid) return;
240
+ this.sid = uuid32();
241
+ this.started = (/* @__PURE__ */ new Date()).toISOString();
242
+ this.status = "ok";
243
+ this.errors = 0;
244
+ this.send(false);
245
+ }
246
+ end() {
247
+ if (!this.sid) return;
248
+ this.send(true);
249
+ this.sid = "";
250
+ }
251
+ markError(unhandled) {
252
+ if (!this.sid) return;
253
+ this.errors += 1;
254
+ const next = unhandled ? "crashed" : "errored";
255
+ if (RANK[next] <= RANK[this.status]) return;
256
+ this.status = next;
257
+ this.send(false);
258
+ }
259
+ send(ending) {
260
+ if (!this.core.enabled) return;
261
+ const did = this.core.user?.id ?? this.core.user?.email;
262
+ const status = this.status === "ok" && ending ? "exited" : this.status;
263
+ this.core.post("/api/v1/sessions", { sid: this.sid, did, status, errors: this.errors, started: this.started, release: this.release, environment: this.environment }).catch(() => void 0);
264
+ }
265
+ };
266
+ function safeJson(v) {
267
+ try {
268
+ return JSON.stringify(v) ?? String(v);
269
+ } catch {
270
+ return String(v);
271
+ }
272
+ }
273
+
274
+ // src/instrument.ts
275
+ var done = /* @__PURE__ */ new WeakSet();
276
+ function instrument(core2, g = globalThis) {
277
+ if (done.has(g)) return;
278
+ done.add(g);
279
+ const eu = g.ErrorUtils;
280
+ if (eu?.setGlobalHandler) {
281
+ const prev = eu.getGlobalHandler?.();
282
+ eu.setGlobalHandler((error, isFatal) => {
283
+ const c = core2();
284
+ c?.captureException(error, false, isFatal ? "fatal" : "error");
285
+ if (isFatal) void c?.flush();
286
+ prev?.(error, isFatal);
287
+ });
288
+ }
289
+ const onUnhandled = (_id, reason) => void core2()?.captureException(reason, false);
290
+ if (g.HermesInternal?.enablePromiseRejectionTracker) {
291
+ g.HermesInternal.enablePromiseRejectionTracker({ allRejections: true, onUnhandled });
292
+ } else {
293
+ try {
294
+ __require("promise/setimmediate/rejection-tracking").enable({ allRejections: true, onUnhandled });
295
+ } catch {
296
+ }
297
+ }
298
+ for (const level of ["warn", "error"]) {
299
+ const original = g.console[level];
300
+ if (typeof original !== "function") continue;
301
+ g.console[level] = (...args) => {
302
+ const message = truncate(args.map((a) => typeof a === "string" ? a : a instanceof Error ? a.message : json(a)).join(" "), 1024);
303
+ if (!message.startsWith("[blipit]")) core2()?.addBreadcrumb({ category: "console", level: level === "warn" ? "warning" : "error", message });
304
+ original.apply(g.console, args);
305
+ };
306
+ }
307
+ const proto = g.XMLHttpRequest?.prototype;
308
+ if (proto?.open && proto.send) {
309
+ const open = proto.open;
310
+ const send = proto.send;
311
+ proto.open = function(method, url, ...rest) {
312
+ this._blipit = [String(method).toUpperCase(), String(url)];
313
+ return open.call(this, method, url, ...rest);
314
+ };
315
+ proto.send = function(...args) {
316
+ const meta = this._blipit;
317
+ const c = core2();
318
+ if (c && meta && !meta[1].startsWith(c.endpoint)) {
319
+ const start = Date.now();
320
+ this.addEventListener?.("loadend", () => {
321
+ const status = this.status;
322
+ const url = meta[1].replace(/[?#].*$/, "");
323
+ c.addBreadcrumb({
324
+ category: "http",
325
+ level: !status || status >= 400 ? "error" : "info",
326
+ message: `${meta[0]} ${url} -> ${status || "network error"}`,
327
+ data: { url, method: meta[0], status_code: status || void 0, duration_ms: Date.now() - start }
328
+ });
329
+ });
330
+ }
331
+ return send.apply(this, args);
332
+ };
333
+ }
334
+ }
335
+ function trackNavigation(core2, ref) {
336
+ let last;
337
+ const seen = () => {
338
+ const name = ref.getCurrentRoute()?.name;
339
+ if (!name || name === last) return;
340
+ core2()?.addBreadcrumb({ category: "navigation", message: `Navigated to ${name}`, data: { from: last, to: name } });
341
+ last = name;
342
+ };
343
+ seen();
344
+ return ref.addListener("state", seen);
345
+ }
346
+ function json(v) {
347
+ try {
348
+ return JSON.stringify(v) ?? String(v);
349
+ } catch {
350
+ return String(v);
351
+ }
352
+ }
353
+
354
+ // src/native.ts
355
+ import { NativeModules } from "react-native";
356
+ var bridge = () => NativeModules.BlipitNuggets;
357
+ function nativeInfo() {
358
+ const b = bridge();
359
+ try {
360
+ return b?.getConstants?.() ?? b ?? {};
361
+ } catch {
362
+ return {};
363
+ }
364
+ }
365
+ function nativeStore() {
366
+ const b = bridge();
367
+ if (!b?.save || !b.load) return void 0;
368
+ return {
369
+ load: () => {
370
+ try {
371
+ return b.load();
372
+ } catch {
373
+ return null;
374
+ }
375
+ },
376
+ save: (data) => void b.save(data)
377
+ };
378
+ }
379
+ function defaultRelease(info) {
380
+ if (!info.appId || !info.appVersion) return void 0;
381
+ return `${info.appId}@${info.appVersion}${info.appBuild ? `+${info.appBuild}` : ""}`;
382
+ }
383
+
384
+ // src/boundary.ts
385
+ import { Component, createElement } from "react";
386
+ var report = () => void 0;
387
+ function setBoundaryReporter(fn) {
388
+ report = fn;
389
+ }
390
+ var ErrorBoundary = class extends Component {
391
+ state = { error: null };
392
+ static getDerivedStateFromError(error) {
393
+ return { error };
394
+ }
395
+ componentDidCatch(error) {
396
+ const id = report(error);
397
+ this.props.onError?.(error, id);
398
+ }
399
+ resetError = () => this.setState({ error: null });
400
+ render() {
401
+ if (this.state.error === null) return this.props.children ?? null;
402
+ const { fallback } = this.props;
403
+ if (typeof fallback === "function") return fallback({ error: this.state.error, resetError: this.resetError });
404
+ if (fallback === void 0) throw this.state.error;
405
+ return fallback;
406
+ }
407
+ };
408
+ function wrap(Root, options = {}) {
409
+ const Wrapped = (props) => createElement(ErrorBoundary, options, createElement(Root, props));
410
+ Wrapped.displayName = `Blipit(${Root.displayName ?? Root.name ?? "App"})`;
411
+ return Wrapped;
412
+ }
413
+
12
414
  // src/report-strings.ts
13
415
  var REPORT_STRINGS = {
14
416
  "en": {
@@ -428,8 +830,8 @@ var ReportClient = class {
428
830
  this.key = key;
429
831
  this.fetcher = fetcher;
430
832
  }
431
- async call(path, init3) {
432
- const res = await this.fetcher(`${this.endpoint}${path}`, { ...init3, headers: { "X-Blipit-Key": this.key, ...init3.headers } });
833
+ async call(path, init2) {
834
+ const res = await this.fetcher(`${this.endpoint}${path}`, { ...init2, headers: { "X-Blipit-Key": this.key, ...init2.headers } });
433
835
  const text2 = await res.text();
434
836
  if (!res.ok) throw new Error(`Blipit returned ${res.status}`);
435
837
  return text2;
@@ -442,9 +844,9 @@ var ReportClient = class {
442
844
  return res.ok || res.status >= 400 && res.status < 500 && res.status !== 408 && res.status !== 429;
443
845
  }
444
846
  async send(body) {
445
- const json = JSON.parse(await this.call("/api/v1/feedback", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) }));
446
- if (typeof json.upload_token !== "string") throw new Error("Blipit returned no upload token");
447
- return { id: String(json.id), token: json.upload_token, ref: typeof json.ref === "string" ? json.ref : null };
847
+ const json2 = JSON.parse(await this.call("/api/v1/feedback", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) }));
848
+ if (typeof json2.upload_token !== "string") throw new Error("Blipit returned no upload token");
849
+ return { id: String(json2.id), token: json2.upload_token, ref: typeof json2.ref === "string" ? json2.ref : null };
448
850
  }
449
851
  async uploadScreenshot(receipt, data, type) {
450
852
  await this.call(`/api/v1/feedback/${encodeURIComponent(receipt.id)}/screenshot?position=0`, { method: "POST", headers: { "Content-Type": type, "X-Blipit-Upload": receipt.token }, body: data });
@@ -1011,8 +1413,8 @@ function Details({ t, lang, shot, flat, shapes, notice, onBack, onDone }) {
1011
1413
  uploaded = false;
1012
1414
  }
1013
1415
  }
1014
- const done = receipt.ref ? t("sentRef").replace("{ref}", receipt.ref) : t("sentTitle");
1015
- setStatus({ text: uploaded ? done : `${done} \xB7 ${t("noShot")}`, error: !uploaded });
1416
+ const done2 = receipt.ref ? t("sentRef").replace("{ref}", receipt.ref) : t("sentTitle");
1417
+ setStatus({ text: uploaded ? done2 : `${done2} \xB7 ${t("noShot")}`, error: !uploaded });
1016
1418
  setTimeout(onDone, 1600);
1017
1419
  } catch {
1018
1420
  setStatus({ text: t("error"), error: true });
@@ -1068,29 +1470,13 @@ var s = StyleSheet.create({
1068
1470
  });
1069
1471
 
1070
1472
  // src/index.ts
1071
- import { captureException, captureMessage as captureMessage2, setUser, setTag, addBreadcrumb, flush, wrap } from "@sentry/react-native";
1072
- var DEFAULT_ENDPOINT = "https://in.blipit.io";
1073
- var VERSION = "0.4.0";
1074
- var PACKAGE = { name: "npm:@blipit/react-native", version: VERSION };
1075
- function withIdentity(user) {
1076
- return (event, hint) => {
1077
- try {
1078
- const sdk = event.sdk ??= {};
1079
- const packages = sdk.packages ?? [];
1080
- if (!packages.some((p) => p?.name === PACKAGE.name)) sdk.packages = [...packages, { ...PACKAGE }];
1081
- } catch {
1082
- }
1083
- return user ? user(event, hint) : event;
1084
- };
1085
- }
1086
- function dsn(key, project, endpoint = DEFAULT_ENDPOINT) {
1087
- const host = endpoint.split("://").pop().replace(/\/+$/, "");
1088
- const scheme = endpoint.startsWith("http://") ? "http" : "https";
1089
- return `${scheme}://${key}@${host}/${project}`;
1090
- }
1473
+ var SECURITY_KINDS = ["login_failed", "login_succeeded", "login_blocked", "password_reset_requested", "privilege_granted"];
1091
1474
  var MISSING_KEY = "[blipit] Blipit.init got no key, so Blipit is off and nothing is sent. Pass the project's public key (app.blipit.io, Keys); with Expo, check that EXPO_PUBLIC_BLIPIT_KEY is set at build time.";
1092
1475
  var MISSING_PROJECT = "[blipit] Blipit.init got no project id, so Blipit is off and nothing is sent. Pass project with the id from the project's Keys page at app.blipit.io.";
1093
- function init2(options) {
1476
+ var core;
1477
+ var session;
1478
+ var appState;
1479
+ function init(options) {
1094
1480
  const { key, publicKey, project, endpoint, waitForReady, ...rest } = options ?? {};
1095
1481
  const k = (key ?? publicKey ?? "").trim();
1096
1482
  if (!k) {
@@ -1101,17 +1487,44 @@ function init2(options) {
1101
1487
  console.warn(MISSING_PROJECT);
1102
1488
  return false;
1103
1489
  }
1104
- Sentry.init({
1105
- dsn: dsn(k, project, endpoint),
1106
- sendDefaultPii: false,
1107
- tracesSampleRate: 0,
1108
- ...rest,
1109
- beforeSend: withIdentity(rest.beforeSend)
1490
+ const info = nativeInfo();
1491
+ const release = rest.release ?? defaultRelease(info);
1492
+ const base = endpoint ?? DEFAULT_ENDPOINT;
1493
+ session?.end();
1494
+ appState?.remove();
1495
+ core = new Nuggets({ ...rest, key: k, endpoint: base, release, store: nativeStore(), contexts: () => contexts(info.model, info.osVersion) });
1496
+ const c = core;
1497
+ setBoundaryReporter((error) => c.captureException(error, false));
1498
+ instrument(() => core);
1499
+ const native = rest.enableNative !== false ? bridge() : void 0;
1500
+ try {
1501
+ native?.start(k, String(project), rest.environment ?? null, release ?? null, c.endpoint);
1502
+ } catch {
1503
+ }
1504
+ session = release && rest.autoSessionTracking !== false ? new Session(c, release, rest.environment ?? "production") : void 0;
1505
+ c.onError = (unhandled) => session?.markError(unhandled);
1506
+ if (c.enabled) session?.start();
1507
+ appState = AppState?.addEventListener?.("change", (state) => {
1508
+ if (state === "active") {
1509
+ if (c.enabled) session?.start();
1510
+ void c.flush();
1511
+ } else if (state === "background") {
1512
+ session?.end();
1513
+ void c.flush();
1514
+ }
1110
1515
  });
1111
- const client = new ReportClient(endpoint ?? DEFAULT_ENDPOINT, k);
1112
- configureReporter(client, () => deviceContext(rest.release));
1516
+ void c.flush();
1517
+ const reports = new ReportClient(base, k);
1518
+ configureReporter(reports, () => deviceContext(release));
1519
+ reportClient = reports;
1113
1520
  if (!stuck) {
1114
- stuck = createStuck(client, { release: rest.release, environment: rest.environment, os: Platform2.OS, osVersion: String(Platform2.Version), version: VERSION });
1521
+ stuck = createStuck(
1522
+ {
1523
+ settings: () => reportClient ? reportClient.settings() : Promise.resolve(null),
1524
+ event: async (body) => (core?.enqueue(body), true)
1525
+ },
1526
+ { release, environment: rest.environment, os: Platform2.OS, osVersion: info.osVersion ?? String(Platform2.Version), version: VERSION }
1527
+ );
1115
1528
  try {
1116
1529
  stuck.setForeground(AppState.currentState !== "background");
1117
1530
  AppState.addEventListener("change", (state) => stuck?.setForeground(state !== "background"));
@@ -1120,9 +1533,11 @@ function init2(options) {
1120
1533
  }
1121
1534
  if (waitForReady) stuck.start(STARTUP);
1122
1535
  }
1536
+ if (rest.debug) console.log(`[blipit] ${SDK_NAME}@${VERSION} initialized`);
1123
1537
  return true;
1124
1538
  }
1125
1539
  var stuck = null;
1540
+ var reportClient;
1126
1541
  function reportReady() {
1127
1542
  stuck?.end(STARTUP);
1128
1543
  }
@@ -1139,6 +1554,16 @@ function endFlow(name) {
1139
1554
  const flow = cleanName(name, 64);
1140
1555
  if (flow) stuck?.end(flow);
1141
1556
  }
1557
+ function contexts(model, osVersion) {
1558
+ const { width, height } = Dimensions.get("window");
1559
+ const engine = globalThis.HermesInternal ? "hermes" : "jsc";
1560
+ const rn = Platform2.constants?.reactNativeVersion;
1561
+ return {
1562
+ os: { name: Platform2.OS, version: osVersion ?? String(Platform2.Version) },
1563
+ device: { ...model ? { model } : {}, screen: `${Math.round(width)}x${Math.round(height)}` },
1564
+ runtime: { name: engine, ...rn ? { version: `react-native ${rn.major}.${rn.minor}.${rn.patch}` } : {} }
1565
+ };
1566
+ }
1142
1567
  function deviceContext(release) {
1143
1568
  const { width, height, scale } = Dimensions.get("window");
1144
1569
  let language = "";
@@ -1151,11 +1576,17 @@ function deviceContext(release) {
1151
1576
  }
1152
1577
  return {
1153
1578
  platform: "react-native",
1154
- sdk: { name: PACKAGE.name, version: VERSION },
1579
+ sdk: { name: `npm:${SDK_NAME}`, version: VERSION },
1155
1580
  ...release ? { app: { release } } : {},
1156
1581
  device: { os: Platform2.OS, os_version: String(Platform2.Version), screen: `${Math.round(width)}x${Math.round(height)}`, dpr: scale, language, timezone, touch: true }
1157
1582
  };
1158
1583
  }
1584
+ function captureException(error) {
1585
+ return core?.captureException(error, true);
1586
+ }
1587
+ function captureMessage(message, level = "info") {
1588
+ return core?.captureMessage(message, level);
1589
+ }
1159
1590
  function captureSecurity(kind, actor, details = {}) {
1160
1591
  const context = { kind, actor };
1161
1592
  const extra = { outcome: details.outcome, actor_id: details.actorId, ip: details.ip, user_agent: details.userAgent, target: details.target };
@@ -1163,30 +1594,80 @@ function captureSecurity(kind, actor, details = {}) {
1163
1594
  if (v !== void 0 && v !== null) context[k] = v;
1164
1595
  }
1165
1596
  const level = kind === "login_failed" || kind === "login_blocked" ? "warning" : "info";
1166
- Sentry.withScope((scope) => {
1167
- scope.setContext("security", context);
1168
- scope.setTag("security.kind", kind);
1169
- Sentry.captureMessage(`${kind} for ${actor}`, level);
1170
- });
1597
+ return core?.captureSecurity(kind, `${kind} for ${actor}`, level, SECURITY_KINDS.includes(kind) && actor ? context : void 0);
1598
+ }
1599
+ function setUser(user) {
1600
+ core?.setUser(user);
1601
+ const u = core?.user;
1602
+ try {
1603
+ bridge()?.setUser(u?.id ?? null, u?.email ?? null, u?.username ?? null);
1604
+ } catch {
1605
+ }
1606
+ }
1607
+ function setTag(key, value) {
1608
+ core?.setTag(key, value);
1609
+ try {
1610
+ bridge()?.setTag(key, String(value));
1611
+ } catch {
1612
+ }
1613
+ }
1614
+ function addBreadcrumb(crumb) {
1615
+ core?.addBreadcrumb(crumb);
1616
+ }
1617
+ async function flush(timeout = 2e3) {
1618
+ if (!core) return true;
1619
+ const c = core;
1620
+ let timer;
1621
+ const late = new Promise((r) => timer = setTimeout(() => r(false), timeout));
1622
+ const ok = await Promise.race([c.flush().then(() => c.pending === 0), late]);
1623
+ clearTimeout(timer);
1624
+ return ok;
1625
+ }
1626
+ function setEnabled(on) {
1627
+ if (!core) return;
1628
+ core.setEnabled(on);
1629
+ if (on) session?.start();
1630
+ else session?.end();
1631
+ }
1632
+ var isEnabled = () => core?.enabled ?? false;
1633
+ var lastEventId = () => core?.lastEventId;
1634
+ function setReplayConsent(granted) {
1635
+ try {
1636
+ bridge()?.setReplayConsent(granted);
1637
+ } catch {
1638
+ }
1639
+ }
1640
+ function hasReplayConsent() {
1641
+ try {
1642
+ return bridge()?.hasReplayConsent() === true;
1643
+ } catch {
1644
+ return false;
1645
+ }
1171
1646
  }
1647
+ var trackNavigation2 = (ref) => trackNavigation(() => core, ref);
1172
1648
  export {
1173
1649
  BlipitReporter,
1174
1650
  DEFAULT_ENDPOINT,
1651
+ ErrorBoundary,
1175
1652
  VERSION,
1176
1653
  addBreadcrumb,
1177
1654
  captureException,
1178
- captureMessage2 as captureMessage,
1655
+ captureMessage,
1179
1656
  captureSecurity,
1180
- dsn,
1181
1657
  endFlow,
1182
1658
  flowStep,
1183
1659
  flush,
1184
- init2 as init,
1660
+ hasReplayConsent,
1661
+ init,
1662
+ isEnabled,
1663
+ lastEventId,
1185
1664
  reportReady,
1665
+ setEnabled,
1666
+ setReplayConsent,
1186
1667
  setTag,
1187
1668
  setUser,
1188
1669
  showReport,
1189
1670
  startFlow,
1190
- withIdentity,
1671
+ trackNavigation2 as trackNavigation,
1191
1672
  wrap
1192
1673
  };
@@ -0,0 +1,13 @@
1
+ #import <React/RCTBridgeModule.h>
2
+
3
+ @interface RCT_EXTERN_MODULE(BlipitNuggets, NSObject)
4
+
5
+ RCT_EXTERN_METHOD(start:(NSString *)key project:(NSString *)project environment:(NSString *)environment release:(NSString *)release endpoint:(NSString *)endpoint)
6
+ RCT_EXTERN_METHOD(setUser:(NSString *)id email:(NSString *)email username:(NSString *)username)
7
+ RCT_EXTERN_METHOD(setTag:(NSString *)key value:(NSString *)value)
8
+ RCT_EXTERN_METHOD(setReplayConsent:(BOOL)granted)
9
+ RCT_EXTERN__BLOCKING_SYNCHRONOUS_METHOD(hasReplayConsent)
10
+ RCT_EXTERN__BLOCKING_SYNCHRONOUS_METHOD(save:(NSString *)data)
11
+ RCT_EXTERN__BLOCKING_SYNCHRONOUS_METHOD(load)
12
+
13
+ @end