stringify.js 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.default = void 0;
  6. exports.unsafeStringify = unsafeStringify;
  7. var _validate = _interopRequireDefault(require("./validate.js"));
  8. function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
  9. /**
  10. * Convert array of 16 byte values to UUID string format of the form:
  11. * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX
  12. */
  13. var byteToHex = [];
  14. for (var i = 0; i < 256; ++i) {
  15. byteToHex.push((i + 0x100).toString(16).slice(1));
  16. }
  17. function unsafeStringify(arr, offset = 0) {
  18. // Note: Be careful editing this code! It's been tuned for performance
  19. // and works in ways you may not expect. See https://github.com/uuidjs/uuid/pull/434
  20. //
  21. // Note to future-self: No, you can't remove the `toLowerCase()` call.
  22. // REF: https://github.com/uuidjs/uuid/pull/677#issuecomment-1757351351
  23. return (byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + '-' + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + '-' + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + '-' + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + '-' + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]]).toLowerCase();
  24. }
  25. function stringify(arr, offset = 0) {
  26. var uuid = unsafeStringify(arr, offset);
  27. // Consistency check for valid UUID. If this throws, it's likely due to one
  28. // of the following:
  29. // - One or more input array values don't map to a hex octet (leading to
  30. // "undefined" in the uuid)
  31. // - Invalid input values for the RFC `version` or `variant` fields
  32. if (!(0, _validate.default)(uuid)) {
  33. throw TypeError('Stringified UUID is invalid');
  34. }
  35. return uuid;
  36. }
  37. var _default = exports.default = stringify;