44 lines
1.4 KiB
TypeScript
44 lines
1.4 KiB
TypeScript
/** 浏览器会话内稳定的旅程 sessionId(WM-O1-KR1-02) */
|
||
const SESSION_KEY = "wz_journey_sid"
|
||
/** 跨会话匿名设备 ID(未登录也可上报旅程) */
|
||
const ANON_KEY = "wz_anon_id"
|
||
|
||
export function getOrCreateJourneySessionId(): string {
|
||
if (typeof window === "undefined") return "ssr"
|
||
try {
|
||
let sid = sessionStorage.getItem(SESSION_KEY)
|
||
if (!sid) {
|
||
sid =
|
||
typeof crypto !== "undefined" && "randomUUID" in crypto
|
||
? crypto.randomUUID()
|
||
: `wz_${Date.now()}_${Math.random().toString(36).slice(2, 12)}`
|
||
sessionStorage.setItem(SESSION_KEY, sid)
|
||
}
|
||
return sid
|
||
} catch {
|
||
return `wz_fallback_${Date.now()}`
|
||
}
|
||
}
|
||
|
||
export function newJourneyClientEventId(): string {
|
||
if (typeof crypto !== "undefined" && "randomUUID" in crypto) return crypto.randomUUID()
|
||
return `evt_${Date.now()}_${Math.random().toString(36).slice(2, 12)}`
|
||
}
|
||
|
||
export function getOrCreateAnonymousId(): string {
|
||
if (typeof window === "undefined") return "ssr"
|
||
try {
|
||
let id = localStorage.getItem(ANON_KEY)
|
||
if (!id) {
|
||
id =
|
||
typeof crypto !== "undefined" && "randomUUID" in crypto
|
||
? `anon_${crypto.randomUUID()}`
|
||
: `anon_${Date.now()}_${Math.random().toString(36).slice(2, 12)}`
|
||
localStorage.setItem(ANON_KEY, id)
|
||
}
|
||
return id.slice(0, 128)
|
||
} catch {
|
||
return `anon_fallback_${Date.now()}`
|
||
}
|
||
}
|