@taole/deploy-helper 1.0.0 → 1.0.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,314 +1,333 @@
1
- import fs from 'fs';
2
- import archiver from 'archiver';
3
- import { join } from "node:path"
4
- import { log, getOssToken, getUserDeployHelperConfig } from './util.mjs';
5
- import { uploadFile } from './upload.js';
6
- import md5File from 'md5-file';
7
-
8
-
9
-
10
- function genArchive(outputPath, dir) {
11
- return new Promise((resolve, reject) => {
12
- const output = fs.createWriteStream(outputPath);
13
- const archive = archiver('zip', {
14
- zlib: { level: 1 } // Sets the compression level.
15
- });
16
- archive.on('error', reject);
17
- archive.on("finish", resolve);
18
- archive.pipe(output);
19
- archive.directory(dir, false);
20
- archive.finalize();
21
- })
22
- }
23
-
24
- /**
25
- * json配置
26
- * @param {string} workDir 项目工作目录
27
- * @returns {Object|null} 配置
28
- */
29
- export function getJsonConfig(workDir, name) {
30
- const filePath = join(workDir, name);
31
- if (fs.existsSync(filePath)) {
32
- try {
33
- return JSON.parse(fs.readFileSync(filePath, "utf-8"));
34
- } catch (_error) {
35
- // pass
36
- }
37
- }
38
- return null;
39
- }
40
-
41
- /**
42
- * 同步离线包列表到api
43
- * @param {{offlineApi: {get: string, set: string}}} userDeployHelperConfig 用户配置
44
- * @param {"prod"|"test"} mode 部署模式 prod: 线上, test: 测试
45
- * @param {{name: string, remove: boolean}} offlineConfig 离线包配置
46
- * @param {any} packageDescJson 离线包描述json
47
- */
48
- export async function syncApi(userDeployHelperConfig, mode, offlineConfig, packageDescJson) {
49
- // 根据部署模式,决定更新调用哪个接口
50
- const doAction = offlineConfig.remove ? "remove" : "add";
51
- const apiDomain = mode === "prod" ? "https://yapi.tuwan.com" : "https://yapi-test.tuwan.com";
52
- const getPath = userDeployHelperConfig.offlineApi.get;
53
- const setPath = userDeployHelperConfig.offlineApi.set;
54
- const getUrl = `${apiDomain}${getPath}`;
55
- const setUrl = `${apiDomain}${setPath}`;
56
- const envPrefix = `${mode === "prod" ? "线上环境" : "测试环境"}[platform=${offlineConfig.platform}]`;
57
- const nowRes = await fetch(getUrl, {
58
- headers: {
59
- platform: String(offlineConfig.platform),
60
- }
61
- });
62
- const nowData = await nowRes.json();
63
- let needSetData = true;
64
- let finalJsonData = null;
65
- if (!nowData || nowData.error !== 0) {
66
- throw new Error(`获取离线包列表失败, 获取离线包当前配置失败: ${nowData.error_msg || "未知错误"}`);
67
- }
68
- const jsonData = JSON.parse(nowData.data.json || "{}");
69
- finalJsonData = jsonData;
70
- jsonData.packages = jsonData.packages || [];
71
- if (doAction === "add") {
72
- const idx = jsonData.packages.findIndex(item => item.name === offlineConfig.name);
73
- if (idx !== -1) {
74
- log(`离线包${offlineConfig.name}已存在, 更新离线包`);
75
- jsonData.packages[idx] = packageDescJson;
76
- } else {
77
- log(`离线包${offlineConfig.name}不存在, 添加离线包`);
78
- jsonData.packages.push(packageDescJson);
79
- }
80
- } else {
81
- const idx = jsonData.packages.findIndex(item => item.name === offlineConfig.name);
82
- if (idx === -1) {
83
- log(`离线包${offlineConfig.name}不存在, 无需删除`);
84
- needSetData = false;
85
- }
86
- jsonData.packages = jsonData.packages.filter(item => item.name !== offlineConfig.name);
87
- }
88
- jsonData.packages = jsonData.packages.filter(item => item.name);
89
- if (needSetData) {
90
- // console.log('jsonData', jsonData);
91
- var formdata = new FormData();
92
- formdata.append("json", JSON.stringify(jsonData));
93
- const setRes = await fetch(setUrl, {
94
- method: "POST",
95
- body: formdata,
96
- headers: {
97
- platform: String(offlineConfig.platform),
98
- }
99
- });
100
- const setData = await setRes.json();
101
- if (!setData || setData.error !== 0) {
102
- throw new Error(`更新离线包列表失败, 更新离线包当前配置失败: ${setData.error_msg || "未知错误"}`);
103
- }
104
- log(`${envPrefix}离线包列表更新完成: ${JSON.stringify(setData)}`);
105
- // 再次获取列表,确保更新成功
106
- const nowRes2 = await fetch(getUrl, {
107
- headers: {
108
- platform: String(offlineConfig.platform),
109
- }
110
- });
111
- const nowData2 = await nowRes2.json();
112
- if (!nowData2 || nowData2.error !== 0) {
113
- throw new Error(`再次获取离线包列表失败, 获取离线包当前配置失败: ${nowData2.error_msg || "未知错误"}`);
114
- }
115
- finalJsonData = JSON.parse(nowData2.data.json || "{}");
116
- }
117
-
118
- const packages = finalJsonData.packages || [];
119
- console.log(`${envPrefix}当前离线包列表:`, packages.map(item => ({ ...item, items: '省略' + item.items.length + '个条目' })));
120
- }
121
-
122
- /**
123
- * @deprecated 不再需要这个函数, 如果插件使用的是@taole/vite-plugin-dynamic-base, 则不需要这个函数
124
- * hack
125
- * 由于vite-plugin-dynamic-base插件和legacy插件同时使用, 生存的入口文件中代码有点问题,这里直接修改有问题的代码
126
- */
127
- function fixEntryHtml(config, offlineConfig) {
128
- if (!offlineConfig || !config) return;
129
- const entryHtmlPath = join(config.workDir, offlineConfig.distDir, "index.html");
130
- if (!fs.existsSync(entryHtmlPath)) {
131
- throw new Error(`构建产物${entryHtmlPath}不存在`);
132
- }
133
- const markLine = "} else if (item.tagName == 'script') {";
134
- const replaceLine = `} else if (item.tagName == 'script')/*injected by deploy-helper*/{
135
- if(item.attrs.id=='vite-legacy-polyfill')childNode.onload=function(){System.import(window.__dynamic_base__ + document.getElementById('vite-legacy-entry').getAttribute('data-src'))};
136
- `;
137
- let entryHtml = fs.readFileSync(entryHtmlPath, "utf-8");
138
- entryHtml = entryHtml.replace(markLine, replaceLine);
139
- fs.writeFileSync(entryHtmlPath, entryHtml);
140
- }
141
-
142
- /**
143
- * @typedef {Object} CheckOfflinePkgResult
144
- * @property {string} workDir 工作目录
145
- * @property {boolean} canBuild 是否可以构建离线包
146
- * @property {string} errorMsg 错误信息
147
- * @property {function} hookPostBuild 构建后钩子
148
- * @property {function} hookPostDeployTest 部署到测试环境后钩子
149
- * @property {function} hookPostDeployProd 部署到生产环境后钩子
150
- */
151
-
152
- /**
153
- * 在项目构建好之后,将项目打包成离线包,并上传到指定服务器
154
- * @param {Object} config 配置
155
- * @param {string} config.workDir 工作目录
156
- * @param {"prod"|"test"} config.mode 部署模式
157
- * @returns {CheckOfflinePkgResult} 结果
158
- */
159
- export function checkOfflinePkg(config) {
160
- let canBuildOfflinePkg = true;
161
- let errorMsg = "";
162
- const offlineConfig = getJsonConfig(config.workDir, "offline.config.json");
163
- if (offlineConfig) {
164
- offlineConfig.distDir = offlineConfig.distDir || "dist";
165
- offlineConfig.platform = offlineConfig.platform || 3; // 3,4是点点
166
- }
167
- const packageJson = getJsonConfig(config.workDir, "package.json");
168
- const userDeployHelperConfig = getUserDeployHelperConfig();
169
- const distPath = join(config.workDir, offlineConfig && offlineConfig.distDir ? offlineConfig.distDir : "dist");
170
- const allDeps = {
171
- ...packageJson.devDependencies,
172
- ...packageJson.dependencies,
173
- };
174
- const useOldPDB = !!allDeps['vite-plugin-dynamic-base'];
175
-
176
- // 如果offlineConfig.remove为true,则不构建离线包
177
- const willRemovePkg = offlineConfig && offlineConfig.name && offlineConfig.remove === true && offlineConfig.skip !== true;
178
- const willSkip = !offlineConfig || !offlineConfig.name || offlineConfig.skip === true || (offlineConfig.onlyTest === true && config.mode === "prod");
179
- if (willRemovePkg) {
180
- return {
181
- canBuild: true,
182
- errorMsg: "",
183
- hookPostBuild: async () => {
184
- if (useOldPDB) {
185
- fixEntryHtml(config, offlineConfig);
186
- }
187
- log(`开始删除离线包${offlineConfig.name}`);
188
- await syncApi(userDeployHelperConfig, config.mode, offlineConfig, null);
189
- }
190
- }
191
- }
192
- if (!fs.existsSync(distPath)) {
193
- errorMsg = `构建产物${distPath}不存在, 请先构建项目`;
194
- canBuildOfflinePkg = false;
195
- } else if (offlineConfig && !offlineConfig.name) {
196
- errorMsg = "离线包配置文件中未配置name, 请先配置";
197
- canBuildOfflinePkg = false;
198
- } else if (!userDeployHelperConfig || !userDeployHelperConfig.offlineApi || !userDeployHelperConfig.offlineApi.get || !userDeployHelperConfig.offlineApi.set) {
199
- errorMsg = "未配置离线包接口, 请移步看配置文档: https://alidocs.dingtalk.com/i/nodes/R1zknDm0WRkbz13oHn0LDz3ZVBQEx5rG?doc_type=wiki_doc";
200
- canBuildOfflinePkg = false;
201
- } else if (!packageJson) {
202
- errorMsg = "啊没有package.json?";
203
- canBuildOfflinePkg = false;
204
- } else {
205
- if (!allDeps['vite-plugin-dynamic-base'] && !allDeps['@taole/vite-plugin-dynamic-base']) {
206
- errorMsg = "检查到项目中未安装依赖@taole/vite-plugin-dynamic-base, 请先安装依赖并调整构建代码以支持离线化,相关文档:https://alidocs.dingtalk.com/i/nodes/ydxXB52LJqexwD71F9K5XNMrJqjMp697?doc_type=wiki_doc";
207
- canBuildOfflinePkg = false;
208
- }
209
- }
210
- if (willSkip) {
211
- if (!offlineConfig) {
212
- return {
213
- canBuild: false,
214
- errorMsg: ""
215
- }
216
- }
217
- if (offlineConfig.onlyTest === true && config.mode === "prod") {
218
- console.log(`离线包${offlineConfig.name}只用于测试环境, 跳过构建线上环境的离线包构建`);
219
- }
220
- return {
221
- canBuild: true,
222
- errorMsg: "",
223
- hookPostBuild: async () => {
224
- if (useOldPDB) {
225
- fixEntryHtml(config, offlineConfig);
226
- }
227
- }
228
- }
229
- }
230
- let ossToken = "";
231
- if (canBuildOfflinePkg) {
232
- ossToken = getOssToken();
233
- if (!ossToken) {
234
- errorMsg = "获取ossToken失败";
235
- canBuildOfflinePkg = false;
236
- }
237
- }
238
- if (!canBuildOfflinePkg) {
239
- return {
240
- canBuild: false,
241
- errorMsg: errorMsg
242
- }
243
- }
244
- const hookPostBuild = async () => {
245
- if (!offlineConfig || !config) return;
246
- // 在构建完成后,执行一些操作
247
- if (useOldPDB) {
248
- fixEntryHtml(config, offlineConfig);
249
- }
250
- // 开始进行打包流程
251
- const offlinePkgDir = join(config.workDir, "./offlinepkgDist");
252
- if (fs.existsSync(offlinePkgDir)) {
253
- fs.rmSync(offlinePkgDir, { recursive: true });
254
- } else {
255
- fs.mkdirSync(offlinePkgDir, { recursive: true });
256
- }
257
-
258
- const packageDir = join(offlinePkgDir, "./package");
259
- fs.mkdirSync(packageDir, { recursive: true });
260
- // cp dist到offlinepkgDist目录下
261
- fs.cpSync(join(config.workDir, offlineConfig.distDir), join(packageDir, offlineConfig.distDir), { recursive: true });
262
-
263
- const targetArchive = join(offlinePkgDir, `./${packageJson.version}.zip`);
264
- await genArchive(targetArchive, packageDir);
265
- log(`离线包zip包打包完成: ${targetArchive}`);
266
-
267
- const packageDescJson = { // 包描述json,之后会通过接口更新
268
- name: offlineConfig.name,
269
- version: packageJson.version,
270
- md5: "",
271
- packageUrl: "",
272
- items: [],
273
- updateTime: String(Math.floor(Date.now() / 1000)),
274
- cacheTime: offlineConfig.cacheTime || "7200",
275
- isLazy: offlineConfig.isLazy || 0,
276
- openType: offlineConfig.openType || "file",
277
- };
278
- Object.keys(offlineConfig.entry || {}).forEach(key => {
279
- const val = offlineConfig.entry[key];
280
- let vals = [];
281
- if (typeof val === 'string') {
282
- vals.push(val);
283
- } else if (Array.isArray(val)) {
284
- vals = val;
285
- }
286
- vals.forEach(v => {
287
- packageDescJson.items.push({
288
- "path": key,
289
- "mimeType": "text/html",
290
- "remoteUrl": v,
291
- "isEntrance": 1
292
- });
293
- });
294
- });
295
- packageDescJson.md5 = await md5File(targetArchive);
296
- const uploadResult = await uploadFile(ossToken, targetArchive, packageDescJson.md5);
297
- packageDescJson.packageUrl = uploadResult.url;
298
- fs.writeFileSync(join(offlinePkgDir, "./offline.package.json"), JSON.stringify(packageDescJson, null, 2));
299
- log(`离线包描述json写入完成: ${join(offlinePkgDir, "./offline.package.json")}`);
300
-
301
- if (config.mode !== "prod") {
302
- packageDescJson.items.forEach(item => {
303
- item.remoteUrl = item.remoteUrl.replace("https://y.tuwan.com", "https://y-test.tuwan.com");
304
- });
305
- }
306
- await syncApi(userDeployHelperConfig, config.mode, offlineConfig, packageDescJson);
307
- }
308
- return {
309
- canBuild: canBuildOfflinePkg,
310
- errorMsg: errorMsg,
311
- hookPostBuild: hookPostBuild,
312
- }
313
- }
314
-
1
+ import fs from 'fs';
2
+ import archiver from 'archiver';
3
+ import { join } from "node:path"
4
+ import { log, getOssToken, getUserDeployHelperConfig } from './util.mjs';
5
+ import { uploadFile } from './upload.js';
6
+ import md5File from 'md5-file';
7
+
8
+
9
+
10
+ function genArchive(outputPath, dir) {
11
+ return new Promise((resolve, reject) => {
12
+ const output = fs.createWriteStream(outputPath);
13
+ const archive = archiver('zip', {
14
+ zlib: { level: 1 } // Sets the compression level.
15
+ });
16
+ let settled = false;
17
+ const onError = (err) => {
18
+ if (settled) return;
19
+ settled = true;
20
+ try {
21
+ archive.abort();
22
+ } catch {
23
+ // ignore
24
+ }
25
+ output.destroy(err);
26
+ reject(err);
27
+ };
28
+ archive.on('error', onError);
29
+ output.on('error', onError);
30
+ // 必须等目标文件流关闭后再继续:仅 archive 'finish' 时缓冲区可能尚未完全刷盘,
31
+ // 后续 md5/上传会读到缺 END 中央目录的截断 zip(如 ADM-ZIP: No END header found)。
32
+ output.on('close', () => {
33
+ if (settled) return;
34
+ settled = true;
35
+ resolve();
36
+ });
37
+ archive.pipe(output);
38
+ archive.directory(dir, false);
39
+ archive.finalize();
40
+ })
41
+ }
42
+
43
+ /**
44
+ * json配置
45
+ * @param {string} workDir 项目工作目录
46
+ * @returns {Object|null} 配置
47
+ */
48
+ export function getJsonConfig(workDir, name) {
49
+ const filePath = join(workDir, name);
50
+ if (fs.existsSync(filePath)) {
51
+ try {
52
+ return JSON.parse(fs.readFileSync(filePath, "utf-8"));
53
+ } catch (_error) {
54
+ // pass
55
+ }
56
+ }
57
+ return null;
58
+ }
59
+
60
+ /**
61
+ * 同步离线包列表到api
62
+ * @param {{offlineApi: {get: string, set: string}}} userDeployHelperConfig 用户配置
63
+ * @param {"prod"|"test"} mode 部署模式 prod: 线上, test: 测试
64
+ * @param {{name: string, remove: boolean}} offlineConfig 离线包配置
65
+ * @param {any} packageDescJson 离线包描述json
66
+ */
67
+ export async function syncApi(userDeployHelperConfig, mode, offlineConfig, packageDescJson) {
68
+ // 根据部署模式,决定更新调用哪个接口
69
+ const doAction = offlineConfig.remove ? "remove" : "add";
70
+ const apiDomain = mode === "prod" ? "https://yapi.tuwan.com" : "https://yapi-test.tuwan.com";
71
+ const getPath = userDeployHelperConfig.offlineApi.get;
72
+ const setPath = userDeployHelperConfig.offlineApi.set;
73
+ const getUrl = `${apiDomain}${getPath}`;
74
+ const setUrl = `${apiDomain}${setPath}`;
75
+ const envPrefix = `${mode === "prod" ? "线上环境" : "测试环境"}[platform=${offlineConfig.platform}]`;
76
+ const nowRes = await fetch(getUrl, {
77
+ headers: {
78
+ platform: String(offlineConfig.platform),
79
+ }
80
+ });
81
+ const nowData = await nowRes.json();
82
+ let needSetData = true;
83
+ let finalJsonData = null;
84
+ if (!nowData || nowData.error !== 0) {
85
+ throw new Error(`获取离线包列表失败, 获取离线包当前配置失败: ${nowData.error_msg || "未知错误"}`);
86
+ }
87
+ const jsonData = JSON.parse(nowData.data.json || "{}");
88
+ finalJsonData = jsonData;
89
+ jsonData.packages = jsonData.packages || [];
90
+ if (doAction === "add") {
91
+ const idx = jsonData.packages.findIndex(item => item.name === offlineConfig.name);
92
+ if (idx !== -1) {
93
+ log(`离线包${offlineConfig.name}已存在, 更新离线包`);
94
+ jsonData.packages[idx] = packageDescJson;
95
+ } else {
96
+ log(`离线包${offlineConfig.name}不存在, 添加离线包`);
97
+ jsonData.packages.push(packageDescJson);
98
+ }
99
+ } else {
100
+ const idx = jsonData.packages.findIndex(item => item.name === offlineConfig.name);
101
+ if (idx === -1) {
102
+ log(`离线包${offlineConfig.name}不存在, 无需删除`);
103
+ needSetData = false;
104
+ }
105
+ jsonData.packages = jsonData.packages.filter(item => item.name !== offlineConfig.name);
106
+ }
107
+ jsonData.packages = jsonData.packages.filter(item => item.name);
108
+ if (needSetData) {
109
+ // console.log('jsonData', jsonData);
110
+ var formdata = new FormData();
111
+ formdata.append("json", JSON.stringify(jsonData));
112
+ const setRes = await fetch(setUrl, {
113
+ method: "POST",
114
+ body: formdata,
115
+ headers: {
116
+ platform: String(offlineConfig.platform),
117
+ }
118
+ });
119
+ const setData = await setRes.json();
120
+ if (!setData || setData.error !== 0) {
121
+ throw new Error(`更新离线包列表失败, 更新离线包当前配置失败: ${setData.error_msg || "未知错误"}`);
122
+ }
123
+ log(`${envPrefix}离线包列表更新完成: ${JSON.stringify(setData)}`);
124
+ // 再次获取列表,确保更新成功
125
+ const nowRes2 = await fetch(getUrl, {
126
+ headers: {
127
+ platform: String(offlineConfig.platform),
128
+ }
129
+ });
130
+ const nowData2 = await nowRes2.json();
131
+ if (!nowData2 || nowData2.error !== 0) {
132
+ throw new Error(`再次获取离线包列表失败, 获取离线包当前配置失败: ${nowData2.error_msg || "未知错误"}`);
133
+ }
134
+ finalJsonData = JSON.parse(nowData2.data.json || "{}");
135
+ }
136
+
137
+ const packages = finalJsonData.packages || [];
138
+ console.log(`${envPrefix}当前离线包列表:`, packages.map(item => ({ ...item, items: '省略' + item.items.length + '个条目' })));
139
+ }
140
+
141
+ /**
142
+ * @deprecated 不再需要这个函数, 如果插件使用的是@taole/vite-plugin-dynamic-base, 则不需要这个函数
143
+ * hack
144
+ * 由于vite-plugin-dynamic-base插件和legacy插件同时使用, 生存的入口文件中代码有点问题,这里直接修改有问题的代码
145
+ */
146
+ function fixEntryHtml(config, offlineConfig) {
147
+ if (!offlineConfig || !config) return;
148
+ const entryHtmlPath = join(config.workDir, offlineConfig.distDir, "index.html");
149
+ if (!fs.existsSync(entryHtmlPath)) {
150
+ throw new Error(`构建产物${entryHtmlPath}不存在`);
151
+ }
152
+ const markLine = "} else if (item.tagName == 'script') {";
153
+ const replaceLine = `} else if (item.tagName == 'script')/*injected by deploy-helper*/{
154
+ if(item.attrs.id=='vite-legacy-polyfill')childNode.onload=function(){System.import(window.__dynamic_base__ + document.getElementById('vite-legacy-entry').getAttribute('data-src'))};
155
+ `;
156
+ let entryHtml = fs.readFileSync(entryHtmlPath, "utf-8");
157
+ entryHtml = entryHtml.replace(markLine, replaceLine);
158
+ fs.writeFileSync(entryHtmlPath, entryHtml);
159
+ }
160
+
161
+ /**
162
+ * @typedef {Object} CheckOfflinePkgResult
163
+ * @property {string} workDir 工作目录
164
+ * @property {boolean} canBuild 是否可以构建离线包
165
+ * @property {string} errorMsg 错误信息
166
+ * @property {function} hookPostBuild 构建后钩子
167
+ * @property {function} hookPostDeployTest 部署到测试环境后钩子
168
+ * @property {function} hookPostDeployProd 部署到生产环境后钩子
169
+ */
170
+
171
+ /**
172
+ * 在项目构建好之后,将项目打包成离线包,并上传到指定服务器
173
+ * @param {Object} config 配置
174
+ * @param {string} config.workDir 工作目录
175
+ * @param {"prod"|"test"} config.mode 部署模式
176
+ * @returns {CheckOfflinePkgResult} 结果
177
+ */
178
+ export function checkOfflinePkg(config) {
179
+ let canBuildOfflinePkg = true;
180
+ let errorMsg = "";
181
+ const offlineConfig = getJsonConfig(config.workDir, "offline.config.json");
182
+ if (offlineConfig) {
183
+ offlineConfig.distDir = offlineConfig.distDir || "dist";
184
+ offlineConfig.platform = offlineConfig.platform || 3; // 3,4是点点
185
+ }
186
+ const packageJson = getJsonConfig(config.workDir, "package.json");
187
+ const userDeployHelperConfig = getUserDeployHelperConfig();
188
+ const distPath = join(config.workDir, offlineConfig && offlineConfig.distDir ? offlineConfig.distDir : "dist");
189
+ const allDeps = {
190
+ ...packageJson.devDependencies,
191
+ ...packageJson.dependencies,
192
+ };
193
+ const useOldPDB = !!allDeps['vite-plugin-dynamic-base'];
194
+
195
+ // 如果offlineConfig.remove为true,则不构建离线包
196
+ const willRemovePkg = offlineConfig && offlineConfig.name && offlineConfig.remove === true && offlineConfig.skip !== true;
197
+ const willSkip = !offlineConfig || !offlineConfig.name || offlineConfig.skip === true || (offlineConfig.onlyTest === true && config.mode === "prod");
198
+ if (willRemovePkg) {
199
+ return {
200
+ canBuild: true,
201
+ errorMsg: "",
202
+ hookPostBuild: async () => {
203
+ if (useOldPDB) {
204
+ fixEntryHtml(config, offlineConfig);
205
+ }
206
+ log(`开始删除离线包${offlineConfig.name}`);
207
+ await syncApi(userDeployHelperConfig, config.mode, offlineConfig, null);
208
+ }
209
+ }
210
+ }
211
+ if (!fs.existsSync(distPath)) {
212
+ errorMsg = `构建产物${distPath}不存在, 请先构建项目`;
213
+ canBuildOfflinePkg = false;
214
+ } else if (offlineConfig && !offlineConfig.name) {
215
+ errorMsg = "离线包配置文件中未配置name, 请先配置";
216
+ canBuildOfflinePkg = false;
217
+ } else if (!userDeployHelperConfig || !userDeployHelperConfig.offlineApi || !userDeployHelperConfig.offlineApi.get || !userDeployHelperConfig.offlineApi.set) {
218
+ errorMsg = "未配置离线包接口, 请移步看配置文档: https://alidocs.dingtalk.com/i/nodes/R1zknDm0WRkbz13oHn0LDz3ZVBQEx5rG?doc_type=wiki_doc";
219
+ canBuildOfflinePkg = false;
220
+ } else if (!packageJson) {
221
+ errorMsg = "啊没有package.json?";
222
+ canBuildOfflinePkg = false;
223
+ } else {
224
+ if (!allDeps['vite-plugin-dynamic-base'] && !allDeps['@taole/vite-plugin-dynamic-base']) {
225
+ errorMsg = "检查到项目中未安装依赖@taole/vite-plugin-dynamic-base, 请先安装依赖并调整构建代码以支持离线化,相关文档:https://alidocs.dingtalk.com/i/nodes/ydxXB52LJqexwD71F9K5XNMrJqjMp697?doc_type=wiki_doc";
226
+ canBuildOfflinePkg = false;
227
+ }
228
+ }
229
+ if (willSkip) {
230
+ if (!offlineConfig) {
231
+ return {
232
+ canBuild: false,
233
+ errorMsg: ""
234
+ }
235
+ }
236
+ if (offlineConfig.onlyTest === true && config.mode === "prod") {
237
+ console.log(`离线包${offlineConfig.name}只用于测试环境, 跳过构建线上环境的离线包构建`);
238
+ }
239
+ return {
240
+ canBuild: true,
241
+ errorMsg: "",
242
+ hookPostBuild: async () => {
243
+ if (useOldPDB) {
244
+ fixEntryHtml(config, offlineConfig);
245
+ }
246
+ }
247
+ }
248
+ }
249
+ let ossToken = "";
250
+ if (canBuildOfflinePkg) {
251
+ ossToken = getOssToken();
252
+ if (!ossToken) {
253
+ errorMsg = "获取ossToken失败";
254
+ canBuildOfflinePkg = false;
255
+ }
256
+ }
257
+ if (!canBuildOfflinePkg) {
258
+ return {
259
+ canBuild: false,
260
+ errorMsg: errorMsg
261
+ }
262
+ }
263
+ const hookPostBuild = async () => {
264
+ if (!offlineConfig || !config) return;
265
+ // 在构建完成后,执行一些操作
266
+ if (useOldPDB) {
267
+ fixEntryHtml(config, offlineConfig);
268
+ }
269
+ // 开始进行打包流程
270
+ const offlinePkgDir = join(config.workDir, "./offlinepkgDist");
271
+ if (fs.existsSync(offlinePkgDir)) {
272
+ fs.rmSync(offlinePkgDir, { recursive: true });
273
+ } else {
274
+ fs.mkdirSync(offlinePkgDir, { recursive: true });
275
+ }
276
+
277
+ const packageDir = join(offlinePkgDir, "./package");
278
+ fs.mkdirSync(packageDir, { recursive: true });
279
+ // cp dist到offlinepkgDist目录下
280
+ fs.cpSync(join(config.workDir, offlineConfig.distDir), join(packageDir, offlineConfig.distDir), { recursive: true });
281
+
282
+ const targetArchive = join(offlinePkgDir, `./${packageJson.version}.zip`);
283
+ await genArchive(targetArchive, packageDir);
284
+ log(`离线包zip包打包完成: ${targetArchive}`);
285
+
286
+ const packageDescJson = { // 包描述json,之后会通过接口更新
287
+ name: offlineConfig.name,
288
+ version: packageJson.version,
289
+ md5: "",
290
+ packageUrl: "",
291
+ items: [],
292
+ updateTime: String(Math.floor(Date.now() / 1000)),
293
+ cacheTime: offlineConfig.cacheTime || "7200",
294
+ isLazy: offlineConfig.isLazy || 0,
295
+ openType: offlineConfig.openType || "file",
296
+ };
297
+ Object.keys(offlineConfig.entry || {}).forEach(key => {
298
+ const val = offlineConfig.entry[key];
299
+ let vals = [];
300
+ if (typeof val === 'string') {
301
+ vals.push(val);
302
+ } else if (Array.isArray(val)) {
303
+ vals = val;
304
+ }
305
+ vals.forEach(v => {
306
+ packageDescJson.items.push({
307
+ "path": key,
308
+ "mimeType": "text/html",
309
+ "remoteUrl": v,
310
+ "isEntrance": 1
311
+ });
312
+ });
313
+ });
314
+ packageDescJson.md5 = await md5File(targetArchive);
315
+ const uploadResult = await uploadFile(ossToken, targetArchive, packageDescJson.md5);
316
+ packageDescJson.packageUrl = uploadResult.url;
317
+ fs.writeFileSync(join(offlinePkgDir, "./offline.package.json"), JSON.stringify(packageDescJson, null, 2));
318
+ log(`离线包描述json写入完成: ${join(offlinePkgDir, "./offline.package.json")}`);
319
+
320
+ if (config.mode !== "prod") {
321
+ packageDescJson.items.forEach(item => {
322
+ item.remoteUrl = item.remoteUrl.replace("https://y.tuwan.com", "https://y-test.tuwan.com");
323
+ });
324
+ }
325
+ await syncApi(userDeployHelperConfig, config.mode, offlineConfig, packageDescJson);
326
+ }
327
+ return {
328
+ canBuild: canBuildOfflinePkg,
329
+ errorMsg: errorMsg,
330
+ hookPostBuild: hookPostBuild,
331
+ }
332
+ }
333
+