Files
syops/frontend/src/shared/utils/id.ts
T
runny 91b7233872 Merge branch 'dev' into runny827
feat(training): 新增精益培训视频与周任务管理

# Conflicts:
#	backend/app/models/__init__.py
2026-09-08 18:30:09 +08:00

30 lines
1.5 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* shared/utils/id.ts
* 用途:生成客户端随机 ID(会话号、operation_id、幂等键等)。
* 依赖:Web Crypto(优先);无安全上下文时回退到 getRandomValues / Math.random。
* 逻辑:HTTP 内网(如 192.168.x)不是 secure context,`crypto.randomUUID` 不可用,
* 直接调用会在 Vue setup 阶段抛 TypeError 导致白屏;统一走本工具避免分叉。
*/
/**
* 生成 UUID 风格随机串;优先 `crypto.randomUUID`,HTTP 等非安全上下文自动降级。
* 核心逻辑:secure context 用原生 API;否则用 getRandomValues 拼 RFC4122 v4;再不行用时间戳+随机。
* @returns 形如 `xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx` 的字符串(降级路径不保证密码学强度)
*/
export function createRandomUuid(): string {
const webCrypto = globalThis.crypto;
if (webCrypto && typeof webCrypto.randomUUID === 'function') {
return webCrypto.randomUUID();
}
if (webCrypto && typeof webCrypto.getRandomValues === 'function') {
const bytes = new Uint8Array(16);
webCrypto.getRandomValues(bytes);
// noUncheckedIndexedAccess 下 Uint8Array 下标为 number | undefined
bytes[6] = ((bytes[6] ?? 0) & 0x0f) | 0x40;
bytes[8] = ((bytes[8] ?? 0) & 0x3f) | 0x80;
const hex = Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join('');
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
}
return `fallback-${Date.now().toString(16)}-${Math.random().toString(16).slice(2, 10)}`;
}