xjs-common 8.0.4 → 8.2.0

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/README.md CHANGED
@@ -215,6 +215,7 @@ XJS throws error with `code` property which has one of the following numbers.
215
215
  |10|`func/u`|
216
216
  |20|`func/u-string`|
217
217
  |30|`func/u-type` (include `func/decorator/d-type`) |
218
+ |40|`func/u-file` |
218
219
  |100|`func/decorator/transaction`|
219
220
  |200|`prcs/http/http-resolver`|
220
221
 
@@ -0,0 +1,9 @@
1
+ export declare enum TimeUnit {
2
+ Year = 1,
3
+ Month = 2,
4
+ Day = 3,
5
+ Hour = 4,
6
+ Min = 5,
7
+ Sec = 6,
8
+ Msec = 7
9
+ }
@@ -0,0 +1,13 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.TimeUnit = void 0;
4
+ var TimeUnit;
5
+ (function (TimeUnit) {
6
+ TimeUnit[TimeUnit["Year"] = 1] = "Year";
7
+ TimeUnit[TimeUnit["Month"] = 2] = "Month";
8
+ TimeUnit[TimeUnit["Day"] = 3] = "Day";
9
+ TimeUnit[TimeUnit["Hour"] = 4] = "Hour";
10
+ TimeUnit[TimeUnit["Min"] = 5] = "Min";
11
+ TimeUnit[TimeUnit["Sec"] = 6] = "Sec";
12
+ TimeUnit[TimeUnit["Msec"] = 7] = "Msec";
13
+ })(TimeUnit = exports.TimeUnit || (exports.TimeUnit = {}));
@@ -21,8 +21,11 @@ var UArray;
21
21
  return [];
22
22
  if (op?.k)
23
23
  return Array.from((0, u_1.array2map)(array, e => e[op.k]).values()).map(a => op?.takeLast ? a.pop() : a.shift());
24
- const a = op?.takeLast ? [...array].reverse() : array;
25
- return a.filter((v, i) => a.findIndex(v2 => op?.predicate ? op?.predicate(v, v2) : v == v2) === i);
24
+ const a = op?.takeLast ? [...array].reverse() : [...array];
25
+ const p = op?.predicate ?? ((v1, v2) => v1 == v2);
26
+ const result = [a.shift()];
27
+ a.forEach(v => result.some(v2 => p(v, v2)) ? {} : result.push(v));
28
+ return result;
26
29
  }
27
30
  UArray.distinct = distinct;
28
31
  function chop(array, len) {
@@ -3,9 +3,11 @@ import { MaybeArray } from "../const/types";
3
3
  export declare namespace UFile {
4
4
  function mkdir(p: MaybeArray<string>): boolean;
5
5
  function write(p: MaybeArray<string>, c: string): void;
6
- function exists(...p: string[]): boolean;
6
+ function rm(p: MaybeArray<string>): void;
7
+ function exists(p: MaybeArray<string>): boolean;
7
8
  function read(p: MaybeArray<string>): Buffer;
8
9
  function read(p: MaybeArray<string>, encoding: BufferEncoding): string;
9
10
  function cp(from: MaybeArray<string>, to: MaybeArray<string>): void;
10
11
  function mv(from: MaybeArray<string>, to: MaybeArray<string>): void;
12
+ function joinPath(p: MaybeArray<string>): string;
11
13
  }
@@ -27,43 +27,55 @@ exports.UFile = void 0;
27
27
  const fs = __importStar(require("fs"));
28
28
  const path = __importStar(require("path"));
29
29
  const u_type_1 = require("./u-type");
30
+ const xjs_err_1 = require("../obj/xjs-err");
31
+ const s_errCode = 40;
30
32
  var UFile;
31
33
  (function (UFile) {
32
34
  function mkdir(p) {
33
- const dirPath = join(p);
35
+ const dirPath = joinPath(p);
34
36
  const e = fs.existsSync(dirPath);
35
- if (!e || !fs.statSync(dirPath).isDirectory())
37
+ if (!e)
36
38
  fs.mkdirSync(dirPath, { recursive: true });
39
+ else if (!fs.statSync(dirPath).isDirectory())
40
+ throw new xjs_err_1.XjsErr(s_errCode, "Already exists a file (not directory) on the path.");
37
41
  return !e;
38
42
  }
39
43
  UFile.mkdir = mkdir;
40
44
  function write(p, c) {
41
- fs.writeFileSync(join(p), c);
45
+ fs.writeFileSync(joinPath(p), c);
42
46
  }
43
47
  UFile.write = write;
44
- function exists(...p) {
45
- return !!p && fs.existsSync(path.join(...p));
48
+ function rm(p) {
49
+ fs.rmSync(joinPath(p), { recursive: true });
50
+ }
51
+ UFile.rm = rm;
52
+ function exists(p) {
53
+ return fs.existsSync(joinPath(p));
46
54
  }
47
55
  UFile.exists = exists;
48
56
  function read(p, encoding) {
49
- return fs.readFileSync(join(p), encoding);
57
+ const f = joinPath(p);
58
+ if (!fs.existsSync(f))
59
+ throw new xjs_err_1.XjsErr(s_errCode, `No file found => ${f}`);
60
+ return fs.readFileSync(f, encoding);
50
61
  }
51
62
  UFile.read = read;
52
63
  function cp(from, to) {
53
- const f = join(from), t = join(to);
54
- if (fs.existsSync(f))
55
- fs.writeFileSync(t, fs.readFileSync(f));
64
+ const f = joinPath(from), t = joinPath(to);
65
+ if (!fs.existsSync(f))
66
+ throw new xjs_err_1.XjsErr(s_errCode, `No file found => ${f}`);
67
+ fs.copyFileSync(f, t);
56
68
  }
57
69
  UFile.cp = cp;
58
70
  function mv(from, to) {
59
- const f = join(from), t = join(to);
60
- if (fs.existsSync(f) && fs.statSync(f).isFile()) {
61
- fs.writeFileSync(t, fs.readFileSync(f));
62
- fs.rmSync(f, { force: true });
63
- }
71
+ const f = joinPath(from), t = joinPath(to);
72
+ if (!fs.existsSync(f))
73
+ throw new xjs_err_1.XjsErr(s_errCode, `No file found => ${f}`);
74
+ fs.renameSync(f, t);
64
75
  }
65
76
  UFile.mv = mv;
66
- function join(p) {
77
+ function joinPath(p) {
67
78
  return u_type_1.UType.isString(p) ? p : path.join(...p);
68
79
  }
80
+ UFile.joinPath = joinPath;
69
81
  })(UFile = exports.UFile || (exports.UFile = {}));
@@ -1,7 +1,16 @@
1
+ import { TimeUnit } from "../const/time-unit";
1
2
  export declare namespace UString {
2
3
  function eq(s1: string, s2: string): boolean;
3
- function simpleDate2sec(date?: Date): string;
4
- function simpleDate2day(date?: Date): string;
4
+ /**
5
+ * generate date time number as fixed length (depends on `unit`) string without separator charactor.
6
+ * For example, `2025-06-08T10:15:06.366Z` is to be `20250608101506366`.
7
+ * @param op.date Date object refered by this. default is `new Date()`.
8
+ * @param op.unit time unit. default is secound.
9
+ */
10
+ function simpleTime(op?: {
11
+ date?: Date;
12
+ unit?: TimeUnit;
13
+ }): string;
5
14
  function trimProps(obj: any): void;
6
15
  function generateRandomString(len: number): string;
7
16
  function idx2az(idx: number): string;
@@ -1,6 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.UString = void 0;
4
+ const time_unit_1 = require("../const/time-unit");
4
5
  const xjs_err_1 = require("../obj/xjs-err");
5
6
  const u_1 = require("./u");
6
7
  const u_type_1 = require("./u-type");
@@ -11,14 +12,19 @@ var UString;
11
12
  return !u_type_1.UType.isString(s1) || !u_type_1.UType.isString(s2) ? s1 === s2 : s1.trim() === s2.trim();
12
13
  }
13
14
  UString.eq = eq;
14
- function simpleDate2sec(date) {
15
- return (date ?? new Date()).toISOString().split(".")[0].replace(/[-T:]/g, "");
15
+ /**
16
+ * generate date time number as fixed length (depends on `unit`) string without separator charactor.
17
+ * For example, `2025-06-08T10:15:06.366Z` is to be `20250608101506366`.
18
+ * @param op.date Date object refered by this. default is `new Date()`.
19
+ * @param op.unit time unit. default is secound.
20
+ */
21
+ function simpleTime(op) {
22
+ const t = (op?.date ?? new Date()).toISOString().split(".")[0].replace(/[-T:]/g, "");
23
+ if (op?.unit === time_unit_1.TimeUnit.Msec)
24
+ return t;
25
+ return t.substring(0, 14 - (6 - (op?.unit ?? time_unit_1.TimeUnit.Sec)) * 2);
16
26
  }
17
- UString.simpleDate2sec = simpleDate2sec;
18
- function simpleDate2day(date) {
19
- return simpleDate2sec(date).substring(0, 8);
20
- }
21
- UString.simpleDate2day = simpleDate2day;
27
+ UString.simpleTime = simpleTime;
22
28
  function trimProps(obj) {
23
29
  Object.keys(obj)
24
30
  .filter(k => typeof obj[k] === "string")
package/dist/func/u.d.ts CHANGED
@@ -1,6 +1,9 @@
1
+ import { Loggable } from "../const/types";
1
2
  export declare function getJSTDate(d?: Date): Date;
2
3
  export declare function delay(sec: number): Promise<void>;
3
4
  export declare function int2array(size: number): number[];
4
5
  export declare function array2map<K, T>(array: T[], keyGen: (e: T) => K): Map<K, T[]>;
5
6
  export declare function bitor(...bit: number[]): number;
6
7
  export declare function checkPortAvailability(port: number): Promise<boolean>;
8
+ export declare function retry<T>(cb: () => T, count?: number, logger?: Loggable): T;
9
+ export declare function retry<T>(cb: () => Promise<T>, count?: number, logger?: Loggable): Promise<T>;
package/dist/func/u.js CHANGED
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.checkPortAvailability = exports.bitor = exports.array2map = exports.int2array = exports.delay = exports.getJSTDate = void 0;
3
+ exports.retry = exports.checkPortAvailability = exports.bitor = exports.array2map = exports.int2array = exports.delay = exports.getJSTDate = void 0;
4
4
  const xjs_err_1 = require("../obj/xjs-err");
5
5
  const s_errCode = 10;
6
6
  function getJSTDate(d) {
@@ -43,3 +43,24 @@ function checkPortAvailability(port) {
43
43
  });
44
44
  }
45
45
  exports.checkPortAvailability = checkPortAvailability;
46
+ function retry(cb, count = 2, logger = console) {
47
+ const prcs = (c) => {
48
+ if (c < 0)
49
+ throw new xjs_err_1.XjsErr(s_errCode, "failure exceeds retryable count.");
50
+ let ret = null;
51
+ try {
52
+ ret = cb();
53
+ }
54
+ catch (e) {
55
+ logger.warn(e);
56
+ ret = prcs(c - 1);
57
+ }
58
+ if (ret instanceof Promise) {
59
+ return new Promise(resolve => ret.then(resolve).catch(e => { logger.warn(e); resolve(prcs(c - 1)); }));
60
+ }
61
+ else
62
+ return ret;
63
+ };
64
+ return prcs(count);
65
+ }
66
+ exports.retry = retry;
package/dist/index.d.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  export * from "./const/types";
2
+ export * from "./const/time-unit";
2
3
  export * from "./const/gender";
3
4
  export * from "./const/http-method";
4
5
  export * from "./func/u";
package/dist/index.js CHANGED
@@ -16,6 +16,7 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
16
16
  Object.defineProperty(exports, "__esModule", { value: true });
17
17
  exports.s_clientMode = exports.HttpResolver = exports.DType = void 0;
18
18
  __exportStar(require("./const/types"), exports);
19
+ __exportStar(require("./const/time-unit"), exports);
19
20
  __exportStar(require("./const/gender"), exports);
20
21
  __exportStar(require("./const/http-method"), exports);
21
22
  __exportStar(require("./func/u"), exports);
@@ -1,5 +1,6 @@
1
1
  import { ClientMode } from "./http-resolver";
2
2
  import { ClientOption, IHttpClient, RequestOption } from "./i-http-client";
3
+ import { Loggable } from "../../const/types";
3
4
  export declare const s_clientMode: Record<string, ClientMode>;
4
5
  export declare class HttpResolverContext implements IHttpClient {
5
6
  private readonly _cmv;
@@ -10,10 +11,7 @@ export declare class HttpResolverContext implements IHttpClient {
10
11
  private readonly _proxyConfig?;
11
12
  private readonly _chHeaders;
12
13
  private _cookies?;
13
- constructor(_cmv: number, op?: ClientOption, _l?: {
14
- log: (msg: any) => void;
15
- warn: (msg: any) => void;
16
- });
14
+ constructor(_cmv: number, op?: ClientOption, _l?: Loggable);
17
15
  /**
18
16
  * request GET to the url.
19
17
  * @param url target url.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "xjs-common",
3
- "version": "8.0.4",
3
+ "version": "8.2.0",
4
4
  "description": "library modules for nodejs + typescript that bundled general-purpose implementations.",
5
5
  "repository": {
6
6
  "type": "git",