@infly/libs 2.2.11 → 2.2.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,136 +1,136 @@
1
- function shouldSkipWebhook() {
2
- const args = process.argv || [];
3
- const hasNoWebhookArg = args.some((arg = "") =>
4
- ["--nowebhook", "--noWebhook", "--no-webhook"].includes(arg)
5
- );
6
-
7
- const env = process.env || {};
8
- const envValues = [
9
- env.npm_config_nowebhook,
10
- env.npm_config_noWebhook,
11
- env.NO_WEBHOOK,
12
- env.DISABLE_WEBHOOK
13
- ];
14
- const hasNoWebhookEnv = envValues.some((value) => {
15
- const normalized = String(value || "").toLowerCase();
16
- return ["1", "true", "yes", "on"].includes(normalized);
17
- });
18
-
19
- return hasNoWebhookArg || hasNoWebhookEnv;
20
- }
21
-
22
- function getWebhookMessage() {
23
- const args = process.argv || [];
24
- const env = process.env || {};
25
- const messageEnv =
26
- env.npm_config_m ||
27
- env.npm_config_message ||
28
- env.WEBHOOK_MESSAGE ||
29
- env.BUILD_MESSAGE ||
30
- "";
31
-
32
- if (messageEnv) {
33
- return String(messageEnv).trim();
34
- }
35
-
36
- for (let index = 0; index < args.length; index += 1) {
37
- const arg = args[index] || "";
38
-
39
- if (arg === "-m" || arg === "--message") {
40
- return String(args[index + 1] || "").trim();
41
- }
42
-
43
- if (arg.startsWith("-m=")) {
44
- return arg.slice(3).trim();
45
- }
46
-
47
- if (arg.startsWith("--message=")) {
48
- return arg.slice(10).trim();
49
- }
50
- }
51
-
52
- return "";
53
- }
54
-
55
- function postVersionFileAndMsg(publishText, extraParams = {}) {
56
- const {
57
- projectName,
58
- newFileName,
59
- gitInfo,
60
- webhookUrl = "", // 启用企业微信推送
61
- webhookAtUser = [],
62
- webhookExtraText = "",
63
- gitAutoPushRepos,
64
- gitAutoPushReposBranchMap,
65
- repos,
66
- deployUrl = ""
67
- } = extraParams || {};
68
- const { branch, commitMsg, author } = gitInfo || {};
69
- const webhookMessage = getWebhookMessage();
70
- const GITPATH = `https://gitee.com/gdinfly_1/${projectName}/blob/${branch}/${newFileName}`;
71
- const UPLOADURL = `https://qyapi.weixin.qq.com/cgi-bin/webhook/upload_media?key=&type=file`;
72
- /* const data = {
73
- msgtype: "markdown",
74
- markdown: {
75
- content: `${publishText}\n构建文件:[点击下载](${GITPATH})`,
76
- },
77
- };
78
- if (Array.isArray(webhookAtUser) && webhookAtUser.length > 0) {
79
- webhookAtUser.forEach((item, index) => {
80
- data.markdown.content = `${data.markdown.content}\n<@${item}>`;
81
- });
82
- } */
83
- let content = publishText;
84
- if (gitAutoPushReposBranchMap) {
85
- content = [
86
- publishText,
87
- `构建文件:已推送对应仓库【${repos}】- 分支【${gitAutoPushReposBranchMap[branch]}】`,
88
- `构建人:${author}`,
89
- deployUrl ? `部署系统:${deployUrl}` : ""
90
- ].filter(Boolean).join("\n");
91
- } else {
92
- content = `${publishText}\n构建文件下载地址:${GITPATH}\n${webhookExtraText}\n`;
93
- }
94
-
95
- if (webhookMessage) {
96
- content = `${content}\n${webhookMessage}`;
97
- }
98
-
99
- // 防御性过滤:防止运行时数据中的 %s 等格式化占位符泄露到推送内容
100
- content = (content || "").replace(/%s/g, "");
101
-
102
- const data = {
103
- msgtype: "text",
104
- text: {
105
- content,
106
- mentioned_mobile_list: Array.isArray(webhookAtUser) ? webhookAtUser : webhookAtUser[branch] // 支持按分支配置不同的提醒人
107
- }
108
- };
109
-
110
- if (shouldSkipWebhook()) {
111
- console.log(global.logColor?.info || "%s", "🔕 已跳过企业微信机器人推送(nowebhook)");
112
- return;
113
- }
114
-
115
- try {
116
- const axios = require("axios");
117
-
118
- if (axios) {
119
- axios
120
- .post(webhookUrl, data, {
121
- headers: {
122
- "Content-Type": "application/json"
123
- }
124
- })
125
- .catch((e) => {
126
- console.error("请求出错:", e);
127
- });
128
- }
129
- } catch (error) {
130
- console.error("axios is not available, please install it.");
131
- }
132
- }
133
-
134
- module.exports = {
135
- postVersionFileAndMsg
136
- };
1
+ function shouldSkipWebhook() {
2
+ const args = process.argv || [];
3
+ const hasNoWebhookArg = args.some((arg = "") =>
4
+ ["--nowebhook", "--noWebhook", "--no-webhook"].includes(arg)
5
+ );
6
+
7
+ const env = process.env || {};
8
+ const envValues = [
9
+ env.npm_config_nowebhook,
10
+ env.npm_config_noWebhook,
11
+ env.NO_WEBHOOK,
12
+ env.DISABLE_WEBHOOK
13
+ ];
14
+ const hasNoWebhookEnv = envValues.some((value) => {
15
+ const normalized = String(value || "").toLowerCase();
16
+ return ["1", "true", "yes", "on"].includes(normalized);
17
+ });
18
+
19
+ return hasNoWebhookArg || hasNoWebhookEnv;
20
+ }
21
+
22
+ function getWebhookMessage() {
23
+ const args = process.argv || [];
24
+ const env = process.env || {};
25
+ const messageEnv =
26
+ env.npm_config_m ||
27
+ env.npm_config_message ||
28
+ env.WEBHOOK_MESSAGE ||
29
+ env.BUILD_MESSAGE ||
30
+ "";
31
+
32
+ if (messageEnv) {
33
+ return String(messageEnv).trim();
34
+ }
35
+
36
+ for (let index = 0; index < args.length; index += 1) {
37
+ const arg = args[index] || "";
38
+
39
+ if (arg === "-m" || arg === "--message") {
40
+ return String(args[index + 1] || "").trim();
41
+ }
42
+
43
+ if (arg.startsWith("-m=")) {
44
+ return arg.slice(3).trim();
45
+ }
46
+
47
+ if (arg.startsWith("--message=")) {
48
+ return arg.slice(10).trim();
49
+ }
50
+ }
51
+
52
+ return "";
53
+ }
54
+
55
+ function postVersionFileAndMsg(publishText, extraParams = {}) {
56
+ const {
57
+ projectName,
58
+ newFileName,
59
+ gitInfo,
60
+ webhookUrl = "", // 启用企业微信推送
61
+ webhookAtUser = [],
62
+ webhookExtraText = "",
63
+ gitAutoPushRepos,
64
+ gitAutoPushReposBranchMap,
65
+ repos,
66
+ deployUrl = ""
67
+ } = extraParams || {};
68
+ const { branch, commitMsg, author } = gitInfo || {};
69
+ const webhookMessage = getWebhookMessage();
70
+ const GITPATH = `https://gitee.com/gdinfly_1/${projectName}/blob/${branch}/${newFileName}`;
71
+ const UPLOADURL = `https://qyapi.weixin.qq.com/cgi-bin/webhook/upload_media?key=&type=file`;
72
+ /* const data = {
73
+ msgtype: "markdown",
74
+ markdown: {
75
+ content: `${publishText}\n构建文件:[点击下载](${GITPATH})`,
76
+ },
77
+ };
78
+ if (Array.isArray(webhookAtUser) && webhookAtUser.length > 0) {
79
+ webhookAtUser.forEach((item, index) => {
80
+ data.markdown.content = `${data.markdown.content}\n<@${item}>`;
81
+ });
82
+ } */
83
+ let content = publishText;
84
+ if (gitAutoPushReposBranchMap) {
85
+ content = [
86
+ publishText,
87
+ `构建文件:已推送对应仓库【${repos}】- 分支【${gitAutoPushReposBranchMap[branch]}】`,
88
+ `构建人:${author}`,
89
+ deployUrl ? `部署系统:${deployUrl}` : ""
90
+ ].filter(Boolean).join("\n");
91
+ } else {
92
+ content = `${publishText}\n构建文件下载地址:${GITPATH}\n${webhookExtraText}\n`;
93
+ }
94
+
95
+ if (webhookMessage) {
96
+ content = `${content}\n${webhookMessage}`;
97
+ }
98
+
99
+ // 防御性过滤:防止运行时数据中的 %s 等格式化占位符泄露到推送内容
100
+ content = (content || "").replace(/%s/g, "");
101
+
102
+ const data = {
103
+ msgtype: "text",
104
+ text: {
105
+ content,
106
+ mentioned_mobile_list: Array.isArray(webhookAtUser) ? webhookAtUser : webhookAtUser[branch] // 支持按分支配置不同的提醒人
107
+ }
108
+ };
109
+
110
+ if (shouldSkipWebhook()) {
111
+ console.log(global.logColor?.info || "%s", "🔕 已跳过企业微信机器人推送(nowebhook)");
112
+ return;
113
+ }
114
+
115
+ try {
116
+ const axios = require("axios");
117
+
118
+ if (axios) {
119
+ axios
120
+ .post(webhookUrl, data, {
121
+ headers: {
122
+ "Content-Type": "application/json"
123
+ }
124
+ })
125
+ .catch((e) => {
126
+ console.error("请求出错:", e);
127
+ });
128
+ }
129
+ } catch (error) {
130
+ console.error("axios is not available, please install it.");
131
+ }
132
+ }
133
+
134
+ module.exports = {
135
+ postVersionFileAndMsg
136
+ };
@@ -1,98 +1,98 @@
1
- const { execFileSync } = require("node:child_process");
2
- const fs = require("node:fs");
3
- const path = require("node:path");
4
-
1
+ const { execFileSync } = require("node:child_process");
2
+ const fs = require("node:fs");
3
+ const path = require("node:path");
4
+
5
5
  function bumpComposeImageVersion(content, bump = "patch") {
6
6
  if (!["none", "patch"].includes(bump)) {
7
7
  throw new Error(`Unsupported version bump: ${bump}. Supported values: none, patch.`);
8
- }
9
-
10
- const imageRegex = /^(\s*image:\s*)([^\s#]+):(\d+)\.(\d+)\.(\d+)(\s*(?:#.*)?)$/gm;
11
- const matches = [...content.matchAll(imageRegex)];
12
-
13
- if (matches.length !== 1) {
14
- throw new Error(`Compose file must contain exactly one versioned image; found ${matches.length}.`);
15
- }
16
-
8
+ }
9
+
10
+ const imageRegex = /^(\s*image:\s*)([^\s#]+):(\d+)\.(\d+)\.(\d+)(\s*(?:#.*)?)$/gm;
11
+ const matches = [...content.matchAll(imageRegex)];
12
+
13
+ if (matches.length !== 1) {
14
+ throw new Error(`Compose file must contain exactly one versioned image; found ${matches.length}.`);
15
+ }
16
+
17
17
  const [, prefix, image, major, minor, patchVersion, suffix] = matches[0];
18
18
  const from = `${image}:${major}.${minor}.${patchVersion}`;
19
19
  const to = bump === "none"
20
20
  ? from
21
21
  : `${image}:${major}.${minor}.${Number(patchVersion) + 1}`;
22
22
  const replacement = `${prefix}${to}${suffix}`;
23
-
24
- return {
25
- content: content.replace(imageRegex, replacement),
26
- from,
27
- to,
28
- };
29
- }
30
-
31
- function resolveComposePath(projectDir, file) {
32
- if (!projectDir) throw new Error("--project-dir is required.");
33
- if (!file) throw new Error("--file is required.");
34
-
35
- const resolvedProjectDir = path.resolve(projectDir);
36
- const composePath = path.resolve(resolvedProjectDir, file);
37
- const relative = path.relative(resolvedProjectDir, composePath);
38
-
39
- if (relative.startsWith("..") || path.isAbsolute(relative)) {
40
- throw new Error("Compose file must be inside project-dir.");
41
- }
42
- if (!fs.existsSync(composePath)) {
43
- throw new Error(`Compose file not found: ${composePath}`);
44
- }
45
-
46
- return { projectDir: resolvedProjectDir, composePath };
47
- }
48
-
49
- function defaultRunDocker(args, options) {
50
- execFileSync("docker", args, { cwd: options.cwd, stdio: "inherit" });
51
- }
52
-
53
- function composeRelease(options = {}, dependencies = {}) {
54
- const {
55
- projectDir,
56
- file,
57
- bump = "patch",
58
- push = false,
59
- dryRun = false,
60
- } = options;
61
- const runDocker = dependencies.runDocker || defaultRunDocker;
62
- const resolved = resolveComposePath(projectDir, file);
63
- const original = fs.readFileSync(resolved.composePath, "utf8");
64
- const updated = bumpComposeImageVersion(original, bump);
65
- const baseArgs = ["compose", "-f", resolved.composePath];
66
-
23
+
24
+ return {
25
+ content: content.replace(imageRegex, replacement),
26
+ from,
27
+ to,
28
+ };
29
+ }
30
+
31
+ function resolveComposePath(projectDir, file) {
32
+ if (!projectDir) throw new Error("--project-dir is required.");
33
+ if (!file) throw new Error("--file is required.");
34
+
35
+ const resolvedProjectDir = path.resolve(projectDir);
36
+ const composePath = path.resolve(resolvedProjectDir, file);
37
+ const relative = path.relative(resolvedProjectDir, composePath);
38
+
39
+ if (relative.startsWith("..") || path.isAbsolute(relative)) {
40
+ throw new Error("Compose file must be inside project-dir.");
41
+ }
42
+ if (!fs.existsSync(composePath)) {
43
+ throw new Error(`Compose file not found: ${composePath}`);
44
+ }
45
+
46
+ return { projectDir: resolvedProjectDir, composePath };
47
+ }
48
+
49
+ function defaultRunDocker(args, options) {
50
+ execFileSync("docker", args, { cwd: options.cwd, stdio: "inherit" });
51
+ }
52
+
53
+ function composeRelease(options = {}, dependencies = {}) {
54
+ const {
55
+ projectDir,
56
+ file,
57
+ bump = "patch",
58
+ push = false,
59
+ dryRun = false,
60
+ } = options;
61
+ const runDocker = dependencies.runDocker || defaultRunDocker;
62
+ const resolved = resolveComposePath(projectDir, file);
63
+ const original = fs.readFileSync(resolved.composePath, "utf8");
64
+ const updated = bumpComposeImageVersion(original, bump);
65
+ const baseArgs = ["compose", "-f", resolved.composePath];
66
+
67
67
  if (bump === "none") {
68
68
  console.log(`Version fixed: ${updated.from}`);
69
69
  } else {
70
70
  console.log(`Version update: ${updated.from} -> ${updated.to}`);
71
71
  }
72
-
73
- if (dryRun) {
74
- console.log(`[dry-run] docker ${[...baseArgs, "config"].join(" ")}`);
75
- console.log(`[dry-run] docker ${[...baseArgs, "build"].join(" ")}`);
76
- if (push) console.log(`[dry-run] docker ${[...baseArgs, "push"].join(" ")}`);
77
- return { ...updated, projectDir: resolved.projectDir, composePath: resolved.composePath };
78
- }
79
-
72
+
73
+ if (dryRun) {
74
+ console.log(`[dry-run] docker ${[...baseArgs, "config"].join(" ")}`);
75
+ console.log(`[dry-run] docker ${[...baseArgs, "build"].join(" ")}`);
76
+ if (push) console.log(`[dry-run] docker ${[...baseArgs, "push"].join(" ")}`);
77
+ return { ...updated, projectDir: resolved.projectDir, composePath: resolved.composePath };
78
+ }
79
+
80
80
  const versionChanged = updated.content !== original;
81
81
  if (versionChanged) fs.writeFileSync(resolved.composePath, updated.content, "utf8");
82
82
  try {
83
- runDocker([...baseArgs, "config"], { cwd: resolved.projectDir });
84
- runDocker([...baseArgs, "build"], { cwd: resolved.projectDir });
85
- if (push) runDocker([...baseArgs, "push"], { cwd: resolved.projectDir });
83
+ runDocker([...baseArgs, "config"], { cwd: resolved.projectDir });
84
+ runDocker([...baseArgs, "build"], { cwd: resolved.projectDir });
85
+ if (push) runDocker([...baseArgs, "push"], { cwd: resolved.projectDir });
86
86
  } catch (error) {
87
87
  if (versionChanged) fs.writeFileSync(resolved.composePath, original, "utf8");
88
- throw error;
89
- }
90
-
91
- return { ...updated, projectDir: resolved.projectDir, composePath: resolved.composePath };
92
- }
93
-
94
- module.exports = {
95
- bumpComposeImageVersion,
96
- composeRelease,
97
- resolveComposePath,
98
- };
88
+ throw error;
89
+ }
90
+
91
+ return { ...updated, projectDir: resolved.projectDir, composePath: resolved.composePath };
92
+ }
93
+
94
+ module.exports = {
95
+ bumpComposeImageVersion,
96
+ composeRelease,
97
+ resolveComposePath,
98
+ };
@@ -3,53 +3,53 @@ const path = require("path");
3
3
 
4
4
  // 兼容旧 tools/file-process.js 的 __dirname 路径语义。
5
5
  const legacyToolsDir = path.resolve(__dirname, "../tools");
6
-
7
- /**
8
- * 覆盖写入构建脚本
9
- * @param {String} filePath - 覆盖文件路径
10
- * @param {Array | Object} scriptsList - 写入脚本配置
11
- * @param {String} 更新字段值
12
- */
13
- function scriptWrite(filePath, scriptsList, updateKey = "scripts") {
14
- const pkg = JSON.parse(fs.readFileSync(filePath));
15
- pkg[updateKey] = pkg[updateKey] || {};
16
- if (Array.isArray(scriptsList)) {
17
- scriptsList.forEach(item => {
18
- if (pkg[updateKey][item.key]) {
19
- pkg[updateKey][`origin:${item.key}`] = pkg[updateKey][item.key];
20
- }
21
- pkg[updateKey][item.key] = item.value;
22
- });
23
- } else if (typeof scriptsList === "object") {
24
- pkg[updateKey] = scriptsList;
25
- }
26
-
27
- fs.writeFileSync(filePath, JSON.stringify(pkg, null, 2));
28
- }
29
-
30
- /**
31
- * 获取文件绝对路径
32
- * @param {String} filePath - 文件路径
33
- * @returns
34
- */
35
- function targetProjectFileResolve(filePath) {
36
- // 初始脚本自动执行路径会自动读取node_modules
37
- const projectRoot = process.cwd();
38
- const absoluteProjectRoot = projectRoot.replace(/\\node_modules.*$/g, "");
39
- return path.resolve(absoluteProjectRoot, filePath);
40
- }
41
-
42
- /**
43
- * 获取文件绝对路径
44
- * @param {String} filePath - 文件路径
45
- * @returns
46
- */
6
+
7
+ /**
8
+ * 覆盖写入构建脚本
9
+ * @param {String} filePath - 覆盖文件路径
10
+ * @param {Array | Object} scriptsList - 写入脚本配置
11
+ * @param {String} 更新字段值
12
+ */
13
+ function scriptWrite(filePath, scriptsList, updateKey = "scripts") {
14
+ const pkg = JSON.parse(fs.readFileSync(filePath));
15
+ pkg[updateKey] = pkg[updateKey] || {};
16
+ if (Array.isArray(scriptsList)) {
17
+ scriptsList.forEach(item => {
18
+ if (pkg[updateKey][item.key]) {
19
+ pkg[updateKey][`origin:${item.key}`] = pkg[updateKey][item.key];
20
+ }
21
+ pkg[updateKey][item.key] = item.value;
22
+ });
23
+ } else if (typeof scriptsList === "object") {
24
+ pkg[updateKey] = scriptsList;
25
+ }
26
+
27
+ fs.writeFileSync(filePath, JSON.stringify(pkg, null, 2));
28
+ }
29
+
30
+ /**
31
+ * 获取文件绝对路径
32
+ * @param {String} filePath - 文件路径
33
+ * @returns
34
+ */
35
+ function targetProjectFileResolve(filePath) {
36
+ // 初始脚本自动执行路径会自动读取node_modules
37
+ const projectRoot = process.cwd();
38
+ const absoluteProjectRoot = projectRoot.replace(/\\node_modules.*$/g, "");
39
+ return path.resolve(absoluteProjectRoot, filePath);
40
+ }
41
+
42
+ /**
43
+ * 获取文件绝对路径
44
+ * @param {String} filePath - 文件路径
45
+ * @returns
46
+ */
47
47
  function currentProjectFileResolve(filePath) {
48
48
  return path.join(legacyToolsDir, filePath);
49
49
  }
50
-
51
- module.exports = {
52
- scriptWrite,
53
- targetProjectFileResolve,
54
- currentProjectFileResolve
55
- };
50
+
51
+ module.exports = {
52
+ scriptWrite,
53
+ targetProjectFileResolve,
54
+ currentProjectFileResolve
55
+ };
@@ -1,31 +1,31 @@
1
1
  /**
2
2
  * 框架无关的异步并发控制。
3
- * 异步并发限流器。
4
- * 对 items 数组中的每一项执行 worker,同时最多运行 concurrency 个 worker。
5
- *
6
- * @param {Array} items - 待处理项
7
- * @param {number} concurrency - 最大并发数
8
- * @param {Function} worker - 处理函数 (item, index) => Promise
9
- * @returns {Promise<Array>} 结果数组,索引与 items 一一对应
10
- */
11
- async function runWithConcurrency(items, concurrency, worker) {
12
- if (!Number.isInteger(concurrency) || concurrency < 1) {
13
- throw new TypeError("concurrency must be a positive integer");
14
- }
15
-
16
- const results = new Array(items.length);
17
- let nextIndex = 0;
18
- const runWorker = async () => {
19
- while (nextIndex < items.length) {
20
- const index = nextIndex;
21
- nextIndex += 1;
22
- results[index] = await worker(items[index], index);
23
- }
24
- };
25
-
26
- const workerCount = Math.min(concurrency, items.length);
27
- await Promise.all(Array.from({ length: workerCount }, runWorker));
28
- return results;
29
- }
30
-
31
- module.exports = { runWithConcurrency };
3
+ * 异步并发限流器。
4
+ * 对 items 数组中的每一项执行 worker,同时最多运行 concurrency 个 worker。
5
+ *
6
+ * @param {Array} items - 待处理项
7
+ * @param {number} concurrency - 最大并发数
8
+ * @param {Function} worker - 处理函数 (item, index) => Promise
9
+ * @returns {Promise<Array>} 结果数组,索引与 items 一一对应
10
+ */
11
+ async function runWithConcurrency(items, concurrency, worker) {
12
+ if (!Number.isInteger(concurrency) || concurrency < 1) {
13
+ throw new TypeError("concurrency must be a positive integer");
14
+ }
15
+
16
+ const results = new Array(items.length);
17
+ let nextIndex = 0;
18
+ const runWorker = async () => {
19
+ while (nextIndex < items.length) {
20
+ const index = nextIndex;
21
+ nextIndex += 1;
22
+ results[index] = await worker(items[index], index);
23
+ }
24
+ };
25
+
26
+ const workerCount = Math.min(concurrency, items.length);
27
+ await Promise.all(Array.from({ length: workerCount }, runWorker));
28
+ return results;
29
+ }
30
+
31
+ module.exports = { runWithConcurrency };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@infly/libs",
3
- "version": "2.2.11",
3
+ "version": "2.2.12",
4
4
  "description": "不受前端框架限制的独立工具库",
5
5
  "main": "index.js",
6
6
  "types": "index.d.ts",