v35.js 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  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. }
  25. // Compute hash of namespace and value, Per 4.3
  26. // Future: Use spread syntax when supported on all platforms, e.g. `bytes =
  27. // hashfunc([...namespace, ... value])`
  28. let bytes = new Uint8Array(16 + value.length);
  29. bytes.set(namespace);
  30. bytes.set(value, namespace.length);
  31. bytes = hashfunc(bytes);
  32. bytes[6] = bytes[6] & 0x0f | version;
  33. bytes[8] = bytes[8] & 0x3f | 0x80;
  34. if (buf) {
  35. offset = offset || 0;
  36. for (let i = 0; i < 16; ++i) {
  37. buf[offset + i] = bytes[i];
  38. }
  39. return buf;
  40. }
  41. return unsafeStringify(bytes);
  42. }
  43. // Function#name is not settable on some platforms (#270)
  44. try {
  45. generateUUID.name = name;
  46. } catch (err) {}
  47. // For CommonJS default export support
  48. generateUUID.DNS = DNS;
  49. generateUUID.URL = URL;
  50. return generateUUID;
  51. }