UNPKG

@datadayrepos/js-id-web

Version:

Utils for generating identifiers in javascript browser environment. Using web crypto engine for random number generation.

46 lines (45 loc) 1.39 kB
import { computeSHA256String } from '../hash/index.js'; export function randInt3() { const randomArray = new Uint8Array(3); window.crypto.getRandomValues(randomArray); return (randomArray[0] << 16) + (randomArray[1] << 8) + randomArray[2]; } export function randInt2() { const randomArray = new Uint8Array(2); window.crypto.getRandomValues(randomArray); return (randomArray[0] << 8) + randomArray[1]; } export function randInt1() { const randomArray = new Uint8Array(1); window.crypto.getRandomValues(randomArray); return randomArray[0]; } export function getEnvironmentMachineID() { const id = navigator.userAgent; return id || String(randInt3()); } export async function getProcessID() { const dpr = window.devicePixelRatio; const tz = Intl.DateTimeFormat().resolvedOptions().timeZone; const l = navigator.language; const rawid = `${dpr}|${tz}|${l}`; const hash = await computeSHA256String(rawid, 2); const id = (hash[0] << 8) + hash[1]; return id || randInt2(); } export class TextEncoderPolyfill { constructor() { this.encoder = new TextEncoder(); } encode(str) { return this.encoder.encode(str); } } export class TextDecoderPolyfill { constructor() { this.decoder = new TextDecoder(); } decode(uint8Array) { return this.decoder.decode(uint8Array); } }