uuid.js 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272
  1. // uuid.js
  2. //
  3. // Copyright (c) 2010-2012 Robert Kieffer
  4. // MIT License - http://opensource.org/licenses/mit-license.php
  5. /*global window, require, define */
  6. (function(_window) {
  7. 'use strict';
  8. // Unique ID creation requires a high quality random # generator. We feature
  9. // detect to determine the best RNG source, normalizing to a function that
  10. // returns 128-bits of randomness, since that's what's usually required
  11. var _rng, _mathRNG, _nodeRNG, _whatwgRNG, _previousRoot;
  12. function setupBrowser() {
  13. // Allow for MSIE11 msCrypto
  14. var _crypto = _window.crypto || _window.msCrypto;
  15. if (!_rng && _crypto && _crypto.getRandomValues) {
  16. // WHATWG crypto-based RNG - http://wiki.whatwg.org/wiki/Crypto
  17. //
  18. // Moderately fast, high quality
  19. try {
  20. var _rnds8 = new Uint8Array(16);
  21. _whatwgRNG = _rng = function whatwgRNG() {
  22. _crypto.getRandomValues(_rnds8);
  23. return _rnds8;
  24. };
  25. _rng();
  26. } catch(e) {}
  27. }
  28. if (!_rng) {
  29. // Math.random()-based (RNG)
  30. //
  31. // If all else fails, use Math.random(). It's fast, but is of unspecified
  32. // quality.
  33. var _rnds = new Array(16);
  34. _mathRNG = _rng = function() {
  35. for (var i = 0, r; i < 16; i++) {
  36. if ((i & 0x03) === 0) { r = Math.random() * 0x100000000; }
  37. _rnds[i] = r >>> ((i & 0x03) << 3) & 0xff;
  38. }
  39. return _rnds;
  40. };
  41. if ('undefined' !== typeof console && console.warn) {
  42. console.warn("[SECURITY] node-uuid: crypto not usable, falling back to insecure Math.random()");
  43. }
  44. }
  45. }
  46. function setupNode() {
  47. // Node.js crypto-based RNG - http://nodejs.org/docs/v0.6.2/api/crypto.html
  48. //
  49. // Moderately fast, high quality
  50. if ('function' === typeof require) {
  51. try {
  52. var _rb = require('crypto').randomBytes;
  53. _nodeRNG = _rng = _rb && function() {return _rb(16);};
  54. _rng();
  55. } catch(e) {}
  56. }
  57. }
  58. if (_window) {
  59. setupBrowser();
  60. } else {
  61. setupNode();
  62. }
  63. // Buffer class to use
  64. var BufferClass = ('function' === typeof Buffer) ? Buffer : Array;
  65. // Maps for number <-> hex string conversion
  66. var _byteToHex = [];
  67. var _hexToByte = {};
  68. for (var i = 0; i < 256; i++) {
  69. _byteToHex[i] = (i + 0x100).toString(16).substr(1);
  70. _hexToByte[_byteToHex[i]] = i;
  71. }
  72. // **`parse()` - Parse a UUID into it's component bytes**
  73. function parse(s, buf, offset) {
  74. var i = (buf && offset) || 0, ii = 0;
  75. buf = buf || [];
  76. s.toLowerCase().replace(/[0-9a-f]{2}/g, function(oct) {
  77. if (ii < 16) { // Don't overflow!
  78. buf[i + ii++] = _hexToByte[oct];
  79. }
  80. });
  81. // Zero out remaining bytes if string was short
  82. while (ii < 16) {
  83. buf[i + ii++] = 0;
  84. }
  85. return buf;
  86. }
  87. // **`unparse()` - Convert UUID byte array (ala parse()) into a string**
  88. function unparse(buf, offset) {
  89. var i = offset || 0, bth = _byteToHex;
  90. return bth[buf[i++]] + bth[buf[i++]] +
  91. bth[buf[i++]] + bth[buf[i++]] + '-' +
  92. bth[buf[i++]] + bth[buf[i++]] + '-' +
  93. bth[buf[i++]] + bth[buf[i++]] + '-' +
  94. bth[buf[i++]] + bth[buf[i++]] + '-' +
  95. bth[buf[i++]] + bth[buf[i++]] +
  96. bth[buf[i++]] + bth[buf[i++]] +
  97. bth[buf[i++]] + bth[buf[i++]];
  98. }
  99. // **`v1()` - Generate time-based UUID**
  100. //
  101. // Inspired by https://github.com/LiosK/UUID.js
  102. // and http://docs.python.org/library/uuid.html
  103. // random #'s we need to init node and clockseq
  104. var _seedBytes = _rng();
  105. // Per 4.5, create and 48-bit node id, (47 random bits + multicast bit = 1)
  106. var _nodeId = [
  107. _seedBytes[0] | 0x01,
  108. _seedBytes[1], _seedBytes[2], _seedBytes[3], _seedBytes[4], _seedBytes[5]
  109. ];
  110. // Per 4.2.2, randomize (14 bit) clockseq
  111. var _clockseq = (_seedBytes[6] << 8 | _seedBytes[7]) & 0x3fff;
  112. // Previous uuid creation time
  113. var _lastMSecs = 0, _lastNSecs = 0;
  114. // See https://github.com/broofa/node-uuid for API details
  115. function v1(options, buf, offset) {
  116. var i = buf && offset || 0;
  117. var b = buf || [];
  118. options = options || {};
  119. var clockseq = (options.clockseq != null) ? options.clockseq : _clockseq;
  120. // UUID timestamps are 100 nano-second units since the Gregorian epoch,
  121. // (1582-10-15 00:00). JSNumbers aren't precise enough for this, so
  122. // time is handled internally as 'msecs' (integer milliseconds) and 'nsecs'
  123. // (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00.
  124. var msecs = (options.msecs != null) ? options.msecs : new Date().getTime();
  125. // Per 4.2.1.2, use count of uuid's generated during the current clock
  126. // cycle to simulate higher resolution clock
  127. var nsecs = (options.nsecs != null) ? options.nsecs : _lastNSecs + 1;
  128. // Time since last uuid creation (in msecs)
  129. var dt = (msecs - _lastMSecs) + (nsecs - _lastNSecs)/10000;
  130. // Per 4.2.1.2, Bump clockseq on clock regression
  131. if (dt < 0 && options.clockseq == null) {
  132. clockseq = clockseq + 1 & 0x3fff;
  133. }
  134. // Reset nsecs if clock regresses (new clockseq) or we've moved onto a new
  135. // time interval
  136. if ((dt < 0 || msecs > _lastMSecs) && options.nsecs == null) {
  137. nsecs = 0;
  138. }
  139. // Per 4.2.1.2 Throw error if too many uuids are requested
  140. if (nsecs >= 10000) {
  141. throw new Error('uuid.v1(): Can\'t create more than 10M uuids/sec');
  142. }
  143. _lastMSecs = msecs;
  144. _lastNSecs = nsecs;
  145. _clockseq = clockseq;
  146. // Per 4.1.4 - Convert from unix epoch to Gregorian epoch
  147. msecs += 12219292800000;
  148. // `time_low`
  149. var tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000;
  150. b[i++] = tl >>> 24 & 0xff;
  151. b[i++] = tl >>> 16 & 0xff;
  152. b[i++] = tl >>> 8 & 0xff;
  153. b[i++] = tl & 0xff;
  154. // `time_mid`
  155. var tmh = (msecs / 0x100000000 * 10000) & 0xfffffff;
  156. b[i++] = tmh >>> 8 & 0xff;
  157. b[i++] = tmh & 0xff;
  158. // `time_high_and_version`
  159. b[i++] = tmh >>> 24 & 0xf | 0x10; // include version
  160. b[i++] = tmh >>> 16 & 0xff;
  161. // `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant)
  162. b[i++] = clockseq >>> 8 | 0x80;
  163. // `clock_seq_low`
  164. b[i++] = clockseq & 0xff;
  165. // `node`
  166. var node = options.node || _nodeId;
  167. for (var n = 0; n < 6; n++) {
  168. b[i + n] = node[n];
  169. }
  170. return buf ? buf : unparse(b);
  171. }
  172. // **`v4()` - Generate random UUID**
  173. // See https://github.com/broofa/node-uuid for API details
  174. function v4(options, buf, offset) {
  175. // Deprecated - 'format' argument, as supported in v1.2
  176. var i = buf && offset || 0;
  177. if (typeof(options) === 'string') {
  178. buf = (options === 'binary') ? new BufferClass(16) : null;
  179. options = null;
  180. }
  181. options = options || {};
  182. var rnds = options.random || (options.rng || _rng)();
  183. // Per 4.4, set bits for version and `clock_seq_hi_and_reserved`
  184. rnds[6] = (rnds[6] & 0x0f) | 0x40;
  185. rnds[8] = (rnds[8] & 0x3f) | 0x80;
  186. // Copy bytes to buffer, if provided
  187. if (buf) {
  188. for (var ii = 0; ii < 16; ii++) {
  189. buf[i + ii] = rnds[ii];
  190. }
  191. }
  192. return buf || unparse(rnds);
  193. }
  194. // Export public API
  195. var uuid = v4;
  196. uuid.v1 = v1;
  197. uuid.v4 = v4;
  198. uuid.parse = parse;
  199. uuid.unparse = unparse;
  200. uuid.BufferClass = BufferClass;
  201. uuid._rng = _rng;
  202. uuid._mathRNG = _mathRNG;
  203. uuid._nodeRNG = _nodeRNG;
  204. uuid._whatwgRNG = _whatwgRNG;
  205. if (('undefined' !== typeof module) && module.exports) {
  206. // Publish as node.js module
  207. module.exports = uuid;
  208. } else if (typeof define === 'function' && define.amd) {
  209. // Publish as AMD module
  210. define(function() {return uuid;});
  211. } else {
  212. // Publish as global (in browsers)
  213. _previousRoot = _window.uuid;
  214. // **`noConflict()` - (browser only) to reset global 'uuid' var**
  215. uuid.noConflict = function() {
  216. _window.uuid = _previousRoot;
  217. return uuid;
  218. };
  219. _window.uuid = uuid;
  220. }
  221. })('undefined' !== typeof window ? window : null);