@deveco/deveco-cli-common 1.3.12 → 1.3.13-alpha

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 (48) hide show
  1. package/NOTICE +4982 -0
  2. package/README.md +163 -29
  3. package/dist/cli.js +266 -240
  4. package/dist/internal/telemetry-upload-background.js +10 -10
  5. package/package.json +6 -4
  6. package/skills/deveco-cli/SKILL.md +68 -19
  7. package/skills/deveco-cli/docs/arkts-rules.md +33 -0
  8. package/skills/deveco-cli/docs/design2arkts.md +276 -0
  9. package/skills/hmos-dfx-analyzer/SKILL.md +42 -8
  10. package/skills/hmos-dfx-analyzer/references/report-encoding-pitfalls.md +41 -0
  11. package/skills/hmos-dfx-analyzer/scripts/export_report.py +10 -4
  12. package/skills/hmos-dfx-analyzer/test-cases/functional.md +54 -6
  13. package/skills/hmos-dfx-analyzer/test-cases/smoke.md +40 -3
  14. package/skills/hmos-dfx-analyzer/test-cases/trigger.md +21 -2
  15. package/skills/index.json +2 -2
  16. package/src/resources/arkts-check.cjs +783 -96
  17. package/templates/application/template.json +8 -0
  18. package/templates/native-cpp/AppScope/app.json5 +10 -0
  19. package/templates/native-cpp/AppScope/resources/base/element/string.json +8 -0
  20. package/templates/native-cpp/AppScope/resources/base/media/layered_image.json +7 -0
  21. package/templates/native-cpp/build-profile.json5 +43 -0
  22. package/templates/native-cpp/code-linter.json5 +32 -0
  23. package/templates/native-cpp/entry/build-profile.json5 +48 -0
  24. package/templates/native-cpp/entry/gitignore.txt +6 -0
  25. package/templates/native-cpp/entry/hvigorfile.ts +6 -0
  26. package/templates/native-cpp/entry/obfuscation-rules.txt +20 -0
  27. package/templates/native-cpp/entry/oh-package.json5 +11 -0
  28. package/templates/native-cpp/entry/src/main/cpp/CMakeLists.txt +15 -0
  29. package/templates/native-cpp/entry/src/main/cpp/napi_init.cpp +67 -0
  30. package/templates/native-cpp/entry/src/main/cpp/types/libentry/Index.d.ts +16 -0
  31. package/templates/native-cpp/entry/src/main/cpp/types/libentry/oh-package.json5 +6 -0
  32. package/templates/native-cpp/entry/src/main/ets/entryability/EntryAbility.ets +63 -0
  33. package/templates/native-cpp/entry/src/main/ets/entrybackupability/EntryBackupAbility.ets +31 -0
  34. package/templates/native-cpp/entry/src/main/ets/pages/Index.ets +26 -0
  35. package/templates/native-cpp/entry/src/main/module.json5 +50 -0
  36. package/templates/native-cpp/entry/src/main/resources/base/element/color.json +8 -0
  37. package/templates/native-cpp/entry/src/main/resources/base/element/float.json +8 -0
  38. package/templates/native-cpp/entry/src/main/resources/base/element/string.json +16 -0
  39. package/templates/native-cpp/entry/src/main/resources/base/media/layered_image.json +7 -0
  40. package/templates/native-cpp/entry/src/main/resources/base/profile/backup_config.json +3 -0
  41. package/templates/native-cpp/entry/src/main/resources/base/profile/main_pages.json +5 -0
  42. package/templates/native-cpp/entry/src/main/resources/dark/element/color.json +8 -0
  43. package/templates/native-cpp/gitignore.txt +13 -0
  44. package/templates/native-cpp/hvigor/hvigor-config.json5 +23 -0
  45. package/templates/native-cpp/hvigorfile.ts +6 -0
  46. package/templates/native-cpp/oh-package.json5 +10 -0
  47. package/templates/native-cpp/template.json +8 -0
  48. package/THIRD-PARTY-LICENSES +0 -76
@@ -3,6 +3,7 @@
3
3
 
4
4
  const path = require('path');
5
5
  const fs = require('fs');
6
+ const { createRequire } = require('module');
6
7
 
7
8
  // --- Argument parsing ---
8
9
 
@@ -73,6 +74,43 @@ function findEtsLoader(devecoHome) {
73
74
  return null;
74
75
  }
75
76
 
77
+ // Resolves `BuildProfile` per importer when set; see loadEtsChecker.
78
+ let resolveBuildProfilePath;
79
+
80
+ // BuildProfile is per-module, but one checker run resolves every module's
81
+ // `import ... from 'BuildProfile'` through the same wildcard `paths` (issue
82
+ // #688 1b). Wrap the SDK's own typescript `resolveModuleName` while loading the
83
+ // checker so `BuildProfile` resolves against the importer's module instead.
84
+ // The checker keeps the wrapped reference, reading resolveBuildProfilePath on
85
+ // each call; the rest of the process keeps the original module.
86
+ function loadEtsChecker(etsLoaderPath) {
87
+ const checkerPath = path.join(etsLoaderPath, 'lib', 'ets_checker.js');
88
+ if (require.cache[checkerPath]) return require(checkerPath);
89
+
90
+ const sdkRequire = createRequire(checkerPath);
91
+ const compilerPath = sdkRequire.resolve('typescript');
92
+ const compiler = sdkRequire(compilerPath);
93
+ const descriptors = Object.getOwnPropertyDescriptors(compiler);
94
+ const resolveModuleName = compiler.resolveModuleName;
95
+ descriptors.resolveModuleName = {
96
+ enumerable: true,
97
+ value(name, importer, options, host, ...rest) {
98
+ const profile = name === 'BuildProfile' && resolveBuildProfilePath?.(importer);
99
+ if (!profile) return resolveModuleName(name, importer, options, host, ...rest);
100
+ return resolveModuleName(
101
+ name, importer, { ...options, paths: { BuildProfile: [profile] } }, host, ...rest,
102
+ );
103
+ },
104
+ };
105
+ const compilerModule = require.cache[compilerPath];
106
+ compilerModule.exports = Object.create(Object.getPrototypeOf(compiler), descriptors);
107
+ try {
108
+ return require(checkerPath);
109
+ } finally {
110
+ compilerModule.exports = compiler;
111
+ }
112
+ }
113
+
76
114
  // --- Collect .ets files from project ---
77
115
 
78
116
  function collectEtsFiles(projectPath) {
@@ -198,6 +236,12 @@ function computeEpoch(projectPath, devecoHome) {
198
236
  for (const abs of collectAmbientDeclarations(projectPath)) {
199
237
  parts.push(path.relative(projectPath, abs), fileHash(abs));
200
238
  }
239
+ // Per-module BuildProfile is resolved by importer (loadEtsChecker), so a
240
+ // regenerated profile changes a file's diagnostics without touching that file.
241
+ for (const { genDir } of moduleDirEntries(projectPath)) {
242
+ const profile = path.join(genDir, 'BuildProfile.ets');
243
+ if (fs.existsSync(profile)) parts.push(path.relative(projectPath, profile), fileHash(profile));
244
+ }
201
245
  return hashText(parts.join('\n'));
202
246
  }
203
247
 
@@ -362,8 +406,191 @@ const APP_RESOURCE_REF_RE = /\$r\(\s*['"]app\.([a-z]+)\.([A-Za-z0-9_]+)['"]\s*\)
362
406
  // so an unknown-name check does not apply to them here.
363
407
  const APP_RESOURCE_INDEXED_KINDS = new Set(['media', 'color', 'string', 'float', 'integer', 'boolean', 'intarray', 'strarray', 'pattern', 'plural', 'profile', 'symbol']);
364
408
 
409
+ // Keywords after which a `/` begins a regex literal even though the preceding
410
+ // char is an identifier char (computeCommentStringSpans).
411
+ const REGEX_AFTER_KEYWORDS = new Set([
412
+ 'return', 'typeof', 'case', 'in', 'of', 'new', 'delete', 'void',
413
+ 'throw', 'do', 'else', 'instanceof', 'yield', 'await',
414
+ ]);
415
+
416
+ // End (exclusive) of a regex literal starting at `start`, or -1 when the slash
417
+ // is division. A quote inside a regex (e.g. /'/) must not open a string span,
418
+ // or every following $r('app.*') reference is masked (issue #710). `/` is
419
+ // division when the preceding token can end an expression, unless that token
420
+ // is a keyword (return /x/, typeof /x/) where a regex follows.
421
+ function regexLiteralEnd(line, start) {
422
+ let k = start - 1;
423
+ while (k >= 0 && (line[k] === ' ' || line[k] === '\t')) k--;
424
+ const prev = k >= 0 ? line[k] : '';
425
+ let isRegex = !/[\w$)\]}]/.test(prev);
426
+ if (!isRegex && /[A-Za-z$]/.test(prev)) {
427
+ let w = k;
428
+ while (w >= 0 && /[\w$]/.test(line[w])) w--;
429
+ if (REGEX_AFTER_KEYWORDS.has(line.slice(w + 1, k + 1))) isRegex = true;
430
+ }
431
+ if (!isRegex) return -1;
432
+ let j = start + 1;
433
+ let inClass = false;
434
+ for (; j < line.length; j++) {
435
+ const c = line[j];
436
+ if (c === '\\') { j++; continue; }
437
+ if (c === '[') inClass = true;
438
+ else if (c === ']') inClass = false;
439
+ else if (c === '/' && !inClass) break;
440
+ }
441
+ if (j >= line.length) return -1;
442
+ j++;
443
+ while (j < line.length && /[a-z]/.test(line[j])) j++; // flags
444
+ return j;
445
+ }
446
+
447
+ // Comment/string spans of one source line, for telling real `$r('app.*')`
448
+ // calls from mere mentions in comments or string literals (issue #688).
449
+ // `state.block` carries an unterminated `/*` block comment across lines;
450
+ // `state.stringQuote` likewise carries an unterminated string/template across
451
+ // lines (continuation lines stay string until the closing quote — multi-line
452
+ // template `${}` is NOT re-opened as code, the same safe-direction miss as the
453
+ // single-line interpolation skip).
454
+ // Returns [{ start, end }] half-open spans; positions are preserved so
455
+ // match indices stay valid against the original line.
456
+ function computeCommentStringSpans(line, state) {
457
+ const spans = [];
458
+ const n = line.length;
459
+ let i = 0;
460
+ if (state.stringQuote) {
461
+ let j = 0;
462
+ while (j < n) {
463
+ if (line[j] === '\\') { j += 2; continue; }
464
+ if (line[j] === state.stringQuote) break;
465
+ j++;
466
+ }
467
+ if (j >= n) { spans.push({ start: 0, end: n }); return spans; }
468
+ spans.push({ start: 0, end: j + 1 });
469
+ state.stringQuote = null;
470
+ i = j + 1;
471
+ }
472
+ while (i < n) {
473
+ if (state.block) {
474
+ const end = line.indexOf('*/', i);
475
+ if (end === -1) { spans.push({ start: i, end: n }); i = n; continue; }
476
+ spans.push({ start: i, end: end + 2 });
477
+ state.block = false;
478
+ i = end + 2;
479
+ continue;
480
+ }
481
+ const ch = line[i];
482
+ const next = line[i + 1];
483
+ if (ch === '/' && next === '/') { spans.push({ start: i, end: n }); break; }
484
+ if (ch === '/' && next === '*') {
485
+ const end = line.indexOf('*/', i + 2);
486
+ if (end === -1) { spans.push({ start: i, end: n }); state.block = true; break; }
487
+ spans.push({ start: i, end: end + 2 });
488
+ i = end + 2;
489
+ continue;
490
+ }
491
+ // Regex literals are skipped whole so their quotes cannot open a string
492
+ // span (issue #710); -1 means this slash is division or unterminated.
493
+ if (ch === '/') {
494
+ const regexEnd = regexLiteralEnd(line, i);
495
+ if (regexEnd > i) { i = regexEnd; continue; }
496
+ }
497
+ if (ch === "'" || ch === '"' || ch === '`') {
498
+ const quote = ch;
499
+ let j = i + 1;
500
+ while (j < n) {
501
+ if (line[j] === '\\') { j += 2; continue; }
502
+ if (line[j] === quote) break;
503
+ if (quote === '`' && line[j] === '$' && line[j + 1] === '{') {
504
+ let depth = 1;
505
+ j += 2;
506
+ while (j < n && depth > 0) {
507
+ if (line[j] === '{') depth++;
508
+ else if (line[j] === '}') depth--;
509
+ j++;
510
+ }
511
+ continue;
512
+ }
513
+ j++;
514
+ }
515
+ if (j >= n) {
516
+ // Unterminated on this line: the string continues on the next line.
517
+ spans.push({ start: i, end: n });
518
+ state.stringQuote = quote;
519
+ i = n;
520
+ continue;
521
+ }
522
+ const end = j + 1;
523
+ spans.push({ start: i, end });
524
+ i = end;
525
+ continue;
526
+ }
527
+ i++;
528
+ }
529
+ return spans;
530
+ }
531
+
532
+ // Collect the resource names of one module into `names`.
533
+ function collectModuleResourceNames(modulePath, names) {
534
+ const resourcesDir = path.join(modulePath, 'src', 'main', 'resources');
535
+ let qualifiers;
536
+ try {
537
+ qualifiers = fs.readdirSync(resourcesDir, { withFileTypes: true }).filter((d) => d.isDirectory());
538
+ } catch {
539
+ return;
540
+ }
541
+
542
+ for (const qualifier of qualifiers) {
543
+ const qualifierDir = path.join(resourcesDir, qualifier.name);
544
+
545
+ // media/profile: the file's basename (minus extension) is the resource name.
546
+ for (const kind of ['media', 'profile']) {
547
+ const kindDir = path.join(qualifierDir, kind);
548
+ let files;
549
+ try { files = fs.readdirSync(kindDir); } catch { continue; }
550
+ for (const file of files) {
551
+ names.add(`${kind}.${file.replace(/\.[^.]+$/, '')}`);
552
+ }
553
+ }
554
+
555
+ // element/*.json: {"color": [{"name": "primary", ...}], ...}
556
+ const elementDir = path.join(qualifierDir, 'element');
557
+ let elementFiles;
558
+ try { elementFiles = fs.readdirSync(elementDir); } catch { continue; }
559
+ for (const file of elementFiles) {
560
+ if (!file.endsWith('.json')) continue;
561
+ let parsed;
562
+ try {
563
+ parsed = JSON.parse(fs.readFileSync(path.join(elementDir, file), 'utf-8'));
564
+ } catch {
565
+ // A malformed element file is its own build error; skipping it here
566
+ // only means we cannot vouch for names it would have defined, and the
567
+ // unknown-name diagnostics below are suppressed for that kind.
568
+ continue;
569
+ }
570
+ for (const [kind, entries] of Object.entries(parsed)) {
571
+ if (!Array.isArray(entries)) continue;
572
+ for (const entry of entries) {
573
+ if (entry && typeof entry.name === 'string') names.add(`${kind}.${entry.name}`);
574
+ }
575
+ }
576
+ }
577
+ }
578
+ }
579
+
365
580
  function loadAppResourceNames(projectPath) {
366
581
  const names = new Set();
582
+
583
+ // Authoritative module list from build-profile.json5 first: modules can
584
+ // nest (e.g. commons/lib_foundation), and the flat top-level scan below
585
+ // never reaches their resources (issue #688).
586
+ const declared = readProjectModules(projectPath).modules;
587
+ if (declared.length > 0) {
588
+ for (const mod of declared) {
589
+ collectModuleResourceNames(path.resolve(projectPath, mod.srcPath), names);
590
+ }
591
+ return names;
592
+ }
593
+
367
594
  let moduleDirs;
368
595
  try {
369
596
  moduleDirs = fs.readdirSync(projectPath, { withFileTypes: true }).filter((d) => d.isDirectory());
@@ -373,50 +600,7 @@ function loadAppResourceNames(projectPath) {
373
600
 
374
601
  for (const mod of moduleDirs) {
375
602
  if (mod.name === 'node_modules' || mod.name === 'oh_modules' || mod.name.startsWith('.')) continue;
376
- const resourcesDir = path.join(projectPath, mod.name, 'src', 'main', 'resources');
377
- let qualifiers;
378
- try {
379
- qualifiers = fs.readdirSync(resourcesDir, { withFileTypes: true }).filter((d) => d.isDirectory());
380
- } catch {
381
- continue;
382
- }
383
-
384
- for (const qualifier of qualifiers) {
385
- const qualifierDir = path.join(resourcesDir, qualifier.name);
386
-
387
- // media/profile: the file's basename (minus extension) is the resource name.
388
- for (const kind of ['media', 'profile']) {
389
- const kindDir = path.join(qualifierDir, kind);
390
- let files;
391
- try { files = fs.readdirSync(kindDir); } catch { continue; }
392
- for (const file of files) {
393
- names.add(`${kind}.${file.replace(/\.[^.]+$/, '')}`);
394
- }
395
- }
396
-
397
- // element/*.json: {"color": [{"name": "primary", ...}], ...}
398
- const elementDir = path.join(qualifierDir, 'element');
399
- let elementFiles;
400
- try { elementFiles = fs.readdirSync(elementDir); } catch { continue; }
401
- for (const file of elementFiles) {
402
- if (!file.endsWith('.json')) continue;
403
- let parsed;
404
- try {
405
- parsed = JSON.parse(fs.readFileSync(path.join(elementDir, file), 'utf-8'));
406
- } catch {
407
- // A malformed element file is its own build error; skipping it here
408
- // only means we cannot vouch for names it would have defined, and the
409
- // unknown-name diagnostics below are suppressed for that kind.
410
- continue;
411
- }
412
- for (const [kind, entries] of Object.entries(parsed)) {
413
- if (!Array.isArray(entries)) continue;
414
- for (const entry of entries) {
415
- if (entry && typeof entry.name === 'string') names.add(`${kind}.${entry.name}`);
416
- }
417
- }
418
- }
419
- }
603
+ collectModuleResourceNames(path.join(projectPath, mod.name), names);
420
604
  }
421
605
  return names;
422
606
  }
@@ -439,10 +623,15 @@ function validateAppResources(files, projectPath) {
439
623
  try { content = fs.readFileSync(filePath, 'utf-8'); } catch { continue; }
440
624
  const relFile = path.relative(projectPath, filePath);
441
625
  const fileLines = content.split('\n');
626
+ const commentState = { block: false, stringQuote: null };
442
627
  for (let i = 0; i < fileLines.length; i++) {
628
+ const spans = computeCommentStringSpans(fileLines[i], commentState);
443
629
  let match;
444
630
  APP_RESOURCE_REF_RE.lastIndex = 0;
445
631
  while ((match = APP_RESOURCE_REF_RE.exec(fileLines[i])) !== null) {
632
+ // A `$r('app.*')` mention inside a comment or another string literal
633
+ // is not a real reference — only validate calls in actual code.
634
+ if (spans.some((s) => match.index >= s.start && match.index < s.end)) continue;
446
635
  const kind = match[1];
447
636
  const resName = match[2];
448
637
  if (!APP_RESOURCE_INDEXED_KINDS.has(kind)) continue;
@@ -886,14 +1075,16 @@ function validateComponentDecorators(files, projectPath) {
886
1075
  // decorator vs. its OWN struct's decorator), this needs real cross-file
887
1076
  // resolution — the property's decorator lives in the component file, but the
888
1077
  // referenced type's @ObservedV2 decorator often lives in a different model
889
- // file entirely. Implemented as two passes over the whole project file set:
890
- // 1) index every top-level class decorated with @ObservedV2, by name
1078
+ // file entirely. Implemented in two passes over the whole project file set:
1079
+ // 1) index every top-level class with its decorator set, per file
891
1080
  // 2) flag every @State/@Prop/@Provide/@Consume property whose simple type
892
- // annotation matches a name in that index
893
- // Deliberately name-keyed (no module/import resolution): two same-named
894
- // classes in different files where only one is @ObservedV2 would be a false
895
- // negative, but that pattern does not occur in generated ArkTS and a real
896
- // symbol table is out of scope for this lightweight heuristic.
1081
+ // resolves — via imports, aliases and re-export chains — to a class that
1082
+ // is decorated @ObservedV2
1083
+ // A usage whose type origin cannot be resolved (bare package or ambient
1084
+ // import) falls back to the conservative global name index, so genuinely V2
1085
+ // types keep being detected. Name-only matching is not enough: two
1086
+ // same-named classes in different files, only one of them @ObservedV2, are
1087
+ // common once pages and models split (issue #688).
897
1088
  const V1_TYPE_SENSITIVE_DECORATORS = new Set(['State', 'Prop', 'Provide', 'Consume']);
898
1089
 
899
1090
  const CLASS_DECL_RE = /^(\s*)((?:@\w+(?:\([^)]*\))?\s*)*)(?:export\s+(?:default\s+)?)?class\s+(\w+)\b/;
@@ -935,22 +1126,209 @@ const SDK_OBSERVED_V2_CLASSES = new Set();
935
1126
  // false positive on a file the caller did not ask about.
936
1127
  function collectObservedV2ClassNames(files, projectPath) {
937
1128
  const names = new Set(SDK_OBSERVED_V2_CLASSES);
1129
+ const index = buildProjectClassIndex(files, projectPath);
1130
+ for (const perFile of index.values()) {
1131
+ for (const [name, entry] of perFile) {
1132
+ if (entry.decorators.has('ObservedV2')) names.add(name);
1133
+ }
1134
+ }
1135
+ return names;
1136
+ }
1137
+
1138
+ // --- Import-aware class origin resolution (issue #688) ---
1139
+ //
1140
+ // Same-named classes in different files must not be decided by a global name
1141
+ // set: `@Provide model: Model` is only a violation when the Model IMPORTED at
1142
+ // that usage site is the @ObservedV2 one. These helpers follow a file's
1143
+ // named/default imports and `export ... from` re-export chains (aliases
1144
+ // included) to the declaring file, then read that class's decorators. Bare
1145
+ // package or unresolvable specifiers yield null and callers fall back to the
1146
+ // conservative global name set.
1147
+
1148
+ // classIndexCache: projectPath -> Map(absFile -> Map(className -> { decorators, isDefault })).
1149
+ // Cached per project like projectEtsFileCache; cleared per request in serve mode.
1150
+ const classIndexCache = new Map();
1151
+
1152
+ function buildProjectClassIndex(files, projectPath) {
1153
+ const cached = projectPath ? classIndexCache.get(projectPath) : null;
1154
+ if (cached) return cached;
938
1155
  const declarationFiles = projectPath ? unionProjectFiles(files, projectPath) : files;
1156
+ const index = new Map();
939
1157
  for (const filePath of declarationFiles) {
940
1158
  let content;
941
1159
  try { content = fs.readFileSync(filePath, 'utf-8'); } catch { continue; }
942
1160
  const lines = content.split('\n');
1161
+ const perFile = new Map();
943
1162
  for (let i = 0; i < lines.length; i++) {
944
1163
  const m = CLASS_DECL_RE.exec(lines[i]);
945
1164
  if (!m) continue;
946
1165
  const decorators = collectStructDecorators(lines, i, m[2]);
947
- if (decorators.has('ObservedV2')) names.add(m[3]);
1166
+ perFile.set(m[3], { decorators, isDefault: /export\s+default\s+class\b/.test(lines[i]) });
948
1167
  }
1168
+ index.set(path.resolve(filePath), perFile);
949
1169
  }
950
- return names;
1170
+ if (projectPath) classIndexCache.set(projectPath, index);
1171
+ return index;
1172
+ }
1173
+
1174
+ // fileImportCache: absFile -> Map(localName -> { spec, remote }); remote is
1175
+ // the name exported by the target module ('*default*' for default imports).
1176
+ // Plain imports and `export ... from` re-exports both land here, so barrel
1177
+ // files resolve transparently.
1178
+ const fileImportCache = new Map();
1179
+
1180
+ const FROM_CLAUSE_RE = /(?:^|\n)[ \t]*(?:import|export)[ \t]+(?:type[ \t]+)?([\s\S]*?)[ \t]*from[ \t]*['"]([^'"]+)['"]/g;
1181
+
1182
+ // Flags every offset that lies inside a comment or string span, so callers can
1183
+ // reject a regex match whose start is not real code — a `from` inside a
1184
+ // comment or string would otherwise bind a fake local name and shadow the true
1185
+ // import of the same name (issue #710). The import specifier itself is a
1186
+ // string span, but the match starts at `import`/`export`, outside it.
1187
+ function maskedOffsets(content) {
1188
+ const state = { block: false };
1189
+ const flags = new Uint8Array(content.length);
1190
+ let offset = 0;
1191
+ for (const line of content.split('\n')) {
1192
+ for (const s of computeCommentStringSpans(line, state)) {
1193
+ flags.fill(1, offset + s.start, offset + s.end);
1194
+ }
1195
+ offset += line.length + 1;
1196
+ }
1197
+ return flags;
1198
+ }
1199
+
1200
+ // Start offset of the leading `import`/`export` keyword in a FROM_CLAUSE_RE
1201
+ // match. The match itself begins at the preceding newline, which is outside
1202
+ // any span even when the keyword line sits inside a multi-line string.
1203
+ function clauseKeywordOffset(m) {
1204
+ return m.index + m[0].search(/import|export/);
1205
+ }
1206
+
1207
+ function getFileBindings(absFile) {
1208
+ const cached = fileImportCache.get(absFile);
1209
+ if (cached) return cached;
1210
+ const bindings = new Map();
1211
+ let content;
1212
+ try {
1213
+ content = fs.readFileSync(absFile, 'utf-8');
1214
+ } catch {
1215
+ fileImportCache.set(absFile, bindings);
1216
+ return bindings;
1217
+ }
1218
+ const masked = maskedOffsets(content);
1219
+ FROM_CLAUSE_RE.lastIndex = 0;
1220
+ for (;;) {
1221
+ const m = FROM_CLAUSE_RE.exec(content);
1222
+ if (!m) break;
1223
+ if (masked[clauseKeywordOffset(m)]) continue;
1224
+ const clause = m[1];
1225
+ const spec = m[2];
1226
+ const brace = /\{([^}]*)\}/.exec(clause);
1227
+ if (brace) {
1228
+ for (const part of brace[1].split(',')) {
1229
+ // `import { type Foo }` — strip the type-only marker before matching.
1230
+ const p = part.trim().replace(/^type[ \t]+/, '');
1231
+ if (!p) continue;
1232
+ const b = /^([A-Za-z_$][\w$]*)(?:\s+as\s+([A-Za-z_$][\w$]*))?$/.exec(p);
1233
+ if (b) bindings.set(b[2] || b[1], { spec, remote: b[1] });
1234
+ }
1235
+ }
1236
+ const head = clause
1237
+ .replace(/\{[^}]*\}/, '')
1238
+ .replace(/^\*\s+as\s+[A-Za-z_$][\w$]*$/, '')
1239
+ .replace(/,\s*$/, '')
1240
+ .trim();
1241
+ const dm = /^([A-Za-z_$][\w$]*)$/.exec(head);
1242
+ if (dm) bindings.set(dm[1], { spec, remote: '*default*' });
1243
+ }
1244
+ fileImportCache.set(absFile, bindings);
1245
+ return bindings;
1246
+ }
1247
+
1248
+ // fileStarExportCache: absFile -> string[] of `export * from` specifiers. Star
1249
+ // re-exports bind no local name, so getFileBindings cannot see them; origin
1250
+ // resolution walks these explicitly.
1251
+ const fileStarExportCache = new Map();
1252
+
1253
+ const STAR_EXPORT_RE = /(?:^|\n)[ \t]*export[ \t]+\*[ \t]*from[ \t]*['"]([^'"]+)['"]/g;
1254
+
1255
+ function getFileStarExports(absFile) {
1256
+ const cached = fileStarExportCache.get(absFile);
1257
+ if (cached) return cached;
1258
+ const specs = [];
1259
+ let content;
1260
+ try {
1261
+ content = fs.readFileSync(absFile, 'utf-8');
1262
+ } catch {
1263
+ fileStarExportCache.set(absFile, specs);
1264
+ return specs;
1265
+ }
1266
+ const masked = maskedOffsets(content);
1267
+ STAR_EXPORT_RE.lastIndex = 0;
1268
+ for (;;) {
1269
+ const m = STAR_EXPORT_RE.exec(content);
1270
+ if (!m) break;
1271
+ if (masked[clauseKeywordOffset(m)]) continue;
1272
+ specs.push(m[1]);
1273
+ }
1274
+ fileStarExportCache.set(absFile, specs);
1275
+ return specs;
1276
+ }
1277
+
1278
+ function resolveClassOrigin(absFile, typeName, classIndex, visited) {
1279
+ if (!visited) visited = new Set();
1280
+ const step = absFile + '::' + typeName;
1281
+ if (visited.has(step) || visited.size >= 16) return null;
1282
+ visited.add(step);
1283
+ const binding = getFileBindings(absFile).get(typeName);
1284
+ if (!binding) {
1285
+ // No direct binding: the name may arrive via `export * from` — check each
1286
+ // star-exported module for the declaration, then follow its star chains.
1287
+ for (const spec of getFileStarExports(absFile)) {
1288
+ const target = resolveClosureDependency(absFile, spec);
1289
+ if (!target) continue;
1290
+ const targetAbs = path.resolve(target);
1291
+ const perFile = classIndex.get(targetAbs);
1292
+ if (perFile && perFile.has(typeName)) return { file: targetAbs, name: typeName };
1293
+ const found = resolveClassOrigin(targetAbs, typeName, classIndex, visited);
1294
+ if (found) return found;
1295
+ }
1296
+ return null;
1297
+ }
1298
+ const target = resolveClosureDependency(absFile, binding.spec);
1299
+ if (!target) return null;
1300
+ const targetAbs = path.resolve(target);
1301
+ const perFile = classIndex.get(targetAbs);
1302
+ if (!perFile) return null; // target outside the indexed project sources
1303
+ // `import X from` records '*default*'; `export { default as X } from` and
1304
+ // `import { default as X } from` record remote 'default' — both mean the
1305
+ // target module's default export (issue #710).
1306
+ if (binding.remote === '*default*' || binding.remote === 'default') {
1307
+ for (const [name, entry] of perFile) {
1308
+ if (entry.isDefault) return { file: targetAbs, name };
1309
+ }
1310
+ return null;
1311
+ }
1312
+ if (perFile.has(binding.remote)) return { file: targetAbs, name: binding.remote };
1313
+ // Not declared here (indirect barrel): follow the re-export chain onward.
1314
+ return resolveClassOrigin(targetAbs, binding.remote, classIndex, visited);
1315
+ }
1316
+
1317
+ // Verdict for one usage site (`@X prop: Type`, `new Type(...)`,
1318
+ // `AppStorage.setOrCreate<Type>`): resolve, then read the resolved class's
1319
+ // decorators; fall back to the global name set when unresolvable.
1320
+ function isObservedV2Usage(absFile, typeName, classIndex, fallbackNames) {
1321
+ if (!typeName) return false;
1322
+ const origin = resolveClassOrigin(absFile, typeName, classIndex);
1323
+ if (origin) {
1324
+ const entry = classIndex.get(origin.file)?.get(origin.name);
1325
+ return !!entry && entry.decorators.has('ObservedV2');
1326
+ }
1327
+ return fallbackNames.has(typeName);
951
1328
  }
952
1329
 
953
1330
  function validateObservedV2PropertyTypes(files, projectPath) {
1331
+ const classIndex = buildProjectClassIndex(files, projectPath);
954
1332
  const observedV2Classes = collectObservedV2ClassNames(files, projectPath);
955
1333
  if (observedV2Classes.size === 0) return [];
956
1334
 
@@ -960,12 +1338,13 @@ function validateObservedV2PropertyTypes(files, projectPath) {
960
1338
  try { content = fs.readFileSync(filePath, 'utf-8'); } catch { continue; }
961
1339
  const lines = content.split('\n');
962
1340
  const relFile = path.relative(projectPath, filePath);
1341
+ const absFile = path.resolve(filePath);
963
1342
  for (let i = 0; i < lines.length; i++) {
964
1343
  const m = STATE_PROPERTY_TYPE_RE.exec(lines[i]);
965
1344
  if (!m) continue;
966
1345
  const decoratorName = m[1];
967
1346
  const typeName = m[2];
968
- if (!observedV2Classes.has(typeName)) continue;
1347
+ if (!isObservedV2Usage(absFile, typeName, classIndex, observedV2Classes)) continue;
969
1348
  diagnostics.push({
970
1349
  file: relFile,
971
1350
  line: i + 1,
@@ -1897,6 +2276,7 @@ function validateAppStorageV2Mixing(files, projectPath) {
1897
2276
  // exactly what this index holds while SDK_OBSERVED_V2_CLASSES stays empty. If a
1898
2277
  // name is ever seeded there, re-check whether it also crashes AppStorage before
1899
2278
  // letting it reach this rule.
2279
+ const classIndex = buildProjectClassIndex(files, projectPath);
1900
2280
  const observedV2Classes = collectObservedV2ClassNames(files, projectPath);
1901
2281
  if (observedV2Classes.size === 0) return [];
1902
2282
 
@@ -1906,6 +2286,7 @@ function validateAppStorageV2Mixing(files, projectPath) {
1906
2286
  try { content = fs.readFileSync(filePath, 'utf-8'); } catch { continue; }
1907
2287
  const lines = content.split('\n');
1908
2288
  const relFile = path.relative(projectPath, filePath);
2289
+ const absFile = path.resolve(filePath);
1909
2290
 
1910
2291
  // Local `name: Type` declarations, so a bare `this.viewModel` argument can
1911
2292
  // be resolved back to its @ObservedV2 class.
@@ -1925,9 +2306,11 @@ function validateAppStorageV2Mixing(files, projectPath) {
1925
2306
  const argName = /^(?:this\s*\.\s*)?([A-Za-z_$][\w$]*)$/.exec(argExpr);
1926
2307
  const newed = /^new\s+([A-Za-z_$][\w$]*)/.exec(argExpr);
1927
2308
  const resolved =
1928
- (explicit && observedV2Classes.has(explicit) && explicit) ||
1929
- (newed && observedV2Classes.has(newed[1]) && newed[1]) ||
1930
- (argName && observedV2Classes.has(declaredTypes.get(argName[1])) && declaredTypes.get(argName[1]));
2309
+ (explicit && isObservedV2Usage(absFile, explicit, classIndex, observedV2Classes) && explicit) ||
2310
+ (newed && isObservedV2Usage(absFile, newed[1], classIndex, observedV2Classes) && newed[1]) ||
2311
+ (argName &&
2312
+ isObservedV2Usage(absFile, declaredTypes.get(argName[1]), classIndex, observedV2Classes) &&
2313
+ declaredTypes.get(argName[1]));
1931
2314
  if (!resolved) continue;
1932
2315
 
1933
2316
  diagnostics.push({
@@ -2320,9 +2703,17 @@ const STATE_DECORATORS = [
2320
2703
 
2321
2704
  // State-field decorator matcher. Compiled once at module load (the pattern is
2322
2705
  // built from the constant STATE_DECORATORS) instead of on every call. It carries
2323
- // the global flag, so reset lastIndex before each reuse.
2706
+ // the global flag, so reset lastIndex before each reuse. Between the state
2707
+ // decorator and the field name it tolerates stacked decorators (e.g.
2708
+ // `@Watch('onChanged')`) and access modifiers (`private`/`public`/`protected`/
2709
+ // `static`/`readonly`) — `@State private visible` must yield `visible`, not
2710
+ // `private`, and `@State @Watch('cb') selected` must yield `selected`, not
2711
+ // nothing.
2324
2712
  const STATE_FIELD_RE = new RegExp(
2325
- '@(?:' + STATE_DECORATORS.join('|') + ')(?:\\([^)]*\\))?\\s+([A-Za-z_$][\\w$]*)',
2713
+ '@(?:' + STATE_DECORATORS.join('|') + ')(?:\\([^)]*\\))?' +
2714
+ '(?:\\s+@\\w+(?:\\([^)]*\\))?)*' +
2715
+ '(?:\\s+(?:private|public|protected|static|readonly))*' +
2716
+ '\\s+([A-Za-z_$][\\w$]*)',
2326
2717
  'g',
2327
2718
  );
2328
2719
 
@@ -2898,6 +3289,23 @@ function buildProfileNotBuiltHint(projectPath) {
2898
3289
 
2899
3290
  const resolveModulePathsCache = new Map();
2900
3291
 
3292
+ // One place that derives a declared module's on-disk dirs; both
3293
+ // collectResolveModulePaths and groupFilesByModule compose their path lists
3294
+ // from these entries (issue #710 P3). genDir is exactly hvigor's
3295
+ // buildGeneratedProfilePath shape; a missing dir is simply not added —
3296
+ // runCheck then attaches buildProfileNotBuiltHint to the diagnostic.
3297
+ function moduleDirEntries(projectPath) {
3298
+ const { productName, modules } = readProjectModules(projectPath);
3299
+ return modules.map((m) => {
3300
+ const modulePath = path.resolve(projectPath, m.srcPath);
3301
+ return {
3302
+ modulePath,
3303
+ srcMain: path.join(modulePath, 'src', 'main'),
3304
+ genDir: path.join(modulePath, 'build', productName, 'generated', 'profile', m.target),
3305
+ };
3306
+ });
3307
+ }
3308
+
2901
3309
  function collectResolveModulePaths(projectPath) {
2902
3310
  const cached = resolveModulePathsCache.get(projectPath);
2903
3311
  if (cached) return cached;
@@ -2914,15 +3322,11 @@ function collectResolveModulePaths(projectPath) {
2914
3322
  } catch { /* ignore */ }
2915
3323
  };
2916
3324
 
2917
- const { productName, modules } = readProjectModules(projectPath);
2918
- if (modules.length > 0) {
2919
- for (const m of modules) {
2920
- const modulePath = path.resolve(projectPath, m.srcPath);
2921
- push(path.join(modulePath, 'src', 'main'));
2922
- // Exactly hvigor's buildGeneratedProfilePath shape. A missing dir (module
2923
- // not built for this product yet) is simply not added — runCheck then
2924
- // attaches buildProfileNotBuiltHint to the resulting diagnostic.
2925
- push(path.join(modulePath, 'build', productName, 'generated', 'profile', m.target));
3325
+ const entries = moduleDirEntries(projectPath);
3326
+ if (entries.length > 0) {
3327
+ for (const e of entries) {
3328
+ push(e.srcMain);
3329
+ push(e.genDir);
2926
3330
  }
2927
3331
  } else {
2928
3332
  // No declared modules (minimal or unparseable profile): fall back to
@@ -2978,6 +3382,160 @@ function findModuleSrcMainOnDisk(projectPath, push) {
2978
3382
  walkBuildGenerated(projectPath);
2979
3383
  }
2980
3384
 
3385
+ // Modules may import their own sources through the package name declared in the
3386
+ // module's oh-package.json5 (`import { Item } from '@sample/widget/ets/model/Item'`).
3387
+ // hvigor maps that name back to the module itself; the standalone checker has no
3388
+ // such mapping, and the SDK's wildcard `paths: {"*": [...]}` only tries each
3389
+ // resolveModulePaths entry as a literal prefix, so the import would resolve to
3390
+ // <module>/src/main/@sample/widget/... and fail. Mirror each declared package
3391
+ // name to the module's src/main via a link under .cache/arkts-check-pkgs and add
3392
+ // that dir to resolveModulePaths — the wildcard then maps the package specifier
3393
+ // to the real sources. Links share the checker cache's lifecycle and are removed
3394
+ // together with it, so nothing lingers in the project (issue #688).
3395
+ const SELF_PACKAGE_NAME_RE = /^(?:@[a-z0-9][\w.-]*\/)?[a-z0-9][\w.-]*$/i;
3396
+
3397
+ function collectSelfPackageRoots(projectPath) {
3398
+ const { modules } = readProjectModules(projectPath);
3399
+ const roots = [];
3400
+ const seen = new Set();
3401
+ for (const m of modules) {
3402
+ const modulePath = path.resolve(projectPath, m.srcPath);
3403
+ const srcMain = path.join(modulePath, 'src', 'main');
3404
+ let name = null;
3405
+ try {
3406
+ const parsed = parseJson5Loose(fs.readFileSync(path.join(modulePath, 'oh-package.json5'), 'utf-8'));
3407
+ if (parsed && typeof parsed.name === 'string') name = parsed.name.trim();
3408
+ } catch { /* no readable package name: nothing to mirror */ }
3409
+ if (!name || !SELF_PACKAGE_NAME_RE.test(name) || seen.has(name)) continue;
3410
+ if (!fs.existsSync(srcMain)) continue;
3411
+ seen.add(name);
3412
+ roots.push({ name, srcMain });
3413
+ }
3414
+ return roots;
3415
+ }
3416
+
3417
+ function sameLinkTarget(linkPath, target) {
3418
+ let resolved;
3419
+ try { resolved = path.resolve(path.dirname(linkPath), fs.readlinkSync(linkPath)); } catch { return false; }
3420
+ return process.platform === 'win32'
3421
+ ? resolved.toLowerCase() === target.toLowerCase()
3422
+ : resolved === target;
3423
+ }
3424
+
3425
+ // Per-process exclusive mirror dir name under <project>/.cache. A fixed name
3426
+ // would clash with — and be recursively deleted by cleanup alongside — any
3427
+ // real directory already sitting there; cleanup removes only the dir this
3428
+ // process actually created (issue #710 P1). Lazily created once per process
3429
+ // and reset after cleanup, so repeated checks in one --serve process each get
3430
+ // a fresh dir.
3431
+ let cachedSelfPkgMirrorDirName = null;
3432
+
3433
+ function selfPkgMirrorDirName() {
3434
+ if (!cachedSelfPkgMirrorDirName) {
3435
+ cachedSelfPkgMirrorDirName = `arkts-check-pkgs-${process.pid}-${Math.random().toString(36).slice(2, 8)}`;
3436
+ }
3437
+ return cachedSelfPkgMirrorDirName;
3438
+ }
3439
+
3440
+ // Idempotent: re-running against an up-to-date mirror only stats links. Returns
3441
+ // the mirror dir, or null when no module declares a package name.
3442
+ function ensureSelfPackageMirror(projectPath) {
3443
+ const roots = collectSelfPackageRoots(projectPath);
3444
+ if (roots.length === 0) return null;
3445
+ const mirrorDir = path.join(projectPath, '.cache', selfPkgMirrorDirName());
3446
+ for (const { name, srcMain } of roots) {
3447
+ const linkPath = path.join(mirrorDir, ...name.split('/'));
3448
+ if (sameLinkTarget(linkPath, srcMain)) continue;
3449
+ try {
3450
+ // 只清理链接/普通文件;linkPath 若是真实目录则保留——rmSync 会递归删除
3451
+ // 真实内容(symlinkSync 随后因 EEXIST 失败,导入保持未解析诊断,方向安全)。
3452
+ const st = fs.lstatSync(linkPath);
3453
+ if (st.isSymbolicLink() || !st.isDirectory()) {
3454
+ fs.rmSync(linkPath, { recursive: true, force: true });
3455
+ }
3456
+ } catch { /* best-effort(不存在时无需清理) */ }
3457
+ try {
3458
+ fs.mkdirSync(path.dirname(linkPath), { recursive: true });
3459
+ // Junctions need no elevated rights on Windows, unlike file symlinks.
3460
+ fs.symlinkSync(srcMain, linkPath, process.platform === 'win32' ? 'junction' : 'dir');
3461
+ } catch { /* best-effort: the import stays an unresolved diagnostic */ }
3462
+ }
3463
+ return mirrorDir;
3464
+ }
3465
+
3466
+ function isSubPath(parent, child) {
3467
+ const rel = path.relative(parent, child);
3468
+ return rel === '' || (!!rel && !rel.startsWith('..') && !path.isAbsolute(rel));
3469
+ }
3470
+
3471
+ // BuildProfile and other generated-profile classes are per-module, but
3472
+ // collectResolveModulePaths returns one flat list, so a single checker run lets
3473
+ // the SDK's wildcard `paths` resolve one module's generated class against
3474
+ // another module's copy (issue #688 1b). Group `files` by owning module so each
3475
+ // run sees that module's own generated profile dir — mirroring hvigor, which
3476
+ // compiles every module with only its own dirs. Every module's src/main stays
3477
+ // in each group's paths (they contain no generated classes), so cross-module
3478
+ // source imports keep resolving as before. Files under no declared module keep
3479
+ // the global list. `resolveModulePaths: null` means "use the global list".
3480
+ function groupFilesByModule(files, projectPath) {
3481
+ const declared = moduleDirEntries(projectPath)
3482
+ .filter((e) => fs.existsSync(e.srcMain))
3483
+ .sort((a, b) => b.modulePath.length - a.modulePath.length);
3484
+ if (declared.length === 0) return [{ files, resolveModulePaths: null, modulePath: null }];
3485
+
3486
+ const globalSrcMains = declared.map((e) => e.srcMain);
3487
+ // 只有一个模块存在 generated profile 目录时,全局 resolveModulePaths 里最多
3488
+ // 一个 BuildProfile,不存在跨模块串扰;保持单次全局运行,避免 N 个模块 N 次
3489
+ // checker 冷启动(SDK 类型图每组重建,大工程明显变慢)。
3490
+ if (declared.filter((e) => fs.existsSync(e.genDir)).length <= 1) {
3491
+ return [{ files, resolveModulePaths: null, modulePath: null }];
3492
+ }
3493
+ const groups = [];
3494
+ const byModulePath = new Map();
3495
+ const rest = [];
3496
+ for (const f of files) {
3497
+ const abs = path.resolve(f);
3498
+ const owner = declared.find((e) => isSubPath(e.modulePath, abs));
3499
+ if (!owner) { rest.push(f); continue; }
3500
+ if (!byModulePath.has(owner.modulePath)) {
3501
+ const entry = { modulePath: owner.modulePath, files: [] };
3502
+ byModulePath.set(owner.modulePath, entry);
3503
+ groups.push(entry);
3504
+ }
3505
+ byModulePath.get(owner.modulePath).files.push(f);
3506
+ }
3507
+
3508
+ const result = groups.map(({ modulePath, files: groupFiles }) => ({
3509
+ files: groupFiles,
3510
+ modulePath,
3511
+ resolveModulePaths: [
3512
+ ...globalSrcMains,
3513
+ declared.find((e) => e.modulePath === modulePath).genDir,
3514
+ ].filter((p) => fs.existsSync(p)),
3515
+ }));
3516
+ // A rest file belongs to no declared module, so no module's generated
3517
+ // profile is authoritative for it. Handing it the flat global list would
3518
+ // push every module's BuildProfile back into one run and let the cross-talk
3519
+ // the gate above just avoided leak back in through the rest group.
3520
+ if (rest.length > 0) result.push({ files: rest, resolveModulePaths: globalSrcMains, modulePath: null });
3521
+ return result;
3522
+ }
3523
+
3524
+ // Whether a diagnostic on absFile may be reported by the groupIndex run.
3525
+ // Checked files report only from their owning group. A file owned by another
3526
+ // declared module — pulled into this group's program as an import dependency,
3527
+ // where the SDK type-checks it under THIS module's BuildProfile — is the wrong
3528
+ // context (issue #688/#710), so it never reports here; its own module's group
3529
+ // run reports it instead. Files under no declared module (external deps) keep
3530
+ // the legacy report-everything behavior.
3531
+ function shouldReportDiagnostic(absFile, groupIndex, groups, declaredModulePaths, diagOwner) {
3532
+ const owner = diagOwner.get(absFile);
3533
+ if (owner !== undefined) return owner === groupIndex;
3534
+ const ownerModule = declaredModulePaths.find((mp) => isSubPath(mp, absFile));
3535
+ if (!ownerModule) return true;
3536
+ return groups[groupIndex].modulePath === ownerModule;
3537
+ }
3538
+
2981
3539
  // Project-level diagnostics read only immutable config/SDK files (module.json5,
2982
3540
  // main_pages.json, hvigor-config.json5, PermissionDefinitions.json, string.json,
2983
3541
  // resources/*/{media,profile,element}) plus a scan of `files` and — for the
@@ -3028,6 +3586,12 @@ function computeProjectDiagnostics(files, env, hasExplicitFiles) {
3028
3586
  function cleanupCheckerCache(projectPath) {
3029
3587
  const cachePath = path.join(projectPath, '.cache', 'arkts-check');
3030
3588
  try { fs.rmSync(cachePath, { recursive: true, force: true }); } catch { /* best-effort */ }
3589
+ // Only the mirror dir created by this process is removed — never the fixed
3590
+ // .cache/arkts-check-pkgs path, which may hold user content (#710 P1).
3591
+ if (cachedSelfPkgMirrorDirName) {
3592
+ try { fs.rmSync(path.join(projectPath, '.cache', cachedSelfPkgMirrorDirName), { recursive: true, force: true }); } catch { /* best-effort */ }
3593
+ cachedSelfPkgMirrorDirName = null;
3594
+ }
3031
3595
  // `.cache` 可能被其它工具使用,仅在为空时移除。
3032
3596
  try {
3033
3597
  const parent = path.dirname(cachePath);
@@ -3035,16 +3599,49 @@ function cleanupCheckerCache(projectPath) {
3035
3599
  } catch { /* best-effort */ }
3036
3600
  }
3037
3601
 
3602
+ // Diagnostics can be attributed to a file the checker reached through the
3603
+ // self-package mirror (a wildcard-paths resolution of `@scope/name/...`), in
3604
+ // which case the reported path lives under .cache/arkts-check-pkgs and is
3605
+ // deleted with the mirror when the run ends. Map such a path back to the real
3606
+ // module source file so reported paths stay navigable. Returns null when the
3607
+ // path is not under any mirrored package.
3608
+ function remapMirrorDiagnosticPath(absFile, mirrorDir, pkgRoots) {
3609
+ if (!absFile || !path.isAbsolute(absFile)) return null;
3610
+ for (const { name, srcMain } of pkgRoots) {
3611
+ const linkPath = path.join(mirrorDir, ...name.split('/'));
3612
+ const rel = path.relative(linkPath, absFile);
3613
+ if (rel && !rel.startsWith('..') && !path.isAbsolute(rel)) {
3614
+ return path.join(srcMain, rel);
3615
+ }
3616
+ }
3617
+ return null;
3618
+ }
3619
+
3620
+ // Generated-profile specifier target for the module owning `importer`, or null
3621
+ // to keep the default resolution. Modules are expected deepest-first so a
3622
+ // nested module wins over its parent. A module without a generated profile
3623
+ // returns null: leave the missing import to the checker's own diagnostic.
3624
+ function buildProfilePathFor(importer, modules, selfPkgMirror, mirrorPkgRoots) {
3625
+ if (!importer || !path.isAbsolute(importer) || modules.length === 0) return null;
3626
+ const source = selfPkgMirror
3627
+ ? remapMirrorDiagnosticPath(importer, selfPkgMirror, mirrorPkgRoots) || importer
3628
+ : importer;
3629
+ const owner = modules.find(({ modulePath }) => isSubPath(modulePath, source));
3630
+ if (!owner) return null;
3631
+ const profile = path.join(owner.genDir, 'BuildProfile');
3632
+ return fs.existsSync(profile + '.ets') ? profile : null;
3633
+ }
3634
+
3038
3635
  function runChecker(files, env) {
3039
3636
  const { devecoHome, etsLoaderPath, projectPath, aceModuleJsonPath } = env;
3040
3637
  // Carried on env when runCheck computed it (one profile read per request);
3041
3638
  // read here so runChecker stays usable standalone, as in tests.
3042
3639
  const sdkConfig = env.sdkConfig || readProjectSdkConfig(projectPath, env.devecoHome);
3043
3640
 
3044
- const fileMap = {};
3045
- files.forEach((f, i) => { fileMap[`file_${i}`] = f; });
3046
-
3047
3641
  const captured = [];
3642
+ // Function scope: filled inside the try block, appended to after it (project
3643
+ // diagnostics) and returned, so it must outlive the try/catch/finally.
3644
+ const diagnostics = [];
3048
3645
  let checkerFailure;
3049
3646
  const origLog = console.log;
3050
3647
  const origError = console.error;
@@ -3054,6 +3651,16 @@ function runChecker(files, env) {
3054
3651
  console.error = capture;
3055
3652
  console.warn = capture;
3056
3653
 
3654
+ // runChecker mutates process.env for the SDK checker. A --serve process serves
3655
+ // many requests and projects, so restore the previous values when the run ends
3656
+ // instead of leaking compileTool/externalApiPaths into later requests (and into
3657
+ // other tools in the same process).
3658
+ const prevEnv = {
3659
+ compileTool: process.env.compileTool,
3660
+ compileMode: process.env.compileMode,
3661
+ externalApiPaths: process.env.externalApiPaths,
3662
+ };
3663
+
3057
3664
  const hmsSdkEts = path.join(devecoHome, 'sdk', 'default', 'hms', 'ets');
3058
3665
  if (fs.existsSync(hmsSdkEts) && !(process.env.externalApiPaths || '').includes(hmsSdkEts)) {
3059
3666
  const existing = process.env.externalApiPaths || '';
@@ -3061,7 +3668,7 @@ function runChecker(files, env) {
3061
3668
  }
3062
3669
 
3063
3670
  try {
3064
- const etsChecker = require(path.join(etsLoaderPath, 'lib', 'ets_checker.js'));
3671
+ const etsChecker = loadEtsChecker(etsLoaderPath);
3065
3672
  const mainModule = require(path.join(etsLoaderPath, 'main.js'));
3066
3673
 
3067
3674
  Object.assign(mainModule.partialUpdateConfig, {
@@ -3096,6 +3703,39 @@ function runChecker(files, env) {
3096
3703
  process.env.compileTool = 'rollup';
3097
3704
  process.env.compileMode = 'moduleJson';
3098
3705
 
3706
+ // Generated-profile classes (BuildProfile) are per-module, so files are
3707
+ // checked per owning module with that module's own generated profile dir;
3708
+ // see groupFilesByModule. The self-package mirror (issue #688) is appended
3709
+ // to every group: any module may import any workspace package by name.
3710
+ const selfPkgMirror = ensureSelfPackageMirror(projectPath);
3711
+ const mirrorPaths = selfPkgMirror ? [selfPkgMirror] : [];
3712
+ const mirrorPkgRoots = selfPkgMirror ? collectSelfPackageRoots(projectPath) : [];
3713
+ const baseResolvePaths = [...collectResolveModulePaths(projectPath), ...mirrorPaths];
3714
+ // Deepest-first so a module nested under another directory wins.
3715
+ const profileModules = moduleDirEntries(projectPath)
3716
+ .sort((a, b) => b.modulePath.length - a.modulePath.length);
3717
+ resolveBuildProfilePath = (importer) =>
3718
+ buildProfilePathFor(importer, profileModules, selfPkgMirror, mirrorPkgRoots);
3719
+ const moduleGroups = groupFilesByModule(files, projectPath);
3720
+ // Grouped runs share every src/main (and the mirror) across groups, so a
3721
+ // group's program also contains files owned by other modules — checked
3722
+ // under THIS group's BuildProfile. A file's diagnostics are therefore
3723
+ // reported only by its owning group's run; files outside the check list
3724
+ // entirely (external deps pulled in via wildcard paths) keep the
3725
+ // existing keep-everything behavior.
3726
+ const diagOwner = new Map();
3727
+ let declaredModulePaths = [];
3728
+ if (moduleGroups.length > 1) {
3729
+ moduleGroups.forEach((g, gi) => {
3730
+ for (const f of g.files) diagOwner.set(path.resolve(f), gi);
3731
+ });
3732
+ declaredModulePaths = moduleDirEntries(projectPath)
3733
+ .map((e) => e.modulePath)
3734
+ .filter((mp) => fs.existsSync(path.join(mp, 'src', 'main')));
3735
+ }
3736
+
3737
+ let capturedMark = 0;
3738
+ for (const [groupIndex, group] of moduleGroups.entries()) {
3099
3739
  const projectConfig = {
3100
3740
  projectPath,
3101
3741
  modulePath: projectPath,
@@ -3120,7 +3760,12 @@ function runChecker(files, env) {
3120
3760
  originCompatibleSdkVersion: sdkConfig.compatibleSdkVersion,
3121
3761
  bundleType: '',
3122
3762
  compilerTypes: [],
3123
- resolveModulePaths: collectResolveModulePaths(projectPath),
3763
+ resolveModulePaths: group.resolveModulePaths ? [...group.resolveModulePaths, ...mirrorPaths] : baseResolvePaths,
3764
+ // SDK ETS annotations such as @Available in ets/api/@ohos.annotation.d.ets
3765
+ // are only parsed/exported when this flag is set — the ets-loader build
3766
+ // config sets it; without it the checker reports the annotation as an
3767
+ // unexported member and the decorator as invalid.
3768
+ allowEtsAnnotations: true,
3124
3769
  };
3125
3770
 
3126
3771
  // The checker persists .tsbuildinfo/.tsbuildinfo.linter under cachePath.
@@ -3130,8 +3775,46 @@ function runChecker(files, env) {
3130
3775
  try { fs.rmSync(projectConfig.cachePath, { recursive: true, force: true }); } catch { /* best-effort */ }
3131
3776
  fs.mkdirSync(projectConfig.cachePath, { recursive: true });
3132
3777
 
3778
+ const fileMap = {};
3779
+ group.files.forEach((f, i) => { fileMap[`file_${i}`] = f; });
3133
3780
  const logger = { debug: capture, info: capture, warn: capture, error: capture };
3134
3781
  etsChecker.etsStandaloneChecker(fileMap, logger, projectConfig);
3782
+
3783
+ // Parse this group's output before the next group appends to `captured`.
3784
+ // Diagnostics on a file reached through the self-package mirror are
3785
+ // re-attributed to the real module source: the mirror is deleted when the
3786
+ // run ends, so its paths are dead on arrival. In grouped runs a file's
3787
+ // diagnostics are reported only by its owning group's run — any other
3788
+ // group's program contains the file under the wrong BuildProfile.
3789
+ const groupLines = captured.slice(capturedMark).flatMap((entry) => entry.split('\n'));
3790
+ capturedMark = captured.length;
3791
+ let current = null;
3792
+ for (const line of groupLines) {
3793
+ const clean = line.replace(/\x1b\[\d+m/g, '').replace(/\[(\d+)m/g, '');
3794
+ const loc = parseDiagnosticLine(clean);
3795
+ if (loc) { current = loc; continue; }
3796
+ if (current && clean.trim() && !clean.includes('ArkTS:') && !clean.includes('For details about')) {
3797
+ const remapped = mirrorPkgRoots.length
3798
+ ? remapMirrorDiagnosticPath(current.file, selfPkgMirror, mirrorPkgRoots)
3799
+ : null;
3800
+ const diagFile = remapped || current.file;
3801
+ if (diagOwner.size > 0 && !shouldReportDiagnostic(path.resolve(diagFile), groupIndex, moduleGroups, declaredModulePaths, diagOwner)) {
3802
+ current = null;
3803
+ continue;
3804
+ }
3805
+ const { message, rule } = parseMessageLine(clean);
3806
+ diagnostics.push({
3807
+ file: path.relative(projectPath, diagFile),
3808
+ line: current.line,
3809
+ column: current.column,
3810
+ severity: current.severity === 'error' ? 'error' : 'warning',
3811
+ message,
3812
+ rule,
3813
+ });
3814
+ current = null;
3815
+ }
3816
+ }
3817
+ }
3135
3818
  } catch (e) {
3136
3819
  // The checker threw, so it type-checked nothing (or stopped partway) and the
3137
3820
  // diagnostics below describe an incomplete run. Recording this in `captured`
@@ -3146,6 +3829,13 @@ function runChecker(files, env) {
3146
3829
  console.log = origLog;
3147
3830
  console.error = origError;
3148
3831
  console.warn = origWarn;
3832
+ if (prevEnv.compileTool === undefined) delete process.env.compileTool;
3833
+ else process.env.compileTool = prevEnv.compileTool;
3834
+ if (prevEnv.compileMode === undefined) delete process.env.compileMode;
3835
+ else process.env.compileMode = prevEnv.compileMode;
3836
+ if (prevEnv.externalApiPaths === undefined) delete process.env.externalApiPaths;
3837
+ else process.env.externalApiPaths = prevEnv.externalApiPaths;
3838
+ resolveBuildProfilePath = undefined;
3149
3839
  // 缓存只在单次检查期间有效(下次运行前会重建),结束后清掉,
3150
3840
  // 避免在用户工程根残留 .cache/arkts-check 目录。
3151
3841
  cleanupCheckerCache(projectPath);
@@ -3165,28 +3855,6 @@ function runChecker(files, env) {
3165
3855
  );
3166
3856
  }
3167
3857
 
3168
- const diagnostics = [];
3169
- let current = null;
3170
- const lines = captured.flatMap(entry => entry.split('\n'));
3171
-
3172
- for (const line of lines) {
3173
- const clean = line.replace(/\x1b\[\d+m/g, '').replace(/\[(\d+)m/g, '');
3174
- const loc = parseDiagnosticLine(clean);
3175
- if (loc) { current = loc; continue; }
3176
- if (current && clean.trim() && !clean.includes('ArkTS:') && !clean.includes('For details about')) {
3177
- const { message, rule } = parseMessageLine(clean);
3178
- diagnostics.push({
3179
- file: path.relative(projectPath, current.file),
3180
- line: current.line,
3181
- column: current.column,
3182
- severity: current.severity === 'error' ? 'error' : 'warning',
3183
- message,
3184
- rule,
3185
- });
3186
- current = null;
3187
- }
3188
- }
3189
-
3190
3858
  // Reuse the project-level diagnostics computed once in main(); fall back to
3191
3859
  // computing them here so runChecker stays usable standalone (e.g. in tests).
3192
3860
  const projectDiagnostics = env.skipProjectDiagnostics
@@ -3194,7 +3862,17 @@ function runChecker(files, env) {
3194
3862
  : (env.projectDiagnostics || computeProjectDiagnostics(files, env, env.hasExplicitFiles));
3195
3863
  diagnostics.push(...projectDiagnostics);
3196
3864
 
3197
- return dropFalsePositives(diagnostics, projectPath, aceModuleJsonPath);
3865
+ // 分组运行时 checker 会把诊断归因到 fileMap 之外的依赖文件,同一
3866
+ // file|line|message 可能被多组重复报告,按 diagKey 去重。
3867
+ const seenDiagKeys = new Set();
3868
+ const uniqueDiagnostics = diagnostics.filter((d) => {
3869
+ const key = diagKey(d);
3870
+ if (seenDiagKeys.has(key)) return false;
3871
+ seenDiagKeys.add(key);
3872
+ return true;
3873
+ });
3874
+
3875
+ return dropFalsePositives(uniqueDiagnostics, projectPath, aceModuleJsonPath);
3198
3876
  }
3199
3877
 
3200
3878
  // The checker type-checks the whole program, so SDK `.d.ets` files are pulled in
@@ -3752,6 +4430,9 @@ function handleRequest(line) {
3752
4430
  projectEtsFileCache.clear();
3753
4431
  stateFieldCache.clear();
3754
4432
  resolveModulePathsCache.clear();
4433
+ classIndexCache.clear();
4434
+ fileImportCache.clear();
4435
+ fileStarExportCache.clear();
3755
4436
 
3756
4437
  const result = (() => {
3757
4438
  try {
@@ -3803,7 +4484,10 @@ module.exports = {
3803
4484
  validateComponentDecoratorConsistency, collectStructDecorators,
3804
4485
  V1_ONLY_MEMBER_DECORATORS, V2_ONLY_MEMBER_DECORATORS,
3805
4486
  validateObservedV2PropertyTypes, collectObservedV2ClassNames, V1_TYPE_SENSITIVE_DECORATORS,
4487
+ buildProjectClassIndex, getFileBindings, resolveClassOrigin, isObservedV2Usage,
4488
+ classIndexCache, fileImportCache,
3806
4489
  validateAppResources, loadAppResourceNames, APP_RESOURCE_INDEXED_KINDS,
4490
+ computeCommentStringSpans, collectModuleResourceNames,
3807
4491
  collectProjectEtsFiles, unionProjectFiles, projectEtsFileCache,
3808
4492
  STRUCT_DECL_RE, collectStructs,
3809
4493
  validateRegularPropertyInit, collectComponentRegularProperties,
@@ -3822,6 +4506,9 @@ module.exports = {
3822
4506
  DEFAULT_SDK_INFO, DEFAULT_RUNTIME_OS,
3823
4507
  collectResolveModulePaths, readProjectModules, pickTargetNameForProduct,
3824
4508
  buildProfileNotBuiltHint, resolveModulePathsCache,
4509
+ collectSelfPackageRoots, ensureSelfPackageMirror, remapMirrorDiagnosticPath,
4510
+ buildProfilePathFor, loadEtsChecker, cleanupCheckerCache,
4511
+ groupFilesByModule,
3825
4512
  closureHash, computeEpoch, resolveClosureDependency, collectAmbientDeclarations,
3826
4513
  fileDiagCache, invalidateFileDiagCache, dropFalsePositives, hashText,
3827
4514
  isOutsideProject, isDeclarationFile,