@dimina/compiler 1.0.14-beta.0 → 1.0.15

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
- const require_env = require("../env-M-7lpbHL.cjs");
2
+ const require_env = require("../env-Dmnqp9bD.cjs");
3
+ const require_compatibility = require("../compatibility-DlYbbw0F.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 - 模块路径
@@ -312,9 +396,14 @@ function resolveDependencyId(specifier, modulePath, allowAbsolute) {
312
396
  };
313
397
  if (specifier.startsWith("@") || isBareModuleSpecifier(specifier)) {
314
398
  const npmModuleId = resolveNpmModuleId(specifier, modulePath);
399
+ if (npmModuleId) return {
400
+ id: npmModuleId,
401
+ shouldProcess: true
402
+ };
403
+ const siblingModuleId = resolveBareSiblingModuleId(specifier, modulePath);
315
404
  return {
316
- id: npmModuleId || specifier,
317
- shouldProcess: Boolean(npmModuleId)
405
+ id: siblingModuleId || specifier,
406
+ shouldProcess: Boolean(siblingModuleId)
318
407
  };
319
408
  }
320
409
  return {
@@ -329,6 +418,9 @@ function resolveRelativeModuleId(specifier, modulePath) {
329
418
  const relativeId = (0, node_path.resolve)(modulePath, `../${specifier}`).split(`${require_env.getWorkPath()}${node_path.sep}`)[1];
330
419
  return normalizeModuleId(relativeId);
331
420
  }
421
+ function resolveBareSiblingModuleId(specifier, modulePath) {
422
+ return resolveModuleIdToExistingPath(resolveRelativeModuleId(`./${specifier}`, modulePath));
423
+ }
332
424
  function normalizeModuleId(moduleId) {
333
425
  let normalized = moduleId.replace(/\.(js|ts)$/, "").replace(/\\/g, "/");
334
426
  if (!normalized.startsWith("/")) normalized = `/${normalized}`;