posthog-js-lite 2.6.0 → 2.6.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,3 +1,7 @@
1
+ # 2.6.1 - 2024-02-06
2
+
3
+ 1. Swapped to `uuidv7` for unique ID generation
4
+
1
5
  # 2.6.0 - 2024-01-18
2
6
 
3
7
  1. Adds support for overriding the event `uuid` via capture options
package/lib/index.cjs.js CHANGED
@@ -211,26 +211,6 @@ function retriable(fn, props) {
211
211
  });
212
212
  });
213
213
  }
214
- // https://stackoverflow.com/a/8809472
215
- function generateUUID(globalThis) {
216
- // Public Domain/MIT
217
- var d = new Date().getTime(); //Timestamp
218
- var d2 = (globalThis && globalThis.performance && globalThis.performance.now && globalThis.performance.now() * 1000) || 0; //Time in microseconds since page-load or 0 if unsupported
219
- return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
220
- var r = Math.random() * 16; //random number between 0 and 16
221
- if (d > 0) {
222
- //Use timestamp until depleted
223
- r = (d + r) % 16 | 0;
224
- d = Math.floor(d / 16);
225
- }
226
- else {
227
- //Use microseconds since page-load if supported
228
- r = (d2 + r) % 16 | 0;
229
- d2 = Math.floor(d2 / 16);
230
- }
231
- return (c === 'x' ? r : (r & 0x3) | 0x8).toString(16);
232
- });
233
- }
234
214
  function currentTimestamp() {
235
215
  return new Date().getTime();
236
216
  }
@@ -705,6 +685,401 @@ var SimpleEventEmitter = /** @class */ (function () {
705
685
  return SimpleEventEmitter;
706
686
  }());
707
687
 
688
+ /**
689
+ * uuidv7: An experimental implementation of the proposed UUID Version 7
690
+ *
691
+ * @license Apache-2.0
692
+ * @copyright 2021-2023 LiosK
693
+ * @packageDocumentation
694
+ */
695
+ var DIGITS = "0123456789abcdef";
696
+ /** Represents a UUID as a 16-byte byte array. */
697
+ var UUID = /** @class */ (function () {
698
+ /** @param bytes - The 16-byte byte array representation. */
699
+ function UUID(bytes) {
700
+ this.bytes = bytes;
701
+ }
702
+ /**
703
+ * Creates an object from the internal representation, a 16-byte byte array
704
+ * containing the binary UUID representation in the big-endian byte order.
705
+ *
706
+ * This method does NOT shallow-copy the argument, and thus the created object
707
+ * holds the reference to the underlying buffer.
708
+ *
709
+ * @throws TypeError if the length of the argument is not 16.
710
+ */
711
+ UUID.ofInner = function (bytes) {
712
+ if (bytes.length !== 16) {
713
+ throw new TypeError("not 128-bit length");
714
+ }
715
+ else {
716
+ return new UUID(bytes);
717
+ }
718
+ };
719
+ /**
720
+ * Builds a byte array from UUIDv7 field values.
721
+ *
722
+ * @param unixTsMs - A 48-bit `unix_ts_ms` field value.
723
+ * @param randA - A 12-bit `rand_a` field value.
724
+ * @param randBHi - The higher 30 bits of 62-bit `rand_b` field value.
725
+ * @param randBLo - The lower 32 bits of 62-bit `rand_b` field value.
726
+ * @throws RangeError if any field value is out of the specified range.
727
+ */
728
+ UUID.fromFieldsV7 = function (unixTsMs, randA, randBHi, randBLo) {
729
+ if (!Number.isInteger(unixTsMs) ||
730
+ !Number.isInteger(randA) ||
731
+ !Number.isInteger(randBHi) ||
732
+ !Number.isInteger(randBLo) ||
733
+ unixTsMs < 0 ||
734
+ randA < 0 ||
735
+ randBHi < 0 ||
736
+ randBLo < 0 ||
737
+ unixTsMs > 281474976710655 ||
738
+ randA > 0xfff ||
739
+ randBHi > 1073741823 ||
740
+ randBLo > 4294967295) {
741
+ throw new RangeError("invalid field value");
742
+ }
743
+ var bytes = new Uint8Array(16);
744
+ bytes[0] = unixTsMs / Math.pow(2, 40);
745
+ bytes[1] = unixTsMs / Math.pow(2, 32);
746
+ bytes[2] = unixTsMs / Math.pow(2, 24);
747
+ bytes[3] = unixTsMs / Math.pow(2, 16);
748
+ bytes[4] = unixTsMs / Math.pow(2, 8);
749
+ bytes[5] = unixTsMs;
750
+ bytes[6] = 0x70 | (randA >>> 8);
751
+ bytes[7] = randA;
752
+ bytes[8] = 0x80 | (randBHi >>> 24);
753
+ bytes[9] = randBHi >>> 16;
754
+ bytes[10] = randBHi >>> 8;
755
+ bytes[11] = randBHi;
756
+ bytes[12] = randBLo >>> 24;
757
+ bytes[13] = randBLo >>> 16;
758
+ bytes[14] = randBLo >>> 8;
759
+ bytes[15] = randBLo;
760
+ return new UUID(bytes);
761
+ };
762
+ /**
763
+ * Builds a byte array from a string representation.
764
+ *
765
+ * This method accepts the following formats:
766
+ *
767
+ * - 32-digit hexadecimal format without hyphens: `0189dcd553117d408db09496a2eef37b`
768
+ * - 8-4-4-4-12 hyphenated format: `0189dcd5-5311-7d40-8db0-9496a2eef37b`
769
+ * - Hyphenated format with surrounding braces: `{0189dcd5-5311-7d40-8db0-9496a2eef37b}`
770
+ * - RFC 4122 URN format: `urn:uuid:0189dcd5-5311-7d40-8db0-9496a2eef37b`
771
+ *
772
+ * Leading and trailing whitespaces represents an error.
773
+ *
774
+ * @throws SyntaxError if the argument could not parse as a valid UUID string.
775
+ */
776
+ UUID.parse = function (uuid) {
777
+ var _a, _b, _c, _d;
778
+ var hex = undefined;
779
+ switch (uuid.length) {
780
+ case 32:
781
+ hex = (_a = /^[0-9a-f]{32}$/i.exec(uuid)) === null || _a === void 0 ? void 0 : _a[0];
782
+ break;
783
+ case 36:
784
+ hex =
785
+ (_b = /^([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})$/i
786
+ .exec(uuid)) === null || _b === void 0 ? void 0 : _b.slice(1, 6).join("");
787
+ break;
788
+ case 38:
789
+ hex =
790
+ (_c = /^\{([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})\}$/i
791
+ .exec(uuid)) === null || _c === void 0 ? void 0 : _c.slice(1, 6).join("");
792
+ break;
793
+ case 45:
794
+ hex =
795
+ (_d = /^urn:uuid:([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})$/i
796
+ .exec(uuid)) === null || _d === void 0 ? void 0 : _d.slice(1, 6).join("");
797
+ break;
798
+ }
799
+ if (hex) {
800
+ var inner = new Uint8Array(16);
801
+ for (var i = 0; i < 16; i += 4) {
802
+ var n = parseInt(hex.substring(2 * i, 2 * i + 8), 16);
803
+ inner[i + 0] = n >>> 24;
804
+ inner[i + 1] = n >>> 16;
805
+ inner[i + 2] = n >>> 8;
806
+ inner[i + 3] = n;
807
+ }
808
+ return new UUID(inner);
809
+ }
810
+ else {
811
+ throw new SyntaxError("could not parse UUID string");
812
+ }
813
+ };
814
+ /**
815
+ * @returns The 8-4-4-4-12 canonical hexadecimal string representation
816
+ * (`0189dcd5-5311-7d40-8db0-9496a2eef37b`).
817
+ */
818
+ UUID.prototype.toString = function () {
819
+ var text = "";
820
+ for (var i = 0; i < this.bytes.length; i++) {
821
+ text += DIGITS.charAt(this.bytes[i] >>> 4);
822
+ text += DIGITS.charAt(this.bytes[i] & 0xf);
823
+ if (i === 3 || i === 5 || i === 7 || i === 9) {
824
+ text += "-";
825
+ }
826
+ }
827
+ return text;
828
+ };
829
+ /**
830
+ * @returns The 32-digit hexadecimal representation without hyphens
831
+ * (`0189dcd553117d408db09496a2eef37b`).
832
+ */
833
+ UUID.prototype.toHex = function () {
834
+ var text = "";
835
+ for (var i = 0; i < this.bytes.length; i++) {
836
+ text += DIGITS.charAt(this.bytes[i] >>> 4);
837
+ text += DIGITS.charAt(this.bytes[i] & 0xf);
838
+ }
839
+ return text;
840
+ };
841
+ /** @returns The 8-4-4-4-12 canonical hexadecimal string representation. */
842
+ UUID.prototype.toJSON = function () {
843
+ return this.toString();
844
+ };
845
+ /**
846
+ * Reports the variant field value of the UUID or, if appropriate, "NIL" or
847
+ * "MAX".
848
+ *
849
+ * For convenience, this method reports "NIL" or "MAX" if `this` represents
850
+ * the Nil or Max UUID, although the Nil and Max UUIDs are technically
851
+ * subsumed under the variants `0b0` and `0b111`, respectively.
852
+ */
853
+ UUID.prototype.getVariant = function () {
854
+ var n = this.bytes[8] >>> 4;
855
+ if (n < 0) {
856
+ throw new Error("unreachable");
857
+ }
858
+ else if (n <= 7) {
859
+ return this.bytes.every(function (e) { return e === 0; }) ? "NIL" : "VAR_0";
860
+ }
861
+ else if (n <= 11) {
862
+ return "VAR_10";
863
+ }
864
+ else if (n <= 13) {
865
+ return "VAR_110";
866
+ }
867
+ else if (n <= 15) {
868
+ return this.bytes.every(function (e) { return e === 0xff; }) ? "MAX" : "VAR_RESERVED";
869
+ }
870
+ else {
871
+ throw new Error("unreachable");
872
+ }
873
+ };
874
+ /**
875
+ * Returns the version field value of the UUID or `undefined` if the UUID does
876
+ * not have the variant field value of `0b10`.
877
+ */
878
+ UUID.prototype.getVersion = function () {
879
+ return this.getVariant() === "VAR_10" ? this.bytes[6] >>> 4 : undefined;
880
+ };
881
+ /** Creates an object from `this`. */
882
+ UUID.prototype.clone = function () {
883
+ return new UUID(this.bytes.slice(0));
884
+ };
885
+ /** Returns true if `this` is equivalent to `other`. */
886
+ UUID.prototype.equals = function (other) {
887
+ return this.compareTo(other) === 0;
888
+ };
889
+ /**
890
+ * Returns a negative integer, zero, or positive integer if `this` is less
891
+ * than, equal to, or greater than `other`, respectively.
892
+ */
893
+ UUID.prototype.compareTo = function (other) {
894
+ for (var i = 0; i < 16; i++) {
895
+ var diff = this.bytes[i] - other.bytes[i];
896
+ if (diff !== 0) {
897
+ return Math.sign(diff);
898
+ }
899
+ }
900
+ return 0;
901
+ };
902
+ return UUID;
903
+ }());
904
+ /**
905
+ * Encapsulates the monotonic counter state.
906
+ *
907
+ * This class provides APIs to utilize a separate counter state from that of the
908
+ * global generator used by {@link uuidv7} and {@link uuidv7obj}. In addition to
909
+ * the default {@link generate} method, this class has {@link generateOrAbort}
910
+ * that is useful to absolutely guarantee the monotonically increasing order of
911
+ * generated UUIDs. See their respective documentation for details.
912
+ */
913
+ var V7Generator = /** @class */ (function () {
914
+ /**
915
+ * Creates a generator object with the default random number generator, or
916
+ * with the specified one if passed as an argument. The specified random
917
+ * number generator should be cryptographically strong and securely seeded.
918
+ */
919
+ function V7Generator(randomNumberGenerator) {
920
+ this.timestamp = 0;
921
+ this.counter = 0;
922
+ this.random = randomNumberGenerator !== null && randomNumberGenerator !== void 0 ? randomNumberGenerator : getDefaultRandom();
923
+ }
924
+ /**
925
+ * Generates a new UUIDv7 object from the current timestamp, or resets the
926
+ * generator upon significant timestamp rollback.
927
+ *
928
+ * This method returns a monotonically increasing UUID by reusing the previous
929
+ * timestamp even if the up-to-date timestamp is smaller than the immediately
930
+ * preceding UUID's. However, when such a clock rollback is considered
931
+ * significant (i.e., by more than ten seconds), this method resets the
932
+ * generator and returns a new UUID based on the given timestamp, breaking the
933
+ * increasing order of UUIDs.
934
+ *
935
+ * See {@link generateOrAbort} for the other mode of generation and
936
+ * {@link generateOrResetCore} for the low-level primitive.
937
+ */
938
+ V7Generator.prototype.generate = function () {
939
+ return this.generateOrResetCore(Date.now(), 10000);
940
+ };
941
+ /**
942
+ * Generates a new UUIDv7 object from the current timestamp, or returns
943
+ * `undefined` upon significant timestamp rollback.
944
+ *
945
+ * This method returns a monotonically increasing UUID by reusing the previous
946
+ * timestamp even if the up-to-date timestamp is smaller than the immediately
947
+ * preceding UUID's. However, when such a clock rollback is considered
948
+ * significant (i.e., by more than ten seconds), this method aborts and
949
+ * returns `undefined` immediately.
950
+ *
951
+ * See {@link generate} for the other mode of generation and
952
+ * {@link generateOrAbortCore} for the low-level primitive.
953
+ */
954
+ V7Generator.prototype.generateOrAbort = function () {
955
+ return this.generateOrAbortCore(Date.now(), 10000);
956
+ };
957
+ /**
958
+ * Generates a new UUIDv7 object from the `unixTsMs` passed, or resets the
959
+ * generator upon significant timestamp rollback.
960
+ *
961
+ * This method is equivalent to {@link generate} except that it takes a custom
962
+ * timestamp and clock rollback allowance.
963
+ *
964
+ * @param rollbackAllowance - The amount of `unixTsMs` rollback that is
965
+ * considered significant. A suggested value is `10_000` (milliseconds).
966
+ * @throws RangeError if `unixTsMs` is not a 48-bit positive integer.
967
+ */
968
+ V7Generator.prototype.generateOrResetCore = function (unixTsMs, rollbackAllowance) {
969
+ var value = this.generateOrAbortCore(unixTsMs, rollbackAllowance);
970
+ if (value === undefined) {
971
+ // reset state and resume
972
+ this.timestamp = 0;
973
+ value = this.generateOrAbortCore(unixTsMs, rollbackAllowance);
974
+ }
975
+ return value;
976
+ };
977
+ /**
978
+ * Generates a new UUIDv7 object from the `unixTsMs` passed, or returns
979
+ * `undefined` upon significant timestamp rollback.
980
+ *
981
+ * This method is equivalent to {@link generateOrAbort} except that it takes a
982
+ * custom timestamp and clock rollback allowance.
983
+ *
984
+ * @param rollbackAllowance - The amount of `unixTsMs` rollback that is
985
+ * considered significant. A suggested value is `10_000` (milliseconds).
986
+ * @throws RangeError if `unixTsMs` is not a 48-bit positive integer.
987
+ */
988
+ V7Generator.prototype.generateOrAbortCore = function (unixTsMs, rollbackAllowance) {
989
+ var MAX_COUNTER = 4398046511103;
990
+ if (!Number.isInteger(unixTsMs) ||
991
+ unixTsMs < 1 ||
992
+ unixTsMs > 281474976710655) {
993
+ throw new RangeError("`unixTsMs` must be a 48-bit positive integer");
994
+ }
995
+ else if (rollbackAllowance < 0 || rollbackAllowance > 281474976710655) {
996
+ throw new RangeError("`rollbackAllowance` out of reasonable range");
997
+ }
998
+ if (unixTsMs > this.timestamp) {
999
+ this.timestamp = unixTsMs;
1000
+ this.resetCounter();
1001
+ }
1002
+ else if (unixTsMs + rollbackAllowance >= this.timestamp) {
1003
+ // go on with previous timestamp if new one is not much smaller
1004
+ this.counter++;
1005
+ if (this.counter > MAX_COUNTER) {
1006
+ // increment timestamp at counter overflow
1007
+ this.timestamp++;
1008
+ this.resetCounter();
1009
+ }
1010
+ }
1011
+ else {
1012
+ // abort if clock went backwards to unbearable extent
1013
+ return undefined;
1014
+ }
1015
+ return UUID.fromFieldsV7(this.timestamp, Math.trunc(this.counter / Math.pow(2, 30)), this.counter & (Math.pow(2, 30) - 1), this.random.nextUint32());
1016
+ };
1017
+ /** Initializes the counter at a 42-bit random integer. */
1018
+ V7Generator.prototype.resetCounter = function () {
1019
+ this.counter =
1020
+ this.random.nextUint32() * 0x400 + (this.random.nextUint32() & 0x3ff);
1021
+ };
1022
+ /**
1023
+ * Generates a new UUIDv4 object utilizing the random number generator inside.
1024
+ *
1025
+ * @internal
1026
+ */
1027
+ V7Generator.prototype.generateV4 = function () {
1028
+ var bytes = new Uint8Array(Uint32Array.of(this.random.nextUint32(), this.random.nextUint32(), this.random.nextUint32(), this.random.nextUint32()).buffer);
1029
+ bytes[6] = 0x40 | (bytes[6] >>> 4);
1030
+ bytes[8] = 0x80 | (bytes[8] >>> 2);
1031
+ return UUID.ofInner(bytes);
1032
+ };
1033
+ return V7Generator;
1034
+ }());
1035
+ /** Returns the default random number generator available in the environment. */
1036
+ var getDefaultRandom = function () {
1037
+ // detect Web Crypto API
1038
+ if (typeof crypto !== "undefined" &&
1039
+ typeof crypto.getRandomValues !== "undefined") {
1040
+ return new BufferedCryptoRandom();
1041
+ }
1042
+ else {
1043
+ // fall back on Math.random() unless the flag is set to true
1044
+ if (typeof UUIDV7_DENY_WEAK_RNG !== "undefined" && UUIDV7_DENY_WEAK_RNG) {
1045
+ throw new Error("no cryptographically strong RNG available");
1046
+ }
1047
+ return {
1048
+ nextUint32: function () { return Math.trunc(Math.random() * 65536) * 65536 +
1049
+ Math.trunc(Math.random() * 65536); },
1050
+ };
1051
+ }
1052
+ };
1053
+ /**
1054
+ * Wraps `crypto.getRandomValues()` to enable buffering; this uses a small
1055
+ * buffer by default to avoid both unbearable throughput decline in some
1056
+ * environments and the waste of time and space for unused values.
1057
+ */
1058
+ var BufferedCryptoRandom = /** @class */ (function () {
1059
+ function BufferedCryptoRandom() {
1060
+ this.buffer = new Uint32Array(8);
1061
+ this.cursor = 0xffff;
1062
+ }
1063
+ BufferedCryptoRandom.prototype.nextUint32 = function () {
1064
+ if (this.cursor >= this.buffer.length) {
1065
+ crypto.getRandomValues(this.buffer);
1066
+ this.cursor = 0;
1067
+ }
1068
+ return this.buffer[this.cursor++];
1069
+ };
1070
+ return BufferedCryptoRandom;
1071
+ }());
1072
+ var defaultGenerator;
1073
+ /**
1074
+ * Generates a UUIDv7 string.
1075
+ *
1076
+ * @returns The 8-4-4-4-12 canonical hexadecimal string representation
1077
+ * ("xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx").
1078
+ */
1079
+ var uuidv7 = function () { return uuidv7obj().toString(); };
1080
+ /** Generates a UUIDv7 object. */
1081
+ var uuidv7obj = function () { return (defaultGenerator || (defaultGenerator = new V7Generator())).generate(); };
1082
+
708
1083
  var PostHogFetchHttpError = /** @class */ (function (_super) {
709
1084
  __extends(PostHogFetchHttpError, _super);
710
1085
  function PostHogFetchHttpError(response) {
@@ -796,7 +1171,7 @@ var PostHogCoreStateless = /** @class */ (function () {
796
1171
  };
797
1172
  PostHogCoreStateless.prototype.addPendingPromise = function (promise) {
798
1173
  var _this = this;
799
- var promiseUUID = generateUUID();
1174
+ var promiseUUID = uuidv7();
800
1175
  this.pendingPromises[promiseUUID] = promise;
801
1176
  promise.finally(function () {
802
1177
  delete _this.pendingPromises[promiseUUID];
@@ -1000,7 +1375,7 @@ var PostHogCoreStateless = /** @class */ (function () {
1000
1375
  this._events.emit(type, "Library is disabled. Not sending event. To re-enable, call posthog.optIn()");
1001
1376
  return;
1002
1377
  }
1003
- var message = __assign(__assign({}, _message), { type: type, library: this.getLibraryId(), library_version: this.getLibraryVersion(), timestamp: (options === null || options === void 0 ? void 0 : options.timestamp) ? options === null || options === void 0 ? void 0 : options.timestamp : currentISOTime(), uuid: (options === null || options === void 0 ? void 0 : options.uuid) ? options.uuid : generateUUID(globalThis) });
1378
+ var message = __assign(__assign({}, _message), { type: type, library: this.getLibraryId(), library_version: this.getLibraryVersion(), timestamp: (options === null || options === void 0 ? void 0 : options.timestamp) ? options === null || options === void 0 ? void 0 : options.timestamp : currentISOTime(), uuid: (options === null || options === void 0 ? void 0 : options.uuid) ? options.uuid : uuidv7() });
1004
1379
  var addGeoipDisableProperty = (_a = options === null || options === void 0 ? void 0 : options.disableGeoip) !== null && _a !== void 0 ? _a : this.disableGeoip;
1005
1380
  if (addGeoipDisableProperty) {
1006
1381
  if (!message.properties) {
@@ -1265,7 +1640,7 @@ var PostHogCore = /** @class */ (function (_super) {
1265
1640
  var sessionId = this.getPersistedProperty(PostHogPersistedProperty.SessionId);
1266
1641
  var sessionTimestamp = this.getPersistedProperty(PostHogPersistedProperty.SessionLastTimestamp) || 0;
1267
1642
  if (!sessionId || Date.now() - sessionTimestamp > this._sessionExpirationTimeSeconds * 1000) {
1268
- sessionId = generateUUID(globalThis);
1643
+ sessionId = uuidv7();
1269
1644
  this.setPersistedProperty(PostHogPersistedProperty.SessionId, sessionId);
1270
1645
  }
1271
1646
  this.setPersistedProperty(PostHogPersistedProperty.SessionLastTimestamp, Date.now());
@@ -1277,7 +1652,7 @@ var PostHogCore = /** @class */ (function (_super) {
1277
1652
  PostHogCore.prototype.getAnonymousId = function () {
1278
1653
  var anonId = this.getPersistedProperty(PostHogPersistedProperty.AnonymousId);
1279
1654
  if (!anonId) {
1280
- anonId = generateUUID(globalThis);
1655
+ anonId = uuidv7();
1281
1656
  this.setPersistedProperty(PostHogPersistedProperty.AnonymousId, anonId);
1282
1657
  }
1283
1658
  return anonId;
@@ -1600,7 +1975,7 @@ var PostHogCore = /** @class */ (function (_super) {
1600
1975
  return PostHogCore;
1601
1976
  }(PostHogCoreStateless));
1602
1977
 
1603
- var version = "2.6.0";
1978
+ var version = "2.6.1";
1604
1979
 
1605
1980
  function getContext(window) {
1606
1981
  var context = {};