@dimina/compiler 1.0.14-beta.0 → 1.0.14

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,22 +1,106 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
2
  const require_env = require("../env-M-7lpbHL.cjs");
3
+ const require_compatibility = require("../compatibility-DCnJNS-s.cjs");
3
4
  let node_path = require("node:path");
4
5
  let node_worker_threads = require("node:worker_threads");
5
6
  let node_fs = require("node:fs");
6
7
  node_fs = require_env.__toESM(node_fs, 1);
7
- let esbuild = require("esbuild");
8
8
  let oxc_parser = require("oxc-parser");
9
9
  let oxc_walker = require("oxc-walker");
10
- let oxc_transform = require("oxc-transform");
11
10
  let magic_string = require("magic-string");
12
11
  magic_string = require_env.__toESM(magic_string, 1);
13
- let typescript = require("typescript");
14
- typescript = require_env.__toESM(typescript, 1);
12
+ let esbuild = require("esbuild");
13
+ let source_map_js = require("source-map-js");
14
+ //#region src/core/sourcemap.js
15
+ function wrapModDefine(module) {
16
+ const code = module.code.endsWith("\n") ? module.code : module.code + "\n";
17
+ const extraLine = module.extraInfoCode || "";
18
+ return {
19
+ header: `modDefine('${module.path}', function(require, module, exports) {\n${extraLine}`,
20
+ code,
21
+ footer: "});\n"
22
+ };
23
+ }
24
+ function mergeSourcemap(compileRes) {
25
+ const smg = new source_map_js.SourceMapGenerator({ file: "logic.js" });
26
+ let bundleCode = "";
27
+ let lineOffset = 0;
28
+ for (const module of compileRes) {
29
+ const { header, code, footer } = wrapModDefine(module);
30
+ bundleCode += header;
31
+ const headerLineCount = header.split("\n").length - 1;
32
+ lineOffset += headerLineCount;
33
+ if (module.map) {
34
+ const moduleMap = JSON.parse(module.map);
35
+ new source_map_js.SourceMapConsumer(moduleMap).eachMapping((mapping) => {
36
+ if (mapping.source == null) return;
37
+ smg.addMapping({
38
+ generated: {
39
+ line: mapping.generatedLine + lineOffset,
40
+ column: mapping.generatedColumn
41
+ },
42
+ original: {
43
+ line: mapping.originalLine,
44
+ column: mapping.originalColumn
45
+ },
46
+ source: mapping.source,
47
+ name: mapping.name
48
+ });
49
+ });
50
+ if (moduleMap.sourcesContent) moduleMap.sources.forEach((src, i) => {
51
+ smg.setSourceContent(src, moduleMap.sourcesContent[i]);
52
+ });
53
+ }
54
+ bundleCode += code;
55
+ lineOffset += code.split("\n").length - 1;
56
+ bundleCode += footer;
57
+ lineOffset += footer.split("\n").length - 1;
58
+ }
59
+ return {
60
+ bundleCode,
61
+ sourcemap: smg.toString()
62
+ };
63
+ }
64
+ function remapSourcemap(nextMap, prevMap) {
65
+ if (!nextMap) return prevMap;
66
+ if (!prevMap) return nextMap;
67
+ const nextMapObj = typeof nextMap === "string" ? JSON.parse(nextMap) : nextMap;
68
+ const prevMapObj = typeof prevMap === "string" ? JSON.parse(prevMap) : prevMap;
69
+ const smg = new source_map_js.SourceMapGenerator({ file: nextMapObj.file || prevMapObj.file || "" });
70
+ const prevSmc = new source_map_js.SourceMapConsumer(prevMapObj);
71
+ new source_map_js.SourceMapConsumer(nextMapObj).eachMapping((mapping) => {
72
+ if (mapping.source == null || mapping.originalLine == null || mapping.originalColumn == null) return;
73
+ const original = prevSmc.originalPositionFor({
74
+ line: mapping.originalLine,
75
+ column: mapping.originalColumn
76
+ });
77
+ if (original.source == null || original.line == null || original.column == null) return;
78
+ smg.addMapping({
79
+ generated: {
80
+ line: mapping.generatedLine,
81
+ column: mapping.generatedColumn
82
+ },
83
+ original: {
84
+ line: original.line,
85
+ column: original.column
86
+ },
87
+ source: original.source,
88
+ name: original.name || mapping.name
89
+ });
90
+ });
91
+ if (prevMapObj.sourcesContent) prevMapObj.sources.forEach((src, i) => {
92
+ smg.setSourceContent(src, prevMapObj.sourcesContent[i]);
93
+ });
94
+ return smg.toString();
95
+ }
96
+ //#endregion
15
97
  //#region src/core/logic-compiler.js
16
98
  var processedModules = /* @__PURE__ */ new Set();
17
- if (!node_worker_threads.isMainThread) node_worker_threads.parentPort.on("message", async ({ pages, storeInfo }) => {
99
+ var enableSourcemap = false;
100
+ if (!node_worker_threads.isMainThread) node_worker_threads.parentPort.on("message", async ({ pages, storeInfo, sourcemap }) => {
18
101
  try {
19
102
  require_env.resetStoreInfo(storeInfo);
103
+ enableSourcemap = !!sourcemap;
20
104
  const progress = {
21
105
  _completedTasks: 0,
22
106
  get completedTasks() {
@@ -49,25 +133,26 @@ if (!node_worker_threads.isMainThread) node_worker_threads.parentPort.on("messag
49
133
  }
50
134
  });
51
135
  async function writeCompileRes(compileRes, root) {
52
- let mergeCode = "";
53
- for (const module of compileRes) {
54
- const { code: minifiedCode } = await (0, esbuild.transform)(`modDefine('${module.path}', function(require, module, exports) {
136
+ const outputDir = root ? `${require_env.getTargetPath()}/${root}` : `${require_env.getTargetPath()}/main`;
137
+ if (!node_fs.default.existsSync(outputDir)) node_fs.default.mkdirSync(outputDir, { recursive: true });
138
+ if (enableSourcemap) {
139
+ const { bundleCode, sourcemap } = mergeSourcemap(compileRes);
140
+ const sourcemapFileName = "logic.js.map";
141
+ node_fs.default.writeFileSync(`${outputDir}/logic.js`, `${bundleCode}//# sourceMappingURL=${sourcemapFileName}\n`);
142
+ node_fs.default.writeFileSync(`${outputDir}/${sourcemapFileName}`, sourcemap);
143
+ } else {
144
+ let mergeCode = "";
145
+ for (const module of compileRes) {
146
+ const { code: minifiedCode } = await (0, esbuild.transform)(`modDefine('${module.path}', function(require, module, exports) {
55
147
  ${module.code}
56
148
  });`, {
57
- minify: true,
58
- target: ["es2023"],
59
- platform: "neutral"
60
- });
61
- mergeCode += minifiedCode;
62
- }
63
- if (root) {
64
- const subDir = `${require_env.getTargetPath()}/${root}`;
65
- if (!node_fs.default.existsSync(subDir)) node_fs.default.mkdirSync(subDir, { recursive: true });
66
- node_fs.default.writeFileSync(`${subDir}/logic.js`, mergeCode);
67
- } else {
68
- const mainDir = `${require_env.getTargetPath()}/main`;
69
- if (!node_fs.default.existsSync(mainDir)) node_fs.default.mkdirSync(mainDir, { recursive: true });
70
- node_fs.default.writeFileSync(`${mainDir}/logic.js`, mergeCode);
149
+ minify: true,
150
+ target: ["es2023"],
151
+ platform: "neutral"
152
+ });
153
+ mergeCode += minifiedCode;
154
+ }
155
+ node_fs.default.writeFileSync(`${outputDir}/logic.js`, mergeCode);
71
156
  }
72
157
  }
73
158
  /**
@@ -97,7 +182,8 @@ async function buildJSByPath(packageName, module, compileRes, mainCompileRes, ad
97
182
  if (require_env.hasCompileInfo(module.path, compileRes, mainCompileRes)) return;
98
183
  const compileInfo = {
99
184
  path: module.path,
100
- code: ""
185
+ code: "",
186
+ sourceFile: null
101
187
  };
102
188
  const src = module.path.startsWith("/") ? module.path : `/${module.path}`;
103
189
  const modulePath = getJSAbsolutePath(src);
@@ -105,29 +191,22 @@ async function buildJSByPath(packageName, module, compileRes, mainCompileRes, ad
105
191
  console.warn("[logic]", `找不到模块文件: ${src}`);
106
192
  return;
107
193
  }
194
+ const diagnosticSource = modulePath.startsWith(require_env.getWorkPath()) ? modulePath.slice(require_env.getWorkPath().length) : src;
108
195
  const sourceCode = require_env.getContentByPath(modulePath);
109
196
  if (!sourceCode) {
110
197
  console.warn("[logic]", `无法读取模块文件: ${modulePath}`);
111
198
  return;
112
199
  }
113
- let jsCode = sourceCode;
114
- if (modulePath.endsWith(".ts")) try {
115
- jsCode = typescript.default.transpileModule(sourceCode, { compilerOptions: {
116
- target: typescript.default.ScriptTarget.ES2020,
117
- module: typescript.default.ModuleKind.ESNext,
118
- strict: false,
119
- esModuleInterop: true,
120
- skipLibCheck: true
121
- } }).outputText;
122
- } catch (error) {
123
- console.error(`[logic] TypeScript 编译失败 ${modulePath}:`, error.message);
124
- jsCode = sourceCode;
200
+ const isTypeScript = modulePath.endsWith(".ts");
201
+ if (enableSourcemap) {
202
+ const workPath = require_env.getWorkPath();
203
+ compileInfo.sourceFile = modulePath.startsWith(workPath) ? modulePath.slice(workPath.length) : src;
125
204
  }
126
- const ast = (0, oxc_parser.parseSync)(modulePath, jsCode, {
205
+ const ast = (0, oxc_parser.parseSync)(modulePath, sourceCode, {
127
206
  sourceType: "module",
128
- lang: modulePath.endsWith(".ts") ? "ts" : "js"
207
+ lang: isTypeScript ? "ts" : "js"
129
208
  }).program;
130
- const s = new magic_string.default(jsCode);
209
+ const s = new magic_string.default(sourceCode);
131
210
  const extraInfo = { path: module.path };
132
211
  if (module.component) extraInfo.component = true;
133
212
  if (module.usingComponents) {
@@ -151,13 +230,16 @@ async function buildJSByPath(packageName, module, compileRes, mainCompileRes, ad
151
230
  }
152
231
  if (addExtra) {
153
232
  const extraInfoCode = `globalThis.__extraInfo = ${JSON.stringify(extraInfo)};\n`;
154
- s.prepend(extraInfoCode);
233
+ if (enableSourcemap) compileInfo.extraInfoCode = extraInfoCode;
234
+ else s.prepend(extraInfoCode);
155
235
  }
156
236
  if (putMain) mainCompileRes.push(compileInfo);
157
237
  else compileRes.push(compileInfo);
158
238
  const pathReplacements = [];
159
239
  const dependenciesToProcess = [];
160
240
  (0, oxc_walker.walk)(ast, { enter(node, parent) {
241
+ const wxMemberName = require_compatibility.getWxMemberName(node);
242
+ if (wxMemberName) require_compatibility.warnUnsupportedWxApi(wxMemberName, compileInfo.sourceFile || diagnosticSource, node.loc?.start?.line || getLineByIndex(sourceCode, node.start));
161
243
  if ((node.type === "StringLiteral" || node.type === "Literal") && isLocalAssetString(node.value)) pathReplacements.push({
162
244
  start: node.start,
163
245
  end: node.end,
@@ -196,6 +278,21 @@ async function buildJSByPath(packageName, module, compileRes, mainCompileRes, ad
196
278
  }
197
279
  }
198
280
  }
281
+ if (node.type === "TSImportEqualsDeclaration" && node.moduleReference?.type === "TSExternalModuleReference") {
282
+ const importPathNode = node.moduleReference.expression;
283
+ const importPath = importPathNode?.value;
284
+ if (importPath) {
285
+ const { id, shouldProcess } = resolveDependencyId(importPath, modulePath, false);
286
+ if (shouldProcess) {
287
+ pathReplacements.push({
288
+ start: importPathNode.start,
289
+ end: importPathNode.end,
290
+ newValue: id
291
+ });
292
+ if (!processedModules.has(packageName + id)) dependenciesToProcess.push(id);
293
+ }
294
+ }
295
+ }
199
296
  if ((node.type === "ExportAllDeclaration" || node.type === "ExportNamedDeclaration") && node.source) {
200
297
  const exportPath = node.source.value;
201
298
  if (exportPath) {
@@ -214,62 +311,49 @@ async function buildJSByPath(packageName, module, compileRes, mainCompileRes, ad
214
311
  for (const depId of dependenciesToProcess) await buildJSByPath(packageName, { path: depId }, compileRes, mainCompileRes, false, depthChain, putMain);
215
312
  for (const replacement of pathReplacements.reverse()) s.overwrite(replacement.start, replacement.end, `'${replacement.newValue}'`);
216
313
  const modifiedCode = s.toString();
217
- let transformedCode = modifiedCode;
218
- if (modulePath.endsWith(".ts") || modulePath.endsWith(".tsx")) try {
219
- transformedCode = (0, oxc_transform.transformSync)(modulePath, modifiedCode, {
220
- sourceType: "module",
221
- lang: modulePath.endsWith(".tsx") ? "tsx" : "ts",
222
- target: "es2020",
223
- typescript: { onlyRemoveTypeImports: true }
224
- }).code;
225
- } catch (error) {
226
- console.error(`[logic] oxc-transform 转换失败 ${modulePath}:`, error.message);
227
- transformedCode = modifiedCode;
314
+ let preEsbuildMap = null;
315
+ if (enableSourcemap && compileInfo.sourceFile) {
316
+ const generatedMap = JSON.parse(s.generateMap({
317
+ file: compileInfo.sourceFile,
318
+ source: compileInfo.sourceFile,
319
+ includeContent: true,
320
+ hires: true
321
+ }).toString());
322
+ generatedMap.file = compileInfo.sourceFile;
323
+ generatedMap.sources = [compileInfo.sourceFile];
324
+ generatedMap.sourcesContent = [sourceCode];
325
+ preEsbuildMap = JSON.stringify(generatedMap);
228
326
  }
229
327
  try {
230
- const esbuildCode = (await (0, esbuild.transform)(transformedCode, {
328
+ const esbuildOpts = {
231
329
  format: "cjs",
232
330
  target: "es2020",
233
331
  platform: "neutral",
234
- loader: "js"
235
- })).code;
236
- const esbuildAst = (0, oxc_parser.parseSync)(modulePath, esbuildCode, {
237
- sourceType: "module",
238
- lang: "js"
239
- });
240
- const postEsbuildReplacements = [];
241
- (0, oxc_walker.walk)(esbuildAst.program, { enter(node) {
242
- if (node.type === "CallExpression") {
243
- const isRequire = node.callee.type === "Identifier" && node.callee.name === "require";
244
- const isRequireProperty = node.callee.type === "MemberExpression" && node.callee.object?.type === "Identifier" && node.callee.object?.name === "require";
245
- if ((isRequire || isRequireProperty) && node.arguments.length > 0 && (node.arguments[0].type === "StringLiteral" || node.arguments[0].type === "Literal")) {
246
- const arg = node.arguments[0];
247
- const requirePath = arg.value;
248
- if (requirePath && (requirePath.startsWith("./") || requirePath.startsWith("../"))) {
249
- const { id } = resolveDependencyId(requirePath, modulePath, false);
250
- postEsbuildReplacements.push({
251
- start: arg.start,
252
- end: arg.end,
253
- newValue: id
254
- });
255
- }
256
- }
257
- }
258
- } });
259
- if (postEsbuildReplacements.length > 0) {
260
- const finalMagicString = new magic_string.default(esbuildCode);
261
- for (const replacement of postEsbuildReplacements.reverse()) finalMagicString.overwrite(replacement.start, replacement.end, `"${replacement.newValue}"`);
262
- compileInfo.code = finalMagicString.toString();
263
- } else compileInfo.code = esbuildCode;
332
+ loader: isTypeScript ? "ts" : "js"
333
+ };
334
+ if (enableSourcemap && compileInfo.sourceFile) {
335
+ esbuildOpts.sourcemap = true;
336
+ esbuildOpts.sourcefile = compileInfo.sourceFile;
337
+ esbuildOpts.sourcesContent = true;
338
+ }
339
+ const esbuildResult = await (0, esbuild.transform)(modifiedCode, esbuildOpts);
340
+ if (enableSourcemap && esbuildResult.map) compileInfo.map = preEsbuildMap ? remapSourcemap(esbuildResult.map, preEsbuildMap) : esbuildResult.map;
341
+ compileInfo.code = esbuildResult.code;
264
342
  } catch (error) {
265
343
  console.error(`[logic] esbuild 转换失败 ${modulePath}:`, error.message);
266
- compileInfo.code = transformedCode;
344
+ compileInfo.code = modifiedCode;
267
345
  }
268
346
  processedModules.add(packageName + currentPath);
269
347
  }
270
348
  function isLocalAssetString(value) {
271
349
  return typeof value === "string" && !value.startsWith("http") && !value.startsWith("//") && (value.startsWith("/") || value.startsWith("./") || value.startsWith("../")) && /\.(?:png|jpe?g|gif|svg)(?:\?.*)?$/.test(value);
272
350
  }
351
+ function getLineByIndex(content, index) {
352
+ if (typeof index !== "number" || index < 0) return null;
353
+ let line = 1;
354
+ for (let i = 0; i < index; i++) if (content.charCodeAt(i) === 10) line++;
355
+ return line;
356
+ }
273
357
  /**
274
358
  * 获取 JavaScript 或 TypeScript 文件的绝对路径
275
359
  * @param {string} modulePath - 模块路径
@@ -1,18 +1,103 @@
1
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
+ import { n as getWxMemberName, r as warnUnsupportedWxApi } from "../compatibility-B_5UilxZ.js";
2
3
  import { resolve, sep } from "node:path";
3
4
  import { isMainThread, parentPort } from "node:worker_threads";
4
5
  import fs from "node:fs";
5
- import { transform } from "esbuild";
6
6
  import { parseSync } from "oxc-parser";
7
7
  import { walk } from "oxc-walker";
8
- import { transformSync } from "oxc-transform";
9
8
  import MagicString from "magic-string";
10
- import ts from "typescript";
9
+ import { transform } from "esbuild";
10
+ import { SourceMapConsumer, SourceMapGenerator } from "source-map-js";
11
+ //#region src/core/sourcemap.js
12
+ function wrapModDefine(module) {
13
+ const code = module.code.endsWith("\n") ? module.code : module.code + "\n";
14
+ const extraLine = module.extraInfoCode || "";
15
+ return {
16
+ header: `modDefine('${module.path}', function(require, module, exports) {\n${extraLine}`,
17
+ code,
18
+ footer: "});\n"
19
+ };
20
+ }
21
+ function mergeSourcemap(compileRes) {
22
+ const smg = new SourceMapGenerator({ file: "logic.js" });
23
+ let bundleCode = "";
24
+ let lineOffset = 0;
25
+ for (const module of compileRes) {
26
+ const { header, code, footer } = wrapModDefine(module);
27
+ bundleCode += header;
28
+ const headerLineCount = header.split("\n").length - 1;
29
+ lineOffset += headerLineCount;
30
+ if (module.map) {
31
+ const moduleMap = JSON.parse(module.map);
32
+ new SourceMapConsumer(moduleMap).eachMapping((mapping) => {
33
+ if (mapping.source == null) return;
34
+ smg.addMapping({
35
+ generated: {
36
+ line: mapping.generatedLine + lineOffset,
37
+ column: mapping.generatedColumn
38
+ },
39
+ original: {
40
+ line: mapping.originalLine,
41
+ column: mapping.originalColumn
42
+ },
43
+ source: mapping.source,
44
+ name: mapping.name
45
+ });
46
+ });
47
+ if (moduleMap.sourcesContent) moduleMap.sources.forEach((src, i) => {
48
+ smg.setSourceContent(src, moduleMap.sourcesContent[i]);
49
+ });
50
+ }
51
+ bundleCode += code;
52
+ lineOffset += code.split("\n").length - 1;
53
+ bundleCode += footer;
54
+ lineOffset += footer.split("\n").length - 1;
55
+ }
56
+ return {
57
+ bundleCode,
58
+ sourcemap: smg.toString()
59
+ };
60
+ }
61
+ function remapSourcemap(nextMap, prevMap) {
62
+ if (!nextMap) return prevMap;
63
+ if (!prevMap) return nextMap;
64
+ const nextMapObj = typeof nextMap === "string" ? JSON.parse(nextMap) : nextMap;
65
+ const prevMapObj = typeof prevMap === "string" ? JSON.parse(prevMap) : prevMap;
66
+ const smg = new SourceMapGenerator({ file: nextMapObj.file || prevMapObj.file || "" });
67
+ const prevSmc = new SourceMapConsumer(prevMapObj);
68
+ new SourceMapConsumer(nextMapObj).eachMapping((mapping) => {
69
+ if (mapping.source == null || mapping.originalLine == null || mapping.originalColumn == null) return;
70
+ const original = prevSmc.originalPositionFor({
71
+ line: mapping.originalLine,
72
+ column: mapping.originalColumn
73
+ });
74
+ if (original.source == null || original.line == null || original.column == null) return;
75
+ smg.addMapping({
76
+ generated: {
77
+ line: mapping.generatedLine,
78
+ column: mapping.generatedColumn
79
+ },
80
+ original: {
81
+ line: original.line,
82
+ column: original.column
83
+ },
84
+ source: original.source,
85
+ name: original.name || mapping.name
86
+ });
87
+ });
88
+ if (prevMapObj.sourcesContent) prevMapObj.sources.forEach((src, i) => {
89
+ smg.setSourceContent(src, prevMapObj.sourcesContent[i]);
90
+ });
91
+ return smg.toString();
92
+ }
93
+ //#endregion
11
94
  //#region src/core/logic-compiler.js
12
95
  var processedModules = /* @__PURE__ */ new Set();
13
- if (!isMainThread) parentPort.on("message", async ({ pages, storeInfo }) => {
96
+ var enableSourcemap = false;
97
+ if (!isMainThread) parentPort.on("message", async ({ pages, storeInfo, sourcemap }) => {
14
98
  try {
15
99
  resetStoreInfo(storeInfo);
100
+ enableSourcemap = !!sourcemap;
16
101
  const progress = {
17
102
  _completedTasks: 0,
18
103
  get completedTasks() {
@@ -45,25 +130,26 @@ if (!isMainThread) parentPort.on("message", async ({ pages, storeInfo }) => {
45
130
  }
46
131
  });
47
132
  async function writeCompileRes(compileRes, root) {
48
- let mergeCode = "";
49
- for (const module of compileRes) {
50
- const { code: minifiedCode } = await transform(`modDefine('${module.path}', function(require, module, exports) {
133
+ const outputDir = root ? `${getTargetPath()}/${root}` : `${getTargetPath()}/main`;
134
+ if (!fs.existsSync(outputDir)) fs.mkdirSync(outputDir, { recursive: true });
135
+ if (enableSourcemap) {
136
+ const { bundleCode, sourcemap } = mergeSourcemap(compileRes);
137
+ const sourcemapFileName = "logic.js.map";
138
+ fs.writeFileSync(`${outputDir}/logic.js`, `${bundleCode}//# sourceMappingURL=${sourcemapFileName}\n`);
139
+ fs.writeFileSync(`${outputDir}/${sourcemapFileName}`, sourcemap);
140
+ } else {
141
+ let mergeCode = "";
142
+ for (const module of compileRes) {
143
+ const { code: minifiedCode } = await transform(`modDefine('${module.path}', function(require, module, exports) {
51
144
  ${module.code}
52
145
  });`, {
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);
146
+ minify: true,
147
+ target: ["es2023"],
148
+ platform: "neutral"
149
+ });
150
+ mergeCode += minifiedCode;
151
+ }
152
+ fs.writeFileSync(`${outputDir}/logic.js`, mergeCode);
67
153
  }
68
154
  }
69
155
  /**
@@ -93,7 +179,8 @@ async function buildJSByPath(packageName, module, compileRes, mainCompileRes, ad
93
179
  if (hasCompileInfo(module.path, compileRes, mainCompileRes)) return;
94
180
  const compileInfo = {
95
181
  path: module.path,
96
- code: ""
182
+ code: "",
183
+ sourceFile: null
97
184
  };
98
185
  const src = module.path.startsWith("/") ? module.path : `/${module.path}`;
99
186
  const modulePath = getJSAbsolutePath(src);
@@ -101,29 +188,22 @@ async function buildJSByPath(packageName, module, compileRes, mainCompileRes, ad
101
188
  console.warn("[logic]", `找不到模块文件: ${src}`);
102
189
  return;
103
190
  }
191
+ const diagnosticSource = modulePath.startsWith(getWorkPath()) ? modulePath.slice(getWorkPath().length) : src;
104
192
  const sourceCode = getContentByPath(modulePath);
105
193
  if (!sourceCode) {
106
194
  console.warn("[logic]", `无法读取模块文件: ${modulePath}`);
107
195
  return;
108
196
  }
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;
197
+ const isTypeScript = modulePath.endsWith(".ts");
198
+ if (enableSourcemap) {
199
+ const workPath = getWorkPath();
200
+ compileInfo.sourceFile = modulePath.startsWith(workPath) ? modulePath.slice(workPath.length) : src;
121
201
  }
122
- const ast = parseSync(modulePath, jsCode, {
202
+ const ast = parseSync(modulePath, sourceCode, {
123
203
  sourceType: "module",
124
- lang: modulePath.endsWith(".ts") ? "ts" : "js"
204
+ lang: isTypeScript ? "ts" : "js"
125
205
  }).program;
126
- const s = new MagicString(jsCode);
206
+ const s = new MagicString(sourceCode);
127
207
  const extraInfo = { path: module.path };
128
208
  if (module.component) extraInfo.component = true;
129
209
  if (module.usingComponents) {
@@ -147,13 +227,16 @@ async function buildJSByPath(packageName, module, compileRes, mainCompileRes, ad
147
227
  }
148
228
  if (addExtra) {
149
229
  const extraInfoCode = `globalThis.__extraInfo = ${JSON.stringify(extraInfo)};\n`;
150
- s.prepend(extraInfoCode);
230
+ if (enableSourcemap) compileInfo.extraInfoCode = extraInfoCode;
231
+ else s.prepend(extraInfoCode);
151
232
  }
152
233
  if (putMain) mainCompileRes.push(compileInfo);
153
234
  else compileRes.push(compileInfo);
154
235
  const pathReplacements = [];
155
236
  const dependenciesToProcess = [];
156
237
  walk(ast, { enter(node, parent) {
238
+ const wxMemberName = getWxMemberName(node);
239
+ if (wxMemberName) warnUnsupportedWxApi(wxMemberName, compileInfo.sourceFile || diagnosticSource, node.loc?.start?.line || getLineByIndex(sourceCode, node.start));
157
240
  if ((node.type === "StringLiteral" || node.type === "Literal") && isLocalAssetString(node.value)) pathReplacements.push({
158
241
  start: node.start,
159
242
  end: node.end,
@@ -192,6 +275,21 @@ async function buildJSByPath(packageName, module, compileRes, mainCompileRes, ad
192
275
  }
193
276
  }
194
277
  }
278
+ if (node.type === "TSImportEqualsDeclaration" && node.moduleReference?.type === "TSExternalModuleReference") {
279
+ const importPathNode = node.moduleReference.expression;
280
+ const importPath = importPathNode?.value;
281
+ if (importPath) {
282
+ const { id, shouldProcess } = resolveDependencyId(importPath, modulePath, false);
283
+ if (shouldProcess) {
284
+ pathReplacements.push({
285
+ start: importPathNode.start,
286
+ end: importPathNode.end,
287
+ newValue: id
288
+ });
289
+ if (!processedModules.has(packageName + id)) dependenciesToProcess.push(id);
290
+ }
291
+ }
292
+ }
195
293
  if ((node.type === "ExportAllDeclaration" || node.type === "ExportNamedDeclaration") && node.source) {
196
294
  const exportPath = node.source.value;
197
295
  if (exportPath) {
@@ -210,62 +308,49 @@ async function buildJSByPath(packageName, module, compileRes, mainCompileRes, ad
210
308
  for (const depId of dependenciesToProcess) await buildJSByPath(packageName, { path: depId }, compileRes, mainCompileRes, false, depthChain, putMain);
211
309
  for (const replacement of pathReplacements.reverse()) s.overwrite(replacement.start, replacement.end, `'${replacement.newValue}'`);
212
310
  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;
311
+ let preEsbuildMap = null;
312
+ if (enableSourcemap && compileInfo.sourceFile) {
313
+ const generatedMap = JSON.parse(s.generateMap({
314
+ file: compileInfo.sourceFile,
315
+ source: compileInfo.sourceFile,
316
+ includeContent: true,
317
+ hires: true
318
+ }).toString());
319
+ generatedMap.file = compileInfo.sourceFile;
320
+ generatedMap.sources = [compileInfo.sourceFile];
321
+ generatedMap.sourcesContent = [sourceCode];
322
+ preEsbuildMap = JSON.stringify(generatedMap);
224
323
  }
225
324
  try {
226
- const esbuildCode = (await transform(transformedCode, {
325
+ const esbuildOpts = {
227
326
  format: "cjs",
228
327
  target: "es2020",
229
328
  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;
329
+ loader: isTypeScript ? "ts" : "js"
330
+ };
331
+ if (enableSourcemap && compileInfo.sourceFile) {
332
+ esbuildOpts.sourcemap = true;
333
+ esbuildOpts.sourcefile = compileInfo.sourceFile;
334
+ esbuildOpts.sourcesContent = true;
335
+ }
336
+ const esbuildResult = await transform(modifiedCode, esbuildOpts);
337
+ if (enableSourcemap && esbuildResult.map) compileInfo.map = preEsbuildMap ? remapSourcemap(esbuildResult.map, preEsbuildMap) : esbuildResult.map;
338
+ compileInfo.code = esbuildResult.code;
260
339
  } catch (error) {
261
340
  console.error(`[logic] esbuild 转换失败 ${modulePath}:`, error.message);
262
- compileInfo.code = transformedCode;
341
+ compileInfo.code = modifiedCode;
263
342
  }
264
343
  processedModules.add(packageName + currentPath);
265
344
  }
266
345
  function isLocalAssetString(value) {
267
346
  return typeof value === "string" && !value.startsWith("http") && !value.startsWith("//") && (value.startsWith("/") || value.startsWith("./") || value.startsWith("../")) && /\.(?:png|jpe?g|gif|svg)(?:\?.*)?$/.test(value);
268
347
  }
348
+ function getLineByIndex(content, index) {
349
+ if (typeof index !== "number" || index < 0) return null;
350
+ let line = 1;
351
+ for (let i = 0; i < index; i++) if (content.charCodeAt(i) === 10) line++;
352
+ return line;
353
+ }
269
354
  /**
270
355
  * 获取 JavaScript 或 TypeScript 文件的绝对路径
271
356
  * @param {string} modulePath - 模块路径