@dimina/compiler 1.0.12-beta.1 → 1.0.12-beta.11

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.
@@ -5,7 +5,7 @@ const process = require("node:process");
5
5
  const chokidar = require("chokidar");
6
6
  const commander = require("commander");
7
7
  const index = require("../index.cjs");
8
- const version = "1.0.12-beta.0";
8
+ const version = "1.0.12-beta.11";
9
9
  const pack = {
10
10
  version
11
11
  };
package/dist/bin/index.js CHANGED
@@ -4,7 +4,7 @@ import process from "node:process";
4
4
  import chokidar from "chokidar";
5
5
  import { program } from "commander";
6
6
  import build from "../index.js";
7
- const version = "1.0.12-beta.0";
7
+ const version = "1.0.12-beta.11";
8
8
  const pack = {
9
9
  version
10
10
  };
@@ -3,14 +3,13 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
3
  const fs = require("node:fs");
4
4
  const path = require("node:path");
5
5
  const node_worker_threads = require("node:worker_threads");
6
- const babel = require("@babel/core");
7
- const _traverse = require("@babel/traverse");
8
- const types = require("@babel/types");
6
+ const oxcParser = require("oxc-parser");
7
+ const oxcWalker = require("oxc-walker");
8
+ const oxcTransform = require("oxc-transform");
9
+ const MagicString = require("magic-string");
9
10
  const esbuild = require("esbuild");
10
11
  const ts = require("typescript");
11
- const transformModulesCommonjs = require("@babel/plugin-transform-modules-commonjs");
12
12
  const env = require("../env-Cmen1qwy.cjs");
13
- const traverse = _traverse.default ? _traverse.default : _traverse;
14
13
  const processedModules = /* @__PURE__ */ new Set();
15
14
  if (!node_worker_threads.isMainThread) {
16
15
  node_worker_threads.parentPort.on("message", async ({ pages, storeInfo }) => {
@@ -42,8 +41,10 @@ ${error.stack}`);
42
41
  }
43
42
  }
44
43
  await writeCompileRes(mainCompileRes, null);
44
+ processedModules.clear();
45
45
  node_worker_threads.parentPort.postMessage({ success: true });
46
46
  } catch (error) {
47
+ processedModules.clear();
47
48
  node_worker_threads.parentPort.postMessage({
48
49
  success: false,
49
50
  error: {
@@ -86,26 +87,31 @@ ${module2.code}
86
87
  async function compileJS(pages, root, mainCompileRes, progress) {
87
88
  const compileRes = [];
88
89
  if (!root) {
89
- buildJSByPath(root, { path: "app" }, compileRes, mainCompileRes, false);
90
+ await buildJSByPath(root, { path: "app" }, compileRes, mainCompileRes, false);
90
91
  }
91
- pages.forEach((page) => {
92
- buildJSByPath(root, page, compileRes, mainCompileRes, true);
92
+ for (const page of pages) {
93
+ await buildJSByPath(root, page, compileRes, mainCompileRes, true);
93
94
  progress.completedTasks++;
94
- });
95
+ }
95
96
  return compileRes;
96
97
  }
97
- function buildJSByPath(packageName, module2, compileRes, mainCompileRes, addExtra, depthChain = [], putMain = false) {
98
- if (!module2.path) {
98
+ async function buildJSByPath(packageName, module2, compileRes, mainCompileRes, addExtra, depthChain = [], putMain = false) {
99
+ const currentPath = module2.path;
100
+ if (depthChain.includes(currentPath)) {
101
+ console.warn("[logic]", `检测到循环依赖: ${[...depthChain, currentPath].join(" -> ")}`);
99
102
  return;
100
103
  }
101
- const moduleKey = packageName + module2.path;
102
- if (processedModules.has(moduleKey)) {
104
+ if (depthChain.length > 20) {
105
+ console.warn("[logic]", `检测到深度依赖: ${[...depthChain, currentPath].join(" -> ")}`);
106
+ return;
107
+ }
108
+ depthChain = [...depthChain, currentPath];
109
+ if (!module2.path) {
103
110
  return;
104
111
  }
105
112
  if (env.hasCompileInfo(module2.path, compileRes, mainCompileRes)) {
106
113
  return;
107
114
  }
108
- processedModules.add(moduleKey);
109
115
  const compileInfo = {
110
116
  path: module2.path,
111
117
  code: ""
@@ -127,7 +133,8 @@ function buildJSByPath(packageName, module2, compileRes, mainCompileRes, addExtr
127
133
  const result = ts.transpileModule(sourceCode, {
128
134
  compilerOptions: {
129
135
  target: ts.ScriptTarget.ES2020,
130
- module: ts.ModuleKind.CommonJS,
136
+ module: ts.ModuleKind.ESNext,
137
+ // 保持 ES6 模块语法,让 oxc-transform 后续处理
131
138
  strict: false,
132
139
  esModuleInterop: true,
133
140
  skipLibCheck: true
@@ -139,16 +146,20 @@ function buildJSByPath(packageName, module2, compileRes, mainCompileRes, addExtr
139
146
  jsCode = sourceCode;
140
147
  }
141
148
  }
142
- const ast = babel.parseSync(jsCode);
143
- const addedArgs = types.objectExpression([
144
- types.objectProperty(types.identifier("path"), types.stringLiteral(module2.path))
145
- ]);
149
+ const parseResult = oxcParser.parseSync(modulePath, jsCode, {
150
+ sourceType: "module",
151
+ lang: modulePath.endsWith(".ts") ? "ts" : "js"
152
+ });
153
+ const ast = parseResult.program;
154
+ const s = new MagicString(jsCode);
155
+ const extraInfo = {
156
+ path: module2.path
157
+ };
146
158
  if (module2.component) {
147
- const component = types.objectProperty(types.identifier("component"), types.booleanLiteral(true));
148
- addedArgs.properties.push(component);
159
+ extraInfo.component = true;
149
160
  }
150
161
  if (module2.usingComponents) {
151
- const components = types.objectProperty(types.identifier("usingComponents"), types.objectExpression([]));
162
+ const componentsObj = {};
152
163
  const allSubPackages = env.getAppConfigInfo().subPackages;
153
164
  for (const [name, path2] of Object.entries(module2.usingComponents)) {
154
165
  let toMainSubPackage = true;
@@ -167,83 +178,183 @@ function buildJSByPath(packageName, module2, compileRes, mainCompileRes, addExtr
167
178
  if (!componentModule) {
168
179
  continue;
169
180
  }
170
- buildJSByPath(packageName, componentModule, compileRes, mainCompileRes, true, toMainSubPackage);
171
- const props = types.objectProperty(types.identifier(`'${name}'`), types.stringLiteral(path2));
172
- components.value.properties.push(props);
181
+ await buildJSByPath(packageName, componentModule, compileRes, mainCompileRes, true, depthChain, toMainSubPackage);
182
+ componentsObj[name] = path2;
173
183
  }
174
- addedArgs.properties.push(components);
184
+ extraInfo.usingComponents = componentsObj;
175
185
  }
176
186
  if (addExtra) {
177
- ast.program.body.splice(0, 0, getExtraInfoStatement("this", addedArgs));
187
+ const extraInfoCode = `globalThis.__extraInfo = ${JSON.stringify(extraInfo)};
188
+ `;
189
+ s.prepend(extraInfoCode);
178
190
  }
179
191
  if (putMain) {
180
192
  mainCompileRes.push(compileInfo);
181
193
  } else {
182
194
  compileRes.push(compileInfo);
183
195
  }
184
- traverse(ast, {
185
- CallExpression(ap) {
186
- if (ap.node.callee.name === "require" || ap.node.callee.object?.name === "require") {
187
- const requirePath = ap.node.arguments[0].value;
188
- if (requirePath) {
189
- const requireFullPath = path.resolve(modulePath, `../${requirePath}`);
190
- let id = requireFullPath.split(`${env.getWorkPath()}${path.sep}`)[1];
191
- id = id.replace(/\.(js|ts)$/, "").replace(/\\/g, "/");
192
- if (!id.startsWith("/")) {
193
- id = "/" + id;
196
+ const pathReplacements = [];
197
+ const dependenciesToProcess = [];
198
+ oxcWalker.walk(ast, {
199
+ enter(node, parent) {
200
+ if (node.type === "CallExpression") {
201
+ const isRequire = node.callee.type === "Identifier" && node.callee.name === "require";
202
+ const isRequireProperty = node.callee.type === "MemberExpression" && node.callee.object?.type === "Identifier" && node.callee.object?.name === "require";
203
+ if ((isRequire || isRequireProperty) && node.arguments.length > 0 && (node.arguments[0].type === "StringLiteral" || node.arguments[0].type === "Literal")) {
204
+ const arg = node.arguments[0];
205
+ const requirePath = arg.value;
206
+ if (requirePath) {
207
+ let id;
208
+ if (requirePath.startsWith("@") || requirePath.startsWith("miniprogram_npm/")) {
209
+ if (requirePath.startsWith("@")) {
210
+ id = `/miniprogram_npm/${requirePath}`;
211
+ } else {
212
+ id = requirePath.startsWith("/") ? requirePath : `/${requirePath}`;
213
+ }
214
+ } else {
215
+ const requireFullPath = path.resolve(modulePath, `../${requirePath}`);
216
+ id = requireFullPath.split(`${env.getWorkPath()}${path.sep}`)[1];
217
+ id = id.replace(/\.(js|ts)$/, "").replace(/\\/g, "/");
218
+ if (!id.startsWith("/")) {
219
+ id = "/" + id;
220
+ }
221
+ }
222
+ {
223
+ pathReplacements.push({
224
+ start: arg.start,
225
+ end: arg.end,
226
+ newValue: id
227
+ });
228
+ if (!processedModules.has(packageName + id)) {
229
+ dependenciesToProcess.push(id);
230
+ }
231
+ }
194
232
  }
195
- ap.node.arguments[0] = types.stringLiteral(id);
196
- buildJSByPath(packageName, { path: id }, compileRes, mainCompileRes, false);
197
233
  }
198
234
  }
199
- },
200
- ImportDeclaration(ap) {
201
- const importPath = ap.node.source.value;
202
- if (importPath) {
203
- let id;
204
- let shouldProcess = false;
205
- if (importPath.startsWith("@") || importPath.startsWith("miniprogram_npm/")) {
206
- if (importPath.startsWith("@")) {
207
- id = `/miniprogram_npm/${importPath}`;
235
+ if (node.type === "ImportDeclaration") {
236
+ const importPath = node.source.value;
237
+ if (importPath) {
238
+ let id;
239
+ let shouldProcess = false;
240
+ if (importPath.startsWith("@") || importPath.startsWith("miniprogram_npm/")) {
241
+ if (importPath.startsWith("@")) {
242
+ id = `/miniprogram_npm/${importPath}`;
243
+ } else {
244
+ id = importPath.startsWith("/") ? importPath : `/${importPath}`;
245
+ }
246
+ shouldProcess = true;
247
+ } else if (importPath.startsWith("./") || importPath.startsWith("../") || !importPath.startsWith("/")) {
248
+ const importFullPath = path.resolve(modulePath, `../${importPath}`);
249
+ id = importFullPath.split(`${env.getWorkPath()}${path.sep}`)[1];
250
+ id = id.replace(/\.(js|ts)$/, "").replace(/\\/g, "/");
251
+ if (!id.startsWith("/")) {
252
+ id = "/" + id;
253
+ }
254
+ shouldProcess = true;
208
255
  } else {
209
- id = importPath.startsWith("/") ? importPath : `/${importPath}`;
256
+ id = importPath;
257
+ shouldProcess = true;
210
258
  }
211
- shouldProcess = true;
212
- } else if (importPath.startsWith("./") || importPath.startsWith("../") || !importPath.startsWith("/")) {
213
- const importFullPath = path.resolve(modulePath, `../${importPath}`);
214
- id = importFullPath.split(`${env.getWorkPath()}${path.sep}`)[1];
215
- id = id.replace(/\.(js|ts)$/, "").replace(/\\/g, "/");
216
- if (!id.startsWith("/")) {
217
- id = "/" + id;
259
+ if (shouldProcess) {
260
+ pathReplacements.push({
261
+ start: node.source.start,
262
+ end: node.source.end,
263
+ newValue: id
264
+ });
265
+ if (!processedModules.has(packageName + id)) {
266
+ dependenciesToProcess.push(id);
267
+ }
218
268
  }
219
- shouldProcess = true;
220
- } else {
221
- id = importPath;
222
- shouldProcess = true;
223
- }
224
- if (shouldProcess) {
225
- ap.node.source = types.stringLiteral(id);
226
- buildJSByPath(packageName, { path: id }, compileRes, mainCompileRes, false);
227
269
  }
228
270
  }
229
271
  }
230
272
  });
231
- const { code } = babel.transformFromAstSync(ast, "", {
232
- comments: false,
233
- plugins: [
234
- // ES6 import/export 转换为 CommonJS
235
- transformModulesCommonjs
236
- ]
237
- });
238
- compileInfo.code = code;
239
- }
240
- function getExtraInfoStatement(type, addedArgs) {
241
- const assignmentExpression = types.assignmentExpression(
242
- "=",
243
- types.memberExpression(types.identifier("globalThis"), types.identifier("__extraInfo")),
244
- addedArgs
245
- );
246
- return types.expressionStatement(assignmentExpression);
273
+ for (const depId of dependenciesToProcess) {
274
+ await buildJSByPath(packageName, { path: depId }, compileRes, mainCompileRes, false, depthChain);
275
+ }
276
+ for (const replacement of pathReplacements.reverse()) {
277
+ s.overwrite(replacement.start, replacement.end, `'${replacement.newValue}'`);
278
+ }
279
+ const modifiedCode = s.toString();
280
+ let transformedCode = modifiedCode;
281
+ if (modulePath.endsWith(".ts") || modulePath.endsWith(".tsx")) {
282
+ try {
283
+ const result = oxcTransform.transformSync(modulePath, modifiedCode, {
284
+ sourceType: "module",
285
+ lang: modulePath.endsWith(".tsx") ? "tsx" : "ts",
286
+ target: "es2020",
287
+ typescript: {
288
+ onlyRemoveTypeImports: true
289
+ }
290
+ });
291
+ transformedCode = result.code;
292
+ } catch (error) {
293
+ console.error(`[logic] oxc-transform 转换失败 ${modulePath}:`, error.message);
294
+ transformedCode = modifiedCode;
295
+ }
296
+ }
297
+ try {
298
+ const esbuildResult = await esbuild.transform(transformedCode, {
299
+ format: "cjs",
300
+ target: "es2020",
301
+ platform: "neutral",
302
+ loader: "js"
303
+ });
304
+ const esbuildCode = esbuildResult.code;
305
+ const esbuildAst = oxcParser.parseSync(modulePath, esbuildCode, {
306
+ sourceType: "module",
307
+ lang: "js"
308
+ });
309
+ const postEsbuildReplacements = [];
310
+ oxcWalker.walk(esbuildAst.program, {
311
+ enter(node) {
312
+ if (node.type === "CallExpression") {
313
+ const isRequire = node.callee.type === "Identifier" && node.callee.name === "require";
314
+ const isRequireProperty = node.callee.type === "MemberExpression" && node.callee.object?.type === "Identifier" && node.callee.object?.name === "require";
315
+ if ((isRequire || isRequireProperty) && node.arguments.length > 0 && (node.arguments[0].type === "StringLiteral" || node.arguments[0].type === "Literal")) {
316
+ const arg = node.arguments[0];
317
+ const requirePath = arg.value;
318
+ if (requirePath && (requirePath.startsWith("./") || requirePath.startsWith("../"))) {
319
+ let id;
320
+ if (requirePath.startsWith("@") || requirePath.startsWith("miniprogram_npm/")) {
321
+ if (requirePath.startsWith("@")) {
322
+ id = `/miniprogram_npm/${requirePath}`;
323
+ } else {
324
+ id = requirePath.startsWith("/") ? requirePath : `/${requirePath}`;
325
+ }
326
+ } else {
327
+ const requireFullPath = path.resolve(modulePath, `../${requirePath}`);
328
+ id = requireFullPath.split(`${env.getWorkPath()}${path.sep}`)[1];
329
+ id = id.replace(/\.(js|ts)$/, "").replace(/\\/g, "/");
330
+ if (!id.startsWith("/")) {
331
+ id = "/" + id;
332
+ }
333
+ }
334
+ postEsbuildReplacements.push({
335
+ start: arg.start,
336
+ end: arg.end,
337
+ newValue: id
338
+ });
339
+ }
340
+ }
341
+ }
342
+ }
343
+ });
344
+ if (postEsbuildReplacements.length > 0) {
345
+ const finalMagicString = new MagicString(esbuildCode);
346
+ for (const replacement of postEsbuildReplacements.reverse()) {
347
+ finalMagicString.overwrite(replacement.start, replacement.end, `"${replacement.newValue}"`);
348
+ }
349
+ compileInfo.code = finalMagicString.toString();
350
+ } else {
351
+ compileInfo.code = esbuildCode;
352
+ }
353
+ } catch (error) {
354
+ console.error(`[logic] esbuild 转换失败 ${modulePath}:`, error.message);
355
+ compileInfo.code = transformedCode;
356
+ }
357
+ processedModules.add(packageName + currentPath);
247
358
  }
248
359
  function getJSAbsolutePath(modulePath) {
249
360
  const workPath = env.getWorkPath();