@gera2ld/common 0.0.20 → 0.1.1

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/dist/index.js CHANGED
@@ -134,7 +134,7 @@ function O(e) {
134
134
  //#endregion
135
135
  //#region src/buffer.ts
136
136
  var k = new Uint8Array([13, 10]), A = class {
137
- buffer = new Uint8Array();
137
+ buffer = /* @__PURE__ */ new Uint8Array();
138
138
  requests = [];
139
139
  isClosed = !1;
140
140
  read(e = 8192) {
@@ -228,6 +228,7 @@ function N(e, t) {
228
228
  return s;
229
229
  }
230
230
  var P = class {
231
+ maxSize;
231
232
  data = [];
232
233
  getQueue = /* @__PURE__ */ new Set();
233
234
  putQueue = /* @__PURE__ */ new Set();
@@ -377,6 +378,8 @@ async function U(e, n) {
377
378
  //#endregion
378
379
  //#region src/request.ts
379
380
  var W = class extends Error {
381
+ request;
382
+ response;
380
383
  constructor(e, t, n, r) {
381
384
  super(e, { cause: r }), this.request = t, this.response = n;
382
385
  }
@@ -395,50 +398,45 @@ function G(e) {
395
398
  }), t;
396
399
  }
397
400
  function K(e, t) {
398
- let { json: n, timeout: r = 1e4, searchParams: i, ...a } = t || {}, o = new AbortController(), s = r ? setTimeout(() => o.abort(), r) : null, c = new Headers(a.headers);
399
- n != null && (a.body = JSON.stringify(n), c.set("content-type", "application/json"));
400
- let l = new URL(e);
401
- i && (l.search = G(i).toString());
402
- async function u(e) {
401
+ let { json: n, timeout: r = 1e4, searchParams: i, signal: a = AbortSignal.timeout(r), ...o } = t || {}, s = new Headers(o.headers);
402
+ n != null && (o.body = JSON.stringify(n), s.set("content-type", "application/json"));
403
+ let c = new URL(e);
404
+ i && (c.search = G(i).toString());
405
+ async function l(e) {
403
406
  let n;
404
407
  try {
405
- n = await fetch(l, {
406
- ...a,
407
- headers: c,
408
- signal: o.signal
408
+ n = await fetch(c, {
409
+ ...o,
410
+ headers: s,
411
+ signal: a
409
412
  });
410
413
  let r = await e(n);
411
414
  if (!n.ok) throw new W(n.statusText, {
412
- url: l.toString(),
413
- method: a.method || "GET",
415
+ url: c.toString(),
416
+ method: o.method || "GET",
414
417
  options: t
415
418
  }, n, r);
416
419
  return r;
417
420
  } catch (e) {
418
421
  throw e instanceof W ? e : new W(e?.message || `${e}`, {
419
- url: l.toString(),
420
- method: a.method || "GET",
422
+ url: c.toString(),
423
+ method: o.method || "GET",
421
424
  options: t
422
425
  }, n, e);
423
- } finally {
424
- s && clearTimeout(s);
425
426
  }
426
427
  }
427
428
  return {
428
429
  async arrayBuffer() {
429
- return u((e) => e.arrayBuffer());
430
+ return l((e) => e.arrayBuffer());
430
431
  },
431
432
  async blob() {
432
- return u((e) => e.blob());
433
+ return l((e) => e.blob());
433
434
  },
434
435
  async json() {
435
- return c.has("accept") || c.set("accept", "application/json"), u((e) => e.json());
436
+ return s.has("accept") || s.set("accept", "application/json"), l((e) => e.json());
436
437
  },
437
438
  async text() {
438
- return u((e) => e.text());
439
- },
440
- abort() {
441
- o.abort();
439
+ return l((e) => e.text());
442
440
  }
443
441
  };
444
442
  }
@@ -452,40 +450,62 @@ var q = [
452
450
  ["d", 24],
453
451
  ["mo", 30],
454
452
  ["y", 365 / 30]
453
+ ], J = [
454
+ ["year", 365 * 24 * 60 * 60 * 1e3],
455
+ ["month", 720 * 60 * 60 * 1e3],
456
+ ["week", 10080 * 60 * 1e3],
457
+ ["day", 1440 * 60 * 1e3],
458
+ ["hour", 3600 * 1e3],
459
+ ["minute", 60 * 1e3],
460
+ ["second", 1e3]
455
461
  ];
456
- function J(e, t) {
457
- let n = `${e}`.match(/[a-zA-Z]+$/)?.[0] || "", r = n ? +`${e}`.slice(0, -n.length) : +e;
458
- if (n) {
459
- for (let [e, i] of t?.intervalLevels || q) if (r *= i, e === n) {
460
- n = "";
462
+ function Y(e) {
463
+ let t = `${e}`.match(/[a-zA-Z]+$/)?.[0] || "", n = t ? +`${e}`.slice(0, -t.length) : +e;
464
+ if (t) {
465
+ for (let [e, r] of q) if (n *= r, e === t) {
466
+ t = "";
461
467
  break;
462
468
  }
463
469
  }
464
- if (n || isNaN(r)) throw Error(`Invalid interval: ${e}`);
465
- return r;
466
- }
467
- function Y(e, t) {
468
- let n = Math.sign(e);
469
- e = Math.abs(e);
470
- let r = "ms";
471
- for (let [n, i] of t?.intervalLevels || q) {
472
- if (e < i) break;
473
- e /= i, r = n;
474
- }
475
- return `${n < 0 ? "-" : ""}${z(e, t) || ""}${r}`;
470
+ if (t || isNaN(n)) throw Error(`Invalid interval: ${e}`);
471
+ return n;
476
472
  }
477
- function X(e) {
473
+ function X(e, t) {
474
+ let { locale: n, style: r = "long" } = t ?? {}, i = Math.abs(e);
475
+ for (let [e, t] of J) if (i >= t) return new Intl.NumberFormat(n, {
476
+ style: "unit",
477
+ unit: e,
478
+ unitDisplay: r
479
+ }).format(Math.round(i / t));
480
+ return new Intl.NumberFormat(n, {
481
+ style: "unit",
482
+ unit: "second",
483
+ unitDisplay: r
484
+ }).format(Math.round(i / 1e3));
485
+ }
486
+ function Z(e) {
478
487
  return [
479
488
  e.getFullYear(),
480
489
  e.getMonth() + 1,
481
490
  e.getDate()
482
491
  ].map((e) => `${e}`.padStart(2, "0")).join("-");
483
492
  }
484
- function Z(e) {
493
+ function Q(e) {
485
494
  return new Intl.DateTimeFormat("en-GB", {
486
495
  dateStyle: "short",
487
496
  timeStyle: "medium"
488
497
  }).format(new Date(e));
489
498
  }
499
+ function $(e, t) {
500
+ let n = new Date(e).getTime() - Date.now(), r = Math.abs(n), { locale: i, numeric: a = "auto", style: o = "long" } = t ?? {};
501
+ for (let [e, t] of J) if (r >= t) return new Intl.RelativeTimeFormat(i, {
502
+ numeric: a,
503
+ style: o
504
+ }).format(Math.round(n / t), e);
505
+ return new Intl.RelativeTimeFormat(i, {
506
+ numeric: a,
507
+ style: o
508
+ }).format(Math.round(n / 1e3), "second");
509
+ }
490
510
  //#endregion
491
- export { A as BufferReader, k as CrLf, F as Logger, P as Queue, W as SimpleRequestError, h as b64decode, m as b64encode, _ as b64urlDecode, g as b64urlEncode, G as buildSearchParams, D as bytesToHex, j as concatBuffer, y as decodeText, q as defaultIntervalLevels, T as defer, L as deflateNumber, v as encodeText, X as formatDate, Y as formatInterval, z as formatNumber, B as formatPercentage, w as formatString, I as inflateNumber, N as limitConcurrency, O as loadJS, J as normalizeInterval, H as rateLimiter, b as replacerBigInt, Z as reprDate, C as reprJson, M as searchBuffer, K as simpleRequest, S as truncateString, U as waitUntil, E as wrapFunction };
511
+ export { A as BufferReader, k as CrLf, F as Logger, P as Queue, W as SimpleRequestError, h as b64decode, m as b64encode, _ as b64urlDecode, g as b64urlEncode, G as buildSearchParams, D as bytesToHex, j as concatBuffer, y as decodeText, T as defer, L as deflateNumber, v as encodeText, X as formatDuration, Z as formatISODate, z as formatNumber, B as formatPercentage, w as formatString, I as inflateNumber, N as limitConcurrency, O as loadJS, Y as normalizeInterval, H as rateLimiter, b as replacerBigInt, Q as reprDate, C as reprJson, M as searchBuffer, K as simpleRequest, $ as timeAgo, S as truncateString, U as waitUntil, E as wrapFunction };
package/package.json CHANGED
@@ -1,7 +1,8 @@
1
1
  {
2
2
  "name": "@gera2ld/common",
3
- "version": "0.0.20",
3
+ "version": "0.1.1",
4
4
  "type": "module",
5
+ "sideEffects": false,
5
6
  "exports": {
6
7
  ".": {
7
8
  "import": "./dist/index.js",
@@ -16,8 +17,8 @@
16
17
  "registry": "https://registry.npmjs.org/"
17
18
  },
18
19
  "dependencies": {
19
- "bignumber.js": "^11.0.0",
20
- "es-toolkit": "^1.45.1"
20
+ "bignumber.js": "^11.1.4",
21
+ "es-toolkit": "^1.49.0"
21
22
  },
22
23
  "scripts": {
23
24
  "clean": "del-cli dist tsconfig.tsbuildinfo",
package/dist/base64.d.ts DELETED
@@ -1,6 +0,0 @@
1
- export declare function b64encode(bytes: Uint8Array): string;
2
- export declare function b64decode(base64: string): Uint8Array<ArrayBuffer>;
3
- export declare function b64urlEncode(bytes: Uint8Array): string;
4
- export declare function b64urlDecode(base64url: string): Uint8Array<ArrayBuffer>;
5
- export declare function encodeText(str: string): Uint8Array<ArrayBuffer>;
6
- export declare function decodeText(bytes: Uint8Array): string;
package/dist/buffer.d.ts DELETED
@@ -1,14 +0,0 @@
1
- export declare const CrLf: Uint8Array<ArrayBuffer>;
2
- export declare class BufferReader {
3
- private buffer;
4
- private requests;
5
- isClosed: boolean;
6
- read(size?: number): Promise<Uint8Array>;
7
- readExact(size: number): Promise<Uint8Array>;
8
- readUntil(delimiter?: string | Uint8Array): Promise<Uint8Array>;
9
- feed(chunk: Uint8Array): void;
10
- close(): void;
11
- private processBuffer;
12
- }
13
- export declare function concatBuffer(a: Uint8Array, b: Uint8Array): Uint8Array;
14
- export declare function searchBuffer(buffer: Uint8Array, slice: Uint8Array): number;
@@ -1,13 +0,0 @@
1
- export declare function limitConcurrency<T extends unknown[], U>(fn: (...args: T) => Promise<U>, concurrency: number): (...args: T) => Promise<U>;
2
- export declare class Queue<T> {
3
- maxSize: number;
4
- private data;
5
- private getQueue;
6
- private putQueue;
7
- constructor(maxSize?: number);
8
- get size(): number;
9
- private defer;
10
- private resolve;
11
- get(maxWait?: number): Promise<T | undefined>;
12
- put(item: T, maxWait?: number): Promise<void>;
13
- }
package/dist/index.d.ts DELETED
@@ -1,9 +0,0 @@
1
- export * from './base64';
2
- export * from './buffer';
3
- export * from './concurrency';
4
- export * from './logger';
5
- export * from './number';
6
- export * from './rate-limiter';
7
- export * from './request';
8
- export * from './time';
9
- export * from './util';
package/dist/logger.d.ts DELETED
@@ -1,16 +0,0 @@
1
- interface ILoggerOptions {
2
- prefix?: string | (() => string);
3
- }
4
- export declare class Logger {
5
- static defaultOptions: ILoggerOptions;
6
- private output?;
7
- options: ILoggerOptions;
8
- constructor(opts?: string | Partial<ILoggerOptions>);
9
- getPrefix(): string;
10
- collect(): () => string[];
11
- log(type: 'info' | 'error', pattern: string, ...args: unknown[]): void;
12
- info(pattern: string, ...args: unknown[]): void;
13
- error(pattern: string, ...args: unknown[]): void;
14
- wrap<U extends unknown[], V, T>(fn: (this: T, ...args: U) => V, wrapper: (logger: Logger, fn: (this: T, ...args: U) => V, ...args: U) => V): (this: T, ...args: U) => V;
15
- }
16
- export {};
package/dist/number.d.ts DELETED
@@ -1,41 +0,0 @@
1
- export declare function inflateNumber(input: number | string, decimals: number): bigint;
2
- export declare function deflateNumber(input: number | string | bigint, decimals: number): number;
3
- export interface INumberOptions {
4
- /**
5
- * Maximum digits after the decimal point in fixed-point notation.
6
- * `1.2345` with `2` becomes `1.23`.
7
- */
8
- maximumFractionDigits: number;
9
- /**
10
- * Absolute value threshold for switching to exponential notation for large numbers.
11
- * `12345678`>\`1e6` becomes `1.23456e+7`.
12
- */
13
- exponentialThresholdLarge: number;
14
- /**
15
- * Absolute value threshold for switching to exponential notation for small non-zero numbers.
16
- * `0.000000123`<\`1e-6` becomes `1.23e-7`.
17
- */
18
- exponentialThresholdSmall: number;
19
- /**
20
- * Minimum number of significant digits to display.
21
- * `12` with `3` becomes `12.00`.
22
- */
23
- minimumSignificantDigits: number;
24
- /**
25
- * Maximum number of significant digits to display.
26
- * `123456789` with `5` might become `1.2346e+8`.
27
- */
28
- maximumSignificantDigits: number;
29
- /**
30
- * Rounds the numerical value to the nearest multiple of this step *before* formatting.
31
- * `123456` with `100` becomes `123400` then formatted.
32
- */
33
- quantizationStep: number;
34
- /**
35
- * Whether to keep trailing zeros in the fractional part of a number.
36
- * e.g. `1.200` becomes `1.2` if false.
37
- */
38
- keepTrailingZeros?: boolean;
39
- }
40
- export declare function formatNumber(num?: number | string, options?: Partial<INumberOptions>): string;
41
- export declare function formatPercentage(value: number, options?: Partial<INumberOptions>): string;
@@ -1 +0,0 @@
1
- export {};
@@ -1,17 +0,0 @@
1
- export interface IRetryOptions {
2
- interval: number;
3
- maxRetry: number;
4
- maxInterval: number;
5
- }
6
- export interface IRateLimitOptions extends IRetryOptions {
7
- isTooFrequent?: (error: any) => boolean;
8
- onScheduleRetry?: (interval: number) => void;
9
- }
10
- export declare function rateLimiter(options?: Partial<IRateLimitOptions>): <U>(fn: () => Promise<U>) => Promise<U>;
11
- export interface IWaitResult<T = unknown> {
12
- interval?: number;
13
- error?: unknown;
14
- ok: boolean;
15
- data: T;
16
- }
17
- export declare function waitUntil<T = unknown>(fn: () => Promise<IWaitResult<T>>, options?: IRetryOptions): Promise<IWaitResult<T>>;
package/dist/request.d.ts DELETED
@@ -1,26 +0,0 @@
1
- export type IRequestOptions = RequestInit & {
2
- json?: unknown;
3
- timeout?: number;
4
- searchParams?: string[][] | Record<string, any> | URLSearchParams;
5
- };
6
- export declare class SimpleRequestError extends Error {
7
- request: {
8
- url: string;
9
- method: string;
10
- options?: IRequestOptions;
11
- };
12
- response?: Response | undefined;
13
- constructor(message: string, request: {
14
- url: string;
15
- method: string;
16
- options?: IRequestOptions;
17
- }, response?: Response | undefined, cause?: unknown);
18
- }
19
- export declare function buildSearchParams(init?: IRequestOptions['searchParams']): URLSearchParams;
20
- export declare function simpleRequest<T = unknown>(url: string | URL, options?: IRequestOptions): {
21
- arrayBuffer(): Promise<ArrayBuffer>;
22
- blob(): Promise<Blob>;
23
- json<U = T>(): Promise<U>;
24
- text(): Promise<string>;
25
- abort(): void;
26
- };
@@ -1 +0,0 @@
1
- export {};
package/dist/time.d.ts DELETED
@@ -1,10 +0,0 @@
1
- import { type INumberOptions } from './number.ts';
2
- export declare const defaultIntervalLevels: Array<[string, number]>;
3
- export declare function normalizeInterval(interval: string | number, options?: Partial<{
4
- intervalLevels: Array<[string, number]>;
5
- }>): number;
6
- export declare function formatInterval(interval: number, options?: Partial<INumberOptions & {
7
- intervalLevels: Array<[string, number]>;
8
- }>): string;
9
- export declare function formatDate(date: Date): string;
10
- export declare function reprDate(date: number | string | Date): string;
package/dist/util.d.ts DELETED
@@ -1,21 +0,0 @@
1
- export declare function replacerBigInt(_key: string, value: any): any;
2
- interface ReprJsonOptions {
3
- truncateThreshold: number;
4
- headLength: number;
5
- tailLength: number;
6
- }
7
- export declare function truncateString(input: string, options?: Partial<ReprJsonOptions>): string;
8
- export declare function reprJson(obj: unknown, options?: Partial<ReprJsonOptions>): string;
9
- export declare function formatString(fmt: string, ...args: unknown[]): string;
10
- export interface IDeferred<T> {
11
- promise: Promise<T>;
12
- resolve: (result: T | Promise<T>) => void;
13
- reject: (reason?: any) => void;
14
- status: 'pending' | 'resolved' | 'rejected';
15
- }
16
- export declare function defer<T = void>(): IDeferred<T>;
17
- type IFunction<U extends any[], V, T> = (this: T, ...args: U) => V;
18
- export declare function wrapFunction<U extends any[], V, T>(fn: IFunction<U, V, T>, wrapper: (this: T, originalFn: IFunction<U, V, T>, ...args: U) => V): (this: T, ...args: U) => V;
19
- export declare function bytesToHex(bytes: Uint8Array): string;
20
- export declare function loadJS(url: string): Promise<unknown>;
21
- export {};