@sv443-network/userutils 9.3.0 → 9.4.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.
@@ -7,18 +7,65 @@ export interface NanoEmitterOptions {
7
7
  /** If set to true, allows emitting events through the public method emit() */
8
8
  publicEmit: boolean;
9
9
  }
10
- /** Class that can be extended or instantiated by itself to create an event emitter with helper methods and a strongly typed event map */
10
+ /**
11
+ * Class that can be extended or instantiated by itself to create a lightweight event emitter with helper methods and a strongly typed event map.
12
+ * If extended from, you can use `this.events.emit()` to emit events, even if the `emit()` method doesn't work because `publicEmit` is not set to true in the constructor.
13
+ */
11
14
  export declare class NanoEmitter<TEvtMap extends EventsMap = DefaultEvents> {
12
15
  protected readonly events: Emitter<TEvtMap>;
13
16
  protected eventUnsubscribes: Unsubscribe[];
14
17
  protected emitterOptions: NanoEmitterOptions;
18
+ /** Creates a new instance of NanoEmitter - a lightweight event emitter with helper methods and a strongly typed event map */
15
19
  constructor(options?: Partial<NanoEmitterOptions>);
16
- /** Subscribes to an event - returns a function that unsubscribes the event listener */
20
+ /**
21
+ * Subscribes to an event and calls the callback when it's emitted.
22
+ * @param event The event to subscribe to. Use `as "_"` in case your event names aren't thoroughly typed (like when using a template literal, e.g. \`event-${val}\` as "_")
23
+ * @returns Returns a function that can be called to unsubscribe the event listener
24
+ * @example ```ts
25
+ * const emitter = new NanoEmitter<{
26
+ * foo: (bar: string) => void;
27
+ * }>({
28
+ * publicEmit: true,
29
+ * });
30
+ *
31
+ * let i = 0;
32
+ * const unsub = emitter.on("foo", (bar) => {
33
+ * // unsubscribe after 10 events:
34
+ * if(++i === 10) unsub();
35
+ * console.log(bar);
36
+ * });
37
+ *
38
+ * emitter.emit("foo", "bar");
39
+ * ```
40
+ */
17
41
  on<TKey extends keyof TEvtMap>(event: TKey | "_", cb: TEvtMap[TKey]): () => void;
18
- /** Subscribes to an event and calls the callback or resolves the Promise only once */
42
+ /**
43
+ * Subscribes to an event and calls the callback or resolves the Promise only once when it's emitted.
44
+ * @param event The event to subscribe to. Use `as "_"` in case your event names aren't thoroughly typed (like when using a template literal, e.g. \`event-${val}\` as "_")
45
+ * @param cb The callback to call when the event is emitted - if provided or not, the returned Promise will resolve with the event arguments
46
+ * @returns Returns a Promise that resolves with the event arguments when the event is emitted
47
+ * @example ```ts
48
+ * const emitter = new NanoEmitter<{
49
+ * foo: (bar: string) => void;
50
+ * }>();
51
+ *
52
+ * // Promise syntax:
53
+ * const [bar] = await emitter.once("foo");
54
+ * console.log(bar);
55
+ *
56
+ * // Callback syntax:
57
+ * emitter.once("foo", (bar) => console.log(bar));
58
+ * ```
59
+ */
19
60
  once<TKey extends keyof TEvtMap>(event: TKey | "_", cb?: TEvtMap[TKey]): Promise<Parameters<TEvtMap[TKey]>>;
20
- /** Emits an event on this instance - Needs `publicEmit` to be set to true in the constructor! */
61
+ /**
62
+ * Emits an event on this instance.
63
+ * ⚠️ Needs `publicEmit` to be set to true in the NanoEmitter constructor or super() call!
64
+ * @param event The event to emit
65
+ * @param args The arguments to pass to the event listeners
66
+ * @returns Returns true if `publicEmit` is true and the event was emitted successfully
67
+ */
21
68
  emit<TKey extends keyof TEvtMap>(event: TKey, ...args: Parameters<TEvtMap[TKey]>): boolean;
22
- /** Unsubscribes all event listeners */
69
+ /** Unsubscribes all event listeners from this instance */
23
70
  unsubscribeAll(): void;
24
71
  }
package/dist/lib/dom.d.ts CHANGED
@@ -20,7 +20,7 @@ export declare function addParent<TElem extends Element, TParentElem extends Ele
20
20
  export declare function addGlobalStyle(style: string): HTMLStyleElement;
21
21
  /**
22
22
  * Preloads an array of image URLs so they can be loaded instantly from the browser cache later on
23
- * @param rejects If set to `true`, the returned PromiseSettledResults will contain rejections for any of the images that failed to load
23
+ * @param rejects If set to `true`, the returned PromiseSettledResults will contain rejections for any of the images that failed to load. Is set to `false` by default.
24
24
  * @returns Returns an array of `PromiseSettledResult` - each resolved result will contain the loaded image element, while each rejected result will contain an `ErrorEvent`
25
25
  */
26
26
  export declare function preloadImages(srcUrls: string[], rejects?: boolean): Promise<PromiseSettledResult<HTMLImageElement>[]>;
@@ -13,6 +13,7 @@ export * from "./dom.js";
13
13
  export * from "./errors.js";
14
14
  export * from "./math.js";
15
15
  export * from "./misc.js";
16
+ export * from "./Mixins.js";
16
17
  export * from "./NanoEmitter.js";
17
18
  export * from "./SelectorObserver.js";
18
19
  export * from "./translation.js";
@@ -165,7 +165,7 @@ declare function addTransform<TTrKey extends string = string>(transform: Transfo
165
165
  * @param patternOrFn A reference to the regular expression of the transform function, a string matching the original pattern, or a reference to the transform function to delete
166
166
  * @returns Returns true if the transform function was found and deleted, false if it wasn't found
167
167
  */
168
- declare function deleteTransform(patternOrFn: RegExp | string | TransformFn): boolean;
168
+ declare function deleteTransform(patternOrFn: RegExp | TransformFn): boolean;
169
169
  declare const tr: {
170
170
  for: <TTrKey extends string = string>(language: string, key: TTrKey, ...args: (Stringifiable | Record<string, Stringifiable>)[]) => ReturnType<typeof trFor<TTrKey>>;
171
171
  use: <TTrKey extends string = string>(language: string) => ReturnType<typeof useTr<TTrKey>>;
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@sv443-network/userutils",
3
3
  "libName": "UserUtils",
4
- "version": "9.3.0",
4
+ "version": "9.4.0",
5
5
  "description": "General purpose DOM/GreaseMonkey library that allows you to register listeners for when CSS selectors exist, intercept events, create persistent & synchronous data stores, modify the DOM more easily and much more",
6
6
  "main": "dist/index.js",
7
7
  "module": "dist/index.js",
@@ -14,6 +14,11 @@
14
14
  "import": "./dist/index.js"
15
15
  }
16
16
  },
17
+ "engines": {
18
+ "pnpm": ">=9",
19
+ "npm": "please-use-pnpm",
20
+ "yarn": "please-use-pnpm"
21
+ },
17
22
  "type": "module",
18
23
  "repository": {
19
24
  "type": "git",
@@ -38,6 +43,8 @@
38
43
  "devDependencies": {
39
44
  "@changesets/cli": "^2.27.11",
40
45
  "@eslint/eslintrc": "^3.2.0",
46
+ "@eslint/js": "^9.23.0",
47
+ "@testing-library/dom": "^10.4.0",
41
48
  "@types/express": "^4.17.21",
42
49
  "@types/greasemonkey": "^4.0.7",
43
50
  "@types/node": "^22.10.5",
@@ -45,15 +52,18 @@
45
52
  "@typescript-eslint/eslint-plugin": "^8.21.0",
46
53
  "@typescript-eslint/parser": "^8.21.0",
47
54
  "@typescript-eslint/utils": "^8.21.0",
55
+ "@vitest/coverage-v8": "^3.0.9",
48
56
  "concurrently": "^8.2.2",
49
57
  "eslint": "^9.18.0",
50
58
  "express": "^4.21.2",
51
59
  "globals": "^15.14.0",
60
+ "jsdom": "^26.0.0",
52
61
  "kleur": "^4.1.5",
53
62
  "tslib": "^2.8.1",
54
63
  "tsup": "^8.3.5",
55
64
  "tsx": "^4.19.2",
56
- "typescript": "^5.7.3"
65
+ "typescript": "^5.7.3",
66
+ "vitest": "^3.0.9"
57
67
  },
58
68
  "files": [
59
69
  "/dist/index.js",
@@ -63,7 +73,7 @@
63
73
  "/dist/index.umd.js",
64
74
  "/dist/lib/**.d.ts",
65
75
  "/package.json",
66
- "/README-summary.md",
76
+ "/README.md",
67
77
  "/CHANGELOG.md",
68
78
  "/LICENSE.txt"
69
79
  ],
@@ -81,8 +91,10 @@
81
91
  "publish-package-jsr": "pnpm update-jsr-version && npx jsr publish --allow-dirty",
82
92
  "check-jsr": "npx jsr publish --allow-dirty --dry-run",
83
93
  "change": "changeset",
84
- "test-serve": "node --import tsx ./test/TestPage/server.mts",
85
- "test-dev": "cd test/TestScript && pnpm dev",
86
- "test": "concurrently \"pnpm test-serve\" \"pnpm test-dev\""
94
+ "test-gm-serve": "node --import tsx ./test/TestPage/server.mts",
95
+ "test-gm-dev": "cd test/TestScript && pnpm dev",
96
+ "test-gm": "concurrently \"pnpm test-gm-serve\" \"pnpm test-gm-dev\"",
97
+ "test": "vitest --passWithNoTests",
98
+ "test-coverage": "vitest --passWithNoTests --coverage"
87
99
  }
88
100
  }
package/README-summary.md DELETED
@@ -1,214 +0,0 @@
1
- ## UserUtils
2
- General purpose DOM/GreaseMonkey library that allows you to register listeners for when CSS selectors exist, intercept events, create persistent & synchronous data stores, modify the DOM more easily and much more.
3
- Contains builtin TypeScript declarations. Supports ESM and CJS imports via a bundler and global declaration via `@require`
4
- The library works in any DOM environment with or without the [GreaseMonkey API](https://wiki.greasespot.net/Greasemonkey_Manual:API), but some features will be unavailable or limited.
5
-
6
- You may want to check out my [template for userscripts in TypeScript](https://github.com/Sv443/Userscript.ts) that you can use to get started quickly. It also includes this library by default.
7
-
8
- If you like using this library, please consider [supporting the development ❤️](https://github.com/sponsors/Sv443)
9
-
10
- <br>
11
-
12
- [![minified bundle size badge](https://badgen.net/bundlephobia/min/@sv443-network/userutils)](https://bundlephobia.com/package/@sv443-network/userutils)
13
- [![minified and gzipped bundle size badge](https://badgen.net/bundlephobia/minzip/@sv443-network/userutils)](https://bundlephobia.com/package/@sv443-network/userutils)
14
- [![tree shaking support badge](https://badgen.net/bundlephobia/tree-shaking/@sv443-network/userutils)](https://bundlephobia.com/package/@sv443-network/userutils)
15
-
16
- [![github stargazers badge](https://badgen.net/github/stars/Sv443-Network/UserUtils?icon=github)](https://github.com/Sv443-Network/UserUtils/stargazers)
17
- [![discord server badge](https://badgen.net/discord/online-members/aBH4uRG?icon=discord)](https://dc.sv443.net/)
18
-
19
- <br>
20
-
21
- ## &gt; [Full documentation on GitHub](https://github.com/Sv443-Network/UserUtils/blob/main/docs.md#readme) &lt;
22
-
23
- <br>
24
-
25
- <span style="font-size: 0.8em;">
26
-
27
- View the documentation of previous major releases:
28
- <a href="https://github.com/Sv443-Network/UserUtils/blob/v8.0.0/README.md" rel="noopener noreferrer">8.0.0</a>, <a href="https://github.com/Sv443-Network/UserUtils/blob/v7.0.0/README.md" rel="noopener noreferrer">7.0.0</a>, <a href="https://github.com/Sv443-Network/UserUtils/blob/v6.0.0/README.md" rel="noopener noreferrer">6.0.0</a>, <a href="https://github.com/Sv443-Network/UserUtils/blob/v5.0.0/README.md" rel="noopener noreferrer">5.0.0</a>, <a href="https://github.com/Sv443-Network/UserUtils/blob/v4.0.0/README.md" rel="noopener noreferrer">4.0.0</a>, <a href="https://github.com/Sv443-Network/UserUtils/blob/v3.0.0/README.md" rel="noopener noreferrer">3.0.0</a>, <a href="https://github.com/Sv443-Network/UserUtils/blob/v2.0.0/README.md" rel="noopener noreferrer">2.0.0</a>, <a href="https://github.com/Sv443-Network/UserUtils/blob/v1.0.0/README.md" rel="noopener noreferrer">1.0.0</a>, <a href="https://github.com/Sv443-Network/UserUtils/blob/v0.5.3/README.md" rel="noopener noreferrer">0.5.3</a>
29
- <!-- <a href="https://github.com/Sv443-Network/UserUtils/blob/vX.0.0/docs.md" rel="noopener noreferrer">X.0.0</a>, -->
30
- </span>
31
-
32
- <br>
33
-
34
- <!-- https://github.com/Sv443-Network/UserUtils < #foo -->
35
- ## Feature Summary:
36
- - **DOM:**
37
- - [`SelectorObserver`](https://github.com/Sv443-Network/UserUtils/blob/main/docs.md#selectorobserver) - class that manages listeners that are called when selectors are found in the DOM
38
- - [`getUnsafeWindow()`](https://github.com/Sv443-Network/UserUtils/blob/main/docs.md#getunsafewindow) - get the unsafeWindow object or fall back to the regular window object
39
- - [`isDomLoaded()`](https://github.com/Sv443-Network/UserUtils/blob/main/docs.md#isdomloaded) - check if the DOM has finished loading and can be queried and modified
40
- - [`onDomLoad()`](https://github.com/Sv443-Network/UserUtils/blob/main/docs.md#ondomload) - run a function or pause async execution until the DOM has finished loading (or immediately if DOM is already loaded)
41
- - [`addParent()`](https://github.com/Sv443-Network/UserUtils/blob/main/docs.md#addparent) - add a parent element around another element
42
- - [`addGlobalStyle()`](https://github.com/Sv443-Network/UserUtils/blob/main/docs.md#addglobalstyle) - add a global style to the page
43
- - [`preloadImages()`](https://github.com/Sv443-Network/UserUtils/blob/main/docs.md#preloadimages) - preload images into the browser cache for faster loading later on
44
- - [`openInNewTab()`](https://github.com/Sv443-Network/UserUtils/blob/main/docs.md#openinnewtab) - open a link in a new tab
45
- - [`interceptEvent()`](https://github.com/Sv443-Network/UserUtils/blob/main/docs.md#interceptevent) - conditionally intercepts events registered by `addEventListener()` on any given EventTarget object
46
- - [`interceptWindowEvent()`](https://github.com/Sv443-Network/UserUtils/blob/main/docs.md#interceptwindowevent) - conditionally intercepts events registered by `addEventListener()` on the window object
47
- - [`isScrollable()`](https://github.com/Sv443-Network/UserUtils/blob/main/docs.md#isscrollable) - check if an element has a horizontal or vertical scroll bar
48
- - [`observeElementProp()`](https://github.com/Sv443-Network/UserUtils/blob/main/docs.md#observeelementprop) - observe changes to an element's property that can't be observed with MutationObserver
49
- - [`getSiblingsFrame()`](https://github.com/Sv443-Network/UserUtils/blob/main/docs.md#getsiblingsframe) - returns a frame of an element's siblings, with a given alignment and size
50
- - [`setInnerHtmlUnsafe()`](https://github.com/Sv443-Network/UserUtils/blob/main/docs.md#setinnerhtmlunsafe) - set the innerHTML of an element using a [Trusted Types policy](https://developer.mozilla.org/en-US/docs/Web/API/Trusted_Types_API) without sanitizing or escaping it
51
- - [`probeElementStyle()`](https://github.com/Sv443-Network/UserUtils/blob/main/docs.md#probeelementstyle) - probe the computed style of a temporary element (get default font size, resolve CSS variables, etc.)
52
- - **Math:**
53
- - [`clamp()`](https://github.com/Sv443-Network/UserUtils/blob/main/docs.md#clamp) - constrain a number between a min and max value
54
- - [`mapRange()`](https://github.com/Sv443-Network/UserUtils/blob/main/docs.md#maprange) - map a number from one range to the same spot in another range
55
- - [`randRange()`](https://github.com/Sv443-Network/UserUtils/blob/main/docs.md#randrange) - generate a random number between a min and max boundary
56
- - [`digitCount()`](https://github.com/Sv443-Network/UserUtils/blob/main/docs.md#digitcount) - calculate the amount of digits in a number
57
- - [`roundFixed()`](https://github.com/Sv443-Network/UserUtils/blob/main/docs.md#roundfixed) - round a floating-point number at the given amount of decimals, or to the given power of 10
58
- - [`bitSetHas()`](https://github.com/Sv443-Network/UserUtils/blob/main/docs.md#bitsethas) - check if a bit is set in a [bitset](https://www.geeksforgeeks.org/cpp-bitset-and-its-application/)
59
- - **Misc:**
60
- - [`DataStore`](https://github.com/Sv443-Network/UserUtils/blob/main/docs.md#datastore) - class that manages a hybrid sync & async persistent JSON database, including data migration
61
- - [`DataStoreSerializer`](https://github.com/Sv443-Network/UserUtils/blob/main/docs.md#datastoreserializer) - class for importing & exporting data of multiple DataStore instances, including compression, checksumming and running migrations
62
- - [`Dialog`](https://github.com/Sv443-Network/UserUtils/blob/main/docs.md#dialog) - class for creating custom modal dialogs with a promise-based API and a generic, default style
63
- - [`NanoEmitter`](https://github.com/Sv443-Network/UserUtils/blob/main/docs.md#nanoemitter) - tiny event emitter class with a focus on performance and simplicity (based on [nanoevents](https://npmjs.com/package/nanoevents))
64
- - [`Debouncer`](https://github.com/Sv443-Network/UserUtils/blob/main/docs.md#debouncer) - class for debouncing function calls with a given timeout
65
- - [`debounce()`](https://github.com/Sv443-Network/UserUtils/blob/main/docs.md#debounce) - function wrapper for the Debouncer class for easier usage
66
- - [`autoPlural()`](https://github.com/Sv443-Network/UserUtils/blob/main/docs.md#autoplural) - automatically pluralize a string
67
- - [`pauseFor()`](https://github.com/Sv443-Network/UserUtils/blob/main/docs.md#pausefor) - pause the execution of a function for a given amount of time
68
- - [`fetchAdvanced()`](https://github.com/Sv443-Network/UserUtils/blob/main/docs.md#fetchadvanced) - wrapper around the fetch API with a timeout option
69
- - [`insertValues()`](https://github.com/Sv443-Network/UserUtils/blob/main/docs.md#insertvalues) - insert values into a string at specified placeholders
70
- - [`compress()`](https://github.com/Sv443-Network/UserUtils/blob/main/docs.md#compress) - compress a string with Gzip or Deflate
71
- - [`decompress()`](https://github.com/Sv443-Network/UserUtils/blob/main/docs.md#decompress) - decompress a previously compressed string
72
- - [`computeHash()`](https://github.com/Sv443-Network/UserUtils/blob/main/docs.md#computehash) - compute the hash / checksum of a string or ArrayBuffer
73
- - [`randomId()`](https://github.com/Sv443-Network/UserUtils/blob/main/docs.md#randomid) - generate a random ID of a given length and radix
74
- - [`consumeGen()`](https://github.com/Sv443-Network/UserUtils/blob/main/docs.md#consumegen) - consumes a ValueGen and returns the value
75
- - [`consumeStringGen()`](https://github.com/Sv443-Network/UserUtils/blob/main/docs.md#consumestringgen) - consumes a StringGen and returns the string
76
- - [`getListLength()`](https://github.com/Sv443-Network/UserUtils/blob/main/docs.md#getlistlength) - get the length of any object with a numeric `length`, `count` or `size` property
77
- - [`purifyObj()`](https://github.com/Sv443-Network/UserUtils/blob/main/docs.md#purifyobj) - removes the prototype chain (all default properties like `toString`, `__proto__`, etc.) from an object
78
- - **Arrays:**
79
- - [`randomItem()`](https://github.com/Sv443-Network/UserUtils/blob/main/docs.md#randomitem) - returns a random item from an array
80
- - [`randomItemIndex()`](https://github.com/Sv443-Network/UserUtils/blob/main/docs.md#randomitemindex) - returns a tuple of a random item and its index from an array
81
- - [`takeRandomItem()`](https://github.com/Sv443-Network/UserUtils/blob/main/docs.md#takerandomitem) - returns a random item from an array and mutates it to remove the item
82
- - [`randomizeArray()`](https://github.com/Sv443-Network/UserUtils/blob/main/docs.md#randomizearray) - returns a copy of the array with its items in a random order
83
- - **Translation:**
84
- - [`tr.for()`](https://github.com/Sv443-Network/UserUtils/blob/main/docs.md#trfor) - translates a key for the specified language
85
- - [`tr.use()`](https://github.com/Sv443-Network/UserUtils/blob/main/docs.md#truse) - creates a translation function for the specified language
86
- - [`tr.hasKey()`](https://github.com/Sv443-Network/UserUtils/blob/main/docs.md#trhaskey) - checks if a key exists in the given language
87
- - [`tr.addTranslations()`](https://github.com/Sv443-Network/UserUtils/blob/main/docs.md#traddtranslations) - add a flat or recursive translation object for a language
88
- - [`tr.getTranslations()`](https://github.com/Sv443-Network/UserUtils/blob/main/docs.md#trgettranslations) - returns the translation object for a language
89
- - [`tr.deleteTranslations()`](https://github.com/Sv443-Network/UserUtils/blob/main/docs.md#trdeletetranslations) - delete the translation object for a language
90
- - [`tr.setFallbackLanguage()`](https://github.com/Sv443-Network/UserUtils/blob/main/docs.md#trsetfallbacklanguage) - set the fallback language used when a key is not found in the given language
91
- - [`tr.getFallbackLanguage()`](https://github.com/Sv443-Network/UserUtils/blob/main/docs.md#trgetfallbacklanguage) - returns the fallback language
92
- - [`tr.addTransform()`](https://github.com/Sv443-Network/UserUtils/blob/main/docs.md#traddtransform) - adds a transform function to the translation system for custom argument insertion and much more
93
- - [`tr.deleteTransform()`](https://github.com/Sv443-Network/UserUtils/blob/main/docs.md#trdeletetransform) - removes a transform function
94
- - [`tr.transforms`](https://github.com/Sv443-Network/UserUtils/blob/main/docs.md#trtransforms) - predefined transform functions for quickly adding custom argument insertion
95
- - [`TrKeys`](https://github.com/Sv443-Network/UserUtils/blob/main/docs.md#trkeys) - generic type that extracts all keys from a flat or recursive translation object into a union
96
- - **Colors:**
97
- - [`hexToRgb()`](https://github.com/Sv443-Network/UserUtils/blob/main/docs.md#hextorgb) - convert a hex color string to an RGB or RGBA value tuple
98
- - [`rgbToHex()`](https://github.com/Sv443-Network/UserUtils/blob/main/docs.md#rgbtohex) - convert RGB or RGBA values to a hex color string
99
- - [`lightenColor()`](https://github.com/Sv443-Network/UserUtils/blob/main/docs.md#lightencolor) - lighten a CSS color string (hex, rgb or rgba) by a given percentage
100
- - [`darkenColor()`](https://github.com/Sv443-Network/UserUtils/blob/main/docs.md#darkencolor) - darken a CSS color string (hex, rgb or rgba) by a given percentage
101
- - **Utility types for TypeScript:**
102
- - [`Stringifiable`](https://github.com/Sv443-Network/UserUtils/blob/main/docs.md#stringifiable) - any value that is a string or can be converted to one (implicitly or explicitly)
103
- - [`NonEmptyArray`](https://github.com/Sv443-Network/UserUtils/blob/main/docs.md#nonemptyarray) - any array that should have at least one item
104
- - [`NonEmptyString`](https://github.com/Sv443-Network/UserUtils/blob/main/docs.md#nonemptystring) - any string that should have at least one character
105
- - [`LooseUnion`](https://github.com/Sv443-Network/UserUtils/blob/main/docs.md#looseunion) - a union that gives autocomplete in the IDE but also allows any other value of the same type
106
- - [`Prettify`](https://github.com/Sv443-Network/UserUtils/blob/main/docs.md#prettify) - expands a complex type into a more readable format while keeping functionality the same
107
- - [`ValueGen`](https://github.com/Sv443-Network/UserUtils/blob/main/docs.md#valuegen) - a "generator" value that allows for super flexible value typing and declaration
108
- - [`StringGen`](https://github.com/Sv443-Network/UserUtils/blob/main/docs.md#stringgen) - a "generator" string that allows for super flexible string typing and declaration, including enhanced support for unions
109
- - [`ListWithLength`](https://github.com/Sv443-Network/UserUtils/blob/main/docs.md#listwithlength) - represents an array or object with a numeric `length`, `count` or `size` property
110
- - **Custom Error classes:**
111
- - [`UUError`](https://github.com/Sv443-Network/UserUtils/blob/main/docs.md#uuerror) - base class for all custom UserUtils errors - has a custom `date` prop set to the time of creation
112
- - [`ChecksumMismatchError`](https://github.com/Sv443-Network/UserUtils/blob/main/docs.md#checksummismatcherror) - thrown when a string of data doesn't match its checksum
113
- - [`MigrationError`](https://github.com/Sv443-Network/UserUtils/blob/main/docs.md#migrationerror) - thrown when a data migration fails
114
- - [`PlatformError`](https://github.com/Sv443-Network/UserUtils/blob/main/docs.md#platformerror) - thrown when a function is called in an unsupported environment
115
-
116
- <br><br>
117
-
118
- ## Installation:
119
- Shameless plug: I made a [template for userscripts in TypeScript](https://github.com/Sv443/Userscript.ts) that you can use to get started quickly. It also includes this library by default.
120
-
121
- - If you are using a bundler (like webpack, rollup, vite, etc.), you can install this package in one of the following ways:
122
- ```
123
- npm i @sv443-network/userutils
124
- pnpm i @sv443-network/userutils
125
- yarn add @sv443-network/userutils
126
- npx jsr install @sv443-network/userutils
127
- deno add jsr:@sv443-network/userutils
128
- ```
129
- Then import it in your script as usual:
130
-
131
- ```ts
132
- // on Node:
133
- import { addGlobalStyle } from "@sv443-network/userutils";
134
-
135
- // on Deno:
136
- import { addGlobalStyle } from "jsr:@sv443-network/userutils";
137
-
138
- // you can also import the entire library as an object (not recommended because of worse treeshaking support):
139
- import * as UserUtils from "@sv443-network/userutils";
140
- ```
141
-
142
-
143
- <br>
144
-
145
- - If you are not using a bundler, want to reduce the size of your userscript, or declared the package as external in your bundler, you can include the latest release by adding one of these directives to the userscript header, depending on your preferred CDN:
146
- Versioned (recommended):
147
-
148
- ```
149
- // @require https://cdn.jsdelivr.net/npm/@sv443-network/userutils@INSERT_VERSION/dist/index.global.js
150
- // @require https://unpkg.com/@sv443-network/userutils@INSERT_VERSION/dist/index.global.js
151
- ```
152
- Non-versioned (not recommended because auto-updating):
153
-
154
- ```
155
- // @require https://update.greasyfork.org/scripts/472956/UserUtils.js
156
- // @require https://openuserjs.org/src/libs/Sv443/UserUtils.js
157
- ```
158
-
159
- - If you are using this library in a generic DOM environment without access to the GreaseMonkey API, either download the latest release from the [releases page](https://github.com/Sv443-Network/UserUtils/releases) to include in your project or add one of the following tags to the &lt;head&gt;:
160
- ```html
161
- <script src="https://cdn.jsdelivr.net/npm/@sv443-network/userutils@INSERT_VERSION/dist/index.global.js"></script>
162
- <script src="https://unpkg.com/@sv443-network/userutils@INSERT_VERSION/dist/index.global.js"></script>
163
- ```
164
-
165
- > **Note:**
166
- > In order for your userscript not to break on a major library update, use one the versioned URLs above after replacing `INSERT_VERSION` with the desired version (e.g. `8.3.2`) or the versioned URL that's shown [at the top of the GreasyFork page.](https://greasyfork.org/scripts/472956-userutils)
167
-
168
- <br>
169
-
170
- - Then, access the functions on the global variable `UserUtils`:
171
- ```ts
172
- UserUtils.addGlobalStyle("body { background-color: red; }");
173
-
174
- // or using object destructuring:
175
-
176
- const { clamp } = UserUtils;
177
- console.log(clamp(1, 5, 10)); // 5
178
- ```
179
-
180
- <br>
181
-
182
- - If you're using TypeScript and it complains about the missing global variable `UserUtils`, install the library using the package manager of your choice and add the following inside any `.ts` file that is included in the final build:
183
- ```ts
184
- declare const UserUtils: typeof import("@sv443-network/userutils");
185
-
186
- declare global {
187
- interface Window {
188
- UserUtils: typeof UserUtils;
189
- }
190
- }
191
- ```
192
-
193
- <br>
194
-
195
- - If you're using a linter like ESLint, it might complain about the global variable `UserUtils` not being defined. To fix this, add the following to your ESLint configuration file:
196
- ```json
197
- "globals": {
198
- "UserUtils": "readonly"
199
- }
200
- ```
201
-
202
- <br><br>
203
-
204
- <!-- #region License -->
205
- ## License:
206
- This library is licensed under the MIT License.
207
- See the [license file](./LICENSE.txt) for details.
208
-
209
- <br><br>
210
-
211
- ---
212
-
213
- Made with ❤️ by [Sv443](https://github.com/Sv443)
214
- If you like this library, please consider [supporting the development](https://github.com/sponsors/Sv443)