Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ref(utils): Improve uuid generation #5426

Merged
merged 4 commits into from
Jul 22, 2022
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
44 changes: 15 additions & 29 deletions packages/utils/src/misc.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,47 +12,33 @@ interface MsCryptoWindow extends Window {
msCrypto?: Crypto;
}

/** Many browser now support native uuid v4 generation */
interface CryptoWithRandomUUID extends Crypto {
randomUUID?(): string;
}

/**
* UUID4 generator
*
* @returns string Generated UUID4.
*/
export function uuid4(): string {
const global = getGlobalObject() as MsCryptoWindow;
const crypto = global.crypto || global.msCrypto;
const crypto = (global.crypto || global.msCrypto) as CryptoWithRandomUUID;

if (!(crypto === void 0) && crypto.getRandomValues) {
// Use window.crypto API if available
const arr = new Uint16Array(8);
crypto.getRandomValues(arr);

// set 4 in byte 7
// eslint-disable-next-line no-bitwise
arr[3] = (arr[3] & 0xfff) | 0x4000;
// set 2 most significant bits of byte 9 to '10'
// eslint-disable-next-line no-bitwise
arr[4] = (arr[4] & 0x3fff) | 0x8000;
if (crypto && crypto.randomUUID) {
return crypto.randomUUID().replace(/-/g, '');
}

const pad = (num: number): string => {
let v = num.toString(16);
while (v.length < 4) {
v = `0${v}`;
}
return v;
};
const getRandomByte =
crypto && crypto.getRandomValues ? () => crypto.getRandomValues(new Uint8Array(1))[0] : () => Math.random() * 16;

return (
pad(arr[0]) + pad(arr[1]) + pad(arr[2]) + pad(arr[3]) + pad(arr[4]) + pad(arr[5]) + pad(arr[6]) + pad(arr[7])
);
}
// http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#2117523
return 'xxxxxxxxxxxx4xxxyxxxxxxxxxxxxxxx'.replace(/[xy]/g, c => {
// eslint-disable-next-line no-bitwise
const r = (Math.random() * 16) | 0;
// Concatenating the following numbers as strings results in '10000000100040008000100000000000'
return (([1e7] as unknown as string) + 1e3 + 4e3 + 8e3 + 1e11).replace(/[018]/g, c =>
// eslint-disable-next-line no-bitwise
const v = c === 'x' ? r : (r & 0x3) | 0x8;
return v.toString(16);
});
((c as unknown as number) ^ ((getRandomByte() & 15) >> ((c as unknown as number) / 4))).toString(16),
);
}

/**
Expand Down