* 降级 GUID 生成实现 * * Fallback GUID generation using crypto.getRandomValues or Math.random.
()
| 38 | * Fallback GUID generation using crypto.getRandomValues or Math.random. |
| 39 | */ |
| 40 | function generateGUIDFallback(): string { |
| 41 | // 尝试使用 crypto.getRandomValues |
| 42 | if (typeof crypto !== 'undefined' && typeof crypto.getRandomValues === 'function') { |
| 43 | const bytes = new Uint8Array(16); |
| 44 | crypto.getRandomValues(bytes); |
| 45 | |
| 46 | // 设置版本号 (version 4) |
| 47 | bytes[6] = (bytes[6]! & 0x0f) | 0x40; |
| 48 | // 设置变体 (variant 1) |
| 49 | bytes[8] = (bytes[8]! & 0x3f) | 0x80; |
| 50 | |
| 51 | return formatUUID(bytes); |
| 52 | } |
| 53 | |
| 54 | // 最终降级:使用 Math.random(不推荐,但可用) |
| 55 | return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => { |
| 56 | const r = (Math.random() * 16) | 0; |
| 57 | const v = c === 'x' ? r : (r & 0x3) | 0x8; |
| 58 | return v.toString(16); |
| 59 | }); |
| 60 | } |
| 61 | |
| 62 | /** |
| 63 | * 格式化 16 字节数组为 UUID 字符串 |
no test coverage detected