@dimina/compiler 1.0.12-beta.9 → 1.0.13

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,276 +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-COaZNCzL.js";
2
2
  import { resolve, sep } from "node:path";
3
3
  import { isMainThread, parentPort } from "node:worker_threads";
4
- import babel from "@babel/core";
5
- import _traverse from "@babel/traverse";
6
- import types from "@babel/types";
4
+ import fs from "node:fs";
7
5
  import { transform } from "esbuild";
6
+ import { parseSync } from "oxc-parser";
7
+ import { walk } from "oxc-walker";
8
+ import { transformSync } from "oxc-transform";
9
+ import MagicString from "magic-string";
8
10
  import ts from "typescript";
9
- import transformModulesCommonjs from "@babel/plugin-transform-modules-commonjs";
10
- import { r as resetStoreInfo, g as getTargetPath, i as hasCompileInfo, b as getContentByPath, j as getAppConfigInfo, a as getComponent, d as getWorkPath } from "../env-Csj3AHY4.js";
11
- const traverse = _traverse.default ? _traverse.default : _traverse;
12
- const BABEL_TRANSFORM_CONFIG = {
13
- comments: false,
14
- configFile: false,
15
- babelrc: false,
16
- plugins: [
17
- // 将 ES6 import/export 转换为 CommonJS
18
- transformModulesCommonjs
19
- ]
20
- };
21
- const processedModules = /* @__PURE__ */ new Set();
22
- if (!isMainThread) {
23
- parentPort.on("message", async ({ pages, storeInfo }) => {
24
- try {
25
- resetStoreInfo(storeInfo);
26
- const progress = {
27
- _completedTasks: 0,
28
- get completedTasks() {
29
- return this._completedTasks;
30
- },
31
- set completedTasks(value) {
32
- this._completedTasks = value;
33
- parentPort.postMessage({ completedTasks: this.completedTasks });
34
- }
35
- };
36
- const mainCompileRes = await compileJS(pages.mainPages, null, null, progress);
37
- for (const [root, subPages] of Object.entries(pages.subPages)) {
38
- try {
39
- const subCompileRes = await compileJS(
40
- subPages.info,
41
- root,
42
- subPages.independent ? [] : mainCompileRes,
43
- progress
44
- );
45
- await writeCompileRes(subCompileRes, root);
46
- } catch (error) {
47
- throw new Error(`Error processing subpackage ${root}: ${error.message}
48
- ${error.stack}`);
49
- }
50
- }
51
- await writeCompileRes(mainCompileRes, null);
52
- processedModules.clear();
53
- parentPort.postMessage({ success: true });
54
- } catch (error) {
55
- processedModules.clear();
56
- parentPort.postMessage({
57
- success: false,
58
- error: {
59
- message: error.message,
60
- stack: error.stack,
61
- name: error.name
62
- }
63
- });
64
- }
65
- });
66
- }
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
+ });
67
47
  async function writeCompileRes(compileRes, root) {
68
- let mergeCode = "";
69
- for (const module of compileRes) {
70
- 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) {
71
51
  ${module.code}
72
- });`;
73
- const { code: minifiedCode } = await transform(amdFormat, {
74
- minify: true,
75
- target: ["es2023"],
76
- // quickjs 支持版本
77
- platform: "neutral"
78
- });
79
- mergeCode += minifiedCode;
80
- }
81
- if (root) {
82
- const subDir = `${getTargetPath()}/${root}`;
83
- if (!fs.existsSync(subDir)) {
84
- fs.mkdirSync(subDir, { recursive: true });
85
- }
86
- fs.writeFileSync(`${subDir}/logic.js`, mergeCode);
87
- } else {
88
- const mainDir = `${getTargetPath()}/main`;
89
- if (!fs.existsSync(mainDir)) {
90
- fs.mkdirSync(mainDir, { recursive: true });
91
- }
92
- fs.writeFileSync(`${mainDir}/logic.js`, mergeCode);
93
- }
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
+ }
94
68
  }
69
+ /**
70
+ * 编译 js 文件
71
+ */
95
72
  async function compileJS(pages, root, mainCompileRes, progress) {
96
- const compileRes = [];
97
- if (!root) {
98
- buildJSByPath(root, { path: "app" }, compileRes, mainCompileRes, false);
99
- }
100
- pages.forEach((page) => {
101
- buildJSByPath(root, page, compileRes, mainCompileRes, true);
102
- progress.completedTasks++;
103
- });
104
- 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;
105
80
  }
106
- function buildJSByPath(packageName, module, compileRes, mainCompileRes, addExtra, depthChain = [], putMain = false) {
107
- const currentPath = module.path;
108
- if (depthChain.includes(currentPath)) {
109
- console.warn("[logic]", `检测到循环依赖: ${[...depthChain, currentPath].join(" -> ")}`);
110
- return;
111
- }
112
- if (depthChain.length > 20) {
113
- console.warn("[logic]", `检测到深度依赖: ${[...depthChain, currentPath].join(" -> ")}`);
114
- return;
115
- }
116
- depthChain = [...depthChain, currentPath];
117
- if (!module.path) {
118
- return;
119
- }
120
- if (hasCompileInfo(module.path, compileRes, mainCompileRes)) {
121
- return;
122
- }
123
- const compileInfo = {
124
- path: module.path,
125
- code: ""
126
- };
127
- const src = module.path.startsWith("/") ? module.path : `/${module.path}`;
128
- const modulePath = getJSAbsolutePath(src);
129
- if (!modulePath) {
130
- console.warn("[logic]", `找不到模块文件: ${src}`);
131
- return;
132
- }
133
- const sourceCode = getContentByPath(modulePath);
134
- if (!sourceCode) {
135
- console.warn("[logic]", `无法读取模块文件: ${modulePath}`);
136
- return;
137
- }
138
- let jsCode = sourceCode;
139
- if (modulePath.endsWith(".ts")) {
140
- try {
141
- const result = ts.transpileModule(sourceCode, {
142
- compilerOptions: {
143
- target: ts.ScriptTarget.ES2020,
144
- module: ts.ModuleKind.CommonJS,
145
- strict: false,
146
- esModuleInterop: true,
147
- skipLibCheck: true
148
- }
149
- });
150
- jsCode = result.outputText;
151
- } catch (error) {
152
- console.error(`[logic] TypeScript 编译失败 ${modulePath}:`, error.message);
153
- jsCode = sourceCode;
154
- }
155
- }
156
- const ast = babel.parseSync(jsCode);
157
- const addedArgs = types.objectExpression([
158
- types.objectProperty(types.identifier("path"), types.stringLiteral(module.path))
159
- ]);
160
- if (module.component) {
161
- const component = types.objectProperty(types.identifier("component"), types.booleanLiteral(true));
162
- addedArgs.properties.push(component);
163
- }
164
- if (module.usingComponents) {
165
- const components = types.objectProperty(types.identifier("usingComponents"), types.objectExpression([]));
166
- const allSubPackages = getAppConfigInfo().subPackages;
167
- for (const [name, path] of Object.entries(module.usingComponents)) {
168
- let toMainSubPackage = true;
169
- if (packageName) {
170
- const normalizedPath = path.startsWith("/") ? path.substring(1) : path;
171
- for (const subPackage of allSubPackages) {
172
- if (normalizedPath.startsWith(`${subPackage.root}/`)) {
173
- toMainSubPackage = false;
174
- break;
175
- }
176
- }
177
- } else {
178
- toMainSubPackage = false;
179
- }
180
- const componentModule = getComponent(path);
181
- if (!componentModule) {
182
- continue;
183
- }
184
- buildJSByPath(packageName, componentModule, compileRes, mainCompileRes, true, depthChain, toMainSubPackage);
185
- const props = types.objectProperty(types.identifier(`'${name}'`), types.stringLiteral(path));
186
- components.value.properties.push(props);
187
- }
188
- addedArgs.properties.push(components);
189
- }
190
- if (addExtra) {
191
- ast.program.body.splice(0, 0, getExtraInfoStatement("this", addedArgs));
192
- }
193
- if (putMain) {
194
- mainCompileRes.push(compileInfo);
195
- } else {
196
- compileRes.push(compileInfo);
197
- }
198
- traverse(ast, {
199
- CallExpression(ap) {
200
- if (ap.node.callee.name === "require" || ap.node.callee.object?.name === "require") {
201
- const requirePath = ap.node.arguments[0].value;
202
- if (requirePath) {
203
- const requireFullPath = resolve(modulePath, `../${requirePath}`);
204
- let id = requireFullPath.split(`${getWorkPath()}${sep}`)[1];
205
- id = id.replace(/\.(js|ts)$/, "").replace(/\\/g, "/");
206
- if (!id.startsWith("/")) {
207
- id = "/" + id;
208
- }
209
- ap.node.arguments[0] = types.stringLiteral(id);
210
- if (!processedModules.has(packageName + id)) {
211
- buildJSByPath(packageName, { path: id }, compileRes, mainCompileRes, false, depthChain);
212
- }
213
- }
214
- }
215
- },
216
- ImportDeclaration(ap) {
217
- const importPath = ap.node.source.value;
218
- if (importPath) {
219
- let id;
220
- let shouldProcess = false;
221
- if (importPath.startsWith("@") || importPath.startsWith("miniprogram_npm/")) {
222
- if (importPath.startsWith("@")) {
223
- id = `/miniprogram_npm/${importPath}`;
224
- } else {
225
- id = importPath.startsWith("/") ? importPath : `/${importPath}`;
226
- }
227
- shouldProcess = true;
228
- } else if (importPath.startsWith("./") || importPath.startsWith("../") || !importPath.startsWith("/")) {
229
- const importFullPath = resolve(modulePath, `../${importPath}`);
230
- id = importFullPath.split(`${getWorkPath()}${sep}`)[1];
231
- id = id.replace(/\.(js|ts)$/, "").replace(/\\/g, "/");
232
- if (!id.startsWith("/")) {
233
- id = "/" + id;
234
- }
235
- shouldProcess = true;
236
- } else {
237
- id = importPath;
238
- shouldProcess = true;
239
- }
240
- if (shouldProcess) {
241
- ap.node.source = types.stringLiteral(id);
242
- if (!processedModules.has(packageName + id)) {
243
- buildJSByPath(packageName, { path: id }, compileRes, mainCompileRes, false, depthChain);
244
- }
245
- }
246
- }
247
- }
248
- });
249
- const { code } = babel.transformFromAstSync(ast, "", BABEL_TRANSFORM_CONFIG);
250
- compileInfo.code = code;
251
- processedModules.add(packageName + currentPath);
81
+ async function buildJSByPath(packageName, module, compileRes, mainCompileRes, addExtra, depthChain = [], putMain = false) {
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);
252
265
  }
253
- function getExtraInfoStatement(type, addedArgs) {
254
- const propertyAssignment = types.objectProperty(types.identifier("__extraInfo"), addedArgs);
255
- const assignmentExpression = types.assignmentExpression(
256
- "=",
257
- types.memberExpression(types.identifier("globalThis"), propertyAssignment.key),
258
- propertyAssignment.value
259
- );
260
- return types.expressionStatement(assignmentExpression);
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);
261
268
  }
269
+ /**
270
+ * 获取 JavaScript 或 TypeScript 文件的绝对路径
271
+ * @param {string} modulePath - 模块路径
272
+ * @returns {string|null} - 文件的绝对路径,如果找不到则返回 null
273
+ */
262
274
  function getJSAbsolutePath(modulePath) {
263
- const workPath = getWorkPath();
264
- const fileTypes = [".js", ".ts"];
265
- for (const ext of fileTypes) {
266
- const fullPath = `${workPath}${modulePath}${ext}`;
267
- if (fs.existsSync(fullPath)) {
268
- return fullPath;
269
- }
270
- }
271
- 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;
272
354
  }
273
- export {
274
- buildJSByPath,
275
- compileJS
276
- };
355
+ //#endregion
356
+ export { buildJSByPath, compileJS };