@leisuresaas/react-native 0.6.7-dev.1 → 0.6.8-dev.1

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@leisuresaas/react-native",
3
- "version": "0.6.7-dev.1",
3
+ "version": "0.6.8-dev.1",
4
4
  "description": "React Native SDK for LeisureSaas: OAuth, Public Ads/App Config, Drive User Plane (publishable keys). Frontend-only — no Integration Key.",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -0,0 +1,210 @@
1
+ import { AppState, Platform, type AppStateStatus } from "react-native";
2
+
3
+ import { authGetItem, authSetItem } from "./auth-storage";
4
+ import { ErrorReason, isReason, PlatformError } from "./errors";
5
+ import { authHeaders, deviceHeaders, type PublicAuthContext } from "./public-auth";
6
+
7
+ /**
8
+ * Product analytics for apps: app_open, foreground / background (automatic), screen views and
9
+ * custom events. Events are queued in memory and sent in batches to
10
+ * `/v1/public/analytics/events` (Publishable Key with the `analytics` capability). On by default
11
+ * once started; `setAnalyticsEnabled(false)` opts the device out and is remembered.
12
+ */
13
+ export type AnalyticsOptions = PublicAuthContext & {
14
+ /** Signed-in user's access token, so events are attributed to the user. */
15
+ getAccessToken?: () => string | undefined | Promise<string | undefined>;
16
+ /** Record app_open, app_foreground and app_background. Default true. */
17
+ autoAppEvents?: boolean;
18
+ /** Send queued events this often while the app is active. Default 10 s. */
19
+ flushIntervalMs?: number;
20
+ };
21
+
22
+ export type AnalyticsProps = Record<string, string | number | boolean | null | undefined>;
23
+
24
+ type QueuedEvent = {
25
+ event_id: string;
26
+ name: string;
27
+ occurred_at: number;
28
+ session_id: string;
29
+ screen?: string;
30
+ props?: Record<string, string>;
31
+ };
32
+
33
+ const maxBatch = 50;
34
+ const flushAt = 20;
35
+ const maxQueue = 500;
36
+ const sessionIdleMs = 30 * 60 * 1000;
37
+ const disabledKey = "leisuresaas.analytics_disabled";
38
+
39
+ let opts: AnalyticsOptions | undefined;
40
+ let queue: QueuedEvent[] = [];
41
+ let timer: ReturnType<typeof setInterval> | undefined;
42
+ let appStateSub: { remove: () => void } | undefined;
43
+ let sending = false;
44
+ let session = { id: "", lastActive: 0 };
45
+ let optedOut = false;
46
+ let productDisabled = false;
47
+
48
+ /**
49
+ * Starts collection: app_open now, app_foreground / app_background on AppState changes (unless
50
+ * `autoAppEvents: false`), and a flush every 10 s while active and when the app goes to the
51
+ * background. Returns a function that stops it.
52
+ */
53
+ export function startAnalytics(options: AnalyticsOptions): () => void {
54
+ stopAnalytics();
55
+ opts = options;
56
+ productDisabled = false;
57
+ void authGetItem(disabledKey).then((v) => {
58
+ optedOut = v === "1";
59
+ if (optedOut) {
60
+ queue = [];
61
+ }
62
+ }).catch(() => undefined);
63
+
64
+ timer = setInterval(() => {
65
+ if (AppState.currentState === "active") {
66
+ void flushAnalytics();
67
+ }
68
+ }, options.flushIntervalMs ?? 10_000);
69
+
70
+ let last = (AppState.currentState ?? "unknown") as AppStateStatus;
71
+ appStateSub = AppState.addEventListener("change", (next) => {
72
+ if (options.autoAppEvents !== false) {
73
+ if (next === "active" && last !== "active") {
74
+ track("app_foreground");
75
+ } else if (next === "background" && last !== "background") {
76
+ track("app_background");
77
+ }
78
+ }
79
+ if (next === "background") {
80
+ void flushAnalytics();
81
+ }
82
+ last = next;
83
+ });
84
+
85
+ if (options.autoAppEvents !== false) {
86
+ track("app_open");
87
+ }
88
+ return stopAnalytics;
89
+ }
90
+
91
+ /** Stops automatic collection and the flush timer. Queued events stay until the next start. */
92
+ export function stopAnalytics(): void {
93
+ if (timer !== undefined) {
94
+ clearInterval(timer);
95
+ timer = undefined;
96
+ }
97
+ appStateSub?.remove();
98
+ appStateSub = undefined;
99
+ }
100
+
101
+ /** Records a screen view; call it from your navigation container's state change. */
102
+ export function screen(name: string, props?: AnalyticsProps): void {
103
+ if (!collecting()) {
104
+ return;
105
+ }
106
+ enqueue({ ...baseEvent("screen_view"), screen: name, props: stringProps(props) });
107
+ }
108
+
109
+ /** Records a custom event, e.g. `track("checkout_started", { plan: "premium" })`. */
110
+ export function track(name: string, props?: AnalyticsProps): void {
111
+ if (!collecting()) {
112
+ return;
113
+ }
114
+ enqueue({ ...baseEvent(name), props: stringProps(props) });
115
+ }
116
+
117
+ /** Opts this device in or out. Opting out drops queued events; the choice is kept in secure storage. */
118
+ export async function setAnalyticsEnabled(enabled: boolean): Promise<void> {
119
+ optedOut = !enabled;
120
+ if (!enabled) {
121
+ queue = [];
122
+ }
123
+ try {
124
+ await authSetItem(disabledKey, enabled ? "" : "1");
125
+ } catch {
126
+ // storage unavailable: the choice lasts for this run
127
+ }
128
+ }
129
+
130
+ /** Whether this device collects analytics (default true). */
131
+ export function analyticsEnabled(): boolean {
132
+ return !optedOut;
133
+ }
134
+
135
+ /** Sends queued events now. Failed sends stay queued; ANALYTICS_DISABLED stops collection. */
136
+ export async function flushAnalytics(): Promise<void> {
137
+ if (!opts || sending || queue.length === 0) {
138
+ return;
139
+ }
140
+ sending = true;
141
+ const batch = queue.slice(0, maxBatch);
142
+ try {
143
+ await sendBatch(opts, batch);
144
+ queue = queue.slice(batch.length);
145
+ } catch (err) {
146
+ if (isReason(err, ErrorReason.AnalyticsDisabled)) {
147
+ productDisabled = true;
148
+ queue = [];
149
+ stopAnalytics();
150
+ } else if (err instanceof PlatformError && err.statusCode >= 400 && err.statusCode < 500 && err.statusCode !== 429) {
151
+ // The batch itself is unacceptable (bad key, too large); retrying would fail again.
152
+ queue = queue.slice(batch.length);
153
+ }
154
+ } finally {
155
+ sending = false;
156
+ }
157
+ }
158
+
159
+ function collecting(): boolean {
160
+ return !optedOut && !productDisabled;
161
+ }
162
+
163
+ function enqueue(ev: QueuedEvent): void {
164
+ queue.push(ev);
165
+ if (queue.length > maxQueue) {
166
+ queue = queue.slice(queue.length - maxQueue);
167
+ }
168
+ if (queue.length >= flushAt) {
169
+ void flushAnalytics();
170
+ }
171
+ }
172
+
173
+ function baseEvent(name: string): QueuedEvent {
174
+ const now = Date.now();
175
+ if (!session.id || now - session.lastActive > sessionIdleMs) {
176
+ session = { id: newId(), lastActive: now };
177
+ }
178
+ session.lastActive = now;
179
+ return { event_id: newId(), name, occurred_at: now, session_id: session.id };
180
+ }
181
+
182
+ function stringProps(props?: AnalyticsProps): Record<string, string> | undefined {
183
+ if (!props) {
184
+ return undefined;
185
+ }
186
+ const out: Record<string, string> = {};
187
+ for (const [k, v] of Object.entries(props)) {
188
+ if (v !== undefined && v !== null) {
189
+ out[k] = String(v);
190
+ }
191
+ }
192
+ return out;
193
+ }
194
+
195
+ async function sendBatch(options: AnalyticsOptions, events: QueuedEvent[]): Promise<void> {
196
+ const token = await options.getAccessToken?.();
197
+ const headers = { ...authHeaders(options, token), ...(await deviceHeaders(options)) };
198
+ const res = await fetch(`${options.gatewayUrl.replace(/\/+$/, "")}/v1/public/analytics/events`, {
199
+ method: "POST",
200
+ headers,
201
+ body: JSON.stringify({ os: `${Platform.OS} ${String(Platform.Version)}`, events }),
202
+ });
203
+ if (!res.ok) {
204
+ throw PlatformError.fromHttp(res.status, (await res.text()).trim());
205
+ }
206
+ }
207
+
208
+ function newId(): string {
209
+ return globalThis.crypto?.randomUUID?.() ?? `rn-${Date.now()}-${Math.random().toString(36).slice(2)}`;
210
+ }
package/src/errors.ts CHANGED
@@ -33,6 +33,7 @@ export const ErrorReason = {
33
33
  // the product allows fewer devices / signed out from another device or by an operator.
34
34
  SessionReplaced: "SESSION_REPLACED",
35
35
  SessionLimitReached: "SESSION_LIMIT_REACHED",
36
+ AnalyticsDisabled: "ANALYTICS_DISABLED",
36
37
  SessionRevoked: "SESSION_REVOKED",
37
38
  // Drive uploads: the user's plan storage is used up / the product's storage is full / the file is
38
39
  // over the product's single-file limit.
package/src/index.ts CHANGED
@@ -201,3 +201,14 @@ export type {
201
201
  RegisterDeviceTokenInput,
202
202
  SubscriptionStatus,
203
203
  } from "./types";
204
+
205
+ export {
206
+ analyticsEnabled,
207
+ flushAnalytics,
208
+ screen,
209
+ setAnalyticsEnabled,
210
+ startAnalytics,
211
+ stopAnalytics,
212
+ track,
213
+ } from "./analytics";
214
+ export type { AnalyticsOptions, AnalyticsProps } from "./analytics";
@@ -48,7 +48,8 @@ function resolvePlatform(ctx: PublicAuthContext): MobilePlatform | "web" {
48
48
  return ctx.platform ?? mobilePlatform();
49
49
  }
50
50
 
51
- function authHeaders(ctx: PublicAuthContext, accessToken?: string): Record<string, string> {
51
+ /** @internal Shared with analytics. */
52
+ export function authHeaders(ctx: PublicAuthContext, accessToken?: string): Record<string, string> {
52
53
  const platform = resolvePlatform(ctx);
53
54
  const headers: Record<string, string> = {
54
55
  Accept: "application/json",
@@ -67,7 +68,8 @@ function authHeaders(ctx: PublicAuthContext, accessToken?: string): Record<strin
67
68
  return headers;
68
69
  }
69
70
 
70
- async function deviceHeaders(ctx: PublicAuthContext): Promise<Record<string, string>> {
71
+ /** @internal Shared with analytics. */
72
+ export async function deviceHeaders(ctx: PublicAuthContext): Promise<Record<string, string>> {
71
73
  const headers: Record<string, string> = { "X-Device-Id": await appDeviceId() };
72
74
  if (ctx.appVersion?.trim()) headers["X-App-Version"] = ctx.appVersion.trim();
73
75
  if (ctx.deviceModel?.trim()) headers["X-Device-Model"] = ctx.deviceModel.trim();