v35.js 1.6 KB

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