@infly/libs 2.7.1 → 2.7.2

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,57 +1,57 @@
1
1
  /**
2
2
  * Webpack require.context 适配器。
3
- * 自动导出目录下所有文件
4
- * @param {Function} requireContext - require.context 返回的函数
5
- * @returns {Object} 导出对象,key 为文件名(不含扩展名),value 为模块内容
6
- *
7
- * @example
8
- * // 在 components/Dialog/index.js 中使用
3
+ * 自动导出目录下所有文件
4
+ * @param {Function} requireContext - require.context 返回的函数
5
+ * @returns {Object} 导出对象,key 为文件名(不含扩展名),value 为模块内容
6
+ *
7
+ * @example
8
+ * // 在 components/Dialog/index.js 中使用
9
9
  * import { autoExportFiles } from '@infly/libs/adapters/webpack/auto-export';
10
- * const components = autoExportFiles(require.context('./', false, /\.vue$/));
11
- * Object.keys(components).forEach(name => {
12
- * module.exports[name] = components[name];
13
- * });
14
- *
15
- * // 或者直接一行
16
- * Object.assign(module.exports, autoExportFiles(require.context('./', false, /\.vue$/)));
17
- */
18
- const { logTerminal } = require("../../cli/terminal-style");
19
- function autoExportFiles(requireContext) {
20
- if (!requireContext || typeof requireContext !== 'function') {
21
- logTerminal("error", 'autoExportFiles: requireContext 必须是 require.context 返回的函数');
22
- return {};
23
- }
24
-
25
- const exports = {};
26
-
27
- requireContext.keys().forEach(fileName => {
28
- // 跳过 index 文件自身
29
- if (fileName.includes('index')) return;
30
-
31
- const componentConfig = requireContext(fileName);
32
- const componentName = fileName
33
- .replace(/^\.\//, '') // 移除 './'
34
- .replace(/\.\w+$/, ''); // 移除扩展名
35
-
36
- exports[componentName] = componentConfig.default || componentConfig;
37
- });
38
-
39
- return exports;
40
- }
41
-
42
- /**
43
- * 简化版:直接挂载到 module.exports
44
- * @param {Function} requireContext - require.context 返回的函数
45
- * @param {Object} targetExports - 目标导出对象(通常是 module.exports)
46
- *
47
- * @example
48
- * // 在 components/Dialog/index.js 中使用
10
+ * const components = autoExportFiles(require.context('./', false, /\.vue$/));
11
+ * Object.keys(components).forEach(name => {
12
+ * module.exports[name] = components[name];
13
+ * });
14
+ *
15
+ * // 或者直接一行
16
+ * Object.assign(module.exports, autoExportFiles(require.context('./', false, /\.vue$/)));
17
+ */
18
+ const { logTerminal } = require("../../cli/terminal-style");
19
+ function autoExportFiles(requireContext) {
20
+ if (!requireContext || typeof requireContext !== 'function') {
21
+ logTerminal("error", 'autoExportFiles: requireContext 必须是 require.context 返回的函数');
22
+ return {};
23
+ }
24
+
25
+ const exports = {};
26
+
27
+ requireContext.keys().forEach(fileName => {
28
+ // 跳过 index 文件自身
29
+ if (fileName.includes('index')) return;
30
+
31
+ const componentConfig = requireContext(fileName);
32
+ const componentName = fileName
33
+ .replace(/^\.\//, '') // 移除 './'
34
+ .replace(/\.\w+$/, ''); // 移除扩展名
35
+
36
+ exports[componentName] = componentConfig.default || componentConfig;
37
+ });
38
+
39
+ return exports;
40
+ }
41
+
42
+ /**
43
+ * 简化版:直接挂载到 module.exports
44
+ * @param {Function} requireContext - require.context 返回的函数
45
+ * @param {Object} targetExports - 目标导出对象(通常是 module.exports)
46
+ *
47
+ * @example
48
+ * // 在 components/Dialog/index.js 中使用
49
49
  * import { autoExportToModule } from '@infly/libs/adapters/webpack/auto-export';
50
- * autoExportToModule(require.context('./', false, /\.vue$/), module.exports);
51
- */
52
- function autoExportToModule(requireContext, targetExports) {
53
- const files = autoExportFiles(requireContext);
54
- Object.assign(targetExports, files);
55
- }
56
-
57
- export { autoExportFiles, autoExportToModule };
50
+ * autoExportToModule(require.context('./', false, /\.vue$/), module.exports);
51
+ */
52
+ function autoExportToModule(requireContext, targetExports) {
53
+ const files = autoExportFiles(requireContext);
54
+ Object.assign(targetExports, files);
55
+ }
56
+
57
+ export { autoExportFiles, autoExportToModule };
@@ -1,20 +1,20 @@
1
- const fs = require("fs");
2
- const path = require("path");
3
-
4
- /**
5
- * 从项目的 webpack/vite 等构建配置中解析对兄弟 app 的依赖。
6
- *
1
+ const fs = require("fs");
2
+ const path = require("path");
3
+
4
+ /**
5
+ * 从项目的 webpack/vite 等构建配置中解析对兄弟 app 的依赖。
6
+ *
7
7
  * 规则:如果 vue.config.js / vite.config.* / next.config.* 的 alias 中存在指向 ../ 的路径,
8
- * 则认为当前项目依赖该兄弟 app,构建前需要确保兄弟 app 源码是最新的。
9
- *
10
- * 示例(vue.config.js):
11
- * alias: {
12
- * "@example-admin": projectResolve("../example-admin/src")
13
- * }
14
- *
15
- * @param {string} appDir - 当前 app 目录的绝对路径
16
- * @returns {string[]} 兄弟 app 根目录(含 package.json)的绝对路径列表
17
- */
8
+ * 则认为当前项目依赖该兄弟 app,构建前需要确保兄弟 app 源码是最新的。
9
+ *
10
+ * 示例(vue.config.js):
11
+ * alias: {
12
+ * "@example-admin": projectResolve("../example-admin/src")
13
+ * }
14
+ *
15
+ * @param {string} appDir - 当前 app 目录的绝对路径
16
+ * @returns {string[]} 兄弟 app 根目录(含 package.json)的绝对路径列表
17
+ */
18
18
  function resolveSiblingAppDeps(appDir) {
19
19
  const siblings = [];
20
20
  const configFiles = [
@@ -51,13 +51,13 @@ function resolveSiblingAppDeps(appDir) {
51
51
  addSibling(match[2]);
52
52
  }
53
53
  }
54
-
55
- for (const configFile of configFiles) {
56
- const configPath = path.join(appDir, configFile);
57
- if (!fs.existsSync(configPath)) continue;
58
-
59
- const content = fs.readFileSync(configPath, "utf8");
60
-
54
+
55
+ for (const configFile of configFiles) {
56
+ const configPath = path.join(appDir, configFile);
57
+ if (!fs.existsSync(configPath)) continue;
58
+
59
+ const content = fs.readFileSync(configPath, "utf8");
60
+
61
61
  // 匹配 alias 中指向 ../ 兄弟目录的值,兼容以下写法:
62
62
  // "@foo": projectResolve("../foo/src")
63
63
  // "@foo": resolve("../foo/src")
@@ -77,8 +77,8 @@ function resolveSiblingAppDeps(appDir) {
77
77
 
78
78
  [...objectAliasPatterns, ...arrayAliasPatterns].forEach((pattern) => collectMatches(content, pattern));
79
79
  }
80
-
81
- return siblings;
82
- }
83
-
84
- module.exports = { resolveSiblingAppDeps };
80
+
81
+ return siblings;
82
+ }
83
+
84
+ module.exports = { resolveSiblingAppDeps };
@@ -1,135 +1,135 @@
1
- const fs = require("fs");
2
- const { formatReleaseResult, resolveWebhookUrl } = require("../release-result");
3
-
4
- function shouldSkipWebhook(args = process.argv, env = process.env) {
5
- return args.some((arg) => ["--nowebhook", "--noWebhook", "--no-webhook"].includes(arg))
6
- || [env.npm_config_nowebhook, env.npm_config_noWebhook, env.NO_WEBHOOK, env.DISABLE_WEBHOOK]
7
- .some((value) => ["1", "true", "yes", "on"].includes(String(value || "").toLowerCase()));
8
- }
9
-
10
- function getWebhookMessage(args = process.argv, env = process.env) {
11
- const configured = env.npm_config_m || env.npm_config_message || env.WEBHOOK_MESSAGE || env.BUILD_MESSAGE;
12
- if (configured) return String(configured).trim();
13
- for (let index = 0; index < args.length; index++) {
14
- const arg = args[index] || "";
15
- if (["-m", "--message"].includes(arg)) return String(args[index + 1] || "").trim();
16
- if (arg.startsWith("-m=")) return arg.slice(3).trim();
17
- if (arg.startsWith("--message=")) return arg.slice(10).trim();
18
- }
19
- return "";
20
- }
21
-
22
- async function sendWebhookContent(content, options = {}, dependencies = {}) {
23
- const env = dependencies.env || process.env;
24
- const logger = dependencies.logger || console;
25
- const webhookUrl = resolveWebhookUrl(options, env);
26
- if (!webhookUrl) return false;
27
- const { webhookAtUser = [], gitInfo = {} } = options;
28
- const mentions = Array.isArray(webhookAtUser) ? webhookAtUser : webhookAtUser[gitInfo.branch];
29
- try {
30
- const response = await (dependencies.httpClient || require("axios")).post(webhookUrl, {
31
- msgtype: "text", text: {
32
- content: String(content || "").replace(/%s/g, ""), mentioned_mobile_list: mentions,
33
- },
34
- }, { timeout: 15000, headers: { "Content-Type": "application/json" } });
35
- if (response.data?.errcode !== 0) throw new Error('WEBHOOK_REJECTED');
36
- return true;
37
- } catch (error) {
38
- // Axios error/config 可能包含完整凭据 URL,日志只输出受限错误码。
39
- const code = /^[A-Z0-9_]{1,40}$/.test(error.code || '') ? error.code : 'WEBHOOK_FAILED';
40
- logger.error("企业微信推送失败", code);
41
- return false;
42
- }
43
- }
44
-
45
- function getRecordContent(record, deployUrl) {
46
- if (record?.extraParams?.releaseResult) return formatReleaseResult(record.extraParams.releaseResult);
47
- const { publishText = "", extraParams = {} } = record || {};
48
- const {
49
- gitInfo = {},
50
- gitAutoPushReposBranchMap,
51
- repos,
52
- newFileName,
53
- projectName,
54
- webhookExtraText = ""
55
- } = extraParams;
56
- const { branch, author } = gitInfo || {};
57
-
58
- if (gitAutoPushReposBranchMap) {
59
- const targetBranch = gitAutoPushReposBranchMap[branch] || branch || "";
60
- return [
61
- publishText,
62
- `构建文件:已推送对应仓库【${repos || ""}】- 分支【${targetBranch}】`,
63
- `构建人:${author || ""}`,
64
- deployUrl ? `部署系统:${deployUrl}` : ""
65
- ]
66
- .filter(Boolean)
67
- .join("\n");
68
- }
69
-
70
- const gitPath =
71
- projectName && branch && newFileName
72
- ? `https://gitee.com/gdinfly_1/${projectName}/blob/${branch}/${newFileName}`
73
- : "";
74
-
75
- return [
76
- publishText,
77
- gitPath ? `构建文件下载地址:${gitPath}` : "",
78
- webhookExtraText
79
- ]
80
- .filter(Boolean)
81
- .join("\n");
82
- }
83
-
84
- async function postBatchWebhook(batchWebhookFile, extraArgs = [], mode, dependencies = {}) {
85
- if (shouldSkipWebhook(extraArgs, dependencies.env || process.env)) {
86
- console.log("\n已跳过企业微信机器人汇总推送(nowebhook)");
87
- return;
88
- }
89
-
90
- if (!fs.existsSync(batchWebhookFile)) {
91
- return;
92
- }
93
-
94
- const records = fs
95
- .readFileSync(batchWebhookFile, "utf8")
96
- .split(/\r?\n/)
97
- .filter(Boolean)
98
- .map((line) => JSON.parse(line));
99
-
100
- if (records.length === 0) {
101
- return;
102
- }
103
-
104
- const [firstRecord] = records;
105
- const { deployUrl = "" } =
106
- firstRecord.extraParams || {};
107
-
108
- let content = [
109
- records.map((record) => getRecordContent(record, deployUrl)).join("\n\n")
110
- ].join("\n");
111
- // 防御性过滤:防止运行时数据中的 %s 等格式化占位符泄露到推送内容
112
- content = (content || "").replace(/%s/g, "");
113
- if (await sendWebhookContent(content, firstRecord.extraParams, dependencies)) {
114
- console.log("\n已发送批量构建企业微信汇总推送");
115
- }
116
- }
117
-
118
- function postVersionFileAndMsg(publishText, extraParams = {}, dependencies = {}) {
119
- const env = dependencies.env || process.env;
120
- const args = dependencies.args || process.argv;
121
- if (shouldSkipWebhook(args, env)) return;
122
- let content = getRecordContent({ publishText, extraParams }, extraParams.deployUrl);
123
- const message = getWebhookMessage(args, env);
124
- if (message && !extraParams.releaseResult) content += `\n${message}`;
125
- return sendWebhookContent(content, extraParams, dependencies);
126
- }
127
-
128
- module.exports = {
129
- getRecordContent,
130
- getWebhookMessage,
131
- shouldSkipWebhook,
132
- sendWebhookContent,
133
- postVersionFileAndMsg,
134
- postBatchWebhook
135
- };
1
+ const fs = require("fs");
2
+ const { formatReleaseResult, resolveWebhookUrl } = require("../release-result");
3
+
4
+ function shouldSkipWebhook(args = process.argv, env = process.env) {
5
+ return args.some((arg) => ["--nowebhook", "--noWebhook", "--no-webhook"].includes(arg))
6
+ || [env.npm_config_nowebhook, env.npm_config_noWebhook, env.NO_WEBHOOK, env.DISABLE_WEBHOOK]
7
+ .some((value) => ["1", "true", "yes", "on"].includes(String(value || "").toLowerCase()));
8
+ }
9
+
10
+ function getWebhookMessage(args = process.argv, env = process.env) {
11
+ const configured = env.npm_config_m || env.npm_config_message || env.WEBHOOK_MESSAGE || env.BUILD_MESSAGE;
12
+ if (configured) return String(configured).trim();
13
+ for (let index = 0; index < args.length; index++) {
14
+ const arg = args[index] || "";
15
+ if (["-m", "--message"].includes(arg)) return String(args[index + 1] || "").trim();
16
+ if (arg.startsWith("-m=")) return arg.slice(3).trim();
17
+ if (arg.startsWith("--message=")) return arg.slice(10).trim();
18
+ }
19
+ return "";
20
+ }
21
+
22
+ async function sendWebhookContent(content, options = {}, dependencies = {}) {
23
+ const env = dependencies.env || process.env;
24
+ const logger = dependencies.logger || console;
25
+ const webhookUrl = resolveWebhookUrl(options, env);
26
+ if (!webhookUrl) return false;
27
+ const { webhookAtUser = [], gitInfo = {} } = options;
28
+ const mentions = Array.isArray(webhookAtUser) ? webhookAtUser : webhookAtUser[gitInfo.branch];
29
+ try {
30
+ const response = await (dependencies.httpClient || require("axios")).post(webhookUrl, {
31
+ msgtype: "text", text: {
32
+ content: String(content || "").replace(/%s/g, ""), mentioned_mobile_list: mentions,
33
+ },
34
+ }, { timeout: 15000, headers: { "Content-Type": "application/json" } });
35
+ if (response.data?.errcode !== 0) throw new Error('WEBHOOK_REJECTED');
36
+ return true;
37
+ } catch (error) {
38
+ // Axios error/config 可能包含完整凭据 URL,日志只输出受限错误码。
39
+ const code = /^[A-Z0-9_]{1,40}$/.test(error.code || '') ? error.code : 'WEBHOOK_FAILED';
40
+ logger.error("企业微信推送失败", code);
41
+ return false;
42
+ }
43
+ }
44
+
45
+ function getRecordContent(record, deployUrl) {
46
+ if (record?.extraParams?.releaseResult) return formatReleaseResult(record.extraParams.releaseResult);
47
+ const { publishText = "", extraParams = {} } = record || {};
48
+ const {
49
+ gitInfo = {},
50
+ gitAutoPushReposBranchMap,
51
+ repos,
52
+ newFileName,
53
+ projectName,
54
+ webhookExtraText = ""
55
+ } = extraParams;
56
+ const { branch, author } = gitInfo || {};
57
+
58
+ if (gitAutoPushReposBranchMap) {
59
+ const targetBranch = gitAutoPushReposBranchMap[branch] || branch || "";
60
+ return [
61
+ publishText,
62
+ `构建文件:已推送对应仓库【${repos || ""}】- 分支【${targetBranch}】`,
63
+ `构建人:${author || ""}`,
64
+ deployUrl ? `部署系统:${deployUrl}` : ""
65
+ ]
66
+ .filter(Boolean)
67
+ .join("\n");
68
+ }
69
+
70
+ const gitPath =
71
+ projectName && branch && newFileName
72
+ ? `https://gitee.com/gdinfly_1/${projectName}/blob/${branch}/${newFileName}`
73
+ : "";
74
+
75
+ return [
76
+ publishText,
77
+ gitPath ? `构建文件下载地址:${gitPath}` : "",
78
+ webhookExtraText
79
+ ]
80
+ .filter(Boolean)
81
+ .join("\n");
82
+ }
83
+
84
+ async function postBatchWebhook(batchWebhookFile, extraArgs = [], mode, dependencies = {}) {
85
+ if (shouldSkipWebhook(extraArgs, dependencies.env || process.env)) {
86
+ console.log("\n已跳过企业微信机器人汇总推送(nowebhook)");
87
+ return;
88
+ }
89
+
90
+ if (!fs.existsSync(batchWebhookFile)) {
91
+ return;
92
+ }
93
+
94
+ const records = fs
95
+ .readFileSync(batchWebhookFile, "utf8")
96
+ .split(/\r?\n/)
97
+ .filter(Boolean)
98
+ .map((line) => JSON.parse(line));
99
+
100
+ if (records.length === 0) {
101
+ return;
102
+ }
103
+
104
+ const [firstRecord] = records;
105
+ const { deployUrl = "" } =
106
+ firstRecord.extraParams || {};
107
+
108
+ let content = [
109
+ records.map((record) => getRecordContent(record, deployUrl)).join("\n\n")
110
+ ].join("\n");
111
+ // 防御性过滤:防止运行时数据中的 %s 等格式化占位符泄露到推送内容
112
+ content = (content || "").replace(/%s/g, "");
113
+ if (await sendWebhookContent(content, firstRecord.extraParams, dependencies)) {
114
+ console.log("\n已发送批量构建企业微信汇总推送");
115
+ }
116
+ }
117
+
118
+ function postVersionFileAndMsg(publishText, extraParams = {}, dependencies = {}) {
119
+ const env = dependencies.env || process.env;
120
+ const args = dependencies.args || process.argv;
121
+ if (shouldSkipWebhook(args, env)) return;
122
+ let content = getRecordContent({ publishText, extraParams }, extraParams.deployUrl);
123
+ const message = getWebhookMessage(args, env);
124
+ if (message && !extraParams.releaseResult) content += `\n${message}`;
125
+ return sendWebhookContent(content, extraParams, dependencies);
126
+ }
127
+
128
+ module.exports = {
129
+ getRecordContent,
130
+ getWebhookMessage,
131
+ shouldSkipWebhook,
132
+ sendWebhookContent,
133
+ postVersionFileAndMsg,
134
+ postBatchWebhook
135
+ };
@@ -1,30 +1,30 @@
1
- const fs = require("node:fs");
2
- const path = require("node:path");
3
-
4
- function inside(root, relative) {
5
- if (typeof relative !== "string" || !relative || path.isAbsolute(relative)) throw new Error(`必须配置相对路径: ${relative}`);
6
- const result = path.resolve(root, relative);
7
- const offset = path.relative(root, result);
8
- if (offset === ".." || offset.startsWith(`..${path.sep}`)) throw new Error(`路径越界: ${relative}`);
9
- return result;
10
- }
11
-
12
- function confinedPath(root, relative, io = fs) {
13
- const candidate = inside(root, relative);
14
- let existing = candidate;
15
- while (existing !== root && !io.existsSync(existing)) {
16
- if (io.lstatSync) {
17
- try {
18
- if (io.lstatSync(existing).isSymbolicLink()) throw new Error(`无法解析链接路径: ${relative}`);
19
- } catch (error) { if (error.code !== "ENOENT") throw error; }
20
- }
21
- existing = path.dirname(existing);
22
- }
23
- if (io.realpathSync && io.existsSync(existing)) {
24
- const offset = path.relative(io.realpathSync(root), io.realpathSync(existing));
25
- if (offset === ".." || offset.startsWith(`..${path.sep}`) || path.isAbsolute(offset)) throw new Error(`链接路径越界: ${relative}`);
26
- }
27
- return candidate;
28
- }
29
-
30
- module.exports = { inside, confinedPath };
1
+ const fs = require("node:fs");
2
+ const path = require("node:path");
3
+
4
+ function inside(root, relative) {
5
+ if (typeof relative !== "string" || !relative || path.isAbsolute(relative)) throw new Error(`必须配置相对路径: ${relative}`);
6
+ const result = path.resolve(root, relative);
7
+ const offset = path.relative(root, result);
8
+ if (offset === ".." || offset.startsWith(`..${path.sep}`)) throw new Error(`路径越界: ${relative}`);
9
+ return result;
10
+ }
11
+
12
+ function confinedPath(root, relative, io = fs) {
13
+ const candidate = inside(root, relative);
14
+ let existing = candidate;
15
+ while (existing !== root && !io.existsSync(existing)) {
16
+ if (io.lstatSync) {
17
+ try {
18
+ if (io.lstatSync(existing).isSymbolicLink()) throw new Error(`无法解析链接路径: ${relative}`);
19
+ } catch (error) { if (error.code !== "ENOENT") throw error; }
20
+ }
21
+ existing = path.dirname(existing);
22
+ }
23
+ if (io.realpathSync && io.existsSync(existing)) {
24
+ const offset = path.relative(io.realpathSync(root), io.realpathSync(existing));
25
+ if (offset === ".." || offset.startsWith(`..${path.sep}`) || path.isAbsolute(offset)) throw new Error(`链接路径越界: ${relative}`);
26
+ }
27
+ return candidate;
28
+ }
29
+
30
+ module.exports = { inside, confinedPath };
@@ -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
+ };