@dimina/compiler 1.0.12 → 1.0.14-beta.0

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,371 +1,356 @@
1
- import fs from "node:fs";
1
+ import { a as getContentByPath, d as resetStoreInfo, f as resolveAppAlias, g as hasCompileInfo, i as getComponent, l as getTargetPath, m as collectAssets, n as getAppId, o as getNpmResolver, t as getAppConfigInfo, u as getWorkPath } from "../env-DgCLbrQb.js";
2
2
  import { resolve, sep } from "node:path";
3
3
  import { isMainThread, parentPort } from "node:worker_threads";
4
+ import fs from "node:fs";
5
+ import { transform } from "esbuild";
4
6
  import { parseSync } from "oxc-parser";
5
7
  import { walk } from "oxc-walker";
6
8
  import { transformSync } from "oxc-transform";
7
9
  import MagicString from "magic-string";
8
- import { transform } from "esbuild";
9
10
  import ts from "typescript";
10
- import { r as resetStoreInfo, e as getTargetPath, i as hasCompileInfo, a as getContentByPath, j as getAppConfigInfo, g as getComponent, f as getWorkPath } from "../env-QQjdhY-G.js";
11
- const processedModules = /* @__PURE__ */ new Set();
12
- if (!isMainThread) {
13
- parentPort.on("message", async ({ pages, storeInfo }) => {
14
- try {
15
- resetStoreInfo(storeInfo);
16
- const progress = {
17
- _completedTasks: 0,
18
- get completedTasks() {
19
- return this._completedTasks;
20
- },
21
- set completedTasks(value) {
22
- this._completedTasks = value;
23
- parentPort.postMessage({ completedTasks: this.completedTasks });
24
- }
25
- };
26
- const mainCompileRes = await compileJS(pages.mainPages, null, null, progress);
27
- for (const [root, subPages] of Object.entries(pages.subPages)) {
28
- try {
29
- const subCompileRes = await compileJS(
30
- subPages.info,
31
- root,
32
- subPages.independent ? [] : mainCompileRes,
33
- progress
34
- );
35
- await writeCompileRes(subCompileRes, root);
36
- } catch (error) {
37
- throw new Error(`Error processing subpackage ${root}: ${error.message}
38
- ${error.stack}`);
39
- }
40
- }
41
- await writeCompileRes(mainCompileRes, null);
42
- processedModules.clear();
43
- parentPort.postMessage({ success: true });
44
- } catch (error) {
45
- processedModules.clear();
46
- parentPort.postMessage({
47
- success: false,
48
- error: {
49
- message: error.message,
50
- stack: error.stack,
51
- name: error.name
52
- }
53
- });
54
- }
55
- });
56
- }
11
+ //#region src/core/logic-compiler.js
12
+ var processedModules = /* @__PURE__ */ new Set();
13
+ if (!isMainThread) parentPort.on("message", async ({ pages, storeInfo }) => {
14
+ try {
15
+ resetStoreInfo(storeInfo);
16
+ const progress = {
17
+ _completedTasks: 0,
18
+ get completedTasks() {
19
+ return this._completedTasks;
20
+ },
21
+ set completedTasks(value) {
22
+ this._completedTasks = value;
23
+ parentPort.postMessage({ completedTasks: this.completedTasks });
24
+ }
25
+ };
26
+ const mainCompileRes = await compileJS(pages.mainPages, null, null, progress);
27
+ for (const [root, subPages] of Object.entries(pages.subPages)) try {
28
+ await writeCompileRes(await compileJS(subPages.info, root, subPages.independent ? [] : mainCompileRes, progress), root);
29
+ } catch (error) {
30
+ throw new Error(`Error processing subpackage ${root}: ${error.message}\n${error.stack}`);
31
+ }
32
+ await writeCompileRes(mainCompileRes, null);
33
+ processedModules.clear();
34
+ parentPort.postMessage({ success: true });
35
+ } catch (error) {
36
+ processedModules.clear();
37
+ parentPort.postMessage({
38
+ success: false,
39
+ error: {
40
+ message: error.message,
41
+ stack: error.stack,
42
+ name: error.name
43
+ }
44
+ });
45
+ }
46
+ });
57
47
  async function writeCompileRes(compileRes, root) {
58
- let mergeCode = "";
59
- for (const module of compileRes) {
60
- const amdFormat = `modDefine('${module.path}', function(require, module, exports) {
48
+ let mergeCode = "";
49
+ for (const module of compileRes) {
50
+ const { code: minifiedCode } = await transform(`modDefine('${module.path}', function(require, module, exports) {
61
51
  ${module.code}
62
- });`;
63
- const { code: minifiedCode } = await transform(amdFormat, {
64
- minify: true,
65
- target: ["es2023"],
66
- // quickjs 支持版本
67
- platform: "neutral"
68
- });
69
- mergeCode += minifiedCode;
70
- }
71
- if (root) {
72
- const subDir = `${getTargetPath()}/${root}`;
73
- if (!fs.existsSync(subDir)) {
74
- fs.mkdirSync(subDir, { recursive: true });
75
- }
76
- fs.writeFileSync(`${subDir}/logic.js`, mergeCode);
77
- } else {
78
- const mainDir = `${getTargetPath()}/main`;
79
- if (!fs.existsSync(mainDir)) {
80
- fs.mkdirSync(mainDir, { recursive: true });
81
- }
82
- fs.writeFileSync(`${mainDir}/logic.js`, mergeCode);
83
- }
52
+ });`, {
53
+ minify: true,
54
+ target: ["es2023"],
55
+ platform: "neutral"
56
+ });
57
+ mergeCode += minifiedCode;
58
+ }
59
+ if (root) {
60
+ const subDir = `${getTargetPath()}/${root}`;
61
+ if (!fs.existsSync(subDir)) fs.mkdirSync(subDir, { recursive: true });
62
+ fs.writeFileSync(`${subDir}/logic.js`, mergeCode);
63
+ } else {
64
+ const mainDir = `${getTargetPath()}/main`;
65
+ if (!fs.existsSync(mainDir)) fs.mkdirSync(mainDir, { recursive: true });
66
+ fs.writeFileSync(`${mainDir}/logic.js`, mergeCode);
67
+ }
84
68
  }
69
+ /**
70
+ * 编译 js 文件
71
+ */
85
72
  async function compileJS(pages, root, mainCompileRes, progress) {
86
- const compileRes = [];
87
- if (!root) {
88
- await buildJSByPath(root, { path: "app" }, compileRes, mainCompileRes, false);
89
- }
90
- for (const page of pages) {
91
- await buildJSByPath(root, page, compileRes, mainCompileRes, true);
92
- progress.completedTasks++;
93
- }
94
- return compileRes;
73
+ const compileRes = [];
74
+ if (!root) await buildJSByPath(root, { path: "app" }, compileRes, mainCompileRes, false);
75
+ for (const page of pages) {
76
+ await buildJSByPath(root, page, compileRes, mainCompileRes, true);
77
+ progress.completedTasks++;
78
+ }
79
+ return compileRes;
95
80
  }
96
81
  async function buildJSByPath(packageName, module, compileRes, mainCompileRes, addExtra, depthChain = [], putMain = false) {
97
- const currentPath = module.path;
98
- if (depthChain.includes(currentPath)) {
99
- console.warn("[logic]", `检测到循环依赖: ${[...depthChain, currentPath].join(" -> ")}`);
100
- return;
101
- }
102
- if (depthChain.length > 20) {
103
- console.warn("[logic]", `检测到深度依赖: ${[...depthChain, currentPath].join(" -> ")}`);
104
- return;
105
- }
106
- depthChain = [...depthChain, currentPath];
107
- if (!module.path) {
108
- return;
109
- }
110
- if (hasCompileInfo(module.path, compileRes, mainCompileRes)) {
111
- return;
112
- }
113
- const compileInfo = {
114
- path: module.path,
115
- code: ""
116
- };
117
- const src = module.path.startsWith("/") ? module.path : `/${module.path}`;
118
- const modulePath = getJSAbsolutePath(src);
119
- if (!modulePath) {
120
- console.warn("[logic]", `找不到模块文件: ${src}`);
121
- return;
122
- }
123
- const sourceCode = getContentByPath(modulePath);
124
- if (!sourceCode) {
125
- console.warn("[logic]", `无法读取模块文件: ${modulePath}`);
126
- return;
127
- }
128
- let jsCode = sourceCode;
129
- if (modulePath.endsWith(".ts")) {
130
- try {
131
- const result = ts.transpileModule(sourceCode, {
132
- compilerOptions: {
133
- target: ts.ScriptTarget.ES2020,
134
- module: ts.ModuleKind.ESNext,
135
- // 保持 ES6 模块语法,让 oxc-transform 后续处理
136
- strict: false,
137
- esModuleInterop: true,
138
- skipLibCheck: true
139
- }
140
- });
141
- jsCode = result.outputText;
142
- } catch (error) {
143
- console.error(`[logic] TypeScript 编译失败 ${modulePath}:`, error.message);
144
- jsCode = sourceCode;
145
- }
146
- }
147
- const parseResult = parseSync(modulePath, jsCode, {
148
- sourceType: "module",
149
- lang: modulePath.endsWith(".ts") ? "ts" : "js"
150
- });
151
- const ast = parseResult.program;
152
- const s = new MagicString(jsCode);
153
- const extraInfo = {
154
- path: module.path
155
- };
156
- if (module.component) {
157
- extraInfo.component = true;
158
- }
159
- if (module.usingComponents) {
160
- const componentsObj = {};
161
- const allSubPackages = getAppConfigInfo().subPackages;
162
- for (const [name, path] of Object.entries(module.usingComponents)) {
163
- let toMainSubPackage = true;
164
- if (packageName) {
165
- const normalizedPath = path.startsWith("/") ? path.substring(1) : path;
166
- for (const subPackage of allSubPackages) {
167
- if (normalizedPath.startsWith(`${subPackage.root}/`)) {
168
- toMainSubPackage = false;
169
- break;
170
- }
171
- }
172
- } else {
173
- toMainSubPackage = false;
174
- }
175
- const componentModule = getComponent(path);
176
- if (!componentModule) {
177
- continue;
178
- }
179
- await buildJSByPath(packageName, componentModule, compileRes, mainCompileRes, true, depthChain, toMainSubPackage);
180
- componentsObj[name] = path;
181
- }
182
- extraInfo.usingComponents = componentsObj;
183
- }
184
- if (addExtra) {
185
- const extraInfoCode = `globalThis.__extraInfo = ${JSON.stringify(extraInfo)};
186
- `;
187
- s.prepend(extraInfoCode);
188
- }
189
- if (putMain) {
190
- mainCompileRes.push(compileInfo);
191
- } else {
192
- compileRes.push(compileInfo);
193
- }
194
- const pathReplacements = [];
195
- const dependenciesToProcess = [];
196
- walk(ast, {
197
- enter(node, parent) {
198
- if (node.type === "CallExpression") {
199
- const isRequire = node.callee.type === "Identifier" && node.callee.name === "require";
200
- const isRequireProperty = node.callee.type === "MemberExpression" && node.callee.object?.type === "Identifier" && node.callee.object?.name === "require";
201
- if ((isRequire || isRequireProperty) && node.arguments.length > 0 && (node.arguments[0].type === "StringLiteral" || node.arguments[0].type === "Literal")) {
202
- const arg = node.arguments[0];
203
- const requirePath = arg.value;
204
- if (requirePath) {
205
- let id;
206
- if (requirePath.startsWith("@") || requirePath.startsWith("miniprogram_npm/")) {
207
- if (requirePath.startsWith("@")) {
208
- id = `/miniprogram_npm/${requirePath}`;
209
- } else {
210
- id = requirePath.startsWith("/") ? requirePath : `/${requirePath}`;
211
- }
212
- } else {
213
- const requireFullPath = resolve(modulePath, `../${requirePath}`);
214
- id = requireFullPath.split(`${getWorkPath()}${sep}`)[1];
215
- id = id.replace(/\.(js|ts)$/, "").replace(/\\/g, "/");
216
- if (!id.startsWith("/")) {
217
- id = "/" + id;
218
- }
219
- }
220
- {
221
- pathReplacements.push({
222
- start: arg.start,
223
- end: arg.end,
224
- newValue: id
225
- });
226
- if (!processedModules.has(packageName + id)) {
227
- dependenciesToProcess.push(id);
228
- }
229
- }
230
- }
231
- }
232
- }
233
- if (node.type === "ImportDeclaration") {
234
- const importPath = node.source.value;
235
- if (importPath) {
236
- let id;
237
- let shouldProcess = false;
238
- if (importPath.startsWith("@") || importPath.startsWith("miniprogram_npm/")) {
239
- if (importPath.startsWith("@")) {
240
- id = `/miniprogram_npm/${importPath}`;
241
- } else {
242
- id = importPath.startsWith("/") ? importPath : `/${importPath}`;
243
- }
244
- shouldProcess = true;
245
- } else if (importPath.startsWith("./") || importPath.startsWith("../") || !importPath.startsWith("/")) {
246
- const importFullPath = resolve(modulePath, `../${importPath}`);
247
- id = importFullPath.split(`${getWorkPath()}${sep}`)[1];
248
- id = id.replace(/\.(js|ts)$/, "").replace(/\\/g, "/");
249
- if (!id.startsWith("/")) {
250
- id = "/" + id;
251
- }
252
- shouldProcess = true;
253
- } else {
254
- id = importPath;
255
- shouldProcess = true;
256
- }
257
- if (shouldProcess) {
258
- pathReplacements.push({
259
- start: node.source.start,
260
- end: node.source.end,
261
- newValue: id
262
- });
263
- if (!processedModules.has(packageName + id)) {
264
- dependenciesToProcess.push(id);
265
- }
266
- }
267
- }
268
- }
269
- }
270
- });
271
- for (const depId of dependenciesToProcess) {
272
- await buildJSByPath(packageName, { path: depId }, compileRes, mainCompileRes, false, depthChain);
273
- }
274
- for (const replacement of pathReplacements.reverse()) {
275
- s.overwrite(replacement.start, replacement.end, `'${replacement.newValue}'`);
276
- }
277
- const modifiedCode = s.toString();
278
- let transformedCode = modifiedCode;
279
- if (modulePath.endsWith(".ts") || modulePath.endsWith(".tsx")) {
280
- try {
281
- const result = transformSync(modulePath, modifiedCode, {
282
- sourceType: "module",
283
- lang: modulePath.endsWith(".tsx") ? "tsx" : "ts",
284
- target: "es2020",
285
- typescript: {
286
- onlyRemoveTypeImports: true
287
- }
288
- });
289
- transformedCode = result.code;
290
- } catch (error) {
291
- console.error(`[logic] oxc-transform 转换失败 ${modulePath}:`, error.message);
292
- transformedCode = modifiedCode;
293
- }
294
- }
295
- try {
296
- const esbuildResult = await transform(transformedCode, {
297
- format: "cjs",
298
- target: "es2020",
299
- platform: "neutral",
300
- loader: "js"
301
- });
302
- const esbuildCode = esbuildResult.code;
303
- const esbuildAst = parseSync(modulePath, esbuildCode, {
304
- sourceType: "module",
305
- lang: "js"
306
- });
307
- const postEsbuildReplacements = [];
308
- walk(esbuildAst.program, {
309
- enter(node) {
310
- if (node.type === "CallExpression") {
311
- const isRequire = node.callee.type === "Identifier" && node.callee.name === "require";
312
- const isRequireProperty = node.callee.type === "MemberExpression" && node.callee.object?.type === "Identifier" && node.callee.object?.name === "require";
313
- if ((isRequire || isRequireProperty) && node.arguments.length > 0 && (node.arguments[0].type === "StringLiteral" || node.arguments[0].type === "Literal")) {
314
- const arg = node.arguments[0];
315
- const requirePath = arg.value;
316
- if (requirePath && (requirePath.startsWith("./") || requirePath.startsWith("../"))) {
317
- let id;
318
- if (requirePath.startsWith("@") || requirePath.startsWith("miniprogram_npm/")) {
319
- if (requirePath.startsWith("@")) {
320
- id = `/miniprogram_npm/${requirePath}`;
321
- } else {
322
- id = requirePath.startsWith("/") ? requirePath : `/${requirePath}`;
323
- }
324
- } else {
325
- const requireFullPath = resolve(modulePath, `../${requirePath}`);
326
- id = requireFullPath.split(`${getWorkPath()}${sep}`)[1];
327
- id = id.replace(/\.(js|ts)$/, "").replace(/\\/g, "/");
328
- if (!id.startsWith("/")) {
329
- id = "/" + id;
330
- }
331
- }
332
- postEsbuildReplacements.push({
333
- start: arg.start,
334
- end: arg.end,
335
- newValue: id
336
- });
337
- }
338
- }
339
- }
340
- }
341
- });
342
- if (postEsbuildReplacements.length > 0) {
343
- const finalMagicString = new MagicString(esbuildCode);
344
- for (const replacement of postEsbuildReplacements.reverse()) {
345
- finalMagicString.overwrite(replacement.start, replacement.end, `"${replacement.newValue}"`);
346
- }
347
- compileInfo.code = finalMagicString.toString();
348
- } else {
349
- compileInfo.code = esbuildCode;
350
- }
351
- } catch (error) {
352
- console.error(`[logic] esbuild 转换失败 ${modulePath}:`, error.message);
353
- compileInfo.code = transformedCode;
354
- }
355
- processedModules.add(packageName + currentPath);
82
+ const currentPath = module.path;
83
+ if (depthChain.includes(currentPath)) {
84
+ console.warn("[logic]", `检测到循环依赖: ${[...depthChain, currentPath].join(" -> ")}`);
85
+ return;
86
+ }
87
+ if (depthChain.length > 20) {
88
+ console.warn("[logic]", `检测到深度依赖: ${[...depthChain, currentPath].join(" -> ")}`);
89
+ return;
90
+ }
91
+ depthChain = [...depthChain, currentPath];
92
+ if (!module.path) return;
93
+ if (hasCompileInfo(module.path, compileRes, mainCompileRes)) return;
94
+ const compileInfo = {
95
+ path: module.path,
96
+ code: ""
97
+ };
98
+ const src = module.path.startsWith("/") ? module.path : `/${module.path}`;
99
+ const modulePath = getJSAbsolutePath(src);
100
+ if (!modulePath) {
101
+ console.warn("[logic]", `找不到模块文件: ${src}`);
102
+ return;
103
+ }
104
+ const sourceCode = getContentByPath(modulePath);
105
+ if (!sourceCode) {
106
+ console.warn("[logic]", `无法读取模块文件: ${modulePath}`);
107
+ return;
108
+ }
109
+ let jsCode = sourceCode;
110
+ if (modulePath.endsWith(".ts")) try {
111
+ jsCode = ts.transpileModule(sourceCode, { compilerOptions: {
112
+ target: ts.ScriptTarget.ES2020,
113
+ module: ts.ModuleKind.ESNext,
114
+ strict: false,
115
+ esModuleInterop: true,
116
+ skipLibCheck: true
117
+ } }).outputText;
118
+ } catch (error) {
119
+ console.error(`[logic] TypeScript 编译失败 ${modulePath}:`, error.message);
120
+ jsCode = sourceCode;
121
+ }
122
+ const ast = parseSync(modulePath, jsCode, {
123
+ sourceType: "module",
124
+ lang: modulePath.endsWith(".ts") ? "ts" : "js"
125
+ }).program;
126
+ const s = new MagicString(jsCode);
127
+ const extraInfo = { path: module.path };
128
+ if (module.component) extraInfo.component = true;
129
+ if (module.usingComponents) {
130
+ const componentsObj = {};
131
+ const allSubPackages = getAppConfigInfo().subPackages;
132
+ for (const [name, path] of Object.entries(module.usingComponents)) {
133
+ let toMainSubPackage = true;
134
+ if (packageName) {
135
+ const normalizedPath = path.startsWith("/") ? path.substring(1) : path;
136
+ for (const subPackage of allSubPackages) if (normalizedPath.startsWith(`${subPackage.root}/`)) {
137
+ toMainSubPackage = false;
138
+ break;
139
+ }
140
+ } else toMainSubPackage = false;
141
+ const componentModule = getComponent(path);
142
+ if (!componentModule) continue;
143
+ await buildJSByPath(packageName, componentModule, compileRes, mainCompileRes, true, depthChain, putMain || toMainSubPackage);
144
+ componentsObj[name] = path;
145
+ }
146
+ extraInfo.usingComponents = componentsObj;
147
+ }
148
+ if (addExtra) {
149
+ const extraInfoCode = `globalThis.__extraInfo = ${JSON.stringify(extraInfo)};\n`;
150
+ s.prepend(extraInfoCode);
151
+ }
152
+ if (putMain) mainCompileRes.push(compileInfo);
153
+ else compileRes.push(compileInfo);
154
+ const pathReplacements = [];
155
+ const dependenciesToProcess = [];
156
+ walk(ast, { enter(node, parent) {
157
+ if ((node.type === "StringLiteral" || node.type === "Literal") && isLocalAssetString(node.value)) pathReplacements.push({
158
+ start: node.start,
159
+ end: node.end,
160
+ newValue: collectAssets(getWorkPath(), modulePath, node.value, getTargetPath(), getAppId())
161
+ });
162
+ if (node.type === "CallExpression") {
163
+ const isRequire = node.callee.type === "Identifier" && node.callee.name === "require";
164
+ const isRequireProperty = node.callee.type === "MemberExpression" && node.callee.object?.type === "Identifier" && node.callee.object?.name === "require";
165
+ if ((isRequire || isRequireProperty) && node.arguments.length > 0 && (node.arguments[0].type === "StringLiteral" || node.arguments[0].type === "Literal")) {
166
+ const arg = node.arguments[0];
167
+ const requirePath = arg.value;
168
+ if (requirePath) {
169
+ const { id, shouldProcess } = resolveDependencyId(requirePath, modulePath, false);
170
+ if (shouldProcess) {
171
+ pathReplacements.push({
172
+ start: arg.start,
173
+ end: arg.end,
174
+ newValue: id
175
+ });
176
+ if (!processedModules.has(packageName + id)) dependenciesToProcess.push(id);
177
+ }
178
+ }
179
+ }
180
+ }
181
+ if (node.type === "ImportDeclaration") {
182
+ const importPath = node.source.value;
183
+ if (importPath) {
184
+ const { id, shouldProcess } = resolveDependencyId(importPath, modulePath, true);
185
+ if (shouldProcess) {
186
+ pathReplacements.push({
187
+ start: node.source.start,
188
+ end: node.source.end,
189
+ newValue: id
190
+ });
191
+ if (!processedModules.has(packageName + id)) dependenciesToProcess.push(id);
192
+ }
193
+ }
194
+ }
195
+ if ((node.type === "ExportAllDeclaration" || node.type === "ExportNamedDeclaration") && node.source) {
196
+ const exportPath = node.source.value;
197
+ if (exportPath) {
198
+ const { id, shouldProcess } = resolveDependencyId(exportPath, modulePath, true);
199
+ if (shouldProcess) {
200
+ pathReplacements.push({
201
+ start: node.source.start,
202
+ end: node.source.end,
203
+ newValue: id
204
+ });
205
+ if (!processedModules.has(packageName + id)) dependenciesToProcess.push(id);
206
+ }
207
+ }
208
+ }
209
+ } });
210
+ for (const depId of dependenciesToProcess) await buildJSByPath(packageName, { path: depId }, compileRes, mainCompileRes, false, depthChain, putMain);
211
+ for (const replacement of pathReplacements.reverse()) s.overwrite(replacement.start, replacement.end, `'${replacement.newValue}'`);
212
+ const modifiedCode = s.toString();
213
+ let transformedCode = modifiedCode;
214
+ if (modulePath.endsWith(".ts") || modulePath.endsWith(".tsx")) try {
215
+ transformedCode = transformSync(modulePath, modifiedCode, {
216
+ sourceType: "module",
217
+ lang: modulePath.endsWith(".tsx") ? "tsx" : "ts",
218
+ target: "es2020",
219
+ typescript: { onlyRemoveTypeImports: true }
220
+ }).code;
221
+ } catch (error) {
222
+ console.error(`[logic] oxc-transform 转换失败 ${modulePath}:`, error.message);
223
+ transformedCode = modifiedCode;
224
+ }
225
+ try {
226
+ const esbuildCode = (await transform(transformedCode, {
227
+ format: "cjs",
228
+ target: "es2020",
229
+ platform: "neutral",
230
+ loader: "js"
231
+ })).code;
232
+ const esbuildAst = parseSync(modulePath, esbuildCode, {
233
+ sourceType: "module",
234
+ lang: "js"
235
+ });
236
+ const postEsbuildReplacements = [];
237
+ walk(esbuildAst.program, { enter(node) {
238
+ if (node.type === "CallExpression") {
239
+ const isRequire = node.callee.type === "Identifier" && node.callee.name === "require";
240
+ const isRequireProperty = node.callee.type === "MemberExpression" && node.callee.object?.type === "Identifier" && node.callee.object?.name === "require";
241
+ if ((isRequire || isRequireProperty) && node.arguments.length > 0 && (node.arguments[0].type === "StringLiteral" || node.arguments[0].type === "Literal")) {
242
+ const arg = node.arguments[0];
243
+ const requirePath = arg.value;
244
+ if (requirePath && (requirePath.startsWith("./") || requirePath.startsWith("../"))) {
245
+ const { id } = resolveDependencyId(requirePath, modulePath, false);
246
+ postEsbuildReplacements.push({
247
+ start: arg.start,
248
+ end: arg.end,
249
+ newValue: id
250
+ });
251
+ }
252
+ }
253
+ }
254
+ } });
255
+ if (postEsbuildReplacements.length > 0) {
256
+ const finalMagicString = new MagicString(esbuildCode);
257
+ for (const replacement of postEsbuildReplacements.reverse()) finalMagicString.overwrite(replacement.start, replacement.end, `"${replacement.newValue}"`);
258
+ compileInfo.code = finalMagicString.toString();
259
+ } else compileInfo.code = esbuildCode;
260
+ } catch (error) {
261
+ console.error(`[logic] esbuild 转换失败 ${modulePath}:`, error.message);
262
+ compileInfo.code = transformedCode;
263
+ }
264
+ processedModules.add(packageName + currentPath);
265
+ }
266
+ function isLocalAssetString(value) {
267
+ return typeof value === "string" && !value.startsWith("http") && !value.startsWith("//") && (value.startsWith("/") || value.startsWith("./") || value.startsWith("../")) && /\.(?:png|jpe?g|gif|svg)(?:\?.*)?$/.test(value);
356
268
  }
269
+ /**
270
+ * 获取 JavaScript 或 TypeScript 文件的绝对路径
271
+ * @param {string} modulePath - 模块路径
272
+ * @returns {string|null} - 文件的绝对路径,如果找不到则返回 null
273
+ */
357
274
  function getJSAbsolutePath(modulePath) {
358
- const workPath = getWorkPath();
359
- const fileTypes = [".js", ".ts"];
360
- for (const ext of fileTypes) {
361
- const fullPath = `${workPath}${modulePath}${ext}`;
362
- if (fs.existsSync(fullPath)) {
363
- return fullPath;
364
- }
365
- }
366
- return null;
275
+ const workPath = getWorkPath();
276
+ const resolvedModuleId = resolveModuleIdToExistingPath(modulePath);
277
+ if (!resolvedModuleId) return null;
278
+ for (const ext of [".js", ".ts"]) {
279
+ const fullPath = `${workPath}${resolvedModuleId}${ext}`;
280
+ if (fs.existsSync(fullPath)) return fullPath;
281
+ }
282
+ return null;
283
+ }
284
+ function resolveDependencyId(specifier, modulePath, allowAbsolute) {
285
+ if (!specifier) return {
286
+ id: specifier,
287
+ shouldProcess: false
288
+ };
289
+ if (specifier.startsWith("miniprogram_npm/")) {
290
+ const npmModuleId = normalizeModuleId(`/${specifier}`);
291
+ return {
292
+ id: resolveModuleIdToExistingPath(npmModuleId) || npmModuleId,
293
+ shouldProcess: true
294
+ };
295
+ }
296
+ if (specifier.startsWith("./") || specifier.startsWith("../")) return {
297
+ id: resolveRelativeModuleId(specifier, modulePath),
298
+ shouldProcess: true
299
+ };
300
+ if (specifier.startsWith("/")) return {
301
+ id: allowAbsolute ? normalizeModuleId(specifier) : resolveRelativeModuleId(specifier, modulePath),
302
+ shouldProcess: true
303
+ };
304
+ const aliasResolved = resolveAppAlias(specifier);
305
+ if (aliasResolved) return {
306
+ id: normalizeModuleId(aliasResolved),
307
+ shouldProcess: true
308
+ };
309
+ if (specifier.startsWith("@") || isBareModuleSpecifier(specifier)) {
310
+ const npmModuleId = resolveNpmModuleId(specifier, modulePath);
311
+ return {
312
+ id: npmModuleId || specifier,
313
+ shouldProcess: Boolean(npmModuleId)
314
+ };
315
+ }
316
+ return {
317
+ id: specifier,
318
+ shouldProcess: false
319
+ };
320
+ }
321
+ function isBareModuleSpecifier(specifier) {
322
+ return !specifier.startsWith(".") && !specifier.startsWith("/");
323
+ }
324
+ function resolveRelativeModuleId(specifier, modulePath) {
325
+ const relativeId = resolve(modulePath, `../${specifier}`).split(`${getWorkPath()}${sep}`)[1];
326
+ return normalizeModuleId(relativeId);
327
+ }
328
+ function normalizeModuleId(moduleId) {
329
+ let normalized = moduleId.replace(/\.(js|ts)$/, "").replace(/\\/g, "/");
330
+ if (!normalized.startsWith("/")) normalized = `/${normalized}`;
331
+ return normalized;
332
+ }
333
+ function resolveNpmModuleId(specifier, modulePath) {
334
+ const npmResolver = getNpmResolver();
335
+ if (!npmResolver) return null;
336
+ return npmResolver.resolveScriptModule(specifier, modulePath, resolveModuleIdToExistingPath);
337
+ }
338
+ function resolveModuleIdToExistingPath(moduleId) {
339
+ const normalizedModuleId = normalizeModuleId(moduleId);
340
+ const workPath = getWorkPath();
341
+ for (const ext of [".js", ".ts"]) if (fs.existsSync(`${workPath}${normalizedModuleId}${ext}`)) return normalizedModuleId;
342
+ for (const ext of [".js", ".ts"]) if (fs.existsSync(`${workPath}${normalizedModuleId}/index${ext}`)) return `${normalizedModuleId}/index`;
343
+ const packageJsonPath = `${workPath}${normalizedModuleId}/package.json`;
344
+ if (fs.existsSync(packageJsonPath)) try {
345
+ const packageInfo = JSON.parse(fs.readFileSync(packageJsonPath, "utf-8"));
346
+ for (const entryField of ["miniprogram", "main"]) if (typeof packageInfo[entryField] === "string" && packageInfo[entryField]) {
347
+ const resolvedEntry = resolveModuleIdToExistingPath(normalizeModuleId(resolve(normalizedModuleId, packageInfo[entryField])));
348
+ if (resolvedEntry) return resolvedEntry;
349
+ }
350
+ } catch (error) {
351
+ console.warn("[logic]", `解析 package.json 失败: ${packageJsonPath}`, error.message);
352
+ }
353
+ return null;
367
354
  }
368
- export {
369
- buildJSByPath,
370
- compileJS
371
- };
355
+ //#endregion
356
+ export { buildJSByPath, compileJS };