uuid.ts 927 B

123456789101112131415161718192021222324252627282930313233343536
  1. /**
  2. * Explain UUID and link to RFC here.
  3. *
  4. * @_subsection: api/utils:UUID [about-uuid]
  5. */
  6. import { getBytes, hexlify } from "./data.js";
  7. import type { BytesLike } from "./index.js";
  8. /**
  9. * Returns the version 4 [[link-uuid]] for the %%randomBytes%%.
  10. *
  11. * @see: https://www.ietf.org/rfc/rfc4122.txt (Section 4.4)
  12. */
  13. export function uuidV4(randomBytes: BytesLike): string {
  14. const bytes = getBytes(randomBytes, "randomBytes");
  15. // Section: 4.1.3:
  16. // - time_hi_and_version[12:16] = 0b0100
  17. bytes[6] = (bytes[6] & 0x0f) | 0x40;
  18. // Section 4.4
  19. // - clock_seq_hi_and_reserved[6] = 0b0
  20. // - clock_seq_hi_and_reserved[7] = 0b1
  21. bytes[8] = (bytes[8] & 0x3f) | 0x80;
  22. const value = hexlify(bytes);
  23. return [
  24. value.substring(2, 10),
  25. value.substring(10, 14),
  26. value.substring(14, 18),
  27. value.substring(18, 22),
  28. value.substring(22, 34),
  29. ].join("-");
  30. }