v35.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. import { unsafeStringify } 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 v35(name, version, hashfunc) {
  14. function generateUUID(value, namespace, buf, offset) {
  15. var _namespace;
  16. if (typeof value === 'string') {
  17. value = stringToBytes(value);
  18. }
  19. if (typeof namespace === 'string') {
  20. namespace = parse(namespace);
  21. }
  22. if (((_namespace = namespace) === null || _namespace === void 0 ? void 0 : _namespace.length) !== 16) {
  23. throw TypeError('Namespace must be array-like (16 iterable integer values, 0-255)');
  24. } // Compute hash of namespace and value, Per 4.3
  25. // Future: Use spread syntax when supported on all platforms, e.g. `bytes =
  26. // hashfunc([...namespace, ... value])`
  27. let bytes = new Uint8Array(16 + value.length);
  28. bytes.set(namespace);
  29. bytes.set(value, namespace.length);
  30. bytes = hashfunc(bytes);
  31. bytes[6] = bytes[6] & 0x0f | version;
  32. bytes[8] = bytes[8] & 0x3f | 0x80;
  33. if (buf) {
  34. offset = offset || 0;
  35. for (let i = 0; i < 16; ++i) {
  36. buf[offset + i] = bytes[i];
  37. }
  38. return buf;
  39. }
  40. return unsafeStringify(bytes);
  41. } // Function#name is not settable on some platforms (#270)
  42. try {
  43. generateUUID.name = name; // eslint-disable-next-line no-empty
  44. } catch (err) {} // For CommonJS default export support
  45. generateUUID.DNS = DNS;
  46. generateUUID.URL = URL;
  47. return generateUUID;
  48. }