@dimina/compiler 1.0.5 → 1.0.7

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,14 +1,15 @@
1
1
  "use strict";
2
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
3
  const fs = require("node:fs");
3
4
  const node_worker_threads = require("node:worker_threads");
4
5
  const babel = require("@babel/core");
5
- const types = require("@babel/types");
6
6
  const _traverse = require("@babel/traverse");
7
+ const types = require("@babel/types");
7
8
  const compilerSfc = require("@vue/compiler-sfc");
8
9
  const cheerio = require("cheerio");
9
- const htmlparser2 = require("htmlparser2");
10
10
  const esbuild = require("esbuild");
11
- const env = require("../env-Chow6VXH.cjs");
11
+ const htmlparser2 = require("htmlparser2");
12
+ const env = require("../env-CGYKCSjT.cjs");
12
13
  function _interopNamespaceDefault(e) {
13
14
  const n = Object.create(null, { [Symbol.toStringTag]: { value: "Module" } });
14
15
  if (e) {
@@ -30,7 +31,6 @@ const htmlparser2__namespace = /* @__PURE__ */ _interopNamespaceDefault(htmlpars
30
31
  const traverse = _traverse.default ? _traverse.default : _traverse;
31
32
  const fileType = [".wxml", ".ddml"];
32
33
  const compileResCache = /* @__PURE__ */ new Map();
33
- const processedModules = /* @__PURE__ */ new Set();
34
34
  if (!node_worker_threads.isMainThread) {
35
35
  node_worker_threads.parentPort.on("message", async ({ pages, storeInfo }) => {
36
36
  try {
@@ -75,13 +75,13 @@ async function compileML(pages, root, progress) {
75
75
  if (root) {
76
76
  const subDir = `${env.getTargetPath()}/${root}`;
77
77
  if (!fs.existsSync(subDir)) {
78
- fs.mkdirSync(subDir);
78
+ fs.mkdirSync(subDir, { recursive: true });
79
79
  }
80
80
  fs.writeFileSync(`${subDir}/${filename}.js`, mergeRender);
81
81
  } else {
82
82
  const mainDir = `${env.getTargetPath()}/main`;
83
83
  if (!fs.existsSync(mainDir)) {
84
- fs.mkdirSync(mainDir);
84
+ fs.mkdirSync(mainDir, { recursive: true });
85
85
  }
86
86
  fs.writeFileSync(`${mainDir}/${filename}.js`, mergeRender);
87
87
  }
@@ -91,10 +91,12 @@ async function compileML(pages, root, progress) {
91
91
  function buildCompileView(module2, isComponent = false, scriptRes, depthChain = []) {
92
92
  const currentPath = module2.path;
93
93
  if (depthChain.includes(currentPath)) {
94
- console.warn(`检测到循环依赖: ${[...depthChain, currentPath].join(" -> ")}`);
94
+ console.warn("[view]", `检测到循环依赖: ${[...depthChain, currentPath].join(" -> ")}`);
95
+ return;
95
96
  }
96
- if (depthChain.length > 100) {
97
- console.warn(`检测到深度依赖: ${[...depthChain, currentPath].join(" -> ")}`);
97
+ if (depthChain.length > 20) {
98
+ console.warn("[view]", `检测到深度依赖: ${[...depthChain, currentPath].join(" -> ")}`);
99
+ return;
98
100
  }
99
101
  depthChain = [...depthChain, currentPath];
100
102
  compileModule(module2, isComponent, scriptRes);
@@ -104,10 +106,13 @@ function buildCompileView(module2, isComponent = false, scriptRes, depthChain =
104
106
  if (!componentModule) {
105
107
  continue;
106
108
  }
109
+ if (componentModule.path === module2.path) {
110
+ console.warn("[view]", `检测到自依赖,跳过处理: ${module2.path}`);
111
+ continue;
112
+ }
107
113
  buildCompileView(componentModule, true, scriptRes, depthChain);
108
114
  }
109
115
  }
110
- processedModules.add(currentPath);
111
116
  }
112
117
  function compileModule(module2, isComponent, scriptRes) {
113
118
  const { tpl, instruction } = toCompileTemplate(isComponent, module2.path, module2.usingComponents, module2.componentPlaceholder);
@@ -143,7 +148,7 @@ function compileModule(module2, isComponent, scriptRes) {
143
148
  });
144
149
  let tplComponents = "{";
145
150
  for (const tm of instruction.templateModule) {
146
- tplComponents += `'${tm.path}':${compilerSfc.compileTemplate({
151
+ let { code: code2 } = compilerSfc.compileTemplate({
147
152
  source: tm.tpl,
148
153
  filename: tm.path,
149
154
  id: `data-v-${module2.id}`,
@@ -156,36 +161,17 @@ function compileModule(module2, isComponent, scriptRes) {
156
161
  mode: "function",
157
162
  inline: true
158
163
  }
159
- }).code},`;
164
+ });
165
+ const ast = babel.parseSync(code2);
166
+ insertWxsToRenderAst(ast, instruction.scriptModule, scriptRes);
167
+ code2 = babel.transformFromAstSync(ast, "", {
168
+ comments: false
169
+ }).code;
170
+ tplComponents += `'${tm.path}':${code2.replace(/;$/, "").replace(/^"use strict";\s*/, "")},`;
160
171
  }
161
172
  tplComponents += "}";
162
173
  const tplAst = babel.parseSync(tplCode.code);
163
- for (const sm of instruction.scriptModule) {
164
- if (!scriptRes.has(sm.path)) {
165
- scriptRes.set(sm.path, sm.code);
166
- }
167
- const assignmentExpression = types.assignmentExpression(
168
- "=",
169
- // 创建赋值表达式
170
- types.memberExpression(
171
- types.identifier("_ctx"),
172
- // 对象标识符
173
- types.identifier(sm.path),
174
- // 属性标识符
175
- false
176
- // 是否是计算属性
177
- ),
178
- // 创建require调用表达式
179
- types.callExpression(
180
- types.identifier("require"),
181
- // 函数标识符
182
- [types.stringLiteral(sm.path)]
183
- // 参数列表,这里传入字符串字面量'foo'
184
- )
185
- );
186
- const expressionStatement = types.expressionStatement(assignmentExpression);
187
- tplAst.program.body[0].expression.body.body.splice(0, 0, expressionStatement);
188
- }
174
+ insertWxsToRenderAst(tplAst, instruction.scriptModule, scriptRes);
189
175
  const { code: transCode } = babel.transformFromAstSync(tplAst, "", {
190
176
  comments: false
191
177
  });
@@ -211,9 +197,19 @@ function toCompileTemplate(isComponent, path, components, componentPlaceholder)
211
197
  } else {
212
198
  if (isComponent) {
213
199
  content = `<wrapper>${content}</wrapper>`;
200
+ } else {
201
+ const tempRoot = cheerio__namespace.load(content, {
202
+ xmlMode: true,
203
+ decodeEntities: false
204
+ });
205
+ const rootNodes = tempRoot.root().children().toArray().filter((node) => node.type !== "comment");
206
+ if (rootNodes.length > 1) {
207
+ content = `<view>${content}</view>`;
208
+ }
214
209
  }
215
210
  }
216
211
  const templateModule = [];
212
+ const scriptModule = [];
217
213
  const $ = cheerio__namespace.load(content, {
218
214
  xmlMode: true,
219
215
  decodeEntities: false
@@ -236,70 +232,34 @@ function toCompileTemplate(isComponent, path, components, componentPlaceholder)
236
232
  }
237
233
  });
238
234
  transTagTemplate($, templateModule, path, components);
235
+ transTagWxs($, scriptModule, path);
239
236
  const importNodes = $("import");
240
237
  importNodes.each((_, elem) => {
241
238
  const src = $(elem).attr("src");
242
239
  if (src) {
243
- const importContent = env.getContentByPath(env.getAbsolutePath(workPath, path, src)).trim();
240
+ const importFullPath = env.getAbsolutePath(workPath, path, src);
241
+ const importPath = importFullPath.replace(workPath, "").split("/").slice(0, -1).join("/");
242
+ const importContent = env.getContentByPath(importFullPath).trim();
244
243
  if (importContent) {
244
+ const $$ = cheerio__namespace.load(importContent, {
245
+ xmlMode: true,
246
+ decodeEntities: false
247
+ });
245
248
  transTagTemplate(
246
- cheerio__namespace.load(importContent, {
247
- xmlMode: true,
248
- decodeEntities: false
249
- }),
249
+ $$,
250
250
  templateModule,
251
251
  path,
252
252
  components
253
253
  );
254
+ transTagWxs(
255
+ $$,
256
+ scriptModule,
257
+ importPath
258
+ );
254
259
  }
255
260
  }
256
261
  });
257
262
  importNodes.remove();
258
- const scriptModule = [];
259
- let wxsNodes = $("wxs");
260
- if (wxsNodes.length === 0) {
261
- wxsNodes = $("dds");
262
- }
263
- wxsNodes.each((_, elem) => {
264
- const smName = $(elem).attr("module");
265
- if (smName) {
266
- let wxsContent;
267
- if (compileResCache.has(smName)) {
268
- wxsContent = compileResCache.get(smName);
269
- } else {
270
- const src = $(elem).attr("src");
271
- if (src) {
272
- wxsContent = env.getContentByPath(env.getAbsolutePath(workPath, path, src)).trim();
273
- } else {
274
- wxsContent = $(elem).html();
275
- }
276
- const wxsAst = babel.parseSync(wxsContent);
277
- traverse(wxsAst, {
278
- CallExpression(path2) {
279
- if (path2.node.callee.name === "getRegExp" || path2.node.callee.name === "getDate") {
280
- const args = [];
281
- for (let i = 0; i < path2.node.arguments.length; i++) {
282
- args.push(path2.node.arguments[i]);
283
- }
284
- const newExpr = types.newExpression(types.identifier(path2.node.callee.name.substring(3)), args);
285
- path2.replaceWith(newExpr);
286
- }
287
- }
288
- });
289
- wxsContent = babel.transformFromAstSync(wxsAst, "", {
290
- comments: false
291
- }).code;
292
- compileResCache.set(smName, wxsContent);
293
- }
294
- if (wxsContent) {
295
- scriptModule.push({
296
- path: smName,
297
- code: wxsContent
298
- });
299
- }
300
- }
301
- });
302
- wxsNodes.remove();
303
263
  transAsses($, $("image"), path);
304
264
  const res = [];
305
265
  transHtmlTag($.html(), res, components);
@@ -316,7 +276,6 @@ function transTagTemplate($, templateModule, path, components, componentPlacehol
316
276
  templateNodes.each((_, elem) => {
317
277
  const name = $(elem).attr("name");
318
278
  const templateContent = $(elem);
319
- templateContent.find("template").remove();
320
279
  templateContent.find("import").remove();
321
280
  templateContent.find("include").remove();
322
281
  templateContent.find("wxs").remove();
@@ -377,20 +336,20 @@ function transTag(opts) {
377
336
  res = `dd-${tag}`;
378
337
  }
379
338
  let tagRes;
380
- const propsAry = getProps(attrs, tag);
339
+ const propsAry = isStart ? getProps(attrs, tag) : [];
381
340
  const multipleSlots = attrs?.slot;
382
341
  if (attrs?.slot) {
383
- const withVIf = [];
384
- const withoutVIf = [];
385
- for (let i = 0; i < propsAry.length; i++) {
386
- const prop = propsAry[i];
387
- if (prop.includes("v-if") || prop.includes("v-else-if") || prop.includes("v-else")) {
388
- withVIf.push(prop);
389
- } else {
390
- withoutVIf.push(prop);
391
- }
392
- }
393
342
  if (isStart) {
343
+ const withVIf = [];
344
+ const withoutVIf = [];
345
+ for (let i = 0; i < propsAry.length; i++) {
346
+ const prop = propsAry[i];
347
+ if (prop.includes("v-if") || prop.includes("v-else-if") || prop.includes("v-else")) {
348
+ withVIf.push(prop);
349
+ } else {
350
+ withoutVIf.push(prop);
351
+ }
352
+ }
394
353
  tagRes = `<template ${`${withVIf.join(" ")}`} #${multipleSlots}><${res}${` ${withoutVIf.join(" ")}`}>`;
395
354
  } else {
396
355
  tagRes = `</${res}></template>`;
@@ -430,14 +389,7 @@ function getProps(attrs, tag) {
430
389
  });
431
390
  } else if (name.endsWith(":for-item") || name.endsWith(":for-index")) ;
432
391
  else if (name.endsWith(":key")) {
433
- let tranValue;
434
- if (/\*this/.test(value)) {
435
- tranValue = JSON.stringify("item");
436
- } else if (/item/.test(value)) {
437
- tranValue = getForItemName(attrs);
438
- } else {
439
- tranValue = parseKeyExpression(value, getForItemName(attrs));
440
- }
392
+ const tranValue = parseKeyExpression(value, getForItemName(attrs));
441
393
  attrsList.push({
442
394
  name: ":key",
443
395
  value: tranValue
@@ -556,12 +508,22 @@ function generateVModelTemplate(expression) {
556
508
  }
557
509
  function parseKeyExpression(exp, itemName = "item") {
558
510
  exp = exp.trim();
511
+ if (/\*this/.test(exp) || /\*item/.test(exp)) {
512
+ return `${itemName}.toString()`;
513
+ }
559
514
  if (!exp.includes("{{")) {
560
- return exp.startsWith(itemName) ? `'${exp}'` : `'${itemName}.${exp}'`;
515
+ if (/^-?\d+(\.\d+)?$/.test(exp)) {
516
+ return exp;
517
+ }
518
+ return exp.startsWith(itemName) ? `${exp}` : `${itemName}.${exp}`;
561
519
  }
562
520
  if (exp.startsWith("{{") && exp.endsWith("}}")) {
563
521
  const content = exp.slice(2, -2).trim();
564
- return content.startsWith(itemName) ? `'${content}'` : `'${itemName}.${content}'`;
522
+ if (content === "this") {
523
+ return `${itemName}.toString()`;
524
+ } else {
525
+ return content.startsWith(itemName) ? `${content}` : `${itemName}.${content}`;
526
+ }
565
527
  }
566
528
  const parts = exp.split(/(\{\{.*?\}\})/);
567
529
  const result = parts.map((part) => {
@@ -672,12 +634,83 @@ function parseBraceExp(exp) {
672
634
  }
673
635
  return group.join("").replace(/^\+|\+$/g, "");
674
636
  }
675
- const viewCompiler = {
676
- splitWithBraces,
677
- parseClassRules,
678
- parseBraceExp,
679
- parseKeyExpression,
680
- compileML,
681
- generateVModelTemplate
682
- };
683
- module.exports = viewCompiler;
637
+ function transTagWxs($, scriptModule, path) {
638
+ let wxsNodes = $("wxs");
639
+ if (wxsNodes.length === 0) {
640
+ wxsNodes = $("dds");
641
+ }
642
+ wxsNodes.each((_, elem) => {
643
+ const smName = $(elem).attr("module");
644
+ if (smName) {
645
+ let wxsContent;
646
+ if (compileResCache.has(smName)) {
647
+ wxsContent = compileResCache.get(smName);
648
+ } else {
649
+ const src = $(elem).attr("src");
650
+ if (src) {
651
+ wxsContent = env.getContentByPath(env.getAbsolutePath(env.getWorkPath(), path, src)).trim();
652
+ } else {
653
+ wxsContent = $(elem).html();
654
+ }
655
+ const wxsAst = babel.parseSync(wxsContent);
656
+ traverse(wxsAst, {
657
+ CallExpression(path2) {
658
+ if (path2.node.callee.name === "getRegExp" || path2.node.callee.name === "getDate") {
659
+ const args = [];
660
+ for (let i = 0; i < path2.node.arguments.length; i++) {
661
+ args.push(path2.node.arguments[i]);
662
+ }
663
+ const newExpr = types.newExpression(types.identifier(path2.node.callee.name.substring(3)), args);
664
+ path2.replaceWith(newExpr);
665
+ }
666
+ }
667
+ });
668
+ wxsContent = babel.transformFromAstSync(wxsAst, "", {
669
+ comments: false
670
+ }).code;
671
+ compileResCache.set(smName, wxsContent);
672
+ }
673
+ if (wxsContent) {
674
+ scriptModule.push({
675
+ path: smName,
676
+ code: wxsContent
677
+ });
678
+ }
679
+ }
680
+ });
681
+ wxsNodes.remove();
682
+ }
683
+ function insertWxsToRenderAst(ast, scriptModule, scriptRes) {
684
+ for (const sm of scriptModule) {
685
+ if (!scriptRes.has(sm.path)) {
686
+ scriptRes.set(sm.path, sm.code);
687
+ }
688
+ const assignmentExpression = types.assignmentExpression(
689
+ "=",
690
+ // 创建赋值表达式
691
+ types.memberExpression(
692
+ types.identifier("_ctx"),
693
+ // 对象标识符
694
+ types.identifier(sm.path),
695
+ // 属性标识符
696
+ false
697
+ // 是否是计算属性
698
+ ),
699
+ // 创建require调用表达式
700
+ types.callExpression(
701
+ types.identifier("require"),
702
+ // 函数标识符
703
+ [types.stringLiteral(sm.path)]
704
+ // 参数列表,这里传入字符串字面量'foo'
705
+ )
706
+ );
707
+ const expressionStatement = types.expressionStatement(assignmentExpression);
708
+ ast.program.body[0].expression.body.body.unshift(expressionStatement);
709
+ }
710
+ }
711
+ exports.compileML = compileML;
712
+ exports.generateVModelTemplate = generateVModelTemplate;
713
+ exports.parseBraceExp = parseBraceExp;
714
+ exports.parseClassRules = parseClassRules;
715
+ exports.parseKeyExpression = parseKeyExpression;
716
+ exports.splitWithBraces = splitWithBraces;