liding
昨天 303d42574231d0cc57f18a736bf8047d158233ce
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// HTTP 内网地址没有原生 randomUUID;getRandomValues 在该环境下仍可用。
// 此函数也会被构建插件注入文档 Worker,必须保持无外部依赖。
export function installCryptoRandomUUID() {
  const crypto = globalThis.crypto
  if (!crypto || typeof crypto.randomUUID === 'function') return
  if (typeof crypto.getRandomValues !== 'function') {
    throw new Error('当前浏览器不支持安全随机数,请升级浏览器后重试')
  }
  Object.defineProperty(crypto, 'randomUUID', {
    configurable: true,
    writable: true,
    value() {
      const bytes = crypto.getRandomValues(new Uint8Array(16))
      bytes[6] = (bytes[6] & 0x0f) | 0x40
      bytes[8] = (bytes[8] & 0x3f) | 0x80
      const hex = Array.from(bytes, byte => byte.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)}`
    }
  })
}