@hia-doc/dotnetdoc-runner 0.1.11 → 1.0.0-rc.1

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.
@@ -8,24 +8,41 @@ import path from 'node:path';
8
8
  import { extractDotnetProjectDiscovery, extractDotnetSourceFiles } from '@hia-doc/dotnet-source-extractor';
9
9
  import { dotnetXmlDocsToHiaDocument } from '@hia-doc/dotnetdoc-adapter';
10
10
  import { DOTNETDOC_XML_DOC_EXTRACTION_CONTRACT, DOTNETDOC_CSHARP_SOURCE_EXTRACTION_CONTRACT, DOTNETDOC_PROJECT_DISCOVERY_CONTRACT } from '@hia-doc/dotnetdoc-spec';
11
+ import { hasUnpairedSurrogate } from './doc-source-map.mjs';
11
12
 
12
13
  /**
13
- * @lang zh-CN 按完整成员ID选择唯一声明;已知程序集不能跨界,重复注册和partial多位置保持歧义。
14
- * @lang en Selects a declaration by its complete member ID, respecting known assemblies and retaining ambiguity for duplicate registrations or partial locations.
14
+ * @lang zh-CN 按完整成员ID选声明;同次抽取的真实partial类型选主声明,重复注册/跨抽取冲突仍拒绝。
15
+ * @lang en Selects declarations by complete member ID; genuine partial types from one extraction select a primary declaration, while duplicates and cross-extraction conflicts remain refused.
15
16
  * @param {object} member <lang><zh-CN>XML成员身份。</zh-CN><en>XML member identity.</en></lang>
16
17
  * @param {object[]} candidates <lang><zh-CN>声明及其程序集身份。</zh-CN><en>Declarations with assembly identities.</en></lang>
17
18
  * @param {string|null} assembly <lang><zh-CN>XML声明的程序集。</zh-CN><en>Assembly declared by the XML input.</en></lang>
18
- * @returns {{declaration?:object,status:string}} <lang><zh-CN>唯一声明或missing/ambiguous;不按简称或参数数量回退。</zh-CN><en>Unique declaration or missing/ambiguous, without short-name or arity fallback.</en></lang>
19
+ * @returns {{declaration?:object,origin?:object,status:string,candidateCount:number,selectionRule?:string}} <lang><zh-CN>精确/partial主声明及其抽取事实,或missing/ambiguous;不按简称或参数数量回退。</zh-CN><en>Exact/partial primary declaration and its extraction fact, or missing/ambiguous; no short-name or arity fallback.</en></lang>
19
20
  */
20
21
  export function selectExactDeclaration(member, candidates, assembly) {
21
- // <lang><zh-CN>沿用既有唯一声明门禁;相同位置重复注册也不自动推断为同一输入事实。</zh-CN><en>Retain the existing unique-declaration gate; duplicate registrations at the same location are not automatically treated as one input fact.</en></lang>
22
+ // <lang><zh-CN>完整ID及签名类型先验证;相同位置重复注册不自动合并为同一输入事实。</zh-CN><en>Validate complete IDs and signature types first; duplicate registrations at the same location do not automatically become one input fact.</en></lang>
22
23
  const unique = [];
23
24
  for (const candidate of candidates) {
24
- if (candidate.member.semantic?.documentationCommentId !== member.memberName) continue;
25
+ if (candidate.member.semantic?.documentationCommentId !== member.memberName || candidate.member.semantic?.hasUnresolvedSignatureTypes === true) continue;
25
26
  if (assembly && candidate.assembly && candidate.assembly !== 'DotNetDoc.SourceExtraction' && candidate.assembly !== assembly) continue;
26
- unique.push(candidate.member);
27
+ unique.push(candidate);
27
28
  }
28
- return unique.length === 1 ? { status: 'resolved', declaration: unique[0] } : { status: unique.length === 0 ? 'missing' : 'ambiguous' };
29
+ if(unique.length===1) return {status:'resolved',declaration:unique[0].member,origin:unique[0].origin,candidateCount:1,selectionRule:'exact-documentation-id'};
30
+ // <lang><zh-CN>partial必须来自同一编译事实、同一程序集且位置各异;普通重复不能靠排序变成有效声明。</zh-CN><en>Partial declarations must share a compilation and assembly with distinct locations; ordering cannot legitimize ordinary duplicates.</en></lang>
31
+ const first=unique[0];
32
+ const locations=new Set(unique.map(candidate=>`${candidate.member.source?.path}:${candidate.member.source?.range?.start?.line}:${candidate.member.source?.range?.start?.column}`));
33
+ if(unique.length>1 && first.origin && locations.size===unique.length && unique.every(candidate=>candidate.origin===first.origin && candidate.assembly===first.assembly && candidate.member.kind==='dotnet-type' && candidate.member.semantic?.declaration?.isPartialType===true && candidate.member.semantic.declaration.declarationCount===unique.length)){
34
+ const ranked=[...unique].sort(compareDeclarations);
35
+ return {status:'resolved',declaration:ranked[0].member,origin:ranked[0].origin,candidateCount:unique.length,selectionRule:'non-generated-path-line'};
36
+ }
37
+ return {status:unique.length===0?'missing':'ambiguous',candidateCount:unique.length};
38
+ }
39
+
40
+ /** @lang zh-CN 排序仅用于已证明的同一partial语义符号,不使用宿主locale。 @lang en Orders only proven parts of the same semantic symbol, independently of host locale. */
41
+ function compareDeclarations(left,right){
42
+ const a=left.member,b=right.member;
43
+ const generated=Number(a.semantic.declaration.isGenerated)-Number(b.semantic.declaration.isGenerated);
44
+ const aPath=a.source.path.replaceAll('\\','/'),bPath=b.source.path.replaceAll('\\','/');
45
+ return generated || (aPath<bPath?-1:aPath>bPath?1:0) || a.source.range.start.line-b.source.range.start.line || (a.source.range.start.column??1)-(b.source.range.start.column??1);
29
46
  }
30
47
 
31
48
  /**
@@ -56,10 +73,15 @@ export async function enrichXmlSourceLocations(records, request) {
56
73
  const matches = assembly ? available.filter(project => (project.assemblyName ?? project.name) === assembly) : [];
57
74
  // <lang><zh-CN>每项目串行抽取并缓存一次;失败也是本请求缓存结果,不反复启动helper。</zh-CN><en>Extract each project serially once and cache failures too, preventing repeated helper launches.</en></lang>
58
75
  let discovered = [];
76
+ let referenceDiagnosticCodes = [];
59
77
  if (matches.length === 1) {
60
78
  const project = matches[0];
61
- if (!cache.has(project.path)) cache.set(project.path, await readProjectCandidates(project, request.workspaceRoot));
62
- discovered = cache.get(project.path);
79
+ const referenceDirectory=path.posix.dirname(record.input.path.replaceAll('\\','/'));
80
+ const cacheKey=`${project.path}\n${referenceDirectory}`;
81
+ if (!cache.has(cacheKey)) cache.set(cacheKey, await readProjectCandidates(project, request.workspaceRoot, referenceDirectory));
82
+ const extracted=cache.get(cacheKey);
83
+ discovered = extracted.candidates;
84
+ referenceDiagnosticCodes=extracted.referenceDiagnosticCodes;
63
85
  }
64
86
  // <lang><zh-CN>显式输入对其成员ID优先;自动项目发现不重复注册同一显式身份,显式输入之间的重复仍拒绝。</zh-CN><en>Explicit inputs take precedence for their member IDs; automatic discovery never duplicates an explicit identity, while duplicates between explicit inputs remain refused.</en></lang>
65
87
  const explicitIds = new Set(explicit.filter(candidate => !assembly || !candidate.assembly || candidate.assembly === assembly || candidate.assembly === 'DotNetDoc.SourceExtraction').map(candidate => candidate.member.semantic?.documentationCommentId));
@@ -74,21 +96,32 @@ export async function enrichXmlSourceLocations(records, request) {
74
96
  }
75
97
  // <lang><zh-CN>统计是有界元数据;每个符号保留XML原文/i18n,只合并验证后的代码声明。
76
98
  // </zh-CN><en>Counts are bounded metadata; each symbol retains XML text/i18n and merges only verified code declarations.</en></lang>
77
- const summary = { strategy: 'assembly-and-documentation-id', resolved: 0, ambiguous: 0, missing: 0 };
99
+ const summary = { strategy: 'assembly-and-documentation-id', resolved: 0, ambiguous: 0, missing: 0, resolvedPartial: 0, referenceDiagnosticCodes };
78
100
  const members = [];
101
+ // <lang><zh-CN>逐成员记录与计数在同一循环生成,避免诊断和source事实漂移。</zh-CN><en>Generate per-member records and counts in one loop to keep diagnostics aligned with source facts.</en></lang>
102
+ const resolutions=[];
79
103
  for (const member of record.artifact.members) {
80
104
  const selected = selectExactDeclaration(member, byId.get(member.memberName) ?? [], assembly);
81
- if (selected.status !== 'resolved') { summary[selected.status] += 1; members.push(member); continue; }
105
+ if (selected.status !== 'resolved') { summary[selected.status] += 1; members.push(member); resolutions.push({status:selected.status,candidateCount:selected.candidateCount,reason:selected.status,detail:referenceDiagnosticCodes.length?'metadata-reference-or-project-unavailable':'no-unique-exact-declaration'}); continue; }
82
106
  const declaration = selected.declaration;
83
107
  try {
84
108
  await assertContainedFile(request.workspaceRoot, declaration.source.path);
85
109
  if (!/\.cs$/iu.test(declaration.source.path) || !validRange(declaration.source.range)) throw new Error('Not a bounded C# declaration');
86
110
  summary.resolved += 1;
111
+ if(selected.selectionRule==='non-generated-path-line') summary.resolvedPartial+=1;
87
112
  members.push({ ...member, source: declaration.source, semantic: { ...member.semantic, ...declaration.semantic } });
88
- } catch { summary.missing += 1; members.push(member); }
113
+ // <lang><zh-CN>只记录当前 Roslyn 事实的固定类别和错误存在性,映射不能凭 XML 或外来名称自行升格。</zh-CN><en>Record only the current Roslyn fact category and error presence, so maps cannot promote XML or foreign labels on their own.</en></lang>
114
+ resolutions.push({status:'resolved',candidateCount:selected.candidateCount,selectionRule:selected.selectionRule,...(request.options?.writeDocSourceMapArtifact ? {sourceRangeSource:declaration.source.rangeSource,sourceHasErrors:(selected.origin?.diagnostics??[]).some(item=>item.severity==='error')} : {})});
115
+ } catch { summary.missing += 1; members.push(member); resolutions.push({status:'missing',reason:'missing',detail:'unsafe-or-invalid-declaration-location',candidateCount:selected.candidateCount}); }
89
116
  }
90
117
  const document = dotnetXmlDocsToHiaDocument({ ...record.artifact, members }, { id: record.input.hiaDocumentId, title: record.input.title });
91
118
  document.metadata.sourceLocationResolution = summary;
119
+ for(const [index,symbol] of document.symbols.entries()){
120
+ const resolution=resolutions[index];
121
+ symbol.metadata.dotnetdoc.sourceLocationResolution=resolution;
122
+ if(resolution.status!=='resolved') symbol.diagnostics.push({code:resolution.status==='ambiguous'?'DOTNETDOC_SOURCE_LOCATION_AMBIGUOUS':'DOTNETDOC_SOURCE_LOCATION_MISSING',message:'No unique verified C# location is available for this documentation member.',severity:'warning',data:{symbolId:symbol.id,memberName:symbol.metadata.dotnetdoc.memberName,...resolution}});
123
+ }
124
+ if(summary.missing||summary.ambiguous) document.diagnostics.push({code:'DOTNETDOC_SOURCE_LOCATION_UNRESOLVED',message:'Some documentation members have no unique verified C# location; inspect member diagnostics and metadata.sourceLocationResolution.',severity:'warning',data:summary});
92
125
  record.hiaDocument = document;
93
126
  await writeFile(path.join(request.outputDirectory, record.hiaPath), `${JSON.stringify(document, null, 2)}\n`, 'utf8');
94
127
  if (summary.missing || summary.ambiguous) diagnostics.push({ code: 'DOTNETDOC_SOURCE_LOCATION_UNRESOLVED', message: 'Some XML members have no unique C# declaration. Configure the matching project/source inputs and resolve missing references; XML origins are not exposed as code.', severity: 'warning', source: { path: record.input.path }, metadata: summary });
@@ -98,11 +131,11 @@ export async function enrichXmlSourceLocations(records, request) {
98
131
 
99
132
  /** @lang zh-CN 从已有抽取结果取身份和定位,不复制方法体。 @lang en Selects identities/locators from existing extraction results without copying method bodies. */
100
133
  function candidatesFrom(artifact) {
101
- return artifact.members.map(member => ({ member, assembly: artifact.assembly?.name ?? member.semantic?.containingAssembly }));
134
+ return artifact.members.map(member => ({ member, assembly: artifact.assembly?.name ?? member.semantic?.containingAssembly, origin: artifact }));
102
135
  }
103
136
 
104
137
  /** @lang zh-CN 受限项目只读抽取;任何路径/工具失败都变为未定位,不泄露底层错误。 @lang en Performs bounded read-only project extraction, mapping path/tool failures to unresolved locations without leaking underlying errors. */
105
- async function readProjectCandidates(project, root) {
138
+ async function readProjectCandidates(project, root, referenceDirectory) {
106
139
  try {
107
140
  await assertContainedFile(root, project.path);
108
141
  // <lang><zh-CN>显式Compile条目先验证真实路径;SDK默认遍历不跟随symlink,项目根仍须在工作区内。</zh-CN><en>Validate real paths of explicit Compile items first; SDK enumeration does not follow symlinks and its project root must remain inside the workspace.</en></lang>
@@ -111,13 +144,14 @@ async function readProjectCandidates(project, root) {
111
144
  const sourcePath = path.posix.normalize(path.posix.join(path.posix.dirname(project.path), item.include.replaceAll('\\', '/')));
112
145
  await assertContainedFile(root, sourcePath);
113
146
  }
114
- return candidatesFrom(await extractDotnetSourceFiles({ workspaceRoot: root, projectPath: project.path }));
115
- } catch { return []; }
147
+ const artifact=await extractDotnetSourceFiles({ workspaceRoot: root, projectPath: project.path, referenceDirectory });
148
+ return {candidates:candidatesFrom(artifact),referenceDiagnosticCodes:[...new Set((artifact.diagnostics??[]).filter(item=>/^DOTNETDOC_(?:METADATA|FRAMEWORK)_REFERENCE/u.test(item.code)).map(item=>item.code))].sort()};
149
+ } catch { return {candidates:[],referenceDiagnosticCodes:['DOTNETDOC_SOURCE_PROJECT_UNAVAILABLE']}; }
116
150
  }
117
151
 
118
152
  /** @lang zh-CN 双重路径包含检查,不读取越界symlink目标正文。 @lang en Checks lexical and real-path containment without reading bodies behind escaping symlinks. */
119
153
  async function assertContainedFile(root, relative) {
120
- if (typeof relative !== 'string' || /^(?:[/\\]|[a-z][a-z0-9+.-]*:)/iu.test(relative) || relative.replaceAll('\\', '/').split('/').includes('..')) throw new Error('Unsafe source locator');
154
+ if (typeof relative !== 'string' || hasUnpairedSurrogate(relative) || relative.includes(':') || /^(?:[/\\]|[a-z][a-z0-9+.-]*:)/iu.test(relative) || relative.replaceAll('\\', '/').split('/').includes('..')) throw new Error('Unsafe source locator');
121
155
  const [realRoot, realFile] = await Promise.all([realpath(root), realpath(path.resolve(root, relative))]);
122
156
  const inside = path.relative(realRoot, realFile);
123
157
  if (path.isAbsolute(inside) || inside === '..' || inside.startsWith(`..${path.sep}`)) throw new Error('Source leaves workspace');