@gera2ld/common 0.1.0 → 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
@@ -398,50 +398,45 @@ function G(e) {
398
398
  }), t;
399
399
  }
400
400
  function K(e, t) {
401
- 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);
402
- n != null && (a.body = JSON.stringify(n), c.set("content-type", "application/json"));
403
- let l = new URL(e);
404
- i && (l.search = G(i).toString());
405
- 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) {
406
406
  let n;
407
407
  try {
408
- n = await fetch(l, {
409
- ...a,
410
- headers: c,
411
- signal: o.signal
408
+ n = await fetch(c, {
409
+ ...o,
410
+ headers: s,
411
+ signal: a
412
412
  });
413
413
  let r = await e(n);
414
414
  if (!n.ok) throw new W(n.statusText, {
415
- url: l.toString(),
416
- method: a.method || "GET",
415
+ url: c.toString(),
416
+ method: o.method || "GET",
417
417
  options: t
418
418
  }, n, r);
419
419
  return r;
420
420
  } catch (e) {
421
421
  throw e instanceof W ? e : new W(e?.message || `${e}`, {
422
- url: l.toString(),
423
- method: a.method || "GET",
422
+ url: c.toString(),
423
+ method: o.method || "GET",
424
424
  options: t
425
425
  }, n, e);
426
- } finally {
427
- s && clearTimeout(s);
428
426
  }
429
427
  }
430
428
  return {
431
429
  async arrayBuffer() {
432
- return u((e) => e.arrayBuffer());
430
+ return l((e) => e.arrayBuffer());
433
431
  },
434
432
  async blob() {
435
- return u((e) => e.blob());
433
+ return l((e) => e.blob());
436
434
  },
437
435
  async json() {
438
- 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());
439
437
  },
440
438
  async text() {
441
- return u((e) => e.text());
442
- },
443
- abort() {
444
- o.abort();
439
+ return l((e) => e.text());
445
440
  }
446
441
  };
447
442
  }
@@ -455,40 +450,62 @@ var q = [
455
450
  ["d", 24],
456
451
  ["mo", 30],
457
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]
458
461
  ];
459
- function J(e, t) {
460
- let n = `${e}`.match(/[a-zA-Z]+$/)?.[0] || "", r = n ? +`${e}`.slice(0, -n.length) : +e;
461
- if (n) {
462
- for (let [e, i] of t?.intervalLevels || q) if (r *= i, e === n) {
463
- 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 = "";
464
467
  break;
465
468
  }
466
469
  }
467
- if (n || isNaN(r)) throw Error(`Invalid interval: ${e}`);
468
- return r;
469
- }
470
- function Y(e, t) {
471
- let n = Math.sign(e);
472
- e = Math.abs(e);
473
- let r = "ms";
474
- for (let [n, i] of t?.intervalLevels || q) {
475
- if (e < i) break;
476
- e /= i, r = n;
477
- }
478
- return `${n < 0 ? "-" : ""}${z(e, t) || ""}${r}`;
470
+ if (t || isNaN(n)) throw Error(`Invalid interval: ${e}`);
471
+ return n;
479
472
  }
480
- 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) {
481
487
  return [
482
488
  e.getFullYear(),
483
489
  e.getMonth() + 1,
484
490
  e.getDate()
485
491
  ].map((e) => `${e}`.padStart(2, "0")).join("-");
486
492
  }
487
- function Z(e) {
493
+ function Q(e) {
488
494
  return new Intl.DateTimeFormat("en-GB", {
489
495
  dateStyle: "short",
490
496
  timeStyle: "medium"
491
497
  }).format(new Date(e));
492
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
+ }
493
510
  //#endregion
494
- 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,6 +1,6 @@
1
1
  {
2
2
  "name": "@gera2ld/common",
3
- "version": "0.1.0",
3
+ "version": "0.1.1",
4
4
  "type": "module",
5
5
  "sideEffects": false,
6
6
  "exports": {
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 {};