@talismn/util 0.5.6 → 0.5.8

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.
Files changed (44) hide show
  1. package/dist/index.d.mts +270 -0
  2. package/dist/index.d.ts +270 -0
  3. package/dist/index.js +490 -0
  4. package/dist/index.js.map +1 -0
  5. package/dist/index.mjs +421 -0
  6. package/dist/index.mjs.map +1 -0
  7. package/package.json +23 -19
  8. package/dist/declarations/src/BigMath.d.ts +0 -10
  9. package/dist/declarations/src/FunctionPropertyNames.d.ts +0 -8
  10. package/dist/declarations/src/Prettify.d.ts +0 -3
  11. package/dist/declarations/src/addTrailingSlash.d.ts +0 -1
  12. package/dist/declarations/src/classNames.d.ts +0 -2
  13. package/dist/declarations/src/deferred.d.ts +0 -15
  14. package/dist/declarations/src/firstThenDebounce.d.ts +0 -8
  15. package/dist/declarations/src/formatDecimals.d.ts +0 -12
  16. package/dist/declarations/src/formatPrice.d.ts +0 -1
  17. package/dist/declarations/src/getLoadable.d.ts +0 -25
  18. package/dist/declarations/src/getQuery.d.ts +0 -45
  19. package/dist/declarations/src/getSharedObservable.d.ts +0 -13
  20. package/dist/declarations/src/hasOwnProperty.d.ts +0 -1
  21. package/dist/declarations/src/index.d.ts +0 -31
  22. package/dist/declarations/src/isAbortError.d.ts +0 -1
  23. package/dist/declarations/src/isArrayOf.d.ts +0 -1
  24. package/dist/declarations/src/isAscii.d.ts +0 -1
  25. package/dist/declarations/src/isBigInt.d.ts +0 -1
  26. package/dist/declarations/src/isBooleanTrue.d.ts +0 -1
  27. package/dist/declarations/src/isHexString.d.ts +0 -3
  28. package/dist/declarations/src/isNotNil.d.ts +0 -9
  29. package/dist/declarations/src/isPromise.d.ts +0 -1
  30. package/dist/declarations/src/isSubject.d.ts +0 -5
  31. package/dist/declarations/src/isTruthy.d.ts +0 -1
  32. package/dist/declarations/src/keepAlive.d.ts +0 -17
  33. package/dist/declarations/src/planckToTokens.d.ts +0 -3
  34. package/dist/declarations/src/replaySubjectFrom.d.ts +0 -12
  35. package/dist/declarations/src/sleep.d.ts +0 -1
  36. package/dist/declarations/src/splitSubject.d.ts +0 -11
  37. package/dist/declarations/src/throwAfter.d.ts +0 -1
  38. package/dist/declarations/src/tokensToPlanck.d.ts +0 -3
  39. package/dist/declarations/src/validateHexString.d.ts +0 -11
  40. package/dist/talismn-util.cjs.d.ts +0 -1
  41. package/dist/talismn-util.cjs.dev.js +0 -500
  42. package/dist/talismn-util.cjs.js +0 -7
  43. package/dist/talismn-util.cjs.prod.js +0 -500
  44. package/dist/talismn-util.esm.js +0 -463
@@ -1,463 +0,0 @@
1
- import { twMerge } from 'tailwind-merge';
2
- import { concat, take, skip, debounceTime, shareReplay, Subject, tap, ReplaySubject, timer, switchMap, from, startWith, map, catchError, of, Observable, BehaviorSubject, distinctUntilChanged } from 'rxjs';
3
- import BigNumber from 'bignumber.js';
4
- import { isEqual } from 'lodash-es';
5
-
6
- const addTrailingSlash = url => {
7
- if (url.endsWith("/")) {
8
- return url;
9
- }
10
- return `${url}/`;
11
- };
12
-
13
- /**
14
- * Javascript's `Math` library for `BigInt`.
15
- * Taken from https://stackoverflow.com/questions/51867270/is-there-a-library-similar-to-math-that-supports-javascript-bigint/64953280#64953280
16
- */
17
- const BigMath = {
18
- abs(x) {
19
- return x < 0n ? -x : x;
20
- },
21
- sign(x) {
22
- if (x === 0n) return 0n;
23
- return x < 0n ? -1n : 1n;
24
- },
25
- // TODO: Improve our babel/tsc config to let us use the `**` operator on bigint values.
26
- // Error thrown: Exponentiation cannot be performed on 'bigint' values unless the 'target' option is set to 'es2016' or later. ts(2791)
27
- // pow(base: bigint, exponent: bigint) {
28
- // return base ** exponent
29
- // },
30
- min(value, ...values) {
31
- for (const v of values) if (v < value) value = v;
32
- return value;
33
- },
34
- max(value, ...values) {
35
- for (const v of values) if (v > value) value = v;
36
- return value;
37
- }
38
- };
39
-
40
- const classNames = twMerge;
41
- const cn = twMerge;
42
-
43
- /**
44
- * In TypeScript, a deferred promise refers to a pattern that involves creating a promise that can be
45
- * resolved or rejected at a later point in time, typically by code outside of the current function scope.
46
- *
47
- * This pattern is often used when dealing with asynchronous operations that involve multiple steps or when
48
- * the result of an operation cannot be immediately determined.
49
- */
50
- function Deferred() {
51
- let resolve;
52
- let reject;
53
- let isPending = true;
54
- let isResolved = false;
55
- let isRejected = false;
56
- const promise = new Promise((innerResolve, innerReject) => {
57
- resolve = value => {
58
- isPending = false;
59
- isResolved = true;
60
- innerResolve(value);
61
- };
62
- reject = reason => {
63
- isPending = false;
64
- isRejected = true;
65
- innerReject(reason);
66
- };
67
- });
68
- return {
69
- promise,
70
- resolve,
71
- reject,
72
- isPending: () => isPending,
73
- isResolved: () => isResolved,
74
- isRejected: () => isRejected
75
- };
76
- }
77
-
78
- /**
79
- * An rxjs operator which:
80
- *
81
- * 1. Emits the first value it receives from the source observable, then:
82
- * 2. Debounces any future values by `timeout` ms.
83
- */
84
- const firstThenDebounce = timeout => source => concat(source.pipe(take(1)), source.pipe(skip(1)).pipe(debounceTime(timeout)));
85
-
86
- const MIN_DIGITS = 4; // less truncates more than what compact formating is
87
- const MAX_DECIMALS_FORMAT = 12;
88
-
89
- /**
90
- * Custom decimal number formatting for Talisman
91
- * note that the NumberFormat().format() call is the ressource heavy part, it's not worth trying to optimize other parts
92
- * @param num input number
93
- * @param digits number of significant digits to display
94
- * @param locale locale used to format the number
95
- * @param options formatting options
96
- * @returns the formatted value
97
- */
98
- const formatDecimals = (num, digits = MIN_DIGITS, options = {}, locale = "en-US") => {
99
- if (num === null || num === undefined) return "";
100
- if (digits < MIN_DIGITS) digits = MIN_DIGITS;
101
- const value = new BigNumber(num);
102
- // very small numbers should display "< 0.0001"
103
- const minDisplayVal = 1 / Math.pow(10, digits);
104
- if (value.gt(0) && value.lt(minDisplayVal)) return `< ${formatDecimals(minDisplayVal)}`;
105
-
106
- // count digits
107
- const flooredValue = value.integerValue();
108
- const intDigits = flooredValue.isEqualTo(0) ? 0 : flooredValue.toString().length;
109
-
110
- // we never want to display a rounded up value
111
- // to prevent JS default rounding, we will remove/truncate insignificant digits ourselves before formatting
112
- let truncatedValue = value;
113
- //remove insignificant fraction digits
114
- const excessFractionDigitsPow10 = new BigNumber(10).pow(digits > intDigits ? digits - intDigits : 0);
115
- truncatedValue = truncatedValue.multipliedBy(excessFractionDigitsPow10).integerValue().dividedBy(excessFractionDigitsPow10);
116
-
117
- //remove insignificant integer digits
118
- const excessIntegerDigits = new BigNumber(intDigits > digits ? intDigits - digits : 0);
119
- const excessIntegerDigitsPow10 = new BigNumber(10).pow(excessIntegerDigits);
120
- if (excessIntegerDigits.gt(0)) truncatedValue = truncatedValue.dividedBy(excessIntegerDigitsPow10).integerValue().multipliedBy(excessIntegerDigitsPow10);
121
-
122
- // format
123
-
124
- return Intl.NumberFormat(locale, {
125
- // compact notation (K, M, B) if above 9999
126
- notation: truncatedValue.gt(9999) ? "compact" : "standard",
127
- // NOTE: possible values are from `0` to `21`
128
- // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat#maximumsignificantdigits
129
- maximumSignificantDigits: Math.max(1, Math.min(digits + (truncatedValue.lt(1) ? 1 : 0), 21)),
130
- ...options
131
- }).format(truncatedValue.toNumber());
132
- };
133
-
134
- const formatPrice = (price, currency, compact) => {
135
- return Intl.NumberFormat(undefined, {
136
- style: "currency",
137
- currency,
138
- currencyDisplay: currency === "usd" ? "narrowSymbol" : "symbol",
139
- minimumSignificantDigits: 3,
140
- maximumSignificantDigits: compact ? price < 1 ? 3 : 4 : undefined,
141
- roundingPriority: compact ? "auto" : "morePrecision",
142
- notation: compact ? "compact" : "standard"
143
- }).format(price);
144
- };
145
-
146
- const CACHE = new Map();
147
-
148
- /**
149
- * When using react-rxjs hooks and state observables, the options are used as weak map keys.
150
- * This means that if the options object is recreated on each render, the observable will be recreated as well.
151
- * This utility function allows you to create a shared observable based on a namespace and arguments that, so react-rxjs can reuse the same observables
152
- *
153
- * @param namespace
154
- * @param args
155
- * @param createObservable
156
- * @param serializer
157
- * @returns
158
- */
159
- const getSharedObservable = (namespace, args, createObservable, serializer = args => JSON.stringify(args)) => {
160
- const cacheKey = `${namespace}:${serializer(args)}`;
161
- if (CACHE.has(cacheKey)) return CACHE.get(cacheKey);
162
- const obs = createObservable(args);
163
- const sharedObs = obs.pipe(shareReplay({
164
- bufferSize: 1,
165
- refCount: true
166
- }));
167
- CACHE.set(cacheKey, sharedObs);
168
- return sharedObs;
169
- };
170
-
171
- function hasOwnProperty(obj, prop) {
172
- if (typeof obj !== "object") return false;
173
- if (obj === null) return false;
174
- return prop in obj;
175
- }
176
-
177
- const isAbortError = error => {
178
- return error instanceof Error && error.name === "AbortError";
179
- };
180
-
181
- function isArrayOf(array, func) {
182
- if (array.length > 0 && array[0] instanceof func) return true;
183
- return false;
184
- }
185
-
186
- const isAscii = str => {
187
- return [...str].every(char => char.charCodeAt(0) <= 127);
188
- };
189
-
190
- const isBigInt = value => typeof value === "bigint";
191
-
192
- const isBooleanTrue = x => !!x;
193
-
194
- const REGEX_HEX_STRING = /^0x[0-9a-fA-F]*$/;
195
- const isHexString = value => {
196
- return typeof value === "string" && REGEX_HEX_STRING.test(value);
197
- };
198
-
199
- /**
200
- * WARNING: This function only checks against null or undefined, it does not coerce the value.
201
- * ie: false and 0 are considered not nil
202
- * Use isTruthy instead for a regular coercion check.
203
- *
204
- * @param value
205
- * @returns whether the value is neither null nor undefined
206
- */
207
- const isNotNil = value => value !== null && value !== undefined;
208
-
209
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
210
- const isPromise = value => !!value && (typeof value === "object" || typeof value === "function") && typeof value.then === "function";
211
-
212
- /**
213
- * Tests to see if an object is an RxJS {@link Subject}.
214
- */
215
- function isSubject(object) {
216
- if (!object) return false;
217
- if (object instanceof Subject) return true;
218
- return "asObservable" in object && isFn(object.asObservable) && "complete" in object && isFn(object.complete) && "error" in object && isFn(object.error) && "forEach" in object && isFn(object.forEach) && "next" in object && isFn(object.next) && "pipe" in object && isFn(object.pipe) && "subscribe" in object && isFn(object.subscribe) && "unsubscribe" in object && isFn(object.unsubscribe) && "closed" in object && isBool(object.closed) && "observed" in object && isBool(object.observed);
219
- }
220
-
221
- /**
222
- * Returns `true` if `value` is a function.
223
- */
224
- function isFn(value) {
225
- return typeof value === "function";
226
- }
227
-
228
- /**
229
- * Returns `true` if `value` is a boolean.
230
- */
231
- function isBool(value) {
232
- return typeof value === "boolean";
233
- }
234
-
235
- const isTruthy = value => Boolean(value);
236
-
237
- /**
238
- * An RxJS operator that keeps the source observable alive for a specified duration
239
- * after all subscribers have unsubscribed. This prevents expensive re-subscriptions
240
- * when subscribers come and go frequently.
241
- *
242
- * @param keepAliveMs - Duration in milliseconds to keep the source alive after last unsubscription
243
- * @returns MonoTypeOperatorFunction that can be used in pipe()
244
- *
245
- * @example
246
- * ```typescript
247
- * const data$ = expensive_api_call$.pipe(
248
- * keepAlive(3000) // Keep alive for 3 seconds
249
- * );
250
- * ```
251
- */
252
- const keepAlive = timeout => {
253
- let release;
254
- return source => source.pipe(tap({
255
- subscribe: () => {
256
- release = keepSourceSubscribed(source, timeout);
257
- },
258
- unsubscribe: () => {
259
- release?.();
260
- }
261
- }), shareReplay({
262
- refCount: true,
263
- bufferSize: 1
264
- }));
265
- };
266
- const keepSourceSubscribed = (observable, ms) => {
267
- const sub = observable.subscribe();
268
- return () => setTimeout(() => sub.unsubscribe(), ms);
269
- };
270
-
271
- function planckToTokens(planck, tokenDecimals) {
272
- if (typeof planck !== "string" || typeof tokenDecimals !== "number") return;
273
- const base = 10;
274
- const exponent = -1 * tokenDecimals;
275
- const multiplier = base ** exponent;
276
- return new BigNumber(planck).multipliedBy(multiplier).toString(10);
277
- }
278
-
279
- /**
280
- * Turns a value into a {@link ReplaySubject} of size 1.
281
- *
282
- * If the value is already a {@link ReplaySubject}, it will be returned as-is.
283
- *
284
- * If the value is a {@link Promise}, it will be awaited,
285
- * and the awaited value will be published into the {@link ReplaySubject} when it becomes available.
286
- *
287
- * For any other type of value, it will be immediately published into the {@link ReplaySubject}.
288
- */
289
- const replaySubjectFrom = initialValue => {
290
- if (initialValue instanceof ReplaySubject) return initialValue;
291
- const subject = new ReplaySubject(1);
292
-
293
- // if initialValue is a promise, await it and then call `subject.next()` with the awaited value
294
- if (isPromise(initialValue)) {
295
- initialValue.then(value => subject.next(value), error => subject.error(error));
296
- return subject;
297
- }
298
-
299
- // if initialValue is not a promise, immediately call `subject.next()` with the value
300
- subject.next(initialValue);
301
- return subject;
302
- };
303
-
304
- const sleep = ms => new Promise(resolve => {
305
- if (process.env.NODE_ENV === "test") resolve();else setTimeout(resolve, ms);
306
- });
307
-
308
- /**
309
- * Takes a subject and splits it into two parts:
310
- *
311
- * 1. A function to submit new values into the subject.
312
- * 2. An observable for subscribing to new values from the subject.
313
- *
314
- * This can be helpful when, to avoid bugs, you want to expose only one
315
- * of these parts to external code and keep the other part private.
316
- */
317
- function splitSubject(subject) {
318
- const next = value => subject.next(value);
319
- const observable = subject.asObservable();
320
- return [next, observable];
321
- }
322
-
323
- const throwAfter = (ms, reason) => new Promise((_, reject) => setTimeout(() => reject(new Error(reason)), ms));
324
-
325
- function tokensToPlanck(tokens, tokenDecimals) {
326
- if (typeof tokens !== "string" || typeof tokenDecimals !== "number") return;
327
- const base = 10;
328
- const exponent = tokenDecimals;
329
- const multiplier = base ** exponent;
330
- return new BigNumber(tokens).multipliedBy(multiplier).toString(10);
331
- }
332
-
333
- /**
334
- * @name validateHexString
335
- * @description Checks if a string is a hex string. Required to account for type differences between different polkadot libraries
336
- * @param {string} str - string to check
337
- * @returns {`0x${string}`} - boolean
338
- * @example
339
- * validateHexString("0x1234") // "0x1234"
340
- * validateHexString("1234") // Error: Expected a hex string
341
- * validateHexString(1234) // Error: Expected a string
342
- **/
343
- const validateHexString = str => {
344
- if (typeof str !== "string") {
345
- throw new Error("Expected a string");
346
- }
347
- if (str.startsWith("0x")) {
348
- return str;
349
- }
350
- throw new Error("Expected a hex string");
351
- };
352
-
353
- // Designed to be serializable as it can be sent to the frontend
354
-
355
- function getLoadable$(factory, options = {}) {
356
- const {
357
- getError,
358
- refreshInterval
359
- } = options;
360
- const createLoadableStream = () => from(factory()).pipe(map(data => ({
361
- status: "success",
362
- data
363
- })), catchError(error => of({
364
- status: "error",
365
- error: getError ? getError(error) : getGenericError(error)
366
- })));
367
- const source$ = refreshInterval ? timer(0, refreshInterval).pipe(switchMap(() => createLoadableStream())) : createLoadableStream();
368
- return source$.pipe(startWith({
369
- status: "loading"
370
- }));
371
- }
372
- const getGenericError = error => ({
373
- name: "Error",
374
- message: getGenericErrorMessage(error)
375
- });
376
- const getGenericErrorMessage = error => {
377
- if (typeof error === "string") {
378
- return error;
379
- } else if (error instanceof Error) {
380
- return error.message;
381
- } else if (error && typeof error === "object" && "message" in error) {
382
- return error.message;
383
- }
384
- return String(error) || "Unknown error";
385
- };
386
-
387
- /**
388
- * Creates a shared observable for executing queries with caching, loading states, and automatic refresh capabilities.
389
- *
390
- * @example
391
- * ```typescript
392
- * const userQuery$ = getQuery$({
393
- * namespace: 'users',
394
- * args: { userId: 123 },
395
- * queryFn: async ({ userId }) => fetchUser(userId),
396
- * defaultValue: null,
397
- * refreshInterval: 30000
398
- * });
399
- *
400
- * userQuery$.subscribe(result => {
401
- * if (result.status === 'loaded') {
402
- * console.log(result.data);
403
- * }
404
- * });
405
- * ```
406
- */
407
- const getQuery$ = ({
408
- namespace,
409
- args,
410
- queryFn,
411
- defaultValue,
412
- refreshInterval,
413
- serializer = args => JSON.stringify(args)
414
- }) => {
415
- return getSharedObservable(namespace, args, () => new Observable(subscriber => {
416
- const controller = new AbortController();
417
- const result = new BehaviorSubject({
418
- status: "loading",
419
- data: defaultValue,
420
- error: undefined
421
- });
422
-
423
- // result subscription
424
- const sub = result.pipe(distinctUntilChanged(isEqual)).subscribe(subscriber);
425
-
426
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
427
- let timeout = null;
428
-
429
- // fetch result subscription
430
- const run = () => {
431
- if (controller.signal.aborted) return;
432
- queryFn(args, controller.signal).then(data => {
433
- if (controller.signal.aborted) return;
434
- result.next({
435
- status: "loaded",
436
- data,
437
- error: undefined
438
- });
439
- }).catch(error => {
440
- if (controller.signal.aborted) return;
441
- result.next({
442
- status: "error",
443
- data: undefined,
444
- error
445
- });
446
- }).finally(() => {
447
- if (controller.signal.aborted) return;
448
- if (refreshInterval) timeout = setTimeout(run, refreshInterval);
449
- });
450
- };
451
- run();
452
- return () => {
453
- sub.unsubscribe();
454
- if (timeout) clearTimeout(timeout);
455
- controller.abort(new Error("getQuery$ unsubscribed"));
456
- };
457
- }).pipe(shareReplay({
458
- refCount: true,
459
- bufferSize: 1
460
- })), serializer);
461
- };
462
-
463
- export { BigMath, Deferred, MAX_DECIMALS_FORMAT, REGEX_HEX_STRING, addTrailingSlash, classNames, cn, firstThenDebounce, formatDecimals, formatPrice, getLoadable$, getQuery$, getSharedObservable, hasOwnProperty, isAbortError, isArrayOf, isAscii, isBigInt, isBooleanTrue, isHexString, isNotNil, isPromise, isSubject, isTruthy, keepAlive, planckToTokens, replaySubjectFrom, sleep, splitSubject, throwAfter, tokensToPlanck, validateHexString };