From fb588ac0c5dd370aff7e599746bd9f27283b3d32 Mon Sep 17 00:00:00 2001 From: tangyw Date: Thu, 11 May 2023 21:32:14 +0800 Subject: [PATCH 01/30] feat(esbuild-config-custom): fix path error in window --- tools/esbuild-config-custom/build.cjs | 8 +++++++- tools/esbuild-config-custom/package.json | 2 +- 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/tools/esbuild-config-custom/build.cjs b/tools/esbuild-config-custom/build.cjs index 31b68a93..7aadff6b 100755 --- a/tools/esbuild-config-custom/build.cjs +++ b/tools/esbuild-config-custom/build.cjs @@ -30,7 +30,13 @@ class ZhiBuild { if (existsSync(esbuildConfigFile)) { try { // 兼容 mjs 和 cjs - const pkg = await import(esbuildConfigFile) + // const pkg = await import(esbuildConfigFile) + const protocol = process.platform === 'win32' ? 'file:///' : 'file://'; + // 获取文件的绝对路径 + const esbuildConfigPath = path.resolve(esbuildConfigFile); + // 拼接 file:// 协议和路径 + const esbuildConfigFileUrl = protocol + esbuildConfigPath; + const pkg = await import(esbuildConfigFileUrl); console.log("pkg=>", pkg) let cfg = pkg if (pkg.default) { diff --git a/tools/esbuild-config-custom/package.json b/tools/esbuild-config-custom/package.json index 201bf9c2..eb52f67d 100644 --- a/tools/esbuild-config-custom/package.json +++ b/tools/esbuild-config-custom/package.json @@ -1,6 +1,6 @@ { "name": "@terwer/esbuild-config-custom", - "version": "1.0.6", + "version": "1.1.0", "type": "module", "description": "universal esbuild tool for library", "bin": { From 934de27324f96a01f8b64d8aeb1ec44d7c60c276 Mon Sep 17 00:00:00 2001 From: terwer Date: Thu, 31 Aug 2023 13:40:00 +0800 Subject: [PATCH 02/30] feat: Optimize YAML parsing --- libs/zhi-blog-api/CHANGELOG.md | 7 +++++ libs/zhi-blog-api/package.json | 2 +- libs/zhi-common/CHANGELOG.md | 6 ++++ libs/zhi-common/package.json | 2 +- libs/zhi-common/src/lib/yamlUtil.spec.ts | 40 ++++++++++++++++++++++++ libs/zhi-common/src/lib/yamlUtil.ts | 22 ++++++------- libs/zhi-fetch-middleware/CHANGELOG.md | 7 +++++ libs/zhi-fetch-middleware/package.json | 2 +- libs/zhi-github-middleware/CHANGELOG.md | 7 +++++ libs/zhi-github-middleware/package.json | 2 +- libs/zhi-gitlab-middleware/CHANGELOG.md | 6 ++++ libs/zhi-gitlab-middleware/package.json | 2 +- libs/zhi-siyuan-api/CHANGELOG.md | 8 +++++ libs/zhi-siyuan-api/package.json | 2 +- libs/zhi-xmlrpc-middleware/CHANGELOG.md | 7 +++++ libs/zhi-xmlrpc-middleware/package.json | 2 +- 16 files changed, 105 insertions(+), 19 deletions(-) diff --git a/libs/zhi-blog-api/CHANGELOG.md b/libs/zhi-blog-api/CHANGELOG.md index 2aa928f6..b0a0b133 100644 --- a/libs/zhi-blog-api/CHANGELOG.md +++ b/libs/zhi-blog-api/CHANGELOG.md @@ -1,5 +1,12 @@ # zhi-blog-api +## 1.34.14 + +### Patch Changes + +- Updated dependencies + - zhi-common@1.23.7 + ## 1.34.13 ### Patch Changes diff --git a/libs/zhi-blog-api/package.json b/libs/zhi-blog-api/package.json index 53eebb08..88e29bca 100644 --- a/libs/zhi-blog-api/package.json +++ b/libs/zhi-blog-api/package.json @@ -1,6 +1,6 @@ { "name": "zhi-blog-api", - "version": "1.34.13", + "version": "1.34.14", "type": "module", "description": "a common blog interface", "main": "./dist/index.js", diff --git a/libs/zhi-common/CHANGELOG.md b/libs/zhi-common/CHANGELOG.md index df9fc19e..d6e4c02d 100644 --- a/libs/zhi-common/CHANGELOG.md +++ b/libs/zhi-common/CHANGELOG.md @@ -1,5 +1,11 @@ # zhi-common +## 1.23.7 + +### Patch Changes + +- feat: Optimize YAML parsing + ## 1.23.6 ### Patch Changes diff --git a/libs/zhi-common/package.json b/libs/zhi-common/package.json index e83b3c0e..a3a2ace4 100644 --- a/libs/zhi-common/package.json +++ b/libs/zhi-common/package.json @@ -1,6 +1,6 @@ { "name": "zhi-common", - "version": "1.23.6", + "version": "1.23.7", "type": "module", "description": "a collection of util tools", "main": "./dist/index.js", diff --git a/libs/zhi-common/src/lib/yamlUtil.spec.ts b/libs/zhi-common/src/lib/yamlUtil.spec.ts index 08320eec..dcf0a671 100644 --- a/libs/zhi-common/src/lib/yamlUtil.spec.ts +++ b/libs/zhi-common/src/lib/yamlUtil.spec.ts @@ -59,4 +59,44 @@ toc: true const yaml = YamlUtil.obj2Yaml(obj) console.log(yaml) }) + + it("test extractMarkdown", () => { + const md = `--- +title: 'WordPress未开启xmlrpc的时候给出友好提示 · Issue #643 · terwersiyuan-plugin-publisher' +date: '2023-08-31 11:09:31' +updated: '2023-08-31 11:12:18' +permalink: /post/wordpress-does-not-open-xmlrpc-to-give-friendly-prompts-nbtkf.html +comments: true +toc: true +--- +# WordPress未开启xmlrpc的时候给出友好提示 · Issue #643 · terwersiyuan-plugin-publisher + +--- + +* [https://github.com/terwer/siyuan-plugin-publisher/issues/643 - GitHub](https://github.com/terwer/siyuan-plugin-publisher/issues/643) +* Slash commands +* 2023-08-31 11:09:31 + +--- + +**Slash commands** + +Beta + +[ Give feedback ](https://github.com/feedback/slash-commands) + +**Slash commands** + +Beta + +[ Give feedback ](https://github.com/feedback/slash-commands) + +#### An unexpected error has occurred + +** ** Attach files by dragging & dropping, selecting or pasting them. ** ** ** ** Uploading your files… ** ** ** We don’t support that file type. ** **Try again** with a GIF, JPEG, JPG, MOV, MP4, PNG, SVG, WEBM, CSV, DOCX, FODG, FODP, FODS, FODT, GZ, LOG, MD, ODF, ODG, ODP, ODS, ODT, PATCH, PDF, PPTX, TGZ, TXT, XLS, XLSX or ZIP. ** ** ** Attaching documents requires write permission to this repository. ** **Try again** with a GIF, JPEG, JPG, MOV, MP4, PNG, SVG, WEBM, CSV, DOCX, FODG, FODP, FODS, FODT, GZ, LOG, MD, ODF, ODG, ODP, ODS, ODT, PATCH, PDF, PPTX, TGZ, TXT, XLS, XLSX or ZIP. ** ** ** We don’t support that file type. ** **Try again** with a GIF, JPEG, JPG, MOV, MP4, PNG, SVG, WEBM, CSV, DOCX, FODG, FODP, FODS, FODT, GZ, LOG, MD, ODF, ODG, ODP, ODS, ODT, PATCH, PDF, PPTX, TGZ, TXT, XLS, XLSX or ZIP. ** ** ** ** ** This file is empty. ** **Try again** with a file that’s not empty. ** ** ** This file is hidden. ** **Try again** with another file. ** ** ** Something went really wrong, and we can’t process that file. ** **Try again.** ** ** [ ](https://docs.github.com/github/writing-on-github/getting-started-with-writing-and-formatting-on-github/basic-writing-and-formatting-syntax) +` + const result = YamlUtil.extractMarkdown(md) + const result2 = YamlUtil.extractMarkdown(result) + console.log(result2) + }) }) diff --git a/libs/zhi-common/src/lib/yamlUtil.ts b/libs/zhi-common/src/lib/yamlUtil.ts index 88724caa..45f65199 100644 --- a/libs/zhi-common/src/lib/yamlUtil.ts +++ b/libs/zhi-common/src/lib/yamlUtil.ts @@ -35,6 +35,7 @@ import { simpleLogger } from "zhi-lib-base" */ class YamlUtil { private static logger = simpleLogger("yaml-util") + private static YAML_REGEX = /---\n([\s\S]*?\n)---/ /** * yaml转对象 @@ -43,7 +44,11 @@ class YamlUtil { */ public static yaml2Obj(content: string): any { const frontMatter = this.extractFrontmatter(content) - return jsYaml.load(frontMatter, {}) + let ret = jsYaml.load(frontMatter, {}) + if (!ret) { + ret = {} + } + return ret } /** @@ -56,11 +61,8 @@ class YamlUtil { public static async yaml2ObjAsync(content: string): Promise { // 提取 YAML const frontMatter = this.extractFrontmatter(content, true) - // 去掉分隔符 - const regex = /^---\n([\s\S]*)\n---$/ - const match = frontMatter.match(regex) - + const match = frontMatter.match(this.YAML_REGEX) if (match) { const rawContent = match[1] try { @@ -94,9 +96,7 @@ class YamlUtil { * @param addSign - 是否包含符号 */ public static extractFrontmatter(content: string, addSign?: boolean): any { - const regex = /^---\n([\s\S]*?\n)---/ - const match = content.match(regex) - + const match = content.match(this.YAML_REGEX) if (match) { let frontMatter = match[1].trim() if (addSign) { @@ -114,11 +114,9 @@ class YamlUtil { * @param content - 包含正文和前置数据的字符串 */ public static extractMarkdown(content: string): any { - const regex = /^---\n([\s\S]*?\n)---/ - let markdown = content - if (regex.test(content)) { - markdown = content.replace(regex, "") + if (this.YAML_REGEX.test(content)) { + markdown = content.replace(this.YAML_REGEX, "") this.logger.info("发现原有的YAML,已移除") } diff --git a/libs/zhi-fetch-middleware/CHANGELOG.md b/libs/zhi-fetch-middleware/CHANGELOG.md index 58a60ab8..1d62a077 100644 --- a/libs/zhi-fetch-middleware/CHANGELOG.md +++ b/libs/zhi-fetch-middleware/CHANGELOG.md @@ -1,5 +1,12 @@ # zhi-fetch-middleware +## 0.6.4 + +### Patch Changes + +- Updated dependencies + - zhi-common@1.23.7 + ## 0.6.3 ### Patch Changes diff --git a/libs/zhi-fetch-middleware/package.json b/libs/zhi-fetch-middleware/package.json index 94cbf325..e48e481d 100644 --- a/libs/zhi-fetch-middleware/package.json +++ b/libs/zhi-fetch-middleware/package.json @@ -1,6 +1,6 @@ { "name": "zhi-fetch-middleware", - "version": "0.6.3", + "version": "0.6.4", "type": "module", "description": "an intermediate tier prepared for fetch requests", "main": "./dist/index.js", diff --git a/libs/zhi-github-middleware/CHANGELOG.md b/libs/zhi-github-middleware/CHANGELOG.md index 624df7fe..1785e015 100644 --- a/libs/zhi-github-middleware/CHANGELOG.md +++ b/libs/zhi-github-middleware/CHANGELOG.md @@ -1,5 +1,12 @@ # zhi-github-middleware +## 0.4.2 + +### Patch Changes + +- Updated dependencies + - zhi-common@1.23.7 + ## 0.4.1 ### Patch Changes diff --git a/libs/zhi-github-middleware/package.json b/libs/zhi-github-middleware/package.json index a4147125..5eeec8ae 100644 --- a/libs/zhi-github-middleware/package.json +++ b/libs/zhi-github-middleware/package.json @@ -1,6 +1,6 @@ { "name": "zhi-github-middleware", - "version": "0.4.1", + "version": "0.4.2", "type": "module", "description": "a middleware for github api", "main": "./dist/index.js", diff --git a/libs/zhi-gitlab-middleware/CHANGELOG.md b/libs/zhi-gitlab-middleware/CHANGELOG.md index 864575c4..1f61713e 100644 --- a/libs/zhi-gitlab-middleware/CHANGELOG.md +++ b/libs/zhi-gitlab-middleware/CHANGELOG.md @@ -1,5 +1,11 @@ # zhi-gitlab-middleware +## 0.6.4 + +### Patch Changes + +- zhi-fetch-middleware@0.6.4 + ## 0.6.3 ### Patch Changes diff --git a/libs/zhi-gitlab-middleware/package.json b/libs/zhi-gitlab-middleware/package.json index 428972a2..64efc59a 100644 --- a/libs/zhi-gitlab-middleware/package.json +++ b/libs/zhi-gitlab-middleware/package.json @@ -1,6 +1,6 @@ { "name": "zhi-gitlab-middleware", - "version": "0.6.3", + "version": "0.6.4", "type": "module", "description": "a middleware for gitlab api ", "main": "./dist/index.js", diff --git a/libs/zhi-siyuan-api/CHANGELOG.md b/libs/zhi-siyuan-api/CHANGELOG.md index 6093eb84..5962a32f 100644 --- a/libs/zhi-siyuan-api/CHANGELOG.md +++ b/libs/zhi-siyuan-api/CHANGELOG.md @@ -1,5 +1,13 @@ # zhi-siyuan-api +## 2.6.2 + +### Patch Changes + +- Updated dependencies + - zhi-common@1.23.7 + - zhi-blog-api@1.34.14 + ## 2.6.1 ### Patch Changes diff --git a/libs/zhi-siyuan-api/package.json b/libs/zhi-siyuan-api/package.json index 75e5cf12..96e0523e 100644 --- a/libs/zhi-siyuan-api/package.json +++ b/libs/zhi-siyuan-api/package.json @@ -1,6 +1,6 @@ { "name": "zhi-siyuan-api", - "version": "2.6.1", + "version": "2.6.2", "type": "module", "description": "a siyuan-note api including both kernel and client", "main": "./dist/index.js", diff --git a/libs/zhi-xmlrpc-middleware/CHANGELOG.md b/libs/zhi-xmlrpc-middleware/CHANGELOG.md index 22f3b075..6d405da9 100644 --- a/libs/zhi-xmlrpc-middleware/CHANGELOG.md +++ b/libs/zhi-xmlrpc-middleware/CHANGELOG.md @@ -1,5 +1,12 @@ # zhi-xmlrpc-middleware +## 0.5.11 + +### Patch Changes + +- Updated dependencies + - zhi-common@1.23.7 + ## 0.5.10 ### Patch Changes diff --git a/libs/zhi-xmlrpc-middleware/package.json b/libs/zhi-xmlrpc-middleware/package.json index 1c3c8805..5ab97e56 100644 --- a/libs/zhi-xmlrpc-middleware/package.json +++ b/libs/zhi-xmlrpc-middleware/package.json @@ -1,6 +1,6 @@ { "name": "zhi-xmlrpc-middleware", - "version": "0.5.10", + "version": "0.5.11", "type": "module", "description": "abstract xmlrpc middle layer", "main": "./dist/index.js", From 2bc5a4ff10844da621e38b28ffb90e493bd9ade6 Mon Sep 17 00:00:00 2001 From: terwer Date: Thu, 31 Aug 2023 14:21:20 +0800 Subject: [PATCH 03/30] feat: Extract fromYaml and toYamlObj --- libs/zhi-blog-api/CHANGELOG.md | 6 ++ libs/zhi-blog-api/package.json | 2 +- libs/zhi-blog-api/src/index.ts | 2 + libs/zhi-blog-api/src/lib/PostUtil.ts | 78 +++++++++++++++++++ libs/zhi-blog-api/src/lib/models/post.ts | 41 ---------- libs/zhi-siyuan-api/CHANGELOG.md | 11 +++ libs/zhi-siyuan-api/package.json | 2 +- .../src/lib/adaptor/siYuanApiAdaptor.ts | 4 +- 8 files changed, 101 insertions(+), 45 deletions(-) create mode 100644 libs/zhi-blog-api/src/lib/PostUtil.ts diff --git a/libs/zhi-blog-api/CHANGELOG.md b/libs/zhi-blog-api/CHANGELOG.md index b0a0b133..a67c3843 100644 --- a/libs/zhi-blog-api/CHANGELOG.md +++ b/libs/zhi-blog-api/CHANGELOG.md @@ -1,5 +1,11 @@ # zhi-blog-api +## 1.35.0 + +### Minor Changes + +- feat: Extract fromYaml and toYamlObj + ## 1.34.14 ### Patch Changes diff --git a/libs/zhi-blog-api/package.json b/libs/zhi-blog-api/package.json index 88e29bca..e4a2a1a8 100644 --- a/libs/zhi-blog-api/package.json +++ b/libs/zhi-blog-api/package.json @@ -1,6 +1,6 @@ { "name": "zhi-blog-api", - "version": "1.34.14", + "version": "1.35.0", "type": "module", "description": "a common blog interface", "main": "./dist/index.js", diff --git a/libs/zhi-blog-api/src/index.ts b/libs/zhi-blog-api/src/index.ts index 8e319308..b6764a27 100644 --- a/libs/zhi-blog-api/src/index.ts +++ b/libs/zhi-blog-api/src/index.ts @@ -21,6 +21,7 @@ import CategoryTypeEnum from "./lib/enums/categoryTypeEnum" import YamlFormatObj from "./lib/models/yamlFormatObj" import YamlConvertAdaptor from "./lib/yamlConvertAdaptor" import PreferenceConfig from "./lib/PreferenceConfig" +import PostUtil from "./lib/PostUtil" export { BlogApi, BlogAdaptor } export { WebApi, WebAdaptor } @@ -29,5 +30,6 @@ export { WebConfig, WebPlaceholder } export { Post, UserBlog, SiteConfig, CategoryInfo, MediaObject, Attachment } export { BlogConstants, BlogTypeEnum, PageTypeEnum, CategoryTypeEnum } export { YamlFormatObj, YamlConvertAdaptor } +export { PostUtil } export { PreferenceConfig } export { type ElectronCookie } diff --git a/libs/zhi-blog-api/src/lib/PostUtil.ts b/libs/zhi-blog-api/src/lib/PostUtil.ts new file mode 100644 index 00000000..e3984083 --- /dev/null +++ b/libs/zhi-blog-api/src/lib/PostUtil.ts @@ -0,0 +1,78 @@ +/* + * Copyright (c) 2023, Terwer . All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Terwer designates this + * particular file as subject to the "Classpath" exception as provided + * by Terwer in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Terwer, Shenzhen, Guangdong, China, youweics@163.com + * or visit www.terwer.space if you need additional information or have any + * questions. + */ + +import Post from "./models/post" +import { DateUtil } from "zhi-common" + +/** + * 文章处理工具类 + * + * @since 1.11.2 + */ +class PostUtil { + /** + * 将当前对象的数据转换为适用于 YAML 的对象 + * + * @returns {Object} 表示数据的适用于 YAML 的对象 + */ + public static toYamlObj(post: Post): Record { + const yamlObj: Record = {} + + post.dateCreated && (yamlObj.created = DateUtil.formatIsoToZh(post.dateCreated.toISOString(), true)) + post.dateUpdated && (yamlObj.updated = DateUtil.formatIsoToZh(post.dateUpdated.toISOString(), true)) + post.title && (yamlObj.title = post.title) + post.wp_slug && (yamlObj.slug = post.wp_slug) + post.permalink && (yamlObj.permalink = post.permalink) + post.shortDesc && (yamlObj.desc = post.shortDesc) + post.mt_keywords && (yamlObj.tags = post.mt_keywords?.split(",")) + post.categories && (yamlObj.categories = post.categories) + + return yamlObj + } + + /** + * 使用来自适用于 YAML 的对象的数据填充当前对象的属性 + * + * @param post - 文章对象 + * @param {Object} yamlObj - 包含要填充对象属性的数据的适用于 YAML 的对象 + */ + public static fromYaml(post: Post, yamlObj: Record): void { + post.dateCreated = yamlObj?.created ? DateUtil.convertStringToDate(yamlObj.created) : post.dateCreated + post.dateUpdated = yamlObj?.updated ? DateUtil.convertStringToDate(yamlObj.updated) : post.dateUpdated + post.title = yamlObj?.title ?? post.title + post.wp_slug = yamlObj?.slug ?? post.wp_slug + post.permalink = yamlObj?.permalink ?? post.permalink + post.shortDesc = yamlObj?.desc ?? post.shortDesc + // 修复历史遗留问题 + if (typeof yamlObj?.tags === "string" && yamlObj?.tags.indexOf(",") > -1) { + post.mt_keywords = yamlObj?.tag + } else { + post.mt_keywords = yamlObj?.tags ? yamlObj?.tags.join(",") : post.mt_keywords + } + post.categories = yamlObj?.categories ?? post.categories + } +} + +export default PostUtil diff --git a/libs/zhi-blog-api/src/lib/models/post.ts b/libs/zhi-blog-api/src/lib/models/post.ts index 5a1fc14d..a9860f6f 100644 --- a/libs/zhi-blog-api/src/lib/models/post.ts +++ b/libs/zhi-blog-api/src/lib/models/post.ts @@ -161,47 +161,6 @@ class Post { this.wp_password = "" this.attrs = "{}" } - - /** - * 将当前对象的数据转换为适用于 YAML 的对象 - * - * @returns {Object} 表示数据的适用于 YAML 的对象 - */ - public toYamlObj(): Record { - const yamlObj: Record = {} - - this.dateCreated && (yamlObj.created = DateUtil.formatIsoToZh(this.dateCreated.toISOString(), true)) - this.dateUpdated && (yamlObj.updated = DateUtil.formatIsoToZh(this.dateUpdated.toISOString(), true)) - this.title && (yamlObj.title = this.title) - this.wp_slug && (yamlObj.slug = this.wp_slug) - this.permalink && (yamlObj.permalink = this.permalink) - this.shortDesc && (yamlObj.desc = this.shortDesc) - this.mt_keywords && (yamlObj.tags = this.mt_keywords?.split(",")) - this.categories && (yamlObj.categories = this.categories) - - return yamlObj - } - - /** - * 使用来自适用于 YAML 的对象的数据填充当前对象的属性 - * - * @param {Object} yamlObj - 包含要填充对象属性的数据的适用于 YAML 的对象 - */ - public fromYaml(yamlObj: Record): void { - this.dateCreated = yamlObj?.created ? DateUtil.convertStringToDate(yamlObj.created) : this.dateCreated - this.dateUpdated = yamlObj?.updated ? DateUtil.convertStringToDate(yamlObj.updated) : this.dateUpdated - this.title = yamlObj?.title ?? this.title - this.wp_slug = yamlObj?.slug ?? this.wp_slug - this.permalink = yamlObj?.permalink ?? this.permalink - this.shortDesc = yamlObj?.desc ?? this.shortDesc - // 修复历史遗留问题 - if (typeof yamlObj?.tags === "string" && yamlObj?.tags.indexOf(",") > -1) { - this.mt_keywords = yamlObj?.tag - } else { - this.mt_keywords = yamlObj?.tags ? yamlObj?.tags.join(",") : this.mt_keywords - } - this.categories = yamlObj?.categories ?? this.categories - } } export default Post diff --git a/libs/zhi-siyuan-api/CHANGELOG.md b/libs/zhi-siyuan-api/CHANGELOG.md index 5962a32f..909c6a10 100644 --- a/libs/zhi-siyuan-api/CHANGELOG.md +++ b/libs/zhi-siyuan-api/CHANGELOG.md @@ -1,5 +1,16 @@ # zhi-siyuan-api +## 2.7.0 + +### Minor Changes + +- feat: Extract fromYaml and toYamlObj + +### Patch Changes + +- Updated dependencies + - zhi-blog-api@1.35.0 + ## 2.6.2 ### Patch Changes diff --git a/libs/zhi-siyuan-api/package.json b/libs/zhi-siyuan-api/package.json index 96e0523e..7acffc7a 100644 --- a/libs/zhi-siyuan-api/package.json +++ b/libs/zhi-siyuan-api/package.json @@ -1,6 +1,6 @@ { "name": "zhi-siyuan-api", - "version": "2.6.2", + "version": "2.7.0", "type": "module", "description": "a siyuan-note api including both kernel and client", "main": "./dist/index.js", diff --git a/libs/zhi-siyuan-api/src/lib/adaptor/siYuanApiAdaptor.ts b/libs/zhi-siyuan-api/src/lib/adaptor/siYuanApiAdaptor.ts index 179e208c..e703d236 100644 --- a/libs/zhi-siyuan-api/src/lib/adaptor/siYuanApiAdaptor.ts +++ b/libs/zhi-siyuan-api/src/lib/adaptor/siYuanApiAdaptor.ts @@ -23,7 +23,7 @@ * questions. */ -import { Attachment, BlogApi, CategoryInfo, MediaObject, Post, PostStatusEnum, UserBlog } from "zhi-blog-api" +import { Attachment, BlogApi, CategoryInfo, MediaObject, Post, PostStatusEnum, PostUtil, UserBlog } from "zhi-blog-api" import SiyuanKernelApi from "../kernel/siyuanKernelApi" import SiyuanConfig from "../config/siyuanConfig" import { NotImplementedException } from "zhi-lib-base" @@ -225,7 +225,7 @@ class SiYuanApiAdaptor extends BlogApi { commonPost.attrs = JSON.stringify(publicAttrs) // yaml 适配 - const yamlObj = commonPost.toYamlObj() + const yamlObj = PostUtil.toYamlObj(commonPost) commonPost.yaml = YamlUtil.obj2Yaml(yamlObj) return commonPost From 9b6324b2abfb4c6a617da90bb125e3e76d5fc481 Mon Sep 17 00:00:00 2001 From: terwer Date: Sat, 2 Sep 2023 20:35:08 +0800 Subject: [PATCH 04/30] feat: YAML serialization requires merge labels and classifications --- libs/zhi-blog-api/CHANGELOG.md | 6 ++++ libs/zhi-blog-api/package.json | 2 +- libs/zhi-blog-api/src/lib/PostUtil.spec.ts | 32 ++++++++++++++++++++++ libs/zhi-blog-api/src/lib/PostUtil.ts | 20 +++++++++----- libs/zhi-siyuan-api/CHANGELOG.md | 7 +++++ libs/zhi-siyuan-api/package.json | 2 +- 6 files changed, 60 insertions(+), 9 deletions(-) create mode 100644 libs/zhi-blog-api/src/lib/PostUtil.spec.ts diff --git a/libs/zhi-blog-api/CHANGELOG.md b/libs/zhi-blog-api/CHANGELOG.md index a67c3843..adb27628 100644 --- a/libs/zhi-blog-api/CHANGELOG.md +++ b/libs/zhi-blog-api/CHANGELOG.md @@ -1,5 +1,11 @@ # zhi-blog-api +## 1.36.0 + +### Minor Changes + +- feat: YAML serialization requires merge labels and classifications + ## 1.35.0 ### Minor Changes diff --git a/libs/zhi-blog-api/package.json b/libs/zhi-blog-api/package.json index e4a2a1a8..0c3a852b 100644 --- a/libs/zhi-blog-api/package.json +++ b/libs/zhi-blog-api/package.json @@ -1,6 +1,6 @@ { "name": "zhi-blog-api", - "version": "1.35.0", + "version": "1.36.0", "type": "module", "description": "a common blog interface", "main": "./dist/index.js", diff --git a/libs/zhi-blog-api/src/lib/PostUtil.spec.ts b/libs/zhi-blog-api/src/lib/PostUtil.spec.ts new file mode 100644 index 00000000..76732858 --- /dev/null +++ b/libs/zhi-blog-api/src/lib/PostUtil.spec.ts @@ -0,0 +1,32 @@ +/* + * Copyright (c) 2023, Terwer . All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Terwer designates this + * particular file as subject to the "Classpath" exception as provided + * by Terwer in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Terwer, Shenzhen, Guangdong, China, youweics@163.com + * or visit www.terwer.space if you need additional information or have any + * questions. + */ + +import { describe, it } from "vitest" + +describe("test PostUtil", () => { + it("test fromYaml", () => { + + }) +}) diff --git a/libs/zhi-blog-api/src/lib/PostUtil.ts b/libs/zhi-blog-api/src/lib/PostUtil.ts index e3984083..224681bf 100644 --- a/libs/zhi-blog-api/src/lib/PostUtil.ts +++ b/libs/zhi-blog-api/src/lib/PostUtil.ts @@ -60,18 +60,24 @@ class PostUtil { */ public static fromYaml(post: Post, yamlObj: Record): void { post.dateCreated = yamlObj?.created ? DateUtil.convertStringToDate(yamlObj.created) : post.dateCreated - post.dateUpdated = yamlObj?.updated ? DateUtil.convertStringToDate(yamlObj.updated) : post.dateUpdated + post.dateUpdated = + (yamlObj?.updated ? DateUtil.convertStringToDate(yamlObj.updated) : post.dateUpdated) ?? new Date() post.title = yamlObj?.title ?? post.title post.wp_slug = yamlObj?.slug ?? post.wp_slug post.permalink = yamlObj?.permalink ?? post.permalink post.shortDesc = yamlObj?.desc ?? post.shortDesc - // 修复历史遗留问题 - if (typeof yamlObj?.tags === "string" && yamlObj?.tags.indexOf(",") > -1) { - post.mt_keywords = yamlObj?.tag - } else { - post.mt_keywords = yamlObj?.tags ? yamlObj?.tags.join(",") : post.mt_keywords + + // 标签合并 + if (yamlObj?.tags && yamlObj.tags.length > 0) { + const existingTags = post.mt_keywords.split(",") + const uniqueKeywords = [...new Set([...existingTags, ...yamlObj.tags])] + post.mt_keywords = uniqueKeywords.join(",") + } + + // 分类合并 + if (yamlObj?.categories && yamlObj.categories.length > 0) { + post.categories = [...new Set([...post.categories, ...yamlObj.categories])] } - post.categories = yamlObj?.categories ?? post.categories } } diff --git a/libs/zhi-siyuan-api/CHANGELOG.md b/libs/zhi-siyuan-api/CHANGELOG.md index 909c6a10..4b81e2e8 100644 --- a/libs/zhi-siyuan-api/CHANGELOG.md +++ b/libs/zhi-siyuan-api/CHANGELOG.md @@ -1,5 +1,12 @@ # zhi-siyuan-api +## 2.7.1 + +### Patch Changes + +- Updated dependencies + - zhi-blog-api@1.36.0 + ## 2.7.0 ### Minor Changes diff --git a/libs/zhi-siyuan-api/package.json b/libs/zhi-siyuan-api/package.json index 7acffc7a..47319a29 100644 --- a/libs/zhi-siyuan-api/package.json +++ b/libs/zhi-siyuan-api/package.json @@ -1,6 +1,6 @@ { "name": "zhi-siyuan-api", - "version": "2.7.0", + "version": "2.7.1", "type": "module", "description": "a siyuan-note api including both kernel and client", "main": "./dist/index.js", From 7a2a2a0090047da4ed36901c8c15d917c06af701 Mon Sep 17 00:00:00 2001 From: terwer Date: Sat, 2 Sep 2023 20:45:31 +0800 Subject: [PATCH 05/30] fix: change empty categories --- libs/zhi-blog-api/CHANGELOG.md | 6 ++++++ libs/zhi-blog-api/package.json | 2 +- libs/zhi-blog-api/src/lib/PostUtil.ts | 5 +++-- libs/zhi-siyuan-api/CHANGELOG.md | 7 +++++++ libs/zhi-siyuan-api/package.json | 2 +- 5 files changed, 18 insertions(+), 4 deletions(-) diff --git a/libs/zhi-blog-api/CHANGELOG.md b/libs/zhi-blog-api/CHANGELOG.md index adb27628..23d91e1f 100644 --- a/libs/zhi-blog-api/CHANGELOG.md +++ b/libs/zhi-blog-api/CHANGELOG.md @@ -1,5 +1,11 @@ # zhi-blog-api +## 1.36.1 + +### Patch Changes + +- fix; change empty categories + ## 1.36.0 ### Minor Changes diff --git a/libs/zhi-blog-api/package.json b/libs/zhi-blog-api/package.json index 0c3a852b..4a2c5a58 100644 --- a/libs/zhi-blog-api/package.json +++ b/libs/zhi-blog-api/package.json @@ -1,6 +1,6 @@ { "name": "zhi-blog-api", - "version": "1.36.0", + "version": "1.36.1", "type": "module", "description": "a common blog interface", "main": "./dist/index.js", diff --git a/libs/zhi-blog-api/src/lib/PostUtil.ts b/libs/zhi-blog-api/src/lib/PostUtil.ts index 224681bf..777caeeb 100644 --- a/libs/zhi-blog-api/src/lib/PostUtil.ts +++ b/libs/zhi-blog-api/src/lib/PostUtil.ts @@ -71,12 +71,13 @@ class PostUtil { if (yamlObj?.tags && yamlObj.tags.length > 0) { const existingTags = post.mt_keywords.split(",") const uniqueKeywords = [...new Set([...existingTags, ...yamlObj.tags])] - post.mt_keywords = uniqueKeywords.join(",") + post.mt_keywords = uniqueKeywords.length > 0 ? uniqueKeywords.join(",") : "" } // 分类合并 if (yamlObj?.categories && yamlObj.categories.length > 0) { - post.categories = [...new Set([...post.categories, ...yamlObj.categories])] + const combinedCategories = [...new Set([...post.categories, ...yamlObj.categories])] + post.categories = combinedCategories.length > 0 ? combinedCategories : [] } } } diff --git a/libs/zhi-siyuan-api/CHANGELOG.md b/libs/zhi-siyuan-api/CHANGELOG.md index 4b81e2e8..e713cf7e 100644 --- a/libs/zhi-siyuan-api/CHANGELOG.md +++ b/libs/zhi-siyuan-api/CHANGELOG.md @@ -1,5 +1,12 @@ # zhi-siyuan-api +## 2.7.2 + +### Patch Changes + +- Updated dependencies + - zhi-blog-api@1.36.1 + ## 2.7.1 ### Patch Changes diff --git a/libs/zhi-siyuan-api/package.json b/libs/zhi-siyuan-api/package.json index 47319a29..1046052e 100644 --- a/libs/zhi-siyuan-api/package.json +++ b/libs/zhi-siyuan-api/package.json @@ -1,6 +1,6 @@ { "name": "zhi-siyuan-api", - "version": "2.7.1", + "version": "2.7.2", "type": "module", "description": "a siyuan-note api including both kernel and client", "main": "./dist/index.js", From a05a3f1f0543474676f1984bf5613d9c3481c23a Mon Sep 17 00:00:00 2001 From: terwer Date: Sat, 2 Sep 2023 20:56:47 +0800 Subject: [PATCH 06/30] fix: deduplicate duplicate null values --- libs/zhi-blog-api/CHANGELOG.md | 6 ++++++ libs/zhi-blog-api/package.json | 2 +- libs/zhi-blog-api/src/lib/PostUtil.ts | 6 ++++-- libs/zhi-siyuan-api/CHANGELOG.md | 7 +++++++ libs/zhi-siyuan-api/package.json | 2 +- 5 files changed, 19 insertions(+), 4 deletions(-) diff --git a/libs/zhi-blog-api/CHANGELOG.md b/libs/zhi-blog-api/CHANGELOG.md index 23d91e1f..c67af3ce 100644 --- a/libs/zhi-blog-api/CHANGELOG.md +++ b/libs/zhi-blog-api/CHANGELOG.md @@ -1,5 +1,11 @@ # zhi-blog-api +## 1.36.2 + +### Patch Changes + +- fix: deduplicate duplicate null values + ## 1.36.1 ### Patch Changes diff --git a/libs/zhi-blog-api/package.json b/libs/zhi-blog-api/package.json index 4a2c5a58..8b72aeb8 100644 --- a/libs/zhi-blog-api/package.json +++ b/libs/zhi-blog-api/package.json @@ -1,6 +1,6 @@ { "name": "zhi-blog-api", - "version": "1.36.1", + "version": "1.36.2", "type": "module", "description": "a common blog interface", "main": "./dist/index.js", diff --git a/libs/zhi-blog-api/src/lib/PostUtil.ts b/libs/zhi-blog-api/src/lib/PostUtil.ts index 777caeeb..c636be44 100644 --- a/libs/zhi-blog-api/src/lib/PostUtil.ts +++ b/libs/zhi-blog-api/src/lib/PostUtil.ts @@ -70,13 +70,15 @@ class PostUtil { // 标签合并 if (yamlObj?.tags && yamlObj.tags.length > 0) { const existingTags = post.mt_keywords.split(",") - const uniqueKeywords = [...new Set([...existingTags, ...yamlObj.tags])] + const uniqueKeywords = [...new Set([...existingTags, ...yamlObj.tags])].filter((tag) => tag.trim() !== "") post.mt_keywords = uniqueKeywords.length > 0 ? uniqueKeywords.join(",") : "" } // 分类合并 if (yamlObj?.categories && yamlObj.categories.length > 0) { - const combinedCategories = [...new Set([...post.categories, ...yamlObj.categories])] + const combinedCategories = [...new Set([...post.categories, ...yamlObj.categories])].filter( + (cate) => cate.trim() !== "" + ) post.categories = combinedCategories.length > 0 ? combinedCategories : [] } } diff --git a/libs/zhi-siyuan-api/CHANGELOG.md b/libs/zhi-siyuan-api/CHANGELOG.md index e713cf7e..d58b1775 100644 --- a/libs/zhi-siyuan-api/CHANGELOG.md +++ b/libs/zhi-siyuan-api/CHANGELOG.md @@ -1,5 +1,12 @@ # zhi-siyuan-api +## 2.7.3 + +### Patch Changes + +- Updated dependencies + - zhi-blog-api@1.36.2 + ## 2.7.2 ### Patch Changes diff --git a/libs/zhi-siyuan-api/package.json b/libs/zhi-siyuan-api/package.json index 1046052e..caf551bd 100644 --- a/libs/zhi-siyuan-api/package.json +++ b/libs/zhi-siyuan-api/package.json @@ -1,6 +1,6 @@ { "name": "zhi-siyuan-api", - "version": "2.7.2", + "version": "2.7.3", "type": "module", "description": "a siyuan-note api including both kernel and client", "main": "./dist/index.js", From 81c86d375396d1d80917edb664015d913e0daa57 Mon Sep 17 00:00:00 2001 From: terwer Date: Sat, 2 Sep 2023 21:44:32 +0800 Subject: [PATCH 07/30] fix: feat: add filename for uploadFile --- libs/zhi-blog-api/CHANGELOG.md | 6 ++++++ libs/zhi-blog-api/package.json | 2 +- libs/zhi-blog-api/src/lib/IWebApi.ts | 3 ++- libs/zhi-blog-api/src/lib/webAdaptor.ts | 4 ++-- libs/zhi-blog-api/src/lib/webApi.ts | 2 +- libs/zhi-siyuan-api/CHANGELOG.md | 7 +++++++ libs/zhi-siyuan-api/package.json | 2 +- 7 files changed, 20 insertions(+), 6 deletions(-) diff --git a/libs/zhi-blog-api/CHANGELOG.md b/libs/zhi-blog-api/CHANGELOG.md index c67af3ce..814dfed5 100644 --- a/libs/zhi-blog-api/CHANGELOG.md +++ b/libs/zhi-blog-api/CHANGELOG.md @@ -1,5 +1,11 @@ # zhi-blog-api +## 1.36.3 + +### Patch Changes + +- feat: add filename for uploadFile + ## 1.36.2 ### Patch Changes diff --git a/libs/zhi-blog-api/package.json b/libs/zhi-blog-api/package.json index 8b72aeb8..15acdb67 100644 --- a/libs/zhi-blog-api/package.json +++ b/libs/zhi-blog-api/package.json @@ -1,6 +1,6 @@ { "name": "zhi-blog-api", - "version": "1.36.2", + "version": "1.36.3", "type": "module", "description": "a common blog interface", "main": "./dist/index.js", diff --git a/libs/zhi-blog-api/src/lib/IWebApi.ts b/libs/zhi-blog-api/src/lib/IWebApi.ts index 114b7389..f34f4a51 100644 --- a/libs/zhi-blog-api/src/lib/IWebApi.ts +++ b/libs/zhi-blog-api/src/lib/IWebApi.ts @@ -80,9 +80,10 @@ interface IWebApi extends IBlogApi { * 上传图片:调用平台 API 上传图片 * * @param file 图片文件 + * @param filename 文件名,可选 * @returns Promise 上传后的图片地址 */ - uploadFile(file: File): Promise + uploadFile(file: File, filename?: string): Promise /** * 更新文章:调用平台 API 更新文章(发布工具内部通过该接口替换文章内图片地址) diff --git a/libs/zhi-blog-api/src/lib/webAdaptor.ts b/libs/zhi-blog-api/src/lib/webAdaptor.ts index 24640bb3..bb0e480b 100644 --- a/libs/zhi-blog-api/src/lib/webAdaptor.ts +++ b/libs/zhi-blog-api/src/lib/webAdaptor.ts @@ -81,8 +81,8 @@ class WebAdaptor extends BlogAdaptor { return await this.webAdaptor.addPost(post) } - public async uploadFile(file: File): Promise { - return await this.webAdaptor.uploadFile(file) + public async uploadFile(file: File, filename?: string): Promise { + return await this.webAdaptor.uploadFile(file, filename) } public async editPost(postid: string, post: Post, publish?: boolean): Promise { diff --git a/libs/zhi-blog-api/src/lib/webApi.ts b/libs/zhi-blog-api/src/lib/webApi.ts index 58920b5c..b24f2399 100644 --- a/libs/zhi-blog-api/src/lib/webApi.ts +++ b/libs/zhi-blog-api/src/lib/webApi.ts @@ -54,7 +54,7 @@ class WebApi extends BlogApi implements IWebApi { throw new NotImplementedException("You must implement addPost in sub class") } - public async uploadFile(file: File): Promise { + public async uploadFile(file: File, filename?: string): Promise { throw new NotImplementedException("You must implement uploadFile in sub class") } diff --git a/libs/zhi-siyuan-api/CHANGELOG.md b/libs/zhi-siyuan-api/CHANGELOG.md index d58b1775..9e214286 100644 --- a/libs/zhi-siyuan-api/CHANGELOG.md +++ b/libs/zhi-siyuan-api/CHANGELOG.md @@ -1,5 +1,12 @@ # zhi-siyuan-api +## 2.7.4 + +### Patch Changes + +- Updated dependencies + - zhi-blog-api@1.36.3 + ## 2.7.3 ### Patch Changes diff --git a/libs/zhi-siyuan-api/package.json b/libs/zhi-siyuan-api/package.json index caf551bd..7fc435da 100644 --- a/libs/zhi-siyuan-api/package.json +++ b/libs/zhi-siyuan-api/package.json @@ -1,6 +1,6 @@ { "name": "zhi-siyuan-api", - "version": "2.7.3", + "version": "2.7.4", "type": "module", "description": "a siyuan-note api including both kernel and client", "main": "./dist/index.js", From 0f56130877abfee60afd53cb28be69e650c4b8c3 Mon Sep 17 00:00:00 2001 From: terwer Date: Tue, 5 Sep 2023 11:55:58 +0800 Subject: [PATCH 08/30] feat: add zhi-formdata-fetch --- .../.env.development.example | 1 + .../.env.production.example | 1 + apps/zhi-formdata-fetch/.env.test.example | 1 + apps/zhi-formdata-fetch/.eslintrc.cjs | 4 + apps/zhi-formdata-fetch/.gitignore | 18 ++++ apps/zhi-formdata-fetch/CHANGELOG.md | 13 +++ apps/zhi-formdata-fetch/README.md | 6 ++ apps/zhi-formdata-fetch/env.d.ts | 28 ++++++ apps/zhi-formdata-fetch/esbuild.config.cjs | 65 ++++++++++++++ apps/zhi-formdata-fetch/package.json | 32 +++++++ apps/zhi-formdata-fetch/src/index.spec.ts | 20 +++++ apps/zhi-formdata-fetch/src/index.ts | 3 + .../src/lib/formdataFetch.ts | 87 +++++++++++++++++++ apps/zhi-formdata-fetch/tsconfig.json | 19 ++++ pnpm-lock.yaml | 47 ++++++++++ 15 files changed, 345 insertions(+) create mode 100644 apps/zhi-formdata-fetch/.env.development.example create mode 100644 apps/zhi-formdata-fetch/.env.production.example create mode 100644 apps/zhi-formdata-fetch/.env.test.example create mode 100644 apps/zhi-formdata-fetch/.eslintrc.cjs create mode 100644 apps/zhi-formdata-fetch/.gitignore create mode 100644 apps/zhi-formdata-fetch/CHANGELOG.md create mode 100644 apps/zhi-formdata-fetch/README.md create mode 100644 apps/zhi-formdata-fetch/env.d.ts create mode 100644 apps/zhi-formdata-fetch/esbuild.config.cjs create mode 100644 apps/zhi-formdata-fetch/package.json create mode 100644 apps/zhi-formdata-fetch/src/index.spec.ts create mode 100644 apps/zhi-formdata-fetch/src/index.ts create mode 100644 apps/zhi-formdata-fetch/src/lib/formdataFetch.ts create mode 100644 apps/zhi-formdata-fetch/tsconfig.json diff --git a/apps/zhi-formdata-fetch/.env.development.example b/apps/zhi-formdata-fetch/.env.development.example new file mode 100644 index 00000000..42c92bd3 --- /dev/null +++ b/apps/zhi-formdata-fetch/.env.development.example @@ -0,0 +1 @@ +VITE_DEBUG_MODE=true \ No newline at end of file diff --git a/apps/zhi-formdata-fetch/.env.production.example b/apps/zhi-formdata-fetch/.env.production.example new file mode 100644 index 00000000..303ce5b0 --- /dev/null +++ b/apps/zhi-formdata-fetch/.env.production.example @@ -0,0 +1 @@ +VITE_DEBUG_MODE=false \ No newline at end of file diff --git a/apps/zhi-formdata-fetch/.env.test.example b/apps/zhi-formdata-fetch/.env.test.example new file mode 100644 index 00000000..42c92bd3 --- /dev/null +++ b/apps/zhi-formdata-fetch/.env.test.example @@ -0,0 +1 @@ +VITE_DEBUG_MODE=true \ No newline at end of file diff --git a/apps/zhi-formdata-fetch/.eslintrc.cjs b/apps/zhi-formdata-fetch/.eslintrc.cjs new file mode 100644 index 00000000..a1993b7b --- /dev/null +++ b/apps/zhi-formdata-fetch/.eslintrc.cjs @@ -0,0 +1,4 @@ +module.exports = { + root: true, + extends: ["./node_modules/@terwer/eslint-config-custom/typescript/index.cjs"], +} diff --git a/apps/zhi-formdata-fetch/.gitignore b/apps/zhi-formdata-fetch/.gitignore new file mode 100644 index 00000000..d6ee86d1 --- /dev/null +++ b/apps/zhi-formdata-fetch/.gitignore @@ -0,0 +1,18 @@ +# idea +.idea + +# build +dist +lib +!src/lib +node_modules + +# api-extractor +etc +temp +tsdoc-metadata.json + +# env +.env.development +.env.production +.env.test \ No newline at end of file diff --git a/apps/zhi-formdata-fetch/CHANGELOG.md b/apps/zhi-formdata-fetch/CHANGELOG.md new file mode 100644 index 00000000..82a63872 --- /dev/null +++ b/apps/zhi-formdata-fetch/CHANGELOG.md @@ -0,0 +1,13 @@ +# zhi-formdata-fetch + +## 0.1.2 + +### Patch Changes + +- fix: change build type + +## 0.1.1 + +### Patch Changes + +- add zhi-formdata-fetch diff --git a/apps/zhi-formdata-fetch/README.md b/apps/zhi-formdata-fetch/README.md new file mode 100644 index 00000000..7554830a --- /dev/null +++ b/apps/zhi-formdata-fetch/README.md @@ -0,0 +1,6 @@ +# zhi-formdata-fetch +custom fetch with formdata + +## How to use + +For more detail, please go to [zhi-cli](https://github.com/terwer/zhi/tree/dev/apps/zhi-cli) \ No newline at end of file diff --git a/apps/zhi-formdata-fetch/env.d.ts b/apps/zhi-formdata-fetch/env.d.ts new file mode 100644 index 00000000..244ec48c --- /dev/null +++ b/apps/zhi-formdata-fetch/env.d.ts @@ -0,0 +1,28 @@ +/* + * Copyright (c) 2023, Terwer . All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Terwer designates this + * particular file as subject to the "Classpath" exception as provided + * by Terwer in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Terwer, Shenzhen, Guangdong, China, youweics@163.com + * or visit www.terwer.space if you need additional information or have any + * questions. + */ + +interface ImportMeta { + readonly env: ImportMetaEnv +} diff --git a/apps/zhi-formdata-fetch/esbuild.config.cjs b/apps/zhi-formdata-fetch/esbuild.config.cjs new file mode 100644 index 00000000..5a8deaaa --- /dev/null +++ b/apps/zhi-formdata-fetch/esbuild.config.cjs @@ -0,0 +1,65 @@ +/* + * Copyright (c) 2023, Terwer . All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Terwer designates this + * particular file as subject to the "Classpath" exception as provided + * by Terwer in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Terwer, Shenzhen, Guangdong, China, youweics@163.com + * or visit www.terwer.space if you need additional information or have any + * questions. + */ + +const path = require("path") +const minimist = require("minimist") +const { dtsPlugin } = require("esbuild-plugin-d.ts") +const { copy } = require("esbuild-plugin-copy") + +const args = minimist(process.argv.slice(2)) +const outDir = args.outDir || args.o + +// for outer custom output for dev +const baseDir = outDir ?? "./" +const distDir = outDir ? baseDir : path.join(baseDir, "dist") + +/** + * 构建配置 + */ +module.exports = { + esbuildConfig: { + entryPoints: ["src/index.ts"], + outfile: path.join(distDir, "index.cjs"), + format: "cjs", + bundle: true, + platform: "node", + plugins: [ + dtsPlugin(), + copy({ + // this is equal to process.cwd(), which means we use cwd path as base path to resolve `to` path + // if not specified, this plugin uses ESBuild.build outdir/outfile options as base path. + resolveFrom: "cwd", + assets: [ + { + from: ["./README.md"], + to: [path.join(distDir, "/README.md")], + }, + ], + watch: true, + }), + ], + }, + customConfig: {}, +} diff --git a/apps/zhi-formdata-fetch/package.json b/apps/zhi-formdata-fetch/package.json new file mode 100644 index 00000000..40426657 --- /dev/null +++ b/apps/zhi-formdata-fetch/package.json @@ -0,0 +1,32 @@ +{ + "name": "zhi-formdata-fetch", + "version": "0.1.2", + "type": "module", + "description": "custom fetch with formdata", + "main": "./dist/index.cjs", + "typings": "./dist/index.d.ts", + "repository": "terwer/zhi", + "homepage": "https://github.com/terwer/zhi/tree/main/apps/zhi-formdata-fetch", + "author": "terwer", + "license": "MIT", + "keywords": [], + "scripts": { + "dev": "zhi-build --watch", + "build": "zhi-build --production", + "test": "vitest", + "lint": "eslint 'src/**/*.{ts,js}' --fix" + }, + "devDependencies": { + "@terwer/esbuild-config-custom": "workspace:*", + "@terwer/eslint-config-custom": "workspace:*", + "@terwer/tsconfig": "workspace:*", + "@terwer/vitest-config-custom": "workspace:*" + }, + "dependencies": { + "formdata-polyfill": "^4.0.10", + "zhi-lib-base": "workspace:*" + }, + "publishConfig": { + "access": "public" + } +} \ No newline at end of file diff --git a/apps/zhi-formdata-fetch/src/index.spec.ts b/apps/zhi-formdata-fetch/src/index.spec.ts new file mode 100644 index 00000000..76801e68 --- /dev/null +++ b/apps/zhi-formdata-fetch/src/index.spec.ts @@ -0,0 +1,20 @@ +import { describe, it } from "vitest" +// import { FormdataFetch } from "./index" + +describe("zhi-formdata-fetch", () => { + // it("test doFetch", async () => { + // const f = new FormdataFetch() + // const response = await f.doFetch("baidu.com") + // console.log(response) + // }) + + it("test doFetch2", async () => { + const moduleBase = "/Users/terwer/Documents/mydocs/zhi-framework/zhi" + const { FormdataFetch } = require(`${moduleBase}/apps/zhi-formdata-fetch/dist/index.cjs`) as any + console.log(FormdataFetch) + + const f = new FormdataFetch() + const response = await f.doFetch("baidu.com") + console.log(response) + }) +}) diff --git a/apps/zhi-formdata-fetch/src/index.ts b/apps/zhi-formdata-fetch/src/index.ts new file mode 100644 index 00000000..776afc3e --- /dev/null +++ b/apps/zhi-formdata-fetch/src/index.ts @@ -0,0 +1,3 @@ +import FormdataFetch from "./lib/formdataFetch" + +export { FormdataFetch } diff --git a/apps/zhi-formdata-fetch/src/lib/formdataFetch.ts b/apps/zhi-formdata-fetch/src/lib/formdataFetch.ts new file mode 100644 index 00000000..3da95c2b --- /dev/null +++ b/apps/zhi-formdata-fetch/src/lib/formdataFetch.ts @@ -0,0 +1,87 @@ +/* + * Copyright (c) 2023, Terwer . All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Terwer designates this + * particular file as subject to the "Classpath" exception as provided + * by Terwer in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Terwer, Shenzhen, Guangdong, China, youweics@163.com + * or visit www.terwer.space if you need additional information or have any + * questions. + */ + +import fetch from "node-fetch" +import { FormData, formDataToBlob } from "formdata-polyfill/esm.min.js" +import { Readable } from "node:stream" +import { simpleLogger } from "zhi-lib-base" + +// https://github.com/node-fetch/node-fetch/issues/1582#issuecomment-1154842272 +// @ts-expect-error Typings are not perfect +ReadableStream.prototype[Symbol.asyncIterator] ??= async function* () { + // @ts-expect-error Typings are not perfect + const reader = this.getReader() + try { + while (true) { + const { done, value } = await reader.read() + if (done) return + yield value + } + } finally { + reader.releaseLock() + } +} + +class FormdataFetch { + private logger: any + + constructor(isDev?: boolean) { + this.logger = simpleLogger("form-data-fetch", "zhi-formdata-fetch", isDev) + } + + /** + * 执行网络请求并返回数据 + * + * @param url - 请求的URL地址 + * @param headers - 请求头信息 + * @param formData - 可选的FormData对象,用于发送表单数据 + * @returns 包含响应数据的Promise + */ + public async doFetch(url: string, headers: Record, formData?: FormData) { + const blob: any = formDataToBlob(formData ?? new FormData()) + const stream = Readable.from(blob.stream()) + const h = { + ...headers, + "Content-Length": blob.size, + "Content-Type": blob.type, + } + this.logger.debug("headers =>", h) + + const response = await fetch(url, { + method: "POST", + headers: h, + body: stream, + }) + + if (!response.ok) { + throw new Error("Network response was not ok") + } + + const resText = await response.text() + return resText + } +} + +export default FormdataFetch diff --git a/apps/zhi-formdata-fetch/tsconfig.json b/apps/zhi-formdata-fetch/tsconfig.json new file mode 100644 index 00000000..e9246af0 --- /dev/null +++ b/apps/zhi-formdata-fetch/tsconfig.json @@ -0,0 +1,19 @@ +{ + "extends": "../../tools/tsconfig/base.json", + "compilerOptions": { + "target": "esnext", + "module": "esnext", + "moduleResolution": "node", + "isolatedModules": false, + "esModuleInterop": true, + "outDir": "./dist" + }, + "include": [ + "./**/*.vue", + "./**/*.ts", + "./**/*.spec.ts" + ], + "exclude": [ + "./dist" + ] +} \ No newline at end of file diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 5c3ff593..6daf52bc 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -61,6 +61,28 @@ importers: specifier: ^0.2.0 version: 0.2.0 + apps/zhi-formdata-fetch: + dependencies: + formdata-polyfill: + specifier: ^4.0.10 + version: 4.0.10 + zhi-lib-base: + specifier: workspace:* + version: link:../../libs/zhi-lib-base + devDependencies: + '@terwer/esbuild-config-custom': + specifier: workspace:* + version: link:../../tools/esbuild-config-custom + '@terwer/eslint-config-custom': + specifier: workspace:* + version: link:../../tools/eslint-config-custom + '@terwer/tsconfig': + specifier: workspace:* + version: link:../../tools/tsconfig + '@terwer/vitest-config-custom': + specifier: workspace:* + version: link:../../tools/vitest-config-custom + libs/zhi-blog-api: dependencies: zhi-common: @@ -4508,6 +4530,14 @@ packages: dependencies: reusify: 1.0.4 + /fetch-blob@3.2.0: + resolution: {integrity: sha512-7yAQpD2UMJzLi1Dqv7qFYnPbaPx7ZfFK6PiIxQ4PfkGPyNyl2Ugx+a/umUonmKqjhM4DnfbMvdX6otXq83soQQ==} + engines: {node: ^12.20 || >= 14.13} + dependencies: + node-domexception: 1.0.0 + web-streams-polyfill: 3.2.1 + dev: false + /figures@2.0.0: resolution: {integrity: sha512-Oa2M9atig69ZkfwiApY8F2Yy+tzMbazyvqv21R0NsSC8floSOC09BbT1ITWAdoMGQvJ/aZnR1KMwdx9tvHnTNA==} engines: {node: '>=4'} @@ -4619,6 +4649,13 @@ packages: combined-stream: 1.0.8 mime-types: 2.1.33 + /formdata-polyfill@4.0.10: + resolution: {integrity: sha512-buewHzMvYL29jdeQTVILecSaZKnt/RJWjoZCF5OW60Z67/GmSLBkOFM7qh1PI3zFNtJbaZL5eQu1vLfazOwj4g==} + engines: {node: '>=12.20.0'} + dependencies: + fetch-blob: 3.2.0 + dev: false + /fs-extra@10.1.0: resolution: {integrity: sha512-oRXApq54ETRj4eMiFzGnHWGy+zo5raudjuxN0b8H7s/RU2oW0Wvsx9O0ACRN/kRq9E8Vu/ReskGB5o3ji+FzHQ==} engines: {node: '>=12'} @@ -6223,6 +6260,11 @@ packages: resolution: {integrity: sha512-Yd3UES5mWCSqR+qNT93S3UoYUkqAZ9lLg8a7g9rimsWmYGK8cVToA4/sF3RrshdyV3sAGMXVUmpMYOw+dLpOuw==} dev: false + /node-domexception@1.0.0: + resolution: {integrity: sha512-/jKZoMpw0F8GRwl4/eLROPA3cfcXtLApP0QzLmUT/HuPCZWyB7IY9ZrMeKw2O/nFIqPQB3PVM9aYm0F312AXDQ==} + engines: {node: '>=10.5.0'} + dev: false + /node-fetch@2.6.11: resolution: {integrity: sha512-4I6pdBY1EthSqDmJkiNk3JIT8cswwR9nfeW/cPdUagJYEQG7R95WRH74wpz7ma8Gh/9dI9FP+OU+0E4FvtA55w==} engines: {node: 4.x || >=6.0.0} @@ -8606,6 +8648,11 @@ packages: dependencies: defaults: 1.0.4 + /web-streams-polyfill@3.2.1: + resolution: {integrity: sha512-e0MO3wdXWKrLbL0DgGnUV7WHVuw9OUvL4hjgnPkIeEvESk74gAITi5G606JtZPp39cd8HA9VQzCIvA49LpPN5Q==} + engines: {node: '>= 8'} + dev: false + /webidl-conversions@3.0.1: resolution: {integrity: sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ==} From e6ee216a9e70b4730f434cccc7bf8cae77a32adf Mon Sep 17 00:00:00 2001 From: terwer Date: Tue, 5 Sep 2023 11:56:36 +0800 Subject: [PATCH 09/30] feat: add zhi-formdata-fetch --- apps/zhi-formdata-fetch/src/index.spec.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/apps/zhi-formdata-fetch/src/index.spec.ts b/apps/zhi-formdata-fetch/src/index.spec.ts index 76801e68..82195b28 100644 --- a/apps/zhi-formdata-fetch/src/index.spec.ts +++ b/apps/zhi-formdata-fetch/src/index.spec.ts @@ -14,7 +14,7 @@ describe("zhi-formdata-fetch", () => { console.log(FormdataFetch) const f = new FormdataFetch() - const response = await f.doFetch("baidu.com") + const response = await f.doFetch() console.log(response) }) }) From ceed074404e676652f511c1b5742bcf67ebeded8 Mon Sep 17 00:00:00 2001 From: terwer Date: Wed, 6 Sep 2023 14:16:59 +0800 Subject: [PATCH 10/30] feat: change form fetch --- apps/zhi-formdata-fetch/CHANGELOG.md | 12 +++++ apps/zhi-formdata-fetch/package.json | 4 +- apps/zhi-formdata-fetch/src/index.spec.ts | 4 +- apps/zhi-formdata-fetch/src/index.ts | 3 ++ .../src/lib/formdataFetch.ts | 28 +++++------ libs/zhi-siyuan-api/CHANGELOG.md | 24 ++++++++++ libs/zhi-siyuan-api/package.json | 2 +- .../src/lib/kernel/ISiyuanKernelApi.ts | 2 + .../src/lib/kernel/siyuanKernelApi.ts | 5 ++ pnpm-lock.yaml | 46 +++++++++++++++++-- 10 files changed, 108 insertions(+), 22 deletions(-) diff --git a/apps/zhi-formdata-fetch/CHANGELOG.md b/apps/zhi-formdata-fetch/CHANGELOG.md index 82a63872..f34ad5bb 100644 --- a/apps/zhi-formdata-fetch/CHANGELOG.md +++ b/apps/zhi-formdata-fetch/CHANGELOG.md @@ -1,5 +1,17 @@ # zhi-formdata-fetch +## 0.2.0 + +### Minor Changes + +- feat: change form fetch + +## 0.1.3 + +### Patch Changes + +- feat: export formDataToBlob + ## 0.1.2 ### Patch Changes diff --git a/apps/zhi-formdata-fetch/package.json b/apps/zhi-formdata-fetch/package.json index 40426657..3deb93ee 100644 --- a/apps/zhi-formdata-fetch/package.json +++ b/apps/zhi-formdata-fetch/package.json @@ -1,6 +1,6 @@ { "name": "zhi-formdata-fetch", - "version": "0.1.2", + "version": "0.2.0", "type": "module", "description": "custom fetch with formdata", "main": "./dist/index.cjs", @@ -23,7 +23,7 @@ "@terwer/vitest-config-custom": "workspace:*" }, "dependencies": { - "formdata-polyfill": "^4.0.10", + "node-fetch": "^3.3.2", "zhi-lib-base": "workspace:*" }, "publishConfig": { diff --git a/apps/zhi-formdata-fetch/src/index.spec.ts b/apps/zhi-formdata-fetch/src/index.spec.ts index 82195b28..1c64bd8b 100644 --- a/apps/zhi-formdata-fetch/src/index.spec.ts +++ b/apps/zhi-formdata-fetch/src/index.spec.ts @@ -3,8 +3,8 @@ import { describe, it } from "vitest" describe("zhi-formdata-fetch", () => { // it("test doFetch", async () => { - // const f = new FormdataFetch() - // const response = await f.doFetch("baidu.com") + // const f = new FormdataFetch(true) + // const response = await f.doFetch() // console.log(response) // }) diff --git a/apps/zhi-formdata-fetch/src/index.ts b/apps/zhi-formdata-fetch/src/index.ts index 776afc3e..8a536a1c 100644 --- a/apps/zhi-formdata-fetch/src/index.ts +++ b/apps/zhi-formdata-fetch/src/index.ts @@ -1,3 +1,6 @@ import FormdataFetch from "./lib/formdataFetch" +import fetch, { Blob, FormData, Headers } from "node-fetch" export { FormdataFetch } +export { fetch } +export { Blob, FormData, Headers } diff --git a/apps/zhi-formdata-fetch/src/lib/formdataFetch.ts b/apps/zhi-formdata-fetch/src/lib/formdataFetch.ts index 3da95c2b..cfbaa268 100644 --- a/apps/zhi-formdata-fetch/src/lib/formdataFetch.ts +++ b/apps/zhi-formdata-fetch/src/lib/formdataFetch.ts @@ -23,9 +23,7 @@ * questions. */ -import fetch from "node-fetch" -import { FormData, formDataToBlob } from "formdata-polyfill/esm.min.js" -import { Readable } from "node:stream" +import fetch, { Headers } from "node-fetch" import { simpleLogger } from "zhi-lib-base" // https://github.com/node-fetch/node-fetch/issues/1582#issuecomment-1154842272 @@ -60,21 +58,23 @@ class FormdataFetch { * @returns 包含响应数据的Promise */ public async doFetch(url: string, headers: Record, formData?: FormData) { - const blob: any = formDataToBlob(formData ?? new FormData()) - const stream = Readable.from(blob.stream()) - const h = { - ...headers, - "Content-Length": blob.size, - "Content-Type": blob.type, + const myHeaders = new Headers() + // 将headers中的键值对追加到myHeaders中 + for (const key in headers) { + // eslint-disable-next-line no-prototype-builtins + if (headers.hasOwnProperty(key)) { + myHeaders.append(key, headers[key]) + } } - this.logger.debug("headers =>", h) + this.logger.debug("headers =>", myHeaders) - const response = await fetch(url, { + const requestOptions = { method: "POST", - headers: h, - body: stream, - }) + headers: myHeaders, + body: formData, + } + const response = await fetch(url, requestOptions) if (!response.ok) { throw new Error("Network response was not ok") } diff --git a/libs/zhi-siyuan-api/CHANGELOG.md b/libs/zhi-siyuan-api/CHANGELOG.md index 9e214286..d017b63d 100644 --- a/libs/zhi-siyuan-api/CHANGELOG.md +++ b/libs/zhi-siyuan-api/CHANGELOG.md @@ -1,5 +1,29 @@ # zhi-siyuan-api +## 2.9.0 + +### Minor Changes + +- feat: change form fetch + +## 2.8.2 + +### Patch Changes + +- feat: export formDataToBlob + +## 2.8.1 + +### Patch Changes + +- fix: add response log + +## 2.8.0 + +### Minor Changes + +- feat: add payloadEncoding and responseEncoding + ## 2.7.4 ### Patch Changes diff --git a/libs/zhi-siyuan-api/package.json b/libs/zhi-siyuan-api/package.json index 7fc435da..44a2a8a5 100644 --- a/libs/zhi-siyuan-api/package.json +++ b/libs/zhi-siyuan-api/package.json @@ -1,6 +1,6 @@ { "name": "zhi-siyuan-api", - "version": "2.7.4", + "version": "2.9.0", "type": "module", "description": "a siyuan-note api including both kernel and client", "main": "./dist/index.js", diff --git a/libs/zhi-siyuan-api/src/lib/kernel/ISiyuanKernelApi.ts b/libs/zhi-siyuan-api/src/lib/kernel/ISiyuanKernelApi.ts index de83199e..65edf541 100644 --- a/libs/zhi-siyuan-api/src/lib/kernel/ISiyuanKernelApi.ts +++ b/libs/zhi-siyuan-api/src/lib/kernel/ISiyuanKernelApi.ts @@ -96,6 +96,8 @@ interface ISiyuanKernelApi { payload?: any, method?: "GET" | "POST" | "PUT" | "DELETE" | "PATCH", contentType?: string, + payloadEncoding?: "text" | "base64" | "base64-std" | "base64-url" | "base32" | "base32-std" | "base32-hex" | "hex", + responseEncoding?: "text" | "base64" | "base64-std" | "base64-url" | "base32" | "base32-std" | "base32-hex" | "hex", timeout?: number ): Promise diff --git a/libs/zhi-siyuan-api/src/lib/kernel/siyuanKernelApi.ts b/libs/zhi-siyuan-api/src/lib/kernel/siyuanKernelApi.ts index 36ab3668..c559c831 100644 --- a/libs/zhi-siyuan-api/src/lib/kernel/siyuanKernelApi.ts +++ b/libs/zhi-siyuan-api/src/lib/kernel/siyuanKernelApi.ts @@ -286,6 +286,7 @@ class SiyuanKernelApi implements ISiyuanKernelApi { this.logger.debug("开始向思源请求数据,fetchOps=>", fetchOps) const response = await fetch(reqUrl, fetchOps) + this.logger.debug("思源请求数据返回,response=>", response) const resJson = await response.json() this.logger.debug("思源请求数据返回,resJson=>", resJson) @@ -669,6 +670,8 @@ class SiyuanKernelApi implements ISiyuanKernelApi { payload?: any, method?: "GET" | "POST" | "PUT" | "DELETE" | "PATCH", contentType?: string, + payloadEncoding?: "text" | "base64" | "base64-std" | "base64-url" | "base32" | "base32-std" | "base32-hex" | "hex", + responseEncoding?: "text" | "base64" | "base64-std" | "base64-url" | "base32" | "base32-std" | "base32-hex" | "hex", timeout?: number ): Promise { const params = { @@ -677,6 +680,8 @@ class SiyuanKernelApi implements ISiyuanKernelApi { payload: payload, method: method, contentType: contentType, + payloadEncoding: payloadEncoding, + responseEncoding: responseEncoding, timeout: timeout, } return await this.siyuanRequest("/api/network/forwardProxy", params) diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 6daf52bc..607d16f2 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -61,11 +61,33 @@ importers: specifier: ^0.2.0 version: 0.2.0 + apps/zhi-formdata-blob-fetch: + dependencies: + node-fetch-native: + specifier: ^1.4.0 + version: 1.4.0 + zhi-lib-base: + specifier: workspace:* + version: link:../../libs/zhi-lib-base + devDependencies: + '@terwer/esbuild-config-custom': + specifier: workspace:* + version: link:../../tools/esbuild-config-custom + '@terwer/eslint-config-custom': + specifier: workspace:* + version: link:../../tools/eslint-config-custom + '@terwer/tsconfig': + specifier: workspace:* + version: link:../../tools/tsconfig + '@terwer/vitest-config-custom': + specifier: workspace:* + version: link:../../tools/vitest-config-custom + apps/zhi-formdata-fetch: dependencies: - formdata-polyfill: - specifier: ^4.0.10 - version: 4.0.10 + node-fetch: + specifier: ^3.3.2 + version: 3.3.2 zhi-lib-base: specifier: workspace:* version: link:../../libs/zhi-lib-base @@ -3548,6 +3570,11 @@ packages: engines: {node: '>=8'} dev: false + /data-uri-to-buffer@4.0.1: + resolution: {integrity: sha512-0R9ikRb668HB7QDxT1vkpuUBtqc53YyAwMwGeUFKRojY/NWKvdZ+9UYtRfGmhqNbRkTSVpMbmyhXipFFv2cb/A==} + engines: {node: '>= 12'} + dev: false + /data-urls@4.0.0: resolution: {integrity: sha512-/mMTei/JXPqvFqQtfyTowxmJVwr2PVAeCcDxyFf6LhoOu/09TX2OX3kb2wzi4DMXcfj4OItwDOnhl5oziPnT6g==} engines: {node: '>=14'} @@ -6265,6 +6292,10 @@ packages: engines: {node: '>=10.5.0'} dev: false + /node-fetch-native@1.4.0: + resolution: {integrity: sha512-F5kfEj95kX8tkDhUCYdV8dg3/8Olx/94zB8+ZNthFs6Bz31UpUi8Xh40TN3thLwXgrwXry1pEg9lJ++tLWTcqA==} + dev: false + /node-fetch@2.6.11: resolution: {integrity: sha512-4I6pdBY1EthSqDmJkiNk3JIT8cswwR9nfeW/cPdUagJYEQG7R95WRH74wpz7ma8Gh/9dI9FP+OU+0E4FvtA55w==} engines: {node: 4.x || >=6.0.0} @@ -6276,6 +6307,15 @@ packages: dependencies: whatwg-url: 5.0.0 + /node-fetch@3.3.2: + resolution: {integrity: sha512-dRB78srN/l6gqWulah9SrxeYnxeddIG30+GOqK/9OlLVyLg3HPnr6SqOWTWOXKRwC2eGYCkZ59NNuSgvSrpgOA==} + engines: {node: ^12.20.0 || ^14.13.1 || >=16.0.0} + dependencies: + data-uri-to-buffer: 4.0.1 + fetch-blob: 3.2.0 + formdata-polyfill: 4.0.10 + dev: false + /node-stdlib-browser@1.2.0: resolution: {integrity: sha512-VSjFxUhRhkyed8AtLwSCkMrJRfQ3e2lGtG3sP6FEgaLKBBbxM/dLfjRe1+iLhjvyLFW3tBQ8+c0pcOtXGbAZJg==} engines: {node: '>=10'} From b3c3b335fae01596d7c8c322c3fd76e52cd961a7 Mon Sep 17 00:00:00 2001 From: terwer Date: Wed, 6 Sep 2023 14:47:10 +0800 Subject: [PATCH 11/30] feat: change form fetch --- .../.env.development.example | 1 - .../.env.production.example | 1 - apps/zhi-formdata-fetch/.env.test.example | 1 - apps/zhi-formdata-fetch/.eslintrc.cjs | 4 - apps/zhi-formdata-fetch/.gitignore | 18 ---- apps/zhi-formdata-fetch/CHANGELOG.md | 25 ------ apps/zhi-formdata-fetch/README.md | 6 -- apps/zhi-formdata-fetch/env.d.ts | 28 ------ apps/zhi-formdata-fetch/esbuild.config.cjs | 65 -------------- apps/zhi-formdata-fetch/package.json | 32 ------- apps/zhi-formdata-fetch/src/index.spec.ts | 20 ----- apps/zhi-formdata-fetch/src/index.ts | 6 -- .../src/lib/formdataFetch.ts | 87 ------------------- apps/zhi-formdata-fetch/tsconfig.json | 19 ---- 14 files changed, 313 deletions(-) delete mode 100644 apps/zhi-formdata-fetch/.env.development.example delete mode 100644 apps/zhi-formdata-fetch/.env.production.example delete mode 100644 apps/zhi-formdata-fetch/.env.test.example delete mode 100644 apps/zhi-formdata-fetch/.eslintrc.cjs delete mode 100644 apps/zhi-formdata-fetch/.gitignore delete mode 100644 apps/zhi-formdata-fetch/CHANGELOG.md delete mode 100644 apps/zhi-formdata-fetch/README.md delete mode 100644 apps/zhi-formdata-fetch/env.d.ts delete mode 100644 apps/zhi-formdata-fetch/esbuild.config.cjs delete mode 100644 apps/zhi-formdata-fetch/package.json delete mode 100644 apps/zhi-formdata-fetch/src/index.spec.ts delete mode 100644 apps/zhi-formdata-fetch/src/index.ts delete mode 100644 apps/zhi-formdata-fetch/src/lib/formdataFetch.ts delete mode 100644 apps/zhi-formdata-fetch/tsconfig.json diff --git a/apps/zhi-formdata-fetch/.env.development.example b/apps/zhi-formdata-fetch/.env.development.example deleted file mode 100644 index 42c92bd3..00000000 --- a/apps/zhi-formdata-fetch/.env.development.example +++ /dev/null @@ -1 +0,0 @@ -VITE_DEBUG_MODE=true \ No newline at end of file diff --git a/apps/zhi-formdata-fetch/.env.production.example b/apps/zhi-formdata-fetch/.env.production.example deleted file mode 100644 index 303ce5b0..00000000 --- a/apps/zhi-formdata-fetch/.env.production.example +++ /dev/null @@ -1 +0,0 @@ -VITE_DEBUG_MODE=false \ No newline at end of file diff --git a/apps/zhi-formdata-fetch/.env.test.example b/apps/zhi-formdata-fetch/.env.test.example deleted file mode 100644 index 42c92bd3..00000000 --- a/apps/zhi-formdata-fetch/.env.test.example +++ /dev/null @@ -1 +0,0 @@ -VITE_DEBUG_MODE=true \ No newline at end of file diff --git a/apps/zhi-formdata-fetch/.eslintrc.cjs b/apps/zhi-formdata-fetch/.eslintrc.cjs deleted file mode 100644 index a1993b7b..00000000 --- a/apps/zhi-formdata-fetch/.eslintrc.cjs +++ /dev/null @@ -1,4 +0,0 @@ -module.exports = { - root: true, - extends: ["./node_modules/@terwer/eslint-config-custom/typescript/index.cjs"], -} diff --git a/apps/zhi-formdata-fetch/.gitignore b/apps/zhi-formdata-fetch/.gitignore deleted file mode 100644 index d6ee86d1..00000000 --- a/apps/zhi-formdata-fetch/.gitignore +++ /dev/null @@ -1,18 +0,0 @@ -# idea -.idea - -# build -dist -lib -!src/lib -node_modules - -# api-extractor -etc -temp -tsdoc-metadata.json - -# env -.env.development -.env.production -.env.test \ No newline at end of file diff --git a/apps/zhi-formdata-fetch/CHANGELOG.md b/apps/zhi-formdata-fetch/CHANGELOG.md deleted file mode 100644 index f34ad5bb..00000000 --- a/apps/zhi-formdata-fetch/CHANGELOG.md +++ /dev/null @@ -1,25 +0,0 @@ -# zhi-formdata-fetch - -## 0.2.0 - -### Minor Changes - -- feat: change form fetch - -## 0.1.3 - -### Patch Changes - -- feat: export formDataToBlob - -## 0.1.2 - -### Patch Changes - -- fix: change build type - -## 0.1.1 - -### Patch Changes - -- add zhi-formdata-fetch diff --git a/apps/zhi-formdata-fetch/README.md b/apps/zhi-formdata-fetch/README.md deleted file mode 100644 index 7554830a..00000000 --- a/apps/zhi-formdata-fetch/README.md +++ /dev/null @@ -1,6 +0,0 @@ -# zhi-formdata-fetch -custom fetch with formdata - -## How to use - -For more detail, please go to [zhi-cli](https://github.com/terwer/zhi/tree/dev/apps/zhi-cli) \ No newline at end of file diff --git a/apps/zhi-formdata-fetch/env.d.ts b/apps/zhi-formdata-fetch/env.d.ts deleted file mode 100644 index 244ec48c..00000000 --- a/apps/zhi-formdata-fetch/env.d.ts +++ /dev/null @@ -1,28 +0,0 @@ -/* - * Copyright (c) 2023, Terwer . All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Terwer designates this - * particular file as subject to the "Classpath" exception as provided - * by Terwer in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Terwer, Shenzhen, Guangdong, China, youweics@163.com - * or visit www.terwer.space if you need additional information or have any - * questions. - */ - -interface ImportMeta { - readonly env: ImportMetaEnv -} diff --git a/apps/zhi-formdata-fetch/esbuild.config.cjs b/apps/zhi-formdata-fetch/esbuild.config.cjs deleted file mode 100644 index 5a8deaaa..00000000 --- a/apps/zhi-formdata-fetch/esbuild.config.cjs +++ /dev/null @@ -1,65 +0,0 @@ -/* - * Copyright (c) 2023, Terwer . All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Terwer designates this - * particular file as subject to the "Classpath" exception as provided - * by Terwer in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Terwer, Shenzhen, Guangdong, China, youweics@163.com - * or visit www.terwer.space if you need additional information or have any - * questions. - */ - -const path = require("path") -const minimist = require("minimist") -const { dtsPlugin } = require("esbuild-plugin-d.ts") -const { copy } = require("esbuild-plugin-copy") - -const args = minimist(process.argv.slice(2)) -const outDir = args.outDir || args.o - -// for outer custom output for dev -const baseDir = outDir ?? "./" -const distDir = outDir ? baseDir : path.join(baseDir, "dist") - -/** - * 构建配置 - */ -module.exports = { - esbuildConfig: { - entryPoints: ["src/index.ts"], - outfile: path.join(distDir, "index.cjs"), - format: "cjs", - bundle: true, - platform: "node", - plugins: [ - dtsPlugin(), - copy({ - // this is equal to process.cwd(), which means we use cwd path as base path to resolve `to` path - // if not specified, this plugin uses ESBuild.build outdir/outfile options as base path. - resolveFrom: "cwd", - assets: [ - { - from: ["./README.md"], - to: [path.join(distDir, "/README.md")], - }, - ], - watch: true, - }), - ], - }, - customConfig: {}, -} diff --git a/apps/zhi-formdata-fetch/package.json b/apps/zhi-formdata-fetch/package.json deleted file mode 100644 index 3deb93ee..00000000 --- a/apps/zhi-formdata-fetch/package.json +++ /dev/null @@ -1,32 +0,0 @@ -{ - "name": "zhi-formdata-fetch", - "version": "0.2.0", - "type": "module", - "description": "custom fetch with formdata", - "main": "./dist/index.cjs", - "typings": "./dist/index.d.ts", - "repository": "terwer/zhi", - "homepage": "https://github.com/terwer/zhi/tree/main/apps/zhi-formdata-fetch", - "author": "terwer", - "license": "MIT", - "keywords": [], - "scripts": { - "dev": "zhi-build --watch", - "build": "zhi-build --production", - "test": "vitest", - "lint": "eslint 'src/**/*.{ts,js}' --fix" - }, - "devDependencies": { - "@terwer/esbuild-config-custom": "workspace:*", - "@terwer/eslint-config-custom": "workspace:*", - "@terwer/tsconfig": "workspace:*", - "@terwer/vitest-config-custom": "workspace:*" - }, - "dependencies": { - "node-fetch": "^3.3.2", - "zhi-lib-base": "workspace:*" - }, - "publishConfig": { - "access": "public" - } -} \ No newline at end of file diff --git a/apps/zhi-formdata-fetch/src/index.spec.ts b/apps/zhi-formdata-fetch/src/index.spec.ts deleted file mode 100644 index 1c64bd8b..00000000 --- a/apps/zhi-formdata-fetch/src/index.spec.ts +++ /dev/null @@ -1,20 +0,0 @@ -import { describe, it } from "vitest" -// import { FormdataFetch } from "./index" - -describe("zhi-formdata-fetch", () => { - // it("test doFetch", async () => { - // const f = new FormdataFetch(true) - // const response = await f.doFetch() - // console.log(response) - // }) - - it("test doFetch2", async () => { - const moduleBase = "/Users/terwer/Documents/mydocs/zhi-framework/zhi" - const { FormdataFetch } = require(`${moduleBase}/apps/zhi-formdata-fetch/dist/index.cjs`) as any - console.log(FormdataFetch) - - const f = new FormdataFetch() - const response = await f.doFetch() - console.log(response) - }) -}) diff --git a/apps/zhi-formdata-fetch/src/index.ts b/apps/zhi-formdata-fetch/src/index.ts deleted file mode 100644 index 8a536a1c..00000000 --- a/apps/zhi-formdata-fetch/src/index.ts +++ /dev/null @@ -1,6 +0,0 @@ -import FormdataFetch from "./lib/formdataFetch" -import fetch, { Blob, FormData, Headers } from "node-fetch" - -export { FormdataFetch } -export { fetch } -export { Blob, FormData, Headers } diff --git a/apps/zhi-formdata-fetch/src/lib/formdataFetch.ts b/apps/zhi-formdata-fetch/src/lib/formdataFetch.ts deleted file mode 100644 index cfbaa268..00000000 --- a/apps/zhi-formdata-fetch/src/lib/formdataFetch.ts +++ /dev/null @@ -1,87 +0,0 @@ -/* - * Copyright (c) 2023, Terwer . All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Terwer designates this - * particular file as subject to the "Classpath" exception as provided - * by Terwer in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Terwer, Shenzhen, Guangdong, China, youweics@163.com - * or visit www.terwer.space if you need additional information or have any - * questions. - */ - -import fetch, { Headers } from "node-fetch" -import { simpleLogger } from "zhi-lib-base" - -// https://github.com/node-fetch/node-fetch/issues/1582#issuecomment-1154842272 -// @ts-expect-error Typings are not perfect -ReadableStream.prototype[Symbol.asyncIterator] ??= async function* () { - // @ts-expect-error Typings are not perfect - const reader = this.getReader() - try { - while (true) { - const { done, value } = await reader.read() - if (done) return - yield value - } - } finally { - reader.releaseLock() - } -} - -class FormdataFetch { - private logger: any - - constructor(isDev?: boolean) { - this.logger = simpleLogger("form-data-fetch", "zhi-formdata-fetch", isDev) - } - - /** - * 执行网络请求并返回数据 - * - * @param url - 请求的URL地址 - * @param headers - 请求头信息 - * @param formData - 可选的FormData对象,用于发送表单数据 - * @returns 包含响应数据的Promise - */ - public async doFetch(url: string, headers: Record, formData?: FormData) { - const myHeaders = new Headers() - // 将headers中的键值对追加到myHeaders中 - for (const key in headers) { - // eslint-disable-next-line no-prototype-builtins - if (headers.hasOwnProperty(key)) { - myHeaders.append(key, headers[key]) - } - } - this.logger.debug("headers =>", myHeaders) - - const requestOptions = { - method: "POST", - headers: myHeaders, - body: formData, - } - - const response = await fetch(url, requestOptions) - if (!response.ok) { - throw new Error("Network response was not ok") - } - - const resText = await response.text() - return resText - } -} - -export default FormdataFetch diff --git a/apps/zhi-formdata-fetch/tsconfig.json b/apps/zhi-formdata-fetch/tsconfig.json deleted file mode 100644 index e9246af0..00000000 --- a/apps/zhi-formdata-fetch/tsconfig.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "extends": "../../tools/tsconfig/base.json", - "compilerOptions": { - "target": "esnext", - "module": "esnext", - "moduleResolution": "node", - "isolatedModules": false, - "esModuleInterop": true, - "outDir": "./dist" - }, - "include": [ - "./**/*.vue", - "./**/*.ts", - "./**/*.spec.ts" - ], - "exclude": [ - "./dist" - ] -} \ No newline at end of file From 47e69caf738db498948dee4b5da2fc182cbf0957 Mon Sep 17 00:00:00 2001 From: terwer Date: Fri, 8 Sep 2023 09:37:20 +0800 Subject: [PATCH 12/30] feat: add tags_slugs field --- libs/zhi-blog-api/CHANGELOG.md | 6 ++++++ libs/zhi-blog-api/package.json | 2 +- libs/zhi-blog-api/src/lib/models/post.ts | 20 +++++++++++++------- libs/zhi-siyuan-api/CHANGELOG.md | 7 +++++++ libs/zhi-siyuan-api/package.json | 2 +- 5 files changed, 28 insertions(+), 9 deletions(-) diff --git a/libs/zhi-blog-api/CHANGELOG.md b/libs/zhi-blog-api/CHANGELOG.md index 814dfed5..b8421725 100644 --- a/libs/zhi-blog-api/CHANGELOG.md +++ b/libs/zhi-blog-api/CHANGELOG.md @@ -1,5 +1,11 @@ # zhi-blog-api +## 1.37.0 + +### Minor Changes + +- feat: add tags_slugs field + ## 1.36.3 ### Patch Changes diff --git a/libs/zhi-blog-api/package.json b/libs/zhi-blog-api/package.json index 15acdb67..5abbae5c 100644 --- a/libs/zhi-blog-api/package.json +++ b/libs/zhi-blog-api/package.json @@ -1,6 +1,6 @@ { "name": "zhi-blog-api", - "version": "1.36.3", + "version": "1.37.0", "type": "module", "description": "a common blog interface", "main": "./dist/index.js", diff --git a/libs/zhi-blog-api/src/lib/models/post.ts b/libs/zhi-blog-api/src/lib/models/post.ts index a9860f6f..12f5013f 100644 --- a/libs/zhi-blog-api/src/lib/models/post.ts +++ b/libs/zhi-blog-api/src/lib/models/post.ts @@ -42,11 +42,6 @@ class Post { */ title: string - /** - * 逗号分隔的标签 - */ - mt_keywords: string - /** * 链接 */ @@ -107,10 +102,20 @@ class Post { */ dateUpdated: Date + /** + * 逗号分隔的标签 + */ + mt_keywords: string + + /** + * 标签别名,大部分平台不需要 + */ + tags_slugs?: string + /** * 分类 */ - categories: Array + categories: string[] /** * 分类别名,大部分平台不需要 @@ -145,7 +150,6 @@ class Post { constructor() { this.postid = "" this.title = "" - this.mt_keywords = "" this.permalink = "" this.yaml = "---\n---" this.html = "" @@ -154,6 +158,8 @@ class Post { this.description = "" this.wp_slug = "" this.dateCreated = new Date() + this.mt_keywords = "" + this.tags_slugs = "" this.categories = [] this.cate_slugs = [] this.isPublished = true diff --git a/libs/zhi-siyuan-api/CHANGELOG.md b/libs/zhi-siyuan-api/CHANGELOG.md index d017b63d..8d7ddfb3 100644 --- a/libs/zhi-siyuan-api/CHANGELOG.md +++ b/libs/zhi-siyuan-api/CHANGELOG.md @@ -1,5 +1,12 @@ # zhi-siyuan-api +## 2.9.1 + +### Patch Changes + +- Updated dependencies + - zhi-blog-api@1.37.0 + ## 2.9.0 ### Minor Changes diff --git a/libs/zhi-siyuan-api/package.json b/libs/zhi-siyuan-api/package.json index 44a2a8a5..04aa4043 100644 --- a/libs/zhi-siyuan-api/package.json +++ b/libs/zhi-siyuan-api/package.json @@ -1,6 +1,6 @@ { "name": "zhi-siyuan-api", - "version": "2.9.0", + "version": "2.9.1", "type": "module", "description": "a siyuan-note api including both kernel and client", "main": "./dist/index.js", From 348d095451dad831ce2ebda5e3a676bebf032ca9 Mon Sep 17 00:00:00 2001 From: terwer Date: Fri, 8 Sep 2023 10:27:56 +0800 Subject: [PATCH 13/30] feat: add tagSlugEnabled --- libs/zhi-blog-api/CHANGELOG.md | 6 ++++++ libs/zhi-blog-api/package.json | 2 +- libs/zhi-blog-api/src/lib/blogConfig.ts | 6 ++++++ libs/zhi-siyuan-api/CHANGELOG.md | 7 +++++++ libs/zhi-siyuan-api/package.json | 2 +- 5 files changed, 21 insertions(+), 2 deletions(-) diff --git a/libs/zhi-blog-api/CHANGELOG.md b/libs/zhi-blog-api/CHANGELOG.md index b8421725..4530f275 100644 --- a/libs/zhi-blog-api/CHANGELOG.md +++ b/libs/zhi-blog-api/CHANGELOG.md @@ -1,5 +1,11 @@ # zhi-blog-api +## 1.37.1 + +### Patch Changes + +- feat: add tagSlugEnabled + ## 1.37.0 ### Minor Changes diff --git a/libs/zhi-blog-api/package.json b/libs/zhi-blog-api/package.json index 5abbae5c..043163d0 100644 --- a/libs/zhi-blog-api/package.json +++ b/libs/zhi-blog-api/package.json @@ -1,6 +1,6 @@ { "name": "zhi-blog-api", - "version": "1.37.0", + "version": "1.37.1", "type": "module", "description": "a common blog interface", "main": "./dist/index.js", diff --git a/libs/zhi-blog-api/src/lib/blogConfig.ts b/libs/zhi-blog-api/src/lib/blogConfig.ts index 2a7fd4a8..c9276fcd 100644 --- a/libs/zhi-blog-api/src/lib/blogConfig.ts +++ b/libs/zhi-blog-api/src/lib/blogConfig.ts @@ -229,6 +229,11 @@ abstract class BlogConfig { */ public yamlLinkEnabled: boolean + /** + * 是否运行标签别名 + */ + public tagSlugEnabled: boolean + protected constructor() { this.home = "" this.apiUrl = "" @@ -257,6 +262,7 @@ abstract class BlogConfig { this.allowCateChange = false this.categoryType = CategoryTypeEnum.CategoryType_None this.yamlLinkEnabled = true + this.tagSlugEnabled = false } } diff --git a/libs/zhi-siyuan-api/CHANGELOG.md b/libs/zhi-siyuan-api/CHANGELOG.md index 8d7ddfb3..e1ca0187 100644 --- a/libs/zhi-siyuan-api/CHANGELOG.md +++ b/libs/zhi-siyuan-api/CHANGELOG.md @@ -1,5 +1,12 @@ # zhi-siyuan-api +## 2.9.2 + +### Patch Changes + +- Updated dependencies + - zhi-blog-api@1.37.1 + ## 2.9.1 ### Patch Changes diff --git a/libs/zhi-siyuan-api/package.json b/libs/zhi-siyuan-api/package.json index 04aa4043..249cbad9 100644 --- a/libs/zhi-siyuan-api/package.json +++ b/libs/zhi-siyuan-api/package.json @@ -1,6 +1,6 @@ { "name": "zhi-siyuan-api", - "version": "2.9.1", + "version": "2.9.2", "type": "module", "description": "a siyuan-note api including both kernel and client", "main": "./dist/index.js", From 08dd4fb3fdef91f6730bc1a2997855db1e6da0a2 Mon Sep 17 00:00:00 2001 From: terwer Date: Fri, 8 Sep 2023 11:10:02 +0800 Subject: [PATCH 14/30] feat: add getTags method --- libs/zhi-blog-api/CHANGELOG.md | 6 ++ libs/zhi-blog-api/package.json | 2 +- libs/zhi-blog-api/src/lib/IBlogApi.ts | 6 ++ libs/zhi-blog-api/src/lib/blogAdaptor.ts | 8 +++ libs/zhi-blog-api/src/lib/blogApi.ts | 5 ++ libs/zhi-blog-api/src/lib/models/tagInfo.ts | 61 +++++++++++++++++++++ libs/zhi-siyuan-api/CHANGELOG.md | 7 +++ libs/zhi-siyuan-api/package.json | 2 +- 8 files changed, 95 insertions(+), 2 deletions(-) create mode 100644 libs/zhi-blog-api/src/lib/models/tagInfo.ts diff --git a/libs/zhi-blog-api/CHANGELOG.md b/libs/zhi-blog-api/CHANGELOG.md index 4530f275..e37fcb27 100644 --- a/libs/zhi-blog-api/CHANGELOG.md +++ b/libs/zhi-blog-api/CHANGELOG.md @@ -1,5 +1,11 @@ # zhi-blog-api +## 1.38.0 + +### Minor Changes + +- feat: add getTags method + ## 1.37.1 ### Patch Changes diff --git a/libs/zhi-blog-api/package.json b/libs/zhi-blog-api/package.json index 043163d0..97f59bf1 100644 --- a/libs/zhi-blog-api/package.json +++ b/libs/zhi-blog-api/package.json @@ -1,6 +1,6 @@ { "name": "zhi-blog-api", - "version": "1.37.1", + "version": "1.38.0", "type": "module", "description": "a common blog interface", "main": "./dist/index.js", diff --git a/libs/zhi-blog-api/src/lib/IBlogApi.ts b/libs/zhi-blog-api/src/lib/IBlogApi.ts index 8d2d457b..7b885233 100644 --- a/libs/zhi-blog-api/src/lib/IBlogApi.ts +++ b/libs/zhi-blog-api/src/lib/IBlogApi.ts @@ -29,6 +29,7 @@ import MediaObject from "./models/mediaObject" import CategoryInfo from "./models/categoryInfo" import Attachment from "./models/attachmentInfo" import YamlConvertAdaptor from "./yamlConvertAdaptor" +import TagInfo from "./models/tagInfo" /** * 通用博客接口 @@ -166,6 +167,11 @@ interface IBlogApi { */ getCategories(): Promise + /** + * 获取标签列表 + */ + getTags(): Promise + /** * 获取文件树列表 * diff --git a/libs/zhi-blog-api/src/lib/blogAdaptor.ts b/libs/zhi-blog-api/src/lib/blogAdaptor.ts index 8ef8d4ee..373e1e8d 100644 --- a/libs/zhi-blog-api/src/lib/blogAdaptor.ts +++ b/libs/zhi-blog-api/src/lib/blogAdaptor.ts @@ -32,6 +32,7 @@ import { simpleLogger } from "zhi-lib-base" import Attachment from "./models/attachmentInfo" import BlogApi from "./blogApi" import YamlConvertAdaptor from "./yamlConvertAdaptor" +import TagInfo from "./models/tagInfo" /** * 博客API @@ -147,6 +148,13 @@ class BlogAdaptor implements IBlogApi { return await this.apiAdaptor.deletePost(postid) } + /** + * 获取标签列表 + */ + public async getTags(): Promise { + return await this.apiAdaptor.getTags() + } + /** * 获取分类列表 */ diff --git a/libs/zhi-blog-api/src/lib/blogApi.ts b/libs/zhi-blog-api/src/lib/blogApi.ts index 44085820..ccd393cc 100644 --- a/libs/zhi-blog-api/src/lib/blogApi.ts +++ b/libs/zhi-blog-api/src/lib/blogApi.ts @@ -31,6 +31,7 @@ import MediaObject from "./models/mediaObject" import { NotImplementedException } from "zhi-lib-base" import Attachment from "./models/attachmentInfo" import YamlConvertAdaptor from "./yamlConvertAdaptor" +import TagInfo from "./models/tagInfo" /** * 博客基类 @@ -72,6 +73,10 @@ class BlogApi implements IBlogApi { throw new NotImplementedException("You must implement getCategories in sub class") } + getTags(): Promise { + throw new NotImplementedException("You must implement getTags in sub class") + } + public async getCategoryTreeNodes(docPath: string): Promise { throw new NotImplementedException("You must implement getCategoryTreeNodes in sub class") } diff --git a/libs/zhi-blog-api/src/lib/models/tagInfo.ts b/libs/zhi-blog-api/src/lib/models/tagInfo.ts new file mode 100644 index 00000000..c27eae86 --- /dev/null +++ b/libs/zhi-blog-api/src/lib/models/tagInfo.ts @@ -0,0 +1,61 @@ +/* + * Copyright (c) 2023, Terwer . All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Terwer designates this + * particular file as subject to the "Classpath" exception as provided + * by Terwer in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Terwer, Shenzhen, Guangdong, China, youweics@163.com + * or visit www.terwer.space if you need additional information or have any + * questions. + */ + +class TagInfo { + /** + * 标签ID + */ + tagId: string + + /** + * 父标签ID + */ + parentId: string + + /** + * 标签名称 + */ + description: string + + /** + * 标签描述 + */ + tagDescription: string + + /** + * 标签英文名 + */ + tagName: string + + constructor() { + this.tagId = "-1" + this.parentId = "0" + this.description = "标签1" + this.tagDescription = "这是测试标签1" + this.tagName = "cate1" + } +} + +export default TagInfo diff --git a/libs/zhi-siyuan-api/CHANGELOG.md b/libs/zhi-siyuan-api/CHANGELOG.md index e1ca0187..2baf2000 100644 --- a/libs/zhi-siyuan-api/CHANGELOG.md +++ b/libs/zhi-siyuan-api/CHANGELOG.md @@ -1,5 +1,12 @@ # zhi-siyuan-api +## 2.9.3 + +### Patch Changes + +- Updated dependencies + - zhi-blog-api@1.38.0 + ## 2.9.2 ### Patch Changes diff --git a/libs/zhi-siyuan-api/package.json b/libs/zhi-siyuan-api/package.json index 249cbad9..50361b19 100644 --- a/libs/zhi-siyuan-api/package.json +++ b/libs/zhi-siyuan-api/package.json @@ -1,6 +1,6 @@ { "name": "zhi-siyuan-api", - "version": "2.9.2", + "version": "2.9.3", "type": "module", "description": "a siyuan-note api including both kernel and client", "main": "./dist/index.js", From 0d7cb857d2d9d8af13f37be731ca99ddf72f230b Mon Sep 17 00:00:00 2001 From: terwer Date: Fri, 8 Sep 2023 11:14:36 +0800 Subject: [PATCH 15/30] feat: export TagInfo --- libs/zhi-blog-api/CHANGELOG.md | 6 ++++++ libs/zhi-blog-api/package.json | 2 +- libs/zhi-blog-api/src/index.ts | 3 ++- libs/zhi-siyuan-api/CHANGELOG.md | 7 +++++++ libs/zhi-siyuan-api/package.json | 2 +- 5 files changed, 17 insertions(+), 3 deletions(-) diff --git a/libs/zhi-blog-api/CHANGELOG.md b/libs/zhi-blog-api/CHANGELOG.md index e37fcb27..b1d7f0f2 100644 --- a/libs/zhi-blog-api/CHANGELOG.md +++ b/libs/zhi-blog-api/CHANGELOG.md @@ -1,5 +1,11 @@ # zhi-blog-api +## 1.39.0 + +### Minor Changes + +- feat: export TagInfo + ## 1.38.0 ### Minor Changes diff --git a/libs/zhi-blog-api/package.json b/libs/zhi-blog-api/package.json index 97f59bf1..4d00105f 100644 --- a/libs/zhi-blog-api/package.json +++ b/libs/zhi-blog-api/package.json @@ -1,6 +1,6 @@ { "name": "zhi-blog-api", - "version": "1.38.0", + "version": "1.39.0", "type": "module", "description": "a common blog interface", "main": "./dist/index.js", diff --git a/libs/zhi-blog-api/src/index.ts b/libs/zhi-blog-api/src/index.ts index b6764a27..cccec8e4 100644 --- a/libs/zhi-blog-api/src/index.ts +++ b/libs/zhi-blog-api/src/index.ts @@ -22,12 +22,13 @@ import YamlFormatObj from "./lib/models/yamlFormatObj" import YamlConvertAdaptor from "./lib/yamlConvertAdaptor" import PreferenceConfig from "./lib/PreferenceConfig" import PostUtil from "./lib/PostUtil" +import TagInfo from "./lib/models/tagInfo" export { BlogApi, BlogAdaptor } export { WebApi, WebAdaptor } export { BlogConfig, BlogPlaceholder, PasswordType, PageType, PostStatusEnum } export { WebConfig, WebPlaceholder } -export { Post, UserBlog, SiteConfig, CategoryInfo, MediaObject, Attachment } +export { Post, UserBlog, SiteConfig, CategoryInfo, TagInfo, MediaObject, Attachment } export { BlogConstants, BlogTypeEnum, PageTypeEnum, CategoryTypeEnum } export { YamlFormatObj, YamlConvertAdaptor } export { PostUtil } diff --git a/libs/zhi-siyuan-api/CHANGELOG.md b/libs/zhi-siyuan-api/CHANGELOG.md index 2baf2000..b34cb830 100644 --- a/libs/zhi-siyuan-api/CHANGELOG.md +++ b/libs/zhi-siyuan-api/CHANGELOG.md @@ -1,5 +1,12 @@ # zhi-siyuan-api +## 2.9.4 + +### Patch Changes + +- Updated dependencies + - zhi-blog-api@1.39.0 + ## 2.9.3 ### Patch Changes diff --git a/libs/zhi-siyuan-api/package.json b/libs/zhi-siyuan-api/package.json index 50361b19..272ca30b 100644 --- a/libs/zhi-siyuan-api/package.json +++ b/libs/zhi-siyuan-api/package.json @@ -1,6 +1,6 @@ { "name": "zhi-siyuan-api", - "version": "2.9.3", + "version": "2.9.4", "type": "module", "description": "a siyuan-note api including both kernel and client", "main": "./dist/index.js", From 0d9c0efca5c17b4c031cca3168752b9b455c776a Mon Sep 17 00:00:00 2001 From: terwer Date: Mon, 11 Sep 2023 17:50:43 +0800 Subject: [PATCH 16/30] feat: add mdFilename --- libs/zhi-blog-api/CHANGELOG.md | 6 ++++++ libs/zhi-blog-api/package.json | 2 +- libs/zhi-blog-api/src/lib/models/post.ts | 6 ++++++ libs/zhi-siyuan-api/CHANGELOG.md | 7 +++++++ libs/zhi-siyuan-api/package.json | 2 +- 5 files changed, 21 insertions(+), 2 deletions(-) diff --git a/libs/zhi-blog-api/CHANGELOG.md b/libs/zhi-blog-api/CHANGELOG.md index b1d7f0f2..c19b3f37 100644 --- a/libs/zhi-blog-api/CHANGELOG.md +++ b/libs/zhi-blog-api/CHANGELOG.md @@ -1,5 +1,11 @@ # zhi-blog-api +## 1.40.0 + +### Minor Changes + +- feat: add mdFilename + ## 1.39.0 ### Minor Changes diff --git a/libs/zhi-blog-api/package.json b/libs/zhi-blog-api/package.json index 4d00105f..f8cf7ece 100644 --- a/libs/zhi-blog-api/package.json +++ b/libs/zhi-blog-api/package.json @@ -1,6 +1,6 @@ { "name": "zhi-blog-api", - "version": "1.39.0", + "version": "1.40.0", "type": "module", "description": "a common blog interface", "main": "./dist/index.js", diff --git a/libs/zhi-blog-api/src/lib/models/post.ts b/libs/zhi-blog-api/src/lib/models/post.ts index 12f5013f..cb1a2880 100644 --- a/libs/zhi-blog-api/src/lib/models/post.ts +++ b/libs/zhi-blog-api/src/lib/models/post.ts @@ -62,6 +62,11 @@ class Post { */ yaml: string + /** + * MD 文件名,不包括 .md + */ + mdFilename?: string + /** * HTML正文 */ @@ -152,6 +157,7 @@ class Post { this.title = "" this.permalink = "" this.yaml = "---\n---" + this.mdFilename = "test" this.html = "" this.markdown = "" this.editorDom = "" diff --git a/libs/zhi-siyuan-api/CHANGELOG.md b/libs/zhi-siyuan-api/CHANGELOG.md index b34cb830..224557f4 100644 --- a/libs/zhi-siyuan-api/CHANGELOG.md +++ b/libs/zhi-siyuan-api/CHANGELOG.md @@ -1,5 +1,12 @@ # zhi-siyuan-api +## 2.9.5 + +### Patch Changes + +- Updated dependencies + - zhi-blog-api@1.40.0 + ## 2.9.4 ### Patch Changes diff --git a/libs/zhi-siyuan-api/package.json b/libs/zhi-siyuan-api/package.json index 272ca30b..67eda51b 100644 --- a/libs/zhi-siyuan-api/package.json +++ b/libs/zhi-siyuan-api/package.json @@ -1,6 +1,6 @@ { "name": "zhi-siyuan-api", - "version": "2.9.4", + "version": "2.9.5", "type": "module", "description": "a siyuan-note api including both kernel and client", "main": "./dist/index.js", From 1e4caacecc666c861a32e9f21308e9483d969aad Mon Sep 17 00:00:00 2001 From: terwer Date: Mon, 11 Sep 2023 20:03:33 +0800 Subject: [PATCH 17/30] feat: add useMdFilename --- libs/zhi-blog-api/CHANGELOG.md | 6 ++++++ libs/zhi-blog-api/package.json | 2 +- libs/zhi-blog-api/src/lib/blogConfig.ts | 6 ++++++ libs/zhi-blog-api/src/lib/models/post.ts | 6 ------ libs/zhi-siyuan-api/CHANGELOG.md | 7 +++++++ libs/zhi-siyuan-api/package.json | 2 +- 6 files changed, 21 insertions(+), 8 deletions(-) diff --git a/libs/zhi-blog-api/CHANGELOG.md b/libs/zhi-blog-api/CHANGELOG.md index c19b3f37..4ca72f82 100644 --- a/libs/zhi-blog-api/CHANGELOG.md +++ b/libs/zhi-blog-api/CHANGELOG.md @@ -1,5 +1,11 @@ # zhi-blog-api +## 1.41.0 + +### Minor Changes + +- feat: add useMdFilename + ## 1.40.0 ### Minor Changes diff --git a/libs/zhi-blog-api/package.json b/libs/zhi-blog-api/package.json index f8cf7ece..5b9b14ce 100644 --- a/libs/zhi-blog-api/package.json +++ b/libs/zhi-blog-api/package.json @@ -1,6 +1,6 @@ { "name": "zhi-blog-api", - "version": "1.40.0", + "version": "1.41.0", "type": "module", "description": "a common blog interface", "main": "./dist/index.js", diff --git a/libs/zhi-blog-api/src/lib/blogConfig.ts b/libs/zhi-blog-api/src/lib/blogConfig.ts index c9276fcd..f2a9a8ed 100644 --- a/libs/zhi-blog-api/src/lib/blogConfig.ts +++ b/libs/zhi-blog-api/src/lib/blogConfig.ts @@ -234,6 +234,11 @@ abstract class BlogConfig { */ public tagSlugEnabled: boolean + /** + * 是否使用标题作为MD 文件名 + */ + useMdFilename?: boolean + protected constructor() { this.home = "" this.apiUrl = "" @@ -263,6 +268,7 @@ abstract class BlogConfig { this.categoryType = CategoryTypeEnum.CategoryType_None this.yamlLinkEnabled = true this.tagSlugEnabled = false + this.useMdFilename = false } } diff --git a/libs/zhi-blog-api/src/lib/models/post.ts b/libs/zhi-blog-api/src/lib/models/post.ts index cb1a2880..12f5013f 100644 --- a/libs/zhi-blog-api/src/lib/models/post.ts +++ b/libs/zhi-blog-api/src/lib/models/post.ts @@ -62,11 +62,6 @@ class Post { */ yaml: string - /** - * MD 文件名,不包括 .md - */ - mdFilename?: string - /** * HTML正文 */ @@ -157,7 +152,6 @@ class Post { this.title = "" this.permalink = "" this.yaml = "---\n---" - this.mdFilename = "test" this.html = "" this.markdown = "" this.editorDom = "" diff --git a/libs/zhi-siyuan-api/CHANGELOG.md b/libs/zhi-siyuan-api/CHANGELOG.md index 224557f4..90451335 100644 --- a/libs/zhi-siyuan-api/CHANGELOG.md +++ b/libs/zhi-siyuan-api/CHANGELOG.md @@ -1,5 +1,12 @@ # zhi-siyuan-api +## 2.9.6 + +### Patch Changes + +- Updated dependencies + - zhi-blog-api@1.41.0 + ## 2.9.5 ### Patch Changes diff --git a/libs/zhi-siyuan-api/package.json b/libs/zhi-siyuan-api/package.json index 67eda51b..c409eec4 100644 --- a/libs/zhi-siyuan-api/package.json +++ b/libs/zhi-siyuan-api/package.json @@ -1,6 +1,6 @@ { "name": "zhi-siyuan-api", - "version": "2.9.5", + "version": "2.9.6", "type": "module", "description": "a siyuan-note api including both kernel and client", "main": "./dist/index.js", From 6ea9d166a0feccf621ff0ba7eacc219c34234878 Mon Sep 17 00:00:00 2001 From: terwer Date: Mon, 11 Sep 2023 20:33:58 +0800 Subject: [PATCH 18/30] feat: add usePathCategory --- libs/zhi-blog-api/CHANGELOG.md | 6 ++++++ libs/zhi-blog-api/package.json | 2 +- libs/zhi-blog-api/src/lib/blogConfig.ts | 6 ++++++ libs/zhi-siyuan-api/CHANGELOG.md | 7 +++++++ libs/zhi-siyuan-api/package.json | 2 +- 5 files changed, 21 insertions(+), 2 deletions(-) diff --git a/libs/zhi-blog-api/CHANGELOG.md b/libs/zhi-blog-api/CHANGELOG.md index 4ca72f82..a42ac5e7 100644 --- a/libs/zhi-blog-api/CHANGELOG.md +++ b/libs/zhi-blog-api/CHANGELOG.md @@ -1,5 +1,11 @@ # zhi-blog-api +## 1.42.0 + +### Minor Changes + +- feat: add usePathCategory + ## 1.41.0 ### Minor Changes diff --git a/libs/zhi-blog-api/package.json b/libs/zhi-blog-api/package.json index 5b9b14ce..99f8ffe4 100644 --- a/libs/zhi-blog-api/package.json +++ b/libs/zhi-blog-api/package.json @@ -1,6 +1,6 @@ { "name": "zhi-blog-api", - "version": "1.41.0", + "version": "1.42.0", "type": "module", "description": "a common blog interface", "main": "./dist/index.js", diff --git a/libs/zhi-blog-api/src/lib/blogConfig.ts b/libs/zhi-blog-api/src/lib/blogConfig.ts index f2a9a8ed..7472095b 100644 --- a/libs/zhi-blog-api/src/lib/blogConfig.ts +++ b/libs/zhi-blog-api/src/lib/blogConfig.ts @@ -239,6 +239,11 @@ abstract class BlogConfig { */ useMdFilename?: boolean + /** + * 是否使用路径作为分类 + */ + usePathCategory?: boolean + protected constructor() { this.home = "" this.apiUrl = "" @@ -269,6 +274,7 @@ abstract class BlogConfig { this.yamlLinkEnabled = true this.tagSlugEnabled = false this.useMdFilename = false + this.usePathCategory = false } } diff --git a/libs/zhi-siyuan-api/CHANGELOG.md b/libs/zhi-siyuan-api/CHANGELOG.md index 90451335..26eda82f 100644 --- a/libs/zhi-siyuan-api/CHANGELOG.md +++ b/libs/zhi-siyuan-api/CHANGELOG.md @@ -1,5 +1,12 @@ # zhi-siyuan-api +## 2.9.7 + +### Patch Changes + +- Updated dependencies + - zhi-blog-api@1.42.0 + ## 2.9.6 ### Patch Changes diff --git a/libs/zhi-siyuan-api/package.json b/libs/zhi-siyuan-api/package.json index c409eec4..417d6eeb 100644 --- a/libs/zhi-siyuan-api/package.json +++ b/libs/zhi-siyuan-api/package.json @@ -1,6 +1,6 @@ { "name": "zhi-siyuan-api", - "version": "2.9.6", + "version": "2.9.7", "type": "module", "description": "a siyuan-note api including both kernel and client", "main": "./dist/index.js", From bb764800906c1273c3187f1ca24558cfd237c717 Mon Sep 17 00:00:00 2001 From: terwer Date: Mon, 11 Sep 2023 21:44:15 +0800 Subject: [PATCH 19/30] feat: add mdFilename --- libs/zhi-blog-api/CHANGELOG.md | 6 ++++++ libs/zhi-blog-api/package.json | 2 +- libs/zhi-blog-api/src/lib/models/post.ts | 6 ++++++ libs/zhi-siyuan-api/CHANGELOG.md | 7 +++++++ libs/zhi-siyuan-api/package.json | 2 +- 5 files changed, 21 insertions(+), 2 deletions(-) diff --git a/libs/zhi-blog-api/CHANGELOG.md b/libs/zhi-blog-api/CHANGELOG.md index a42ac5e7..dcfe027a 100644 --- a/libs/zhi-blog-api/CHANGELOG.md +++ b/libs/zhi-blog-api/CHANGELOG.md @@ -1,5 +1,11 @@ # zhi-blog-api +## 1.43.0 + +### Minor Changes + +- feat: add mdFilename + ## 1.42.0 ### Minor Changes diff --git a/libs/zhi-blog-api/package.json b/libs/zhi-blog-api/package.json index 99f8ffe4..e2540b4d 100644 --- a/libs/zhi-blog-api/package.json +++ b/libs/zhi-blog-api/package.json @@ -1,6 +1,6 @@ { "name": "zhi-blog-api", - "version": "1.42.0", + "version": "1.43.0", "type": "module", "description": "a common blog interface", "main": "./dist/index.js", diff --git a/libs/zhi-blog-api/src/lib/models/post.ts b/libs/zhi-blog-api/src/lib/models/post.ts index 12f5013f..cb1a2880 100644 --- a/libs/zhi-blog-api/src/lib/models/post.ts +++ b/libs/zhi-blog-api/src/lib/models/post.ts @@ -62,6 +62,11 @@ class Post { */ yaml: string + /** + * MD 文件名,不包括 .md + */ + mdFilename?: string + /** * HTML正文 */ @@ -152,6 +157,7 @@ class Post { this.title = "" this.permalink = "" this.yaml = "---\n---" + this.mdFilename = "test" this.html = "" this.markdown = "" this.editorDom = "" diff --git a/libs/zhi-siyuan-api/CHANGELOG.md b/libs/zhi-siyuan-api/CHANGELOG.md index 26eda82f..56f7cbf9 100644 --- a/libs/zhi-siyuan-api/CHANGELOG.md +++ b/libs/zhi-siyuan-api/CHANGELOG.md @@ -1,5 +1,12 @@ # zhi-siyuan-api +## 2.9.8 + +### Patch Changes + +- Updated dependencies + - zhi-blog-api@1.43.0 + ## 2.9.7 ### Patch Changes diff --git a/libs/zhi-siyuan-api/package.json b/libs/zhi-siyuan-api/package.json index 417d6eeb..18a906cc 100644 --- a/libs/zhi-siyuan-api/package.json +++ b/libs/zhi-siyuan-api/package.json @@ -1,6 +1,6 @@ { "name": "zhi-siyuan-api", - "version": "2.9.7", + "version": "2.9.8", "type": "module", "description": "a siyuan-note api including both kernel and client", "main": "./dist/index.js", From eba9dd67d44cb29fd9a5435949a8ce4c7efcfa43 Mon Sep 17 00:00:00 2001 From: terwer Date: Mon, 18 Sep 2023 21:01:09 +0800 Subject: [PATCH 20/30] feat: add search option --- libs/zhi-blog-api/CHANGELOG.md | 12 ++++++++++++ libs/zhi-blog-api/package.json | 2 +- libs/zhi-blog-api/src/lib/IBlogApi.ts | 3 ++- libs/zhi-blog-api/src/lib/blogAdaptor.ts | 4 ++-- libs/zhi-blog-api/src/lib/blogApi.ts | 2 +- libs/zhi-blog-api/src/lib/blogConfig.ts | 6 ++++++ libs/zhi-siyuan-api/CHANGELOG.md | 19 +++++++++++++++++++ libs/zhi-siyuan-api/package.json | 2 +- .../src/lib/adaptor/siYuanApiAdaptor.ts | 2 +- 9 files changed, 45 insertions(+), 7 deletions(-) diff --git a/libs/zhi-blog-api/CHANGELOG.md b/libs/zhi-blog-api/CHANGELOG.md index dcfe027a..881c443d 100644 --- a/libs/zhi-blog-api/CHANGELOG.md +++ b/libs/zhi-blog-api/CHANGELOG.md @@ -1,5 +1,17 @@ # zhi-blog-api +## 1.44.1 + +### Patch Changes + +- fix: add search option + +## 1.44.0 + +### Minor Changes + +- feat: add search for getCategories + ## 1.43.0 ### Minor Changes diff --git a/libs/zhi-blog-api/package.json b/libs/zhi-blog-api/package.json index e2540b4d..764df570 100644 --- a/libs/zhi-blog-api/package.json +++ b/libs/zhi-blog-api/package.json @@ -1,6 +1,6 @@ { "name": "zhi-blog-api", - "version": "1.43.0", + "version": "1.44.1", "type": "module", "description": "a common blog interface", "main": "./dist/index.js", diff --git a/libs/zhi-blog-api/src/lib/IBlogApi.ts b/libs/zhi-blog-api/src/lib/IBlogApi.ts index 7b885233..fc6efa5e 100644 --- a/libs/zhi-blog-api/src/lib/IBlogApi.ts +++ b/libs/zhi-blog-api/src/lib/IBlogApi.ts @@ -162,10 +162,11 @@ interface IBlogApi { /** * 获取分类列表 * + * @param keyword - 搜索关键字,部分平台不支持 * @see {@link https://codex.wordpress.org/XML-RPC_MetaWeblog_API#metaWeblog.getCategories getCategories} * @returns {Promise} */ - getCategories(): Promise + getCategories(keyword?: string): Promise /** * 获取标签列表 diff --git a/libs/zhi-blog-api/src/lib/blogAdaptor.ts b/libs/zhi-blog-api/src/lib/blogAdaptor.ts index 373e1e8d..4559c3df 100644 --- a/libs/zhi-blog-api/src/lib/blogAdaptor.ts +++ b/libs/zhi-blog-api/src/lib/blogAdaptor.ts @@ -158,8 +158,8 @@ class BlogAdaptor implements IBlogApi { /** * 获取分类列表 */ - public async getCategories(): Promise { - return await this.apiAdaptor.getCategories() + public async getCategories(keyword?: string): Promise { + return await this.apiAdaptor.getCategories(keyword) } /** diff --git a/libs/zhi-blog-api/src/lib/blogApi.ts b/libs/zhi-blog-api/src/lib/blogApi.ts index ccd393cc..167ae075 100644 --- a/libs/zhi-blog-api/src/lib/blogApi.ts +++ b/libs/zhi-blog-api/src/lib/blogApi.ts @@ -69,7 +69,7 @@ class BlogApi implements IBlogApi { throw new NotImplementedException("You must implement deletePost in sub class") } - public async getCategories(): Promise { + public async getCategories(keyword?: string): Promise { throw new NotImplementedException("You must implement getCategories in sub class") } diff --git a/libs/zhi-blog-api/src/lib/blogConfig.ts b/libs/zhi-blog-api/src/lib/blogConfig.ts index 7472095b..85cb36b5 100644 --- a/libs/zhi-blog-api/src/lib/blogConfig.ts +++ b/libs/zhi-blog-api/src/lib/blogConfig.ts @@ -244,6 +244,11 @@ abstract class BlogConfig { */ usePathCategory?: boolean + /** + * 是否允许分类搜索 + */ + public cateSearchEnabled?: boolean + protected constructor() { this.home = "" this.apiUrl = "" @@ -275,6 +280,7 @@ abstract class BlogConfig { this.tagSlugEnabled = false this.useMdFilename = false this.usePathCategory = false + this.cateSearchEnabled = false } } diff --git a/libs/zhi-siyuan-api/CHANGELOG.md b/libs/zhi-siyuan-api/CHANGELOG.md index 56f7cbf9..c4a7cdf8 100644 --- a/libs/zhi-siyuan-api/CHANGELOG.md +++ b/libs/zhi-siyuan-api/CHANGELOG.md @@ -1,5 +1,24 @@ # zhi-siyuan-api +## 2.10.1 + +### Patch Changes + +- fix: add search option +- Updated dependencies + - zhi-blog-api@1.44.1 + +## 2.10.0 + +### Minor Changes + +- feat: add search for getCategories + +### Patch Changes + +- Updated dependencies + - zhi-blog-api@1.44.0 + ## 2.9.8 ### Patch Changes diff --git a/libs/zhi-siyuan-api/package.json b/libs/zhi-siyuan-api/package.json index 18a906cc..572666f5 100644 --- a/libs/zhi-siyuan-api/package.json +++ b/libs/zhi-siyuan-api/package.json @@ -1,6 +1,6 @@ { "name": "zhi-siyuan-api", - "version": "2.9.8", + "version": "2.10.1", "type": "module", "description": "a siyuan-note api including both kernel and client", "main": "./dist/index.js", diff --git a/libs/zhi-siyuan-api/src/lib/adaptor/siYuanApiAdaptor.ts b/libs/zhi-siyuan-api/src/lib/adaptor/siYuanApiAdaptor.ts index e703d236..d2bac202 100644 --- a/libs/zhi-siyuan-api/src/lib/adaptor/siYuanApiAdaptor.ts +++ b/libs/zhi-siyuan-api/src/lib/adaptor/siYuanApiAdaptor.ts @@ -256,7 +256,7 @@ class SiYuanApiAdaptor extends BlogApi { return true } - public override async getCategories(): Promise { + public override async getCategories(keyword?: string): Promise { const cats = [] as CategoryInfo[] const notes = (await this.siyuanKernelApi.lsNotebooks()) as any From a6b7e7837e4a869e0f824cf98ab800fd3dc462c5 Mon Sep 17 00:00:00 2001 From: terwer Date: Mon, 18 Sep 2023 22:04:08 +0800 Subject: [PATCH 21/30] fix: add search --- libs/zhi-blog-api/CHANGELOG.md | 6 ++++++ libs/zhi-blog-api/package.json | 2 +- libs/zhi-blog-api/src/lib/IBlogApi.ts | 4 +++- libs/zhi-blog-api/src/lib/blogAdaptor.ts | 4 ++-- libs/zhi-blog-api/src/lib/blogApi.ts | 2 +- libs/zhi-siyuan-api/CHANGELOG.md | 8 ++++++++ libs/zhi-siyuan-api/package.json | 2 +- libs/zhi-siyuan-api/src/lib/adaptor/siYuanApiAdaptor.ts | 2 +- 8 files changed, 23 insertions(+), 7 deletions(-) diff --git a/libs/zhi-blog-api/CHANGELOG.md b/libs/zhi-blog-api/CHANGELOG.md index 881c443d..5bdbdcb2 100644 --- a/libs/zhi-blog-api/CHANGELOG.md +++ b/libs/zhi-blog-api/CHANGELOG.md @@ -1,5 +1,11 @@ # zhi-blog-api +## 1.44.2 + +### Patch Changes + +- fix: add search + ## 1.44.1 ### Patch Changes diff --git a/libs/zhi-blog-api/package.json b/libs/zhi-blog-api/package.json index 764df570..1ad45317 100644 --- a/libs/zhi-blog-api/package.json +++ b/libs/zhi-blog-api/package.json @@ -1,6 +1,6 @@ { "name": "zhi-blog-api", - "version": "1.44.1", + "version": "1.44.2", "type": "module", "description": "a common blog interface", "main": "./dist/index.js", diff --git a/libs/zhi-blog-api/src/lib/IBlogApi.ts b/libs/zhi-blog-api/src/lib/IBlogApi.ts index fc6efa5e..b4776f3d 100644 --- a/libs/zhi-blog-api/src/lib/IBlogApi.ts +++ b/libs/zhi-blog-api/src/lib/IBlogApi.ts @@ -43,10 +43,12 @@ import TagInfo from "./models/tagInfo" interface IBlogApi { /** * 博客配置列表 + * + * @param keyword - 搜索关键字,部分平台不支持 * @see {@link https://codex.wordpress.org/XML-RPC_MetaWeblog_API#metaWeblog.getUsersBlogs getUsersBlogs} * @returns {Promise>} */ - getUsersBlogs(): Promise> + getUsersBlogs(keyword?: string): Promise> /** * 最新文章数目 diff --git a/libs/zhi-blog-api/src/lib/blogAdaptor.ts b/libs/zhi-blog-api/src/lib/blogAdaptor.ts index 4559c3df..85720f07 100644 --- a/libs/zhi-blog-api/src/lib/blogAdaptor.ts +++ b/libs/zhi-blog-api/src/lib/blogAdaptor.ts @@ -64,8 +64,8 @@ class BlogAdaptor implements IBlogApi { /** * 博客配置列表 */ - public async getUsersBlogs(): Promise> { - return await this.apiAdaptor.getUsersBlogs() + public async getUsersBlogs(keyword?: string): Promise> { + return await this.apiAdaptor.getUsersBlogs(keyword) } /** diff --git a/libs/zhi-blog-api/src/lib/blogApi.ts b/libs/zhi-blog-api/src/lib/blogApi.ts index 167ae075..306e0f60 100644 --- a/libs/zhi-blog-api/src/lib/blogApi.ts +++ b/libs/zhi-blog-api/src/lib/blogApi.ts @@ -37,7 +37,7 @@ import TagInfo from "./models/tagInfo" * 博客基类 */ class BlogApi implements IBlogApi { - public async getUsersBlogs(): Promise> { + public async getUsersBlogs(keyword?: string): Promise> { throw new NotImplementedException("You must implement getUsersBlogs in sub class") } diff --git a/libs/zhi-siyuan-api/CHANGELOG.md b/libs/zhi-siyuan-api/CHANGELOG.md index c4a7cdf8..a27f43d1 100644 --- a/libs/zhi-siyuan-api/CHANGELOG.md +++ b/libs/zhi-siyuan-api/CHANGELOG.md @@ -1,5 +1,13 @@ # zhi-siyuan-api +## 2.10.2 + +### Patch Changes + +- fix: add search +- Updated dependencies + - zhi-blog-api@1.44.2 + ## 2.10.1 ### Patch Changes diff --git a/libs/zhi-siyuan-api/package.json b/libs/zhi-siyuan-api/package.json index 572666f5..da4305d4 100644 --- a/libs/zhi-siyuan-api/package.json +++ b/libs/zhi-siyuan-api/package.json @@ -1,6 +1,6 @@ { "name": "zhi-siyuan-api", - "version": "2.10.1", + "version": "2.10.2", "type": "module", "description": "a siyuan-note api including both kernel and client", "main": "./dist/index.js", diff --git a/libs/zhi-siyuan-api/src/lib/adaptor/siYuanApiAdaptor.ts b/libs/zhi-siyuan-api/src/lib/adaptor/siYuanApiAdaptor.ts index d2bac202..1f3bd8a4 100644 --- a/libs/zhi-siyuan-api/src/lib/adaptor/siYuanApiAdaptor.ts +++ b/libs/zhi-siyuan-api/src/lib/adaptor/siYuanApiAdaptor.ts @@ -57,7 +57,7 @@ class SiYuanApiAdaptor extends BlogApi { this.siyuanKernelApi = new SiyuanKernelApi(cfg) } - public override async getUsersBlogs(): Promise> { + public override async getUsersBlogs(keyword?: string): Promise> { const usersBlogs: UserBlog[] = [] const userBlog = new UserBlog() From e0ca07b930e4cd03b777e772dc0cbb2982f07c87 Mon Sep 17 00:00:00 2001 From: terwer Date: Wed, 20 Sep 2023 10:43:09 +0800 Subject: [PATCH 22/30] fix: change yaml regex --- libs/zhi-blog-api/CHANGELOG.md | 7 +++++++ libs/zhi-blog-api/package.json | 2 +- libs/zhi-common/CHANGELOG.md | 6 ++++++ libs/zhi-common/package.json | 2 +- libs/zhi-common/src/lib/yamlUtil.ts | 2 +- libs/zhi-fetch-middleware/CHANGELOG.md | 7 +++++++ libs/zhi-fetch-middleware/package.json | 2 +- libs/zhi-github-middleware/CHANGELOG.md | 7 +++++++ libs/zhi-github-middleware/package.json | 2 +- libs/zhi-gitlab-middleware/CHANGELOG.md | 6 ++++++ libs/zhi-gitlab-middleware/package.json | 2 +- libs/zhi-siyuan-api/CHANGELOG.md | 8 ++++++++ libs/zhi-siyuan-api/package.json | 2 +- libs/zhi-xmlrpc-middleware/CHANGELOG.md | 7 +++++++ libs/zhi-xmlrpc-middleware/package.json | 2 +- 15 files changed, 56 insertions(+), 8 deletions(-) diff --git a/libs/zhi-blog-api/CHANGELOG.md b/libs/zhi-blog-api/CHANGELOG.md index 5bdbdcb2..f09b38f4 100644 --- a/libs/zhi-blog-api/CHANGELOG.md +++ b/libs/zhi-blog-api/CHANGELOG.md @@ -1,5 +1,12 @@ # zhi-blog-api +## 1.44.3 + +### Patch Changes + +- Updated dependencies + - zhi-common@1.24.0 + ## 1.44.2 ### Patch Changes diff --git a/libs/zhi-blog-api/package.json b/libs/zhi-blog-api/package.json index 1ad45317..719e5a92 100644 --- a/libs/zhi-blog-api/package.json +++ b/libs/zhi-blog-api/package.json @@ -1,6 +1,6 @@ { "name": "zhi-blog-api", - "version": "1.44.2", + "version": "1.44.3", "type": "module", "description": "a common blog interface", "main": "./dist/index.js", diff --git a/libs/zhi-common/CHANGELOG.md b/libs/zhi-common/CHANGELOG.md index d6e4c02d..eea07fd5 100644 --- a/libs/zhi-common/CHANGELOG.md +++ b/libs/zhi-common/CHANGELOG.md @@ -1,5 +1,11 @@ # zhi-common +## 1.24.0 + +### Minor Changes + +- fix: change yaml regex + ## 1.23.7 ### Patch Changes diff --git a/libs/zhi-common/package.json b/libs/zhi-common/package.json index a3a2ace4..e3ff35a3 100644 --- a/libs/zhi-common/package.json +++ b/libs/zhi-common/package.json @@ -1,6 +1,6 @@ { "name": "zhi-common", - "version": "1.23.7", + "version": "1.24.0", "type": "module", "description": "a collection of util tools", "main": "./dist/index.js", diff --git a/libs/zhi-common/src/lib/yamlUtil.ts b/libs/zhi-common/src/lib/yamlUtil.ts index 45f65199..dbd9422d 100644 --- a/libs/zhi-common/src/lib/yamlUtil.ts +++ b/libs/zhi-common/src/lib/yamlUtil.ts @@ -35,7 +35,7 @@ import { simpleLogger } from "zhi-lib-base" */ class YamlUtil { private static logger = simpleLogger("yaml-util") - private static YAML_REGEX = /---\n([\s\S]*?\n)---/ + private static YAML_REGEX = /^-{3}\n([\s\S]*?\n)-{3}/ /** * yaml转对象 diff --git a/libs/zhi-fetch-middleware/CHANGELOG.md b/libs/zhi-fetch-middleware/CHANGELOG.md index 1d62a077..92337731 100644 --- a/libs/zhi-fetch-middleware/CHANGELOG.md +++ b/libs/zhi-fetch-middleware/CHANGELOG.md @@ -1,5 +1,12 @@ # zhi-fetch-middleware +## 0.6.5 + +### Patch Changes + +- Updated dependencies + - zhi-common@1.24.0 + ## 0.6.4 ### Patch Changes diff --git a/libs/zhi-fetch-middleware/package.json b/libs/zhi-fetch-middleware/package.json index e48e481d..46ad96d3 100644 --- a/libs/zhi-fetch-middleware/package.json +++ b/libs/zhi-fetch-middleware/package.json @@ -1,6 +1,6 @@ { "name": "zhi-fetch-middleware", - "version": "0.6.4", + "version": "0.6.5", "type": "module", "description": "an intermediate tier prepared for fetch requests", "main": "./dist/index.js", diff --git a/libs/zhi-github-middleware/CHANGELOG.md b/libs/zhi-github-middleware/CHANGELOG.md index 1785e015..ce536ea6 100644 --- a/libs/zhi-github-middleware/CHANGELOG.md +++ b/libs/zhi-github-middleware/CHANGELOG.md @@ -1,5 +1,12 @@ # zhi-github-middleware +## 0.4.3 + +### Patch Changes + +- Updated dependencies + - zhi-common@1.24.0 + ## 0.4.2 ### Patch Changes diff --git a/libs/zhi-github-middleware/package.json b/libs/zhi-github-middleware/package.json index 5eeec8ae..83c8e0a0 100644 --- a/libs/zhi-github-middleware/package.json +++ b/libs/zhi-github-middleware/package.json @@ -1,6 +1,6 @@ { "name": "zhi-github-middleware", - "version": "0.4.2", + "version": "0.4.3", "type": "module", "description": "a middleware for github api", "main": "./dist/index.js", diff --git a/libs/zhi-gitlab-middleware/CHANGELOG.md b/libs/zhi-gitlab-middleware/CHANGELOG.md index 1f61713e..8838a1fb 100644 --- a/libs/zhi-gitlab-middleware/CHANGELOG.md +++ b/libs/zhi-gitlab-middleware/CHANGELOG.md @@ -1,5 +1,11 @@ # zhi-gitlab-middleware +## 0.6.5 + +### Patch Changes + +- zhi-fetch-middleware@0.6.5 + ## 0.6.4 ### Patch Changes diff --git a/libs/zhi-gitlab-middleware/package.json b/libs/zhi-gitlab-middleware/package.json index 64efc59a..837a6549 100644 --- a/libs/zhi-gitlab-middleware/package.json +++ b/libs/zhi-gitlab-middleware/package.json @@ -1,6 +1,6 @@ { "name": "zhi-gitlab-middleware", - "version": "0.6.4", + "version": "0.6.5", "type": "module", "description": "a middleware for gitlab api ", "main": "./dist/index.js", diff --git a/libs/zhi-siyuan-api/CHANGELOG.md b/libs/zhi-siyuan-api/CHANGELOG.md index a27f43d1..d3c4fb90 100644 --- a/libs/zhi-siyuan-api/CHANGELOG.md +++ b/libs/zhi-siyuan-api/CHANGELOG.md @@ -1,5 +1,13 @@ # zhi-siyuan-api +## 2.10.3 + +### Patch Changes + +- Updated dependencies + - zhi-common@1.24.0 + - zhi-blog-api@1.44.3 + ## 2.10.2 ### Patch Changes diff --git a/libs/zhi-siyuan-api/package.json b/libs/zhi-siyuan-api/package.json index da4305d4..ade86f08 100644 --- a/libs/zhi-siyuan-api/package.json +++ b/libs/zhi-siyuan-api/package.json @@ -1,6 +1,6 @@ { "name": "zhi-siyuan-api", - "version": "2.10.2", + "version": "2.10.3", "type": "module", "description": "a siyuan-note api including both kernel and client", "main": "./dist/index.js", diff --git a/libs/zhi-xmlrpc-middleware/CHANGELOG.md b/libs/zhi-xmlrpc-middleware/CHANGELOG.md index 6d405da9..11026ac0 100644 --- a/libs/zhi-xmlrpc-middleware/CHANGELOG.md +++ b/libs/zhi-xmlrpc-middleware/CHANGELOG.md @@ -1,5 +1,12 @@ # zhi-xmlrpc-middleware +## 0.5.12 + +### Patch Changes + +- Updated dependencies + - zhi-common@1.24.0 + ## 0.5.11 ### Patch Changes diff --git a/libs/zhi-xmlrpc-middleware/package.json b/libs/zhi-xmlrpc-middleware/package.json index 5ab97e56..234645c8 100644 --- a/libs/zhi-xmlrpc-middleware/package.json +++ b/libs/zhi-xmlrpc-middleware/package.json @@ -1,6 +1,6 @@ { "name": "zhi-xmlrpc-middleware", - "version": "0.5.11", + "version": "0.5.12", "type": "module", "description": "abstract xmlrpc middle layer", "main": "./dist/index.js", From 679f8cf9d857ab3ea8fc0624e780248b53ae7653 Mon Sep 17 00:00:00 2001 From: tangyw Date: Wed, 20 Sep 2023 16:31:40 +0800 Subject: [PATCH 23/30] feat: fix deps --- pnpm-lock.yaml | 87 -------------------------------------------------- 1 file changed, 87 deletions(-) diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 607d16f2..5c3ff593 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -61,50 +61,6 @@ importers: specifier: ^0.2.0 version: 0.2.0 - apps/zhi-formdata-blob-fetch: - dependencies: - node-fetch-native: - specifier: ^1.4.0 - version: 1.4.0 - zhi-lib-base: - specifier: workspace:* - version: link:../../libs/zhi-lib-base - devDependencies: - '@terwer/esbuild-config-custom': - specifier: workspace:* - version: link:../../tools/esbuild-config-custom - '@terwer/eslint-config-custom': - specifier: workspace:* - version: link:../../tools/eslint-config-custom - '@terwer/tsconfig': - specifier: workspace:* - version: link:../../tools/tsconfig - '@terwer/vitest-config-custom': - specifier: workspace:* - version: link:../../tools/vitest-config-custom - - apps/zhi-formdata-fetch: - dependencies: - node-fetch: - specifier: ^3.3.2 - version: 3.3.2 - zhi-lib-base: - specifier: workspace:* - version: link:../../libs/zhi-lib-base - devDependencies: - '@terwer/esbuild-config-custom': - specifier: workspace:* - version: link:../../tools/esbuild-config-custom - '@terwer/eslint-config-custom': - specifier: workspace:* - version: link:../../tools/eslint-config-custom - '@terwer/tsconfig': - specifier: workspace:* - version: link:../../tools/tsconfig - '@terwer/vitest-config-custom': - specifier: workspace:* - version: link:../../tools/vitest-config-custom - libs/zhi-blog-api: dependencies: zhi-common: @@ -3570,11 +3526,6 @@ packages: engines: {node: '>=8'} dev: false - /data-uri-to-buffer@4.0.1: - resolution: {integrity: sha512-0R9ikRb668HB7QDxT1vkpuUBtqc53YyAwMwGeUFKRojY/NWKvdZ+9UYtRfGmhqNbRkTSVpMbmyhXipFFv2cb/A==} - engines: {node: '>= 12'} - dev: false - /data-urls@4.0.0: resolution: {integrity: sha512-/mMTei/JXPqvFqQtfyTowxmJVwr2PVAeCcDxyFf6LhoOu/09TX2OX3kb2wzi4DMXcfj4OItwDOnhl5oziPnT6g==} engines: {node: '>=14'} @@ -4557,14 +4508,6 @@ packages: dependencies: reusify: 1.0.4 - /fetch-blob@3.2.0: - resolution: {integrity: sha512-7yAQpD2UMJzLi1Dqv7qFYnPbaPx7ZfFK6PiIxQ4PfkGPyNyl2Ugx+a/umUonmKqjhM4DnfbMvdX6otXq83soQQ==} - engines: {node: ^12.20 || >= 14.13} - dependencies: - node-domexception: 1.0.0 - web-streams-polyfill: 3.2.1 - dev: false - /figures@2.0.0: resolution: {integrity: sha512-Oa2M9atig69ZkfwiApY8F2Yy+tzMbazyvqv21R0NsSC8floSOC09BbT1ITWAdoMGQvJ/aZnR1KMwdx9tvHnTNA==} engines: {node: '>=4'} @@ -4676,13 +4619,6 @@ packages: combined-stream: 1.0.8 mime-types: 2.1.33 - /formdata-polyfill@4.0.10: - resolution: {integrity: sha512-buewHzMvYL29jdeQTVILecSaZKnt/RJWjoZCF5OW60Z67/GmSLBkOFM7qh1PI3zFNtJbaZL5eQu1vLfazOwj4g==} - engines: {node: '>=12.20.0'} - dependencies: - fetch-blob: 3.2.0 - dev: false - /fs-extra@10.1.0: resolution: {integrity: sha512-oRXApq54ETRj4eMiFzGnHWGy+zo5raudjuxN0b8H7s/RU2oW0Wvsx9O0ACRN/kRq9E8Vu/ReskGB5o3ji+FzHQ==} engines: {node: '>=12'} @@ -6287,15 +6223,6 @@ packages: resolution: {integrity: sha512-Yd3UES5mWCSqR+qNT93S3UoYUkqAZ9lLg8a7g9rimsWmYGK8cVToA4/sF3RrshdyV3sAGMXVUmpMYOw+dLpOuw==} dev: false - /node-domexception@1.0.0: - resolution: {integrity: sha512-/jKZoMpw0F8GRwl4/eLROPA3cfcXtLApP0QzLmUT/HuPCZWyB7IY9ZrMeKw2O/nFIqPQB3PVM9aYm0F312AXDQ==} - engines: {node: '>=10.5.0'} - dev: false - - /node-fetch-native@1.4.0: - resolution: {integrity: sha512-F5kfEj95kX8tkDhUCYdV8dg3/8Olx/94zB8+ZNthFs6Bz31UpUi8Xh40TN3thLwXgrwXry1pEg9lJ++tLWTcqA==} - dev: false - /node-fetch@2.6.11: resolution: {integrity: sha512-4I6pdBY1EthSqDmJkiNk3JIT8cswwR9nfeW/cPdUagJYEQG7R95WRH74wpz7ma8Gh/9dI9FP+OU+0E4FvtA55w==} engines: {node: 4.x || >=6.0.0} @@ -6307,15 +6234,6 @@ packages: dependencies: whatwg-url: 5.0.0 - /node-fetch@3.3.2: - resolution: {integrity: sha512-dRB78srN/l6gqWulah9SrxeYnxeddIG30+GOqK/9OlLVyLg3HPnr6SqOWTWOXKRwC2eGYCkZ59NNuSgvSrpgOA==} - engines: {node: ^12.20.0 || ^14.13.1 || >=16.0.0} - dependencies: - data-uri-to-buffer: 4.0.1 - fetch-blob: 3.2.0 - formdata-polyfill: 4.0.10 - dev: false - /node-stdlib-browser@1.2.0: resolution: {integrity: sha512-VSjFxUhRhkyed8AtLwSCkMrJRfQ3e2lGtG3sP6FEgaLKBBbxM/dLfjRe1+iLhjvyLFW3tBQ8+c0pcOtXGbAZJg==} engines: {node: '>=10'} @@ -8688,11 +8606,6 @@ packages: dependencies: defaults: 1.0.4 - /web-streams-polyfill@3.2.1: - resolution: {integrity: sha512-e0MO3wdXWKrLbL0DgGnUV7WHVuw9OUvL4hjgnPkIeEvESk74gAITi5G606JtZPp39cd8HA9VQzCIvA49LpPN5Q==} - engines: {node: '>= 8'} - dev: false - /webidl-conversions@3.0.1: resolution: {integrity: sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ==} From 5abf1c24cc5893c896923dc840c67b72d734cea0 Mon Sep 17 00:00:00 2001 From: terwer Date: Sun, 8 Oct 2023 23:41:44 +0800 Subject: [PATCH 24/30] fix: remove same item --- libs/zhi-blog-api/CHANGELOG.md | 6 +++++ libs/zhi-blog-api/package.json | 2 +- libs/zhi-blog-api/src/lib/PostUtil.ts | 33 +++++++++++++++++++++++---- libs/zhi-siyuan-api/CHANGELOG.md | 7 ++++++ libs/zhi-siyuan-api/package.json | 2 +- 5 files changed, 44 insertions(+), 6 deletions(-) diff --git a/libs/zhi-blog-api/CHANGELOG.md b/libs/zhi-blog-api/CHANGELOG.md index f09b38f4..01087cc8 100644 --- a/libs/zhi-blog-api/CHANGELOG.md +++ b/libs/zhi-blog-api/CHANGELOG.md @@ -1,5 +1,11 @@ # zhi-blog-api +## 1.44.4 + +### Patch Changes + +- fix: remove same item + ## 1.44.3 ### Patch Changes diff --git a/libs/zhi-blog-api/package.json b/libs/zhi-blog-api/package.json index 719e5a92..f500deac 100644 --- a/libs/zhi-blog-api/package.json +++ b/libs/zhi-blog-api/package.json @@ -1,6 +1,6 @@ { "name": "zhi-blog-api", - "version": "1.44.3", + "version": "1.44.4", "type": "module", "description": "a common blog interface", "main": "./dist/index.js", diff --git a/libs/zhi-blog-api/src/lib/PostUtil.ts b/libs/zhi-blog-api/src/lib/PostUtil.ts index c636be44..94a16b3b 100644 --- a/libs/zhi-blog-api/src/lib/PostUtil.ts +++ b/libs/zhi-blog-api/src/lib/PostUtil.ts @@ -67,18 +67,43 @@ class PostUtil { post.permalink = yamlObj?.permalink ?? post.permalink post.shortDesc = yamlObj?.desc ?? post.shortDesc + // // 标签合并 + // if (yamlObj?.tags && yamlObj.tags.length > 0) { + // const existingTags = post.mt_keywords.split(",") + // const uniqueKeywords = [...new Set([...existingTags, ...yamlObj.tags])].filter((tag) => tag.trim() !== "") + // post.mt_keywords = uniqueKeywords.length > 0 ? uniqueKeywords.join(",") : "" + // } + // + // // 分类合并 + // if (yamlObj?.categories && yamlObj.categories.length > 0) { + // const combinedCategories = [...new Set([...post.categories, ...yamlObj.categories])].filter( + // (cate) => cate.trim() !== "" + // ) + // post.categories = combinedCategories.length > 0 ? combinedCategories : [] + // } + // 标签合并 if (yamlObj?.tags && yamlObj.tags.length > 0) { const existingTags = post.mt_keywords.split(",") - const uniqueKeywords = [...new Set([...existingTags, ...yamlObj.tags])].filter((tag) => tag.trim() !== "") + const uniqueKeywords = [ + ...new Set([ + ...existingTags.map((tag) => tag.trim().toLowerCase()), + ...yamlObj.tags.map((tag) => tag.trim().toLowerCase()), + ]), + ].filter((tag) => tag.trim() !== "") + post.mt_keywords = uniqueKeywords.length > 0 ? uniqueKeywords.join(",") : "" } // 分类合并 if (yamlObj?.categories && yamlObj.categories.length > 0) { - const combinedCategories = [...new Set([...post.categories, ...yamlObj.categories])].filter( - (cate) => cate.trim() !== "" - ) + const combinedCategories = [ + ...new Set([ + ...post.categories.map((cate) => cate.trim().toLowerCase()), + ...yamlObj.categories.map((cate) => cate.trim().toLowerCase()), + ]), + ].filter((cate) => cate.trim() !== "") + post.categories = combinedCategories.length > 0 ? combinedCategories : [] } } diff --git a/libs/zhi-siyuan-api/CHANGELOG.md b/libs/zhi-siyuan-api/CHANGELOG.md index d3c4fb90..d074da9f 100644 --- a/libs/zhi-siyuan-api/CHANGELOG.md +++ b/libs/zhi-siyuan-api/CHANGELOG.md @@ -1,5 +1,12 @@ # zhi-siyuan-api +## 2.10.4 + +### Patch Changes + +- Updated dependencies + - zhi-blog-api@1.44.4 + ## 2.10.3 ### Patch Changes diff --git a/libs/zhi-siyuan-api/package.json b/libs/zhi-siyuan-api/package.json index ade86f08..5e50c2b1 100644 --- a/libs/zhi-siyuan-api/package.json +++ b/libs/zhi-siyuan-api/package.json @@ -1,6 +1,6 @@ { "name": "zhi-siyuan-api", - "version": "2.10.3", + "version": "2.10.4", "type": "module", "description": "a siyuan-note api including both kernel and client", "main": "./dist/index.js", From 84ec58fa4ee6fc874629099517965c7a185b828d Mon Sep 17 00:00:00 2001 From: terwer Date: Sun, 8 Oct 2023 23:50:29 +0800 Subject: [PATCH 25/30] feat: not force lowercase --- libs/zhi-blog-api/CHANGELOG.md | 6 ++++++ libs/zhi-blog-api/package.json | 2 +- libs/zhi-blog-api/src/lib/PostUtil.ts | 10 ++-------- libs/zhi-siyuan-api/CHANGELOG.md | 7 +++++++ libs/zhi-siyuan-api/package.json | 2 +- 5 files changed, 17 insertions(+), 10 deletions(-) diff --git a/libs/zhi-blog-api/CHANGELOG.md b/libs/zhi-blog-api/CHANGELOG.md index 01087cc8..1ea6cbcd 100644 --- a/libs/zhi-blog-api/CHANGELOG.md +++ b/libs/zhi-blog-api/CHANGELOG.md @@ -1,5 +1,11 @@ # zhi-blog-api +## 1.45.0 + +### Minor Changes + +- feat: not force lowercase + ## 1.44.4 ### Patch Changes diff --git a/libs/zhi-blog-api/package.json b/libs/zhi-blog-api/package.json index f500deac..46a4b17b 100644 --- a/libs/zhi-blog-api/package.json +++ b/libs/zhi-blog-api/package.json @@ -1,6 +1,6 @@ { "name": "zhi-blog-api", - "version": "1.44.4", + "version": "1.45.0", "type": "module", "description": "a common blog interface", "main": "./dist/index.js", diff --git a/libs/zhi-blog-api/src/lib/PostUtil.ts b/libs/zhi-blog-api/src/lib/PostUtil.ts index 94a16b3b..45f6276c 100644 --- a/libs/zhi-blog-api/src/lib/PostUtil.ts +++ b/libs/zhi-blog-api/src/lib/PostUtil.ts @@ -86,10 +86,7 @@ class PostUtil { if (yamlObj?.tags && yamlObj.tags.length > 0) { const existingTags = post.mt_keywords.split(",") const uniqueKeywords = [ - ...new Set([ - ...existingTags.map((tag) => tag.trim().toLowerCase()), - ...yamlObj.tags.map((tag) => tag.trim().toLowerCase()), - ]), + ...new Set([...existingTags.map((tag) => tag.trim()), ...yamlObj.tags.map((tag) => tag.trim())]), ].filter((tag) => tag.trim() !== "") post.mt_keywords = uniqueKeywords.length > 0 ? uniqueKeywords.join(",") : "" @@ -98,10 +95,7 @@ class PostUtil { // 分类合并 if (yamlObj?.categories && yamlObj.categories.length > 0) { const combinedCategories = [ - ...new Set([ - ...post.categories.map((cate) => cate.trim().toLowerCase()), - ...yamlObj.categories.map((cate) => cate.trim().toLowerCase()), - ]), + ...new Set([...post.categories.map((cate) => cate.trim()), ...yamlObj.categories.map((cate) => cate.trim())]), ].filter((cate) => cate.trim() !== "") post.categories = combinedCategories.length > 0 ? combinedCategories : [] diff --git a/libs/zhi-siyuan-api/CHANGELOG.md b/libs/zhi-siyuan-api/CHANGELOG.md index d074da9f..55d0c5bc 100644 --- a/libs/zhi-siyuan-api/CHANGELOG.md +++ b/libs/zhi-siyuan-api/CHANGELOG.md @@ -1,5 +1,12 @@ # zhi-siyuan-api +## 2.10.5 + +### Patch Changes + +- Updated dependencies + - zhi-blog-api@1.45.0 + ## 2.10.4 ### Patch Changes diff --git a/libs/zhi-siyuan-api/package.json b/libs/zhi-siyuan-api/package.json index 5e50c2b1..cf5f30c4 100644 --- a/libs/zhi-siyuan-api/package.json +++ b/libs/zhi-siyuan-api/package.json @@ -1,6 +1,6 @@ { "name": "zhi-siyuan-api", - "version": "2.10.4", + "version": "2.10.5", "type": "module", "description": "a siyuan-note api including both kernel and client", "main": "./dist/index.js", From b7185ce623b72d8b0445a4eb849edd940e70529c Mon Sep 17 00:00:00 2001 From: terwer Date: Mon, 9 Oct 2023 14:37:58 +0800 Subject: [PATCH 26/30] feat: init zhi-picgo-core --- libs/zhi-picgo-core/package.json | 130 + libs/zhi-picgo-core/rollup.config.js | 87 + libs/zhi-picgo-core/src/core/Lifecycle.ts | 132 + libs/zhi-picgo-core/src/core/PicGo.ts | 228 + libs/zhi-picgo-core/src/custom-env.d.ts | 19 + libs/zhi-picgo-core/src/i18n/en.ts | 108 + libs/zhi-picgo-core/src/i18n/index.ts | 103 + libs/zhi-picgo-core/src/i18n/zh-CN.ts | 109 + libs/zhi-picgo-core/src/i18n/zh-TW.ts | 108 + libs/zhi-picgo-core/src/index.ts | 11 + libs/zhi-picgo-core/src/lib/Commander.ts | 97 + .../src/lib/LifecyclePlugins.ts | 63 + libs/zhi-picgo-core/src/lib/Logger.ts | 141 + libs/zhi-picgo-core/src/lib/PluginHandler.ts | 293 ++ libs/zhi-picgo-core/src/lib/PluginLoader.ts | 153 + libs/zhi-picgo-core/src/lib/Request.ts | 239 + libs/zhi-picgo-core/src/libs.d.ts | 8 + .../src/plugins/commander/config.ts | 12 + .../src/plugins/commander/i18n.ts | 36 + .../src/plugins/commander/index.ts | 20 + .../src/plugins/commander/init.ts | 120 + .../src/plugins/commander/pluginHandler.ts | 44 + .../src/plugins/commander/proxy.ts | 15 + .../src/plugins/commander/setting.ts | 101 + .../src/plugins/commander/upload.ts | 33 + .../src/plugins/commander/use.ts | 85 + .../src/plugins/transformer/base64.ts | 9 + .../src/plugins/transformer/index.ts | 14 + .../src/plugins/transformer/path.ts | 47 + .../src/plugins/uploader/aliyun.ts | 215 + .../src/plugins/uploader/github.ts | 123 + .../src/plugins/uploader/imgur.ts | 91 + .../src/plugins/uploader/index.ts | 22 + .../src/plugins/uploader/qiniu.ts | 152 + .../src/plugins/uploader/smms.ts | 97 + .../src/plugins/uploader/tcyun.ts | 260 ++ .../src/plugins/uploader/upyun.ts | 254 ++ libs/zhi-picgo-core/src/types/index.ts | 597 +++ libs/zhi-picgo-core/src/types/oldRequest.ts | 29 + .../src/utils/clipboard/linux.sh | 49 + .../src/utils/clipboard/mac.applescript | 41 + .../src/utils/clipboard/windows.ps1 | 26 + .../src/utils/clipboard/windows10.ps1 | 47 + .../zhi-picgo-core/src/utils/clipboard/wsl.sh | 18 + libs/zhi-picgo-core/src/utils/common.ts | 380 ++ .../zhi-picgo-core/src/utils/createContext.ts | 45 + libs/zhi-picgo-core/src/utils/db.ts | 85 + libs/zhi-picgo-core/src/utils/enum.ts | 29 + libs/zhi-picgo-core/src/utils/eventBus.ts | 6 + .../src/utils/getClipboardImage.ts | 141 + libs/zhi-picgo-core/src/utils/initUtils.ts | 118 + libs/zhi-picgo-core/src/utils/interfaces.ts | 217 + libs/zhi-picgo-core/src/utils/static.ts | 1 + libs/zhi-picgo-core/src/utils/streamUtils.ts | 15 + pnpm-lock.yaml | 3868 +++++++++++++++-- 55 files changed, 9212 insertions(+), 279 deletions(-) create mode 100644 libs/zhi-picgo-core/package.json create mode 100644 libs/zhi-picgo-core/rollup.config.js create mode 100644 libs/zhi-picgo-core/src/core/Lifecycle.ts create mode 100644 libs/zhi-picgo-core/src/core/PicGo.ts create mode 100644 libs/zhi-picgo-core/src/custom-env.d.ts create mode 100644 libs/zhi-picgo-core/src/i18n/en.ts create mode 100644 libs/zhi-picgo-core/src/i18n/index.ts create mode 100644 libs/zhi-picgo-core/src/i18n/zh-CN.ts create mode 100644 libs/zhi-picgo-core/src/i18n/zh-TW.ts create mode 100644 libs/zhi-picgo-core/src/index.ts create mode 100644 libs/zhi-picgo-core/src/lib/Commander.ts create mode 100644 libs/zhi-picgo-core/src/lib/LifecyclePlugins.ts create mode 100644 libs/zhi-picgo-core/src/lib/Logger.ts create mode 100644 libs/zhi-picgo-core/src/lib/PluginHandler.ts create mode 100644 libs/zhi-picgo-core/src/lib/PluginLoader.ts create mode 100644 libs/zhi-picgo-core/src/lib/Request.ts create mode 100644 libs/zhi-picgo-core/src/libs.d.ts create mode 100644 libs/zhi-picgo-core/src/plugins/commander/config.ts create mode 100644 libs/zhi-picgo-core/src/plugins/commander/i18n.ts create mode 100644 libs/zhi-picgo-core/src/plugins/commander/index.ts create mode 100644 libs/zhi-picgo-core/src/plugins/commander/init.ts create mode 100644 libs/zhi-picgo-core/src/plugins/commander/pluginHandler.ts create mode 100644 libs/zhi-picgo-core/src/plugins/commander/proxy.ts create mode 100644 libs/zhi-picgo-core/src/plugins/commander/setting.ts create mode 100644 libs/zhi-picgo-core/src/plugins/commander/upload.ts create mode 100644 libs/zhi-picgo-core/src/plugins/commander/use.ts create mode 100644 libs/zhi-picgo-core/src/plugins/transformer/base64.ts create mode 100644 libs/zhi-picgo-core/src/plugins/transformer/index.ts create mode 100644 libs/zhi-picgo-core/src/plugins/transformer/path.ts create mode 100644 libs/zhi-picgo-core/src/plugins/uploader/aliyun.ts create mode 100644 libs/zhi-picgo-core/src/plugins/uploader/github.ts create mode 100644 libs/zhi-picgo-core/src/plugins/uploader/imgur.ts create mode 100644 libs/zhi-picgo-core/src/plugins/uploader/index.ts create mode 100644 libs/zhi-picgo-core/src/plugins/uploader/qiniu.ts create mode 100644 libs/zhi-picgo-core/src/plugins/uploader/smms.ts create mode 100644 libs/zhi-picgo-core/src/plugins/uploader/tcyun.ts create mode 100644 libs/zhi-picgo-core/src/plugins/uploader/upyun.ts create mode 100644 libs/zhi-picgo-core/src/types/index.ts create mode 100644 libs/zhi-picgo-core/src/types/oldRequest.ts create mode 100644 libs/zhi-picgo-core/src/utils/clipboard/linux.sh create mode 100644 libs/zhi-picgo-core/src/utils/clipboard/mac.applescript create mode 100644 libs/zhi-picgo-core/src/utils/clipboard/windows.ps1 create mode 100644 libs/zhi-picgo-core/src/utils/clipboard/windows10.ps1 create mode 100644 libs/zhi-picgo-core/src/utils/clipboard/wsl.sh create mode 100644 libs/zhi-picgo-core/src/utils/common.ts create mode 100644 libs/zhi-picgo-core/src/utils/createContext.ts create mode 100644 libs/zhi-picgo-core/src/utils/db.ts create mode 100644 libs/zhi-picgo-core/src/utils/enum.ts create mode 100644 libs/zhi-picgo-core/src/utils/eventBus.ts create mode 100644 libs/zhi-picgo-core/src/utils/getClipboardImage.ts create mode 100644 libs/zhi-picgo-core/src/utils/initUtils.ts create mode 100644 libs/zhi-picgo-core/src/utils/interfaces.ts create mode 100644 libs/zhi-picgo-core/src/utils/static.ts create mode 100644 libs/zhi-picgo-core/src/utils/streamUtils.ts diff --git a/libs/zhi-picgo-core/package.json b/libs/zhi-picgo-core/package.json new file mode 100644 index 00000000..77c71256 --- /dev/null +++ b/libs/zhi-picgo-core/package.json @@ -0,0 +1,130 @@ +{ + "name": "zhi-picgo-core", + "version": "1.6.0", + "description": "A tool for picture uploading forked from PicGO-Core", + "main": "dist/index.cjs.js", + "module": "dist/index.esm.js", + "typings": "dist/index.d.ts", + "bin": { + "picgo": "./bin/picgo" + }, + "publishConfig": { + "access": "public" + }, + "scripts": { + "build": "cross-env NODE_ENV=production rimraf ./dist && rollup -c rollup.config.js", + "dev": "cross-env NODE_ENV=development rollup -c rollup.config.js -w", + "start": "node ./bin/picgo", + "lint": "eslint src/**/*.ts && npm run build" + }, + "keywords": [ + "picture", + "upload", + "util" + ], + "husky": { + "hooks": { + "pre-commit": "npm run lint", + "commit-msg": "commitlint -E HUSKY_GIT_PARAMS" + } + }, + "config": { + "commitizen": { + "path": "./node_modules/cz-customizable" + }, + "cz-customizable": { + "config": "./node_modules/@picgo/bump-version/.cz-config.js" + } + }, + "commitlint": { + "extends": [ + "./node_modules/@picgo/bump-version/commitlint-picgo" + ] + }, + "author": "Terwer", + "license": "MIT", + "devDependencies": { + "@picgo/bump-version": "^1.1.2", + "@rollup/plugin-commonjs": "^21.0.0", + "@rollup/plugin-json": "^4.1.0", + "@rollup/plugin-node-resolve": "^13.0.5", + "@rollup/plugin-replace": "^3.0.0", + "@types/cross-spawn": "^6.0.0", + "@types/ejs": "^3.0.5", + "@types/fs-extra": "^5.0.4", + "@types/image-size": "^0.0.29", + "@types/inquirer": "^0.0.42", + "@types/js-yaml": "^4.0.5", + "@types/lodash": "^4.14.175", + "@types/md5": "^2.1.32", + "@types/mime-types": "^2.1.0", + "@types/minimatch": "^3.0.3", + "@types/node": "16.11.7", + "@types/resolve": "^0.0.8", + "@types/rimraf": "^3.0.0", + "@types/tunnel": "^0.0.3", + "@typescript-eslint/eslint-plugin": "3", + "@typescript-eslint/parser": "^3.2.0", + "babel-eslint": "^10.1.0", + "builtins": "^4.0.0", + "conventional-changelog": "^3.0.6", + "copyfiles": "^2.1.0", + "cross-env": "^7.0.3", + "cz-customizable": "^5.10.0", + "eslint": "7", + "eslint-config-standard-with-typescript": "^18.0.2", + "eslint-plugin-import": "2", + "eslint-plugin-node": "11", + "eslint-plugin-promise": "4", + "eslint-plugin-standard": "4", + "execa": "^5.1.1", + "husky": "^1.3.1", + "pre-commit": "^1.2.2", + "rollup": "^2.58.0", + "rollup-plugin-string": "^3.0.0", + "rollup-plugin-terser": "^7.0.2", + "rollup-plugin-typescript2": "^0.34.1", + "typescript": "^4.8.2" + }, + "dependencies": { + "@picgo/i18n": "^1.0.0", + "@picgo/store": "^2.0.2", + "ali-oss": "^6.17.1", + "arraybuffer-to-buffer": "^0.0.7", + "axios": "^0.27.2", + "chalk": "^2.4.1", + "commander": "^8.1.0", + "comment-json": "^2.3.1", + "cross-spawn": "^6.0.5", + "dayjs": "^1.7.4", + "download-git-repo": "^3.0.2", + "ejs": "^2.6.1", + "fs-extra": "^6.0.1", + "globby": "^11.0.4", + "image-size": "^0.8.3", + "inquirer": "^6.0.0", + "is-wsl": "^2.2.0", + "js-yaml": "^4.1.0", + "lodash": "^4.17.21", + "md5": "^2.2.1", + "mime-types": "2.1.33", + "minimatch": "^3.0.4", + "minimist": "^1.2.5", + "qiniu": "^7.2.1", + "resolve": "^1.8.1", + "rimraf": "^3.0.2", + "tunnel": "^0.0.6", + "upyun": "^3.4.6" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/terwer/zhi/zhi-picgo-core.git" + }, + "picBed": { + "current": "github" + }, + "plugins": {}, + "engines": { + "node": ">= 12.0.0" + } +} diff --git a/libs/zhi-picgo-core/rollup.config.js b/libs/zhi-picgo-core/rollup.config.js new file mode 100644 index 00000000..2577ecb0 --- /dev/null +++ b/libs/zhi-picgo-core/rollup.config.js @@ -0,0 +1,87 @@ +import { terser } from 'rollup-plugin-terser' +import pkg from './package.json' +import typescript from 'rollup-plugin-typescript2' +import commonjs from '@rollup/plugin-commonjs' +import { string } from 'rollup-plugin-string' +import json from '@rollup/plugin-json' +import builtins from 'builtins' +import replace from '@rollup/plugin-replace' +const version = process.env.VERSION || pkg.version +const sourcemap = 'inline' +const banner = `/* + * picgo@${version}, https://github.com/PicGo/PicGo-Core + * (c) 2018-${new Date().getFullYear()} PicGo Group + * Released under the MIT License. + */` +const input = './src/index.ts' + +const commonOptions = { + // Creating regex of the packages to make sure sub-paths of the + // packages such as `lowdb/adapters/FileSync` are also treated as external + // See https://github.com/rollup/rollup/issues/3684#issuecomment-926558056 + external: [ + ...Object.keys(pkg.dependencies), + ...builtins() + ].map(packageName => new RegExp(`^${packageName}(/.*)?`)), + plugins: [ + typescript({ + tsconfigOverride: { + compilerOptions: { + target: 'ES2017', + module: 'ES2015' + } + } + }), + // terser(), + commonjs(), + string({ + // Required to be specified + include: [ + '**/*.applescript', + '**/*.ps1', + '**/*.sh' + ] + }), + json(), + replace({ + 'process.env.PICGO_VERSION': JSON.stringify(pkg.version), + preventAssignment: true + }) + ], + input +} + +const isDev = process.env.NODE_ENV === 'development' + +if (!isDev) { + commonOptions.plugins.push(terser()) +} + +/** @type import('rollup').RollupOptions */ +const nodeCjs = { + output: [{ + file: 'dist/index.cjs.js', + format: 'cjs', + banner, + sourcemap + }], + ...commonOptions +} + +const nodeEsm = { + output: [{ + file: 'dist/index.esm.js', + format: 'esm', + banner, + sourcemap + }], + ...commonOptions +} + +const bundles = [] +const env = process.env.BUNDLES || '' +if (env.includes('cjs')) bundles.push(nodeCjs) +if (env.includes('esm')) bundles.push(nodeEsm) +if (bundles.length === 0) bundles.push(nodeCjs, nodeEsm) + +export default bundles diff --git a/libs/zhi-picgo-core/src/core/Lifecycle.ts b/libs/zhi-picgo-core/src/core/Lifecycle.ts new file mode 100644 index 00000000..9a9eaa47 --- /dev/null +++ b/libs/zhi-picgo-core/src/core/Lifecycle.ts @@ -0,0 +1,132 @@ +import { EventEmitter } from 'events' +import { ILifecyclePlugins, IPicGo, IPlugin, Undefinable } from '../types' +import { handleUrlEncode } from '../utils/common' +import { IBuildInEvent } from '../utils/enum' +import { createContext } from '../utils/createContext' + +export class Lifecycle extends EventEmitter { + private readonly ctx: IPicGo + + constructor (ctx: IPicGo) { + super() + this.ctx = ctx + } + + async start (input: any[]): Promise { + // ensure every upload process has an unique context + const ctx = createContext(this.ctx) + try { + // images input + if (!Array.isArray(input)) { + throw new Error('Input must be an array.') + } + ctx.input = input + ctx.output = [] + + // lifecycle main + await this.beforeTransform(ctx) + await this.doTransform(ctx) + await this.beforeUpload(ctx) + await this.doUpload(ctx) + await this.afterUpload(ctx) + return ctx + } catch (e: any) { + ctx.log.warn(IBuildInEvent.FAILED) + ctx.emit(IBuildInEvent.UPLOAD_PROGRESS, -1) + ctx.emit(IBuildInEvent.FAILED, e) + ctx.log.error(e) + if (ctx.getConfig>('debug')) { + throw e + } + return ctx + } + } + + private async beforeTransform (ctx: IPicGo): Promise { + ctx.emit(IBuildInEvent.UPLOAD_PROGRESS, 0) + ctx.emit(IBuildInEvent.BEFORE_TRANSFORM, ctx) + ctx.log.info('Before transform') + await this.handlePlugins(ctx.helper.beforeTransformPlugins, ctx) + return ctx + } + + private async doTransform (ctx: IPicGo): Promise { + ctx.emit(IBuildInEvent.UPLOAD_PROGRESS, 30) + const type = ctx.getConfig>('picBed.transformer') || 'path' + let currentTransformer = type + let transformer = ctx.helper.transformer.get(type) + if (!transformer) { + transformer = ctx.helper.transformer.get('path') + currentTransformer = 'path' + ctx.log.warn(`Can't find transformer - ${type}, switch to default transformer - path`) + } + ctx.log.info(`Transforming... Current transformer is [${currentTransformer}]`) + await transformer?.handle(ctx) + return ctx + } + + private async beforeUpload (ctx: IPicGo): Promise { + ctx.emit(IBuildInEvent.UPLOAD_PROGRESS, 60) + ctx.log.info('Before upload') + ctx.emit(IBuildInEvent.BEFORE_UPLOAD, ctx) + await this.handlePlugins(ctx.helper.beforeUploadPlugins, ctx) + return ctx + } + + private async doUpload (ctx: IPicGo): Promise { + let type = ctx.getConfig>('picBed.uploader') || ctx.getConfig>('picBed.current') || 'github' + let uploader = ctx.helper.uploader.get(type) + let currentTransformer = type + if (!uploader) { + type = 'github' + currentTransformer = 'github' + uploader = ctx.helper.uploader.get('github') + ctx.log.warn(`Can't find uploader - ${type}, switch to default uploader - github`) + } + ctx.log.info(`Uploading... Current uploader is [${currentTransformer}]`) + await uploader?.handle(ctx) + for (const outputImg of ctx.output) { + outputImg.type = type + } + return ctx + } + + private async afterUpload (ctx: IPicGo): Promise { + ctx.emit(IBuildInEvent.AFTER_UPLOAD, ctx) + ctx.emit(IBuildInEvent.UPLOAD_PROGRESS, 100) + await this.handlePlugins(ctx.helper.afterUploadPlugins, ctx) + let msg = '' + const length = ctx.output.length + for (let i = 0; i < length; i++) { + if (typeof ctx.output[i].imgUrl !== 'undefined') { + msg += handleUrlEncode(ctx.output[i].imgUrl!) + if (i !== length - 1) { + msg += '\n' + } + } + delete ctx.output[i].base64Image + delete ctx.output[i].buffer + } + ctx.emit(IBuildInEvent.FINISHED, ctx) + ctx.log.success(`\n${msg}`) + return ctx + } + + private async handlePlugins (lifeCyclePlugins: ILifecyclePlugins, ctx: IPicGo): Promise { + const plugins = lifeCyclePlugins.getList() + const pluginNames = lifeCyclePlugins.getIdList() + const lifeCycleName = lifeCyclePlugins.getName() + await Promise.all(plugins.map(async (plugin: IPlugin, index: number) => { + try { + ctx.log.info(`${lifeCycleName}: ${pluginNames[index]} running`) + await plugin.handle(ctx) + } catch (e) { + ctx.log.error(`${lifeCycleName}: ${pluginNames[index]} error`) + throw e + } + })) + return ctx + } +} + +export default Lifecycle diff --git a/libs/zhi-picgo-core/src/core/PicGo.ts b/libs/zhi-picgo-core/src/core/PicGo.ts new file mode 100644 index 00000000..cec34568 --- /dev/null +++ b/libs/zhi-picgo-core/src/core/PicGo.ts @@ -0,0 +1,228 @@ +import fs from 'fs-extra' +import path from 'path' +import { EventEmitter } from 'events' +import { homedir } from 'os' +import Commander from '../lib/Commander' +import { Logger } from '../lib/Logger' +import Lifecycle from './Lifecycle' +import LifecyclePlugins, { setCurrentPluginName } from '../lib/LifecyclePlugins' +import uploaders from '../plugins/uploader' +import transformers from '../plugins/transformer' +import PluginLoader from '../lib/PluginLoader' +import { get, set, unset } from 'lodash' +import { IHelper, IImgInfo, IConfig, IPicGo, IStringKeyMap, IPluginLoader, II18nManager, IPicGoPlugin, IPicGoPluginInterface, IRequest } from '../types' +import getClipboardImage from '../utils/getClipboardImage' +import Request from '../lib/Request' +import DB from '../utils/db' +import PluginHandler from '../lib/PluginHandler' +import { IBuildInEvent, IBusEvent } from '../utils/enum' +import { eventBus } from '../utils/eventBus' +import { isConfigKeyInBlackList, isInputConfigValid } from '../utils/common' +import { I18nManager } from '../i18n' + +export class PicGo extends EventEmitter implements IPicGo { + private _config!: IConfig + private lifecycle!: Lifecycle + private db!: DB + private _pluginLoader!: PluginLoader + configPath: string + baseDir!: string + helper!: IHelper + log: Logger + cmd: Commander + output: IImgInfo[] + input: any[] + pluginHandler: PluginHandler + /** + * @deprecated will be removed in v1.5.0+ + * + * use request instead + */ + Request!: Request + i18n!: II18nManager + VERSION: string = process.env.PICGO_VERSION + GUI_VERSION?: string + + get pluginLoader (): IPluginLoader { + return this._pluginLoader + } + + constructor (configPath: string = '') { + super() + this.configPath = configPath + this.output = [] + this.input = [] + this.helper = { + transformer: new LifecyclePlugins('transformer'), + uploader: new LifecyclePlugins('uploader'), + beforeTransformPlugins: new LifecyclePlugins('beforeTransformPlugins'), + beforeUploadPlugins: new LifecyclePlugins('beforeUploadPlugins'), + afterUploadPlugins: new LifecyclePlugins('afterUploadPlugins') + } + this.initConfigPath() + this.log = new Logger(this) + this.cmd = new Commander(this) + this.pluginHandler = new PluginHandler(this) + this.initConfig() + this.init() + } + + private initConfigPath (): void { + if (this.configPath === '') { + this.configPath = homedir() + '/.picgo/config.json' + } + if (path.extname(this.configPath).toUpperCase() !== '.JSON') { + this.configPath = '' + throw Error('The configuration file only supports JSON format.') + } + this.baseDir = path.dirname(this.configPath) + const exist = fs.pathExistsSync(this.configPath) + if (!exist) { + fs.ensureFileSync(`${this.configPath}`) + } + } + + private initConfig (): void { + this.db = new DB(this) + this._config = this.db.read(true) as IConfig + } + + private init (): void { + try { + // init 18n at first + this.i18n = new I18nManager(this) + this.Request = new Request(this) + this._pluginLoader = new PluginLoader(this) + // load self plugins + setCurrentPluginName('picgo') + uploaders(this).register(this) + transformers(this).register(this) + setCurrentPluginName('') + // load third-party plugins + this._pluginLoader.load() + this.lifecycle = new Lifecycle(this) + } catch (e: any) { + this.emit(IBuildInEvent.UPLOAD_PROGRESS, -1) + this.log.error(e) + throw e + } + } + + /** + * easily mannually load a plugin + * if provide plugin name, will register plugin by name + * or just instantiate a plugin + */ + use (plugin: IPicGoPlugin, name?: string): IPicGoPluginInterface { + if (name) { + this.pluginLoader.registerPlugin(name, plugin) + return this.pluginLoader.getPlugin(name)! + } else { + const pluginInstance = plugin(this) + return pluginInstance + } + } + + registerCommands (): void { + if (this.configPath !== '') { + this.cmd.init() + this.cmd.loadCommands() + } + } + + getConfig (name?: string): T { + if (!name) { + return this._config as unknown as T + } else { + return get(this._config, name) + } + } + + saveConfig (config: IStringKeyMap): void { + if (!isInputConfigValid(config)) { + this.log.warn('the format of config is invalid, please provide object') + return + } + this.setConfig(config) + this.db.saveConfig(config) + } + + removeConfig (key: string, propName: string): void { + if (!key || !propName) return + if (isConfigKeyInBlackList(key)) { + this.log.warn(`the config.${key} can't be removed`) + return + } + this.unsetConfig(key, propName) + this.db.unset(key, propName) + } + + setConfig (config: IStringKeyMap): void { + if (!isInputConfigValid(config)) { + this.log.warn('the format of config is invalid, please provide object') + return + } + Object.keys(config).forEach((name: string) => { + if (isConfigKeyInBlackList(name)) { + this.log.warn(`the config.${name} can't be modified`) + // eslint-disable-next-line @typescript-eslint/no-dynamic-delete + delete config[name] + } + set(this._config, name, config[name]) + eventBus.emit(IBusEvent.CONFIG_CHANGE, { + configName: name, + value: config[name] + }) + }) + } + + unsetConfig (key: string, propName: string): void { + if (!key || !propName) return + if (isConfigKeyInBlackList(key)) { + this.log.warn(`the config.${key} can't be unset`) + return + } + unset(this.getConfig(key), propName) + } + + get request (): IRequest['request'] { + return this.Request.request.bind(this.Request) + } + + async upload (input?: any[]): Promise { + if (this.configPath === '') { + this.log.error('The configuration file only supports JSON format.') + return [] + } + // upload from clipboard + if (input === undefined || input.length === 0) { + try { + const { imgPath, shouldKeepAfterUploading } = await getClipboardImage(this) + if (imgPath === 'no image') { + throw new Error('image not found in clipboard') + } else { + this.once(IBuildInEvent.FAILED, () => { + if (!shouldKeepAfterUploading) { + // 删除 picgo 生成的图片文件,例如 `~/.picgo/20200621205720.png` + fs.remove(imgPath).catch((e) => { this.log.error(e) }) + } + }) + this.once('finished', () => { + if (!shouldKeepAfterUploading) { + fs.remove(imgPath).catch((e) => { this.log.error(e) }) + } + }) + const { output } = await this.lifecycle.start([imgPath]) + return output + } + } catch (e) { + this.emit(IBuildInEvent.FAILED, e) + throw e + } + } else { + // upload from path + const { output } = await this.lifecycle.start(input) + return output + } + } +} diff --git a/libs/zhi-picgo-core/src/custom-env.d.ts b/libs/zhi-picgo-core/src/custom-env.d.ts new file mode 100644 index 00000000..e0d45c86 --- /dev/null +++ b/libs/zhi-picgo-core/src/custom-env.d.ts @@ -0,0 +1,19 @@ +/* eslint-disable @typescript-eslint/naming-convention */ +declare module '*.sh' { + const src: string + export default src +} +declare module '*.applescript' { + const src: string + export default src +} +declare module '*.ps1' { + const src: string + export default src +} + +declare namespace NodeJS { + interface ProcessEnv { + readonly PICGO_VERSION: string + } +} diff --git a/libs/zhi-picgo-core/src/i18n/en.ts b/libs/zhi-picgo-core/src/i18n/en.ts new file mode 100644 index 00000000..92dbad1f --- /dev/null +++ b/libs/zhi-picgo-core/src/i18n/en.ts @@ -0,0 +1,108 @@ +import { ILocales } from './zh-CN' + +/* eslint-disable no-template-curly-in-string */ +export const EN: ILocales = { + UPLOAD_FAILED: 'Upload failed', + CHECK_SETTINGS: 'Please check your settings', + CHECK_SETTINGS_AND_NETWORK: 'Please check your settings and network', + UPLOAD_FAILED_REASON: 'Error code: ${code}, please open the browser and paste the address to see the reason', + SERVER_ERROR: 'Server error, please try again later', + AUTH_FAILED: 'Authentication failed', + + // smms + PICBED_SMMS: 'SM.MS', + PICBED_SMMS_TOKEN: 'Set Token', + PICBED_SMMS_BACKUP_DOMAIN: 'Set Backup Upload Domain', + PICBED_SMMS_MESSAGE_BACKUP_DOMAIN: 'Ex. smms.app', + + // Ali-cloud + PICBED_ALICLOUD: 'Ali Cloud', + PICBED_ALICLOUD_ACCESSKEYID: 'Set KeyId', + PICBED_ALICLOUD_ACCESSKEYSECRET: 'Set KeySecret', + PICBED_ALICLOUD_BUCKET: 'Set Bucket', + PICBED_ALICLOUD_AREA: 'Set Area', + PICBED_ALICLOUD_PATH: 'Set Path', + PICBED_ALICLOUD_CUSTOMURL: 'Set Custom URL', + PICBED_ALICLOUD_OPTIONS: 'Set URL Suffix', + PICBED_ALICLOUD_MESSAGE_AREA: 'Ex. oss-cn-beijing', + PICBED_ALICLOUD_MESSAGE_PATH: 'Ex. test/', + PICBED_ALICLOUD_MESSAGE_OPTIONS: 'Ex. ?x-oss-process=xxx', + PICBED_ALICLOUD_MESSAGE_CUSTOMURL: 'Ex. https://test.com', + + // Tencent-cloud + PICBED_TENCENTCLOUD: 'Tencent Cloud', + PICBED_TENCENTCLOUD_VERSION: 'Choose COS version', + PICBED_TENCENTCLOUD_SECRETID: 'Set SecretId', + PICBED_TENCENTCLOUD_SECRETKEY: 'Set SecretKey', + PICBED_TENCENTCLOUD_APPID: 'Set AppId', + PICBED_TENCENTCLOUD_BUCKET: 'Set Bucket', + PICBED_TENCENTCLOUD_AREA: 'Set Area', + PICBED_TENCENTCLOUD_PATH: 'Set Path', + PICBED_TENCENTCLOUD_OPTIONS: 'Set URL Suffix', + PICBED_TENCENTCLOUD_CUSTOMURL: 'Set Custom URL', + PICBED_TENCENTCLOUD_MESSAGE_APPID: 'Ex. 1234567890', + PICBED_TENCENTCLOUD_MESSAGE_AREA: 'Ex. ap-beijing', + PICBED_TENCENTCLOUD_MESSAGE_PATH: 'Ex. test/', + PICBED_TENCENTCLOUD_MESSAGE_CUSTOMURL: 'Ex. http://test.com', + PICBED_TENCENTCLOUD_MESSAGE_OPTIONS: 'Ex. ?imageMogr2', + + // GitHub + PICBED_GITHUB: 'GitHub', + PICBED_GITHUB_TOKEN: 'Set Token', + PICBED_GITHUB_REPO: 'Set Repo Name', + PICBED_GITHUB_PATH: 'Set Path', + PICBED_GITHUB_BRANCH: 'Set Branch', + PICBED_GITHUB_CUSTOMURL: 'Set Custom URL', + PICBED_GITHUB_MESSAGE_REPO: 'Ex. username/repo', + PICBED_GITHUB_MESSAGE_BRANCH: 'Ex. main', + PICBED_GITHUB_MESSAGE_PATH: 'Ex. test/', + PICBED_GITHUB_MESSAGE_CUSTOMURL: 'Ex. https://test.com', + + // qiniu + PICBED_QINIU: 'Qiniu', + PICBED_QINIU_ACCESSKEY: 'Set AccessKey', + PICBED_QINIU_SECRETKEY: 'Set SecretKey', + PICBED_QINIU_BUCKET: 'Set Bucket', + PICBED_QINIU_PATH: 'Set Path', + PICBED_QINIU_URL: 'Set URL', + PICBED_QINIU_OPTIONS: 'Set URL Suffix', + PICBED_QINIU_AREA: 'Set Area', + PICBED_QINIU_MESSAGE_PATH: 'Ex. test/', + PICBED_QINIU_MESSAGE_AREA: 'Ex. z0', + PICBED_QINIU_MESSAGE_OPTIONS: 'Ex. ?imageslim', + PICBED_QINIU_MESSAGE_URL: 'Ex. https://xxx.yyy.glb.clouddn.com', + + // imgur + PICBED_IMGUR: 'Imgur', + PICBED_IMGUR_CLIENTID: 'Set ClientId', + PICBED_IMGUR_PROXY: 'Set Proxy', + PICBED_IMGUR_MESSAGE_PROXY: 'Ex. http://127.0.0.1:1080', + + // upyun + PICBED_UPYUN: 'Upyun', + PICBED_UPYUN_BUCKET: 'Set Bucket', + PICBED_UPYUN_OPERATOR: 'Set Operator', + PICBED_UPYUN_PASSWORD: 'Set Operator Password', + PICBED_UPYUN_PATH: 'Set Path', + PICBED_UPYUN_URL: 'Set URL', + PICBED_UPYUN_OPTIONS: 'Set URL Suffix', + PICBED_UPYUN_MESSAGE_OPERATOR: 'Ex. me', + PICBED_UPYUN_MESSAGE_PASSWORD: 'Please type the operator password', + PICBED_UPYUN_MESSAGE_URL: 'Ex. http://xxx.test.upcdn.net', + PICBED_UPYUN_MESSAGE_OPTIONS: 'Ex. !imgslim', + PICBED_UPYUN_MESSAGE_PATH: 'Ex. test/', + + // Plugin Handler + PLUGIN_HANDLER_PLUGIN_INSTALL_SUCCESS: 'Plugin installed successfully', + PLUGIN_HANDLER_PLUGIN_INSTALL_FAILED: 'Plugin installation failed', + PLUGIN_HANDLER_PLUGIN_INSTALL_FAILED_REASON: 'Plugin installation failed, error code is ${code}, error log is \n ${data}', + PLUGIN_HANDLER_PLUGIN_INSTALL_FAILED_PATH: 'Plugin installation failed, please enter a valid plugin name or valid installation path', + PLUGIN_HANDLER_PLUGIN_UNINSTALL_SUCCESS: 'Plugin uninstalled successfully', + PLUGIN_HANDLER_PLUGIN_UNINSTALL_FAILED: 'Plugin uninstall failed', + PLUGIN_HANDLER_PLUGIN_UNINSTALL_FAILED_REASON: 'Plugin uninstall failed, error code is ${code}, error log is \n ${data}', + PLUGIN_HANDLER_PLUGIN_UNINSTALL_FAILED_VALID: 'Plugin uninstall failed, please enter a valid plugin name', + PLUGIN_HANDLER_PLUGIN_UPDATE_SUCCESS: 'Plugin updated successfully', + PLUGIN_HANDLER_PLUGIN_UPDATE_FAILED: 'Plugin update failed', + PLUGIN_HANDLER_PLUGIN_UPDATE_FAILED_REASON: 'Plugin update failed, error code is ${code}, error log is \n ${data}', + PLUGIN_HANDLER_PLUGIN_UPDATE_FAILED_VALID: 'Plugin update failed, please enter a valid plugin name' +} diff --git a/libs/zhi-picgo-core/src/i18n/index.ts b/libs/zhi-picgo-core/src/i18n/index.ts new file mode 100644 index 00000000..0bf4536e --- /dev/null +++ b/libs/zhi-picgo-core/src/i18n/index.ts @@ -0,0 +1,103 @@ +import { ZH_CN, ILocalesKey, ILocales } from './zh-CN' +import { merge } from 'lodash' +import { IPicGo } from '../types' +import path from 'path' +import fs from 'fs-extra' +import yaml from 'js-yaml' + +import { ObjectAdapter, I18n } from '@picgo/i18n' +import { IStringKeyMap, II18nManager } from '../types/index' +import { ILocale } from '@picgo/i18n/dist/types' +import { EN } from './en' +import { ZH_TW } from './zh-TW' + +const languageList: IStringKeyMap> = { + 'zh-CN': ZH_CN, + 'zh-TW': ZH_TW, + en: EN +} + +class I18nManager implements II18nManager { + private readonly i18n: I18n + private readonly objectAdapter: ObjectAdapter + private readonly ctx: IPicGo + constructor (ctx: IPicGo) { + this.ctx = ctx + this.objectAdapter = new ObjectAdapter(languageList) + let language = this.ctx.getConfig('settings.language') || 'zh-CN' + if (!languageList[language]) { + language = 'zh-CN' // use default + } + this.i18n = new I18n({ + adapter: this.objectAdapter, + defaultLanguage: language + }) + this.loadOutterI18n() + } + + private loadOutterI18n (): void { + const i18nFolder = this.getOutterI18nFolder() + const files = fs.readdirSync(i18nFolder, { + withFileTypes: true + }) + files.forEach(file => { + if (file.isFile() && file.name.endsWith('.yml')) { + const i18nFilePath = path.join(i18nFolder, file.name) + const i18nFile = fs.readFileSync(i18nFilePath, 'utf8') + try { + const i18nFileObj = yaml.load(i18nFile) as ILocales + languageList[file.name.replace(/\.yml$/, '')] = i18nFileObj + } catch (e) { + console.error(e) + } + } + }) + } + + private getOutterI18nFolder (): string { + const i18nFolder = path.join(this.ctx.baseDir, 'i18n-cli') + if (!fs.pathExistsSync(i18nFolder)) { + fs.ensureDirSync(i18nFolder) + } + return i18nFolder + } + + translate(key: ILocalesKey | T, args?: IStringKeyMap): string { + return this.i18n.translate(key, args) || key + } + + setLanguage (language: string): void { + this.i18n.setLanguage(language) + this.ctx.saveConfig({ + 'settings.language': language + }) + } + + addLocale (language: string, locales: ILocale): boolean { + const originLocales = this.objectAdapter.getLocale(language) + if (!originLocales) { + return false + } + const newLocales = merge(originLocales, locales) + this.objectAdapter.setLocale(language, newLocales) + return true + } + + addLanguage (language: string, locales: ILocale): boolean { + const originLocales = this.objectAdapter.getLocale(language) + if (originLocales) { + return false + } + this.objectAdapter.setLocale(language, locales) + languageList[language] = locales + return true + } + + getLanguageList (): string[] { + return Object.keys(languageList) + } +} + +export { + I18nManager +} diff --git a/libs/zhi-picgo-core/src/i18n/zh-CN.ts b/libs/zhi-picgo-core/src/i18n/zh-CN.ts new file mode 100644 index 00000000..562ffb0e --- /dev/null +++ b/libs/zhi-picgo-core/src/i18n/zh-CN.ts @@ -0,0 +1,109 @@ +/* eslint-disable no-template-curly-in-string */ +export const ZH_CN = { + UPLOAD_FAILED: '上传失败', + CHECK_SETTINGS: '请检查你的配置项是否正确', + CHECK_SETTINGS_AND_NETWORK: '请检查你的配置项以及网络', + UPLOAD_FAILED_REASON: '错误码:${code},请打开浏览器粘贴地址查看相关原因', + SERVER_ERROR: '服务端出错,请重试', + AUTH_FAILED: '认证失败', + + // smms + PICBED_SMMS: 'SM.MS', + PICBED_SMMS_TOKEN: '设定Token', + PICBED_SMMS_BACKUP_DOMAIN: '备用上传域名', + PICBED_SMMS_MESSAGE_BACKUP_DOMAIN: '例如 smms.app', + + // Ali-cloud + PICBED_ALICLOUD: '阿里云OSS', + PICBED_ALICLOUD_ACCESSKEYID: '设定KeyId', + PICBED_ALICLOUD_ACCESSKEYSECRET: '设定KeySecret', + PICBED_ALICLOUD_BUCKET: '设定Bucket', + PICBED_ALICLOUD_AREA: '设定存储区域', + PICBED_ALICLOUD_PATH: '设定存储路径', + PICBED_ALICLOUD_CUSTOMURL: '设定自定义域名', + PICBED_ALICLOUD_OPTIONS: '设定网址后缀', + PICBED_ALICLOUD_MESSAGE_AREA: '例如:oss-cn-beijing', + PICBED_ALICLOUD_MESSAGE_PATH: '例如:test/', + PICBED_ALICLOUD_MESSAGE_OPTIONS: '例如:?x-oss-process=xxx', + PICBED_ALICLOUD_MESSAGE_CUSTOMURL: '例如:https://test.com', + + // Tencent-cloud + PICBED_TENCENTCLOUD: '腾讯云COS', + PICBED_TENCENTCLOUD_VERSION: 'COS版本', + PICBED_TENCENTCLOUD_SECRETID: '设定SecretId', + PICBED_TENCENTCLOUD_SECRETKEY: '设定SecretKey', + PICBED_TENCENTCLOUD_APPID: '设定AppId', + PICBED_TENCENTCLOUD_BUCKET: '设定Bucket', + PICBED_TENCENTCLOUD_AREA: '设定存储区域', + PICBED_TENCENTCLOUD_PATH: '设定存储路径', + PICBED_TENCENTCLOUD_OPTIONS: '设定网址后缀', + PICBED_TENCENTCLOUD_CUSTOMURL: '设定自定义域名', + PICBED_TENCENTCLOUD_MESSAGE_APPID: '例如:1234567890', + PICBED_TENCENTCLOUD_MESSAGE_AREA: '例如:ap-beijing', + PICBED_TENCENTCLOUD_MESSAGE_PATH: '例如:test/', + PICBED_TENCENTCLOUD_MESSAGE_CUSTOMURL: '例如:https://test.com', + PICBED_TENCENTCLOUD_MESSAGE_OPTIONS: '例如:?imageMogr2', + + // GitHub + PICBED_GITHUB: 'GitHub', + PICBED_GITHUB_TOKEN: '设定Token', + PICBED_GITHUB_REPO: '设定仓库名', + PICBED_GITHUB_PATH: '设定存储路径', + PICBED_GITHUB_BRANCH: '设定分支名', + PICBED_GITHUB_CUSTOMURL: '设定自定义域名', + PICBED_GITHUB_MESSAGE_REPO: '格式:username/repo', + PICBED_GITHUB_MESSAGE_BRANCH: '例如:main', + PICBED_GITHUB_MESSAGE_PATH: '例如:test/', + PICBED_GITHUB_MESSAGE_CUSTOMURL: '例如:https://test.com', + + // qiniu + PICBED_QINIU: '七牛云', + PICBED_QINIU_ACCESSKEY: '设定AccessKey', + PICBED_QINIU_SECRETKEY: '设定SecretKey', + PICBED_QINIU_BUCKET: '设定Bucket', + PICBED_QINIU_PATH: '设定存储路径', + PICBED_QINIU_URL: '设定访问网址', + PICBED_QINIU_OPTIONS: '设定网址后缀', + PICBED_QINIU_AREA: '设定存储区域', + PICBED_QINIU_MESSAGE_PATH: '例如:test/', + PICBED_QINIU_MESSAGE_AREA: '例如:z0', + PICBED_QINIU_MESSAGE_OPTIONS: '例如:?imageslim', + PICBED_QINIU_MESSAGE_URL: '例如:https://xxx.yyy.glb.clouddn.com', + + // imgur + PICBED_IMGUR: 'Imgur', + PICBED_IMGUR_CLIENTID: '设定ClientId', + PICBED_IMGUR_PROXY: '设定代理', + PICBED_IMGUR_MESSAGE_PROXY: '例如:http://127.0.0.1:1080', + + // upyun + PICBED_UPYUN: '又拍云', + PICBED_UPYUN_BUCKET: '设定Bucket', + PICBED_UPYUN_OPERATOR: '设定操作员', + PICBED_UPYUN_PASSWORD: '设定操作员密码', + PICBED_UPYUN_PATH: '设定存储路径', + PICBED_UPYUN_URL: '设定加速域名', + PICBED_UPYUN_OPTIONS: '设定网址后缀', + PICBED_UPYUN_MESSAGE_OPERATOR: '例如:me', + PICBED_UPYUN_MESSAGE_PASSWORD: '输入操作员密码', + PICBED_UPYUN_MESSAGE_URL: '例如:http://xxx.test.upcdn.net', + PICBED_UPYUN_MESSAGE_OPTIONS: '例如:!imgslim', + PICBED_UPYUN_MESSAGE_PATH: '例如:test/', + + // Plugin Handler + PLUGIN_HANDLER_PLUGIN_INSTALL_SUCCESS: '插件安装成功', + PLUGIN_HANDLER_PLUGIN_INSTALL_FAILED: '插件安装失败', + PLUGIN_HANDLER_PLUGIN_INSTALL_FAILED_REASON: '插件安装失败,失败码为${code},错误日志为 \n ${data}', + PLUGIN_HANDLER_PLUGIN_INSTALL_FAILED_PATH: '插件安装失败,请输入合法插件名或合法安装路径', + PLUGIN_HANDLER_PLUGIN_UNINSTALL_SUCCESS: '插件卸载成功', + PLUGIN_HANDLER_PLUGIN_UNINSTALL_FAILED: '插件卸载失败', + PLUGIN_HANDLER_PLUGIN_UNINSTALL_FAILED_REASON: '插件卸载失败,失败码为${code},错误日志为 \n ${data}', + PLUGIN_HANDLER_PLUGIN_UNINSTALL_FAILED_VALID: '插件卸载失败,请输入合法插件名', + PLUGIN_HANDLER_PLUGIN_UPDATE_SUCCESS: '插件更新成功', + PLUGIN_HANDLER_PLUGIN_UPDATE_FAILED: '插件更新失败', + PLUGIN_HANDLER_PLUGIN_UPDATE_FAILED_REASON: '插件更新失败,失败码为${code},错误日志为 \n ${data}', + PLUGIN_HANDLER_PLUGIN_UPDATE_FAILED_VALID: '插件更新失败,请输入合法插件名' +} + +export type ILocalesKey = keyof typeof ZH_CN +export type ILocales = typeof ZH_CN diff --git a/libs/zhi-picgo-core/src/i18n/zh-TW.ts b/libs/zhi-picgo-core/src/i18n/zh-TW.ts new file mode 100644 index 00000000..e032c2cf --- /dev/null +++ b/libs/zhi-picgo-core/src/i18n/zh-TW.ts @@ -0,0 +1,108 @@ +import { ILocales } from './zh-CN' + +/* eslint-disable no-template-curly-in-string */ +export const ZH_TW: ILocales = { + UPLOAD_FAILED: '上傳失敗', + CHECK_SETTINGS: '請檢查你的設定是否正確', + CHECK_SETTINGS_AND_NETWORK: '請檢查你的設定及網路', + UPLOAD_FAILED_REASON: '錯誤碼:${code},請打開瀏覽器貼上地址查看相關原因', + SERVER_ERROR: '伺服器出錯,請重試', + AUTH_FAILED: '認證失敗', + + // smms + PICBED_SMMS: 'SM.MS', + PICBED_SMMS_TOKEN: '設定Token', + PICBED_SMMS_BACKUP_DOMAIN: '備用上傳網址', + PICBED_SMMS_MESSAGE_BACKUP_DOMAIN: '例如 smms.app', + + // Ali-cloud + PICBED_ALICLOUD: '阿里云OSS', + PICBED_ALICLOUD_ACCESSKEYID: '設定KeyId', + PICBED_ALICLOUD_ACCESSKEYSECRET: '設定KeySecret', + PICBED_ALICLOUD_BUCKET: '設定Bucket', + PICBED_ALICLOUD_AREA: '設定儲存區域', + PICBED_ALICLOUD_PATH: '設定儲存路徑', + PICBED_ALICLOUD_CUSTOMURL: '設定自訂網址', + PICBED_ALICLOUD_OPTIONS: '設定網址後綴', + PICBED_ALICLOUD_MESSAGE_AREA: '例如:oss-cn-beijing', + PICBED_ALICLOUD_MESSAGE_PATH: '例如:test/', + PICBED_ALICLOUD_MESSAGE_OPTIONS: '例如:?x-oss-process=xxx', + PICBED_ALICLOUD_MESSAGE_CUSTOMURL: '例如:https://test.com', + + // Tencent-cloud + PICBED_TENCENTCLOUD: '騰訊云COS', + PICBED_TENCENTCLOUD_VERSION: 'COS版本', + PICBED_TENCENTCLOUD_SECRETID: '設定SecretId', + PICBED_TENCENTCLOUD_SECRETKEY: '設定SecretKey', + PICBED_TENCENTCLOUD_APPID: '設定AppId', + PICBED_TENCENTCLOUD_BUCKET: '設定Bucket', + PICBED_TENCENTCLOUD_AREA: '設定儲存區域', + PICBED_TENCENTCLOUD_PATH: '設定儲存路徑', + PICBED_TENCENTCLOUD_OPTIONS: '設定網址後綴', + PICBED_TENCENTCLOUD_CUSTOMURL: '設定自訂網址', + PICBED_TENCENTCLOUD_MESSAGE_APPID: '例如:1234567890', + PICBED_TENCENTCLOUD_MESSAGE_AREA: '例如:ap-beijing', + PICBED_TENCENTCLOUD_MESSAGE_PATH: '例如:test/', + PICBED_TENCENTCLOUD_MESSAGE_CUSTOMURL: '例如:https://test.com', + PICBED_TENCENTCLOUD_MESSAGE_OPTIONS: '例如:?imageMogr2', + + // GitHub + PICBED_GITHUB: 'GitHub', + PICBED_GITHUB_TOKEN: '設定Token', + PICBED_GITHUB_REPO: '設定倉庫名稱', + PICBED_GITHUB_PATH: '設定儲存路徑', + PICBED_GITHUB_BRANCH: '設定分支名稱', + PICBED_GITHUB_CUSTOMURL: '設定自訂網址', + PICBED_GITHUB_MESSAGE_REPO: '格式:username/repo', + PICBED_GITHUB_MESSAGE_BRANCH: '例如:main', + PICBED_GITHUB_MESSAGE_PATH: '例如:test/', + PICBED_GITHUB_MESSAGE_CUSTOMURL: '例如:https://test.com', + + // qiniu + PICBED_QINIU: '七牛云', + PICBED_QINIU_ACCESSKEY: '設定AccessKey', + PICBED_QINIU_SECRETKEY: '設定SecretKey', + PICBED_QINIU_BUCKET: '設定Bucket', + PICBED_QINIU_PATH: '設定儲存路徑', + PICBED_QINIU_URL: '設定訪問網址', + PICBED_QINIU_OPTIONS: '設定網址後綴', + PICBED_QINIU_AREA: '設定儲存區域', + PICBED_QINIU_MESSAGE_PATH: '例如:test/', + PICBED_QINIU_MESSAGE_AREA: '例如:z0', + PICBED_QINIU_MESSAGE_OPTIONS: '例如:?imageslim', + PICBED_QINIU_MESSAGE_URL: '例如:https://xxx.yyy.glb.clouddn.com', + + // imgur + PICBED_IMGUR: 'Imgur', + PICBED_IMGUR_CLIENTID: '設定ClientId', + PICBED_IMGUR_PROXY: '設定PROXY', + PICBED_IMGUR_MESSAGE_PROXY: '例如:http://127.0.0.1:1080', + + // upyun + PICBED_UPYUN: '又拍云', + PICBED_UPYUN_BUCKET: '設定Bucket', + PICBED_UPYUN_OPERATOR: '設定操作員', + PICBED_UPYUN_PASSWORD: '設定操作員密碼', + PICBED_UPYUN_PATH: '設定儲存路徑', + PICBED_UPYUN_URL: '設定加速網址', + PICBED_UPYUN_OPTIONS: '設定網址後綴', + PICBED_UPYUN_MESSAGE_OPERATOR: '例如:me', + PICBED_UPYUN_MESSAGE_PASSWORD: '輸入操作員密碼', + PICBED_UPYUN_MESSAGE_URL: '例如:http://xxx.test.upcdn.net', + PICBED_UPYUN_MESSAGE_OPTIONS: '例如:!imgslim', + PICBED_UPYUN_MESSAGE_PATH: '例如:test/', + + // Plugin Handler + PLUGIN_HANDLER_PLUGIN_INSTALL_SUCCESS: '插件安裝成功', + PLUGIN_HANDLER_PLUGIN_INSTALL_FAILED: '插件安裝失敗', + PLUGIN_HANDLER_PLUGIN_INSTALL_FAILED_REASON: '插件安裝失敗,失敗碼為${code},錯誤紀錄為 \n ${data}', + PLUGIN_HANDLER_PLUGIN_INSTALL_FAILED_PATH: '插件安裝失敗,請輸入正確的插件名稱或正確的安裝路徑', + PLUGIN_HANDLER_PLUGIN_UNINSTALL_SUCCESS: '插件卸載成功', + PLUGIN_HANDLER_PLUGIN_UNINSTALL_FAILED: '插件卸載失敗', + PLUGIN_HANDLER_PLUGIN_UNINSTALL_FAILED_REASON: '插件卸載失敗,失敗碼為${code},錯誤紀錄為 \n ${data}', + PLUGIN_HANDLER_PLUGIN_UNINSTALL_FAILED_VALID: '插件卸載失敗,請輸入正確的插件名稱', + PLUGIN_HANDLER_PLUGIN_UPDATE_SUCCESS: '插件更新成功', + PLUGIN_HANDLER_PLUGIN_UPDATE_FAILED: '插件更新失敗', + PLUGIN_HANDLER_PLUGIN_UPDATE_FAILED_REASON: '插件更新失敗,失敗碼為${code},錯誤紀錄為 \n ${data}', + PLUGIN_HANDLER_PLUGIN_UPDATE_FAILED_VALID: '插件更新失敗,請輸入正確的插件名稱' +} diff --git a/libs/zhi-picgo-core/src/index.ts b/libs/zhi-picgo-core/src/index.ts new file mode 100644 index 00000000..3f5ee00a --- /dev/null +++ b/libs/zhi-picgo-core/src/index.ts @@ -0,0 +1,11 @@ +export { PicGo } from './core/PicGo' +export { Lifecycle } from './core/Lifecycle' + +export { Logger } from './lib/Logger' +export { PluginHandler } from './lib/PluginHandler' +export { LifecyclePlugins } from './lib/LifecyclePlugins' +export { Commander } from './lib/Commander' +export { PluginLoader } from './lib/PluginLoader' +export { Request } from './lib/Request' + +export * from './types' diff --git a/libs/zhi-picgo-core/src/lib/Commander.ts b/libs/zhi-picgo-core/src/lib/Commander.ts new file mode 100644 index 00000000..5210c905 --- /dev/null +++ b/libs/zhi-picgo-core/src/lib/Commander.ts @@ -0,0 +1,97 @@ +/* eslint-disable @typescript-eslint/no-misused-promises */ +import { Command } from 'commander' +import inquirer, { Inquirer } from 'inquirer' +import { IPlugin, ICommander, IPicGo } from '../types' +import commanders from '../plugins/commander' +import { getCurrentPluginName } from './LifecyclePlugins' + +export class Commander implements ICommander { + private readonly name = 'commander' + static currentPlugin: string | null + private readonly list: Map = new Map() + private readonly pluginIdMap: Map = new Map() + private readonly ctx: IPicGo + + program: Command + inquirer: Inquirer + + constructor (ctx: IPicGo) { + this.program = new Command() + this.inquirer = inquirer + this.ctx = ctx + } + + getName (): string { + return this.name + } + + init (): void { + this.program + .version(process.env.PICGO_VERSION, '-v, --version') + .option('-d, --debug', 'debug mode', () => { + this.ctx.setConfig({ + debug: true + }) + }) + .option('-s, --silent', 'silent mode', () => { + this.ctx.setConfig({ + silent: true + }) + }) + .on('command:*', () => { + this.ctx.log.error(`Invalid command: ${this.program.args.join(' ')}\nSee --help for a list of available commands.`) + process.exit(1) + }) + + // built-in commands + commanders(this.ctx) + } + + register (id: string, plugin: IPlugin): void { + if (!id) throw new TypeError('name is required!') + if (typeof plugin.handle !== 'function') throw new TypeError('plugin.handle must be a function!') + if (this.list.has(id)) throw new TypeError(`${this.name} plugin duplicate id: ${id}!`) + this.list.set(id, plugin) + const currentPluginName = getCurrentPluginName() + if (currentPluginName !== null) { + if (this.pluginIdMap.has(currentPluginName)) { + this.pluginIdMap.get(currentPluginName)?.push(id) + } else { + this.pluginIdMap.set(currentPluginName, [id]) + } + } + } + + unregister (pluginName: string): void { + if (this.pluginIdMap.has(pluginName)) { + const pluginList = this.pluginIdMap.get(pluginName) + pluginList?.forEach((plugin: string) => { + this.list.delete(plugin) + }) + } + } + + loadCommands (): void { + this.getList().forEach((item: IPlugin) => { + try { + item.handle(this.ctx) + } catch (e: any) { + this.ctx.log.error(e) + } + }) + } + + get (id: string): IPlugin | undefined { + return this.list.get(id) + } + + getList (): IPlugin[] { + return [...this.list.values()] + } + + getIdList (): string[] { + return [...this.list.keys()] + } +} + +export default Commander diff --git a/libs/zhi-picgo-core/src/lib/LifecyclePlugins.ts b/libs/zhi-picgo-core/src/lib/LifecyclePlugins.ts new file mode 100644 index 00000000..e6a6a967 --- /dev/null +++ b/libs/zhi-picgo-core/src/lib/LifecyclePlugins.ts @@ -0,0 +1,63 @@ +import { IPlugin, ILifecyclePlugins } from '../types' + +export class LifecyclePlugins implements ILifecyclePlugins { + static currentPlugin: string | null + private readonly list: Map + private readonly pluginIdMap: Map + private readonly name: string + + constructor (name: string) { + this.name = name + this.list = new Map() + this.pluginIdMap = new Map() + } + + register (id: string, plugin: IPlugin): void { + if (!id) throw new TypeError('id is required!') + if (typeof plugin.handle !== 'function') throw new TypeError('plugin.handle must be a function!') + if (this.list.has(id)) throw new TypeError(`${this.name} duplicate id: ${id}!`) + this.list.set(id, plugin) + if (LifecyclePlugins.currentPlugin) { + if (this.pluginIdMap.has(LifecyclePlugins.currentPlugin)) { + this.pluginIdMap.get(LifecyclePlugins.currentPlugin)?.push(id) + } else { + this.pluginIdMap.set(LifecyclePlugins.currentPlugin, [id]) + } + } + } + + unregister (pluginName: string): void { + if (this.pluginIdMap.has(pluginName)) { + const pluginList = this.pluginIdMap.get(pluginName) + pluginList?.forEach((plugin: string) => { + this.list.delete(plugin) + }) + } + } + + getName (): string { + return this.name + } + + get (id: string): IPlugin | undefined { + return this.list.get(id) + } + + getList (): IPlugin[] { + return [...this.list.values()] + } + + getIdList (): string[] { + return [...this.list.keys()] + } +} + +export const setCurrentPluginName = (name: string | null = null): void => { + LifecyclePlugins.currentPlugin = name +} + +export const getCurrentPluginName = (): string | null => { + return LifecyclePlugins.currentPlugin +} + +export default LifecyclePlugins diff --git a/libs/zhi-picgo-core/src/lib/Logger.ts b/libs/zhi-picgo-core/src/lib/Logger.ts new file mode 100644 index 00000000..43fbabf5 --- /dev/null +++ b/libs/zhi-picgo-core/src/lib/Logger.ts @@ -0,0 +1,141 @@ +import chalk from 'chalk' +import dayjs from 'dayjs' +import fs from 'fs-extra' +import path from 'path' +import util from 'util' +import { ILogType } from '../utils/enum' +import { + ILogArgvType, + ILogArgvTypeWithError, + Undefinable, + ILogColor, + ILogger, + IPicGo +} from '../types' +import { forceNumber, isDev } from '../utils/common' + +export class Logger implements ILogger { + private readonly level = { + [ILogType.success]: 'green', + [ILogType.info]: 'blue', + [ILogType.warn]: 'yellow', + [ILogType.error]: 'red' + } + + private readonly ctx: IPicGo + private logLevel!: string + private logPath!: string + constructor (ctx: IPicGo) { + this.ctx = ctx + } + + private handleLog (type: ILogType, ...msg: ILogArgvTypeWithError[]): void { + // check config.silent + if (!this.ctx.getConfig>('silent')) { + const logHeader = chalk[this.level[type] as ILogColor](`[PicGo ${type.toUpperCase()}]:`) + console.log(logHeader, ...msg) + this.logLevel = this.ctx.getConfig('settings.logLevel') + this.logPath = this.ctx.getConfig>('settings.logPath') || path.join(this.ctx.baseDir, './picgo.log') + setTimeout(() => { + // fix log file is too large, now the log file's default size is 10 MB + try { + const result = this.checkLogFileIsLarge(this.logPath) + if (result.isLarge) { + const warningMsg = `Log file is too large (> ${(result.logFileSizeLimit!) / 1024 / 1024 || '10'} MB), recreate log file` + console.log(chalk.yellow('[PicGo WARN]:'), warningMsg) + this.recreateLogFile(this.logPath) + msg.unshift(warningMsg) + } + this.handleWriteLog(this.logPath, type, ...msg) + } catch (e) { + // why??? + console.error('[PicGo Error] on checking log file size', e) + } + }, 0) + } + } + + private checkLogFileIsLarge (logPath: string): { + isLarge: boolean + logFileSize?: number + logFileSizeLimit?: number + } { + if (fs.existsSync(logPath)) { + const logFileSize = fs.statSync(logPath).size + const logFileSizeLimit = forceNumber(this.ctx.getConfig>('settings.logFileSizeLimit') || 10) * 1024 * 1024 // 10 MB default + return { + isLarge: logFileSize > logFileSizeLimit, + logFileSize, + logFileSizeLimit + } + } + return { + isLarge: false + } + } + + private recreateLogFile (logPath: string): void { + if (fs.existsSync(logPath)) { + fs.unlinkSync(logPath) + fs.createFileSync(logPath) + } + } + + private handleWriteLog (logPath: string, type: string, ...msg: ILogArgvTypeWithError[]): void { + try { + if (this.checkLogLevel(type, this.logLevel)) { + let log = `${dayjs().format('YYYY-MM-DD HH:mm:ss')} [PicGo ${type.toUpperCase()}] ` + msg.forEach((item: ILogArgvTypeWithError) => { + if (item instanceof Error && type === 'error') { + log += `\n------Error Stack Begin------\n${util.format(item?.stack)}\n-------Error Stack End------- ` + } else { + if (typeof item === 'object') { + item = JSON.stringify(item, null, 2) + } + log += `${item as string} ` + } + }) + log += '\n' + // A synchronized approach to avoid log msg sequence errors + fs.appendFileSync(logPath, log) + } + } catch (e) { + console.error('[PicGo Error] on writing log file', e) + } + } + + private checkLogLevel (type: string, level: undefined | string | string[]): boolean { + if (level === undefined || level === 'all') { + return true + } + if (Array.isArray(level)) { + return level.some((item: string) => (item === type || item === 'all')) + } else { + return type === level + } + } + + success (...msg: ILogArgvType[]): void { + return this.handleLog(ILogType.success, ...msg) + } + + info (...msg: ILogArgvType[]): void { + return this.handleLog(ILogType.info, ...msg) + } + + error (...msg: ILogArgvTypeWithError[]): void { + return this.handleLog(ILogType.error, ...msg) + } + + warn (...msg: ILogArgvType[]): void { + return this.handleLog(ILogType.warn, ...msg) + } + + debug (...msg: ILogArgvType[]): void { + if (isDev()) { + this.handleLog(ILogType.info, ...msg) + } + } +} + +export default Logger diff --git a/libs/zhi-picgo-core/src/lib/PluginHandler.ts b/libs/zhi-picgo-core/src/lib/PluginHandler.ts new file mode 100644 index 00000000..50f920f8 --- /dev/null +++ b/libs/zhi-picgo-core/src/lib/PluginHandler.ts @@ -0,0 +1,293 @@ +import spawn from 'cross-spawn' +import { + IResult, + IProcessEnv, + IPluginProcessResult, + IPluginHandler, + IPluginHandlerOptions, + Undefinable, + IPicGo, + IPluginHandlerResult +} from '../types' +import { IBuildInEvent } from '../utils/enum' +import { getProcessPluginName, getNormalPluginName } from '../utils/common' +import { ILocalesKey } from '../i18n/zh-CN' + +export class PluginHandler implements IPluginHandler { + // Thanks to feflow -> https://github.com/feflow/feflow/blob/master/lib/internal/install/plugin.js + private readonly ctx: IPicGo + constructor (ctx: IPicGo) { + this.ctx = ctx + } + + async install (plugins: string[], options?: IPluginHandlerOptions, env?: IProcessEnv): Promise> { + if (!options) { + options = {} + } + const installedPlugins: string[] = [] + const processPlugins = plugins + .map((item: string) => handlePluginNameProcess(this.ctx, item)) + .filter((item) => { + // detect if has already installed + // or will cause error + if (this.ctx.pluginLoader.hasPlugin(item.pkgName)) { + installedPlugins.push(item.pkgName) + this.ctx.log.success(`PicGo has already installed ${item.pkgName}`) + return false + } + // if something wrong, filter it out + if (!item.success) { + return false + } + return true + }) + const fullNameList = processPlugins.map(item => item.fullName) + const pkgNameList = processPlugins.map(item => item.pkgName) + if (fullNameList.length > 0) { + // install plugins must use fullNameList: + // 1. install remote pacage + // 2. install local pacage + const result = await this.execCommand('install', fullNameList, this.ctx.baseDir, options, env) + console.log('execCommand install result=>', result) + if (!result.code) { + pkgNameList.forEach((pluginName: string) => { + this.ctx.pluginLoader.registerPlugin(pluginName) + }) + this.ctx.log.success(this.ctx.i18n.translate('PLUGIN_HANDLER_PLUGIN_INSTALL_SUCCESS')) + this.ctx.emit('installSuccess', { + title: this.ctx.i18n.translate('PLUGIN_HANDLER_PLUGIN_INSTALL_SUCCESS'), + body: [...pkgNameList, ...installedPlugins] + }) + const res: IPluginHandlerResult = { + success: true, + body: [...pkgNameList, ...installedPlugins] + } + return res + } else { + const err = this.ctx.i18n.translate('PLUGIN_HANDLER_PLUGIN_INSTALL_FAILED_REASON', { + code: `${result.code}`, + data: result.data + }) + this.ctx.log.error(err) + this.ctx.emit('installFailed', { + title: this.ctx.i18n.translate('PLUGIN_HANDLER_PLUGIN_INSTALL_FAILED'), + body: err + }) + const res: IPluginHandlerResult = { + success: false, + body: err + } + return res + } + } else if (installedPlugins.length === 0) { + const err = this.ctx.i18n.translate('PLUGIN_HANDLER_PLUGIN_UNINSTALL_FAILED_VALID') + this.ctx.log.error(err) + this.ctx.emit('installFailed', { + title: this.ctx.i18n.translate('PLUGIN_HANDLER_PLUGIN_INSTALL_FAILED'), + body: err + }) + const res: IPluginHandlerResult = { + success: false, + body: err + } + return res + } else { + this.ctx.log.success(this.ctx.i18n.translate('PLUGIN_HANDLER_PLUGIN_INSTALL_SUCCESS')) + this.ctx.emit('installSuccess', { + title: this.ctx.i18n.translate('PLUGIN_HANDLER_PLUGIN_INSTALL_SUCCESS'), + body: [...pkgNameList, ...installedPlugins] + }) + const res: IPluginHandlerResult = { + success: true, + body: [...pkgNameList, ...installedPlugins] + } + return res + } + } + + async uninstall (plugins: string[], options?: IPluginHandlerOptions, env?: IProcessEnv): Promise> { + if (!options) { + options = {} + } + const processPlugins = plugins.map((item: string) => handlePluginNameProcess(this.ctx, item)).filter(item => item.success) + const pkgNameList = processPlugins.map(item => item.pkgName) + if (pkgNameList.length > 0) { + // uninstall plugins must use pkgNameList: + // npm uninstall will use the package.json's name + const result = await this.execCommand('uninstall', pkgNameList, this.ctx.baseDir, options, env) + console.log('execCommand uninstall result=>', result) + if (!result.code) { + pkgNameList.forEach((pluginName: string) => { + this.ctx.pluginLoader.unregisterPlugin(pluginName) + }) + this.ctx.log.success(this.ctx.i18n.translate('PLUGIN_HANDLER_PLUGIN_UNINSTALL_SUCCESS')) + this.ctx.emit('uninstallSuccess', { + title: this.ctx.i18n.translate('PLUGIN_HANDLER_PLUGIN_UNINSTALL_SUCCESS'), + body: pkgNameList + }) + const res: IPluginHandlerResult = { + success: true, + body: pkgNameList + } + return res + } else { + const err = this.ctx.i18n.translate('PLUGIN_HANDLER_PLUGIN_UNINSTALL_FAILED_REASON', { + code: `${result.code}`, + data: result.data + }) + this.ctx.log.error(err) + this.ctx.emit('uninstallFailed', { + title: this.ctx.i18n.translate('PLUGIN_HANDLER_PLUGIN_UNINSTALL_FAILED'), + body: err + }) + const res: IPluginHandlerResult = { + success: false, + body: err + } + return res + } + } else { + const err = this.ctx.i18n.translate('PLUGIN_HANDLER_PLUGIN_UNINSTALL_FAILED_VALID') + this.ctx.log.error(err) + this.ctx.emit('uninstallFailed', { + title: this.ctx.i18n.translate('PLUGIN_HANDLER_PLUGIN_UNINSTALL_FAILED'), + body: err + }) + const res: IPluginHandlerResult = { + success: false, + body: err + } + return res + } + } + + async update (plugins: string[], options?: IPluginHandlerOptions, env?: IProcessEnv): Promise> { + if (!options) { + options = {} + } + const processPlugins = plugins.map((item: string) => handlePluginNameProcess(this.ctx, item)).filter(item => item.success) + const pkgNameList = processPlugins.map(item => item.pkgName) + if (pkgNameList.length > 0) { + // update plugins must use pkgNameList: + // npm update will use the package.json's name + const result = await this.execCommand('update', pkgNameList, this.ctx.baseDir, options, env) + console.log('execCommand update result=>', result) + if (!result.code) { + this.ctx.log.success(this.ctx.i18n.translate('PLUGIN_HANDLER_PLUGIN_UPDATE_SUCCESS')) + this.ctx.emit('updateSuccess', { + title: this.ctx.i18n.translate('PLUGIN_HANDLER_PLUGIN_UPDATE_SUCCESS'), + body: pkgNameList + }) + const res: IPluginHandlerResult = { + success: true, + body: pkgNameList + } + return res + } else { + const err = this.ctx.i18n.translate('PLUGIN_HANDLER_PLUGIN_UPDATE_FAILED_REASON', { + code: `${result.code}`, + data: result.data + }) + this.ctx.log.error(err) + this.ctx.emit('updateFailed', { + title: this.ctx.i18n.translate('PLUGIN_HANDLER_PLUGIN_UPDATE_FAILED'), + body: err + }) + const res: IPluginHandlerResult = { + success: false, + body: err + } + return res + } + } else { + const err = this.ctx.i18n.translate('PLUGIN_HANDLER_PLUGIN_UPDATE_FAILED_VALID') + this.ctx.log.error(err) + this.ctx.emit('updateFailed', { + title: this.ctx.i18n.translate('PLUGIN_HANDLER_PLUGIN_UPDATE_FAILED'), + body: err + }) + const res: IPluginHandlerResult = { + success: false, + body: err + } + return res + } + } + + private async execCommand (cmd: string, modules: string[], where: string, options: IPluginHandlerOptions = {}, env: IProcessEnv = {}): Promise { + // options first + const registry = options.registry || this.ctx.getConfig>('settings.registry') + const proxy = options.proxy || this.ctx.getConfig>('settings.proxy') + return await new Promise((resolve: any): void => { + let args = [cmd].concat(modules).concat('--color=always').concat('--save') + if (registry) { + args = args.concat(`--registry=${registry}`) + } + if (proxy) { + args = args.concat(`--proxy=${proxy}`) + } + try { + const npmOptions = { cwd: where, env: Object.assign({}, process.env, env) } + console.log('Start run npm, args=>', args) + console.log('Start run npm, npmOptions=>', npmOptions) + const npm = spawn('npm', args, npmOptions) + + let output = '' + npm.stdout?.on('data', (data: string) => { + output += data + }).pipe(process.stdout) + + npm.stderr?.on('data', (data: string) => { + output += data + }).pipe(process.stderr) + + npm.on('close', (code: number) => { + if (!code) { + resolve({ code: 0, data: output }) + } else { + resolve({ code: code, data: output }) + } + }) + // for users who haven't installed node.js + npm.on('error', (err: Error) => { + this.ctx.log.error(err) + this.ctx.log.error('NPM is not installed') + this.ctx.emit(IBuildInEvent.FAILED, 'NPM is not installed') + }) + } catch (e) { + this.ctx.log.error(e as Error) + this.ctx.emit(IBuildInEvent.FAILED, e) + } + }) + } +} + +/** + * transform the input plugin name or path string to valid result + * @param ctx + * @param nameOrPath + */ +const handlePluginNameProcess = (ctx: IPicGo, nameOrPath: string): IPluginProcessResult => { + const res = { + success: false, + fullName: '', + pkgName: '' + } + const result = getProcessPluginName(nameOrPath, ctx.log) + if (!result) { + return res + } + // first get result then do this process + // or some error will log twice + const pkgName = getNormalPluginName(result, ctx.log) + if (!pkgName) { + return res + } + return { + success: true, + fullName: result, + pkgName + } +} + +export default PluginHandler diff --git a/libs/zhi-picgo-core/src/lib/PluginLoader.ts b/libs/zhi-picgo-core/src/lib/PluginLoader.ts new file mode 100644 index 00000000..978de042 --- /dev/null +++ b/libs/zhi-picgo-core/src/lib/PluginLoader.ts @@ -0,0 +1,153 @@ +import fs from 'fs-extra' +import path from 'path' +import resolve from 'resolve' +import { IBuildInEvent } from '../utils/enum' +import { IPicGo, IPicGoPlugin, IPluginLoader, IPicGoPluginInterface } from '../types/index' +import { setCurrentPluginName } from './LifecyclePlugins' + +/** + * Local plugin loader, file system is required + */ +export class PluginLoader implements IPluginLoader { + private readonly ctx: IPicGo + private list: string[] = [] + private readonly fullList: Set = new Set() + private readonly pluginMap: Map = new Map() + constructor (ctx: IPicGo) { + this.ctx = ctx + this.init() + } + + private init (): void { + const packagePath = path.join(this.ctx.baseDir, 'package.json') + if (!fs.existsSync(packagePath)) { + const pkg = { + name: 'picgo-plugins', + description: 'picgo-plugins', + repository: 'https://github.com/PicGo/PicGo-Core', + license: 'MIT' + } + fs.writeFileSync(packagePath, JSON.stringify(pkg), 'utf8') + } + } + + // get plugin entry + private resolvePlugin (ctx: IPicGo, name: string): string { + try { + return resolve.sync(name, { basedir: ctx.baseDir }) + } catch (err) { + return path.join(ctx.baseDir, 'node_modules', name) + } + } + + // load all third party plugin + load (): boolean { + const packagePath = path.join(this.ctx.baseDir, 'package.json') + const pluginDir = path.join(this.ctx.baseDir, 'node_modules/') + // Thanks to hexo -> https://github.com/hexojs/hexo/blob/master/lib/hexo/load_plugins.js + if (!fs.existsSync(pluginDir)) { + return false + } + const json = fs.readJSONSync(packagePath) + const deps = Object.keys(json.dependencies || {}) + const devDeps = Object.keys(json.devDependencies || {}) + const modules = deps.concat(devDeps).filter((name: string) => { + if (!/^picgo-plugin-|^@[^/]+\/picgo-plugin-/.test(name)) return false + const path = this.resolvePlugin(this.ctx, name) + return fs.existsSync(path) + }) + for (const module of modules) { + this.registerPlugin(module) + } + return true + } + + registerPlugin (name: string, plugin?: IPicGoPlugin): void { + if (!name || typeof name !== 'string') { + this.ctx.log.warn('Please provide valid plugin') + return + } + console.log('Start registering plugin ' + name + ' ...') + this.fullList.add(name) + try { + // register local plugin + if (!plugin) { + if (this.ctx.getConfig(`picgoPlugins.${name}`) === true || (this.ctx.getConfig(`picgoPlugins.${name}`) === undefined)) { + this.list.push(name) + setCurrentPluginName(name) + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + this.getPlugin(name)!.register(this.ctx) + const plugin = `picgoPlugins[${name}]` + this.ctx.saveConfig( + { + [plugin]: true + } + ) + } + } else { + // register provided plugin + // && won't write config to files + this.list.push(name) + setCurrentPluginName(name) + const pluginInterface = plugin(this.ctx) + this.pluginMap.set(name, pluginInterface) + pluginInterface.register(this.ctx) + } + } catch (e) { + this.pluginMap.delete(name) + this.list = this.list.filter((item: string) => item !== name) + this.fullList.delete(name) + this.ctx.log.error(e as Error) + this.ctx.emit(IBuildInEvent.NOTIFICATION, { + title: `Plugin ${name} Load Error`, + body: e + }) + } + } + + unregisterPlugin (name: string): void { + this.list = this.list.filter((item: string) => item !== name) + this.fullList.delete(name) + this.pluginMap.delete(name) + setCurrentPluginName(name) + this.ctx.helper.uploader.unregister(name) + this.ctx.helper.transformer.unregister(name) + this.ctx.helper.beforeTransformPlugins.unregister(name) + this.ctx.helper.beforeUploadPlugins.unregister(name) + this.ctx.helper.afterUploadPlugins.unregister(name) + this.ctx.cmd.unregister(name) + this.ctx.removeConfig('picgoPlugins', name) + } + + // get plugin by name + getPlugin (name: string): IPicGoPluginInterface | undefined { + if (this.pluginMap.has(name)) { + return this.pluginMap.get(name) + } + const pluginDir = path.join(this.ctx.baseDir, 'node_modules/') + console.log('Start requiring plugin lib, pluginDir', pluginDir) + console.log('Start requiring plugin lib, name', name) + const plugin = require(pluginDir + name)(this.ctx) + this.pluginMap.set(name, plugin) + return plugin + } + + /** + * Get the list of enabled plugins + */ + getList (): string[] { + return this.list + } + + hasPlugin (name: string): boolean { + return this.fullList.has(name) + } + + /** + * Get the full list of plugins, whether it is enabled or not + */ + getFullList (): string[] { + return [...this.fullList] + } +} +export default PluginLoader diff --git a/libs/zhi-picgo-core/src/lib/Request.ts b/libs/zhi-picgo-core/src/lib/Request.ts new file mode 100644 index 00000000..4c7494be --- /dev/null +++ b/libs/zhi-picgo-core/src/lib/Request.ts @@ -0,0 +1,239 @@ +/* eslint-disable @typescript-eslint/explicit-function-return-type */ +/* eslint-disable @typescript-eslint/promise-function-async */ +import axios, { AxiosRequestConfig, AxiosResponse } from 'axios' +import { IPicGo, Undefinable, IConfigChangePayload, IConfig, IRequestConfig, IOldReqOptions, IResponse, IFullResponse, IRequest } from '../types' +import { IBusEvent } from '../utils/enum' +import { eventBus } from '../utils/eventBus' +import { URL } from 'url' +import FormData from 'form-data' +import https from 'https' +import tunnel from 'tunnel' +const httpsAgent = new https.Agent({ + maxVersion: 'TLSv1.2', + minVersion: 'TLSv1.2' +}) + +// thanks for https://github.dev/request/request/blob/master/index.js +function appendFormData (form: FormData, key: string, data: any): void { + if (typeof data === 'object' && 'value' in data && 'options' in data) { + form.append(key, data.value, data.options) + } else { + form.append(key, data) + } +} + +function requestInterceptor (options: IOldReqOptions | AxiosRequestConfig): AxiosRequestConfig & { + __isOldOptions?: boolean +} { + let __isOldOptions = false + const opt: AxiosRequestConfig & { + __isOldOptions?: boolean + } = { + ...options, + url: (options.url as string) || '', + headers: options.headers || {} + } + // user request config proxy + if (options.proxy) { + let proxyOptions = options.proxy + if (typeof proxyOptions === 'string') { + try { + proxyOptions = new URL(options.proxy) + } catch (e) { + proxyOptions = false + opt.proxy = false + console.error(e) + } + __isOldOptions = true + } + if (proxyOptions) { + if (options.url?.startsWith('https://')) { + opt.proxy = false + opt.httpsAgent = tunnel.httpsOverHttp({ + proxy: { + host: proxyOptions?.hostname, + port: parseInt(proxyOptions?.port, 10) + } + }) + } else { + opt.proxy = { + host: proxyOptions.hostname, + port: parseInt(proxyOptions.port, 10), + protocol: 'http' + } + } + } + } + if ('formData' in options) { + const form = new FormData() + for (const key in options.formData) { + const data = options.formData[key] + appendFormData(form, key, data) + } + opt.data = form + opt.headers = Object.assign(opt.headers || {}, form.getHeaders()) + __isOldOptions = true + // @ts-expect-error + delete opt.formData + } + if ('body' in options) { + opt.data = options.body + __isOldOptions = true + // @ts-expect-error + delete opt.body + } + if ('qs' in options) { + opt.params = options.qs + __isOldOptions = true + } + opt.__isOldOptions = __isOldOptions + return opt +} + +function responseInterceptor (response: AxiosResponse): IFullResponse { + return { + ...response, + statusCode: response.status, + body: response.data + } +} + +function responseErrorHandler (error: any) { + // if (error.response) { + // // The request was made and the server responded with a status code + // // that falls out of the range of 2xx + // return Promise.reject(erro) + // } else if (error.request) { + // // The request was made but no response was received + // // `error.request` is an instance of XMLHttpRequest in the browser and an instance of + // // http.ClientRequest in node.js + // return Promise.reject(error.request) + // } else { + // // Something happened in setting up the request that triggered an Error + // return Promise.reject(error.message) + // } + const errorObj = { + method: error?.config?.method?.toUpperCase() || '', + url: error?.config?.url || '', + statusCode: error?.response?.status || 0, + message: error?.message || '', + stack: error?.stack || {}, + response: { + status: error?.response?.status || 0, + statusCode: error?.response?.status || 0, + body: error?.response?.data || '' + } + } + return Promise.reject(errorObj) +} + +export class Request implements IRequest { + private readonly ctx: IPicGo + private proxy: Undefinable = '' + options: AxiosRequestConfig = {} + constructor (ctx: IPicGo) { + this.ctx = ctx + this.init() + eventBus.on(IBusEvent.CONFIG_CHANGE, (data: IConfigChangePayload) => { + switch (data.configName) { + case 'picBed': + if ((data.value as IConfig['picBed'])?.proxy) { + this.proxy = (data.value as IConfig['picBed']).proxy + } + break + case 'picBed.proxy': + this.proxy = data.value as string + break + } + }) + } + + private init (): void { + const proxy = this.ctx.getConfig>('picBed.proxy') + if (proxy) { + this.proxy = proxy + } + } + + private handleProxy (): AxiosRequestConfig['proxy'] | false { + if (this.proxy) { + try { + const proxyOptions = new URL(this.proxy) + return { + host: proxyOptions.hostname, + port: parseInt(proxyOptions.port || '0', 10), + protocol: proxyOptions.protocol + } + } catch (e) { + } + } + return false + } + + // #64 dynamic get proxy value + request extends IOldReqOptions ? IOldReqOptions : IRequestConfig extends AxiosRequestConfig ? AxiosRequestConfig : never + )> (options: U): Promise> { + this.options.proxy = this.handleProxy() + this.options.headers = options.headers || {} + this.options.maxBodyLength = Infinity + this.options.maxContentLength = Infinity + if (this.options.proxy && options.url?.startsWith('https://')) { + this.options.httpsAgent = tunnel.httpsOverHttp({ + proxy: { + host: this.options.proxy.host, + port: this.options.proxy.port + } + }) + this.options.proxy = false + } else { + this.options.httpsAgent = httpsAgent + } + // !NOTICE this.options !== options + // this.options is the default options + const instance = axios.create(this.options) + instance.interceptors.response.use(responseInterceptor, responseErrorHandler) + + // compatible with old request options to new options + const opt = requestInterceptor(options) + + instance.interceptors.request.use(function (obj) { + // handle Content-Type + let contentType = '' + if (obj?.headers?.contentType) { + contentType = obj.headers.contentType as string + delete obj.headers.contentType + } else if (obj?.headers?.ContentType) { + contentType = obj.headers.ContentType as string + delete obj.headers.ContentType + } else if (obj?.headers?.['content-type']) { + contentType = obj.headers['content-type'] as string + delete obj.headers['content-type'] + } + if (contentType !== '' && obj.headers) { + obj.headers['Content-Type'] = contentType + } + return obj + }) + if ('resolveWithFullResponse' in options && options.resolveWithFullResponse) { + return instance.request(opt) + } else { + return instance.request(opt).then(res => { + // use old request option format + if (opt.__isOldOptions) { + if ('json' in options) { + if (options.json) { + return res.data + } + } else { + return JSON.stringify(res.data) + } + } else { + return res.data + } + }) as Promise> + } + } +} + +export default Request diff --git a/libs/zhi-picgo-core/src/libs.d.ts b/libs/zhi-picgo-core/src/libs.d.ts new file mode 100644 index 00000000..8849024c --- /dev/null +++ b/libs/zhi-picgo-core/src/libs.d.ts @@ -0,0 +1,8 @@ +declare module 'download-git-repo' { + function download (...args: any[]): any + export = download +} +declare module 'lodash-id' { + var lodashId: any + export = lodashId +} diff --git a/libs/zhi-picgo-core/src/plugins/commander/config.ts b/libs/zhi-picgo-core/src/plugins/commander/config.ts new file mode 100644 index 00000000..8e1b3430 --- /dev/null +++ b/libs/zhi-picgo-core/src/plugins/commander/config.ts @@ -0,0 +1,12 @@ +import { IPicGo, IPlugin } from '../../types' + +const config: IPlugin = { + handle: (ctx: IPicGo) => { + const cmd = ctx.cmd + cmd.program + .option('-c, --config ', 'set config path') + // will handle in `bin/picgo` + } +} + +export default config diff --git a/libs/zhi-picgo-core/src/plugins/commander/i18n.ts b/libs/zhi-picgo-core/src/plugins/commander/i18n.ts new file mode 100644 index 00000000..5f59c621 --- /dev/null +++ b/libs/zhi-picgo-core/src/plugins/commander/i18n.ts @@ -0,0 +1,36 @@ +import { IPlugin, IPicGo, IStringKeyMap } from '../../types' + +const i18n: IPlugin = { + handle: (ctx: IPicGo) => { + const cmd = ctx.cmd + cmd.program + .command('i18n') + .arguments('[lang]') + .description('change picgo language') + .action(async (lang: string = '') => { + const list = ctx.i18n.getLanguageList() + if (!lang) { + const prompts = [ + { + type: 'list', + name: 'i18n', + choices: list, + message: 'Choose a language', + default: ctx.getConfig('settings.language') || 'zh-CN' + } + ] + const answer = await ctx.cmd.inquirer.prompt>(prompts) + ctx.i18n.setLanguage(answer.i18n) + ctx.log.success(`Language set to ${answer.i18n}`) + return + } + if (!list.includes(lang)) { + return ctx.log.warn('No such language') + } + ctx.i18n.setLanguage(lang) + ctx.log.success(`Language set to ${lang}`) + }) + } +} + +export default i18n diff --git a/libs/zhi-picgo-core/src/plugins/commander/index.ts b/libs/zhi-picgo-core/src/plugins/commander/index.ts new file mode 100644 index 00000000..1bf0d1eb --- /dev/null +++ b/libs/zhi-picgo-core/src/plugins/commander/index.ts @@ -0,0 +1,20 @@ +import pluginHandler from './pluginHandler' +import config from './config' +import upload from './upload' +import setting from './setting' +import use from './use' +import proxy from './proxy' +import init from './init' +import i18n from './i18n' +import { IPicGo } from '../../types' + +export default (ctx: IPicGo): void => { + ctx.cmd.register('pluginHandler', pluginHandler) + ctx.cmd.register('config', config) + ctx.cmd.register('setting', setting) + ctx.cmd.register('upload', upload) + ctx.cmd.register('use', use) + ctx.cmd.register('proxy', proxy) + ctx.cmd.register('init', init) + ctx.cmd.register('i18n', i18n) +} diff --git a/libs/zhi-picgo-core/src/plugins/commander/init.ts b/libs/zhi-picgo-core/src/plugins/commander/init.ts new file mode 100644 index 00000000..e4e57b1d --- /dev/null +++ b/libs/zhi-picgo-core/src/plugins/commander/init.ts @@ -0,0 +1,120 @@ +import chalk from 'chalk' +import path from 'path' +import fs from 'fs-extra' +import { generate } from '../../utils/initUtils' +import { homedir } from 'os' +import download from 'download-git-repo' +import { IOptions, IPlugin, IPicGo } from '../../types' +import rm from 'rimraf' + +const run = (ctx: IPicGo, options: IOptions): void => { + // const name = options.inPlace ? path.relative('../', process.cwd()) : options.project + if (options.offline) { // offline mode + if (fs.existsSync(options.template)) { + generate(ctx, options).catch((e) => { ctx.log.error(e) }) + } else { + ctx.log.error(`Local template ${options.template} not found`) + } + } else { // online mode + options.template = !options.hasSlash + ? 'PicGo/picgo-template-' + options.template // official template + : options.template + downloadAndGenerate(ctx, options) + } +} + +/** + * download template & generate + * @param { PicGo } ctx + * @param { IOptions } options + */ +const downloadAndGenerate = (ctx: IPicGo, options: IOptions): void => { + if (fs.existsSync(options.tmp)) { + rm.sync(options.tmp) + } + ctx.log.info('Template files are downloading...') + download(options.template, options.tmp, { clone: options.clone }, (err: Error) => { + if (err) { + return ctx.log.error(err) + } + ctx.log.success('Template files are downloaded!') + generate(ctx, options).catch((e) => { ctx.log.error(e) }) + }) +} + +const init: IPlugin = { + handle: async (ctx: IPicGo) => { + const cmd = ctx.cmd + cmd.program + .command('init') + .arguments('