uuid.js 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. "use strict";
  2. /**
  3. * Copyright 2023 Google LLC.
  4. * Copyright (c) Microsoft Corporation.
  5. *
  6. * Licensed under the Apache License, Version 2.0 (the "License");
  7. * you may not use this file except in compliance with the License.
  8. * You may obtain a copy of the License at
  9. *
  10. * http://www.apache.org/licenses/LICENSE-2.0
  11. *
  12. * Unless required by applicable law or agreed to in writing, software
  13. * distributed under the License is distributed on an "AS IS" BASIS,
  14. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15. * See the License for the specific language governing permissions and
  16. * limitations under the License.
  17. */
  18. Object.defineProperty(exports, "__esModule", { value: true });
  19. exports.uuidv4 = void 0;
  20. /**
  21. * Generates a random v4 UUID, as specified in RFC4122.
  22. *
  23. * Uses the native Web Crypto API if available, otherwise falls back to a
  24. * polyfill.
  25. *
  26. * Example: '9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6d'
  27. */
  28. function uuidv4() {
  29. // Available only in secure contexts
  30. // https://developer.mozilla.org/en-US/docs/Web/API/Web_Crypto_API
  31. if ('crypto' in globalThis && 'randomUUID' in globalThis.crypto) {
  32. // Node with
  33. // https://nodejs.org/dist/latest-v20.x/docs/api/globals.html#crypto_1 or
  34. // secure browser context.
  35. return globalThis.crypto.randomUUID();
  36. }
  37. const randomValues = new Uint8Array(16);
  38. if ('crypto' in globalThis && 'getRandomValues' in globalThis.crypto) {
  39. // Node with
  40. // https://nodejs.org/dist/latest-v20.x/docs/api/globals.html#crypto_1 or
  41. // browser.
  42. globalThis.crypto.getRandomValues(randomValues);
  43. }
  44. else {
  45. // Node without
  46. // https://nodejs.org/dist/latest-v20.x/docs/api/globals.html#crypto_1.
  47. // eslint-disable-next-line @typescript-eslint/no-var-requires
  48. require('crypto').webcrypto.getRandomValues(randomValues);
  49. }
  50. // Set version (4) and variant (RFC4122) bits.
  51. randomValues[6] = (randomValues[6] & 0x0f) | 0x40;
  52. randomValues[8] = (randomValues[8] & 0x3f) | 0x80;
  53. const bytesToHex = (bytes) => bytes.reduce((str, byte) => str + byte.toString(16).padStart(2, '0'), '');
  54. return [
  55. bytesToHex(randomValues.subarray(0, 4)),
  56. bytesToHex(randomValues.subarray(4, 6)),
  57. bytesToHex(randomValues.subarray(6, 8)),
  58. bytesToHex(randomValues.subarray(8, 10)),
  59. bytesToHex(randomValues.subarray(10, 16)),
  60. ].join('-');
  61. }
  62. exports.uuidv4 = uuidv4;
  63. //# sourceMappingURL=uuid.js.map