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

fix(uuid): update uuid.ts based on JS implementation #852

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 11 additions & 24 deletions packages/analytics-core/src/utils/uuid.ts
Original file line number Diff line number Diff line change
@@ -1,32 +1,19 @@
/**
* Source: [jed's gist]{@link https://gist.github.com/982883}.
* Source: [jed's gist's comment]{@link https://gist.github.com/jed/982883?permalink_comment_id=3223002#gistcomment-3223002}.
* Returns a random v4 UUID of the form xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx,
* where each x is replaced with a random hexadecimal digit from 0 to f, and
* y is replaced with a random hexadecimal digit from 8 to b.
* Used to generate UUIDs for deviceIds.
* @private
*/
export const UUID = function (a?: any): string {
return a // if the placeholder was passed, return
? // a random number from 0 to 15
(
a ^ // unless b is 8,
((Math.random() * // in which case
16) >> // a random number from
(a / 4))
) // 8 to 11
.toString(16) // in hexadecimal
: // or otherwise a concatenated string:
(
String(1e7) + // 10000000 +
String(-1e3) + // -1000 +
String(-4e3) + // -4000 +
String(-8e3) + // -80000000 +
String(-1e11)
) // -100000000000,
.replace(
// replacing
/[018]/g, // zeroes, ones, and eights with
UUID, // random hex digits
);

const hex: string[] = [...Array(256).keys()].map((index) => index.toString(16).padStart(2, '0'));

export const UUID = (): string => {
const r = crypto.getRandomValues(new Uint8Array(16));

r[6] = (r[6] & 0x0f) | 0x40;
r[8] = (r[8] & 0x3f) | 0x80;

return [...r.entries()].map(([index, int]) => ([4, 6, 8, 10].includes(index) ? `-${hex[int]}` : hex[int])).join('');
};
Loading