@cavlyn/react-native-sdk 0.0.0-stage → 0.1.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/CavlynReactNative.podspec +22 -0
- package/LICENSE +202 -0
- package/README.md +164 -2
- package/android/build.gradle +47 -0
- package/android/src/main/AndroidManifest.xml +3 -0
- package/android/src/main/kotlin/com/cavlyn/reactnative/CavlynReactNativeModule.kt +384 -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 +455 -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/http.ts
ADDED
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
import { parseQueryString } from './parser';
|
|
2
|
+
import type { EventApiPayload, FetchLike, ResolvedDynamicLink } from './types';
|
|
3
|
+
|
|
4
|
+
interface RawLinkResolveResponse {
|
|
5
|
+
id: string;
|
|
6
|
+
appId?: string;
|
|
7
|
+
projectId?: string;
|
|
8
|
+
shortCode: string;
|
|
9
|
+
customAlias?: string;
|
|
10
|
+
deepPath: string;
|
|
11
|
+
deepQuery?: string;
|
|
12
|
+
status: string;
|
|
13
|
+
expiresAt?: string;
|
|
14
|
+
campaignId?: string;
|
|
15
|
+
metadata?: Record<string, unknown>;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* Dependency-free HTTP transport for Cavlyn event ingestion and link resolution.
|
|
20
|
+
* Event delivery failures are non-fatal to the host mobile application, matching
|
|
21
|
+
* the iOS and Android native SDKs.
|
|
22
|
+
*/
|
|
23
|
+
export class HttpEventApi {
|
|
24
|
+
private readonly apiKey: string;
|
|
25
|
+
private readonly baseUrl: string;
|
|
26
|
+
private readonly timeoutMs: number;
|
|
27
|
+
private readonly fetchImpl: FetchLike;
|
|
28
|
+
private readonly debug: boolean;
|
|
29
|
+
|
|
30
|
+
constructor(options: {
|
|
31
|
+
apiKey: string;
|
|
32
|
+
apiBaseUrl: string;
|
|
33
|
+
timeoutMs: number;
|
|
34
|
+
fetch?: FetchLike;
|
|
35
|
+
debug?: boolean;
|
|
36
|
+
}) {
|
|
37
|
+
this.apiKey = options.apiKey;
|
|
38
|
+
this.baseUrl = options.apiBaseUrl.replace(/\/+$/, '');
|
|
39
|
+
this.timeoutMs = options.timeoutMs;
|
|
40
|
+
this.debug = Boolean(options.debug);
|
|
41
|
+
this.fetchImpl = options.fetch ?? (globalThis.fetch as unknown as FetchLike);
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* Sends an attribution or commerce event to `POST /api/v1/events`.
|
|
46
|
+
* Network failures are caught and swallowed so the host app never crashes.
|
|
47
|
+
*/
|
|
48
|
+
async sendEvent(payload: EventApiPayload, idempotencyKey: string): Promise<boolean> {
|
|
49
|
+
if (typeof this.fetchImpl !== 'function') {
|
|
50
|
+
if (this.debug) {
|
|
51
|
+
console.debug('[Cavlyn] fetch is unavailable in this runtime; event skipped');
|
|
52
|
+
}
|
|
53
|
+
return false;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
const controller = typeof AbortController !== 'undefined' ? new AbortController() : undefined;
|
|
57
|
+
const timer = controller
|
|
58
|
+
? setTimeout(() => controller.abort(), this.timeoutMs)
|
|
59
|
+
: undefined;
|
|
60
|
+
|
|
61
|
+
try {
|
|
62
|
+
const response = await this.fetchImpl(`${this.baseUrl}/api/v1/events`, {
|
|
63
|
+
method: 'POST',
|
|
64
|
+
headers: {
|
|
65
|
+
'Content-Type': 'application/json',
|
|
66
|
+
'X-API-Key': this.apiKey,
|
|
67
|
+
'Idempotency-Key': idempotencyKey,
|
|
68
|
+
},
|
|
69
|
+
body: JSON.stringify(payload),
|
|
70
|
+
signal: controller?.signal,
|
|
71
|
+
});
|
|
72
|
+
|
|
73
|
+
if (!response.ok && this.debug) {
|
|
74
|
+
console.debug(`[Cavlyn] Event delivery returned HTTP ${response.status}`);
|
|
75
|
+
}
|
|
76
|
+
return response.ok;
|
|
77
|
+
} catch (err) {
|
|
78
|
+
if (this.debug) {
|
|
79
|
+
console.debug('[Cavlyn] Event delivery failed (non-fatal):', err);
|
|
80
|
+
}
|
|
81
|
+
return false;
|
|
82
|
+
} finally {
|
|
83
|
+
if (timer !== undefined) {
|
|
84
|
+
clearTimeout(timer);
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* Resolves a short code, custom alias, or full dynamic link URL via `GET /api/v1/links/resolve`.
|
|
91
|
+
*/
|
|
92
|
+
async resolveLink(shortCodeOrUrl: string): Promise<ResolvedDynamicLink> {
|
|
93
|
+
const trimmed = shortCodeOrUrl.trim();
|
|
94
|
+
if (!trimmed) {
|
|
95
|
+
throw new Error('Cavlyn: shortCodeOrUrl is required to resolve a link');
|
|
96
|
+
}
|
|
97
|
+
if (typeof this.fetchImpl !== 'function') {
|
|
98
|
+
throw new Error('Cavlyn: fetch is unavailable in this runtime');
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
const controller = typeof AbortController !== 'undefined' ? new AbortController() : undefined;
|
|
102
|
+
const timer = controller
|
|
103
|
+
? setTimeout(() => controller.abort(), this.timeoutMs)
|
|
104
|
+
: undefined;
|
|
105
|
+
|
|
106
|
+
try {
|
|
107
|
+
const response = await this.fetchImpl(
|
|
108
|
+
`${this.baseUrl}/api/v1/links/resolve?code=${encodeURIComponent(trimmed)}`,
|
|
109
|
+
{
|
|
110
|
+
method: 'GET',
|
|
111
|
+
headers: {
|
|
112
|
+
'X-API-Key': this.apiKey,
|
|
113
|
+
},
|
|
114
|
+
signal: controller?.signal,
|
|
115
|
+
},
|
|
116
|
+
);
|
|
117
|
+
|
|
118
|
+
if (!response.ok) {
|
|
119
|
+
let message = response.statusText || 'Request failed';
|
|
120
|
+
try {
|
|
121
|
+
const body = (await response.json()) as { message?: string };
|
|
122
|
+
if (body && typeof body.message === 'string') {
|
|
123
|
+
message = body.message;
|
|
124
|
+
}
|
|
125
|
+
} catch {
|
|
126
|
+
// ignore non-JSON error body
|
|
127
|
+
}
|
|
128
|
+
throw new Error(`Cavlyn API GET /api/v1/links/resolve failed (${response.status}): ${message}`);
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
const raw = (await response.json()) as RawLinkResolveResponse;
|
|
132
|
+
const queryParams: Record<string, string> = {};
|
|
133
|
+
if (raw.deepQuery) {
|
|
134
|
+
for (const [k, v] of parseQueryString(raw.deepQuery)) {
|
|
135
|
+
queryParams[k] = v;
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
return {
|
|
140
|
+
id: raw.id,
|
|
141
|
+
appId: raw.appId ?? raw.projectId ?? '',
|
|
142
|
+
shortCode: raw.shortCode,
|
|
143
|
+
customAlias: raw.customAlias,
|
|
144
|
+
deepPath: raw.deepPath,
|
|
145
|
+
deepQuery: raw.deepQuery,
|
|
146
|
+
status: raw.status,
|
|
147
|
+
expiresAt: raw.expiresAt,
|
|
148
|
+
campaignId: raw.campaignId,
|
|
149
|
+
queryParams,
|
|
150
|
+
metadata: raw.metadata,
|
|
151
|
+
};
|
|
152
|
+
} finally {
|
|
153
|
+
if (timer !== undefined) {
|
|
154
|
+
clearTimeout(timer);
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
export { Cavlyn, CavlynClient, CavlynSDK } from './client';
|
|
2
|
+
export {
|
|
3
|
+
useCavlynLink,
|
|
4
|
+
useCavlynTrackEvent,
|
|
5
|
+
type UseCavlynLinkResult,
|
|
6
|
+
type UseCavlynTrackEventResult,
|
|
7
|
+
} from './hooks';
|
|
8
|
+
export {
|
|
9
|
+
extractPath,
|
|
10
|
+
extractUtmParameters,
|
|
11
|
+
fromNativeLinkPayload,
|
|
12
|
+
generateUuid,
|
|
13
|
+
normalizeUuid,
|
|
14
|
+
parseDynamicLink,
|
|
15
|
+
parseQueryString,
|
|
16
|
+
} from './parser';
|
|
17
|
+
export { DeepLinkRepository, MemoryStorage } from './storage';
|
|
18
|
+
export { HttpEventApi } from './http';
|
|
19
|
+
export { NATIVE_LINK_EVENT } from './nativeBridge';
|
|
20
|
+
export type {
|
|
21
|
+
AttributionEventType,
|
|
22
|
+
CavlynConfiguration,
|
|
23
|
+
CavlynEventType,
|
|
24
|
+
CavlynNativeModule,
|
|
25
|
+
CavlynPlatformName,
|
|
26
|
+
CavlynStorage,
|
|
27
|
+
CommerceEventInput,
|
|
28
|
+
CommerceEventType,
|
|
29
|
+
DynamicLink,
|
|
30
|
+
EventApiPayload,
|
|
31
|
+
FetchLike,
|
|
32
|
+
LinkListener,
|
|
33
|
+
LinkSubscription,
|
|
34
|
+
NativeLinkPayload,
|
|
35
|
+
ResolvedDynamicLink,
|
|
36
|
+
TrackEventOptions,
|
|
37
|
+
UtmParameters,
|
|
38
|
+
} from './types';
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
import type { CavlynNativeModule, CavlynPlatformName, LinkSubscription, NativeLinkPayload } from './types';
|
|
2
|
+
|
|
3
|
+
declare const require: (id: string) => unknown;
|
|
4
|
+
|
|
5
|
+
export const NATIVE_LINK_EVENT = 'CavlynLinkReceived';
|
|
6
|
+
|
|
7
|
+
interface ReactNativeRuntime {
|
|
8
|
+
NativeModules?: {
|
|
9
|
+
CavlynReactNative?: CavlynNativeModule;
|
|
10
|
+
};
|
|
11
|
+
NativeEventEmitter?: new (nativeModule: unknown) => {
|
|
12
|
+
addListener(eventType: string, listener: (payload: NativeLinkPayload) => void): LinkSubscription;
|
|
13
|
+
};
|
|
14
|
+
Linking?: {
|
|
15
|
+
getInitialURL(): Promise<string | null>;
|
|
16
|
+
addEventListener(type: 'url', handler: (event: { url: string }) => void): LinkSubscription;
|
|
17
|
+
};
|
|
18
|
+
Platform?: {
|
|
19
|
+
OS?: string;
|
|
20
|
+
};
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
let cachedRuntime: ReactNativeRuntime | null | undefined;
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* Lazily loads `react-native` if available in the host bundle.
|
|
27
|
+
* Returns `null` cleanly in Node.js unit tests or non-RN environments.
|
|
28
|
+
*/
|
|
29
|
+
export function loadReactNativeRuntime(): ReactNativeRuntime | null {
|
|
30
|
+
if (cachedRuntime !== undefined) {
|
|
31
|
+
return cachedRuntime;
|
|
32
|
+
}
|
|
33
|
+
try {
|
|
34
|
+
// Must be a literal `require('react-native')` call: Metro only resolves statically visible
|
|
35
|
+
// require calls, so an aliased/dynamic require silently fails inside real RN bundles.
|
|
36
|
+
// The try/catch keeps Node.js (unit tests, SSR) working when react-native is absent.
|
|
37
|
+
// eslint-disable-next-line @typescript-eslint/no-var-requires
|
|
38
|
+
cachedRuntime = require('react-native') as ReactNativeRuntime;
|
|
39
|
+
} catch {
|
|
40
|
+
cachedRuntime = null;
|
|
41
|
+
}
|
|
42
|
+
return cachedRuntime;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* Returns the linked native Cavlyn module if installed in a bare RN or Expo Dev Client build.
|
|
47
|
+
*/
|
|
48
|
+
export function getNativeModule(): CavlynNativeModule | null {
|
|
49
|
+
const rn = loadReactNativeRuntime();
|
|
50
|
+
return rn?.NativeModules?.CavlynReactNative ?? null;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* Detects the host platform (`IOS`, `ANDROID`, or `WEB`).
|
|
55
|
+
*/
|
|
56
|
+
export function detectPlatform(): CavlynPlatformName {
|
|
57
|
+
const os = loadReactNativeRuntime()?.Platform?.OS?.toLowerCase();
|
|
58
|
+
if (os === 'ios') return 'IOS';
|
|
59
|
+
if (os === 'android') return 'ANDROID';
|
|
60
|
+
if (os === 'web') return 'WEB';
|
|
61
|
+
return 'IOS';
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* Subscribes to native `CavlynLinkReceived` events if `NativeEventEmitter` is available.
|
|
66
|
+
*/
|
|
67
|
+
export function subscribeNativeLinkEvents(
|
|
68
|
+
nativeModule: CavlynNativeModule,
|
|
69
|
+
listener: (payload: NativeLinkPayload) => void,
|
|
70
|
+
): LinkSubscription | null {
|
|
71
|
+
const rn = loadReactNativeRuntime();
|
|
72
|
+
if (!rn?.NativeEventEmitter) return null;
|
|
73
|
+
try {
|
|
74
|
+
const emitter = new rn.NativeEventEmitter(nativeModule);
|
|
75
|
+
return emitter.addListener(NATIVE_LINK_EVENT, listener);
|
|
76
|
+
} catch {
|
|
77
|
+
return null;
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* Fetches the initial launch URL via React Native's `Linking.getInitialURL()`.
|
|
83
|
+
*/
|
|
84
|
+
export async function getLinkingInitialUrl(): Promise<string | null> {
|
|
85
|
+
const rn = loadReactNativeRuntime();
|
|
86
|
+
if (!rn?.Linking?.getInitialURL) return null;
|
|
87
|
+
try {
|
|
88
|
+
return await rn.Linking.getInitialURL();
|
|
89
|
+
} catch {
|
|
90
|
+
return null;
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* Subscribes to incoming URL events via React Native's `Linking.addEventListener('url', ...)`.
|
|
96
|
+
*/
|
|
97
|
+
export function subscribeLinkingUrls(listener: (url: string) => void): LinkSubscription | null {
|
|
98
|
+
const rn = loadReactNativeRuntime();
|
|
99
|
+
if (!rn?.Linking?.addEventListener) return null;
|
|
100
|
+
try {
|
|
101
|
+
return rn.Linking.addEventListener('url', (event) => {
|
|
102
|
+
if (event && typeof event.url === 'string') {
|
|
103
|
+
listener(event.url);
|
|
104
|
+
}
|
|
105
|
+
});
|
|
106
|
+
} catch {
|
|
107
|
+
return null;
|
|
108
|
+
}
|
|
109
|
+
}
|
package/src/parser.ts
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
import type { DynamicLink, NativeLinkPayload, UtmParameters } from './types';
|
|
2
|
+
|
|
3
|
+
const UUID_REGEX = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
4
|
+
const LINK_ID_KEYS = new Set(['linkId', 'link_id']);
|
|
5
|
+
const CLICK_ID_KEYS = new Set(['clickId', 'click_id']);
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Validates and normalizes a UUID string to lowercase, or returns `undefined` if invalid.
|
|
9
|
+
*/
|
|
10
|
+
export function normalizeUuid(value: string | null | undefined): string | undefined {
|
|
11
|
+
if (!value) return undefined;
|
|
12
|
+
const trimmed = value.trim();
|
|
13
|
+
return UUID_REGEX.test(trimmed) ? trimmed.toLowerCase() : undefined;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* Generates an RFC 4122 v4 UUID compatible across Node.js, Hermes, JSC, and browsers.
|
|
18
|
+
*/
|
|
19
|
+
export function generateUuid(): string {
|
|
20
|
+
const cryptoObj = (globalThis as {
|
|
21
|
+
crypto?: {
|
|
22
|
+
randomUUID?: () => string;
|
|
23
|
+
getRandomValues?: (arr: Uint8Array) => Uint8Array;
|
|
24
|
+
};
|
|
25
|
+
}).crypto;
|
|
26
|
+
|
|
27
|
+
if (cryptoObj && typeof cryptoObj.randomUUID === 'function') {
|
|
28
|
+
return cryptoObj.randomUUID().toLowerCase();
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
const bytes = new Uint8Array(16);
|
|
32
|
+
if (cryptoObj && typeof cryptoObj.getRandomValues === 'function') {
|
|
33
|
+
cryptoObj.getRandomValues(bytes);
|
|
34
|
+
} else {
|
|
35
|
+
for (let i = 0; i < 16; i += 1) {
|
|
36
|
+
bytes[i] = Math.floor(Math.random() * 256);
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
// RFC 4122 version 4 and variant bits
|
|
41
|
+
bytes[6] = (bytes[6] & 0x0f) | 0x40;
|
|
42
|
+
bytes[8] = (bytes[8] & 0x3f) | 0x80;
|
|
43
|
+
|
|
44
|
+
const hex = Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join('');
|
|
45
|
+
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* Safely decodes a URL query component (`+` -> space, percent-encoding).
|
|
50
|
+
*/
|
|
51
|
+
function safeDecode(raw: string): string {
|
|
52
|
+
try {
|
|
53
|
+
return decodeURIComponent(raw.replace(/\+/g, ' '));
|
|
54
|
+
} catch {
|
|
55
|
+
return raw;
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* Parses a query string (with or without leading `?`) into key/value entries.
|
|
61
|
+
*/
|
|
62
|
+
export function parseQueryString(query: string): Array<[string, string]> {
|
|
63
|
+
const cleaned = query.startsWith('?') ? query.slice(1) : query;
|
|
64
|
+
if (!cleaned) return [];
|
|
65
|
+
|
|
66
|
+
const entries: Array<[string, string]> = [];
|
|
67
|
+
for (const part of cleaned.split('&')) {
|
|
68
|
+
if (!part) continue;
|
|
69
|
+
const eqIndex = part.indexOf('=');
|
|
70
|
+
if (eqIndex === -1) {
|
|
71
|
+
entries.push([safeDecode(part), '']);
|
|
72
|
+
} else {
|
|
73
|
+
const key = safeDecode(part.slice(0, eqIndex));
|
|
74
|
+
const value = safeDecode(part.slice(eqIndex + 1));
|
|
75
|
+
entries.push([key, value]);
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
return entries;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* Extracts a normalized leading-slash path from HTTP(S) and custom scheme URLs.
|
|
83
|
+
*
|
|
84
|
+
* Examples:
|
|
85
|
+
* - `https://go.brand.com/products/42?linkId=...` -> `/products/42`
|
|
86
|
+
* - `https://go.brand.com?linkId=...` -> `/`
|
|
87
|
+
* - `myapp://products/42?linkId=...` -> `/products/42`
|
|
88
|
+
*/
|
|
89
|
+
export function extractPath(uri: string): string {
|
|
90
|
+
const withoutHash = uri.split('#', 1)[0];
|
|
91
|
+
const withoutQuery = withoutHash.split('?', 1)[0];
|
|
92
|
+
const schemeMatch = /^([a-zA-Z][a-zA-Z0-9+.-]*):\/\/(.*)$/.exec(withoutQuery);
|
|
93
|
+
|
|
94
|
+
if (!schemeMatch) {
|
|
95
|
+
return withoutQuery.startsWith('/') ? withoutQuery : `/${withoutQuery}`;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
const scheme = schemeMatch[1].toLowerCase();
|
|
99
|
+
const remainder = schemeMatch[2];
|
|
100
|
+
|
|
101
|
+
if (scheme === 'http' || scheme === 'https') {
|
|
102
|
+
const slashIdx = remainder.indexOf('/');
|
|
103
|
+
if (slashIdx === -1) return '/';
|
|
104
|
+
const path = remainder.slice(slashIdx);
|
|
105
|
+
return path || '/';
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
// Custom URL scheme (e.g. myapp://products/42 -> /products/42)
|
|
109
|
+
const trimmed = remainder.replace(/^\/+/, '');
|
|
110
|
+
return trimmed ? `/${trimmed}` : '/';
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/**
|
|
114
|
+
* Extracts standard UTM parameters from a parameter map.
|
|
115
|
+
*/
|
|
116
|
+
export function extractUtmParameters(parameters: Record<string, string>): UtmParameters {
|
|
117
|
+
const utm: UtmParameters = {};
|
|
118
|
+
if (parameters.utm_source) utm.source = parameters.utm_source;
|
|
119
|
+
if (parameters.utm_medium) utm.medium = parameters.utm_medium;
|
|
120
|
+
if (parameters.utm_campaign) utm.campaign = parameters.utm_campaign;
|
|
121
|
+
if (parameters.utm_term) utm.term = parameters.utm_term;
|
|
122
|
+
if (parameters.utm_content) utm.content = parameters.utm_content;
|
|
123
|
+
return utm;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/**
|
|
127
|
+
* Parses an incoming Universal Link, Android App Link, or custom URL scheme
|
|
128
|
+
* carrying a backend-issued `linkId` (or `link_id`).
|
|
129
|
+
*
|
|
130
|
+
* Returns `null` if the URL is empty or does not contain a valid UUID `linkId`.
|
|
131
|
+
*/
|
|
132
|
+
export function parseDynamicLink(url: string | null | undefined): DynamicLink | null {
|
|
133
|
+
if (!url || typeof url !== 'string') return null;
|
|
134
|
+
const trimmed = url.trim();
|
|
135
|
+
if (!trimmed) return null;
|
|
136
|
+
|
|
137
|
+
const withoutHash = trimmed.split('#', 1)[0];
|
|
138
|
+
const queryStart = withoutHash.indexOf('?');
|
|
139
|
+
if (queryStart === -1) return null;
|
|
140
|
+
|
|
141
|
+
const entries = parseQueryString(withoutHash.slice(queryStart + 1));
|
|
142
|
+
|
|
143
|
+
let linkId: string | undefined;
|
|
144
|
+
let clickId: string | undefined;
|
|
145
|
+
const parameters: Record<string, string> = {};
|
|
146
|
+
|
|
147
|
+
for (const [key, value] of entries) {
|
|
148
|
+
if (LINK_ID_KEYS.has(key)) {
|
|
149
|
+
if (!linkId) {
|
|
150
|
+
linkId = normalizeUuid(value);
|
|
151
|
+
}
|
|
152
|
+
} else if (CLICK_ID_KEYS.has(key)) {
|
|
153
|
+
if (!clickId) {
|
|
154
|
+
clickId = normalizeUuid(value);
|
|
155
|
+
}
|
|
156
|
+
} else {
|
|
157
|
+
parameters[key] = value;
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
if (!linkId) {
|
|
162
|
+
return null;
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
return {
|
|
166
|
+
uri: trimmed,
|
|
167
|
+
path: extractPath(trimmed),
|
|
168
|
+
linkId,
|
|
169
|
+
...(clickId ? { clickId } : {}),
|
|
170
|
+
parameters,
|
|
171
|
+
utm: extractUtmParameters(parameters),
|
|
172
|
+
};
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
/**
|
|
176
|
+
* Converts a native bridge payload (from iOS Swift or Android Kotlin) into a typed `DynamicLink`.
|
|
177
|
+
*/
|
|
178
|
+
export function fromNativeLinkPayload(payload: NativeLinkPayload | null | undefined): DynamicLink | null {
|
|
179
|
+
if (!payload || !payload.uri || !payload.linkId) return null;
|
|
180
|
+
|
|
181
|
+
const linkId = normalizeUuid(payload.linkId);
|
|
182
|
+
if (!linkId) return null;
|
|
183
|
+
|
|
184
|
+
const clickId = normalizeUuid(payload.clickId ?? undefined);
|
|
185
|
+
const parameters: Record<string, string> = {};
|
|
186
|
+
if (payload.parameters) {
|
|
187
|
+
for (const [k, v] of Object.entries(payload.parameters)) {
|
|
188
|
+
if (v !== undefined && v !== null) {
|
|
189
|
+
parameters[k] = String(v);
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
return {
|
|
195
|
+
uri: payload.uri,
|
|
196
|
+
path: extractPath(payload.uri),
|
|
197
|
+
linkId,
|
|
198
|
+
...(clickId ? { clickId } : {}),
|
|
199
|
+
parameters,
|
|
200
|
+
utm: extractUtmParameters(parameters),
|
|
201
|
+
};
|
|
202
|
+
}
|
package/src/storage.ts
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
import { generateUuid, parseDynamicLink } from './parser';
|
|
2
|
+
import type { CavlynStorage, DynamicLink } from './types';
|
|
3
|
+
|
|
4
|
+
const KEYS = {
|
|
5
|
+
INITIAL_URI: 'com.cavlyn.sdk.initial_uri',
|
|
6
|
+
CURRENT_URI: 'com.cavlyn.sdk.current_uri',
|
|
7
|
+
INSTALLATION_ID: 'com.cavlyn.sdk.installation_id',
|
|
8
|
+
} as const;
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* Default in-memory storage adapter used when no persistent adapter
|
|
12
|
+
* (such as AsyncStorage or MMKV) is supplied in pure JS/Expo Go runtimes.
|
|
13
|
+
*/
|
|
14
|
+
export class MemoryStorage implements CavlynStorage {
|
|
15
|
+
private readonly store = new Map<string, string>();
|
|
16
|
+
|
|
17
|
+
getItem(key: string): string | null {
|
|
18
|
+
return this.store.has(key) ? this.store.get(key)! : null;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
setItem(key: string, value: string): void {
|
|
22
|
+
this.store.set(key, value);
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
removeItem(key: string): void {
|
|
26
|
+
this.store.delete(key);
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
clear(): void {
|
|
30
|
+
this.store.clear();
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* Persists first-touch (`initial`) and latest (`current`) attribution links
|
|
36
|
+
* plus the stable per-installation UUID.
|
|
37
|
+
*/
|
|
38
|
+
export class DeepLinkRepository {
|
|
39
|
+
constructor(private readonly storage: CavlynStorage) {}
|
|
40
|
+
|
|
41
|
+
async readInitial(): Promise<DynamicLink | null> {
|
|
42
|
+
const uri = await this.storage.getItem(KEYS.INITIAL_URI);
|
|
43
|
+
return parseDynamicLink(uri);
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
async saveInitial(link: DynamicLink): Promise<void> {
|
|
47
|
+
await this.storage.setItem(KEYS.INITIAL_URI, link.uri);
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
async readCurrent(): Promise<DynamicLink | null> {
|
|
51
|
+
const uri = await this.storage.getItem(KEYS.CURRENT_URI);
|
|
52
|
+
return parseDynamicLink(uri);
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
async saveCurrent(link: DynamicLink): Promise<void> {
|
|
56
|
+
await this.storage.setItem(KEYS.CURRENT_URI, link.uri);
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
async getOrCreateInstallationId(): Promise<string> {
|
|
60
|
+
const existing = await this.storage.getItem(KEYS.INSTALLATION_ID);
|
|
61
|
+
if (existing && existing.trim().length > 0) {
|
|
62
|
+
return existing.trim();
|
|
63
|
+
}
|
|
64
|
+
const fresh = generateUuid();
|
|
65
|
+
await this.storage.setItem(KEYS.INSTALLATION_ID, fresh);
|
|
66
|
+
return fresh;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
async clear(): Promise<void> {
|
|
70
|
+
await Promise.all([
|
|
71
|
+
this.storage.removeItem(KEYS.INITIAL_URI),
|
|
72
|
+
this.storage.removeItem(KEYS.CURRENT_URI),
|
|
73
|
+
this.storage.removeItem(KEYS.INSTALLATION_ID),
|
|
74
|
+
]);
|
|
75
|
+
}
|
|
76
|
+
}
|