86 lines
2.2 KiB
TypeScript
86 lines
2.2 KiB
TypeScript
export const START_PARAM_SEPARATOR = '!';
|
|
const REF_STORAGE_KEY = 'ref_id';
|
|
|
|
type StartPayload = {
|
|
contentId: string | null;
|
|
referralId: string | null;
|
|
};
|
|
|
|
const safeSessionStorage = (): Storage | null => {
|
|
if (typeof window === 'undefined') {
|
|
return null;
|
|
}
|
|
try {
|
|
return window.sessionStorage;
|
|
} catch (error) {
|
|
return null;
|
|
}
|
|
};
|
|
|
|
export const resolveStartPayload = (): StartPayload => {
|
|
if (typeof window === 'undefined') {
|
|
return { contentId: null, referralId: null };
|
|
}
|
|
|
|
const searchParams = new URLSearchParams(window.location.search);
|
|
const telegramApp = (window as any)?.Telegram?.WebApp;
|
|
const rawStartParam = telegramApp?.initDataUnsafe?.start_param ?? null;
|
|
|
|
let contentId: string | null = null;
|
|
let referralId: string | null = null;
|
|
|
|
const parsePayload = (payload: string | null) => {
|
|
if (!payload) {
|
|
return;
|
|
}
|
|
const [contentPart, refPart] = payload.split(START_PARAM_SEPARATOR, 2);
|
|
if (contentPart) {
|
|
contentId = contentPart;
|
|
}
|
|
if (refPart) {
|
|
referralId = refPart;
|
|
}
|
|
};
|
|
|
|
parsePayload(rawStartParam);
|
|
|
|
if (!contentId) {
|
|
const queryContent =
|
|
searchParams.get('content') ||
|
|
searchParams.get('cid') ||
|
|
searchParams.get('start_param');
|
|
if (queryContent) {
|
|
contentId = queryContent;
|
|
}
|
|
}
|
|
|
|
if (!referralId) {
|
|
const queryRef = searchParams.get('ref') || searchParams.get('ref_id');
|
|
if (queryRef) {
|
|
referralId = queryRef;
|
|
}
|
|
}
|
|
|
|
const storage = safeSessionStorage();
|
|
if (storage) {
|
|
if (referralId) {
|
|
storage.setItem(REF_STORAGE_KEY, referralId);
|
|
} else {
|
|
const stored = storage.getItem(REF_STORAGE_KEY);
|
|
if (stored) {
|
|
referralId = stored;
|
|
}
|
|
}
|
|
}
|
|
|
|
return { contentId, referralId };
|
|
};
|
|
|
|
export const appendReferral = <T extends Record<string, unknown>>(payload: T): T => {
|
|
const { referralId } = resolveStartPayload();
|
|
if (referralId && !payload.ref_id) {
|
|
return { ...payload, ref_id: referralId } as T;
|
|
}
|
|
return payload;
|
|
};
|