@sv443-network/userutils 8.1.0 → 8.2.0

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,5 +1,15 @@
1
1
  # @sv443-network/userutils
2
2
 
3
+ ## 8.2.0
4
+
5
+ ### Minor Changes
6
+
7
+ - 3fe8b25: Added overload to `mapRange()` that only needs both `max` values and assumes 0 for both `min` values
8
+ - d7e8a31: Added utility type `Prettify` to make complex types more readable
9
+ - 8ec2010: Added `randomCase` parameter to the function `randomId()` (true by default)
10
+ - d9a36d5: Added property `migrateIds` to the constructor of `DataStore` for easier ID migration
11
+ - b2f757e: Added `enhancedEntropy` parameter to the function `randRange()` (false by default)
12
+
3
13
  ## 8.1.0
4
14
 
5
15
  ### Minor Changes
package/README.md CHANGED
@@ -78,6 +78,7 @@ View the documentation of previous major releases:
78
78
  - [`NonEmptyArray`](#nonemptyarray) - any array that should have at least one item
79
79
  - [`NonEmptyString`](#nonemptystring) - any string that should have at least one character
80
80
  - [`LooseUnion`](#looseunion) - a union that gives autocomplete in the IDE but also allows any other value of the same type
81
+ - [`Prettify`](#prettify) - expands a complex type into a more readable format while keeping functionality the same
81
82
 
82
83
  <br><br>
83
84
 
@@ -930,16 +931,12 @@ clamp(99999, 0, Infinity); // 99999
930
931
  ### mapRange()
931
932
  Usage:
932
933
  ```ts
933
- mapRange(
934
- value: number,
935
- range1min: number,
936
- range1max: number,
937
- range2min: number,
938
- range2max: number
939
- ): number
934
+ mapRange(value: number, range1min: number, range1max: number, range2min: number, range2max: number): number
935
+ mapRange(value: number, range1max: number, range2max: number): number
940
936
  ```
941
937
 
942
938
  Maps a number from one range to the spot it would be in another range.
939
+ If only the `max` arguments are passed, the function will set the `min` for both ranges to 0.
943
940
 
944
941
  <details><summary><b>Example - click to view</b></summary>
945
942
 
@@ -948,6 +945,7 @@ import { mapRange } from "@sv443-network/userutils";
948
945
 
949
946
  mapRange(5, 0, 10, 0, 100); // 50
950
947
  mapRange(5, 0, 10, 0, 50); // 25
948
+ mapRange(5, 10, 50); // 25
951
949
 
952
950
  // to calculate a percentage from arbitrary values, use 0 and 100 as the second range
953
951
  // for example, if 4 files of a total of 13 were downloaded:
@@ -960,21 +958,41 @@ mapRange(4, 0, 13, 0, 100); // 30.76923076923077
960
958
  ### randRange()
961
959
  Usages:
962
960
  ```ts
963
- randRange(min: number, max: number): number
964
- randRange(max: number): number
961
+ randRange(min: number, max: number, enhancedEntropy?: boolean): number
962
+ randRange(max: number, enhancedEntropy?: boolean): number
965
963
  ```
966
964
 
967
965
  Returns a random number between `min` and `max` (inclusive).
968
966
  If only one argument is passed, it will be used as the `max` value and `min` will be set to 0.
969
967
 
968
+ If `enhancedEntropy` is set to true (false by default), the [Web Crypto API](https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues) is used for generating the random numbers.
969
+ Note that this makes the function call take longer, but the generated IDs will have a higher entropy.
970
+
970
971
  <details><summary><b>Example - click to view</b></summary>
971
972
 
972
973
  ```ts
973
974
  import { randRange } from "@sv443-network/userutils";
974
975
 
975
- randRange(0, 10); // 4
976
- randRange(10, 20); // 17
977
- randRange(10); // 7
976
+ randRange(0, 10); // 4
977
+ randRange(10, 20); // 17
978
+ randRange(10); // 7
979
+ randRange(0, 10, true); // 4 (the devil is in the details)
980
+
981
+
982
+ function benchmark(enhancedEntropy: boolean) {
983
+ const timestamp = Date.now();
984
+ for(let i = 0; i < 100_000; i++)
985
+ randRange(0, 100, enhancedEntropy);
986
+ console.log(`Generated 100k in ${Date.now() - timestamp}ms`)
987
+ }
988
+
989
+ // using Math.random():
990
+ benchmark(false); // Generated 100k in 90ms
991
+
992
+ // using crypto.getRandomValues():
993
+ benchmark(true); // Generated 100k in 461ms
994
+
995
+ // about a 5x slowdown, but the generated numbers are more entropic
978
996
  ```
979
997
  </details>
980
998
 
@@ -1008,6 +1026,7 @@ The options object has the following properties:
1008
1026
  | `defaultData` | The default data to use if no data is saved in persistent storage yet. Until the data is loaded from persistent storage, this will be the data returned by `getData()`. For TypeScript, the type of the data passed here is what will be used for all other methods of the instance. |
1009
1027
  | `formatVersion` | An incremental version of the data format. If the format of the data is changed in any way, this number should be incremented, in which case all necessary functions of the migrations dictionary will be run consecutively. Never decrement this number or skip numbers. |
1010
1028
  | `migrations?` | (Optional) A dictionary of functions that can be used to migrate data from older versions of the data to newer ones. The keys of the dictionary should be the format version that the functions can migrate to, from the previous whole integer value. The values should be functions that take the data in the old format and return the data in the new format. The functions will be run in order from the oldest to the newest version. If the current format version is not in the dictionary, no migrations will be run. |
1029
+ | `migrateIds?` | (Optional) A string or array of strings that migrate from one or more old IDs to the ID set in the constructor. If no data exist for the old ID(s), nothing will be done, but some time may still pass trying to fetch the non-existent data. The ID migration will be done once per session in the call to [`loadData()`](#datastoreloaddata). |
1011
1030
  | `storageMethod?` | (Optional) The method that is used to store the data. Can be `"GM"` (default), `"localStorage"` or `"sessionStorage"`. If you want to store the data in a different way, you can override the methods of the DataStore class. |
1012
1031
  | `encodeData?` | (Optional, but required when `decodeData` is set) Function that encodes the data before saving - you can use [compress()](#compress) here to save space at the cost of a little bit of performance |
1013
1032
  | `decodeData?` | (Optional, but required when `encodeData` is set) Function that decodes the data when loading - you can use [decompress()](#decompress) here to decode data that was previously compressed with [compress()](#compress) |
@@ -1018,8 +1037,9 @@ The options object has the following properties:
1018
1037
  #### `DataStore.loadData()`
1019
1038
  Usage: `loadData(): Promise<TData>`
1020
1039
  Asynchronously loads the data from persistent storage and returns it.
1021
- If no data was saved in persistent storage before, the value of `options.defaultData` will be returned and written to persistent storage.
1022
- If the formatVersion of the saved data is lower than the current one and the `options.migrations` property is present, the data will be migrated to the latest format before the Promise resolves.
1040
+ If no data was saved in persistent storage before, the value of `options.defaultData` will be returned and also written to persistent storage before resolving.
1041
+ If the `options.migrateIds` property is present and this is the first time calling this function in this session, the data will be migrated from the old ID(s) to the current one.
1042
+ Then, if the `formatVersion` of the saved data is lower than the current one and the `options.migrations` property is present, the instance will try to migrate the data to the latest format before resolving, updating the in-memory cache and persistent storage.
1023
1043
 
1024
1044
  <br>
1025
1045
 
@@ -1062,7 +1082,8 @@ If `resetOnError` is set to `false`, the migration will be aborted if an error i
1062
1082
  #### `DataStore.migrateId()`
1063
1083
  Usage: `migrateId(oldIds: string | string[]): Promise<void>`
1064
1084
  Tries to migrate the currently saved persistent data from one or more old IDs to the ID set in the constructor.
1065
- If no data exist for the old ID(s), nothing will be done, but some time may still pass trying to fetch the non-existent data.
1085
+ If no data exist for the old ID(s), nothing will be done, but some time may still pass trying to fetch the non-existent data.
1086
+ Instead of calling this manually, consider setting the `migrateIds` property in the constructor to automatically migrate the data once per session in the call to `loadData()`, unless you know that you need to migrate the ID(s) manually.
1066
1087
 
1067
1088
  <br>
1068
1089
 
@@ -1124,10 +1145,12 @@ export const manager = new DataStore({
1124
1145
  id: "my-userscript-config",
1125
1146
  /** Default, initial and fallback data */
1126
1147
  defaultData,
1127
- /** The current version of the data format */
1148
+ /** The current version of the data format - should be a whole number that is only ever incremented */
1128
1149
  formatVersion,
1129
1150
  /** Data format migration functions called when the formatVersion is increased */
1130
1151
  migrations,
1152
+ /** If the data was saved under different ID(s) before, providing them here will make sure the data is migrated to the current ID when `loadData()` is called */
1153
+ migrateIds: ["my-data", "config"],
1131
1154
  /**
1132
1155
  * Where the data should be stored.
1133
1156
  * For example, you could use `"sessionStorage"` to make the data be automatically deleted after the browser session is finished, or use `"localStorage"` if you don't have access to GM storage for some reason.
@@ -1254,7 +1277,7 @@ See the [`DataStore.loadData()`](#datastoreloaddata) method for more information
1254
1277
  },
1255
1278
  {
1256
1279
  "status": "rejected",
1257
- "reason": "Checksum mismatch for DataStore with ID \"bar-data\"!\nExpected: 69beefdead420\nHas: 420abcdef69"
1280
+ "reason": "Checksum mismatch for DataStore with ID \"bar-data\"!\nExpected: 69beefdead420\nHas: abcdef42"
1258
1281
  }
1259
1282
  ]
1260
1283
  ```
@@ -1406,25 +1429,28 @@ The options object has the following properties:
1406
1429
  #### `Dialog.open()`
1407
1430
  Usage: `open(): Promise<void>`
1408
1431
  Opens the dialog.
1432
+ If the dialog is not mounted yet, it will be mounted before opening.
1409
1433
 
1410
1434
  <br>
1411
1435
 
1412
1436
  #### `Dialog.close()`
1413
1437
  Usage: `close(): void`
1414
1438
  Closes the dialog.
1439
+ If `options.destroyOnClose` is set to `true`, [`Dialog.destroy()`](#dialogdestroy) will be called immediately after closing.
1415
1440
 
1416
1441
  <br>
1417
1442
 
1418
1443
  #### `Dialog.mount()`
1419
1444
  Usage: `mount(): Promise<void>`
1420
1445
  Mounts the dialog to the DOM by calling the render functions provided in the options object.
1421
- Can be done before opening the dialog to avoid a delay.
1446
+ After calling, the dialog will exist in the DOM but will be invisible until [`Dialog.open()`](#dialogopen) is called.
1447
+ Call this before opening the dialog to avoid a rendering delay.
1422
1448
 
1423
1449
  <br>
1424
1450
 
1425
1451
  #### `Dialog.unmount()`
1426
1452
  Usage: `unmount(): void`
1427
- Unmounts the dialog from the DOM.
1453
+ Closes the dialog first if it's open, then removes it from the DOM.
1428
1454
 
1429
1455
  <br>
1430
1456
 
@@ -1451,7 +1477,7 @@ Returns `true` if the dialog is mounted, else `false`.
1451
1477
  #### `Dialog.destroy()`
1452
1478
  Usage: `destroy(): void`
1453
1479
  Destroys the dialog.
1454
- Removes all listeners and unmounts the dialog by default.
1480
+ Removes all listeners by default and closes and unmounts the dialog.
1455
1481
 
1456
1482
  <br>
1457
1483
 
@@ -1508,6 +1534,10 @@ fooDialog.on("close", () => {
1508
1534
  console.log("Dialog closed");
1509
1535
  });
1510
1536
 
1537
+ fooDialog.on("open", () => {
1538
+ console.log("Currently open dialogs:", Dialog.getOpenDialogs());
1539
+ });
1540
+
1511
1541
  fooDialog.open();
1512
1542
  ```
1513
1543
  </details>
@@ -1587,6 +1617,7 @@ myInstance.on("foo", (bar) => {
1587
1617
  console.log("foo event (outside):", bar);
1588
1618
  });
1589
1619
 
1620
+ // only works if publicEmit is set to true
1590
1621
  myInstance.emit("baz", "hello from the outside");
1591
1622
 
1592
1623
  myInstance.unsubscribeAll();
@@ -1620,6 +1651,7 @@ myEmitter.once("baz", (qux) => {
1620
1651
  });
1621
1652
 
1622
1653
  function doStuff() {
1654
+ // only works if publicEmit is set to true
1623
1655
  myEmitter.emit("foo", "hello");
1624
1656
  myEmitter.emit("baz", 42);
1625
1657
  myEmitter.emit("foo", "world");
@@ -1900,7 +1932,7 @@ run();
1900
1932
  ### randomId()
1901
1933
  Usage:
1902
1934
  ```ts
1903
- randomId(length?: number, radix?: number, enhancedEntropy?: boolean): string
1935
+ randomId(length?: number, radix?: number, enhancedEntropy?: boolean, randomCase?: boolean): string
1904
1936
  ```
1905
1937
 
1906
1938
  Generates a random ID of a given length and [radix (base).](https://en.wikipedia.org/wiki/Radix)
@@ -1910,20 +1942,41 @@ You may change the radix to get digits from different numerical systems.
1910
1942
  Use 2 for binary, 8 for octal, 10 for decimal, 16 for hexadecimal and 36 for alphanumeric.
1911
1943
 
1912
1944
  If `enhancedEntropy` is set to true (false by default), the [Web Crypto API](https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues) is used for generating the random numbers.
1913
- Note that this takes MUCH longer, but the generated IDs will have a higher entropy.
1945
+ Note that this makes the function call take longer, but the generated IDs will have a higher entropy.
1946
+
1947
+ If `randomCase` is set to true (which it is by default), the generated ID will contain both upper and lower case letters.
1948
+ This randomization is also affected by the `enhancedEntropy` setting, unless there are no alphabetic characters in the output in which case it will be skipped.
1914
1949
 
1915
- ⚠️ Not suitable for generating anything related to cryptography! Use [SubtleCrypto's `generateKey()`](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/generateKey) for that instead.
1950
+ ⚠️ This is not suitable for generating anything related to cryptography! Use [SubtleCrypto's `generateKey()`](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/generateKey) for that instead.
1916
1951
 
1917
1952
  <details><summary><b>Example - click to view</b></summary>
1918
1953
 
1919
1954
  ```ts
1920
1955
  import { randomId } from "@sv443-network/userutils";
1921
1956
 
1922
- randomId(); // "1bda419a73629d4f" (length 16, radix 16)
1923
- randomId(10); // "f86cd354a4" (length 10, radix 16)
1924
- randomId(10, 2); // "1010001101" (length 10, radix 2)
1925
- randomId(10, 10); // "0183428506" (length 10, radix 10)
1926
- randomId(10, 36); // "z46jfpa37r" (length 10, radix 36)
1957
+ randomId(); // "1bda419a73629d4f" (length 16, radix 16)
1958
+ randomId(10); // "f86cd354a4" (length 10, radix 16)
1959
+ randomId(10, 2); // "1010001101" (length 10, radix 2)
1960
+ randomId(10, 10); // "0183428506" (length 10, radix 10)
1961
+ randomId(10, 36, false, true); // "z46jFPa37R" (length 10, radix 36, random case)
1962
+
1963
+
1964
+ function benchmark(enhancedEntropy: boolean, randomCase: boolean) {
1965
+ const timestamp = Date.now();
1966
+ for(let i = 0; i < 10_000; i++)
1967
+ randomId(16, 36, enhancedEntropy, randomCase);
1968
+ console.log(`Generated 10k in ${Date.now() - timestamp}ms`)
1969
+ }
1970
+
1971
+ // using Math.random():
1972
+ benchmark(false, false); // Generated 10k in 239ms
1973
+ benchmark(false, true); // Generated 10k in 248ms
1974
+
1975
+ // using crypto.getRandomValues():
1976
+ benchmark(true, false); // Generated 10k in 1076ms
1977
+ benchmark(true, true); // Generated 10k in 1054ms
1978
+
1979
+ // 3rd and 4th have a similar time, but in reality the 4th blocks the event loop for much longer
1927
1980
  ```
1928
1981
  </details>
1929
1982
 
@@ -2411,7 +2464,7 @@ Usage:
2411
2464
  NonEmptyArray<TItem = unknown>
2412
2465
  ```
2413
2466
 
2414
- This type describes an array that has at least one item.
2467
+ This generic type describes an array that has at least one item.
2415
2468
  Use the generic parameter to specify the type of the items in the array.
2416
2469
 
2417
2470
  <details><summary><b>Example - click to view</b></summary>
@@ -2441,7 +2494,7 @@ Usage:
2441
2494
  NonEmptyString<TString extends string>
2442
2495
  ```
2443
2496
 
2444
- This type describes a string that has at least one character.
2497
+ This generic type describes a string that has at least one character.
2445
2498
 
2446
2499
  <details><summary><b>Example - click to view</b></summary>
2447
2500
 
@@ -2465,7 +2518,7 @@ Usage:
2465
2518
  LooseUnion<TUnion extends string | number | object>
2466
2519
  ```
2467
2520
 
2468
- A type that offers autocomplete in the IDE for the passed union but also allows any value of the same type to be passed.
2521
+ A generic type that offers autocomplete in the IDE for the passed union but also allows any value of the same type to be passed.
2469
2522
  Supports unions of strings, numbers and objects.
2470
2523
 
2471
2524
  <details><summary><b>Example - click to view</b></summary>
@@ -2484,6 +2537,61 @@ foo(1); // type error: Argument of type '1' is not assignable to parameter of
2484
2537
  ```
2485
2538
  </details>
2486
2539
 
2540
+ <br>
2541
+
2542
+ ## Prettify
2543
+ Usage:
2544
+ ```ts
2545
+ Prettify<T>
2546
+ ```
2547
+
2548
+ A generic type that makes TypeScript and your IDE display the type in a more readable way.
2549
+ This is especially useful for types that reference other types or are very complex.
2550
+ It will also make a variable show its type's structure instead of just the type name (see example).
2551
+
2552
+ <details><summary><b>Example - click to view</b></summary>
2553
+
2554
+ ```ts
2555
+ // tooltip shows all constituent types, leaving you to figure it out yourself:
2556
+ // type Foo = {
2557
+ // a: number;
2558
+ // } & Omit<{
2559
+ // b: string;
2560
+ // c: boolean;
2561
+ // }, "c">
2562
+ type Foo = {
2563
+ a: number;
2564
+ } & Omit<{
2565
+ b: string;
2566
+ c: boolean;
2567
+ }, "c">;
2568
+
2569
+ // tooltip shows just the type name:
2570
+ // const foo: Foo
2571
+ const foo: Foo = {
2572
+ a: 1,
2573
+ b: "2"
2574
+ };
2575
+
2576
+ // tooltip shows the actual type structure:
2577
+ // type Bar = {
2578
+ // a: number;
2579
+ // b: string;
2580
+ // }
2581
+ type Bar = Prettify<Foo>;
2582
+
2583
+ // tooltip again shows the actual type structure:
2584
+ // const bar: {
2585
+ // a: number;
2586
+ // b: string;
2587
+ // }
2588
+ const bar: Bar = {
2589
+ a: 1,
2590
+ b: "2"
2591
+ };
2592
+ ```
2593
+ </details>
2594
+
2487
2595
  <br><br><br><br>
2488
2596
 
2489
2597
  <!-- #region Footer -->
@@ -8,7 +8,7 @@
8
8
  // ==UserLibrary==
9
9
  // @name UserUtils
10
10
  // @description Library with various utilities for userscripts - register listeners for when CSS selectors exist, intercept events, create persistent & synchronous data stores, modify the DOM more easily and more
11
- // @version 8.1.0
11
+ // @version 8.2.0
12
12
  // @license MIT
13
13
  // @copyright Sv443 (https://github.com/Sv443)
14
14
 
@@ -78,12 +78,18 @@ var UserUtils = (function (exports) {
78
78
  return Math.max(Math.min(value, max), min);
79
79
  }
80
80
  function mapRange(value, range1min, range1max, range2min, range2max) {
81
+ if (typeof range2min === "undefined" || range2max === void 0) {
82
+ range2max = range1max;
83
+ range2min = 0;
84
+ range1max = range1min;
85
+ range1min = 0;
86
+ }
81
87
  if (Number(range1min) === 0 && Number(range2min) === 0)
82
88
  return value * (range2max / range1max);
83
89
  return (value - range1min) * ((range2max - range2min) / (range1max - range1min)) + range2min;
84
90
  }
85
91
  function randRange(...args) {
86
- let min, max;
92
+ let min, max, enhancedEntropy = false;
87
93
  if (typeof args[0] === "number" && typeof args[1] === "number")
88
94
  [min, max] = args;
89
95
  else if (typeof args[0] === "number" && typeof args[1] !== "number") {
@@ -91,13 +97,25 @@ var UserUtils = (function (exports) {
91
97
  [max] = args;
92
98
  } else
93
99
  throw new TypeError(`Wrong parameter(s) provided - expected: "number" and "number|undefined", got: "${typeof args[0]}" and "${typeof args[1]}"`);
100
+ if (typeof args[2] === "boolean")
101
+ enhancedEntropy = args[2];
102
+ else if (typeof args[1] === "boolean")
103
+ enhancedEntropy = args[1];
94
104
  min = Number(min);
95
105
  max = Number(max);
96
106
  if (isNaN(min) || isNaN(max))
97
107
  return NaN;
98
108
  if (min > max)
99
109
  throw new TypeError(`Parameter "min" can't be bigger than "max"`);
100
- return Math.floor(Math.random() * (max - min + 1)) + min;
110
+ if (enhancedEntropy) {
111
+ const uintArr = new Uint8Array(1);
112
+ crypto.getRandomValues(uintArr);
113
+ return Number(Array.from(
114
+ uintArr,
115
+ (v) => Math.round(mapRange(v, 0, 255, min, max)).toString(10).substring(0, 1)
116
+ ).join(""));
117
+ } else
118
+ return Math.floor(Math.random() * (max - min + 1)) + min;
101
119
  }
102
120
 
103
121
  // lib/array.ts
@@ -356,19 +374,25 @@ var UserUtils = (function (exports) {
356
374
  return hashHex;
357
375
  });
358
376
  }
359
- function randomId(length = 16, radix = 16, enhancedEntropy = false) {
377
+ function randomId(length = 16, radix = 16, enhancedEntropy = false, randomCase = true) {
378
+ let arr = [];
379
+ const caseArr = randomCase ? [0, 1] : [0];
360
380
  if (enhancedEntropy) {
361
- const arr = new Uint8Array(length);
362
- crypto.getRandomValues(arr);
363
- return Array.from(
364
- arr,
381
+ const uintArr = new Uint8Array(length);
382
+ crypto.getRandomValues(uintArr);
383
+ arr = Array.from(
384
+ uintArr,
365
385
  (v) => mapRange(v, 0, 255, 0, radix).toString(radix).substring(0, 1)
366
- ).join("");
386
+ );
387
+ } else {
388
+ arr = Array.from(
389
+ { length },
390
+ () => Math.floor(Math.random() * radix).toString(radix)
391
+ );
367
392
  }
368
- return Array.from(
369
- { length },
370
- () => Math.floor(Math.random() * radix).toString(radix)
371
- ).join("");
393
+ if (!arr.some((v) => /[a-zA-Z]/.test(v)))
394
+ return arr.join("");
395
+ return arr.map((v) => caseArr[randRange(0, caseArr.length - 1, enhancedEntropy)] === 1 ? v.toUpperCase() : v).join("");
372
396
  }
373
397
 
374
398
  // lib/DataStore.ts
@@ -392,12 +416,15 @@ var UserUtils = (function (exports) {
392
416
  __publicField(this, "storageMethod");
393
417
  __publicField(this, "cachedData");
394
418
  __publicField(this, "migrations");
419
+ __publicField(this, "migrateIds", []);
395
420
  var _a;
396
421
  this.id = options.id;
397
422
  this.formatVersion = options.formatVersion;
398
423
  this.defaultData = options.defaultData;
399
424
  this.cachedData = options.defaultData;
400
425
  this.migrations = options.migrations;
426
+ if (options.migrateIds)
427
+ this.migrateIds = Array.isArray(options.migrateIds) ? options.migrateIds : [options.migrateIds];
401
428
  this.storageMethod = (_a = options.storageMethod) != null ? _a : "GM";
402
429
  this.encodeData = options.encodeData;
403
430
  this.decodeData = options.decodeData;
@@ -411,6 +438,10 @@ var UserUtils = (function (exports) {
411
438
  loadData() {
412
439
  return __async(this, null, function* () {
413
440
  try {
441
+ if (this.migrateIds.length > 0) {
442
+ yield this.migrateId(this.migrateIds);
443
+ this.migrateIds = [];
444
+ }
414
445
  const gmData = yield this.getValue(`_uucfg-${this.id}`, JSON.stringify(this.defaultData));
415
446
  let gmFmtVer = Number(yield this.getValue(`_uucfgver-${this.id}`, NaN));
416
447
  if (typeof gmData !== "string") {
package/dist/index.js CHANGED
@@ -58,12 +58,18 @@ function clamp(value, min, max) {
58
58
  return Math.max(Math.min(value, max), min);
59
59
  }
60
60
  function mapRange(value, range1min, range1max, range2min, range2max) {
61
+ if (typeof range2min === "undefined" || range2max === void 0) {
62
+ range2max = range1max;
63
+ range2min = 0;
64
+ range1max = range1min;
65
+ range1min = 0;
66
+ }
61
67
  if (Number(range1min) === 0 && Number(range2min) === 0)
62
68
  return value * (range2max / range1max);
63
69
  return (value - range1min) * ((range2max - range2min) / (range1max - range1min)) + range2min;
64
70
  }
65
71
  function randRange(...args) {
66
- let min, max;
72
+ let min, max, enhancedEntropy = false;
67
73
  if (typeof args[0] === "number" && typeof args[1] === "number")
68
74
  [min, max] = args;
69
75
  else if (typeof args[0] === "number" && typeof args[1] !== "number") {
@@ -71,13 +77,25 @@ function randRange(...args) {
71
77
  [max] = args;
72
78
  } else
73
79
  throw new TypeError(`Wrong parameter(s) provided - expected: "number" and "number|undefined", got: "${typeof args[0]}" and "${typeof args[1]}"`);
80
+ if (typeof args[2] === "boolean")
81
+ enhancedEntropy = args[2];
82
+ else if (typeof args[1] === "boolean")
83
+ enhancedEntropy = args[1];
74
84
  min = Number(min);
75
85
  max = Number(max);
76
86
  if (isNaN(min) || isNaN(max))
77
87
  return NaN;
78
88
  if (min > max)
79
89
  throw new TypeError(`Parameter "min" can't be bigger than "max"`);
80
- return Math.floor(Math.random() * (max - min + 1)) + min;
90
+ if (enhancedEntropy) {
91
+ const uintArr = new Uint8Array(1);
92
+ crypto.getRandomValues(uintArr);
93
+ return Number(Array.from(
94
+ uintArr,
95
+ (v) => Math.round(mapRange(v, 0, 255, min, max)).toString(10).substring(0, 1)
96
+ ).join(""));
97
+ } else
98
+ return Math.floor(Math.random() * (max - min + 1)) + min;
81
99
  }
82
100
 
83
101
  // lib/array.ts
@@ -336,19 +354,25 @@ function computeHash(input, algorithm = "SHA-256") {
336
354
  return hashHex;
337
355
  });
338
356
  }
339
- function randomId(length = 16, radix = 16, enhancedEntropy = false) {
357
+ function randomId(length = 16, radix = 16, enhancedEntropy = false, randomCase = true) {
358
+ let arr = [];
359
+ const caseArr = randomCase ? [0, 1] : [0];
340
360
  if (enhancedEntropy) {
341
- const arr = new Uint8Array(length);
342
- crypto.getRandomValues(arr);
343
- return Array.from(
344
- arr,
361
+ const uintArr = new Uint8Array(length);
362
+ crypto.getRandomValues(uintArr);
363
+ arr = Array.from(
364
+ uintArr,
345
365
  (v) => mapRange(v, 0, 255, 0, radix).toString(radix).substring(0, 1)
346
- ).join("");
366
+ );
367
+ } else {
368
+ arr = Array.from(
369
+ { length },
370
+ () => Math.floor(Math.random() * radix).toString(radix)
371
+ );
347
372
  }
348
- return Array.from(
349
- { length },
350
- () => Math.floor(Math.random() * radix).toString(radix)
351
- ).join("");
373
+ if (!arr.some((v) => /[a-zA-Z]/.test(v)))
374
+ return arr.join("");
375
+ return arr.map((v) => caseArr[randRange(0, caseArr.length - 1, enhancedEntropy)] === 1 ? v.toUpperCase() : v).join("");
352
376
  }
353
377
 
354
378
  // lib/DataStore.ts
@@ -372,12 +396,15 @@ var DataStore = class {
372
396
  __publicField(this, "storageMethod");
373
397
  __publicField(this, "cachedData");
374
398
  __publicField(this, "migrations");
399
+ __publicField(this, "migrateIds", []);
375
400
  var _a;
376
401
  this.id = options.id;
377
402
  this.formatVersion = options.formatVersion;
378
403
  this.defaultData = options.defaultData;
379
404
  this.cachedData = options.defaultData;
380
405
  this.migrations = options.migrations;
406
+ if (options.migrateIds)
407
+ this.migrateIds = Array.isArray(options.migrateIds) ? options.migrateIds : [options.migrateIds];
381
408
  this.storageMethod = (_a = options.storageMethod) != null ? _a : "GM";
382
409
  this.encodeData = options.encodeData;
383
410
  this.decodeData = options.decodeData;
@@ -391,6 +418,10 @@ var DataStore = class {
391
418
  loadData() {
392
419
  return __async(this, null, function* () {
393
420
  try {
421
+ if (this.migrateIds.length > 0) {
422
+ yield this.migrateId(this.migrateIds);
423
+ this.migrateIds = [];
424
+ }
394
425
  const gmData = yield this.getValue(`_uucfg-${this.id}`, JSON.stringify(this.defaultData));
395
426
  let gmFmtVer = Number(yield this.getValue(`_uucfgver-${this.id}`, NaN));
396
427
  if (typeof gmData !== "string") {
@@ -33,6 +33,13 @@ export type DataStoreOptions<TData> = {
33
33
  * If the current format version is not in the dictionary, no migrations will be run.
34
34
  */
35
35
  migrations?: DataMigrationsDict;
36
+ /**
37
+ * If an ID or multiple IDs are passed here, the data will be migrated from the old ID(s) to the current ID.
38
+ * This will happen once per page load, when {@linkcode DataStore.loadData()} is called.
39
+ * All future calls to {@linkcode DataStore.loadData()} in the session will not check for the old ID(s) anymore.
40
+ * To migrate IDs manually, use the method {@linkcode DataStore.migrateId()} instead.
41
+ */
42
+ migrateIds?: string | string[];
36
43
  /**
37
44
  * Where the data should be saved (`"GM"` by default).
38
45
  * The protected methods {@linkcode DataStore.getValue()}, {@linkcode DataStore.setValue()} and {@linkcode DataStore.deleteValue()} are used to interact with the storage.
@@ -83,6 +90,7 @@ export declare class DataStore<TData extends object = object> {
83
90
  readonly storageMethod: Required<DataStoreOptions<TData>>["storageMethod"];
84
91
  private cachedData;
85
92
  private migrations?;
93
+ private migrateIds;
86
94
  /**
87
95
  * Creates an instance of DataStore to manage a sync & async database that is cached in memory and persistently saved across sessions.
88
96
  * Supports migrating data from older versions to newer ones and populating the cache with default data if no persistent data is found.
@@ -19,6 +19,7 @@ export declare function computeHash(input: string | ArrayBuffer, algorithm?: str
19
19
  * ⚠️ Not suitable for generating anything related to cryptography! Use [SubtleCrypto's `generateKey()`](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/generateKey) for that instead.
20
20
  * @param length The length of the ID to generate (defaults to 16)
21
21
  * @param radix The [radix](https://en.wikipedia.org/wiki/Radix) of each digit (defaults to 16 which is hexadecimal. Use 2 for binary, 10 for decimal, 36 for alphanumeric, etc.)
22
- * @param enhancedEntropy If set to true, uses [`crypto.getRandomValues()`](https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues) for better cryptographic randomness (this also makes it take MUCH longer to generate)
22
+ * @param enhancedEntropy If set to true, uses [`crypto.getRandomValues()`](https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues) for better cryptographic randomness (this also makes it take longer to generate)
23
+ * @param randomCase If set to false, the generated ID will be lowercase only - also makes use of the `enhancedEntropy` parameter unless the output doesn't contain letters
23
24
  */
24
- export declare function randomId(length?: number, radix?: number, enhancedEntropy?: boolean): string;
25
+ export declare function randomId(length?: number, radix?: number, enhancedEntropy?: boolean, randomCase?: boolean): string;
@@ -1,11 +1,22 @@
1
1
  /** Ensures the passed {@linkcode value} always stays between {@linkcode min} and {@linkcode max} */
2
2
  export declare function clamp(value: number, min: number, max: number): number;
3
3
  /**
4
- * Transforms the value parameter from the numerical range `range1minrange1max` to the numerical range `range2minrange2max`
4
+ * Transforms the value parameter from the numerical range `range1min` to `range1max` to the numerical range `range2min` to `range2max`
5
5
  * For example, you can map the value 2 in the range of 0-5 to the range of 0-10 and you'd get a 4 as a result.
6
6
  */
7
7
  export declare function mapRange(value: number, range1min: number, range1max: number, range2min: number, range2max: number): number;
8
- /** Returns a random number between {@linkcode min} and {@linkcode max} (inclusive) */
9
- export declare function randRange(min: number, max: number): number;
10
- /** Returns a random number between 0 and {@linkcode max} (inclusive) */
11
- export declare function randRange(max: number): number;
8
+ /**
9
+ * Transforms the value parameter from the numerical range `0` to `range1max` to the numerical range `0` to `range2max`
10
+ * For example, you can map the value 2 in the range of 0-5 to the range of 0-10 and you'd get a 4 as a result.
11
+ */
12
+ export declare function mapRange(value: number, range1max: number, range2max: number): number;
13
+ /**
14
+ * Returns a random number between {@linkcode min} and {@linkcode max} (inclusive)
15
+ * Set {@linkcode enhancedEntropy} to true to use `crypto.getRandomValues()` for better cryptographic randomness (this also makes it take longer to generate)
16
+ */
17
+ export declare function randRange(min: number, max: number, enhancedEntropy?: boolean): number;
18
+ /**
19
+ * Returns a random number between 0 and {@linkcode max} (inclusive)
20
+ * Set {@linkcode enhancedEntropy} to true to use `crypto.getRandomValues()` for better cryptographic randomness (this also makes it take longer to generate)
21
+ */
22
+ export declare function randRange(max: number, enhancedEntropy?: boolean): number;
@@ -15,3 +15,10 @@ export type LooseUnion<TUnion extends string | number | object> = (TUnion) | (TU
15
15
  * }
16
16
  */
17
17
  export type NonEmptyString<TString extends string> = TString extends "" ? never : TString;
18
+ /**
19
+ * Makes the structure of a type more readable by expanding it.
20
+ * This can be useful for debugging or for improving the readability of complex types.
21
+ */
22
+ export type Prettify<T> = {
23
+ [K in keyof T]: T[K];
24
+ } & {};
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@sv443-network/userutils",
3
3
  "libName": "UserUtils",
4
- "version": "8.1.0",
4
+ "version": "8.2.0",
5
5
  "description": "Library with various utilities for userscripts - register listeners for when CSS selectors exist, intercept events, create persistent & synchronous data stores, modify the DOM more easily and more",
6
6
  "main": "dist/index.js",
7
7
  "module": "dist/index.js",