instrumentality 0.0.3 → 0.0.4

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/README.md CHANGED
@@ -1,5 +1,5 @@
1
- ![white title](./assets/title-white.gif#gh-dark-mode-only)
2
- ![black title](./assets/title-black.gif#gh-light-mode-only)
1
+ <!-- ![black title](./assets/titleDark.webp#gh-light-mode-only) -->
2
+ ![white title](./assets/titleLight.webp#gh-dark-mode-only)
3
3
 
4
4
 
5
5
  ## The INSTRUMENTALITY project (concept)
package/dist/base.d.ts CHANGED
@@ -1,6 +1,4 @@
1
- /**
2
- * Subclass of {@link Error} that represents an error thrown from this library, providing a specific name for easier identification.
3
- */
1
+ /** Subclass of {@link Error} that represents an error thrown from this library, providing a specific name for easier identification. */
4
2
  export declare class InsErr extends Error {
5
3
  name: string;
6
4
  }
@@ -9,29 +7,30 @@ export declare class InsErr extends Error {
9
7
  *
10
8
  * @param fn_ - The function to be retried.
11
9
  * @param maxAttempts_ - The maximum number of attempts to execute the function.
12
- * @param _cbErr - An optional callback function to be executed after each failed attempt.
10
+ * @param cbErr_ - An optional callback function to be executed after each failed attempt.
13
11
  * @param abs_ - An optional AbortSignal to abort the retry process.
14
- * @returns The result of the function if it succeeds within the allowed attempts.
15
- * @throws If the maximum number of attempts is exceeded or if the operation is aborted.
12
+ * @returns The result of {@link fn_} if it succeeds within the allowed attempts.
13
+ * @throws {unknown} If {@link fn_} fails after the maximum attempts, the last error thrown by {@link fn_} is re-thrown.
14
+ * @throws {InsErr} If the maximum attempts is less than 1 or if the operation is aborted.
16
15
  */
17
- export declare function retry<T>(fn_: () => T, maxAttempts_: number, _cbErr?: () => unknown, abs_?: AbortSignal): Promise<T>;
16
+ export declare function retry<T>(fn_: () => T, maxAttempts_: number, cbErr_?: () => unknown, abs_?: AbortSignal): Promise<T>;
18
17
  /**
19
- * Asynchronously sleeps for a specified duration, with optional abort signal support.
18
+ * Asynchronously sleep.
20
19
  *
21
20
  * @param ms_ - The number of milliseconds to sleep.
22
21
  * @param abs_ - An optional AbortSignal to abort the sleep.
23
- * @returns A Promise that resolves after the specified duration or rejects if aborted.
22
+ * @throws {InsErr} If the sleep is aborted before or during the wait.
24
23
  */
25
24
  export declare function sleep(ms_: number, abs_?: AbortSignal): Promise<void>;
26
25
  /**
27
- * Helper type to build a tuple of a specified length.
26
+ * Build a tuple of a specified length.
28
27
  *
29
28
  * @template N - The desired length of the tuple.
30
29
  * @template T - The tuple being built (used for recursion).
31
30
  */
32
31
  type BuildTuple<N extends number, T extends number[] = []> = T['length'] extends N ? T : BuildTuple<N, [...T, T['length']]>;
33
32
  /**
34
- * Helper type to add two number types together.
33
+ * Add two number types together.
35
34
  *
36
35
  * @template A - The first number type.
37
36
  * @template B - The second number type.
@@ -41,38 +40,35 @@ export type Add<A extends number, B extends number> = [
41
40
  ...BuildTuple<B>
42
41
  ]['length'];
43
42
  /**
44
- * Helper type to enumerate numbers from 0 to N-1.
43
+ * Enumerate numbers from 0 to N-1 as a union type.
45
44
  *
46
45
  * @template N - The upper limit (exclusive) for the enumeration.
47
46
  * @template A - The accumulator array used for recursion.
48
47
  */
49
48
  export type Enumerate<N extends number, A extends number[] = []> = A['length'] extends N ? A[number] : Enumerate<N, [...A, A['length']]>;
50
49
  /**
51
- * A benchmarking class that provides various time units for measuring elapsed time.
52
- *
53
- * The class starts a timer upon instantiation and provides properties to access the elapsed time in different units (milliseconds, seconds, minutes, etc.).
54
- * The `round` method can be called to record the current elapsed time and restart the timer.
50
+ * Wrapper around {@link performance.now}
55
51
  *
56
52
  * @property {@link rounds} - An array that stores the recorded elapsed times from each round.
57
53
  * @property {@link timer} - The initial timestamp when the benchmark was created or last reset.
58
54
  * @method {@link round} - Records the current elapsed time and restarts the timer.
59
55
  * @method {@link reset} - Resets the benchmark timer to the current time and clears recorded rounds.
60
- * @accessor {@link y} - Elapsed time in years.
61
- * @accessor {@link mn} - Elapsed time in months.
62
- * @accessor {@link w} - Elapsed time in weeks.
63
- * @accessor {@link d} - Elapsed time in days.
64
- * @accessor {@link h} - Elapsed time in hours.
65
- * @accessor {@link m} - Elapsed time in minutes.
66
- * @accessor {@link s} - Elapsed time in seconds.
67
- * @accessor {@link ms} - Elapsed time in milliseconds.
68
- * @accessor {@link μs} - Elapsed time in microseconds.
69
- * @accessor {@link ns} - Elapsed time in nanoseconds.
70
- * @accessor {@link ps} - Elapsed time in picoseconds.
56
+ * @accessor {@link y} (years)
57
+ * @accessor {@link mn} (months)
58
+ * @accessor {@link w} (weeks)
59
+ * @accessor {@link d} (days)
60
+ * @accessor {@link h} (hours)
61
+ * @accessor {@link m} (minutes)
62
+ * @accessor {@link s} (seconds)
63
+ * @accessor {@link ms} (milliseconds)
64
+ * @accessor {@link μs} (microseconds)
65
+ * @accessor {@link ns} (nanoseconds)
66
+ * @accessor {@link ps} (picoseconds)
71
67
  */
72
68
  export declare class Benchmark {
73
- /** An array that stores the recorded elapsed times from each round. */
69
+ /** An array that stores the recorded elapsed times from each round (relative to the previous). */
74
70
  rounds: number[];
75
- /** Initializes the benchmark timer to the current time using `performance.now()`. */
71
+ /** The initial timestamp when the benchmark was created or last reset. */
76
72
  timer: number;
77
73
  /** Records the current elapsed time and restarts the timer. */
78
74
  round(): void;
@@ -102,9 +98,7 @@ export declare class Benchmark {
102
98
  get ps(): number;
103
99
  }
104
100
  export { Benchmark as Bench, Benchmark as Timer, Benchmark as Stopwatch };
105
- /**
106
- * Helper type that represents a view of a Uint8Array, exposing only view methods and properties, along with a readonly index signature for accessing elements.
107
- */
101
+ /** Compiler sugar to hide mutating methods/properties for read-only operations (no runtime effect). */
108
102
  export type Uint8ArrayView = Pick<Uint8Array, "at" | "includes" | "indexOf" | "lastIndexOf" | "find" | "findIndex" | "findLast" | "findLastIndex" | "every" | "some" | "forEach" | "entries" | "keys" | "values" | typeof Symbol.iterator | "reduce" | "reduceRight" | "join" | "toLocaleString" | "toString" | "map" | "filter" | "slice" | "toReversed" | "toSorted" | "with" | "length" | "byteLength" | "byteOffset"> & {
109
103
  readonly [n: number]: number;
110
104
  };
@@ -115,32 +109,21 @@ export declare const BASE122_ILLEGAL_INDEX: Readonly<Record<number, number>>;
115
109
  /** Shortened payload marker used when escaping an illegal 7-bit value and no subsequent 7-bit chunk is available (the current chunk is reused as payload). */
116
110
  export declare const BASE122_SHORT: 7;
117
111
  /**
118
- * Encodes indexed data into a base-122 representation, going as low as 14% overhead for regular data, making base-64 look pathetic in comparison with its 33% overhead.
119
- * The encoding process packs 7 bits of data into each character, and uses a two-byte sequence for reserved characters to ensure that the output string remains valid.
112
+ * Encodes indexed data into a base-122 representation.
120
113
  *
121
- * @remarks The high density of base-122 comes with the trade-off of not being able to use the output string in certain contexts, such as URLs or file names.
122
114
  * @param data_ - An array-like object containing the data to be encoded.
123
115
  * @returns A string representing the base-122 encoded data.
124
- * @throws If somehow malformed UTF-8 data is generated, the TextDecoder will throw an error (shouldn't happen if the input is valid).
125
- * @see {@link decode122} for decoding the base-122 string back into its original byte representation.
126
- * @see {@link BASE122_ILLEGAL} for the list of reserved characters that are escaped during encoding.
127
- * @example
128
- * // (pseudo-code)
129
- * // build script
130
- * appendFile(".html", `<script type="text/plain">${encode122(compress(readFile(".jpg")))}</script>`)
131
- *
132
- * // HTML
133
- * <script type="text/plain">!!pƋƸ€€²VӦnKZ6w )jpA</script> // embedd data into HTML without it being interpreted as HTML or JS
116
+ * @throws If somehow malformed UTF-8 data is generated, the {@link TextDecoder} will throw an error (shouldn't happen if the input is valid).
117
+ * @remarks The high density might not be suitable for all use cases, especially if the medium used to transmit the data has limitations on character sets or encoding.
118
+ * @see {@link TextDecoder} how the output string is generated from the byte array (this step is necessary for accurate translation to a string).
134
119
  */
135
120
  export declare function encode122(data_: ArrayLike<number>): string;
136
121
  /**
137
122
  * Decodes a base-122 encoded string back into its original byte representation.
138
- * The decoding process reverses the encoding, extracting 7 bits of data from each character and handling two-byte sequences for illegal characters.
139
123
  *
140
124
  * @param base122_ - The base-122 encoded string to decode.
141
125
  * @returns A Uint8Array containing the original byte data.
142
126
  * @throws If an invalid base-122 illegal index is encountered during decoding (shouldn't happen if the input was generated by {@link encode122}).
143
- * @see {@link encode122} for encoding data into base-122.
144
127
  */
145
128
  export declare function decode122(base122_: string): Uint8Array<ArrayBuffer>;
146
129
  //# sourceMappingURL=base.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"base.d.ts","sourceRoot":"","sources":["../src/base.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,qBAAa,MAAO,SAAQ,KAAK;IAAY,IAAI,SAA0B;CAAE;AAK7E;;;;;;;;;GASG;AACH,wBAAsB,KAAK,CAAC,CAAC,EAAE,GAAG,EAAE,MAAM,CAAC,EAAE,YAAY,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,MAAM,OAAO,EAAE,IAAI,CAAC,EAAE,WAAW,GAAG,OAAO,CAAC,CAAC,CAAC,CAazH;AAID;;;;;;GAMG;AACH,wBAAsB,KAAK,CAAC,GAAG,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,WAAW,GAAG,OAAO,CAAC,IAAI,CAAC,CAgB1E;AAID;;;;;GAKG;AACH,KAAK,UAAU,CAAC,CAAC,SAAS,MAAM,EAAE,CAAC,SAAS,MAAM,EAAE,GAAG,EAAE,IACvD,CAAC,CAAC,QAAQ,CAAC,SAAS,CAAC,GAAG,CAAC,GAAG,UAAU,CAAC,CAAC,EAAE,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAA;AAGhE;;;;;GAKG;AACH,MAAM,MAAM,GAAG,CAAC,CAAC,SAAS,MAAM,EAAE,CAAC,SAAS,MAAM,IAChD;IAAC,GAAG,UAAU,CAAC,CAAC,CAAC;IAAE,GAAG,UAAU,CAAC,CAAC,CAAC;CAAC,CAAC,QAAQ,CAAC,CAAA;AAGhD;;;;;GAKG;AACH,MAAM,MAAM,SAAS,CAAC,CAAC,SAAS,MAAM,EAAE,CAAC,SAAS,MAAM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this library, providing a specific name for easier identification.
3
- */
1
+ /** Subclass of {@link Error} that represents an error thrown from this library, providing a specific name for easier identification. */
4
2
  export class InsErr extends Error {
5
3
  name = "Instrumentality-Error";
6
4
  }
@@ -9,32 +7,33 @@ export class InsErr extends Error {
9
7
  *
10
8
  * @param fn_ - The function to be retried.
11
9
  * @param maxAttempts_ - The maximum number of attempts to execute the function.
12
- * @param _cbErr - An optional callback function to be executed after each failed attempt.
10
+ * @param cbErr_ - An optional callback function to be executed after each failed attempt.
13
11
  * @param abs_ - An optional AbortSignal to abort the retry process.
14
- * @returns The result of the function if it succeeds within the allowed attempts.
15
- * @throws If the maximum number of attempts is exceeded or if the operation is aborted.
12
+ * @returns The result of {@link fn_} if it succeeds within the allowed attempts.
13
+ * @throws {unknown} If {@link fn_} fails after the maximum attempts, the last error thrown by {@link fn_} is re-thrown.
14
+ * @throws {InsErr} If the maximum attempts is less than 1 or if the operation is aborted.
16
15
  */
17
- export async function retry(fn_, maxAttempts_, _cbErr, abs_) {
16
+ export async function retry(fn_, maxAttempts_, cbErr_, abs_) {
18
17
  while (--maxAttempts_ >= 0 && !(abs_?.aborted ?? false))
19
18
  try {
20
19
  return await fn_();
21
20
  }
22
21
  catch (err) {
23
- if (maxAttempts_ === 0)
22
+ if (maxAttempts_ <= 0)
24
23
  throw err;
25
- await _cbErr?.();
24
+ await cbErr_?.();
26
25
  }
27
26
  if (maxAttempts_ < 0)
28
- throw new InsErr("Max attempts exceeded");
27
+ throw new InsErr("Max attempts must be at least 1");
29
28
  else
30
29
  throw new InsErr("Operation aborted");
31
30
  }
32
31
  /**
33
- * Asynchronously sleeps for a specified duration, with optional abort signal support.
32
+ * Asynchronously sleep.
34
33
  *
35
34
  * @param ms_ - The number of milliseconds to sleep.
36
35
  * @param abs_ - An optional AbortSignal to abort the sleep.
37
- * @returns A Promise that resolves after the specified duration or rejects if aborted.
36
+ * @throws {InsErr} If the sleep is aborted before or during the wait.
38
37
  */
39
38
  export async function sleep(ms_, abs_) {
40
39
  if (abs_?.aborted)
@@ -53,31 +52,28 @@ export async function sleep(ms_, abs_) {
53
52
  });
54
53
  }
55
54
  /**
56
- * A benchmarking class that provides various time units for measuring elapsed time.
57
- *
58
- * The class starts a timer upon instantiation and provides properties to access the elapsed time in different units (milliseconds, seconds, minutes, etc.).
59
- * The `round` method can be called to record the current elapsed time and restart the timer.
55
+ * Wrapper around {@link performance.now}
60
56
  *
61
57
  * @property {@link rounds} - An array that stores the recorded elapsed times from each round.
62
58
  * @property {@link timer} - The initial timestamp when the benchmark was created or last reset.
63
59
  * @method {@link round} - Records the current elapsed time and restarts the timer.
64
60
  * @method {@link reset} - Resets the benchmark timer to the current time and clears recorded rounds.
65
- * @accessor {@link y} - Elapsed time in years.
66
- * @accessor {@link mn} - Elapsed time in months.
67
- * @accessor {@link w} - Elapsed time in weeks.
68
- * @accessor {@link d} - Elapsed time in days.
69
- * @accessor {@link h} - Elapsed time in hours.
70
- * @accessor {@link m} - Elapsed time in minutes.
71
- * @accessor {@link s} - Elapsed time in seconds.
72
- * @accessor {@link ms} - Elapsed time in milliseconds.
73
- * @accessor {@link μs} - Elapsed time in microseconds.
74
- * @accessor {@link ns} - Elapsed time in nanoseconds.
75
- * @accessor {@link ps} - Elapsed time in picoseconds.
61
+ * @accessor {@link y} (years)
62
+ * @accessor {@link mn} (months)
63
+ * @accessor {@link w} (weeks)
64
+ * @accessor {@link d} (days)
65
+ * @accessor {@link h} (hours)
66
+ * @accessor {@link m} (minutes)
67
+ * @accessor {@link s} (seconds)
68
+ * @accessor {@link ms} (milliseconds)
69
+ * @accessor {@link μs} (microseconds)
70
+ * @accessor {@link ns} (nanoseconds)
71
+ * @accessor {@link ps} (picoseconds)
76
72
  */
77
73
  export class Benchmark {
78
- /** An array that stores the recorded elapsed times from each round. */
74
+ /** An array that stores the recorded elapsed times from each round (relative to the previous). */
79
75
  rounds = [];
80
- /** Initializes the benchmark timer to the current time using `performance.now()`. */
76
+ /** The initial timestamp when the benchmark was created or last reset. */
81
77
  timer = performance.now();
82
78
  /** Records the current elapsed time and restarts the timer. */
83
79
  round() { this.rounds.push(this.ms); this.timer = performance.now(); }
@@ -121,22 +117,13 @@ export const BASE122_ILLEGAL_INDEX = {
121
117
  /** Shortened payload marker used when escaping an illegal 7-bit value and no subsequent 7-bit chunk is available (the current chunk is reused as payload). */
122
118
  export const BASE122_SHORT = 0b111;
123
119
  /**
124
- * Encodes indexed data into a base-122 representation, going as low as 14% overhead for regular data, making base-64 look pathetic in comparison with its 33% overhead.
125
- * The encoding process packs 7 bits of data into each character, and uses a two-byte sequence for reserved characters to ensure that the output string remains valid.
120
+ * Encodes indexed data into a base-122 representation.
126
121
  *
127
- * @remarks The high density of base-122 comes with the trade-off of not being able to use the output string in certain contexts, such as URLs or file names.
128
122
  * @param data_ - An array-like object containing the data to be encoded.
129
123
  * @returns A string representing the base-122 encoded data.
130
- * @throws If somehow malformed UTF-8 data is generated, the TextDecoder will throw an error (shouldn't happen if the input is valid).
131
- * @see {@link decode122} for decoding the base-122 string back into its original byte representation.
132
- * @see {@link BASE122_ILLEGAL} for the list of reserved characters that are escaped during encoding.
133
- * @example
134
- * // (pseudo-code)
135
- * // build script
136
- * appendFile(".html", `<script type="text/plain">${encode122(compress(readFile(".jpg")))}</script>`)
137
- *
138
- * // HTML
139
- * <script type="text/plain">!!pƋƸ€€²VӦnKZ6w )jpA</script> // embedd data into HTML without it being interpreted as HTML or JS
124
+ * @throws If somehow malformed UTF-8 data is generated, the {@link TextDecoder} will throw an error (shouldn't happen if the input is valid).
125
+ * @remarks The high density might not be suitable for all use cases, especially if the medium used to transmit the data has limitations on character sets or encoding.
126
+ * @see {@link TextDecoder} how the output string is generated from the byte array (this step is necessary for accurate translation to a string).
140
127
  */
141
128
  export function encode122(data_) {
142
129
  const out = [];
@@ -171,12 +158,10 @@ export function encode122(data_) {
171
158
  }
172
159
  /**
173
160
  * Decodes a base-122 encoded string back into its original byte representation.
174
- * The decoding process reverses the encoding, extracting 7 bits of data from each character and handling two-byte sequences for illegal characters.
175
161
  *
176
162
  * @param base122_ - The base-122 encoded string to decode.
177
163
  * @returns A Uint8Array containing the original byte data.
178
164
  * @throws If an invalid base-122 illegal index is encountered during decoding (shouldn't happen if the input was generated by {@link encode122}).
179
- * @see {@link encode122} for encoding data into base-122.
180
165
  */
181
166
  export function decode122(base122_) {
182
167
  const out = [];
package/dist/dom.d.ts CHANGED
@@ -1,49 +1,40 @@
1
1
  import * as bs from "./base.ts";
2
- /**
3
- * Subclass of {@link bs.InsErr} that represents an error thrown from this specific module of the library
4
- */
2
+ /** Subclass of {@link bs.InsErr} that represents an error thrown from this specific module of the library */
5
3
  export declare class DomErr extends bs.InsErr {
6
4
  name: string;
7
5
  }
8
6
  /**
9
- * Returns a Promise that resolves when the DOM is fully loaded and ready.
10
- *
11
- * @returns A Promise that resolves when the DOM is ready.
7
+ * Resolves on `DOMContentLoaded` or immediately if the document is already ready.
12
8
  */
13
9
  export declare function onceReady(): Promise<void>;
14
10
  /**
15
- * Retrieves an HTML element by its ID and ensures it matches the specified type.
11
+ * Typed accessor for {@link document.getElementById}
16
12
  *
17
- * @param id_ - The ID of the HTML element to retrieve.
18
- * @param elementType_ - An optional constructor function for the expected element type.
19
- * @returns The HTML element with the specified ID and type.
20
- * @throws Will throw an error if the element is not found or does not match the expected type.
13
+ * @param id_ - The ID of the element to retrieve.
14
+ * @param type_ - Expected type, defaults to {@link HTMLElement}.
15
+ * @returns The corresponding element if found and of the expected type, otherwise `null`.
21
16
  */
22
- export declare function byId<T extends HTMLElement>(id_: string, elementType_?: new () => T): T;
17
+ export declare function byId<T extends HTMLElement>(id_: string, type_: new () => T): T | null;
23
18
  /**
24
- * Retrieves all HTML elements with the specified class name and ensures they match the specified type.
19
+ * Typed accessor for {@link document.getElementsByClassName}
25
20
  *
26
21
  * @param className_ - The class name of the elements to retrieve.
27
- * @param elementType_ - An optional constructor function for the expected element type.
28
- * @returns An array of {@link HTMLElement} with the specified class name and type.
29
- * @throws Will throw an error if any element does not match the expected type.
22
+ * @param type_ - An optional constructor function for the expected element type.
23
+ * @returns All elements with the specified class name and type.
30
24
  */
31
- export declare function byClass<T extends HTMLElement>(className_: string, elementType_?: new () => T): T[];
25
+ export declare function byClass<T extends HTMLElement>(className_: string, type_: new () => T): T[];
32
26
  /**
33
- * Retrieves all HTML elements with the specified tag name.
27
+ * Typed accessor for {@link document.getElementsByTagName}
34
28
  *
35
- * @param tagName_ - The tag name of the HTML elements to retrieve.
29
+ * @param tag_ - The HTML tag name of the elements to retrieve.
30
+ * @returns An array of {@link HTMLElement}s with the specified tag name.
36
31
  */
37
- export declare function byTag<K extends keyof HTMLElementTagNameMap>(tagName_: K): HTMLElementTagNameMap[K][];
38
- /**
39
- * Regular expression to match cookie name-value pairs in a cookie string.
40
- */
41
- export declare const COOKIE_PAIR_REGEX: RegExp;
32
+ export declare function byTag<K extends keyof HTMLElementTagNameMap>(tag_: K): HTMLElementTagNameMap[K][];
42
33
  /**
43
34
  * Sets a cookie with the specified name, data, and optional path.
44
35
  *
45
36
  * @param name_ - The name of the cookie.
46
- * @param data_ - The data to be stored in the cookie, including its value and optional attributes.
37
+ * @param data_ - The data to be stored in the cookie.
47
38
  * @param path_ - An optional path for the cookie; defaults to {@link DEFAULT_PATH}.
48
39
  */
49
40
  export declare function setCookie(name_: string, data_: {
@@ -54,14 +45,14 @@ export declare function setCookie(name_: string, data_: {
54
45
  sameSite?: 'Strict' | 'Lax' | 'None';
55
46
  }, path_?: string): void;
56
47
  /**
57
- * Expires a cookie by setting its value to an empty string and its expiration date to the Unix epoch.
48
+ * Expires a cookie immediately.
58
49
  *
59
- * @param name_ - The name of the cookie to expire.
50
+ * @param name_ - The name of the cookie.
60
51
  * @param path_ - An optional path for the cookie; defaults to {@link DEFAULT_PATH}.
61
52
  */
62
53
  export declare function expireCookie(name_: string, path_?: string): void;
63
54
  /**
64
- * Lists all cookies as a record of name-value pairs.
55
+ * Lists all cookies as a record of key-value pairs.
65
56
  *
66
57
  * @returns A record where each key is a cookie name and each value is the corresponding cookie value.
67
58
  */
package/dist/dom.d.ts.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"dom.d.ts","sourceRoot":"","sources":["../src/dom.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,WAAW,CAAA;AAC/B;;GAEG;AACH,qBAAa,MAAO,SAAQ,EAAE,CAAC,MAAM;IAAY,IAAI,SAA8B;CAAE;AAIrF;;;;GAIG;AACH,wBAAsB,SAAS,IAAI,OAAO,CAAC,IAAI,CAAC,CAI/C;AAID;;;;;;;GAOG;AACH,wBAAgB,IAAI,CAAC,CAAC,SAAS,WAAW,EAAE,GAAG,EAAE,MAAM,EAAE,YAAY,CAAC,EAAE,UAAU,CAAC,GAAG,CAAC,CAMtF;AAGD;;;;;;;GAOG;AACH,wBAAgB,OAAO,CAAC,CAAC,SAAS,WAAW,EAAE,UAAU,EAAE,MAAM,EAAE,YAAY,CAAC,EAAE,UAAU,CAAC,GAAG,CAAC,EAAE,CAOlG;AAGD;;;;GAIG;AACH,wBAAgB,KAAK,CAAC,CAAC,SAAS,MAAM,qBAAqB,EAAE,QAAQ,EAAE,CAAC,GAAG,qBAAqB,CAAC,CAAC,CAAC,EAAE,CAEpG;AAID;;GAEG;AACH,eAAO,MAAM,iBAAiB,QAA8B,CAAA;AAI5D;;;;;;GAMG;AACH,wBAAgB,SAAS,CAAC,KAAK,EAAE,MAAM,EAAE,KAAK,EAAE;IAC9C,KAAK,EAAE,OAAO,CAAA;IACd,OAAO,CAAC,EAAE,IAAI,GAAG,MAAM,CAAA;IACvB,MAAM,CAAC,EAAE,MAAM,CAAA;IACf,MAAM,CAAC,EAAE,OAAO,CAAA;IAChB,QAAQ,CAAC,EAAE,QAAQ,GAAG,KAAK,GAAG,MAAM,CAAA;CACrC,EAAE,KAAK,SAAM,GAAG,IAAI,CASpB;AAED;;;;;GAKG;AACH,wBAAgB,YAAY,CAAC,KAAK,EAAE,MAAM,EAAE,KAAK,SAAM,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;GAIG;AACH,wBAAgB,OAAO,IAAI,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAMjD"}
package/dist/dom.js CHANGED
@@ -1,68 +1,53 @@
1
1
  import * as bs from "./base.js";
2
- /**
3
- * Subclass of {@link bs.InsErr} that represents an error thrown from this specific module of the library
4
- */
2
+ /** Subclass of {@link bs.InsErr} that represents an error thrown from this specific module of the library */
5
3
  export class DomErr extends bs.InsErr {
6
4
  name = "Instrumentality-DOM-Error";
7
5
  }
8
6
  /**
9
- * Returns a Promise that resolves when the DOM is fully loaded and ready.
10
- *
11
- * @returns A Promise that resolves when the DOM is ready.
7
+ * Resolves on `DOMContentLoaded` or immediately if the document is already ready.
12
8
  */
13
9
  export async function onceReady() {
14
10
  if (document.readyState === "complete" || document.readyState === "interactive")
15
- return Promise.resolve();
11
+ return;
16
12
  return new Promise(r => document.addEventListener("DOMContentLoaded", () => r(), { once: true }));
17
13
  }
18
14
  /**
19
- * Retrieves an HTML element by its ID and ensures it matches the specified type.
15
+ * Typed accessor for {@link document.getElementById}
20
16
  *
21
- * @param id_ - The ID of the HTML element to retrieve.
22
- * @param elementType_ - An optional constructor function for the expected element type.
23
- * @returns The HTML element with the specified ID and type.
24
- * @throws Will throw an error if the element is not found or does not match the expected type.
17
+ * @param id_ - The ID of the element to retrieve.
18
+ * @param type_ - Expected type, defaults to {@link HTMLElement}.
19
+ * @returns The corresponding element if found and of the expected type, otherwise `null`.
25
20
  */
26
- export function byId(id_, elementType_) {
21
+ export function byId(id_, type_) {
27
22
  const element = document.getElementById(id_);
28
- const typeCtor = elementType_ ?? HTMLElement;
29
- if (!(element instanceof typeCtor))
30
- throw new DomErr(`Type missmatch: Element with id '${id_}' is not of type ${typeCtor.name}`);
31
- return element;
23
+ if (element instanceof type_)
24
+ return element;
25
+ return null;
32
26
  }
33
27
  /**
34
- * Retrieves all HTML elements with the specified class name and ensures they match the specified type.
28
+ * Typed accessor for {@link document.getElementsByClassName}
35
29
  *
36
30
  * @param className_ - The class name of the elements to retrieve.
37
- * @param elementType_ - An optional constructor function for the expected element type.
38
- * @returns An array of {@link HTMLElement} with the specified class name and type.
39
- * @throws Will throw an error if any element does not match the expected type.
31
+ * @param type_ - An optional constructor function for the expected element type.
32
+ * @returns All elements with the specified class name and type.
40
33
  */
41
- export function byClass(className_, elementType_) {
42
- return Array.from(document.getElementsByClassName(className_)).map((element, index) => {
43
- const typeCtor = elementType_ ?? HTMLElement;
44
- if (!(element instanceof typeCtor))
45
- throw new DomErr(`Type missmatch: Element at index ${index} with class '${className_}' is not of type ${typeCtor.name}`);
46
- return element;
47
- });
34
+ export function byClass(className_, type_) {
35
+ return [...document.getElementsByClassName(className_)].filter((el) => el instanceof type_);
48
36
  }
49
37
  /**
50
- * Retrieves all HTML elements with the specified tag name.
38
+ * Typed accessor for {@link document.getElementsByTagName}
51
39
  *
52
- * @param tagName_ - The tag name of the HTML elements to retrieve.
40
+ * @param tag_ - The HTML tag name of the elements to retrieve.
41
+ * @returns An array of {@link HTMLElement}s with the specified tag name.
53
42
  */
54
- export function byTag(tagName_) {
55
- return Array.from(document.getElementsByTagName(tagName_));
43
+ export function byTag(tag_) {
44
+ return [...document.getElementsByTagName(tag_)];
56
45
  }
57
- /**
58
- * Regular expression to match cookie name-value pairs in a cookie string.
59
- */
60
- export const COOKIE_PAIR_REGEX = /(?:^|; )([^=;]+)=([^;]*)/g;
61
46
  /**
62
47
  * Sets a cookie with the specified name, data, and optional path.
63
48
  *
64
49
  * @param name_ - The name of the cookie.
65
- * @param data_ - The data to be stored in the cookie, including its value and optional attributes.
50
+ * @param data_ - The data to be stored in the cookie.
66
51
  * @param path_ - An optional path for the cookie; defaults to {@link DEFAULT_PATH}.
67
52
  */
68
53
  export function setCookie(name_, data_, path_ = '/') {
@@ -81,22 +66,22 @@ export function setCookie(name_, data_, path_ = '/') {
81
66
  document.cookie = cookieString;
82
67
  }
83
68
  /**
84
- * Expires a cookie by setting its value to an empty string and its expiration date to the Unix epoch.
69
+ * Expires a cookie immediately.
85
70
  *
86
- * @param name_ - The name of the cookie to expire.
71
+ * @param name_ - The name of the cookie.
87
72
  * @param path_ - An optional path for the cookie; defaults to {@link DEFAULT_PATH}.
88
73
  */
89
74
  export function expireCookie(name_, path_ = '/') {
90
75
  setCookie(name_, { value: "", expires: new Date(0) }, path_);
91
76
  }
92
77
  /**
93
- * Lists all cookies as a record of name-value pairs.
78
+ * Lists all cookies as a record of key-value pairs.
94
79
  *
95
80
  * @returns A record where each key is a cookie name and each value is the corresponding cookie value.
96
81
  */
97
82
  export function cookies() {
98
83
  const cookies = {};
99
- const matches = document.cookie.matchAll(COOKIE_PAIR_REGEX);
84
+ const matches = document.cookie.matchAll(/(?:^|; )([^=;]+)=([^;]*)/g);
100
85
  for (const match of matches)
101
86
  cookies[decodeURIComponent(match[1] ?? "")] = JSON.parse(decodeURIComponent(match[2] ?? ""));
102
87
  return cookies;