@supermetry/react-native 0.0.0-stage → 0.2.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.cjs ADDED
@@ -0,0 +1,582 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __getOwnPropNames = Object.getOwnPropertyNames;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
5
+ function __accessProp(key) {
6
+ return this[key];
7
+ }
8
+ var __toCommonJS = (from) => {
9
+ var entry = (__moduleCache ??= new WeakMap).get(from), desc;
10
+ if (entry)
11
+ return entry;
12
+ entry = __defProp({}, "__esModule", { value: true });
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (var key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(entry, key))
16
+ __defProp(entry, key, {
17
+ get: __accessProp.bind(from, key),
18
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
19
+ });
20
+ }
21
+ __moduleCache.set(from, entry);
22
+ return entry;
23
+ };
24
+ var __moduleCache;
25
+ var __returnValue = (v) => v;
26
+ function __exportSetter(name, newValue) {
27
+ this[name] = __returnValue.bind(null, newValue);
28
+ }
29
+ var __export = (target, all) => {
30
+ for (var name in all)
31
+ __defProp(target, name, {
32
+ get: all[name],
33
+ enumerable: true,
34
+ configurable: true,
35
+ set: __exportSetter.bind(all, name)
36
+ });
37
+ };
38
+
39
+ // src/index.ts
40
+ var exports_src = {};
41
+ __export(exports_src, {
42
+ EVENTS_PATH: () => EVENTS_PATH,
43
+ SupermetryHttpError: () => SupermetryHttpError,
44
+ SupermetryProvider: () => SupermetryProvider,
45
+ VERSION: () => VERSION,
46
+ buildUserAgent: () => buildUserAgent,
47
+ createSupermetry: () => createSupermetry,
48
+ screenPath: () => screenPath,
49
+ trackNavigation: () => trackNavigation,
50
+ useSupermetry: () => useSupermetry
51
+ });
52
+ module.exports = __toCommonJS(exports_src);
53
+
54
+ // src/client.ts
55
+ var import_react_native2 = require("react-native");
56
+
57
+ // src/platform.ts
58
+ var import_react_native = require("react-native");
59
+ var VERSION = "0.2.0";
60
+ var SUFFIX = `Supermetry-ReactNative/${VERSION}`;
61
+ function clean(value) {
62
+ return typeof value === "string" ? value.replace(/[;()\r\n]/g, " ").replace(/\s+/g, " ").trim() : "";
63
+ }
64
+ function buildUserAgent(platform = import_react_native.Platform) {
65
+ const constants = platform.constants ?? {};
66
+ switch (platform.OS) {
67
+ case "ios": {
68
+ const version = (clean(constants.osVersion) || clean(String(platform.Version ?? "")) || "17.0").replace(/\./g, "_");
69
+ return platform.isPad ? `Mozilla/5.0 (iPad; CPU OS ${version} like Mac OS X) ${SUFFIX}` : `Mozilla/5.0 (iPhone; CPU iPhone OS ${version} like Mac OS X) ${SUFFIX}`;
70
+ }
71
+ case "android": {
72
+ const release = clean(constants.Release) || clean(String(platform.Version ?? ""));
73
+ const model = clean(constants.Model);
74
+ return `Mozilla/5.0 (Linux; Android ${release}${model ? `; ${model}` : ""}) ${SUFFIX}`;
75
+ }
76
+ case "macos":
77
+ return `Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) ${SUFFIX}`;
78
+ case "windows":
79
+ return `Mozilla/5.0 (Windows NT 10.0; Win64; x64) ${SUFFIX}`;
80
+ default:
81
+ return `Mozilla/5.0 (${clean(platform.OS) || "Unknown"}) ${SUFFIX}`;
82
+ }
83
+ }
84
+ function screenWidth() {
85
+ try {
86
+ const width = Math.round(import_react_native.Dimensions.get("window").width);
87
+ return width > 0 && width <= 32767 ? width : undefined;
88
+ } catch {
89
+ return;
90
+ }
91
+ }
92
+ function screenPath(name) {
93
+ return String(name).split("/").map((segment) => segment.normalize("NFKD").replace(/[̀-ͯ]/g, "").replace(/([a-z0-9])([A-Z])/g, "$1-$2").toLowerCase().replace(/[^a-z0-9._~-]+/g, "-").replace(/^-+|-+$/g, "")).filter(Boolean).join("/");
94
+ }
95
+
96
+ // src/validate.ts
97
+ var MAX_PROPS = 30;
98
+ var MAX_KEY_BYTES = 300;
99
+ var MAX_VALUE_BYTES = 2000;
100
+ var MAX_URL_BYTES = 2000;
101
+ var MAX_NAME_BYTES = 300;
102
+ var MAX_BODY_BYTES = 8 * 1024;
103
+ var MAX_PROFILE_ID_CHARS = 128;
104
+ var MAX_TRAITS = 20;
105
+ var MAX_TRAIT_KEY_CHARS = 64;
106
+ var MAX_TRAIT_VALUE_CHARS = 256;
107
+ function byteLength(value) {
108
+ let bytes = 0;
109
+ for (const ch of value) {
110
+ const code = ch.codePointAt(0);
111
+ bytes += code < 128 ? 1 : code < 2048 ? 2 : code < 65536 ? 3 : 4;
112
+ }
113
+ return bytes;
114
+ }
115
+ function charLength(value) {
116
+ let count = 0;
117
+ for (const _ of value)
118
+ count++;
119
+ return count;
120
+ }
121
+ function truncateBytes(value, max) {
122
+ if (byteLength(value) <= max)
123
+ return value;
124
+ let out = "";
125
+ let size = 0;
126
+ for (const ch of value) {
127
+ const n = byteLength(ch);
128
+ if (size + n > max)
129
+ break;
130
+ out += ch;
131
+ size += n;
132
+ }
133
+ return out;
134
+ }
135
+ function validName(name) {
136
+ return typeof name === "string" && name.length > 0 && byteLength(name) <= MAX_NAME_BYTES;
137
+ }
138
+ function validEventUrl(value) {
139
+ if (typeof value !== "string" || value === "" || byteLength(value) > MAX_URL_BYTES)
140
+ return false;
141
+ try {
142
+ const parsed = new URL(value);
143
+ return (parsed.protocol === "http:" || parsed.protocol === "https:") && parsed.hostname !== "" && parsed.username === "" && parsed.password === "";
144
+ } catch {
145
+ return false;
146
+ }
147
+ }
148
+ function validProfileId(value) {
149
+ return typeof value === "string" && value !== "" && charLength(value) <= MAX_PROFILE_ID_CHARS;
150
+ }
151
+ function sanitizeProps(props) {
152
+ if (!props || typeof props !== "object")
153
+ return;
154
+ const out = {};
155
+ let count = 0;
156
+ for (const [key, raw] of Object.entries(props)) {
157
+ if (count >= MAX_PROPS)
158
+ break;
159
+ if (key === "" || byteLength(key) > MAX_KEY_BYTES)
160
+ continue;
161
+ let value;
162
+ if (typeof raw === "string")
163
+ value = truncateBytes(raw, MAX_VALUE_BYTES);
164
+ else if (typeof raw === "boolean")
165
+ value = raw;
166
+ else if (typeof raw === "number" && Number.isFinite(raw))
167
+ value = raw;
168
+ else
169
+ continue;
170
+ out[key] = value;
171
+ count++;
172
+ }
173
+ return count > 0 ? out : undefined;
174
+ }
175
+ function sanitizeTraits(traits) {
176
+ if (!traits || typeof traits !== "object")
177
+ return;
178
+ const out = {};
179
+ let count = 0;
180
+ for (const [key, raw] of Object.entries(traits)) {
181
+ if (count >= MAX_TRAITS)
182
+ break;
183
+ if (key === "" || charLength(key) > MAX_TRAIT_KEY_CHARS)
184
+ continue;
185
+ let value;
186
+ if (typeof raw === "string")
187
+ value = raw;
188
+ else if (typeof raw === "boolean" || typeof raw === "number" && Number.isFinite(raw))
189
+ value = String(raw);
190
+ else
191
+ continue;
192
+ if (charLength(value) > MAX_TRAIT_VALUE_CHARS)
193
+ continue;
194
+ out[key] = value;
195
+ count++;
196
+ }
197
+ return count > 0 ? out : undefined;
198
+ }
199
+ var amountPattern = /^\d+(\.\d{1,6})?$/;
200
+ function sanitizeRevenue(revenue) {
201
+ if (!revenue || typeof revenue !== "object")
202
+ return;
203
+ let { amount } = revenue;
204
+ const { currency } = revenue;
205
+ if (typeof amount === "number") {
206
+ amount = Math.round(amount * 1e6) / 1e6;
207
+ if (!Number.isFinite(amount) || amount <= 0 || amount > 1000000000000)
208
+ return;
209
+ } else if (typeof amount !== "string" || !amountPattern.test(amount) || Number(amount) <= 0) {
210
+ return;
211
+ }
212
+ if (currency !== undefined && currency !== "" && !/^[A-Z]{3}$/.test(currency))
213
+ return;
214
+ return currency ? { amount, currency } : { amount };
215
+ }
216
+
217
+ // src/client.ts
218
+ var EVENTS_PATH = "/api/public/v1/events";
219
+ var DEFAULT_HOST = "https://app.supermetry.com";
220
+ var MAX_AGE_MS = 24 * 60 * 60 * 1000 - 60000;
221
+ function newEventId() {
222
+ const bytes = new Uint8Array(16);
223
+ const cryptoApi = globalThis.crypto;
224
+ if (cryptoApi?.getRandomValues)
225
+ cryptoApi.getRandomValues(bytes);
226
+ else
227
+ for (let i = 0;i < bytes.length; i++)
228
+ bytes[i] = Math.floor(Math.random() * 256);
229
+ bytes[6] = bytes[6] & 15 | 64;
230
+ bytes[8] = bytes[8] & 63 | 128;
231
+ let out = "";
232
+ for (const b of bytes)
233
+ out += b.toString(16).padStart(2, "0");
234
+ return out;
235
+ }
236
+ function toError(error) {
237
+ return error instanceof Error ? error : new Error(String(error));
238
+ }
239
+
240
+ class SupermetryHttpError extends Error {
241
+ status;
242
+ constructor(status) {
243
+ super(`Supermetry responded ${status}`);
244
+ this.name = "SupermetryHttpError";
245
+ this.status = status;
246
+ }
247
+ }
248
+
249
+ class Client {
250
+ ready;
251
+ options;
252
+ endpoint;
253
+ appUrl;
254
+ userAgent;
255
+ keys;
256
+ queue = [];
257
+ currentProfile;
258
+ optedOut = false;
259
+ loaded = false;
260
+ profileTouched = false;
261
+ optOutTouched = false;
262
+ currentUrl;
263
+ flushing;
264
+ retryTimer;
265
+ flushTimer;
266
+ appStateSubscription;
267
+ destroyed = false;
268
+ constructor(options) {
269
+ if (!options?.site)
270
+ throw new TypeError("@supermetry/react-native: `site` is required");
271
+ if (!validEventUrl(options.appUrl)) {
272
+ throw new TypeError("@supermetry/react-native: `appUrl` must be an absolute http(s) URL");
273
+ }
274
+ this.options = options;
275
+ this.endpoint = options.endpoint ?? (options.host || DEFAULT_HOST).replace(/\/+$/, "") + EVENTS_PATH;
276
+ this.appUrl = options.appUrl.replace(/\/+$/, "");
277
+ this.userAgent = options.userAgent ?? buildUserAgent();
278
+ const prefix = options.storagePrefix ?? "supermetry:";
279
+ this.keys = { profile: `${prefix}profile_id`, optOut: `${prefix}opt_out`, queue: `${prefix}queue` };
280
+ this.ready = this.load();
281
+ try {
282
+ this.appStateSubscription = import_react_native2.AppState.addEventListener("change", (state) => this.onAppState(state));
283
+ } catch (error) {
284
+ this.report(error);
285
+ }
286
+ }
287
+ get profileId() {
288
+ return this.currentProfile;
289
+ }
290
+ isOptedOut() {
291
+ return this.optedOut;
292
+ }
293
+ screen(name, props) {
294
+ const path = screenPath(name);
295
+ const url = `${this.appUrl}/${path}`;
296
+ this.currentUrl = url;
297
+ this.capture("pageview", url, { props });
298
+ }
299
+ pageview(urlOrPath, props) {
300
+ const url = this.resolveUrl(urlOrPath);
301
+ if (url)
302
+ this.currentUrl = url;
303
+ this.capture("pageview", url, { props });
304
+ }
305
+ track(name, props, options = {}) {
306
+ if (name === "identify") {
307
+ this.report(new Error('use identify() instead of track("identify")'));
308
+ return;
309
+ }
310
+ const url = options.url !== undefined ? this.resolveUrl(options.url) : this.currentUrl ?? `${this.appUrl}/`;
311
+ this.capture(name, url, { props, revenue: options.revenue });
312
+ }
313
+ identify(profileId, traits) {
314
+ if (profileId === null || profileId === undefined) {
315
+ this.reset();
316
+ return;
317
+ }
318
+ if (!validProfileId(profileId)) {
319
+ this.report(new Error("identify: profileId must be 1-128 characters"));
320
+ return;
321
+ }
322
+ this.profileTouched = true;
323
+ this.currentProfile = profileId;
324
+ this.persist(this.keys.profile, profileId);
325
+ this.capture("identify", this.currentUrl ?? `${this.appUrl}/`, { traits: sanitizeTraits(traits) });
326
+ }
327
+ reset() {
328
+ this.profileTouched = true;
329
+ this.currentProfile = undefined;
330
+ this.persist(this.keys.profile, undefined);
331
+ }
332
+ async optOut() {
333
+ this.optOutTouched = true;
334
+ this.optedOut = true;
335
+ this.queue = [];
336
+ await this.write(this.keys.optOut, "1");
337
+ await this.write(this.keys.queue, undefined);
338
+ }
339
+ async optIn() {
340
+ this.optOutTouched = true;
341
+ this.optedOut = false;
342
+ await this.write(this.keys.optOut, undefined);
343
+ }
344
+ flush() {
345
+ if (this.retryTimer) {
346
+ clearTimeout(this.retryTimer);
347
+ this.retryTimer = undefined;
348
+ }
349
+ if (this.flushTimer) {
350
+ clearTimeout(this.flushTimer);
351
+ this.flushTimer = undefined;
352
+ }
353
+ if (!this.flushing) {
354
+ this.flushing = this.drain().finally(() => {
355
+ this.flushing = undefined;
356
+ });
357
+ }
358
+ return this.flushing;
359
+ }
360
+ destroy() {
361
+ this.destroyed = true;
362
+ this.appStateSubscription?.remove();
363
+ this.appStateSubscription = undefined;
364
+ if (this.retryTimer)
365
+ clearTimeout(this.retryTimer);
366
+ if (this.flushTimer)
367
+ clearTimeout(this.flushTimer);
368
+ this.retryTimer = this.flushTimer = undefined;
369
+ }
370
+ resolveUrl(urlOrPath) {
371
+ if (urlOrPath && validEventUrl(urlOrPath))
372
+ return urlOrPath;
373
+ const path = (urlOrPath ?? "").replace(/^\/+/, "");
374
+ return `${this.appUrl}/${path}`;
375
+ }
376
+ capture(name, url, extra) {
377
+ try {
378
+ if (this.options.disabled || this.optedOut || this.destroyed)
379
+ return;
380
+ if (!validName(name))
381
+ throw new Error("event name must be 1-300 bytes");
382
+ if (!validEventUrl(url))
383
+ throw new Error(`invalid event url: ${url}`);
384
+ const event = { v: 1, id: newEventId(), ts: Date.now(), site: this.options.site, name, url };
385
+ const width = screenWidth();
386
+ if (width !== undefined)
387
+ event.screen_width = width;
388
+ const props = sanitizeProps(extra.props);
389
+ if (props)
390
+ event.props = props;
391
+ if (name !== "pageview") {
392
+ const revenue = sanitizeRevenue(extra.revenue);
393
+ if (revenue)
394
+ event.revenue = revenue;
395
+ }
396
+ if (this.currentProfile)
397
+ event.profile_id = this.currentProfile;
398
+ if (name === "identify" && extra.traits)
399
+ event.traits = extra.traits;
400
+ if (byteLength(JSON.stringify(event)) > MAX_BODY_BYTES)
401
+ throw new Error("event body exceeds 8 KB");
402
+ this.queue.push({ event, attempts: 0, early: !this.loaded && !this.profileTouched });
403
+ const max = this.options.maxQueueSize ?? 500;
404
+ if (this.queue.length > max)
405
+ this.queue.splice(0, this.queue.length - max);
406
+ this.scheduleFlush();
407
+ } catch (error) {
408
+ this.report(error);
409
+ }
410
+ }
411
+ scheduleFlush() {
412
+ if (this.flushTimer || this.retryTimer || this.destroyed)
413
+ return;
414
+ this.flushTimer = setTimeout(() => {
415
+ this.flushTimer = undefined;
416
+ this.flush();
417
+ }, 0);
418
+ }
419
+ async load() {
420
+ const storage = this.options.storage;
421
+ try {
422
+ if (!storage)
423
+ return;
424
+ const [profile, optOut, queued] = await Promise.all([
425
+ storage.getItem(this.keys.profile),
426
+ storage.getItem(this.keys.optOut),
427
+ storage.getItem(this.keys.queue)
428
+ ]);
429
+ if (!this.profileTouched && profile && validProfileId(profile))
430
+ this.currentProfile = profile;
431
+ if (!this.optOutTouched)
432
+ this.optedOut = optOut === "1";
433
+ if (queued && !this.optedOut) {
434
+ try {
435
+ const restored = JSON.parse(queued).filter((event) => event && typeof event.id === "string" && typeof event.ts === "number").map((event) => ({ event, attempts: 0 }));
436
+ this.queue = [...restored, ...this.queue];
437
+ } catch {}
438
+ await storage.removeItem(this.keys.queue);
439
+ }
440
+ } catch (error) {
441
+ this.report(error);
442
+ } finally {
443
+ this.loaded = true;
444
+ if (this.optedOut)
445
+ this.queue = [];
446
+ for (const item of this.queue) {
447
+ if (item.early && this.currentProfile && !item.event.profile_id)
448
+ item.event.profile_id = this.currentProfile;
449
+ item.early = false;
450
+ }
451
+ }
452
+ }
453
+ async drain() {
454
+ await this.ready;
455
+ while (this.queue.length > 0 && !this.optedOut) {
456
+ const item = this.queue[0];
457
+ if (Date.now() - item.event.ts > MAX_AGE_MS) {
458
+ this.queue.shift();
459
+ continue;
460
+ }
461
+ const outcome = await this.send(item.event);
462
+ if (this.queue[0] !== item)
463
+ continue;
464
+ if (outcome.done) {
465
+ this.queue.shift();
466
+ continue;
467
+ }
468
+ item.attempts++;
469
+ if (item.attempts >= (this.options.maxAttempts ?? 10)) {
470
+ this.queue.shift();
471
+ this.report(outcome.error ?? new Error("Supermetry event dropped after retries"));
472
+ continue;
473
+ }
474
+ this.scheduleRetry(item.attempts, outcome.retryAfter);
475
+ return;
476
+ }
477
+ }
478
+ scheduleRetry(attempts, retryAfterMs) {
479
+ if (this.destroyed)
480
+ return;
481
+ const base = this.options.retryDelay ?? 1000;
482
+ const cap = this.options.maxRetryDelay ?? 60000;
483
+ const backoff = Math.min(cap, base * 2 ** (attempts - 1));
484
+ const delay = Math.max(backoff * (0.8 + Math.random() * 0.4), retryAfterMs ?? 0);
485
+ this.retryTimer = setTimeout(() => {
486
+ this.retryTimer = undefined;
487
+ this.flush();
488
+ }, delay);
489
+ }
490
+ async send(event) {
491
+ try {
492
+ const doFetch = this.options.fetch ?? globalThis.fetch;
493
+ const response = await doFetch(this.endpoint, {
494
+ method: "POST",
495
+ headers: { "Content-Type": "application/json", "User-Agent": this.userAgent },
496
+ body: JSON.stringify(event)
497
+ });
498
+ if (response.ok)
499
+ return { done: true };
500
+ const error = new SupermetryHttpError(response.status);
501
+ if (response.status === 429 || response.status >= 500) {
502
+ const seconds = Number(response.headers?.get?.("retry-after"));
503
+ return { done: false, error, retryAfter: Number.isFinite(seconds) && seconds > 0 ? seconds * 1000 : undefined };
504
+ }
505
+ this.report(error);
506
+ return { done: true, error };
507
+ } catch (error) {
508
+ return { done: false, error: toError(error) };
509
+ }
510
+ }
511
+ onAppState(state) {
512
+ if (state === "background" || state === "inactive") {
513
+ this.flush().then(() => this.persistQueue());
514
+ } else if (state === "active" && this.queue.length > 0) {
515
+ this.flush().then(() => this.persistQueue());
516
+ }
517
+ }
518
+ async persistQueue() {
519
+ if (!this.options.storage || this.optedOut)
520
+ return;
521
+ await this.write(this.keys.queue, this.queue.length > 0 ? JSON.stringify(this.queue.map((item) => item.event)) : undefined);
522
+ }
523
+ persist(key, value) {
524
+ this.write(key, value);
525
+ }
526
+ async write(key, value) {
527
+ const storage = this.options.storage;
528
+ if (!storage)
529
+ return;
530
+ try {
531
+ if (value === undefined)
532
+ await storage.removeItem(key);
533
+ else
534
+ await storage.setItem(key, value);
535
+ } catch (error) {
536
+ this.report(error);
537
+ }
538
+ }
539
+ report(error) {
540
+ try {
541
+ this.options.onError?.(toError(error));
542
+ } catch {}
543
+ }
544
+ }
545
+ function createSupermetry(options) {
546
+ return new Client(options);
547
+ }
548
+ // src/react.tsx
549
+ var import_react = require("react");
550
+ var jsx_runtime = require("react/jsx-runtime");
551
+ var SupermetryContext = import_react.createContext(null);
552
+ function SupermetryProvider({ client, children }) {
553
+ return /* @__PURE__ */ jsx_runtime.jsx(SupermetryContext.Provider, {
554
+ value: client,
555
+ children
556
+ });
557
+ }
558
+ function useSupermetry() {
559
+ const client = import_react.useContext(SupermetryContext);
560
+ if (!client)
561
+ throw new Error("useSupermetry() must be used inside <SupermetryProvider>");
562
+ return client;
563
+ }
564
+ // src/navigation.ts
565
+ var lastRoute = new WeakMap;
566
+ function trackNavigation(client, navigationRef, options = {}) {
567
+ const handle = () => {
568
+ try {
569
+ const route = navigationRef.getCurrentRoute();
570
+ if (!route)
571
+ return;
572
+ const id = route.key ?? route.name;
573
+ if (lastRoute.get(navigationRef) === id)
574
+ return;
575
+ lastRoute.set(navigationRef, id);
576
+ const name = options.screenName ? options.screenName(route) : route.name;
577
+ if (name)
578
+ client.screen(name, options.props?.(route));
579
+ } catch {}
580
+ };
581
+ return { onReady: handle, onStateChange: handle };
582
+ }
@@ -0,0 +1,5 @@
1
+ export { EVENTS_PATH, VERSION, SupermetryHttpError, createSupermetry, type EventPayload, type SupermetryClient, type SupermetryReactNativeOptions, type SupermetryStorage, type TrackOptions, } from "./client";
2
+ export { SupermetryProvider, useSupermetry, type SupermetryProviderProps } from "./react";
3
+ export { trackNavigation, type NavigationRefLike, type NavigationRoute, type TrackNavigationOptions } from "./navigation";
4
+ export { buildUserAgent, screenPath } from "./platform";
5
+ export type { PropValue, Props, Revenue, Traits } from "./validate";