UNPKG

1.66 kBJavaScriptView Raw
1import bytesToUuid from './bytesToUuid.js';
2
3function uuidToBytes(uuid) {
4 // Note: We assume we're being passed a valid uuid string
5 var bytes = [];
6 uuid.replace(/[a-fA-F0-9]{2}/g, function (hex) {
7 bytes.push(parseInt(hex, 16));
8 });
9 return bytes;
10}
11
12function stringToBytes(str) {
13 str = unescape(encodeURIComponent(str)); // UTF8 escape
14
15 var bytes = new Array(str.length);
16
17 for (var i = 0; i < str.length; i++) {
18 bytes[i] = str.charCodeAt(i);
19 }
20
21 return bytes;
22}
23
24export var DNS = '6ba7b810-9dad-11d1-80b4-00c04fd430c8';
25export var URL = '6ba7b811-9dad-11d1-80b4-00c04fd430c8';
26export default function (name, version, hashfunc) {
27 var generateUUID = function generateUUID(value, namespace, buf, offset) {
28 var off = buf && offset || 0;
29 if (typeof value == 'string') value = stringToBytes(value);
30 if (typeof namespace == 'string') namespace = uuidToBytes(namespace);
31 if (!Array.isArray(value)) throw TypeError('value must be an array of bytes');
32 if (!Array.isArray(namespace) || namespace.length !== 16) throw TypeError('namespace must be uuid string or an Array of 16 byte values'); // Per 4.3
33
34 var bytes = hashfunc(namespace.concat(value));
35 bytes[6] = bytes[6] & 0x0f | version;
36 bytes[8] = bytes[8] & 0x3f | 0x80;
37
38 if (buf) {
39 for (var idx = 0; idx < 16; ++idx) {
40 buf[off + idx] = bytes[idx];
41 }
42 }
43
44 return buf || bytesToUuid(bytes);
45 }; // Function#name is not settable on some platforms (#270)
46
47
48 try {
49 generateUUID.name = name;
50 } catch (err) {} // For CommonJS default export support
51
52
53 generateUUID.DNS = DNS;
54 generateUUID.URL = URL;
55 return generateUUID;
56}
\No newline at end of file