@cavlyn/react-native-sdk 0.0.0-stage → 0.1.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/CavlynReactNative.podspec +23 -0
- package/LICENSE +202 -0
- package/README.md +164 -2
- package/android/build.gradle +52 -0
- package/android/src/main/AndroidManifest.xml +3 -0
- package/android/src/main/kotlin/com/cavlyn/reactnative/CavlynReactNativeModule.kt +394 -0
- package/android/src/main/kotlin/com/cavlyn/reactnative/CavlynReactNativePackage.kt +14 -0
- package/dist/client.d.ts +95 -0
- package/dist/client.d.ts.map +1 -0
- package/dist/client.js +395 -0
- package/dist/client.js.map +1 -0
- package/dist/hooks.d.ts +24 -0
- package/dist/hooks.d.ts.map +1 -0
- package/dist/hooks.js +78 -0
- package/dist/hooks.js.map +1 -0
- package/dist/http.d.ts +30 -0
- package/dist/http.d.ts.map +1 -0
- package/dist/http.js +126 -0
- package/dist/http.js.map +1 -0
- package/dist/index.d.ts +8 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +26 -0
- package/dist/index.js.map +1 -0
- package/dist/nativeBridge.d.ts +46 -0
- package/dist/nativeBridge.d.ts.map +1 -0
- package/dist/nativeBridge.js +99 -0
- package/dist/nativeBridge.js.map +1 -0
- package/dist/parser.d.ts +38 -0
- package/dist/parser.d.ts.map +1 -0
- package/dist/parser.js +198 -0
- package/dist/parser.js.map +1 -0
- package/dist/storage.d.ts +27 -0
- package/dist/storage.d.ts.map +1 -0
- package/dist/storage.js +72 -0
- package/dist/storage.js.map +1 -0
- package/dist/types.d.ts +182 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/types.js +3 -0
- package/dist/types.js.map +1 -0
- package/ios/CavlynReactNative.m +40 -0
- package/ios/CavlynReactNative.swift +463 -0
- package/package.json +65 -4
- package/react-native.config.js +14 -0
- package/src/client.ts +479 -0
- package/src/hooks.ts +117 -0
- package/src/http.ts +158 -0
- package/src/index.ts +38 -0
- package/src/nativeBridge.ts +109 -0
- package/src/parser.ts +202 -0
- package/src/storage.ts +76 -0
- package/src/types.ts +214 -0
package/src/client.ts
ADDED
|
@@ -0,0 +1,479 @@
|
|
|
1
|
+
import { HttpEventApi } from './http';
|
|
2
|
+
import {
|
|
3
|
+
detectPlatform,
|
|
4
|
+
getLinkingInitialUrl,
|
|
5
|
+
getNativeModule,
|
|
6
|
+
subscribeLinkingUrls,
|
|
7
|
+
subscribeNativeLinkEvents,
|
|
8
|
+
} from './nativeBridge';
|
|
9
|
+
import { fromNativeLinkPayload, generateUuid, normalizeUuid, parseDynamicLink } from './parser';
|
|
10
|
+
import { DeepLinkRepository, MemoryStorage } from './storage';
|
|
11
|
+
import type {
|
|
12
|
+
CavlynConfiguration,
|
|
13
|
+
CavlynNativeModule,
|
|
14
|
+
CavlynPlatformName,
|
|
15
|
+
CommerceEventInput,
|
|
16
|
+
DynamicLink,
|
|
17
|
+
EventApiPayload,
|
|
18
|
+
LinkListener,
|
|
19
|
+
LinkSubscription,
|
|
20
|
+
ResolvedDynamicLink,
|
|
21
|
+
TrackEventOptions,
|
|
22
|
+
} from './types';
|
|
23
|
+
|
|
24
|
+
const DEFAULT_API_BASE_URL = 'https://api.cavlyn.com';
|
|
25
|
+
const DEFAULT_TIMEOUT_MS = 10_000;
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* Instantiable Cavlyn React Native SDK runtime.
|
|
29
|
+
* Most applications should use the default singleton exported as `Cavlyn` / `CavlynClient`.
|
|
30
|
+
*/
|
|
31
|
+
export class CavlynSDK {
|
|
32
|
+
private initialized = false;
|
|
33
|
+
private apiKey = '';
|
|
34
|
+
private apiBaseUrl = DEFAULT_API_BASE_URL;
|
|
35
|
+
private platform: CavlynPlatformName = 'IOS';
|
|
36
|
+
private debug = false;
|
|
37
|
+
|
|
38
|
+
private nativeModule: CavlynNativeModule | null = null;
|
|
39
|
+
private hasNativeEmitter = false;
|
|
40
|
+
private repository: DeepLinkRepository | null = null;
|
|
41
|
+
private httpApi: HttpEventApi | null = null;
|
|
42
|
+
|
|
43
|
+
private readonly listeners = new Set<LinkListener>();
|
|
44
|
+
private internalSubscriptions: LinkSubscription[] = [];
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* Initializes the Cavlyn SDK. Safe to call multiple times (subsequent calls are no-ops).
|
|
48
|
+
*/
|
|
49
|
+
async initialize(configuration: CavlynConfiguration): Promise<void> {
|
|
50
|
+
if (this.initialized) {
|
|
51
|
+
return;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
if (!configuration || typeof configuration.apiKey !== 'string' || !configuration.apiKey.trim()) {
|
|
55
|
+
throw new Error('Cavlyn: apiKey is required to initialize the SDK');
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
this.apiKey = configuration.apiKey.trim();
|
|
59
|
+
this.apiBaseUrl = (configuration.apiBaseUrl ?? DEFAULT_API_BASE_URL).replace(/\/+$/, '');
|
|
60
|
+
this.platform = configuration.platform ?? detectPlatform();
|
|
61
|
+
this.debug = Boolean(configuration.debug);
|
|
62
|
+
|
|
63
|
+
const timeoutMs = configuration.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
|
64
|
+
this.httpApi = new HttpEventApi({
|
|
65
|
+
apiKey: this.apiKey,
|
|
66
|
+
apiBaseUrl: this.apiBaseUrl,
|
|
67
|
+
timeoutMs,
|
|
68
|
+
fetch: configuration.fetch,
|
|
69
|
+
debug: this.debug,
|
|
70
|
+
});
|
|
71
|
+
|
|
72
|
+
this.nativeModule =
|
|
73
|
+
configuration.nativeModule !== undefined ? configuration.nativeModule : getNativeModule();
|
|
74
|
+
|
|
75
|
+
this.repository = new DeepLinkRepository(configuration.storage ?? new MemoryStorage());
|
|
76
|
+
|
|
77
|
+
const autoListen = configuration.autoListenLinking !== false;
|
|
78
|
+
const autoHandleInitial = configuration.autoHandleInitialUrl !== false;
|
|
79
|
+
const autoCaptureAsa = configuration.autoCaptureAdServicesToken !== false;
|
|
80
|
+
|
|
81
|
+
if (this.nativeModule) {
|
|
82
|
+
await this.nativeModule.initialize(this.apiKey, this.apiBaseUrl);
|
|
83
|
+
this.initialized = true;
|
|
84
|
+
|
|
85
|
+
if (autoListen) {
|
|
86
|
+
const nativeSub = subscribeNativeLinkEvents(this.nativeModule, (payload) => {
|
|
87
|
+
const link = fromNativeLinkPayload(payload);
|
|
88
|
+
if (link) {
|
|
89
|
+
this.notifyListeners(link);
|
|
90
|
+
}
|
|
91
|
+
});
|
|
92
|
+
if (nativeSub) {
|
|
93
|
+
this.hasNativeEmitter = true;
|
|
94
|
+
this.internalSubscriptions.push(nativeSub);
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
if (autoCaptureAsa && this.platform === 'IOS' && this.nativeModule.getAdServicesToken) {
|
|
99
|
+
try {
|
|
100
|
+
const token = await this.nativeModule.getAdServicesToken();
|
|
101
|
+
if (token) {
|
|
102
|
+
await this.recordAdServicesToken(token);
|
|
103
|
+
}
|
|
104
|
+
} catch (err) {
|
|
105
|
+
if (this.debug) {
|
|
106
|
+
console.debug('[Cavlyn] Apple Search Ads token lookup failed (non-fatal):', err);
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
return;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
// Pure JS / Expo Go / Web fallback mode
|
|
114
|
+
this.initialized = true;
|
|
115
|
+
|
|
116
|
+
if (autoListen) {
|
|
117
|
+
const linkingSub = subscribeLinkingUrls((url) => {
|
|
118
|
+
void this.handleUrl(url);
|
|
119
|
+
});
|
|
120
|
+
if (linkingSub) {
|
|
121
|
+
this.internalSubscriptions.push(linkingSub);
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
if (autoHandleInitial) {
|
|
126
|
+
const initialUrl = await getLinkingInitialUrl();
|
|
127
|
+
if (initialUrl) {
|
|
128
|
+
await this.handleUrl(initialUrl);
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/**
|
|
134
|
+
* Returns whether `initialize()` has completed.
|
|
135
|
+
*/
|
|
136
|
+
isInitialized(): boolean {
|
|
137
|
+
return this.initialized;
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/**
|
|
141
|
+
* Returns `true` when backed by the linked native iOS/Android bridge module.
|
|
142
|
+
*/
|
|
143
|
+
isUsingNativeBridge(): boolean {
|
|
144
|
+
return this.nativeModule !== null;
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
/**
|
|
148
|
+
* Handles an incoming Universal Link, Android App Link, or custom scheme URL.
|
|
149
|
+
* Persists first-touch and latest attribution context, dispatches `INSTALL` (once)
|
|
150
|
+
* and `APP_OPEN` events, and notifies all active link subscribers.
|
|
151
|
+
*/
|
|
152
|
+
async handleUrl(url: string | null | undefined): Promise<DynamicLink | null> {
|
|
153
|
+
this.requireInitialized();
|
|
154
|
+
if (!url || !url.trim()) {
|
|
155
|
+
return null;
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
if (this.nativeModule) {
|
|
159
|
+
const raw = await this.nativeModule.handleUrl(url);
|
|
160
|
+
const link = fromNativeLinkPayload(raw);
|
|
161
|
+
if (link && !this.hasNativeEmitter) {
|
|
162
|
+
this.notifyListeners(link);
|
|
163
|
+
}
|
|
164
|
+
return link;
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
const link = parseDynamicLink(url);
|
|
168
|
+
if (!link) {
|
|
169
|
+
return null;
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
const repo = this.repository!;
|
|
173
|
+
const installId = await repo.getOrCreateInstallationId();
|
|
174
|
+
const existingInitial = await repo.readInitial();
|
|
175
|
+
|
|
176
|
+
if (!existingInitial) {
|
|
177
|
+
await repo.saveInitial(link);
|
|
178
|
+
await this.dispatchEvent(
|
|
179
|
+
{
|
|
180
|
+
linkId: link.linkId,
|
|
181
|
+
...(link.clickId ? { clickId: link.clickId } : {}),
|
|
182
|
+
type: 'INSTALL',
|
|
183
|
+
installId,
|
|
184
|
+
platform: this.platform,
|
|
185
|
+
occurredAt: new Date().toISOString(),
|
|
186
|
+
metadata: {},
|
|
187
|
+
},
|
|
188
|
+
`install:${installId}:${link.linkId}`,
|
|
189
|
+
);
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
await repo.saveCurrent(link);
|
|
193
|
+
|
|
194
|
+
await this.dispatchEvent(
|
|
195
|
+
{
|
|
196
|
+
linkId: link.linkId,
|
|
197
|
+
...(link.clickId ? { clickId: link.clickId } : {}),
|
|
198
|
+
type: 'APP_OPEN',
|
|
199
|
+
eventName: 'app_open',
|
|
200
|
+
installId,
|
|
201
|
+
platform: this.platform,
|
|
202
|
+
occurredAt: new Date().toISOString(),
|
|
203
|
+
metadata: {},
|
|
204
|
+
},
|
|
205
|
+
generateUuid(),
|
|
206
|
+
);
|
|
207
|
+
|
|
208
|
+
this.notifyListeners(link);
|
|
209
|
+
return link;
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
/**
|
|
213
|
+
* Returns the very first verified attribution link received by this installation.
|
|
214
|
+
*/
|
|
215
|
+
async initialLink(): Promise<DynamicLink | null> {
|
|
216
|
+
this.requireInitialized();
|
|
217
|
+
if (this.nativeModule) {
|
|
218
|
+
return fromNativeLinkPayload(await this.nativeModule.initialLink());
|
|
219
|
+
}
|
|
220
|
+
return this.repository!.readInitial();
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
/**
|
|
224
|
+
* Returns the most recent verified attribution link received by this installation.
|
|
225
|
+
*/
|
|
226
|
+
async currentLink(): Promise<DynamicLink | null> {
|
|
227
|
+
this.requireInitialized();
|
|
228
|
+
if (this.nativeModule) {
|
|
229
|
+
return fromNativeLinkPayload(await this.nativeModule.currentLink());
|
|
230
|
+
}
|
|
231
|
+
return this.repository!.readCurrent();
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
/**
|
|
235
|
+
* Subscribes a listener to incoming dynamic links while the app is running.
|
|
236
|
+
* Returns a React Native compatible `{ remove() }` subscription handle.
|
|
237
|
+
*/
|
|
238
|
+
onLink(listener: LinkListener): LinkSubscription {
|
|
239
|
+
this.listeners.add(listener);
|
|
240
|
+
return {
|
|
241
|
+
remove: () => {
|
|
242
|
+
this.listeners.delete(listener);
|
|
243
|
+
},
|
|
244
|
+
};
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
/**
|
|
248
|
+
* Alias for `onLink` matching the iOS and Android SDK naming convention.
|
|
249
|
+
*/
|
|
250
|
+
subscribe(listener: LinkListener): LinkSubscription {
|
|
251
|
+
return this.onLink(listener);
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
/**
|
|
255
|
+
* Tracks a custom in-app conversion event (e.g. `'purchase'`, `'sign_up'`, `'subscription_started'`).
|
|
256
|
+
*/
|
|
257
|
+
async trackEvent(
|
|
258
|
+
name: string,
|
|
259
|
+
properties: Record<string, unknown> = {},
|
|
260
|
+
options?: TrackEventOptions,
|
|
261
|
+
): Promise<void> {
|
|
262
|
+
this.requireInitialized();
|
|
263
|
+
const trimmedName = typeof name === 'string' ? name.trim() : '';
|
|
264
|
+
if (!trimmedName) {
|
|
265
|
+
throw new Error('Cavlyn: event name must not be blank');
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
const hasCustomOptions =
|
|
269
|
+
options !== undefined &&
|
|
270
|
+
(options.linkId !== undefined ||
|
|
271
|
+
options.clickId !== undefined ||
|
|
272
|
+
options.idempotencyKey !== undefined ||
|
|
273
|
+
options.occurredAt !== undefined);
|
|
274
|
+
|
|
275
|
+
if (this.nativeModule && !hasCustomOptions) {
|
|
276
|
+
await this.nativeModule.trackEvent(trimmedName, properties);
|
|
277
|
+
return;
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
const context = await this.resolveAttributionContext(options?.linkId, options?.clickId);
|
|
281
|
+
if (!context) {
|
|
282
|
+
return;
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
const installId = await this.getInstallationId();
|
|
286
|
+
const occurredAt = this.formatOccurredAt(options?.occurredAt);
|
|
287
|
+
const idempotencyKey = options?.idempotencyKey ?? generateUuid();
|
|
288
|
+
|
|
289
|
+
await this.dispatchEvent(
|
|
290
|
+
{
|
|
291
|
+
linkId: context.linkId,
|
|
292
|
+
...(context.clickId ? { clickId: context.clickId } : {}),
|
|
293
|
+
type: 'CONVERSION',
|
|
294
|
+
eventName: trimmedName,
|
|
295
|
+
installId,
|
|
296
|
+
platform: this.platform,
|
|
297
|
+
occurredAt,
|
|
298
|
+
metadata: properties,
|
|
299
|
+
},
|
|
300
|
+
idempotencyKey,
|
|
301
|
+
);
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
/**
|
|
305
|
+
* Tracks a typed V2 commerce event (`PRODUCT_VIEW`, `ADD_TO_CART`, `CHECKOUT_STARTED`, `PURCHASE`, etc.).
|
|
306
|
+
*/
|
|
307
|
+
async trackCommerceEvent(event: CommerceEventInput): Promise<void> {
|
|
308
|
+
this.requireInitialized();
|
|
309
|
+
if (!event || !event.type) {
|
|
310
|
+
throw new Error('Cavlyn: commerce event type is required');
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
const hasCustomOptions =
|
|
314
|
+
event.linkId !== undefined ||
|
|
315
|
+
event.clickId !== undefined ||
|
|
316
|
+
event.idempotencyKey !== undefined ||
|
|
317
|
+
event.occurredAt !== undefined;
|
|
318
|
+
|
|
319
|
+
if (this.nativeModule?.trackCommerceEvent && !hasCustomOptions) {
|
|
320
|
+
await this.nativeModule.trackCommerceEvent({ ...event });
|
|
321
|
+
return;
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
const context = await this.resolveAttributionContext(event.linkId, event.clickId);
|
|
325
|
+
if (!context) {
|
|
326
|
+
return;
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
const installId = await this.getInstallationId();
|
|
330
|
+
const payload: EventApiPayload = {
|
|
331
|
+
linkId: context.linkId,
|
|
332
|
+
...(context.clickId ? { clickId: context.clickId } : {}),
|
|
333
|
+
type: event.type,
|
|
334
|
+
eventName: event.eventName ?? event.type.toLowerCase(),
|
|
335
|
+
installId,
|
|
336
|
+
platform: this.platform,
|
|
337
|
+
occurredAt: this.formatOccurredAt(event.occurredAt),
|
|
338
|
+
...(event.storeId ? { storeId: event.storeId } : {}),
|
|
339
|
+
...(event.productId ? { productId: event.productId } : {}),
|
|
340
|
+
...(event.variantId ? { variantId: event.variantId } : {}),
|
|
341
|
+
...(event.orderId ? { orderId: event.orderId } : {}),
|
|
342
|
+
...(event.currency ? { currency: event.currency } : {}),
|
|
343
|
+
...(event.value !== undefined ? { value: event.value } : {}),
|
|
344
|
+
...(event.quantity !== undefined ? { quantity: event.quantity } : {}),
|
|
345
|
+
metadata: event.metadata ?? {},
|
|
346
|
+
};
|
|
347
|
+
|
|
348
|
+
await this.dispatchEvent(payload, event.idempotencyKey ?? generateUuid());
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
/**
|
|
352
|
+
* Records an Apple Search Ads (ASA) AdServices attribution token on iOS 14.3+.
|
|
353
|
+
* When omitted on iOS with the native module linked, automatically fetches the token via AdServices.
|
|
354
|
+
*/
|
|
355
|
+
async recordAdServicesToken(token?: string): Promise<void> {
|
|
356
|
+
this.requireInitialized();
|
|
357
|
+
|
|
358
|
+
let resolvedToken = token?.trim();
|
|
359
|
+
if (!resolvedToken && this.nativeModule?.getAdServicesToken) {
|
|
360
|
+
resolvedToken = (await this.nativeModule.getAdServicesToken())?.trim();
|
|
361
|
+
}
|
|
362
|
+
if (!resolvedToken) {
|
|
363
|
+
return;
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
if (this.nativeModule?.recordAdServicesToken) {
|
|
367
|
+
await this.nativeModule.recordAdServicesToken(resolvedToken);
|
|
368
|
+
return;
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
await this.trackEvent('apple_search_ads_token', { adServicesToken: resolvedToken });
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
/**
|
|
375
|
+
* Resolves a dynamic link by short code, custom alias, or full URL via `GET /api/v1/links/resolve`.
|
|
376
|
+
*/
|
|
377
|
+
async resolveLink(shortCodeOrUrl: string): Promise<ResolvedDynamicLink> {
|
|
378
|
+
this.requireInitialized();
|
|
379
|
+
return this.httpApi!.resolveLink(shortCodeOrUrl);
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
/**
|
|
383
|
+
* Returns the stable privacy-compliant per-installation UUID.
|
|
384
|
+
*/
|
|
385
|
+
async getInstallationId(): Promise<string> {
|
|
386
|
+
this.requireInitialized();
|
|
387
|
+
if (this.nativeModule?.getInstallationId) {
|
|
388
|
+
return this.nativeModule.getInstallationId();
|
|
389
|
+
}
|
|
390
|
+
return this.repository!.getOrCreateInstallationId();
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
/**
|
|
394
|
+
* Resets SDK runtime state and removes all active listeners.
|
|
395
|
+
* Primarily useful in unit tests or when resetting user/session state.
|
|
396
|
+
*/
|
|
397
|
+
async reset(options: { clearStorage?: boolean } = {}): Promise<void> {
|
|
398
|
+
for (const sub of this.internalSubscriptions) {
|
|
399
|
+
try {
|
|
400
|
+
sub.remove();
|
|
401
|
+
} catch {
|
|
402
|
+
// ignore teardown errors
|
|
403
|
+
}
|
|
404
|
+
}
|
|
405
|
+
this.internalSubscriptions = [];
|
|
406
|
+
this.listeners.clear();
|
|
407
|
+
if (options.clearStorage && this.repository) {
|
|
408
|
+
await this.repository.clear();
|
|
409
|
+
}
|
|
410
|
+
this.initialized = false;
|
|
411
|
+
this.nativeModule = null;
|
|
412
|
+
this.hasNativeEmitter = false;
|
|
413
|
+
this.httpApi = null;
|
|
414
|
+
this.repository = null;
|
|
415
|
+
}
|
|
416
|
+
|
|
417
|
+
private async resolveAttributionContext(
|
|
418
|
+
overrideLinkId?: string,
|
|
419
|
+
overrideClickId?: string,
|
|
420
|
+
): Promise<{ linkId: string; clickId?: string } | null> {
|
|
421
|
+
const explicitLinkId = normalizeUuid(overrideLinkId);
|
|
422
|
+
const explicitClickId = normalizeUuid(overrideClickId);
|
|
423
|
+
|
|
424
|
+
if (explicitLinkId) {
|
|
425
|
+
return {
|
|
426
|
+
linkId: explicitLinkId,
|
|
427
|
+
...(explicitClickId ? { clickId: explicitClickId } : {}),
|
|
428
|
+
};
|
|
429
|
+
}
|
|
430
|
+
|
|
431
|
+
const link = (await this.currentLink()) ?? (await this.initialLink());
|
|
432
|
+
if (!link) {
|
|
433
|
+
return null;
|
|
434
|
+
}
|
|
435
|
+
|
|
436
|
+
return {
|
|
437
|
+
linkId: link.linkId,
|
|
438
|
+
...(explicitClickId ?? link.clickId ? { clickId: explicitClickId ?? link.clickId } : {}),
|
|
439
|
+
};
|
|
440
|
+
}
|
|
441
|
+
|
|
442
|
+
private async dispatchEvent(payload: EventApiPayload, idempotencyKey: string): Promise<void> {
|
|
443
|
+
if (!this.httpApi) return;
|
|
444
|
+
await this.httpApi.sendEvent(payload, idempotencyKey);
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
private formatOccurredAt(input?: Date | string): string {
|
|
448
|
+
if (!input) return new Date().toISOString();
|
|
449
|
+
return input instanceof Date ? input.toISOString() : input;
|
|
450
|
+
}
|
|
451
|
+
|
|
452
|
+
private notifyListeners(link: DynamicLink): void {
|
|
453
|
+
for (const listener of Array.from(this.listeners)) {
|
|
454
|
+
try {
|
|
455
|
+
listener(link);
|
|
456
|
+
} catch (err) {
|
|
457
|
+
if (this.debug) {
|
|
458
|
+
console.debug('[Cavlyn] Link listener threw an error:', err);
|
|
459
|
+
}
|
|
460
|
+
}
|
|
461
|
+
}
|
|
462
|
+
}
|
|
463
|
+
|
|
464
|
+
private requireInitialized(): void {
|
|
465
|
+
if (!this.initialized) {
|
|
466
|
+
throw new Error('Cavlyn: call Cavlyn.initialize(...) before using the SDK');
|
|
467
|
+
}
|
|
468
|
+
}
|
|
469
|
+
}
|
|
470
|
+
|
|
471
|
+
/**
|
|
472
|
+
* Default singleton SDK instance.
|
|
473
|
+
*/
|
|
474
|
+
export const Cavlyn = new CavlynSDK();
|
|
475
|
+
|
|
476
|
+
/**
|
|
477
|
+
* Alias matching the Flutter and Node.js SDK facade naming (`CavlynClient`).
|
|
478
|
+
*/
|
|
479
|
+
export const CavlynClient = Cavlyn;
|
package/src/hooks.ts
ADDED
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
import { Cavlyn, type CavlynSDK } from './client';
|
|
2
|
+
import type { CommerceEventInput, DynamicLink, LinkListener, TrackEventOptions } from './types';
|
|
3
|
+
|
|
4
|
+
declare const require: (id: string) => unknown;
|
|
5
|
+
|
|
6
|
+
interface ReactHooksApi {
|
|
7
|
+
useState<T>(initialState: T | (() => T)): [T, (value: T | ((prev: T) => T)) => void];
|
|
8
|
+
useEffect(effect: () => void | (() => void), deps?: readonly unknown[]): void;
|
|
9
|
+
useRef<T>(initialValue: T): { current: T };
|
|
10
|
+
useCallback<T extends (...args: never[]) => unknown>(callback: T, deps: readonly unknown[]): T;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
function loadReact(): ReactHooksApi {
|
|
14
|
+
try {
|
|
15
|
+
// Literal require so Metro/webpack can resolve it statically.
|
|
16
|
+
// eslint-disable-next-line @typescript-eslint/no-var-requires
|
|
17
|
+
const react = require('react') as Partial<ReactHooksApi> | undefined;
|
|
18
|
+
if (react && react.useState && react.useEffect && react.useRef && react.useCallback) {
|
|
19
|
+
return react as ReactHooksApi;
|
|
20
|
+
}
|
|
21
|
+
} catch {
|
|
22
|
+
// fall through to clear error below
|
|
23
|
+
}
|
|
24
|
+
throw new Error('Cavlyn hooks require `react` (>=18.0.0) to be installed in the host application');
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export interface UseCavlynLinkResult {
|
|
28
|
+
/** First verified attribution link received by this installation, if any. */
|
|
29
|
+
initialLink: DynamicLink | null;
|
|
30
|
+
/** Most recent verified attribution link received while running. */
|
|
31
|
+
currentLink: DynamicLink | null;
|
|
32
|
+
/** `true` while fetching the initial attribution link. */
|
|
33
|
+
loading: boolean;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* React hook that loads the initial Cavlyn deep link and subscribes to live incoming links.
|
|
38
|
+
* Automatically unsubscribes when the component unmounts.
|
|
39
|
+
*/
|
|
40
|
+
export function useCavlynLink(
|
|
41
|
+
onLink?: LinkListener,
|
|
42
|
+
sdk: CavlynSDK = Cavlyn,
|
|
43
|
+
): UseCavlynLinkResult {
|
|
44
|
+
const React = loadReact();
|
|
45
|
+
const [initialLink, setInitialLink] = React.useState<DynamicLink | null>(null);
|
|
46
|
+
const [currentLink, setCurrentLink] = React.useState<DynamicLink | null>(null);
|
|
47
|
+
const [loading, setLoading] = React.useState<boolean>(true);
|
|
48
|
+
const onLinkRef = React.useRef<LinkListener | undefined>(onLink);
|
|
49
|
+
onLinkRef.current = onLink;
|
|
50
|
+
|
|
51
|
+
React.useEffect(() => {
|
|
52
|
+
let active = true;
|
|
53
|
+
|
|
54
|
+
const subscription = sdk.onLink((link) => {
|
|
55
|
+
if (!active) return;
|
|
56
|
+
setCurrentLink(link);
|
|
57
|
+
setInitialLink((prev) => prev ?? link);
|
|
58
|
+
onLinkRef.current?.(link);
|
|
59
|
+
});
|
|
60
|
+
|
|
61
|
+
if (sdk.isInitialized()) {
|
|
62
|
+
Promise.all([sdk.initialLink(), sdk.currentLink()])
|
|
63
|
+
.then(([initial, current]) => {
|
|
64
|
+
if (!active) return;
|
|
65
|
+
setInitialLink(initial);
|
|
66
|
+
setCurrentLink(current ?? initial);
|
|
67
|
+
if (initial && onLinkRef.current) {
|
|
68
|
+
onLinkRef.current(current ?? initial);
|
|
69
|
+
}
|
|
70
|
+
})
|
|
71
|
+
.catch(() => {
|
|
72
|
+
// Non-fatal in UI hook
|
|
73
|
+
})
|
|
74
|
+
.finally(() => {
|
|
75
|
+
if (active) setLoading(false);
|
|
76
|
+
});
|
|
77
|
+
} else {
|
|
78
|
+
setLoading(false);
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
return () => {
|
|
82
|
+
active = false;
|
|
83
|
+
subscription.remove();
|
|
84
|
+
};
|
|
85
|
+
}, [sdk]);
|
|
86
|
+
|
|
87
|
+
return { initialLink, currentLink, loading };
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
export interface UseCavlynTrackEventResult {
|
|
91
|
+
trackEvent: (
|
|
92
|
+
name: string,
|
|
93
|
+
properties?: Record<string, unknown>,
|
|
94
|
+
options?: TrackEventOptions,
|
|
95
|
+
) => Promise<void>;
|
|
96
|
+
trackCommerceEvent: (event: CommerceEventInput) => Promise<void>;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/**
|
|
100
|
+
* React hook returning memoized event tracking callbacks bound to the Cavlyn SDK.
|
|
101
|
+
*/
|
|
102
|
+
export function useCavlynTrackEvent(sdk: CavlynSDK = Cavlyn): UseCavlynTrackEventResult {
|
|
103
|
+
const React = loadReact();
|
|
104
|
+
|
|
105
|
+
const trackEvent = React.useCallback(
|
|
106
|
+
(name: string, properties?: Record<string, unknown>, options?: TrackEventOptions) =>
|
|
107
|
+
sdk.trackEvent(name, properties, options),
|
|
108
|
+
[sdk],
|
|
109
|
+
);
|
|
110
|
+
|
|
111
|
+
const trackCommerceEvent = React.useCallback(
|
|
112
|
+
(event: CommerceEventInput) => sdk.trackCommerceEvent(event),
|
|
113
|
+
[sdk],
|
|
114
|
+
);
|
|
115
|
+
|
|
116
|
+
return { trackEvent, trackCommerceEvent };
|
|
117
|
+
}
|