@monterosa/sdk-util 2.0.0-rc.3 → 2.0.0-rc.5

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.
@@ -0,0 +1,513 @@
1
+ /**
2
+ * Shared utilities including emitters, error handling, and storage helpers.
3
+ *
4
+ * @packageDocumentation
5
+ */
6
+
7
+ /**
8
+ * @license
9
+ * @monterosa/sdk-identify-kit
10
+ *
11
+ * Copyright © 2025 Monterosa Productions Limited. All rights reserved.
12
+ *
13
+ * More details on the license can be found at https://www.monterosa.co/sdk/license
14
+ */
15
+ declare type AsyncTask = () => Promise<void>;
16
+
17
+ /**
18
+ * @license
19
+ * @monterosa/sdk-util
20
+ *
21
+ * Copyright © 2025 Monterosa Productions Limited. All rights reserved.
22
+ *
23
+ * More details on the license can be found at https://www.monterosa.co/sdk/license
24
+ */
25
+ /**
26
+ * @internal
27
+ *
28
+ * The backoff strategy to use for retry attempts.
29
+ */
30
+ export declare type BackoffStrategy = 'fixed' | 'incremental' | 'exponential';
31
+
32
+ /**
33
+ * Calculate percentage of each value in the array.
34
+ *
35
+ * It uses Hamilton's method, also known as the method of largest remainder.
36
+ * It is a system used for distributing vote percentages among different
37
+ * options (like candidates or choices) based on their vote counts. It ensures
38
+ * that each option receives at least its lower quota of percentage points, and
39
+ * any remaining percentage points are allocated to those with the largest
40
+ * fractional remainders. This method is used in the US Electoral College.
41
+ *
42
+ * @param values - Array of number values to calculate percentage for
43
+ * @returns Array of percentages, where the sum of the array is 100%
44
+ */
45
+ export declare const calculatePercentage: (values: number[]) => number[];
46
+
47
+ /**
48
+ * Checks locastorage availability.
49
+ * Based on MDN article: https://developer.mozilla.org/en-US/docs/Web/API/Web_Storage_API/Using_the_Web_Storage_API
50
+ * and Paul Irish gists: https://gist.github.com/paulirish/5558557
51
+ *
52
+ * @internal
53
+ *
54
+ * @returns boolean
55
+ */
56
+ export declare function checkAvailability(): boolean;
57
+
58
+ /**
59
+ * @license
60
+ * checksum.ts
61
+ * util
62
+ *
63
+ * Copyright © 2025 Monterosa. All rights reserved.
64
+ *
65
+ * More details on the license can be found at https://www.monterosa.co/sdk/license
66
+ */
67
+ /**
68
+ * @internal
69
+ *
70
+ * FNV-1a 32-bit hash function
71
+ * Produces a fast, non-cryptographic checksum for strings
72
+ *
73
+ * @param str - The input string to hash
74
+ *
75
+ * @returns 8-character hexadecimal string representing the hash
76
+ */
77
+ export declare function checksum(str: string): string;
78
+
79
+ /**
80
+ * @internal
81
+ */
82
+ export declare function clear(): void;
83
+
84
+ /**
85
+ * @internal
86
+ */
87
+ export declare function createError<ErrorCode extends string>(code: ErrorCode, messages: ErrorMap<ErrorCode>, ...params: any[]): MonterosaError;
88
+
89
+ /**
90
+ * @internal
91
+ *
92
+ * Default configuration values for retry logic.
93
+ */
94
+ export declare const DEFAULT_RETRY_CONFIG: Required<RetryConfig>;
95
+
96
+ /**
97
+ * @internal
98
+ *
99
+ * Delays the execution of the code for a given number of milliseconds.
100
+ *
101
+ * @param timeout - The timeout in milliseconds.
102
+ *
103
+ * @returns A promise that resolves after the timeout.
104
+ */
105
+ export declare const delay: (timeout: number) => Promise<void>;
106
+
107
+ /**
108
+ * @internal
109
+ *
110
+ * Event emitter. Provides subscribe/unsubscribe pattern used throughout
111
+ * the SDK for observable state changes.
112
+ */
113
+ export declare class Emitter {
114
+ private readonly listeners;
115
+ /**
116
+ * Subscribes to an event.
117
+ *
118
+ * @param event - The event name
119
+ * @param handler - The callback function
120
+ * @returns A function that unsubscribes the handler when called
121
+ */
122
+ on(event: string, handler: Handler): Unsubscribe;
123
+ /**
124
+ * Unsubscribes from an event.
125
+ *
126
+ * @param event - The event name
127
+ * @param handler - The handler to remove. If omitted, all handlers for the event are removed.
128
+ */
129
+ off(event: string, handler?: Handler): void;
130
+ /**
131
+ * Emits an event with optional arguments.
132
+ *
133
+ * @param event - The event name
134
+ * @param args - Arguments to pass to handlers
135
+ */
136
+ emit(event: string, ...args: any[]): void;
137
+ /**
138
+ * Subscribes to an event and automatically unsubscribes after the first call.
139
+ *
140
+ * @param event - The event name
141
+ * @param handler - The callback function
142
+ * @returns A function that unsubscribes the handler when called
143
+ */
144
+ once(event: string, handler: Handler): Unsubscribe;
145
+ }
146
+
147
+ declare type ErrorMap<ErrorCode extends string> = {
148
+ readonly [K in ErrorCode]: (...rest: any[]) => string;
149
+ };
150
+
151
+ /**
152
+ * @license
153
+ * fromentries.ts
154
+ * util
155
+ *
156
+ * Copyright © 2023 Monterosa Productions Limited. All rights reserved.
157
+ *
158
+ * More details on the license can be found at https://www.monterosa.co/sdk/license
159
+ */
160
+ /**
161
+ * @internal
162
+ */
163
+ export declare function fromEntries(entries: [string | number | symbol, any][]): Record<string | number | symbol, any>;
164
+
165
+ /**
166
+ * @license
167
+ * @monterosa/sdk-util
168
+ *
169
+ * Copyright © 2026 Monterosa Productions Limited. All rights reserved.
170
+ *
171
+ * More details on the license can be found at https://www.monterosa.co/sdk/license
172
+ */
173
+ /**
174
+ * Generates a RFC 4122 version 4 UUID.
175
+ *
176
+ * Uses `crypto.randomUUID()` when available, falling back to
177
+ * `crypto.getRandomValues()` for older browsers.
178
+ *
179
+ * @returns A UUID v4 string
180
+ *
181
+ * @internal
182
+ */
183
+ export declare function generateUUID(): string;
184
+
185
+ /**
186
+ * @internal
187
+ */
188
+ export declare function getErrorMessage(err: unknown): string;
189
+
190
+ /**
191
+ * @license
192
+ * @monterosa/sdk-util
193
+ *
194
+ * Copyright © 2022 Monterosa Productions Limited. All rights reserved.
195
+ *
196
+ * More details on the license can be found at https://www.monterosa.co/sdk/license
197
+ */
198
+ /**
199
+ * @preserve
200
+ * Global object polyfill.
201
+ * Based on MDN article: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/globalThis
202
+ *
203
+ * @internal
204
+ *
205
+ * @returns typeof globalThis
206
+ */
207
+ export declare function getGlobal(): typeof globalThis;
208
+
209
+ /**
210
+ * @internal
211
+ */
212
+ export declare function getItem(key: string): string | null;
213
+
214
+ /**
215
+ * @internal
216
+ */
217
+ export declare const getKey: (name: string) => string;
218
+
219
+ /**
220
+ * @license
221
+ * @monterosa/sdk-util
222
+ *
223
+ * Copyright © 2022 Monterosa Productions Limited. All rights reserved.
224
+ *
225
+ * More details on the license can be found at https://www.monterosa.co/sdk/license
226
+ */
227
+ declare type Handler = (...args: any[]) => void;
228
+
229
+ /**
230
+ * Validates whether a string is a valid UUID v4.
231
+ *
232
+ * @param value - The string to validate
233
+ * @returns `true` if the string is a valid UUID v4
234
+ *
235
+ * @internal
236
+ */
237
+ export declare function isUUID(value: string): boolean;
238
+
239
+ /**
240
+ * Creates a function that memoizes the result of `func`.
241
+ *
242
+ * @internal
243
+ *
244
+ * @param func - A function that returns a promise. The results of its work will be memoized.
245
+ * @param resolver - A function that determines the cache key.
246
+ * @param config - A configuration object with the following optional properties:
247
+ * `clearOnResolve` - Deletes memoized result upon promise resolve. Defaults to `false`.
248
+ * `clearOnReject` - Deletes memoized result upon promise reject. Defaults to `true`.
249
+ */
250
+ export declare const memoizePromise: <T>(func: (...args: any[]) => Promise<T>, resolver: (...args: any[]) => any, config?: {
251
+ clearOnResolve?: boolean;
252
+ clearOnReject?: boolean;
253
+ }) => (...args: any[]) => Promise<T>;
254
+
255
+ /**
256
+ * @license
257
+ * @monterosa/sdk-util
258
+ *
259
+ * Copyright © 2022 Monterosa Productions Limited. All rights reserved.
260
+ *
261
+ * More details on the license can be found at https://www.monterosa.co/sdk/license
262
+ */
263
+ /**
264
+ * MonterosaError extends the standard JavaScript `Error` object. It has
265
+ * an error code so that users can identify the error. It also has its
266
+ * own specific `name` "MonterosaError".
267
+ */
268
+ export declare class MonterosaError extends Error {
269
+ /**
270
+ * The name property represents a name for the type of error.
271
+ */
272
+ readonly name = "MonterosaError";
273
+ /**
274
+ * Error code string
275
+ */
276
+ readonly code: string;
277
+ /**
278
+ * @param code - Error code string
279
+ * @param message - A descriptive message for the error
280
+ */
281
+ constructor(code: string, message: string);
282
+ }
283
+
284
+ /**
285
+ * Returns current timestamp that is preserved by `tick()` function
286
+ *
287
+ * @returns Current timestamp in seconds
288
+ */
289
+ export declare function now(): number;
290
+
291
+ /**
292
+ * Subscribes listener to the timestamp increment
293
+ *
294
+ * @param callback - A handler that executes when the timestamp is incremented
295
+ *
296
+ * @returns A function that unsubscribes the listener
297
+ */
298
+ export declare function onTick(callback: (timestamp: number) => void): Unsubscribe;
299
+
300
+ /**
301
+ * @internal
302
+ */
303
+ export declare function removeItem(key: string): void;
304
+
305
+ /**
306
+ * @internal
307
+ *
308
+ * Configuration options for retry logic with backoff strategies.
309
+ */
310
+ export declare interface RetryConfig {
311
+ /**
312
+ * The backoff strategy to use.
313
+ *
314
+ * @default 'exponential'
315
+ */
316
+ backoffStrategy?: BackoffStrategy;
317
+ /**
318
+ * The number of attempts before failing.
319
+ *
320
+ * @default 3
321
+ */
322
+ attempts?: number;
323
+ /**
324
+ * The base delay in milliseconds for retry attempts.
325
+ *
326
+ * @default 500
327
+ */
328
+ baseDelay?: number;
329
+ /**
330
+ * The maximum jitter to add to the delay in milliseconds.
331
+ *
332
+ * @default 500
333
+ */
334
+ jitter?: number;
335
+ /**
336
+ * The maximum delay in milliseconds for retry attempts.
337
+ *
338
+ * @default 10_000
339
+ */
340
+ maxDelay?: number;
341
+ }
342
+
343
+ /**
344
+ * @internal
345
+ */
346
+ export declare function setItem(key: string, value: string): void;
347
+
348
+ /**
349
+ * @internal
350
+ *
351
+ * Sets or updates current timestamp
352
+ *
353
+ * @param timestamp - Current timestamp in seconds
354
+ */
355
+ export declare function setTimestamp(timestamp: number): void;
356
+
357
+ /**
358
+ * @internal
359
+ */
360
+ export declare interface Subscribe {
361
+ (emitter: Emitter, event: string, callback: (...args: any[]) => void): Unsubscribe;
362
+ }
363
+
364
+ /**
365
+ * @internal
366
+ */
367
+ export declare const subscribe: Subscribe;
368
+
369
+ /**
370
+ * @internal
371
+ *
372
+ * TaskQueue ensures that async tasks run sequentially (FIFO).
373
+ *
374
+ * Behavior:
375
+ * - Tasks run one at a time in the order they were enqueued.
376
+ * - If a task fails (throws/rejects), the queue is stopped
377
+ * and all pending tasks are cleared.
378
+ */
379
+ export declare class TaskQueue {
380
+ private current;
381
+ private queue;
382
+ private paused;
383
+ enqueue(fn: AsyncTask): void;
384
+ enqueueFront(fn: AsyncTask): void;
385
+ pause(): void;
386
+ resume(): void;
387
+ private process;
388
+ get length(): number;
389
+ isEmpty(): boolean;
390
+ hasActiveTask(): boolean;
391
+ clear(): void;
392
+ }
393
+
394
+ /**
395
+ * @license
396
+ * @monterosa/sdk-util
397
+ *
398
+ * Copyright © 2022 Monterosa Productions Limited. All rights reserved.
399
+ *
400
+ * More details on the license can be found at https://www.monterosa.co/sdk/license
401
+ */
402
+ /**
403
+ * Creates a throttled function that only invokes `func` at most once per
404
+ * every `wait` milliseconds. The throttled function comes with a `cancel`
405
+ * method to cancel delayed `func` invocations and a `flush` method to
406
+ * immediately invoke them. Provide `options` to indicate whether `func`
407
+ * should be invoked on the leading and/or trailing edge of the `wait`
408
+ * timeout. The `func` is invoked with the last arguments provided to the
409
+ * throttled function. Subsequent calls to the throttled function return the
410
+ * result of the last `func` invocation.
411
+ *
412
+ * **Note:** If `leading` and `trailing` options are `true`, `func` is
413
+ * invoked on the trailing edge of the timeout only if the throttled function
414
+ * is invoked more than once during the `wait` timeout.
415
+ *
416
+ * If `wait` is `0` and `leading` is `false`, `func` invocation is deferred
417
+ * until to the next tick, similar to `setTimeout` with a timeout of `0`.
418
+ *
419
+ * See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/)
420
+ * for details over the differences between `_.throttle` and `_.debounce`.
421
+ *
422
+ * @internal
423
+ *
424
+ * @static
425
+ * @memberOf _
426
+ * @since 0.1.0
427
+ * @category Function
428
+ * @param {Function} func The function to throttle.
429
+ * @param {number} [wait=0] The number of milliseconds to throttle invocations to.
430
+ * @param {Object} [options={}] The options object.
431
+ * @param {boolean} [options.leading=true]
432
+ * Specify invoking on the leading edge of the timeout.
433
+ * @param {boolean} [options.trailing=true]
434
+ * Specify invoking on the trailing edge of the timeout.
435
+ * @returns {Function} Returns the new throttled function.
436
+ * @example
437
+ *
438
+ * // Avoid excessively updating the position while scrolling.
439
+ * jQuery(window).on('scroll', _.throttle(updatePosition, 100));
440
+ *
441
+ * // Invoke `renewToken` when the click event is fired, but not more than once every 5 minutes.
442
+ * var throttled = _.throttle(renewToken, 300000, { 'trailing': false });
443
+ * jQuery(element).on('click', throttled);
444
+ *
445
+ * // Cancel the trailing throttled invocation.
446
+ * jQuery(window).on('popstate', throttled.cancel);
447
+ */
448
+ export declare function throttle(func: any, wait: any, options: any): {
449
+ (): any;
450
+ cancel: () => void;
451
+ flush: () => any;
452
+ };
453
+
454
+ /**
455
+ * @internal
456
+ *
457
+ * Main function that maintains current timestamp
458
+ */
459
+ export declare function tick(): void;
460
+
461
+ /**
462
+ * The unsubscribe function. When it is called, the previously set event
463
+ * listener is removed. It is returned by every observer functions
464
+ *
465
+ * @example
466
+ * ```typescript
467
+ * const unsubscribe: Unsubscribe = onElementPublished((element) => {
468
+ * console.log('Element published', element);
469
+ * });
470
+ *
471
+ * unsubscribe();
472
+ * ```
473
+ */
474
+ export declare interface Unsubscribe {
475
+ (): void;
476
+ }
477
+
478
+ /**
479
+ * @internal
480
+ *
481
+ * Wraps an async function with retry logic and configurable backoff strategies.
482
+ *
483
+ * @template TArgs - The argument types of the wrapped function.
484
+ * @template TResult - The return type of the wrapped function.
485
+ *
486
+ * @param fn - The async function to wrap.
487
+ * @param config - Configuration object for retry behaviour.
488
+ * - backoffStrategy: BackoffStrategy (default: 'exponential')
489
+ * - attempts: number of retry attempts (default: 3)
490
+ * - baseDelay: base delay in ms (default: 500)
491
+ * - jitter: max jitter in ms (default: 500)
492
+ * - maxDelay: max delay in ms (default: 10_000)
493
+ *
494
+ * @returns A new function that retries the given async function up to the
495
+ * specified number of attempts with the configured backoff strategy.
496
+ *
497
+ * @throws The last encountered error if all retry attempts fail.
498
+ *
499
+ * @example
500
+ * const fetchDataWithRetry = withRetryAsync(fetchData, {
501
+ * backoffStrategy: 'exponential',
502
+ * attempts: 3,
503
+ * baseDelay: 500
504
+ * });
505
+ *
506
+ * // Will retry up to 3 times with exponential backoff
507
+ * fetchDataWithRetry("https://api.example.com")
508
+ * .then(data => console.log(data))
509
+ * .catch(err => console.error("Failed after retries:", err));
510
+ */
511
+ export declare function withRetryAsync<TArgs extends any[], TResult>(fn: (...args: TArgs) => Promise<TResult>, config?: RetryConfig): (...args: TArgs) => Promise<TResult>;
512
+
513
+ export { }
@@ -0,0 +1,11 @@
1
+ // This file is read by tools that parse documentation comments conforming to the TSDoc standard.
2
+ // It should be published with your NPM package. It should not be tracked by Git.
3
+ {
4
+ "tsdocVersion": "0.12",
5
+ "toolPackages": [
6
+ {
7
+ "packageName": "@microsoft/api-extractor",
8
+ "packageVersion": "7.23.0"
9
+ }
10
+ ]
11
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@monterosa/sdk-util",
3
- "version": "2.0.0-rc.3",
3
+ "version": "2.0.0-rc.5",
4
4
  "description": "Monterosa JS SDK / Utils",
5
5
  "author": "Monterosa Productions Limited <hello@monterosa.co.uk> (https://www.monterosa.co/)",
6
6
  "main": "./dist/index.cjs",
@@ -50,5 +50,5 @@
50
50
  "publishConfig": {
51
51
  "access": "public"
52
52
  },
53
- "gitHead": "d692ad26af0b5ea7cd7b664168bffa069f9ab911"
53
+ "gitHead": "4f697a9733d36fb689a35b8e1dd6d589a9ae284c"
54
54
  }