@talismn/util 0.5.5 → 0.5.7

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 -498
  42. package/dist/talismn-util.cjs.js +0 -7
  43. package/dist/talismn-util.cjs.prod.js +0 -498
  44. package/dist/talismn-util.esm.js +0 -461
@@ -1,461 +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
- maximumSignificantDigits: digits + (truncatedValue.lt(1) ? 1 : 0),
128
- ...options
129
- }).format(truncatedValue.toNumber());
130
- };
131
-
132
- const formatPrice = (price, currency, compact) => {
133
- return Intl.NumberFormat(undefined, {
134
- style: "currency",
135
- currency,
136
- currencyDisplay: currency === "usd" ? "narrowSymbol" : "symbol",
137
- minimumSignificantDigits: 3,
138
- maximumSignificantDigits: compact ? price < 1 ? 3 : 4 : undefined,
139
- roundingPriority: compact ? "auto" : "morePrecision",
140
- notation: compact ? "compact" : "standard"
141
- }).format(price);
142
- };
143
-
144
- const CACHE = new Map();
145
-
146
- /**
147
- * When using react-rxjs hooks and state observables, the options are used as weak map keys.
148
- * This means that if the options object is recreated on each render, the observable will be recreated as well.
149
- * 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
150
- *
151
- * @param namespace
152
- * @param args
153
- * @param createObservable
154
- * @param serializer
155
- * @returns
156
- */
157
- const getSharedObservable = (namespace, args, createObservable, serializer = args => JSON.stringify(args)) => {
158
- const cacheKey = `${namespace}:${serializer(args)}`;
159
- if (CACHE.has(cacheKey)) return CACHE.get(cacheKey);
160
- const obs = createObservable(args);
161
- const sharedObs = obs.pipe(shareReplay({
162
- bufferSize: 1,
163
- refCount: true
164
- }));
165
- CACHE.set(cacheKey, sharedObs);
166
- return sharedObs;
167
- };
168
-
169
- function hasOwnProperty(obj, prop) {
170
- if (typeof obj !== "object") return false;
171
- if (obj === null) return false;
172
- return prop in obj;
173
- }
174
-
175
- const isAbortError = error => {
176
- return error instanceof Error && error.name === "AbortError";
177
- };
178
-
179
- function isArrayOf(array, func) {
180
- if (array.length > 0 && array[0] instanceof func) return true;
181
- return false;
182
- }
183
-
184
- const isAscii = str => {
185
- return [...str].every(char => char.charCodeAt(0) <= 127);
186
- };
187
-
188
- const isBigInt = value => typeof value === "bigint";
189
-
190
- const isBooleanTrue = x => !!x;
191
-
192
- const REGEX_HEX_STRING = /^0x[0-9a-fA-F]*$/;
193
- const isHexString = value => {
194
- return typeof value === "string" && REGEX_HEX_STRING.test(value);
195
- };
196
-
197
- /**
198
- * WARNING: This function only checks against null or undefined, it does not coerce the value.
199
- * ie: false and 0 are considered not nil
200
- * Use isTruthy instead for a regular coercion check.
201
- *
202
- * @param value
203
- * @returns whether the value is neither null nor undefined
204
- */
205
- const isNotNil = value => value !== null && value !== undefined;
206
-
207
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
208
- const isPromise = value => !!value && (typeof value === "object" || typeof value === "function") && typeof value.then === "function";
209
-
210
- /**
211
- * Tests to see if an object is an RxJS {@link Subject}.
212
- */
213
- function isSubject(object) {
214
- if (!object) return false;
215
- if (object instanceof Subject) return true;
216
- 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);
217
- }
218
-
219
- /**
220
- * Returns `true` if `value` is a function.
221
- */
222
- function isFn(value) {
223
- return typeof value === "function";
224
- }
225
-
226
- /**
227
- * Returns `true` if `value` is a boolean.
228
- */
229
- function isBool(value) {
230
- return typeof value === "boolean";
231
- }
232
-
233
- const isTruthy = value => Boolean(value);
234
-
235
- /**
236
- * An RxJS operator that keeps the source observable alive for a specified duration
237
- * after all subscribers have unsubscribed. This prevents expensive re-subscriptions
238
- * when subscribers come and go frequently.
239
- *
240
- * @param keepAliveMs - Duration in milliseconds to keep the source alive after last unsubscription
241
- * @returns MonoTypeOperatorFunction that can be used in pipe()
242
- *
243
- * @example
244
- * ```typescript
245
- * const data$ = expensive_api_call$.pipe(
246
- * keepAlive(3000) // Keep alive for 3 seconds
247
- * );
248
- * ```
249
- */
250
- const keepAlive = timeout => {
251
- let release;
252
- return source => source.pipe(tap({
253
- subscribe: () => {
254
- release = keepSourceSubscribed(source, timeout);
255
- },
256
- unsubscribe: () => {
257
- release?.();
258
- }
259
- }), shareReplay({
260
- refCount: true,
261
- bufferSize: 1
262
- }));
263
- };
264
- const keepSourceSubscribed = (observable, ms) => {
265
- const sub = observable.subscribe();
266
- return () => setTimeout(() => sub.unsubscribe(), ms);
267
- };
268
-
269
- function planckToTokens(planck, tokenDecimals) {
270
- if (typeof planck !== "string" || typeof tokenDecimals !== "number") return;
271
- const base = 10;
272
- const exponent = -1 * tokenDecimals;
273
- const multiplier = base ** exponent;
274
- return new BigNumber(planck).multipliedBy(multiplier).toString(10);
275
- }
276
-
277
- /**
278
- * Turns a value into a {@link ReplaySubject} of size 1.
279
- *
280
- * If the value is already a {@link ReplaySubject}, it will be returned as-is.
281
- *
282
- * If the value is a {@link Promise}, it will be awaited,
283
- * and the awaited value will be published into the {@link ReplaySubject} when it becomes available.
284
- *
285
- * For any other type of value, it will be immediately published into the {@link ReplaySubject}.
286
- */
287
- const replaySubjectFrom = initialValue => {
288
- if (initialValue instanceof ReplaySubject) return initialValue;
289
- const subject = new ReplaySubject(1);
290
-
291
- // if initialValue is a promise, await it and then call `subject.next()` with the awaited value
292
- if (isPromise(initialValue)) {
293
- initialValue.then(value => subject.next(value), error => subject.error(error));
294
- return subject;
295
- }
296
-
297
- // if initialValue is not a promise, immediately call `subject.next()` with the value
298
- subject.next(initialValue);
299
- return subject;
300
- };
301
-
302
- const sleep = ms => new Promise(resolve => {
303
- if (process.env.NODE_ENV === "test") resolve();else setTimeout(resolve, ms);
304
- });
305
-
306
- /**
307
- * Takes a subject and splits it into two parts:
308
- *
309
- * 1. A function to submit new values into the subject.
310
- * 2. An observable for subscribing to new values from the subject.
311
- *
312
- * This can be helpful when, to avoid bugs, you want to expose only one
313
- * of these parts to external code and keep the other part private.
314
- */
315
- function splitSubject(subject) {
316
- const next = value => subject.next(value);
317
- const observable = subject.asObservable();
318
- return [next, observable];
319
- }
320
-
321
- const throwAfter = (ms, reason) => new Promise((_, reject) => setTimeout(() => reject(new Error(reason)), ms));
322
-
323
- function tokensToPlanck(tokens, tokenDecimals) {
324
- if (typeof tokens !== "string" || typeof tokenDecimals !== "number") return;
325
- const base = 10;
326
- const exponent = tokenDecimals;
327
- const multiplier = base ** exponent;
328
- return new BigNumber(tokens).multipliedBy(multiplier).toString(10);
329
- }
330
-
331
- /**
332
- * @name validateHexString
333
- * @description Checks if a string is a hex string. Required to account for type differences between different polkadot libraries
334
- * @param {string} str - string to check
335
- * @returns {`0x${string}`} - boolean
336
- * @example
337
- * validateHexString("0x1234") // "0x1234"
338
- * validateHexString("1234") // Error: Expected a hex string
339
- * validateHexString(1234) // Error: Expected a string
340
- **/
341
- const validateHexString = str => {
342
- if (typeof str !== "string") {
343
- throw new Error("Expected a string");
344
- }
345
- if (str.startsWith("0x")) {
346
- return str;
347
- }
348
- throw new Error("Expected a hex string");
349
- };
350
-
351
- // Designed to be serializable as it can be sent to the frontend
352
-
353
- function getLoadable$(factory, options = {}) {
354
- const {
355
- getError,
356
- refreshInterval
357
- } = options;
358
- const createLoadableStream = () => from(factory()).pipe(map(data => ({
359
- status: "success",
360
- data
361
- })), catchError(error => of({
362
- status: "error",
363
- error: getError ? getError(error) : getGenericError(error)
364
- })));
365
- const source$ = refreshInterval ? timer(0, refreshInterval).pipe(switchMap(() => createLoadableStream())) : createLoadableStream();
366
- return source$.pipe(startWith({
367
- status: "loading"
368
- }));
369
- }
370
- const getGenericError = error => ({
371
- name: "Error",
372
- message: getGenericErrorMessage(error)
373
- });
374
- const getGenericErrorMessage = error => {
375
- if (typeof error === "string") {
376
- return error;
377
- } else if (error instanceof Error) {
378
- return error.message;
379
- } else if (error && typeof error === "object" && "message" in error) {
380
- return error.message;
381
- }
382
- return String(error) || "Unknown error";
383
- };
384
-
385
- /**
386
- * Creates a shared observable for executing queries with caching, loading states, and automatic refresh capabilities.
387
- *
388
- * @example
389
- * ```typescript
390
- * const userQuery$ = getQuery$({
391
- * namespace: 'users',
392
- * args: { userId: 123 },
393
- * queryFn: async ({ userId }) => fetchUser(userId),
394
- * defaultValue: null,
395
- * refreshInterval: 30000
396
- * });
397
- *
398
- * userQuery$.subscribe(result => {
399
- * if (result.status === 'loaded') {
400
- * console.log(result.data);
401
- * }
402
- * });
403
- * ```
404
- */
405
- const getQuery$ = ({
406
- namespace,
407
- args,
408
- queryFn,
409
- defaultValue,
410
- refreshInterval,
411
- serializer = args => JSON.stringify(args)
412
- }) => {
413
- return getSharedObservable(namespace, args, () => new Observable(subscriber => {
414
- const controller = new AbortController();
415
- const result = new BehaviorSubject({
416
- status: "loading",
417
- data: defaultValue,
418
- error: undefined
419
- });
420
-
421
- // result subscription
422
- const sub = result.pipe(distinctUntilChanged(isEqual)).subscribe(subscriber);
423
-
424
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
425
- let timeout = null;
426
-
427
- // fetch result subscription
428
- const run = () => {
429
- if (controller.signal.aborted) return;
430
- queryFn(args, controller.signal).then(data => {
431
- if (controller.signal.aborted) return;
432
- result.next({
433
- status: "loaded",
434
- data,
435
- error: undefined
436
- });
437
- }).catch(error => {
438
- if (controller.signal.aborted) return;
439
- result.next({
440
- status: "error",
441
- data: undefined,
442
- error
443
- });
444
- }).finally(() => {
445
- if (controller.signal.aborted) return;
446
- if (refreshInterval) timeout = setTimeout(run, refreshInterval);
447
- });
448
- };
449
- run();
450
- return () => {
451
- sub.unsubscribe();
452
- if (timeout) clearTimeout(timeout);
453
- controller.abort(new Error("getQuery$ unsubscribed"));
454
- };
455
- }).pipe(shareReplay({
456
- refCount: true,
457
- bufferSize: 1
458
- })), serializer);
459
- };
460
-
461
- 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 };