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