@zwa73/utils 1.0.222 → 1.0.224

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 (47) hide show
  1. package/dist/{QuickExport.js → cjs/QuickExport.js} +2 -2
  2. package/dist/{UtilClass → cjs/UtilClass}/Hbs.js +13 -6
  3. package/dist/{UtilClass → cjs/UtilClass}/index.js +0 -1
  4. package/dist/{UtilCodecs.js → cjs/UtilCodecs.js} +24 -16
  5. package/dist/{UtilDecorators.js → cjs/UtilDecorators.js} +0 -1
  6. package/dist/{UtilFileTools.js → cjs/UtilFileTools.js} +72 -16
  7. package/dist/{UtilFunctions.js → cjs/UtilFunctions.js} +28 -8
  8. package/dist/{UtilSymbol.js → cjs/UtilSymbol.js} +0 -1
  9. package/dist/mjs/QuickExport.mjs +35 -0
  10. package/dist/mjs/UtilClass/Hbs.mjs +51 -0
  11. package/dist/mjs/UtilClass/index.mjs +3 -0
  12. package/dist/mjs/UtilCodecs.mjs +109 -0
  13. package/dist/mjs/UtilDecorators.mjs +2 -0
  14. package/dist/mjs/UtilFP.mjs +2 -0
  15. package/dist/mjs/UtilFileTools.mjs +407 -0
  16. package/dist/mjs/UtilFunctions.mjs +138 -0
  17. package/dist/mjs/UtilHttp.mjs +475 -0
  18. package/dist/mjs/UtilI18n.mjs +206 -0
  19. package/dist/mjs/UtilInterfaces.mjs +2 -0
  20. package/dist/mjs/UtilLogger.mjs +361 -0
  21. package/dist/mjs/UtilSymbol.mjs +2 -0
  22. package/dist/mjs/index.mjs +17 -0
  23. package/dist/{QuickExport.d.ts → types/QuickExport.d.ts} +1 -1
  24. package/dist/{UtilClass → types/UtilClass}/Hbs.d.ts +6 -3
  25. package/dist/types/UtilClass/index.d.ts +3 -0
  26. package/dist/{UtilCodecs.d.ts → types/UtilCodecs.d.ts} +6 -6
  27. package/dist/types/UtilDecorators.d.ts +2 -0
  28. package/dist/{UtilFileTools.d.ts → types/UtilFileTools.d.ts} +34 -3
  29. package/dist/{UtilFunctions.d.ts → types/UtilFunctions.d.ts} +9 -7
  30. package/dist/types/UtilInterfaces.d.ts +1 -0
  31. package/dist/types/UtilSymbol.d.ts +2 -0
  32. package/package.json +8 -2
  33. package/dist/UtilClass/index.d.ts +0 -2
  34. package/dist/UtilDecorators.d.ts +0 -1
  35. package/dist/UtilInterfaces.d.ts +0 -1
  36. package/dist/UtilSymbol.d.ts +0 -1
  37. /package/dist/{UtilFP.js → cjs/UtilFP.js} +0 -0
  38. /package/dist/{UtilHttp.js → cjs/UtilHttp.js} +0 -0
  39. /package/dist/{UtilI18n.js → cjs/UtilI18n.js} +0 -0
  40. /package/dist/{UtilInterfaces.js → cjs/UtilInterfaces.js} +0 -0
  41. /package/dist/{UtilLogger.js → cjs/UtilLogger.js} +0 -0
  42. /package/dist/{index.js → cjs/index.js} +0 -0
  43. /package/dist/{UtilFP.d.ts → types/UtilFP.d.ts} +0 -0
  44. /package/dist/{UtilHttp.d.ts → types/UtilHttp.d.ts} +0 -0
  45. /package/dist/{UtilI18n.d.ts → types/UtilI18n.d.ts} +0 -0
  46. /package/dist/{UtilLogger.d.ts → types/UtilLogger.d.ts} +0 -0
  47. /package/dist/{index.d.ts → types/index.d.ts} +0 -0
@@ -0,0 +1,361 @@
1
+ import path from 'pathe';
2
+ import * as winston from 'winston';
3
+ import DailyRotateFile from 'winston-daily-rotate-file';
4
+ import { inspect } from 'util';
5
+ const logLevels = {
6
+ fatal: 0,
7
+ error: 1,
8
+ warn: 2,
9
+ info: 3,
10
+ http: 4,
11
+ verbose: 5,
12
+ debug: 6,
13
+ silly: 7
14
+ };
15
+ const colorizer = winston.format.colorize();
16
+ colorizer.addColors({
17
+ fatal: 'bold yellow redBG',
18
+ error: 'bold yellow',
19
+ warn: 'yellow',
20
+ info: 'white',
21
+ debug: 'bold cyan',
22
+ silly: 'bold magenta'
23
+ });
24
+ export class SLogger {
25
+ /**获取一个Logger,如不存在则用默认参数创建
26
+ * @param name - logger的名称 默认default
27
+ * @returns 获取的logger
28
+ */
29
+ static getLogger(name = "default") {
30
+ let out = SLogger.loggerTable[name];
31
+ if (out == null) {
32
+ SLogger.createLogger(name);
33
+ out = SLogger.loggerTable[name];
34
+ }
35
+ return out;
36
+ }
37
+ /**创建Logger
38
+ * @param name - logger的名称 默认default
39
+ * @param consoleLevel - 输出到控制台的最低等级 默认info
40
+ * @param outFloder - log的输出文件夹路径 如./log/
41
+ * @param fileLevel - 输出到文件的最低等级 默认info
42
+ * @returns 创建完成的logger
43
+ */
44
+ static createLogger(name = "default", consoleLevel = "info", outFloder, fileLevel = "info") {
45
+ const transports = [];
46
+ if (outFloder != null) {
47
+ const fileFormat = winston.format.combine(winston.format.timestamp({ format: 'HH:mm:ss' }), winston.format.printf((info) => {
48
+ const level = info.level.toUpperCase();
49
+ const message = info.message;
50
+ //格式化
51
+ //let format = `[${info.timestamp}] [${level}]: `
52
+ //let space = " ".repeat(format.length);
53
+ const messageList = message.split("\n");
54
+ return `[${info.timestamp}] [${level.toUpperCase()}]: ${messageList.join("\n")}`;
55
+ }));
56
+ transports.push(new DailyRotateFile({
57
+ filename: path.join(outFloder, 'log-%DATE%.txt'),
58
+ datePattern: 'YYYY-MM-DD',
59
+ level: fileLevel,
60
+ format: fileFormat,
61
+ }));
62
+ }
63
+ const consoleFormat = winston.format.combine(winston.format.timestamp({ format: 'HH:mm:ss' }), winston.format.printf((info) => {
64
+ const level = info.level.toUpperCase();
65
+ const message = info.message;
66
+ const colorizedLevel = colorizer.colorize(info.level, level);
67
+ //格式化
68
+ //let format = `[${info.timestamp}] [${level}]: `
69
+ //let space = " ".repeat(format.length);
70
+ let messageList = message.split("\n");
71
+ messageList[0] = colorizer.colorize(info.level, messageList[0]);
72
+ for (let i = 1; i < messageList.length; i++)
73
+ messageList[i] = colorizer.colorize(info.level, messageList[i]);
74
+ let formattedMessage = messageList.join("\n");
75
+ const prefix = `[${info.timestamp}] [${colorizedLevel}]: `;
76
+ if (formattedMessage.startsWith(prefix))
77
+ formattedMessage = formattedMessage.slice(prefix.length);
78
+ return `${prefix}${formattedMessage}`;
79
+ //return `[${info.timestamp}] [${colorizedLevel}]: ${messageList.join("\n")}`;
80
+ }));
81
+ transports.push(new winston.transports.Console({
82
+ level: consoleLevel,
83
+ format: consoleFormat,
84
+ }));
85
+ const logger = winston.createLogger({
86
+ levels: logLevels,
87
+ transports: transports,
88
+ });
89
+ const out = new SLogger();
90
+ out._logger = logger;
91
+ if (SLogger.loggerTable[name] != null) {
92
+ let old = SLogger.loggerTable[name];
93
+ old._logger.transports.forEach(tp => {
94
+ if (tp.close != null)
95
+ tp.close();
96
+ });
97
+ }
98
+ SLogger.loggerTable[name] = out;
99
+ return out;
100
+ }
101
+ constructor() { }
102
+ _logger = null;
103
+ /**记录Logger的表 */
104
+ static loggerTable = {};
105
+ /**记录Logger的表 */
106
+ static timeTable = {};
107
+ //———————————————————— function ——————————————————————//
108
+ /**产生一条对应等级的log 返回自身
109
+ * @param level - log等级
110
+ * @param messages - log消息
111
+ * @returns 自身
112
+ */
113
+ log(level, ...messages) {
114
+ level ??= "silly";
115
+ const strMessages = [];
116
+ //上一条是字符串字符串
117
+ let preIsString = true;
118
+ for (let message of messages) {
119
+ let out;
120
+ //非string类型
121
+ if (typeof message !== "string") {
122
+ out = `<${typeof message}> ${inspect(message)}`;
123
+ preIsString = false;
124
+ }
125
+ else if (!preIsString) {
126
+ //如果上一条不是字符串则需要添加<string>类型标记
127
+ out = `<${typeof message}> ${inspect(message)}`;
128
+ preIsString = true;
129
+ }
130
+ else {
131
+ out = message;
132
+ }
133
+ strMessages.push(out);
134
+ }
135
+ const outMessage = strMessages.join("\n");
136
+ this._logger.log(level, outMessage);
137
+ return this;
138
+ }
139
+ /**产生一条fatal等级的log 返回自身
140
+ * @param messages - log消息
141
+ * @returns 自身
142
+ */
143
+ fatal(...messages) {
144
+ return this.log("fatal", ...messages);
145
+ ;
146
+ }
147
+ /**产生一条error等级的log 返回自身
148
+ * @param messages - log消息
149
+ * @returns 自身
150
+ */
151
+ error(...messages) {
152
+ return this.log("error", ...messages);
153
+ ;
154
+ }
155
+ /**产生一条warn等级的log 返回自身
156
+ * @param messages - log消息
157
+ * @returns 自身
158
+ */
159
+ warn(...messages) {
160
+ return this.log("warn", ...messages);
161
+ ;
162
+ }
163
+ /**产生一条info等级的log 返回自身
164
+ * @param messages - log消息
165
+ * @returns 自身
166
+ */
167
+ info(...messages) {
168
+ return this.log("info", ...messages);
169
+ }
170
+ /**产生一条http等级的log 返回自身
171
+ * @param messages - log消息
172
+ * @returns 自身
173
+ */
174
+ http(...messages) {
175
+ return this.log("http", ...messages);
176
+ }
177
+ /**产生一条verbose等级的log 返回自身
178
+ * @param messages - log消息
179
+ * @returns 自身
180
+ */
181
+ verbose(...messages) {
182
+ return this.log("verbose", ...messages);
183
+ }
184
+ /**产生一条debug等级的log 返回自身
185
+ * @param messages - log消息
186
+ * @returns 自身
187
+ */
188
+ debug(...messages) {
189
+ return this.log("debug", ...messages);
190
+ }
191
+ /**产生一条silly等级的log 返回自身
192
+ * @param messages - log消息
193
+ * @returns 自身
194
+ */
195
+ silly(...messages) {
196
+ return this.log("silly", ...messages);
197
+ }
198
+ /**记录当前时间戳并存入表
199
+ * @param flag - 记录的命名
200
+ * @returns 记录的时间
201
+ */
202
+ time(flag) {
203
+ let hrtime = process.hrtime();
204
+ SLogger.timeTable[flag] = hrtime;
205
+ return hrtime;
206
+ }
207
+ /**根据之前记录的时间戳计算经过的时间 并输出log
208
+ * @param flag - 记录的命名
209
+ * @param level - log等级 === null时不产生log
210
+ * @returns 格式化的时间字符串
211
+ */
212
+ timeEnd(flag, level = "info") {
213
+ const start = SLogger.timeTable[flag];
214
+ if (start == null) {
215
+ this.warn("SLogger.timeEnd 错误 flag:" + flag + " 不存在");
216
+ return;
217
+ }
218
+ const timelen = process.hrtime(start);
219
+ const totalMicroseconds = (timelen[0] * 1e9 + timelen[1]) / 1000;
220
+ const microseconds = totalMicroseconds % 1000;
221
+ const totalMilliseconds = totalMicroseconds / 1000;
222
+ const milliseconds = Math.floor(totalMilliseconds % 1000);
223
+ const totalSeconds = totalMilliseconds / 1000;
224
+ const seconds = Math.floor(totalSeconds % 60);
225
+ const totalMinutes = totalSeconds / 60;
226
+ const minutes = Math.floor(totalMinutes % 60);
227
+ const totalHours = totalMinutes / 60;
228
+ const hours = Math.floor(totalHours % 24);
229
+ const totalDay = totalHours / 24;
230
+ const Days = Math.floor(totalDay);
231
+ let out = '';
232
+ if (totalSeconds > 60) {
233
+ let result = '';
234
+ let format = '';
235
+ let acc = 0;
236
+ const maxAcc = 3;
237
+ const concat = (num, sep, formatText, resultText) => {
238
+ const hasResult = result.length > 0;
239
+ const need = (hasResult || num > 0) && (acc < maxAcc);
240
+ if (!need)
241
+ return;
242
+ if (result.length > 0)
243
+ result += sep;
244
+ if (format.length > 0)
245
+ format += sep;
246
+ result += resultText;
247
+ format += formatText;
248
+ acc++;
249
+ };
250
+ concat(Days, ':', 'dd', `${Days.toString()}`);
251
+ concat(hours, ':', 'HH', `${hours.toString().padStart(2, '0')}`);
252
+ concat(minutes, ':', 'mm', `${minutes.toString().padStart(2, '0')}`);
253
+ concat(seconds, ':', 'ss', `${seconds.toString().padStart(2, '0')}`);
254
+ concat(milliseconds, '.', 'mmm', `${milliseconds.toString().padStart(3, '0')}`);
255
+ //result = result.replace(/^(0(?![^0-9]))+/, '');
256
+ result = result.replace(/^0+([0-9])/, "$1");
257
+ out = `${result} (${format})`;
258
+ }
259
+ else if (totalMilliseconds > 1000) {
260
+ out = `${totalSeconds.toFixed(3)}s`;
261
+ }
262
+ else {
263
+ out = `${totalMilliseconds.toFixed(3)}ms`;
264
+ }
265
+ if (level !== null)
266
+ this.log(level, `${flag}: ${out}`);
267
+ delete SLogger.timeTable[flag];
268
+ return out;
269
+ }
270
+ //———————————————————— static ——————————————————————//
271
+ /**名称为default的slogger实例 */
272
+ static get defaultInstance() {
273
+ if (SLogger.loggerTable.default == null)
274
+ SLogger.createLogger();
275
+ return SLogger.loggerTable.default;
276
+ }
277
+ /**让名称为default的logger 产生一条对应等级的log 返回自身
278
+ * @param level - log等级
279
+ * @param messages - log消息
280
+ * @returns 自身
281
+ */
282
+ static log(level, ...messages) {
283
+ level = level ?? "silly";
284
+ this.defaultInstance.log(level, ...messages);
285
+ return this.defaultInstance;
286
+ }
287
+ /**让名称为default的logger 产生一条fatal等级的log 返回自身
288
+ * @param messages - log消息
289
+ * @returns 自身
290
+ */
291
+ static fatal(...messages) {
292
+ return this.log("fatal", ...messages);
293
+ ;
294
+ }
295
+ /**让名称为default的logger 产生一条error等级的log 返回自身
296
+ * @param messages - log消息
297
+ * @returns 自身
298
+ */
299
+ static error(...messages) {
300
+ return this.log("error", ...messages);
301
+ ;
302
+ }
303
+ /**让名称为default的logger 产生一条warn等级的log 返回自身
304
+ * @param messages - log消息
305
+ * @returns 自身
306
+ */
307
+ static warn(...messages) {
308
+ return this.log("warn", ...messages);
309
+ ;
310
+ }
311
+ /**让名称为default的logger 产生一条info等级的log 返回自身
312
+ * @param messages - log消息
313
+ * @returns 自身
314
+ */
315
+ static info(...messages) {
316
+ return this.log("info", ...messages);
317
+ }
318
+ /**让名称为default的logger 产生一条http等级的log 返回自身
319
+ * @param messages - log消息
320
+ * @returns 自身
321
+ */
322
+ static http(...messages) {
323
+ return this.log("http", ...messages);
324
+ }
325
+ /**让名称为default的logger 产生一条verbose等级的log 返回自身
326
+ * @param messages - log消息
327
+ * @returns 自身
328
+ */
329
+ static verbose(...messages) {
330
+ return this.log("verbose", ...messages);
331
+ }
332
+ /**让名称为default的logger 产生一条debug等级的log 返回自身
333
+ * @param messages - log消息
334
+ * @returns 自身
335
+ */
336
+ static debug(...messages) {
337
+ return this.log("debug", ...messages);
338
+ }
339
+ /**让名称为default的logger 产生一条silly等级的log 返回自身
340
+ * @param messages - log消息
341
+ * @returns 自身
342
+ */
343
+ static silly(...messages) {
344
+ return this.log("silly", ...messages);
345
+ }
346
+ /**让名称为default的logger 记录当前时间戳并存入表
347
+ * @param flag - 记录的命名
348
+ * @returns 记录的时间
349
+ */
350
+ static time(flag) {
351
+ return this.defaultInstance.time(flag);
352
+ }
353
+ /**让名称为default的logger 根据之前记录的时间戳计算经过的时间 并输出log
354
+ * @param flag - 记录的命名
355
+ * @param level - log等级
356
+ * @returns
357
+ */
358
+ static timeEnd(flag, level = "info") {
359
+ this.defaultInstance.timeEnd(flag, level);
360
+ }
361
+ }
@@ -0,0 +1,2 @@
1
+ export { Success, Failed, None, Uninited, Completed, Terminated, Timeout, NoneOut } from "@zwa73/js-utils";
2
+ //#endregion
@@ -0,0 +1,17 @@
1
+ import { SLogger } from './UtilLogger.mjs';
2
+ import { JsDepInjector } from '@zwa73/js-utils';
3
+ import * as crypto from "crypto";
4
+ JsDepInjector.inject('logger', SLogger);
5
+ JsDepInjector.inject('genUUID', () => crypto.randomBytes(16).toString("hex"));
6
+ export * from './UtilFunctions.mjs';
7
+ export * from './UtilInterfaces.mjs';
8
+ export * from './UtilSymbol.mjs';
9
+ export * from './UtilClass/index.mjs';
10
+ export * from './UtilHttp.mjs';
11
+ export * from './UtilCodecs.mjs';
12
+ export * from './UtilDecorators.mjs';
13
+ export * from './UtilFileTools.mjs';
14
+ export * from './UtilLogger.mjs';
15
+ export * from './UtilFP.mjs';
16
+ export * from './QuickExport.mjs';
17
+ export * from './UtilI18n.mjs';
@@ -1,4 +1,4 @@
1
1
  import { UtilFT } from "./UtilFileTools";
2
- export declare const outcome: typeof import("@zwa73/js-utils").JsFunc.outcome, success: typeof import("@zwa73/js-utils").JsFunc.success, failed: typeof import("@zwa73/js-utils").JsFunc.failed, match: typeof import("@zwa73/js-utils").JsFunc.match, isSafeNumber: typeof import("@zwa73/js-utils").JsFunc.isSafeNumber, assertType: typeof import("@zwa73/js-utils").JsFunc.assertType, assertLiteral: typeof import("@zwa73/js-utils").JsFunc.assertLiteral, deepClone: typeof import("@zwa73/js-utils").JsFunc.deepClone, sleep: typeof import("@zwa73/js-utils").JsFunc.sleep, stringifyJToken: typeof import("@zwa73/js-utils").JsFunc.stringifyJToken, getTime: typeof import("@zwa73/js-utils").JsFunc.getTime, mapEntries: typeof import("@zwa73/js-utils").JsFunc.mapEntries, dedent: typeof import("@zwa73/js-utils").JsFunc.dedent, throwError: typeof import("@zwa73/js-utils").JsFunc.throwError, eitherize: typeof import("@zwa73/js-utils").JsFunc.eitherize, memoize: typeof import("@zwa73/js-utils").JsFunc.memoize, ivk: typeof import("@zwa73/js-utils").JsFunc.ivk, l2s: typeof import("@zwa73/js-utils").JsFunc.l2s, s2l: typeof import("@zwa73/js-utils").JsFunc.s2l;
2
+ export declare const outcome: typeof import("@zwa73/js-utils").JsFunc.outcome, success: typeof import("@zwa73/js-utils").JsFunc.success, failed: typeof import("@zwa73/js-utils").JsFunc.failed, match: typeof import("@zwa73/js-utils").JsFunc.match, isSafeNumber: typeof import("@zwa73/js-utils").JsFunc.isSafeNumber, assertType: typeof import("@zwa73/js-utils").JsFunc.assertType, assertLiteral: typeof import("@zwa73/js-utils").JsFunc.assertLiteral, deepClone: typeof import("@zwa73/js-utils").JsFunc.deepClone, sleep: typeof import("@zwa73/js-utils").JsFunc.sleep, stringifyJToken: typeof import("@zwa73/js-utils").JsFunc.stringifyJToken, getTime: typeof import("@zwa73/js-utils").JsFunc.getTime, mapEntries: typeof import("@zwa73/js-utils").JsFunc.mapEntries, dedent: typeof import("@zwa73/js-utils").JsFunc.dedent, throwError: typeof import("@zwa73/js-utils").JsFunc.throwError, eitherize: typeof import("@zwa73/js-utils").JsFunc.eitherize, memoize: typeof import("@zwa73/js-utils").JsFunc.memoize, ivk: typeof import("@zwa73/js-utils").JsFunc.ivk, l2s: typeof import("@zwa73/js-utils").JsFunc.l2s, s2l: typeof import("@zwa73/js-utils").JsFunc.s2l, structEqual: typeof import("@zwa73/js-utils").JsFunc.structEqual;
3
3
  export declare const stylizePath: typeof UtilFT.stylizePath, posixizePath: typeof UtilFT.posixizePath, win32izePath: typeof UtilFT.win32izePath, currosizePath: typeof UtilFT.currosizePath;
4
4
  export declare const when: <S extends import("@zwa73/js-utils").Keyable, T, R>(stat: import("@zwa73/js-utils").Literal<S>, f: (arg: Extract<T, import("@zwa73/js-utils").Matchable<S>>) => R) => (arg: T) => ("E" extends import("@zwa73/js-utils").ProperSubsetCheck<symbol, T> ? T | R : import("@zwa73/js-utils").MatchableFlag<T> extends S ? R : import("@zwa73/js-utils").MatchableFlag<T> extends Exclude<S, import("@zwa73/js-utils").MatchableFlag<T>> ? T : Exclude<T, import("@zwa73/js-utils").Matchable<S>> | R), map: typeof import("@zwa73/js-utils").JsFP.map, flow: typeof import("@zwa73/js-utils").JsFP.flow, pipe: typeof import("@zwa73/js-utils").JsFP.pipe, chain: <T, R>(f: (arg: Extract<T, import("@zwa73/js-utils").Matchable<typeof import("@zwa73/js-utils").Success>>) => R) => (arg: T) => ("E" extends import("@zwa73/js-utils").ProperSubsetCheck<symbol, T> ? T | R : import("@zwa73/js-utils").MatchableFlag<T> extends typeof import("@zwa73/js-utils").Success ? R : import("@zwa73/js-utils").MatchableFlag<T> extends Exclude<typeof import("@zwa73/js-utils").Success, import("@zwa73/js-utils").MatchableFlag<T>> ? T : Exclude<T, import("@zwa73/js-utils").Matchable<typeof import("@zwa73/js-utils").Success>> | R), alt: <T, R>(f: (arg: Extract<T, import("@zwa73/js-utils").Matchable<typeof import("@zwa73/js-utils").Failed>>) => R) => (arg: T) => ("E" extends import("@zwa73/js-utils").ProperSubsetCheck<symbol, T> ? T | R : import("@zwa73/js-utils").MatchableFlag<T> extends typeof import("@zwa73/js-utils").Failed ? R : import("@zwa73/js-utils").MatchableFlag<T> extends Exclude<typeof import("@zwa73/js-utils").Failed, import("@zwa73/js-utils").MatchableFlag<T>> ? T : Exclude<T, import("@zwa73/js-utils").Matchable<typeof import("@zwa73/js-utils").Failed>> | R), tap: typeof import("@zwa73/js-utils").JsFP.tap, curry: typeof import("@zwa73/js-utils").JsFP.curry;
@@ -1,15 +1,18 @@
1
1
  import { Keyable } from '@zwa73/js-utils';
2
- import Handlebars from 'handlebars';
3
2
  /**文本模板渲染器
4
3
  * @template T - 上下文对象的类型,默认为记录类型
5
4
  */
6
5
  export declare class Hbs<T extends Record<Keyable, any> = Record<Keyable, any>> {
7
- hbs: typeof Handlebars;
6
+ private hbs;
8
7
  context: T;
9
8
  /**创建一个新的 Hbs 实例
10
9
  * @param context - 上下文对象,用于在渲染模板时提供数据
11
10
  */
12
- constructor(context?: T);
11
+ private constructor();
12
+ /**创建一个新的 Hbs 实例
13
+ * @param context - 上下文对象,用于在渲染模板时提供数据
14
+ */
15
+ static create<T extends Record<Keyable, any> = Record<Keyable, any>>(context?: T): Promise<Hbs<T>>;
13
16
  /**渲染模板
14
17
  * @param template - 要渲染的 Handlebars 模板字符串
15
18
  * @returns 渲染后的字符串
@@ -0,0 +1,3 @@
1
+ export * from './Hbs';
2
+ export type { BridgeInterface, DListMiddleNode, DListHeadNode, DListTailNode, DListNode, DListMaybeNode, PromoseQueueOption } from "@zwa73/js-utils";
3
+ export { Bridge, DLinkedList, Piper, PromiseQueue, SmartCache, Stream } from "@zwa73/js-utils";
@@ -14,30 +14,30 @@ export declare namespace UtilCodec {
14
14
  * @param str = 所要计算的消息
15
15
  * @returns 整数长度结果
16
16
  */
17
- function tokenNumTurbo(str: string): number;
17
+ function tokenNumTurbo(str: string): Promise<number>;
18
18
  /**token长度计算器 Davinci模型
19
19
  * @param str = 所要计算的消息
20
20
  * @returns 整数长度结果
21
21
  */
22
- function tokenNumDavinci(str: string): number;
22
+ function tokenNumDavinci(str: string): Promise<number>;
23
23
  /**token编码 Turbo模型
24
24
  * @param str = 所要计算的消息
25
25
  * @returns Token数组
26
26
  */
27
- function encodeTokenTurbo(str: string): Uint32Array;
27
+ function encodeTokenTurbo(str: string): Promise<Uint32Array>;
28
28
  /**token编码 Davinci模型
29
29
  * @param str = 所要计算的消息
30
30
  * @returns Token数组
31
31
  */
32
- function encodeTokenDavinci(str: string): Uint32Array;
32
+ function encodeTokenDavinci(str: string): Promise<Uint32Array>;
33
33
  /**token解码 Turbo模型
34
34
  * @param arr = Token数组
35
35
  * @returns 消息字符串
36
36
  */
37
- function decodeTokenTurbo(arr: Uint32Array | number[]): string;
37
+ function decodeTokenTurbo(arr: Uint32Array | number[]): Promise<string>;
38
38
  /**token解码 Davinci模型
39
39
  * @param arr = Token数组
40
40
  * @returns 消息字符串
41
41
  */
42
- function decodeTokenDavinci(arr: Uint32Array | number[]): string;
42
+ function decodeTokenDavinci(arr: Uint32Array | number[]): Promise<string>;
43
43
  }
@@ -0,0 +1,2 @@
1
+ export type { ParamsDecoratorsGener, BaseDecoratorsGener, LogTraceOpt, PostProcessOpt } from "@zwa73/js-utils";
2
+ export { LogTrace, PostProcess, AwaitInited } from "@zwa73/js-utils";
@@ -1,4 +1,5 @@
1
1
  import { JToken } from "./UtilInterfaces";
2
+ import { HashAlgorithm } from "./UtilFunctions";
2
3
  /**创建文件选项 */
3
4
  type CreatePathOpt = Partial<{
4
5
  /**创建一个目录 默认 false
@@ -17,6 +18,10 @@ type EnsurePathExistsOpt = Partial<{
17
18
  type FileSearchGlobOpt = Partial<{
18
19
  /**忽略的文件 默认 undefined */
19
20
  ingore: string | string[];
21
+ /**忽略目录 默认 true */
22
+ nodir: boolean;
23
+ /**忽略大小写 默认 跟随系统 mac/win为true 其他false */
24
+ nocese: boolean;
20
25
  }>;
21
26
  /**regex搜索选项 */
22
27
  type FileSearchRegexOpt = Partial<{
@@ -24,6 +29,8 @@ type FileSearchRegexOpt = Partial<{
24
29
  recursive: boolean;
25
30
  /**无效项 */
26
31
  relative: never;
32
+ /**忽略目录 默认 true */
33
+ nodir: boolean;
27
34
  }>;
28
35
  /**json文件加载选项 */
29
36
  type LoadJsonFileOpt<T> = Partial<{
@@ -149,8 +156,10 @@ export declare namespace UtilFT {
149
156
  function currosizePath(filePath: string): string;
150
157
  /**逐级寻找node_modules文件夹
151
158
  * @param basePath - 基础位置
159
+ * @param extpaths - 额外的路径 如 .bin
160
+ * @returns node_modules文件夹路径 包含额外路径
152
161
  */
153
- function findNodeModulesDir(basePath: string): Promise<string | undefined>;
162
+ function findNodeModulesDir(basePath: string, ...extpaths: string[]): Promise<string | undefined>;
154
163
  /**搜索路径符合正则表达式的文件
155
164
  * @param dir - 起始目录
156
165
  * @param traitRegex - 正则表达式
@@ -171,7 +180,9 @@ export declare namespace UtilFT {
171
180
  * @param dir - 起始目录
172
181
  * @param globPattern - glob匹配
173
182
  * @param opt - 可选参数
174
- * @param opt.ignore - 忽略的文件
183
+ * @param opt.ignore - 忽略的文件
184
+ * @param opt.relative - 忽略目录 默认 true
185
+ * @param opt.nodir - 忽略大小写 默认 跟随系统 mac/win为true 其他false
175
186
  * @returns 文件绝对路径数组
176
187
  */
177
188
  function fileSearchGlob(dir: string, globPattern: string | string[], opt?: FileSearchGlobOpt): Promise<string[]>;
@@ -179,7 +190,9 @@ export declare namespace UtilFT {
179
190
  * @param dir - 起始目录
180
191
  * @param globPattern - glob匹配
181
192
  * @param opt - 可选参数
182
- * @param opt.ignore - 忽略的文件
193
+ * @param opt.ignore - 忽略的文件
194
+ * @param opt.relative - 忽略目录 默认 true
195
+ * @param opt.nodir - 忽略大小写 默认 跟随系统 mac/win为true 其他false
183
196
  * @returns 文件绝对路径数组
184
197
  */
185
198
  function fileSearchGlobSync(dir: string, globPattern: string | string[], opt?: FileSearchGlobOpt): string[];
@@ -187,5 +200,23 @@ export declare namespace UtilFT {
187
200
  * @param filePath - 需要验证的文件路径
188
201
  */
189
202
  function isValidFilePath(filePath: string): boolean;
203
+ /**计算文件的部分md5
204
+ * @param filePath - 目标文件路径
205
+ * @param opt - 可选参数
206
+ * @param opt.algorithm - hash算法 默认md5
207
+ * @param opt.sampled - 抽取部分计算 默认false
208
+ * @param opt.chunkSize - 抽取的块大小 默认1024
209
+ * @param opt.chunkCount - 抽取的块的数量 默认10
210
+ */
211
+ function calculateHash(filePath: string, opt?: {
212
+ /**hash算法 默认md5 */
213
+ algorithm?: HashAlgorithm;
214
+ /**抽取部分计算 默认false */
215
+ sampled?: boolean;
216
+ /**抽取的块大小 默认1024 */
217
+ chunkSize?: number;
218
+ /**抽取的块的数量 默认10 */
219
+ chunkCount?: number;
220
+ }): Promise<string>;
190
221
  }
191
222
  export {};
@@ -1,9 +1,8 @@
1
1
  import { LogLevel } from "./UtilInterfaces";
2
2
  import { JsFunc } from "@zwa73/js-utils";
3
- import { ComposedClass } from "@zwa73/modular-mixer";
4
- export { PromiseRetries, PromiseRetryResult } from "@zwa73/js-utils";
5
- declare const HashMethodList: readonly ["md5", "sha1", "sha256", "sha512", "sha3", "blake2", "blake3"];
6
- type HashMethod = typeof HashMethodList[number];
3
+ export type { PromiseRetries, PromiseRetryResult } from "@zwa73/js-utils";
4
+ declare const HashAlgorithmList: readonly ["RSA-MD5", "RSA-RIPEMD160", "RSA-SHA1", "RSA-SHA1-2", "RSA-SHA224", "RSA-SHA256", "RSA-SHA3-224", "RSA-SHA3-256", "RSA-SHA3-384", "RSA-SHA3-512", "RSA-SHA384", "RSA-SHA512", "RSA-SHA512/224", "RSA-SHA512/256", "RSA-SM3", "blake2b512", "blake2s256", "id-rsassa-pkcs1-v1_5-with-sha3-224", "id-rsassa-pkcs1-v1_5-with-sha3-256", "id-rsassa-pkcs1-v1_5-with-sha3-384", "id-rsassa-pkcs1-v1_5-with-sha3-512", "md5", "md5-sha1", "md5WithRSAEncryption", "ripemd", "ripemd160", "ripemd160WithRSA", "rmd160", "sha1", "sha1WithRSAEncryption", "sha224", "sha224WithRSAEncryption", "sha256", "sha256WithRSAEncryption", "sha3-224", "sha3-256", "sha3-384", "sha3-512", "sha384", "sha384WithRSAEncryption", "sha512", "sha512-224", "sha512-224WithRSAEncryption", "sha512-256", "sha512-256WithRSAEncryption", "sha512WithRSAEncryption", "shake128", "shake256", "sm3", "sm3WithRSAEncryption", "ssl3-md5", "ssl3-sha1"];
5
+ export type HashAlgorithm = typeof HashAlgorithmList[number];
7
6
  /**执行选项 */
8
7
  type ExecOpt = Partial<{
9
8
  outlvl: LogLevel;
@@ -20,7 +19,10 @@ declare class _UtilFunc {
20
19
  * @param method - hash算法
21
20
  * @returns hash
22
21
  */
23
- static calcHash(str: string, method?: HashMethod): string;
22
+ static calcHash(str: string, opt?: {
23
+ /**hash算法 默认md5 */
24
+ algorithm?: HashAlgorithm;
25
+ }): string;
24
26
  /**是否需要检查环境 */
25
27
  private static checkEnv;
26
28
  /**是否有正在运行的exec */
@@ -56,7 +58,7 @@ declare class _UtilFunc {
56
58
  *
57
59
  * @since Node.js 13.2,Node.js开始支持动态import。
58
60
  */
59
- static dynamicImport(moduleName: string): Promise<any>;
61
+ static dynamicImport<T = any>(moduleName: string): Promise<T>;
60
62
  }
61
- export declare const UtilFunc: ComposedClass<typeof _UtilFunc, typeof JsFunc, "__jsUtils", "match" | "failed" | "success" | "prototype" | "genUUID" | "range" | "getTime" | "initField" | "initObject" | "unifyApply" | "sleep" | "getNeverResolvedPromise" | "retryPromise" | "timelimitPromise" | "mapEntries" | "eachField" | "stringifyJToken" | "assertType" | "assertLiteral" | "deepClone" | "isSafeNumber" | "dedent" | "throwError" | "getFuncLoc" | "cachePool" | "memoize" | "asyncize" | "splitToChunk" | "mergeFromChunk" | "concurrencyProc" | "outcome" | "isStatus" | "eitherize" | "parseSrtTime" | "formatSrtTime" | "parseSrt" | "createSrt" | "ivk" | "s2l" | "l2s">;
63
+ export declare const UtilFunc: import("@zwa73/modular-mixer").ComposedClass<typeof _UtilFunc, typeof JsFunc, "__jsUtils", "match" | "failed" | "success" | "prototype" | "genUUID" | "range" | "getTime" | "initField" | "initObject" | "unifyApply" | "sleep" | "getNeverResolvedPromise" | "retryPromise" | "timelimitPromise" | "mapEntries" | "eachField" | "stringifyJToken" | "assertType" | "assertLiteral" | "deepClone" | "isSafeNumber" | "dedent" | "throwError" | "getFuncLoc" | "cachePool" | "memoize" | "asyncize" | "lazyize" | "splitToChunk" | "mergeFromChunk" | "structEqual" | "concurrent" | "outcome" | "isStatus" | "eitherize" | "parseSrtTime" | "formatSrtTime" | "parseSrt" | "createSrt" | "ivk" | "s2l" | "l2s">;
62
64
  export type UtilFunc = typeof UtilFunc;
@@ -0,0 +1 @@
1
+ export type { JToken, JValue, JArray, JObject, IJData, AnyFunc, Keyable, PartialOption, ProperSubset, ProperSubsetCheck, IncludeCheck, UnionCheck, Literal, LiteralCheck, AllExtends, AssignObject, Writeable, Inverted, FixedLengthTuple, Increment, RangeTuple, AnyString, UnionToIntersection, ExclusiveRecord, ExclusiveJObject, PromiseStatus, StatusVerifyFn, Await, FuncPropNames, ExtendThen, RequiredOnly, WithPrefix, Outcome, Either, Matchable, MatchableFlag, ExtractOutcome, ExtractMatchable, SchemaString, NeedInit, PRecord, MPromise, SPromise, SMPromise, NotPromise, AnyRecord, CmtTuple, Flasy, SrtSegment, ILogger, LogLevel, Asyncize } from "@zwa73/js-utils";
@@ -0,0 +1,2 @@
1
+ export type { FailedLike, SuccessLike, StatusSymbol } from "@zwa73/js-utils";
2
+ export { Success, Failed, None, Uninited, Completed, Terminated, Timeout, NoneOut } from "@zwa73/js-utils";
package/package.json CHANGED
@@ -1,8 +1,14 @@
1
1
  {
2
2
  "name": "@zwa73/utils",
3
- "version": "1.0.222",
3
+ "version": "1.0.224",
4
4
  "description": "my utils",
5
- "main": "index.js",
5
+ "exports": {
6
+ ".": {
7
+ "require": "./dist/cjs/index.js",
8
+ "import": "./dist/mjs/index.mjs",
9
+ "types": "./dist/types/index.d.ts"
10
+ }
11
+ },
6
12
  "scripts": {
7
13
  "test": "jest",
8
14
  "release": "powershell scripts/release",
@@ -1,2 +0,0 @@
1
- export * from './Hbs';
2
- export { BridgeInterface, Bridge, DListMiddleNode, DListHeadNode, DListTailNode, DListNode, DListMaybeNode, DLinkedList, Piper, PromoseQueueOption, PromiseQueue, SmartCache, Stream } from "@zwa73/js-utils";
@@ -1 +0,0 @@
1
- export { ParamsDecoratorsGener, BaseDecoratorsGener, LogTraceOpt, LogTrace, PostProcessOpt, PostProcess, AwaitInited } from "@zwa73/js-utils";
@@ -1 +0,0 @@
1
- export { JToken, JValue, JArray, JObject, IJData, AnyFunc, Keyable, PartialOption, ProperSubset, ProperSubsetCheck, IncludeCheck, UnionCheck, Literal, LiteralCheck, AllExtends, AssignObject, Writeable, Inverted, FixedLengthTuple, Increment, RangeTuple, AnyString, UnionToIntersection, ExclusiveRecord, ExclusiveJObject, PromiseStatus, StatusVerifyFn, Await, FuncPropNames, ExtendThen, RequiredOnly, WithPrefix, Outcome, Either, Matchable, MatchableFlag, ExtractOutcome, ExtractMatchable, SchemaString, NeedInit, PRecord, MPromise, SPromise, SMPromise, NotPromise, AnyRecord, CmtTuple, Flasy, SrtSegment, ILogger, LogLevel, Asyncize } from "@zwa73/js-utils";
@@ -1 +0,0 @@
1
- export { Success, Failed, None, Uninited, Completed, Terminated, Timeout, FailedLike, SuccessLike, StatusSymbol, NoneOut } from "@zwa73/js-utils";
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes