UNPKG

1.66 kBJavaScriptView Raw
1import stringify from './stringify.js';
2import parse from './parse.js';
3
4function stringToBytes(str) {
5 str = unescape(encodeURIComponent(str)); // UTF8 escape
6
7 const bytes = [];
8
9 for (let i = 0; i < str.length; ++i) {
10 bytes.push(str.charCodeAt(i));
11 }
12
13 return bytes;
14}
15
16export const DNS = '6ba7b810-9dad-11d1-80b4-00c04fd430c8';
17export const URL = '6ba7b811-9dad-11d1-80b4-00c04fd430c8';
18export default function (name, version, hashfunc) {
19 function generateUUID(value, namespace, buf, offset) {
20 if (typeof value === 'string') {
21 value = stringToBytes(value);
22 }
23
24 if (typeof namespace === 'string') {
25 namespace = parse(namespace);
26 }
27
28 if (namespace.length !== 16) {
29 throw TypeError('Namespace must be array-like (16 iterable integer values, 0-255)');
30 } // Compute hash of namespace and value, Per 4.3
31 // Future: Use spread syntax when supported on all platforms, e.g. `bytes =
32 // hashfunc([...namespace, ... value])`
33
34
35 let bytes = new Uint8Array(16 + value.length);
36 bytes.set(namespace);
37 bytes.set(value, namespace.length);
38 bytes = hashfunc(bytes);
39 bytes[6] = bytes[6] & 0x0f | version;
40 bytes[8] = bytes[8] & 0x3f | 0x80;
41
42 if (buf) {
43 offset = offset || 0;
44
45 for (let i = 0; i < 16; ++i) {
46 buf[offset + i] = bytes[i];
47 }
48
49 return buf;
50 }
51
52 return stringify(bytes);
53 } // Function#name is not settable on some platforms (#270)
54
55
56 try {
57 generateUUID.name = name; // eslint-disable-next-line no-empty
58 } catch (err) {} // For CommonJS default export support
59
60
61 generateUUID.DNS = DNS;
62 generateUUID.URL = URL;
63 return generateUUID;
64}
\No newline at end of file