@zwa73/utils 1.0.278 → 1.0.279

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.
@@ -0,0 +1,9 @@
1
+ type ImportOptionPackOpt = {
2
+ /**包名 */
3
+ name: string;
4
+ /**安装指令提示 */
5
+ installTip: string;
6
+ };
7
+ /**导入可选包 */
8
+ export declare function importOptionPack<T>(opt: ImportOptionPackOpt): Promise<T>;
9
+ export {};
@@ -0,0 +1,12 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.importOptionPack = importOptionPack;
4
+ const UtilFunctions_1 = require("./UtilFunctions");
5
+ /**导入可选包 */
6
+ async function importOptionPack(opt) {
7
+ const { name, installTip } = opt;
8
+ const pack = await UtilFunctions_1.UtilFunc.dynamicImport(name);
9
+ if (pack == undefined)
10
+ UtilFunctions_1.UtilFunc.throwError(`npm包 ${name} 动态导入失败, 可能是未安装, 可使用 ${installTip} 安装`);
11
+ return pack;
12
+ }
@@ -1,8 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.Hbs = void 0;
4
- const js_utils_1 = require("@zwa73/js-utils");
5
- const UtilFunctions_1 = require("../UtilFunctions");
4
+ const Constant_1 = require("../Constant");
6
5
  const UtilLogger_1 = require("../UtilLogger");
7
6
  /**文本模板渲染器
8
7
  * @template T - 上下文对象的类型,默认为记录类型
@@ -35,9 +34,10 @@ class Hbs {
35
34
  * @param context - 上下文对象,用于在渲染模板时提供数据
36
35
  */
37
36
  static async create(context = {}) {
38
- const Handlebars = await js_utils_1.JsFunc.dynamicImport('handlebars');
39
- if (Handlebars == undefined)
40
- UtilFunctions_1.UtilFunc.throwError(`npm包 handlebars 动态导入失败, 此包不会随@zwa73/utils自动安装, 可能是未安装, 可使用 npm i handlebars@4.7.8 来安装`);
37
+ const Handlebars = await (0, Constant_1.importOptionPack)({
38
+ name: 'handlebars',
39
+ installTip: 'npm i handlebars@4.7.8'
40
+ });
41
41
  //console.log(Handlebars);
42
42
  const hbs = Handlebars.create();
43
43
  return new Hbs(hbs, context);
@@ -4,7 +4,13 @@ type ExtractBlockOpt = {
4
4
  /**要提取的标题 必须为 "# 标题" 的格式 */
5
5
  title: string;
6
6
  /**将标题从结构中排除 */
7
- trimTitle: boolean;
7
+ trimTitle?: boolean;
8
+ };
9
+ type ExtractCodeBlockOpt = {
10
+ /**要提取的标题 必须为 "# 标题" 的格式 */
11
+ title: string;
12
+ /**代码类型标记 为undefined时匹配任意 */
13
+ codetype?: string;
8
14
  };
9
15
  type FromArg = {
10
16
  data?: Record<string, any>;
@@ -40,5 +46,10 @@ export declare class Markdown<D extends Record<string, any> = Record<string, any
40
46
  * @param opt - 选项
41
47
  */
42
48
  extractJson(title: string): string | undefined;
49
+ /**根据标题提取块内第一个代码块
50
+ * @param title - 标题
51
+ * @param codetype - 代码类型
52
+ */
53
+ extractCodeBlock(opt: ExtractCodeBlockOpt): string | undefined;
43
54
  }
44
55
  export {};
@@ -5,21 +5,16 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.Markdown = void 0;
7
7
  const fs_1 = __importDefault(require("fs"));
8
- const js_utils_1 = require("@zwa73/js-utils");
9
- const UtilFunctions_1 = require("../UtilFunctions");
8
+ const Constant_1 = require("../Constant");
10
9
  const UtilLogger_1 = require("../UtilLogger");
11
- const getMatter = async () => {
12
- const matter = await js_utils_1.JsFunc.dynamicImport('gray-matter');
13
- if (matter == undefined)
14
- js_utils_1.JsFunc.throwError(`npm包 gray-matter 动态导入失败, 此包不会随@zwa73/utils自动安装, 可能是未安装, 可使用 npm i gray-matter@4.0.3 来安装`);
15
- return matter;
16
- };
17
- const getYaml = async () => {
18
- const yaml = await UtilFunctions_1.UtilFunc.dynamicImport('yaml');
19
- if (yaml == undefined)
20
- UtilFunctions_1.UtilFunc.throwError(`npm包 yaml 动态导入失败, 此包不会随@zwa73/utils自动安装, 可能是未安装, 可使用 npm i yaml@2.8.1 来安装`);
21
- return yaml;
22
- };
10
+ const getMatter = async () => await (0, Constant_1.importOptionPack)({
11
+ name: 'gray-matter',
12
+ installTip: 'npm i gray-matter@4.0.3'
13
+ });
14
+ const getYaml = async () => await (0, Constant_1.importOptionPack)({
15
+ name: 'yaml',
16
+ installTip: 'npm i yaml@2.8.1'
17
+ });
23
18
  /**Markdown解析器 */
24
19
  class Markdown {
25
20
  data;
@@ -105,7 +100,21 @@ class Markdown {
105
100
  * @param opt - 选项
106
101
  */
107
102
  extractJson(title) {
108
- return this.extractBlock({ title, trimTitle: true })?.trim().replace(/```json\n([\s\S]+)\n```/, '$1');
103
+ return this.extractCodeBlock({ title, codetype: 'json' });
104
+ }
105
+ /**根据标题提取块内第一个代码块
106
+ * @param title - 标题
107
+ * @param codetype - 代码类型
108
+ */
109
+ extractCodeBlock(opt) {
110
+ const { title, codetype } = opt;
111
+ const typePart = codetype !== undefined
112
+ ? codetype.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
113
+ : '.*';
114
+ return this.extractBlock({ title, trimTitle: true })?.trim().replace(new RegExp("```" +
115
+ typePart +
116
+ "\\n([\\s\\S]+?)\\n" +
117
+ "```"), '$1');
109
118
  }
110
119
  }
111
120
  exports.Markdown = Markdown;
@@ -0,0 +1,52 @@
1
+ import type { MPromise } from '@zwa73/js-utils';
2
+ import { Markdown } from "./Markdown";
3
+ type ScanOpt = {
4
+ /**glob匹配符 默认 **\/info.md */
5
+ pattern?: string;
6
+ /**根目录 */
7
+ rootPath: string;
8
+ /**json代码块标题 如果提供 则会尝试解析对应代码对象
9
+ * 可以同时与 tomlTitle 使用, 最终结果会按顺序挑选第一个非空值
10
+ */
11
+ jsonTitle?: string;
12
+ /**toml代码块标题 如果提供 则会尝试解析对应代码对象
13
+ * 可以同时与 jsonTitle 使用, 最终结果会按顺序挑选第一个非空值
14
+ */
15
+ tomlTitle?: string;
16
+ };
17
+ type UpdateOpt = ScanOpt & {
18
+ updateFunc: (obj: ScanResult) => MPromise<{
19
+ content?: string;
20
+ data?: Record<string, any>;
21
+ }>;
22
+ /**markdown序列化参数 */
23
+ stringifyOpt?: Parameters<Awaited<ReturnType<typeof Markdown['parse']>>['stringify']>[0];
24
+ };
25
+ type ScanResult = {
26
+ /**info.md内容 */
27
+ content: string;
28
+ /**info.md所在目录的绝对路径 */
29
+ abspath: string;
30
+ /**info.md所在目录的相对路径 */
31
+ relpath: string;
32
+ /**info.md的绝对路径 */
33
+ infopath: string;
34
+ /**info.md解析后的Markdown对象 */
35
+ markdown: Markdown;
36
+ /**info.md中的代码类型 */
37
+ codetype: string;
38
+ /**info.md中的代码对象 */
39
+ codeobj: undefined | Record<string, any>;
40
+ };
41
+ export declare class ObsidianDepot {
42
+ /**将数组转为markdown列表文本 */
43
+ static toList(v?: string[]): string | undefined;
44
+ private constructor();
45
+ /**搜索info.md文件
46
+ * @param opt - 搜索选项
47
+ */
48
+ static scanMarkdown(opt: ScanOpt): Promise<ScanResult[]>;
49
+ /**搜索并更新info.md文件 */
50
+ static updateMarkdown(opt: UpdateOpt): Promise<void>;
51
+ }
52
+ export {};
@@ -0,0 +1,66 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.ObsidianDepot = void 0;
7
+ const fs_1 = __importDefault(require("fs"));
8
+ const js_utils_1 = require("@zwa73/js-utils");
9
+ const Constant_1 = require("../Constant");
10
+ const pathe_1 = __importDefault(require("pathe"));
11
+ const UtilFileTools_1 = require("../UtilFileTools");
12
+ const UtilFunctions_1 = require("../UtilFunctions");
13
+ const Markdown_1 = require("./Markdown");
14
+ class ObsidianDepot {
15
+ /**将数组转为markdown列表文本 */
16
+ static toList(v) {
17
+ return v?.map(vv => ` - ${vv.trim()}`).join('\n');
18
+ }
19
+ constructor() { }
20
+ /**搜索info.md文件
21
+ * @param opt - 搜索选项
22
+ */
23
+ static async scanMarkdown(opt) {
24
+ const { pattern = "**/info.md", rootPath, jsonTitle, tomlTitle, } = opt;
25
+ const infoList = await UtilFileTools_1.UtilFT.fileSearchGlob(rootPath, pattern);
26
+ return await Promise.all(infoList.map(async (v) => {
27
+ const { dir } = pathe_1.default.parse(v);
28
+ const content = await fs_1.default.promises.readFile(v, 'utf-8');
29
+ const markdown = await Markdown_1.Markdown.parse(content);
30
+ const codetype = (jsonTitle != undefined && markdown.extractBlock({ title: jsonTitle, trimTitle: true })) ? 'json'
31
+ : (tomlTitle != undefined && markdown.extractBlock({ title: tomlTitle, trimTitle: true })) ? 'toml'
32
+ : 'none';
33
+ const codeobj = await UtilFunctions_1.UtilFunc.match(codetype, {
34
+ json: () => JSON.parse(markdown.extractCodeBlock({ title: jsonTitle, codetype: 'json' }) ?? ''),
35
+ toml: async () => (await (0, Constant_1.importOptionPack)({
36
+ name: '@iarna/toml',
37
+ installTip: 'npm i @iarna/toml@2.2.5'
38
+ })).parse(markdown.extractCodeBlock({ title: tomlTitle, codetype: 'toml' }) ?? ''),
39
+ none: () => undefined
40
+ });
41
+ return {
42
+ content,
43
+ abspath: dir,
44
+ relpath: pathe_1.default.relative(rootPath, dir),
45
+ infopath: v,
46
+ markdown: await Markdown_1.Markdown.parse(content),
47
+ codetype,
48
+ codeobj,
49
+ };
50
+ }));
51
+ }
52
+ /**搜索并更新info.md文件 */
53
+ static async updateMarkdown(opt) {
54
+ const { stringifyOpt, updateFunc } = opt;
55
+ const scanResultList = await ObsidianDepot.scanMarkdown(opt);
56
+ await js_utils_1.Stream.from(scanResultList, 16).map(async (scanResult) => {
57
+ const { infopath } = scanResult;
58
+ const { content, data } = await updateFunc(scanResult);
59
+ await fs_1.default.promises.writeFile(infopath, await Markdown_1.Markdown.from({
60
+ data,
61
+ content
62
+ }).stringify(stringifyOpt));
63
+ }).apply();
64
+ }
65
+ }
66
+ exports.ObsidianDepot = ObsidianDepot;
@@ -1,4 +1,5 @@
1
1
  export * from './Hbs';
2
2
  export * from './Markdown';
3
+ export * from './ObsidianDepot';
3
4
  export type { EventData, DListMiddleNode, DListHeadNode, DListTailNode, DListInvalidNode, DListMaybeNode, DListNode, BridgeInterface } from "@zwa73/js-utils";
4
5
  export { Stream, Spool, SmartCache, SequenceQueue, PromiseQueue, Piper, EventSystem, DLinkedList, DelayQueue, Bridge } from "@zwa73/js-utils";
@@ -17,6 +17,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
17
17
  exports.Bridge = exports.DelayQueue = exports.DLinkedList = exports.EventSystem = exports.Piper = exports.PromiseQueue = exports.SequenceQueue = exports.SmartCache = exports.Spool = exports.Stream = void 0;
18
18
  __exportStar(require("./Hbs"), exports);
19
19
  __exportStar(require("./Markdown"), exports);
20
+ __exportStar(require("./ObsidianDepot"), exports);
20
21
  var js_utils_1 = require("@zwa73/js-utils");
21
22
  Object.defineProperty(exports, "Stream", { enumerable: true, get: function () { return js_utils_1.Stream; } });
22
23
  Object.defineProperty(exports, "Spool", { enumerable: true, get: function () { return js_utils_1.Spool; } });
@@ -24,16 +24,16 @@ var __importStar = (this && this.__importStar) || function (mod) {
24
24
  };
25
25
  Object.defineProperty(exports, "__esModule", { value: true });
26
26
  exports.UtilCodec = void 0;
27
+ const Constant_1 = require("./Constant");
27
28
  const he = __importStar(require("html-entities"));
28
- const UtilFunctions_1 = require("./UtilFunctions");
29
29
  /**引入tiktoken
30
30
  * 依赖于 tiktoken@1.0.7 但不会自动安装
31
31
  */
32
32
  async function importTikToken() {
33
- const tik = await UtilFunctions_1.UtilFunc.dynamicImport("tiktoken");
34
- if (tik == undefined)
35
- UtilFunctions_1.UtilFunc.throwError(`npm包 tiktoken 动态导入失败, 此包不会随@zwa73/utils自动安装, 可能是未安装, 可使用 npm i tiktoken@1.0.7 来安装`);
36
- return tik;
33
+ return await (0, Constant_1.importOptionPack)({
34
+ name: 'tiktoken',
35
+ installTip: 'npm i tiktoken@1.0.7'
36
+ });
37
37
  }
38
38
  //#endregion
39
39
  /**编码/解码器 */
@@ -44,8 +44,8 @@ declare class _UtilFunc {
44
44
  /**获取当前公网ipv4
45
45
  * 依赖于 public-ip@6.0.2 但不会自动安装
46
46
  */
47
- static getPublicIpv4(): Promise<string | undefined>;
47
+ static getPublicIpv4(): Promise<string>;
48
48
  }
49
- export declare const UtilFunc: import("@zwa73/modular-mixer").ComposedClass<typeof _UtilFunc, typeof JsFunc, "__jsUtils", "prototype" | "preset" | "assignOption" | "genUUID" | "getTime" | "initField" | "initObject" | "afterward" | "sleep" | "getNeverResolvedPromise" | "retryPromise" | "timelimitPromise" | "mapEntries" | "eachField" | "stringifyJToken" | "sortJToken" | "assertType" | "assertLiteral" | "deepClone" | "isSafeNumber" | "dedent" | "throwError" | "getStack" | "getFuncLoc" | "cachePool" | "memoize" | "asyncize" | "lazyFunction" | "splitToChunk" | "mergeFromChunk" | "structEqual" | "concurrent" | "dynamicImport" | "createInjectable" | "createAsyncProxy" | "checkSharpSchema" | "unwarpReadonly" | "outcome" | "extractOutcome" | "success" | "failed" | "match" | "isStatus" | "eitherize" | "parseSrtTime" | "formatSrtTime" | "parseSrt" | "createSrt" | "ivk" | "range" | "s2l" | "l2s">;
49
+ export declare const UtilFunc: import("@zwa73/modular-mixer").ComposedClass<typeof _UtilFunc, typeof JsFunc, "__jsUtils", "match" | "prototype" | "preset" | "assignOption" | "genUUID" | "getTime" | "initField" | "initObject" | "afterward" | "sleep" | "getNeverResolvedPromise" | "retryPromise" | "timelimitPromise" | "mapEntries" | "eachField" | "stringifyJToken" | "sortJToken" | "assertType" | "assertLiteral" | "deepClone" | "isSafeNumber" | "dedent" | "throwError" | "getStack" | "getFuncLoc" | "cachePool" | "memoize" | "asyncize" | "lazyFunction" | "splitToChunk" | "mergeFromChunk" | "structEqual" | "concurrent" | "dynamicImport" | "createInjectable" | "createAsyncProxy" | "checkSharpSchema" | "unwarpReadonly" | "outcome" | "extractOutcome" | "success" | "failed" | "isStatus" | "eitherize" | "parseSrtTime" | "formatSrtTime" | "parseSrt" | "createSrt" | "ivk" | "range" | "s2l" | "l2s">;
50
50
  export type UtilFunc = typeof UtilFunc;
51
51
  export {};
@@ -33,6 +33,7 @@ const path_1 = __importDefault(require("path"));
33
33
  const js_utils_1 = require("@zwa73/js-utils");
34
34
  const modular_mixer_1 = require("@zwa73/modular-mixer");
35
35
  const UtilSymbol_1 = require("./UtilSymbol");
36
+ const Constant_1 = require("./Constant");
36
37
  const UtilFileTools_1 = require("./UtilFileTools");
37
38
  const UtilLogger_1 = require("./UtilLogger");
38
39
  const HashAlgorithmList = [
@@ -130,13 +131,10 @@ class _UtilFunc {
130
131
  * 依赖于 public-ip@6.0.2 但不会自动安装
131
132
  */
132
133
  static async getPublicIpv4() {
133
- const pip = await js_utils_1.JsFunc.dynamicImport('public-ip');
134
- //if(_UtilFunc.publicIp===undefined)
135
- // _UtilFunc.publicIp = await import("public-ip");
136
- if (pip == undefined) {
137
- UtilLogger_1.SLogger.warn(`npm包 public-ip 动态导入失败, 此包不会随@zwa73/utils自动安装, 可能是未安装, 可使用 npm i public-ip@6.0.2 来安装`);
138
- return undefined;
139
- }
134
+ const pip = await (0, Constant_1.importOptionPack)({
135
+ name: 'public-ip',
136
+ installTip: 'npm i public-ip@6.0.2'
137
+ });
140
138
  return pip.publicIpv4();
141
139
  }
142
140
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zwa73/utils",
3
- "version": "1.0.278",
3
+ "version": "1.0.279",
4
4
  "description": "my utils",
5
5
  "main": "dist/index.js",
6
6
  "scripts": {
@@ -19,18 +19,19 @@
19
19
  "@zwa73/js-utils": "*",
20
20
  "@zwa73/modular-mixer": "^1.0.8",
21
21
  "form-data": "^4.0.2",
22
- "glob": "^10.4.1",
23
22
  "html-entities": "^2.3.3",
24
23
  "http-proxy-agent": "^7.0.2",
25
24
  "https-proxy-agent": "^7.0.6",
26
- "json5": "^2.2.3",
27
- "pathe": "^1.1.2",
28
25
  "querystring": "^0.2.1",
29
26
  "winston": "^3.10.0",
30
27
  "winston-daily-rotate-file": "^4.7.1"
31
28
  },
32
29
  "peerDependencies": {
30
+ "@iarna/toml": "^2.2.5",
31
+ "glob": "^13.0.0",
33
32
  "handlebars": "^4.7.8",
33
+ "json5": "^2.2.3",
34
+ "pathe": "^1.1.2",
34
35
  "public-ip": "^6.0.2",
35
36
  "tiktoken": "^1.0.7",
36
37
  "yaml": "^2.8.1"
@@ -47,6 +48,9 @@
47
48
  },
48
49
  "yaml": {
49
50
  "optional": true
51
+ },
52
+ "@iarna/toml": {
53
+ "optional": true
50
54
  }
51
55
  },
52
56
  "devDependencies": {