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