forked from elizaOS/eliza
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathuuid.ts
59 lines (50 loc) · 1.79 KB
/
uuid.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
import { sha1 } from "js-sha1";
import { UUID } from "./types.ts";
import { z } from "zod";
export const uuidSchema = z.string().uuid() as z.ZodType<UUID>;
export function validateUuid(value: unknown): UUID | null {
const result = uuidSchema.safeParse(value);
return result.success ? result.data : null;
}
export function stringToUuid(target: string | number): UUID {
if (typeof target === "number") {
target = (target as number).toString();
}
if (typeof target !== "string") {
throw TypeError("Value must be string");
}
const _uint8ToHex = (ubyte: number): string => {
const first = ubyte >> 4;
const second = ubyte - (first << 4);
const HEX_DIGITS = "0123456789abcdef".split("");
return HEX_DIGITS[first] + HEX_DIGITS[second];
};
const _uint8ArrayToHex = (buf: Uint8Array): string => {
let out = "";
for (let i = 0; i < buf.length; i++) {
out += _uint8ToHex(buf[i]);
}
return out;
};
const escapedStr = encodeURIComponent(target);
const buffer = new Uint8Array(escapedStr.length);
for (let i = 0; i < escapedStr.length; i++) {
buffer[i] = escapedStr[i].charCodeAt(0);
}
const hash = sha1(buffer);
const hashBuffer = new Uint8Array(hash.length / 2);
for (let i = 0; i < hash.length; i += 2) {
hashBuffer[i / 2] = parseInt(hash.slice(i, i + 2), 16);
}
return (_uint8ArrayToHex(hashBuffer.slice(0, 4)) +
"-" +
_uint8ArrayToHex(hashBuffer.slice(4, 6)) +
"-" +
_uint8ToHex(hashBuffer[6] & 0x0f) +
_uint8ToHex(hashBuffer[7]) +
"-" +
_uint8ToHex((hashBuffer[8] & 0x3f) | 0x80) +
_uint8ToHex(hashBuffer[9]) +
"-" +
_uint8ArrayToHex(hashBuffer.slice(10, 16))) as UUID;
}