@dimina-kit/compiler 0.0.2-dev.20260718095333 → 0.0.2-dev.20260728063215

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.
Files changed (24) hide show
  1. package/dist/compile-core.browser.js +5130 -4282
  2. package/dist/compile-core.node-chunks/chunk-23PCGQQU.js +141 -0
  3. package/dist/compile-core.node-chunks/{chunk-QVEZ34FP.js → chunk-M62ZDT7T.js} +281 -21
  4. package/dist/compile-core.node-chunks/{chunk-6734LXNU.js → chunk-QYHGF3MS.js} +75 -4
  5. package/dist/compile-core.node-chunks/{logic-compiler-VJWEQMXZ.js → logic-compiler-AEZPY2MO.js} +26 -102
  6. package/dist/compile-core.node-chunks/style-compiler-4PHMBQIC.js +470 -0
  7. package/dist/compile-core.node-chunks/{view-compiler-3OUFRVZF.js → view-compiler-2SMUHAPD.js} +232 -109
  8. package/dist/compile-core.node.js +11 -6
  9. package/dist/pool.node-chunks/{chunk-7F3E2G42.js → chunk-CKQISGZS.js} +281 -21
  10. package/dist/pool.node-chunks/{chunk-DQNLDQGT.js → chunk-LGB3AH5C.js} +75 -4
  11. package/dist/pool.node-chunks/chunk-VHWKAXDL.js +141 -0
  12. package/dist/pool.node-chunks/{chunk-LKL7FBHG.js → chunk-WX4462A5.js} +11 -6
  13. package/dist/pool.node-chunks/{logic-compiler-HMMTJJWY.js → logic-compiler-P4T4OMTG.js} +26 -102
  14. package/dist/pool.node-chunks/style-compiler-W7EA2Y7R.js +470 -0
  15. package/dist/pool.node-chunks/{view-compiler-2VZMJ65O.js → view-compiler-2D7HPYIN.js} +232 -109
  16. package/dist/pool.node.js +2 -2
  17. package/dist/stage-worker.browser.js +5337 -4489
  18. package/dist/stage-worker.node.js +2 -2
  19. package/package.json +8 -7
  20. package/scripts/check-wasm-alignment.js +173 -0
  21. package/dist/compile-core.node-chunks/chunk-2VRS523Z.js +0 -8
  22. package/dist/compile-core.node-chunks/style-compiler-YWVITCJW.js +0 -288
  23. package/dist/pool.node-chunks/chunk-KLXXOLDF.js +0 -8
  24. package/dist/pool.node-chunks/style-compiler-VGVCLQ7X.js +0 -288
@@ -1,11 +1,16 @@
1
1
  import {
2
2
  checkTemplateCompatibility,
3
+ getTemplateDirectiveName,
3
4
  takeCompatibilityWarnings
4
- } from "./chunk-6734LXNU.js";
5
+ } from "./chunk-QYHGF3MS.js";
5
6
  import {
7
+ concatSourcemap,
8
+ createLineSourcemap,
6
9
  isMainThread,
7
- parentPort
8
- } from "./chunk-2VRS523Z.js";
10
+ mergeSourcemap,
11
+ parentPort,
12
+ remapSourcemap
13
+ } from "./chunk-23PCGQQU.js";
9
14
  import {
10
15
  collectAssets,
11
16
  fs_default,
@@ -13,16 +18,18 @@ import {
13
18
  getAppId,
14
19
  getComponent,
15
20
  getContentByPath,
21
+ getDependencyGraph,
16
22
  getTargetPath,
17
23
  getTemplateExts,
18
24
  getViewScriptExts,
19
25
  getViewScriptTags,
20
26
  getWorkPath,
21
27
  resetStoreInfo,
28
+ resolveAssetSourcePath,
22
29
  tagWhiteList,
23
30
  toMiniProgramModuleId,
24
31
  transformRpx
25
- } from "./chunk-QVEZ34FP.js";
32
+ } from "./chunk-M62ZDT7T.js";
26
33
 
27
34
  // ../../dimina/fe/packages/compiler/src/core/view-compiler.js
28
35
  import path from "node:path";
@@ -281,10 +288,12 @@ function transformTextInterpolation(text) {
281
288
  var compileResCache = /* @__PURE__ */ new Map();
282
289
  var wxsModuleRegistry = /* @__PURE__ */ new Set();
283
290
  var wxsFilePathMap = /* @__PURE__ */ new Map();
291
+ var enableSourcemap = false;
284
292
  if (!isMainThread) {
285
- parentPort.on("message", async ({ pages, storeInfo }) => {
293
+ parentPort.on("message", async ({ pages, storeInfo, sourcemap }) => {
286
294
  try {
287
295
  resetStoreInfo(storeInfo);
296
+ enableSourcemap = !!sourcemap;
288
297
  const progress = {
289
298
  _completedTasks: 0,
290
299
  get completedTasks() {
@@ -304,7 +313,8 @@ if (!isMainThread) {
304
313
  wxsFilePathMap.clear();
305
314
  parentPort.postMessage({
306
315
  success: true,
307
- compatibilityWarnings: takeCompatibilityWarnings()
316
+ compatibilityWarnings: takeCompatibilityWarnings(),
317
+ dependencyGraph: getDependencyGraph().toJSON()
308
318
  });
309
319
  } catch (error) {
310
320
  compileResCache.clear();
@@ -326,43 +336,50 @@ async function compileML(pages, root, progress) {
326
336
  initWxsFilePathMap(workPath);
327
337
  for (const page of pages) {
328
338
  const scriptRes = /* @__PURE__ */ new Map();
329
- buildCompileView(page, false, scriptRes, /* @__PURE__ */ new Set(), /* @__PURE__ */ new Set());
330
- let mergeRender = "";
331
- for (const [key, value] of scriptRes.entries()) {
332
- const amdFormat = `modDefine('${key}', function(require, module, exports) {
333
- ${value}
334
- });`;
335
- try {
336
- const { code: minifiedCode } = await transform(amdFormat, {
337
- minify: true,
338
- target: ["es2020"],
339
- platform: "browser"
340
- });
341
- mergeRender += minifiedCode;
342
- } catch (error) {
343
- const location = error.errors?.[0]?.location;
344
- const sourceLines = amdFormat.split("\n");
345
- const sourceHint = location?.line ? sourceLines.slice(Math.max(0, location.line - 3), location.line + 2).map((line, index) => `${Math.max(1, location.line - 2) + index}: ${line.trim()}`).join("\n") : "";
346
- error.message = `\u89C6\u56FE\u6A21\u5757 ${key} \u8F6C\u6362\u5931\u8D25: ${error.message}${sourceHint ? `
347
- ${sourceHint}` : ""}`;
348
- throw error;
349
- }
350
- }
351
- scriptRes.clear();
339
+ const sourceMapRes = /* @__PURE__ */ new Map();
340
+ buildCompileView(page, false, scriptRes, /* @__PURE__ */ new Set(), /* @__PURE__ */ new Set(), sourceMapRes);
352
341
  const filename = `${page.path.replace(/\//g, "_")}`;
353
- if (root) {
354
- const subDir = `${getTargetPath()}/${root}`;
355
- if (!fs_default.existsSync(subDir)) {
356
- fs_default.mkdirSync(subDir, { recursive: true });
357
- }
358
- fs_default.writeFileSync(`${subDir}/${filename}.js`, mergeRender);
342
+ const outputDir = root ? `${getTargetPath()}/${root}` : `${getTargetPath()}/main`;
343
+ if (!fs_default.existsSync(outputDir)) {
344
+ fs_default.mkdirSync(outputDir, { recursive: true });
345
+ }
346
+ if (enableSourcemap) {
347
+ const compileRes = [...scriptRes.entries()].map(([modulePath, code]) => ({
348
+ path: modulePath,
349
+ code,
350
+ map: sourceMapRes.get(modulePath)
351
+ }));
352
+ const sourcemapFileName = `${filename}.js.map`;
353
+ const { bundleCode, sourcemap } = mergeSourcemap(compileRes, `${filename}.js`);
354
+ fs_default.writeFileSync(`${outputDir}/${filename}.js`, `${bundleCode}//# sourceMappingURL=${sourcemapFileName}
355
+ `);
356
+ fs_default.writeFileSync(`${outputDir}/${sourcemapFileName}`, sourcemap);
359
357
  } else {
360
- const mainDir = `${getTargetPath()}/main`;
361
- if (!fs_default.existsSync(mainDir)) {
362
- fs_default.mkdirSync(mainDir, { recursive: true });
358
+ let mergeRender = "";
359
+ for (const [key, value] of scriptRes.entries()) {
360
+ const amdFormat = `modDefine('${key}', function(require, module, exports) {
361
+ ${value}
362
+ });`;
363
+ try {
364
+ const { code: minifiedCode } = await transform(amdFormat, {
365
+ minify: true,
366
+ target: ["es2020"],
367
+ platform: "browser"
368
+ });
369
+ mergeRender += minifiedCode;
370
+ } catch (error) {
371
+ const location = error.errors?.[0]?.location;
372
+ const sourceLines = amdFormat.split("\n");
373
+ const sourceHint = location?.line ? sourceLines.slice(Math.max(0, location.line - 3), location.line + 2).map((line, index) => `${Math.max(1, location.line - 2) + index}: ${line.trim()}`).join("\n") : "";
374
+ error.message = `\u89C6\u56FE\u6A21\u5757 ${key} \u8F6C\u6362\u5931\u8D25: ${error.message}${sourceHint ? `
375
+ ${sourceHint}` : ""}`;
376
+ throw error;
377
+ }
363
378
  }
364
- fs_default.writeFileSync(`${mainDir}/${filename}.js`, mergeRender);
379
+ fs_default.writeFileSync(`${outputDir}/${filename}.js`, mergeRender);
365
380
  }
381
+ scriptRes.clear();
382
+ sourceMapRes.clear();
366
383
  progress.completedTasks++;
367
384
  }
368
385
  }
@@ -412,7 +429,7 @@ function getTemplateCompilerOptions(scopeId) {
412
429
  function isRegisteredWxsModule(modulePath) {
413
430
  return wxsModuleRegistry.has(modulePath);
414
431
  }
415
- function buildCompileView(module, isComponent = false, scriptRes, activePaths = /* @__PURE__ */ new Set(), inheritedTemplatePaths = /* @__PURE__ */ new Set()) {
432
+ function buildCompileView(module, isComponent = false, scriptRes, activePaths = /* @__PURE__ */ new Set(), inheritedTemplatePaths = /* @__PURE__ */ new Set(), sourceMapRes = /* @__PURE__ */ new Map()) {
416
433
  const currentPath = module.path;
417
434
  if (activePaths.has(currentPath)) {
418
435
  return;
@@ -420,7 +437,8 @@ function buildCompileView(module, isComponent = false, scriptRes, activePaths =
420
437
  activePaths.add(currentPath);
421
438
  const allScriptModules = [];
422
439
  const currentInstruction = compileModule(module, isComponent, scriptRes, {
423
- skipTemplatePaths: isComponent ? inheritedTemplatePaths : /* @__PURE__ */ new Set()
440
+ skipTemplatePaths: isComponent ? inheritedTemplatePaths : /* @__PURE__ */ new Set(),
441
+ sourceMapRes
424
442
  });
425
443
  if (currentInstruction && currentInstruction.scriptModule) {
426
444
  allScriptModules.push(...currentInstruction.scriptModule);
@@ -430,7 +448,9 @@ function buildCompileView(module, isComponent = false, scriptRes, activePaths =
430
448
  childInheritedTemplatePaths.add(tm.path);
431
449
  }
432
450
  if (module.usingComponents) {
433
- for (const componentInfo of Object.values(module.usingComponents)) {
451
+ const graphDependencies = getDependencyGraph().getDirectDependencies(module.path, "component");
452
+ const componentDependencies = graphDependencies.length > 0 ? graphDependencies : Object.values(module.usingComponents);
453
+ for (const componentInfo of componentDependencies) {
434
454
  const componentModule = getComponent(componentInfo);
435
455
  if (!componentModule) {
436
456
  continue;
@@ -438,7 +458,7 @@ function buildCompileView(module, isComponent = false, scriptRes, activePaths =
438
458
  if (componentModule.path === module.path) {
439
459
  continue;
440
460
  }
441
- const componentInstruction = buildCompileView(componentModule, true, scriptRes, activePaths, childInheritedTemplatePaths);
461
+ const componentInstruction = buildCompileView(componentModule, true, scriptRes, activePaths, childInheritedTemplatePaths, sourceMapRes);
442
462
  if (componentInstruction && componentInstruction.scriptModule) {
443
463
  for (const sm of componentInstruction.scriptModule) {
444
464
  if (!allScriptModules.find((existing) => existing.path === sm.path)) {
@@ -454,14 +474,15 @@ function buildCompileView(module, isComponent = false, scriptRes, activePaths =
454
474
  scriptRes.set(sm.path, sm.code);
455
475
  }
456
476
  }
457
- compileModuleWithAllWxs(module, scriptRes, allScriptModules);
477
+ compileModuleWithAllWxs(module, scriptRes, allScriptModules, sourceMapRes);
458
478
  }
459
479
  activePaths.delete(currentPath);
460
480
  return { scriptModule: allScriptModules, templateModule: currentInstruction?.templateModule || [] };
461
481
  }
462
482
  function compileModule(module, isComponent, scriptRes, options = {}) {
463
483
  const skipTemplatePaths = options.skipTemplatePaths || /* @__PURE__ */ new Set();
464
- const { tpl, instruction } = toCompileTemplate(isComponent, module.path, module.usingComponents, module.componentPlaceholder);
484
+ const sourceMapRes = options.sourceMapRes || /* @__PURE__ */ new Map();
485
+ const { tpl, instruction, sourceInfo } = toCompileTemplate(isComponent, module.path, module.usingComponents, module.componentPlaceholder);
465
486
  if (!tpl) {
466
487
  return null;
467
488
  }
@@ -491,6 +512,10 @@ function compileModule(module, isComponent, scriptRes, options = {}) {
491
512
  }
492
513
  if (useCache && cachedCode) {
493
514
  scriptRes.set(module.path, cachedCode);
515
+ const cachedMap = compileResCache.get(module.path)?.map;
516
+ if (enableSourcemap && cachedMap) {
517
+ sourceMapRes.set(module.path, cachedMap);
518
+ }
494
519
  const allWxsModules2 = collectAllWxsModules(scriptRes, /* @__PURE__ */ new Set(), instruction.scriptModule || []);
495
520
  if (allWxsModules2.length > 0) {
496
521
  const existingModules = instruction.scriptModule || [];
@@ -514,33 +539,41 @@ function compileModule(module, isComponent, scriptRes, options = {}) {
514
539
  // 用于错误提示
515
540
  id: `data-v-${module.id}`,
516
541
  scoped: true,
542
+ inMap: enableSourcemap ? createLineSourcemap(processedTpl, sourceInfo.path, sourceInfo.content) : void 0,
517
543
  compilerOptions: getTemplateCompilerOptions(`data-v-${module.id}`)
518
544
  });
519
- let tplComponents = "{";
545
+ const templateResults = [];
520
546
  for (const tm of compileInstruction.templateModule) {
521
- let { code: code2 } = compileTemplate({
547
+ const compiledTemplate = compileTemplate({
522
548
  source: tm.tpl,
523
549
  filename: tm.path,
524
550
  id: `data-v-${module.id}`,
525
551
  scoped: true,
552
+ inMap: enableSourcemap && tm.sourceInfo ? createLineSourcemap(tm.tpl, tm.sourceInfo.path, tm.sourceInfo.content, tm.sourceInfo.startLine) : void 0,
526
553
  compilerOptions: getTemplateCompilerOptions(`data-v-${module.id}`)
527
554
  });
528
- code2 = insertWxsToRenderCode(code2, compileInstruction.scriptModule, scriptRes, tm.path);
529
- tplComponents += `'${tm.path}':${code2},`;
555
+ templateResults.push({
556
+ path: tm.path,
557
+ ...insertWxsToRenderResult(compiledTemplate.code, compileInstruction.scriptModule, scriptRes, tm.path, compiledTemplate.map)
558
+ });
530
559
  }
531
- tplComponents += "}";
532
- const transCode = insertWxsToRenderCode(tplCode.code, compileInstruction.scriptModule, scriptRes, module.path);
533
- const code = `Module({
560
+ const renderResult = insertWxsToRenderResult(tplCode.code, compileInstruction.scriptModule, scriptRes, module.path, tplCode.map);
561
+ const moduleChunks = [`Module({
534
562
  path: '${module.path}',
535
563
  id: '${module.id}',
536
564
  appStyleScopeId: ${JSON.stringify(module.appStyleScopeId || null)},
537
565
  sharedStyleScopeIds: ${JSON.stringify(module.sharedStyleScopeIds || [])},
538
566
  styleIsolation: ${JSON.stringify(module.styleIsolation || "isolated")},
539
- render: ${transCode},
567
+ render: `, renderResult, `,
540
568
  usingComponents: ${JSON.stringify(module.usingComponents)},
569
+ componentPlaceholder: ${JSON.stringify(module.componentPlaceholder || {})},
541
570
  customTabBar: ${JSON.stringify(module.customTabBar || null)},
542
- tplComponents: ${tplComponents},
543
- });`;
571
+ tplComponents: {`];
572
+ for (const templateResult of templateResults) {
573
+ moduleChunks.push(`'${templateResult.path}':`, templateResult, ",");
574
+ }
575
+ moduleChunks.push("},\n });");
576
+ const { code, sourcemap: moduleMap } = concatSourcemap(moduleChunks, module.path);
544
577
  const allWxsModules = collectAllWxsModules(scriptRes, /* @__PURE__ */ new Set(), compileInstruction.scriptModule || []);
545
578
  if (allWxsModules.length > 0) {
546
579
  const existingModules = compileInstruction.scriptModule || [];
@@ -554,18 +587,25 @@ function compileModule(module, isComponent, scriptRes, options = {}) {
554
587
  }
555
588
  const cacheData = {
556
589
  code,
557
- instruction: compileInstruction
590
+ instruction: compileInstruction,
591
+ map: enableSourcemap ? moduleMap : null
558
592
  };
559
593
  if (canUseCache) {
560
594
  compileResCache.set(module.path, cacheData);
561
595
  }
562
596
  scriptRes.set(module.path, code);
597
+ if (enableSourcemap) {
598
+ sourceMapRes.set(module.path, moduleMap);
599
+ }
563
600
  return {
564
601
  ...compileInstruction,
565
602
  templateModule
566
603
  };
567
604
  }
568
- function processWxsContent(wxsContent, wxsFilePath, scriptModule, workPath, filePath) {
605
+ function processWxsContent(wxsContent, wxsFilePath, scriptModule, workPath, filePath, graphOwnerPath = filePath) {
606
+ if (wxsFilePath && graphOwnerPath) {
607
+ getDependencyGraph().addFile(graphOwnerPath, wxsFilePath, "view");
608
+ }
569
609
  let wxsAst;
570
610
  try {
571
611
  wxsAst = parseJs(wxsContent, wxsFilePath || "inline.wxs", "script");
@@ -614,7 +654,7 @@ function processWxsContent(wxsContent, wxsFilePath, scriptModule, workPath, file
614
654
  resolvedWxsPath = path.resolve(currentWxsDir, requirePath);
615
655
  const relativePath = stripViewScriptExt(resolvedWxsPath.replace(workPath, ""));
616
656
  const moduleName = relativePath.replace(/[\/\\@\-]/g, "_").replace(/^_/, "");
617
- processWxsDependency(resolvedWxsPath, moduleName, scriptModule, workPath, filePath);
657
+ processWxsDependency(resolvedWxsPath, moduleName, scriptModule, workPath, filePath, graphOwnerPath);
618
658
  replacements.push({
619
659
  start: node.arguments[0].start,
620
660
  end: node.arguments[0].end,
@@ -625,7 +665,7 @@ function processWxsContent(wxsContent, wxsFilePath, scriptModule, workPath, file
625
665
  resolvedWxsPath = path.resolve(currentWxsDir, requirePath);
626
666
  const relativePath = stripViewScriptExt(resolvedWxsPath.replace(workPath, ""));
627
667
  const depModuleName = relativePath.replace(/[\/\\@\-]/g, "_").replace(/^_/, "");
628
- processWxsDependency(resolvedWxsPath, depModuleName, scriptModule, workPath, filePath);
668
+ processWxsDependency(resolvedWxsPath, depModuleName, scriptModule, workPath, filePath, graphOwnerPath);
629
669
  replacements.push({
630
670
  start: node.arguments[0].start,
631
671
  end: node.arguments[0].end,
@@ -658,7 +698,7 @@ function isWxsModuleByContent(moduleCode, modulePath = "") {
658
698
  }
659
699
  return false;
660
700
  }
661
- function processWxsDependency(wxsFilePath, moduleName, scriptModule, workPath, filePath) {
701
+ function processWxsDependency(wxsFilePath, moduleName, scriptModule, workPath, filePath, graphOwnerPath = filePath) {
662
702
  if (!fs_default.existsSync(wxsFilePath)) {
663
703
  console.warn(`[view] wxs \u4F9D\u8D56\u6587\u4EF6\u4E0D\u5B58\u5728: ${wxsFilePath}`);
664
704
  return;
@@ -670,15 +710,15 @@ function processWxsDependency(wxsFilePath, moduleName, scriptModule, workPath, f
670
710
  if (!wxsContent) {
671
711
  return;
672
712
  }
673
- const wxsCode = processWxsContent(wxsContent, wxsFilePath, scriptModule, workPath, filePath);
713
+ const wxsCode = processWxsContent(wxsContent, wxsFilePath, scriptModule, workPath, filePath, graphOwnerPath);
674
714
  registerWxsModule(moduleName);
675
715
  scriptModule.push({
676
716
  path: moduleName,
677
717
  code: wxsCode
678
718
  });
679
719
  }
680
- function compileModuleWithAllWxs(module, scriptRes, allScriptModules) {
681
- const { tpl, instruction } = toCompileTemplate(false, module.path, module.usingComponents, module.componentPlaceholder);
720
+ function compileModuleWithAllWxs(module, scriptRes, allScriptModules, sourceMapRes = /* @__PURE__ */ new Map()) {
721
+ const { tpl, instruction, sourceInfo } = toCompileTemplate(false, module.path, module.usingComponents, module.componentPlaceholder);
682
722
  if (!tpl) {
683
723
  return;
684
724
  }
@@ -692,46 +732,58 @@ function compileModuleWithAllWxs(module, scriptRes, allScriptModules) {
692
732
  filename: module.path,
693
733
  id: `data-v-${module.id}`,
694
734
  scoped: true,
735
+ inMap: enableSourcemap ? createLineSourcemap(processedTpl, sourceInfo.path, sourceInfo.content) : void 0,
695
736
  compilerOptions: getTemplateCompilerOptions(`data-v-${module.id}`)
696
737
  });
697
- let tplComponents = "{";
738
+ const templateResults = [];
698
739
  for (const tm of mergedInstruction.templateModule) {
699
- let { code: code2 } = compileTemplate({
740
+ const compiledTemplate = compileTemplate({
700
741
  source: tm.tpl,
701
742
  filename: tm.path,
702
743
  id: `data-v-${module.id}`,
703
744
  scoped: true,
745
+ inMap: enableSourcemap && tm.sourceInfo ? createLineSourcemap(tm.tpl, tm.sourceInfo.path, tm.sourceInfo.content, tm.sourceInfo.startLine) : void 0,
704
746
  compilerOptions: getTemplateCompilerOptions(`data-v-${module.id}`)
705
747
  });
706
- code2 = insertWxsToRenderCode(code2, allScriptModules, scriptRes, tm.path);
707
- tplComponents += `'${tm.path}':${code2},`;
748
+ templateResults.push({
749
+ path: tm.path,
750
+ ...insertWxsToRenderResult(compiledTemplate.code, allScriptModules, scriptRes, tm.path, compiledTemplate.map)
751
+ });
708
752
  }
709
- tplComponents += "}";
710
- const transCode = insertWxsToRenderCode(tplCode.code, allScriptModules, scriptRes, module.path);
711
- const code = `Module({
753
+ const renderResult = insertWxsToRenderResult(tplCode.code, allScriptModules, scriptRes, module.path, tplCode.map);
754
+ const moduleChunks = [`Module({
712
755
  path: '${module.path}',
713
756
  id: '${module.id}',
714
757
  appStyleScopeId: ${JSON.stringify(module.appStyleScopeId || null)},
715
758
  sharedStyleScopeIds: ${JSON.stringify(module.sharedStyleScopeIds || [])},
716
759
  styleIsolation: ${JSON.stringify(module.styleIsolation || "isolated")},
717
- render: ${transCode},
760
+ render: `, renderResult, `,
718
761
  usingComponents: ${JSON.stringify(module.usingComponents)},
762
+ componentPlaceholder: ${JSON.stringify(module.componentPlaceholder || {})},
719
763
  customTabBar: ${JSON.stringify(module.customTabBar || null)},
720
- tplComponents: ${tplComponents},
721
- });`;
764
+ tplComponents: {`];
765
+ for (const templateResult of templateResults) {
766
+ moduleChunks.push(`'${templateResult.path}':`, templateResult, ",");
767
+ }
768
+ moduleChunks.push("},\n });");
769
+ const { code, sourcemap: moduleMap } = concatSourcemap(moduleChunks, module.path);
722
770
  const cacheData = {
723
771
  code,
724
- instruction: mergedInstruction
772
+ instruction: mergedInstruction,
773
+ map: enableSourcemap ? moduleMap : null
725
774
  };
726
775
  compileResCache.set(module.path, cacheData);
727
776
  scriptRes.set(module.path, code);
777
+ if (enableSourcemap) {
778
+ sourceMapRes.set(module.path, moduleMap);
779
+ }
728
780
  }
729
781
  function processIncludeConditionalAttrs($, elem, includeContent) {
730
782
  const allAttrs = $(elem).attr();
731
783
  const conditionAttrs = {};
732
784
  let hasCondition = false;
733
785
  for (const attrName in allAttrs) {
734
- if (attrName.endsWith(":if") || attrName.endsWith(":elif") || attrName.endsWith(":else")) {
786
+ if (["if", "elif", "else"].includes(getTemplateDirectiveName(attrName))) {
735
787
  conditionAttrs[attrName] = allAttrs[attrName];
736
788
  hasCondition = true;
737
789
  }
@@ -795,10 +847,12 @@ function toCompileTemplate(isComponent, path2, components, componentPlaceholder,
795
847
  if (!fullPath) {
796
848
  return { tpl: void 0 };
797
849
  }
850
+ getDependencyGraph().addFile(path2, fullPath, "view");
798
851
  const sourcePath = toMiniProgramModuleId(fullPath, workPath).replace(buildExtStripRegex(getTemplateExts()), "");
799
852
  const diagnosticSource = fullPath.startsWith(workPath) ? fullPath.slice(workPath.length) : path2;
800
- let content = getContentByPath(fullPath).trim();
801
- if (!content) {
853
+ const originalContent = getContentByPath(fullPath);
854
+ let content = originalContent;
855
+ if (!content.trim()) {
802
856
  content = "<block></block>";
803
857
  } else {
804
858
  checkTemplateCompatibility(content, diagnosticSource, components);
@@ -823,36 +877,45 @@ function toCompileTemplate(isComponent, path2, components, componentPlaceholder,
823
877
  _useHtmlParser2: true,
824
878
  // 减少内存占用的配置
825
879
  lowerCaseTags: false,
826
- lowerCaseAttributeNames: false
880
+ lowerCaseAttributeNames: false,
881
+ withStartIndices: true,
882
+ withEndIndices: true
827
883
  });
828
884
  const includeNodes = $("include");
829
885
  includeNodes.each((_, elem) => {
830
886
  const src = $(elem).attr("src");
831
887
  if (src) {
832
888
  const includeFullPath = resolveTemplateDependencyPath(workPath, sourcePath, src);
889
+ getDependencyGraph().addFile(path2, includeFullPath, "view");
833
890
  let includePath = includeFullPath.replace(workPath, "").replace(buildExtStripRegex(getTemplateExts()), "");
834
891
  const includeDiagnosticSource = includeFullPath.startsWith(workPath) ? includeFullPath.slice(workPath.length) : includePath;
835
892
  if (!includePath.startsWith("/")) {
836
893
  includePath = "/" + includePath;
837
894
  }
838
- const includeContent = getContentByPath(includeFullPath).trim();
839
- if (includeContent) {
895
+ const includeContent = getContentByPath(includeFullPath);
896
+ if (includeContent.trim()) {
840
897
  checkTemplateCompatibility(includeContent, includeDiagnosticSource, components);
841
898
  const $includeContent = cheerio.load(includeContent, {
842
899
  xmlMode: true,
843
- decodeEntities: false
900
+ decodeEntities: false,
901
+ _useHtmlParser2: true,
902
+ withStartIndices: true,
903
+ withEndIndices: true
844
904
  });
845
905
  transTagTemplate(
846
906
  $includeContent,
847
907
  templateModule,
848
908
  includePath,
849
909
  components,
850
- componentPlaceholder
910
+ componentPlaceholder,
911
+ { path: includeDiagnosticSource, content: includeContent },
912
+ path2
851
913
  );
852
914
  transTagWxs(
853
915
  $includeContent,
854
916
  scriptModule,
855
- includePath
917
+ includePath,
918
+ path2
856
919
  );
857
920
  processIncludedFileWxsDependencies(includeContent, includePath, scriptModule, components, processedPaths);
858
921
  $includeContent("template").remove();
@@ -866,54 +929,73 @@ function toCompileTemplate(isComponent, path2, components, componentPlaceholder,
866
929
  $(elem).remove();
867
930
  }
868
931
  });
869
- transTagTemplate($, templateModule, sourcePath, components, componentPlaceholder);
870
- transTagWxs($, scriptModule, sourcePath);
932
+ transTagTemplate(
933
+ $,
934
+ templateModule,
935
+ sourcePath,
936
+ components,
937
+ componentPlaceholder,
938
+ { path: diagnosticSource, content: originalContent },
939
+ path2
940
+ );
941
+ transTagWxs($, scriptModule, sourcePath, path2);
871
942
  const importNodes = $("import");
872
943
  importNodes.each((_, elem) => {
873
944
  const src = $(elem).attr("src");
874
945
  if (src) {
875
946
  const importFullPath = resolveTemplateDependencyPath(workPath, sourcePath, src);
947
+ getDependencyGraph().addFile(path2, importFullPath, "view");
876
948
  let importPath = importFullPath.replace(workPath, "").replace(buildExtStripRegex(getTemplateExts()), "");
877
949
  const importDiagnosticSource = importFullPath.startsWith(workPath) ? importFullPath.slice(workPath.length) : importPath;
878
950
  if (!importPath.startsWith("/")) {
879
951
  importPath = "/" + importPath;
880
952
  }
881
- const importContent = getContentByPath(importFullPath).trim();
882
- if (importContent) {
953
+ const importContent = getContentByPath(importFullPath);
954
+ if (importContent.trim()) {
883
955
  checkTemplateCompatibility(importContent, importDiagnosticSource, components);
884
956
  const $$ = cheerio.load(importContent, {
885
957
  xmlMode: true,
886
- decodeEntities: false
958
+ decodeEntities: false,
959
+ _useHtmlParser2: true,
960
+ withStartIndices: true,
961
+ withEndIndices: true
887
962
  });
888
963
  transTagTemplate(
889
964
  $$,
890
965
  templateModule,
891
966
  importPath,
892
967
  components,
893
- componentPlaceholder
968
+ componentPlaceholder,
969
+ { path: importDiagnosticSource, content: importContent },
970
+ path2
894
971
  );
895
972
  transTagWxs(
896
973
  $$,
897
974
  scriptModule,
898
- importPath
975
+ importPath,
976
+ path2
899
977
  );
900
978
  processIncludedFileWxsDependencies(importContent, importPath, scriptModule, components, processedPaths);
901
979
  }
902
980
  }
903
981
  });
904
982
  importNodes.remove();
905
- transAsses($, $("image"), sourcePath);
983
+ transAsses($, $("image"), sourcePath, path2);
906
984
  const res = [];
907
985
  transHtmlTag($.html(), res, components, componentPlaceholder);
908
986
  return {
909
987
  tpl: res.join(""),
988
+ sourceInfo: {
989
+ path: diagnosticSource,
990
+ content: originalContent
991
+ },
910
992
  instruction: {
911
993
  templateModule,
912
994
  scriptModule
913
995
  }
914
996
  };
915
997
  }
916
- function transTagTemplate($, templateModule, path2, components, componentPlaceholder) {
998
+ function transTagTemplate($, templateModule, path2, components, componentPlaceholder, sourceInfo, graphOwnerPath = path2) {
917
999
  const templateNodes = $("template[name]");
918
1000
  templateNodes.each((_, elem) => {
919
1001
  const name = $(elem).attr("name");
@@ -921,20 +1003,34 @@ function transTagTemplate($, templateModule, path2, components, componentPlaceho
921
1003
  templateContent.find("import").remove();
922
1004
  templateContent.find("include").remove();
923
1005
  templateContent.find(getViewScriptTags().join(",")).remove();
924
- transAsses($, templateContent.find("image"), path2);
1006
+ transAsses($, templateContent.find("image"), path2, graphOwnerPath);
925
1007
  const res = [];
926
1008
  transHtmlTag(templateContent.html(), res, components, componentPlaceholder);
927
1009
  templateModule.push({
928
1010
  path: `tpl-${name}`,
929
- tpl: res.join("")
1011
+ tpl: res.join(""),
1012
+ sourceInfo: sourceInfo ? {
1013
+ ...sourceInfo,
1014
+ startLine: getSourceLine(sourceInfo.content, elem.children?.[0]?.startIndex ?? elem.startIndex)
1015
+ } : null
930
1016
  });
931
1017
  });
932
1018
  templateNodes.remove();
933
1019
  }
934
- function transAsses($, imageNodes, path2) {
1020
+ function getSourceLine(source, index = 0) {
1021
+ return source.slice(0, Math.max(0, index)).split("\n").length;
1022
+ }
1023
+ function transAsses($, imageNodes, path2, graphOwnerPath = path2) {
935
1024
  imageNodes.each((_, elem) => {
936
1025
  const imgSrc = $(elem).attr("src").trim();
937
1026
  if (!imgSrc.startsWith("{{")) {
1027
+ if (!imgSrc.startsWith("http") && !imgSrc.startsWith("//") && /\.(?:png|jpe?g|gif|svg)(?:\?.*)?$/.test(imgSrc)) {
1028
+ getDependencyGraph().addFile(
1029
+ graphOwnerPath,
1030
+ resolveAssetSourcePath(getWorkPath(), path2, imgSrc),
1031
+ "view"
1032
+ );
1033
+ }
938
1034
  $(elem).attr("src", collectAssets(getWorkPath(), path2, imgSrc, getTargetPath(), getAppId()));
939
1035
  }
940
1036
  });
@@ -942,7 +1038,8 @@ function transAsses($, imageNodes, path2) {
942
1038
  var DIMINA_SLOT_GROUP_TAG = "dimina-slot-group";
943
1039
  var DIMINA_FOR_SCOPE_TAG = "dimina-for-scope";
944
1040
  function getDirectiveAttributeNames(attrs, suffixes) {
945
- return Object.keys(attrs || {}).filter((name) => suffixes.some((suffix) => name.endsWith(suffix)));
1041
+ const directiveNames = new Set(suffixes.map((suffix) => suffix.replace(/^:/, "")));
1042
+ return Object.keys(attrs || {}).filter((name) => directiveNames.has(getTemplateDirectiveName(name)));
946
1043
  }
947
1044
  function hasForAndIf(attrs) {
948
1045
  return getDirectiveAttributeNames(attrs, [":for", ":for-items"]).length > 0 && getDirectiveAttributeNames(attrs, [":if"]).length > 0;
@@ -1120,28 +1217,29 @@ function getProps(attrs, tag, components) {
1120
1217
  });
1121
1218
  }
1122
1219
  Object.entries(attrs).forEach(([name, value]) => {
1123
- if (name.endsWith(":if")) {
1220
+ const templateDirective = getTemplateDirectiveName(name);
1221
+ if (templateDirective === "if") {
1124
1222
  attrsList.push({
1125
1223
  name: "v-if",
1126
1224
  value: parseSafeBraceExp(value)
1127
1225
  });
1128
- } else if (name.endsWith(":elif")) {
1226
+ } else if (templateDirective === "elif") {
1129
1227
  attrsList.push({
1130
1228
  name: "v-else-if",
1131
1229
  value: parseSafeBraceExp(value)
1132
1230
  });
1133
- } else if (name.endsWith(":else")) {
1231
+ } else if (templateDirective === "else") {
1134
1232
  attrsList.push({
1135
1233
  name: "v-else",
1136
1234
  value: ""
1137
1235
  });
1138
- } else if (name.endsWith(":for") || name.endsWith(":for-items")) {
1236
+ } else if (templateDirective === "for" || templateDirective === "for-items") {
1139
1237
  attrsList.push({
1140
1238
  name: "v-for",
1141
1239
  value: parseForExp(value, attrs)
1142
1240
  });
1143
- } else if (name.endsWith(":for-item") || name.endsWith(":for-index")) {
1144
- } else if (name.endsWith(":key")) {
1241
+ } else if (templateDirective === "for-item" || templateDirective === "for-index") {
1242
+ } else if (templateDirective === "key") {
1145
1243
  const tranValue = parseKeyExpression(value, getForItemName(attrs), getForIndexName(attrs));
1146
1244
  attrsList.push({
1147
1245
  name: ":key",
@@ -1401,7 +1499,7 @@ function parseClassRules(cssRule) {
1401
1499
  }
1402
1500
  function getForItemName(attrs) {
1403
1501
  for (const key in attrs) {
1404
- if (key.endsWith(":for-item")) {
1502
+ if (getTemplateDirectiveName(key) === "for-item") {
1405
1503
  return attrs[key];
1406
1504
  }
1407
1505
  }
@@ -1409,7 +1507,7 @@ function getForItemName(attrs) {
1409
1507
  }
1410
1508
  function getForIndexName(attrs) {
1411
1509
  for (const key in attrs) {
1412
- if (key.endsWith(":for-index")) {
1510
+ if (getTemplateDirectiveName(key) === "for-index") {
1413
1511
  return attrs[key];
1414
1512
  }
1415
1513
  }
@@ -1461,7 +1559,7 @@ function parseTemplateDataExp(exp) {
1461
1559
  }
1462
1560
  return `{${parseSafeBraceExp(exp)}}`;
1463
1561
  }
1464
- function transTagWxs($, scriptModule, filePath) {
1562
+ function transTagWxs($, scriptModule, filePath, graphOwnerPath = filePath) {
1465
1563
  const wxsNodes = $(getViewScriptTags().join(","));
1466
1564
  wxsNodes.each((_, elem) => {
1467
1565
  const smName = $(elem).attr("module");
@@ -1481,6 +1579,7 @@ function transTagWxs($, scriptModule, filePath) {
1481
1579
  wxsFilePath = getAbsolutePath(workPath, filePath, src);
1482
1580
  }
1483
1581
  if (wxsFilePath) {
1582
+ getDependencyGraph().addFile(graphOwnerPath, wxsFilePath, "view");
1484
1583
  const relativePath = stripViewScriptExt(wxsFilePath.replace(workPath, ""));
1485
1584
  uniqueModuleName = relativePath.replace(/[\/\\@\-]/g, "_").replace(/^_/, "");
1486
1585
  cacheKey = wxsFilePath;
@@ -1502,7 +1601,7 @@ function transTagWxs($, scriptModule, filePath) {
1502
1601
  if (!wxsContent) {
1503
1602
  return;
1504
1603
  }
1505
- wxsContent = processWxsContent(wxsContent, wxsFilePath, scriptModule, workPath, filePath);
1604
+ wxsContent = processWxsContent(wxsContent, wxsFilePath, scriptModule, workPath, filePath, graphOwnerPath);
1506
1605
  compileResCache.set(cacheKey, wxsContent);
1507
1606
  }
1508
1607
  if (wxsContent) {
@@ -1586,7 +1685,7 @@ function extractWxsDependencies(moduleCode) {
1586
1685
  }
1587
1686
  return dependencies;
1588
1687
  }
1589
- function insertWxsToRenderCode(code, scriptModule, scriptRes, filename = "render.js") {
1688
+ function insertWxsToRenderResult(code, scriptModule, scriptRes, filename = "render.js", inputMap = null) {
1590
1689
  const wxsBindings = [];
1591
1690
  const codeReplacements = [];
1592
1691
  const ast = parseJs(code, filename);
@@ -1640,11 +1739,35 @@ ${declarations.join("\n")}`
1640
1739
  }
1641
1740
  });
1642
1741
  if (codeReplacements.length === 0) {
1643
- return getProgramCode(code, ast);
1742
+ return { code: getProgramCode(code, ast), map: inputMap };
1644
1743
  }
1645
1744
  const transformed = applyCodeReplacements(code, codeReplacements);
1745
+ let map = inputMap;
1746
+ if (enableSourcemap) {
1747
+ const generatedMap = new MagicString(code);
1748
+ const selected = [];
1749
+ for (const replacement of [...codeReplacements].sort((a, b) => b.end - b.start - (a.end - a.start))) {
1750
+ if (!selected.some((item) => replacement.start < item.end && item.start < replacement.end)) {
1751
+ selected.push(replacement);
1752
+ }
1753
+ }
1754
+ for (const replacement of selected.sort((a, b) => b.start - a.start)) {
1755
+ if (replacement.type === "insert") {
1756
+ generatedMap.appendLeft(replacement.start, replacement.value);
1757
+ } else {
1758
+ generatedMap.overwrite(replacement.start, replacement.end, replacement.value);
1759
+ }
1760
+ }
1761
+ const wxsTransformMap = generatedMap.generateMap({
1762
+ file: filename,
1763
+ source: filename,
1764
+ includeContent: true,
1765
+ hires: true
1766
+ }).toString();
1767
+ map = inputMap ? remapSourcemap(wxsTransformMap, inputMap) : wxsTransformMap;
1768
+ }
1646
1769
  const transformedAst = parseJs(transformed, filename);
1647
- return getProgramCode(transformed, transformedAst);
1770
+ return { code: getProgramCode(transformed, transformedAst), map };
1648
1771
  }
1649
1772
  function __resetViewState() {
1650
1773
  compileResCache.clear();