@open-livex-wiki/core 0.2.1 → 0.2.2

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 (130) hide show
  1. package/dist/coverage/handles.d.ts +5 -0
  2. package/dist/coverage/handles.d.ts.map +1 -0
  3. package/dist/coverage/handles.js +116 -0
  4. package/dist/coverage/handles.js.map +1 -0
  5. package/dist/coverage/targets.d.ts +22 -0
  6. package/dist/coverage/targets.d.ts.map +1 -0
  7. package/dist/coverage/targets.js +117 -0
  8. package/dist/coverage/targets.js.map +1 -0
  9. package/dist/coverage/visuals.d.ts +19 -0
  10. package/dist/coverage/visuals.d.ts.map +1 -0
  11. package/dist/coverage/visuals.js +103 -0
  12. package/dist/coverage/visuals.js.map +1 -0
  13. package/dist/coverage.d.ts.map +1 -1
  14. package/dist/coverage.js +36 -233
  15. package/dist/coverage.js.map +1 -1
  16. package/dist/discover/designators.d.ts +26 -0
  17. package/dist/discover/designators.d.ts.map +1 -0
  18. package/dist/discover/designators.js +361 -0
  19. package/dist/discover/designators.js.map +1 -0
  20. package/dist/discover/document-types.d.ts +90 -0
  21. package/dist/discover/document-types.d.ts.map +1 -0
  22. package/dist/discover/document-types.js +2 -0
  23. package/dist/discover/document-types.js.map +1 -0
  24. package/dist/discover/index-builder.d.ts +28 -0
  25. package/dist/discover/index-builder.d.ts.map +1 -0
  26. package/dist/discover/index-builder.js +286 -0
  27. package/dist/discover/index-builder.js.map +1 -0
  28. package/dist/discover/postings.d.ts +9 -0
  29. package/dist/discover/postings.d.ts.map +1 -0
  30. package/dist/discover/postings.js +183 -0
  31. package/dist/discover/postings.js.map +1 -0
  32. package/dist/discover/query-expansion.d.ts +4 -0
  33. package/dist/discover/query-expansion.d.ts.map +1 -0
  34. package/dist/discover/query-expansion.js +109 -0
  35. package/dist/discover/query-expansion.js.map +1 -0
  36. package/dist/discover/scene-document.d.ts +40 -0
  37. package/dist/discover/scene-document.d.ts.map +1 -0
  38. package/dist/discover/scene-document.js +417 -0
  39. package/dist/discover/scene-document.js.map +1 -0
  40. package/dist/discover/scene-ranking.d.ts +14 -0
  41. package/dist/discover/scene-ranking.d.ts.map +1 -0
  42. package/dist/discover/scene-ranking.js +217 -0
  43. package/dist/discover/scene-ranking.js.map +1 -0
  44. package/dist/discover/scoring.d.ts +34 -0
  45. package/dist/discover/scoring.d.ts.map +1 -0
  46. package/dist/discover/scoring.js +425 -0
  47. package/dist/discover/scoring.js.map +1 -0
  48. package/dist/discover/subscene.d.ts +11 -0
  49. package/dist/discover/subscene.d.ts.map +1 -0
  50. package/dist/discover/subscene.js +121 -0
  51. package/dist/discover/subscene.js.map +1 -0
  52. package/dist/discover/term-scoring.d.ts +25 -0
  53. package/dist/discover/term-scoring.d.ts.map +1 -0
  54. package/dist/discover/term-scoring.js +374 -0
  55. package/dist/discover/term-scoring.js.map +1 -0
  56. package/dist/discover/tokenizer.d.ts +35 -0
  57. package/dist/discover/tokenizer.d.ts.map +1 -0
  58. package/dist/discover/tokenizer.js +282 -0
  59. package/dist/discover/tokenizer.js.map +1 -0
  60. package/dist/discover.d.ts +5 -61
  61. package/dist/discover.d.ts.map +1 -1
  62. package/dist/discover.js +54 -2733
  63. package/dist/discover.js.map +1 -1
  64. package/dist/loader/config.d.ts +29 -0
  65. package/dist/loader/config.d.ts.map +1 -0
  66. package/dist/loader/config.js +80 -0
  67. package/dist/loader/config.js.map +1 -0
  68. package/dist/loader/domain.d.ts +19 -0
  69. package/dist/loader/domain.d.ts.map +1 -0
  70. package/dist/loader/domain.js +152 -0
  71. package/dist/loader/domain.js.map +1 -0
  72. package/dist/loader/paths.d.ts +4 -0
  73. package/dist/loader/paths.d.ts.map +1 -0
  74. package/dist/loader/paths.js +29 -0
  75. package/dist/loader/paths.js.map +1 -0
  76. package/dist/loader/scene.d.ts +16 -0
  77. package/dist/loader/scene.d.ts.map +1 -0
  78. package/dist/loader/scene.js +266 -0
  79. package/dist/loader/scene.js.map +1 -0
  80. package/dist/loader.d.ts +2 -2
  81. package/dist/loader.d.ts.map +1 -1
  82. package/dist/loader.js +11 -506
  83. package/dist/loader.js.map +1 -1
  84. package/dist/schemas.d.ts +14 -11
  85. package/dist/schemas.d.ts.map +1 -1
  86. package/dist/schemas.js +2 -1
  87. package/dist/schemas.js.map +1 -1
  88. package/dist/types.d.ts +2 -0
  89. package/dist/types.d.ts.map +1 -1
  90. package/dist/utils/markdown-scanner.d.ts +20 -0
  91. package/dist/utils/markdown-scanner.d.ts.map +1 -0
  92. package/dist/utils/markdown-scanner.js +303 -0
  93. package/dist/utils/markdown-scanner.js.map +1 -0
  94. package/dist/utils/markdown.d.ts +48 -0
  95. package/dist/utils/markdown.d.ts.map +1 -0
  96. package/dist/utils/markdown.js +370 -0
  97. package/dist/utils/markdown.js.map +1 -0
  98. package/dist/utils/paths.d.ts +38 -0
  99. package/dist/utils/paths.d.ts.map +1 -0
  100. package/dist/utils/paths.js +257 -0
  101. package/dist/utils/paths.js.map +1 -0
  102. package/dist/utils/regexp.d.ts +2 -0
  103. package/dist/utils/regexp.d.ts.map +1 -0
  104. package/dist/utils/regexp.js +4 -0
  105. package/dist/utils/regexp.js.map +1 -0
  106. package/dist/utils/symbols.d.ts +9 -0
  107. package/dist/utils/symbols.d.ts.map +1 -0
  108. package/dist/utils/symbols.js +324 -0
  109. package/dist/utils/symbols.js.map +1 -0
  110. package/dist/utils.d.ts +4 -96
  111. package/dist/utils.d.ts.map +1 -1
  112. package/dist/utils.js +3 -1250
  113. package/dist/utils.js.map +1 -1
  114. package/dist/validator/anchor-checker.d.ts +26 -0
  115. package/dist/validator/anchor-checker.d.ts.map +1 -0
  116. package/dist/validator/anchor-checker.js +299 -0
  117. package/dist/validator/anchor-checker.js.map +1 -0
  118. package/dist/validator/git-remotes.d.ts +12 -0
  119. package/dist/validator/git-remotes.d.ts.map +1 -0
  120. package/dist/validator/git-remotes.js +223 -0
  121. package/dist/validator/git-remotes.js.map +1 -0
  122. package/dist/validator/source-resolver.d.ts +29 -0
  123. package/dist/validator/source-resolver.d.ts.map +1 -0
  124. package/dist/validator/source-resolver.js +315 -0
  125. package/dist/validator/source-resolver.js.map +1 -0
  126. package/dist/validator.d.ts +3 -45
  127. package/dist/validator.d.ts.map +1 -1
  128. package/dist/validator.js +6 -823
  129. package/dist/validator.js.map +1 -1
  130. package/package.json +1 -1
package/dist/validator.js CHANGED
@@ -1,10 +1,10 @@
1
- import crypto from "node:crypto";
2
1
  import fsSync from "node:fs";
3
- import fs from "node:fs/promises";
4
- import path from "node:path";
5
- import { inspectGitFileAtRef, isBareGitRepository, isGitRepoRoot, resolveGitCommit, } from "./git-utils.js";
6
- import { isPathStrictlyInsideRoot, loadWiki } from "./loader.js";
7
- import { containsSymbol, detectSceneContentPlaceholders, extractPendingConfirmations, hasExplicitChainSubheadings, isSafeContainedRelativePath, KEBAB_CASE_REGEX, normalizeGitUrlKey, toPosixPath, } from "./utils.js";
2
+ import { loadWiki } from "./loader.js";
3
+ import { detectSceneContentPlaceholders, extractPendingConfirmations, hasExplicitChainSubheadings, KEBAB_CASE_REGEX, normalizeGitUrlKey, toPosixPath, } from "./utils.js";
4
+ import { verifyAnchorOnDisk, verifyCorpusSourceRefOnDisk, verifySourceAnchorOnDisk, } from "./validator/anchor-checker.js";
5
+ import { resolveLocalRepoDir, resolveLocalSourceDir } from "./validator/source-resolver.js";
6
+ export { verifyCorpusSourceRefOnDisk, verifySourceAnchorOnDisk, } from "./validator/anchor-checker.js";
7
+ export { computeFileSha256, resolveLocalRepoDir, resolveLocalSourceDir, resolveSceneRepoLocalPaths, resolveSceneSourceLocalPaths, } from "./validator/source-resolver.js";
8
8
  export { normalizeGitUrlKey };
9
9
  const DOMAIN_BOUNDARY_HEADING_REGEX = /^(?:\d+\s*[.、::)\]]\s*)?(?:域身份与边界|Domain Identity\s*(?:&|and)\s*Boundaries)(?:$|\s|[::(/(-])/i;
10
10
  const REQUIRED_SCENE_SECTIONS = [
@@ -25,823 +25,6 @@ const REQUIRED_SCENE_SECTIONS = [
25
25
  regex: /^(?:4\s*[.、::)\]]\s*)?(?:待确认项|Pending Confirmations)(?:$|\s|[::(/(-])/i,
26
26
  },
27
27
  ];
28
- function isNetworkGitUrl(rawUrl) {
29
- const trimmed = rawUrl.trim();
30
- if (!trimmed) {
31
- return false;
32
- }
33
- if (/^(?:git\+)?(?:https?|ssh|git):\/\//i.test(trimmed)) {
34
- return true;
35
- }
36
- if (!/^[a-zA-Z]:[\\/]/.test(trimmed)) {
37
- return /^(?:[^@/\s]+@)?[a-zA-Z0-9.-]+\.[a-zA-Z0-9-]+:.+$/.test(trimmed);
38
- }
39
- return false;
40
- }
41
- function parseGitConfigRemotes(configContent) {
42
- const originUrls = [];
43
- const otherUrls = [];
44
- let currentRemoteName = null;
45
- for (const rawLine of configContent.split(/\r?\n/)) {
46
- const trimmed = rawLine.trim();
47
- if (!trimmed || trimmed.startsWith("#") || trimmed.startsWith(";")) {
48
- continue;
49
- }
50
- const sectionMatch = /^\[([^\]]+)\]$/.exec(trimmed);
51
- if (sectionMatch?.[1]) {
52
- const remoteMatch = /^remote\s+(?:"([^"]+)"|(\S+))$/i.exec(sectionMatch[1].trim());
53
- currentRemoteName = (remoteMatch?.[1] ?? remoteMatch?.[2] ?? "").trim() || null;
54
- continue;
55
- }
56
- if (!currentRemoteName) {
57
- continue;
58
- }
59
- const urlMatch = /^url\s*=\s*(.+)$/i.exec(trimmed);
60
- if (urlMatch?.[1]) {
61
- const cleaned = urlMatch[1]
62
- .trim()
63
- .replace(/^"(.*)"$/, "$1")
64
- .trim();
65
- if (cleaned) {
66
- if (currentRemoteName === "origin") {
67
- originUrls.push(cleaned);
68
- }
69
- else {
70
- otherUrls.push(cleaned);
71
- }
72
- }
73
- }
74
- }
75
- return { originUrls, otherUrls };
76
- }
77
- function readLocalRepoRemotesSync(repoDir) {
78
- const resolved = path.resolve(repoDir);
79
- if (!isGitRepoRoot(resolved)) {
80
- return { originUrls: [], allUrls: [] };
81
- }
82
- const configPaths = [];
83
- const dotGitPath = path.join(resolved, ".git");
84
- try {
85
- if (fsSync.existsSync(dotGitPath)) {
86
- const stat = fsSync.statSync(dotGitPath);
87
- if (stat.isDirectory()) {
88
- configPaths.push(path.join(dotGitPath, "config"));
89
- }
90
- else if (stat.isFile()) {
91
- const gitdirRaw = fsSync.readFileSync(dotGitPath, "utf8");
92
- const gitdirMatch = /^gitdir:\s*(.+)$/im.exec(gitdirRaw);
93
- if (gitdirMatch?.[1]) {
94
- const gitDir = path.resolve(resolved, gitdirMatch[1].trim());
95
- configPaths.push(path.join(gitDir, "config"));
96
- const commondirFile = path.join(gitDir, "commondir");
97
- if (fsSync.existsSync(commondirFile)) {
98
- const commonRel = fsSync.readFileSync(commondirFile, "utf8").trim();
99
- if (commonRel) {
100
- configPaths.push(path.join(path.resolve(gitDir, commonRel), "config"));
101
- }
102
- }
103
- }
104
- }
105
- }
106
- else {
107
- // Bare repository
108
- configPaths.push(path.join(resolved, "config"));
109
- }
110
- }
111
- catch {
112
- return { originUrls: [], allUrls: [] };
113
- }
114
- const originUrls = [];
115
- const otherUrls = [];
116
- for (const cfgPath of configPaths) {
117
- try {
118
- if (fsSync.existsSync(cfgPath)) {
119
- const raw = fsSync.readFileSync(cfgPath, "utf8");
120
- const parsed = parseGitConfigRemotes(raw);
121
- originUrls.push(...parsed.originUrls);
122
- otherUrls.push(...parsed.otherUrls);
123
- }
124
- }
125
- catch {
126
- // Ignore unreadable git config
127
- }
128
- }
129
- const uniqueOrigin = Array.from(new Set(originUrls));
130
- const uniqueAll = Array.from(new Set([...originUrls, ...otherUrls]));
131
- return { originUrls: uniqueOrigin, allUrls: uniqueAll };
132
- }
133
- function isDirectorySync(dirPath) {
134
- try {
135
- return fsSync.statSync(dirPath).isDirectory();
136
- }
137
- catch {
138
- return false;
139
- }
140
- }
141
- function resolveCandidateInReposDirSync(resolvedReposDir, reposRealDir, candidateDir) {
142
- if (!isPathStrictlyInsideRoot(resolvedReposDir, candidateDir)) {
143
- return undefined;
144
- }
145
- if (!fsSync.existsSync(candidateDir)) {
146
- return undefined;
147
- }
148
- try {
149
- const realDir = fsSync.realpathSync(candidateDir);
150
- if (!isPathStrictlyInsideRoot(reposRealDir, realDir)) {
151
- return undefined;
152
- }
153
- if (!fsSync.statSync(realDir).isDirectory()) {
154
- return undefined;
155
- }
156
- return { candidateDir, realDir };
157
- }
158
- catch {
159
- return undefined;
160
- }
161
- }
162
- function hasConflictingOriginRemote(candidateDir, normalizedRepo, expectedNetworkUrlKeys) {
163
- const { originUrls } = readLocalRepoRemotesSync(candidateDir);
164
- const networkOriginKeys = originUrls
165
- .filter(isNetworkGitUrl)
166
- .map((u) => normalizeGitUrlKey(u))
167
- .filter(Boolean);
168
- if (networkOriginKeys.length === 0) {
169
- return false;
170
- }
171
- if (expectedNetworkUrlKeys.size > 0) {
172
- return !networkOriginKeys.some((k) => expectedNetworkUrlKeys.has(k));
173
- }
174
- if (normalizedRepo.includes("/")) {
175
- const expectedPath = normalizedRepo.toLowerCase();
176
- return !networkOriginKeys.some((k) => k.split("/").slice(1).join("/") === expectedPath);
177
- }
178
- return false;
179
- }
180
- function scanReposDirByRemoteUrl(resolvedReposDir, reposRealDir, normalizedRepo, normalizedRepoKey, expectedNetworkUrlKeys, mode) {
181
- let entries;
182
- try {
183
- entries = fsSync.readdirSync(resolvedReposDir, { withFileTypes: true });
184
- }
185
- catch {
186
- return { ambiguous: false };
187
- }
188
- const sortedDirs = entries
189
- .filter((e) => (e.isDirectory() || e.isSymbolicLink()) && !e.name.startsWith("."))
190
- .sort((a, b) => a.name.localeCompare(b.name));
191
- const matchedByRealDir = new Map();
192
- for (const entry of sortedDirs) {
193
- const rawCandidate = path.resolve(resolvedReposDir, entry.name);
194
- const verified = resolveCandidateInReposDirSync(resolvedReposDir, reposRealDir, rawCandidate);
195
- if (!verified) {
196
- continue;
197
- }
198
- const { allUrls } = readLocalRepoRemotesSync(verified.candidateDir);
199
- const networkKeys = allUrls
200
- .filter(isNetworkGitUrl)
201
- .map((u) => normalizeGitUrlKey(u))
202
- .filter(Boolean);
203
- if (networkKeys.length === 0) {
204
- continue;
205
- }
206
- if (mode === "exact_url") {
207
- if (expectedNetworkUrlKeys.size > 0 &&
208
- networkKeys.some((rk) => expectedNetworkUrlKeys.has(rk))) {
209
- if (!matchedByRealDir.has(verified.realDir)) {
210
- matchedByRealDir.set(verified.realDir, verified.candidateDir);
211
- }
212
- }
213
- continue;
214
- }
215
- // `namespace_fallback`: only used when no expected `gitUrl` was known
216
- for (const remoteKey of networkKeys) {
217
- const remoteNamespacePath = remoteKey.split("/").slice(1).join("/");
218
- if (normalizedRepo.includes("/")) {
219
- if (remoteNamespacePath === normalizedRepo.toLowerCase()) {
220
- if (!matchedByRealDir.has(verified.realDir)) {
221
- matchedByRealDir.set(verified.realDir, verified.candidateDir);
222
- }
223
- break;
224
- }
225
- }
226
- else {
227
- const remoteBase = remoteKey.split("/").pop() ?? remoteKey;
228
- if (remoteBase === normalizedRepoKey) {
229
- if (!matchedByRealDir.has(verified.realDir)) {
230
- matchedByRealDir.set(verified.realDir, verified.candidateDir);
231
- }
232
- break;
233
- }
234
- }
235
- }
236
- }
237
- if (matchedByRealDir.size > 1) {
238
- return { ambiguous: true };
239
- }
240
- if (matchedByRealDir.size === 1) {
241
- return { match: matchedByRealDir.values().next().value, ambiguous: false };
242
- }
243
- return { ambiguous: false };
244
- }
245
- export function resolveLocalRepoDir(wikiOrRootDir, configOrRepoName, repoNameOrOptions, maybeOptions) {
246
- let rootDir;
247
- let config;
248
- let loadedWiki;
249
- let repoName;
250
- let options;
251
- if (typeof wikiOrRootDir === "string") {
252
- rootDir = wikiOrRootDir;
253
- config = configOrRepoName;
254
- repoName = repoNameOrOptions;
255
- options = maybeOptions ?? {};
256
- }
257
- else {
258
- loadedWiki = wikiOrRootDir;
259
- rootDir = wikiOrRootDir.rootDir;
260
- config = wikiOrRootDir.config;
261
- repoName = configOrRepoName;
262
- options = repoNameOrOptions ?? {};
263
- }
264
- const trimmedRepo = repoName.trim();
265
- if (!trimmedRepo) {
266
- return undefined;
267
- }
268
- const normalizedRepo = toPosixPath(trimmedRepo).replace(/\.git$/i, "");
269
- const normalizedRepoKey = normalizeGitUrlKey(normalizedRepo);
270
- const baseRepoName = normalizedRepo.split("/").pop() ?? normalizedRepo;
271
- const explicit = options.repoPaths?.[repoName] ??
272
- options.repoPaths?.[normalizedRepo] ??
273
- options.repoPaths?.[baseRepoName];
274
- if (explicit) {
275
- return path.resolve(explicit);
276
- }
277
- const effectiveReposDir = options.reposDir?.trim() || process.env.OLW_REPOS_DIR?.trim() || undefined;
278
- const configuredExact = config.repositories?.find((r) => toPosixPath(r.repo.trim())
279
- .replace(/\.git$/i, "")
280
- .toLowerCase() === normalizedRepo.toLowerCase());
281
- // Collect authoritative expected network Git URL keys for identity verification
282
- const expectedNetworkUrlKeys = new Set();
283
- if (options.gitUrl && isNetworkGitUrl(options.gitUrl)) {
284
- const k = normalizeGitUrlKey(options.gitUrl);
285
- if (k) {
286
- expectedNetworkUrlKeys.add(k);
287
- }
288
- }
289
- if (configuredExact?.gitUrl && isNetworkGitUrl(configuredExact.gitUrl)) {
290
- const k = normalizeGitUrlKey(configuredExact.gitUrl);
291
- if (k) {
292
- expectedNetworkUrlKeys.add(k);
293
- }
294
- }
295
- if (loadedWiki) {
296
- for (const scene of loadedWiki.scenes.values()) {
297
- for (const repoRef of scene.frontmatter.repositories) {
298
- const refNorm = toPosixPath(repoRef.repo.trim())
299
- .replace(/\.git$/i, "")
300
- .toLowerCase();
301
- if (refNorm === normalizedRepo.toLowerCase() &&
302
- repoRef.gitUrl &&
303
- isNetworkGitUrl(repoRef.gitUrl)) {
304
- const k = normalizeGitUrlKey(repoRef.gitUrl);
305
- if (k) {
306
- expectedNetworkUrlKeys.add(k);
307
- }
308
- }
309
- }
310
- }
311
- }
312
- if (configuredExact?.localPath) {
313
- const candidate = path.resolve(rootDir, configuredExact.localPath);
314
- if (fsSync.existsSync(candidate) &&
315
- isDirectorySync(candidate) &&
316
- (isGitRepoRoot(candidate) || !effectiveReposDir) &&
317
- !hasConflictingOriginRemote(candidate, normalizedRepo, expectedNetworkUrlKeys)) {
318
- return candidate;
319
- }
320
- }
321
- // Only match `config.repositories` by basename when neither side conflicts on org/namespace
322
- // and at most one configured entry shares that basename
323
- const baseMatches = (config.repositories ?? []).filter((r) => {
324
- const rClean = toPosixPath(r.repo.trim()).replace(/\.git$/i, "");
325
- if (normalizedRepo.includes("/") && rClean.includes("/")) {
326
- return false;
327
- }
328
- return (rClean.split("/").pop() ?? rClean).toLowerCase() === baseRepoName.toLowerCase();
329
- });
330
- if (baseMatches.length === 1 && baseMatches[0]?.localPath) {
331
- const configuredByBase = baseMatches[0];
332
- const candidate = path.resolve(rootDir, configuredByBase.localPath);
333
- if (fsSync.existsSync(candidate) &&
334
- isDirectorySync(candidate) &&
335
- (isGitRepoRoot(candidate) || !effectiveReposDir) &&
336
- !hasConflictingOriginRemote(candidate, normalizedRepo, expectedNetworkUrlKeys)) {
337
- return candidate;
338
- }
339
- }
340
- if (effectiveReposDir) {
341
- // Reject `..`, absolute paths, Windows drives, or root aliases before deriving paths inside `reposDir`
342
- if (!isSafeContainedRelativePath(normalizedRepo)) {
343
- return undefined;
344
- }
345
- const resolvedReposDir = path.resolve(effectiveReposDir);
346
- if (!fsSync.existsSync(resolvedReposDir)) {
347
- return undefined;
348
- }
349
- let reposRealDir;
350
- try {
351
- reposRealDir = fsSync.realpathSync(resolvedReposDir);
352
- }
353
- catch {
354
- return undefined;
355
- }
356
- // 1. Direct `<namespace>/<repo>` path inside `reposDir` (e.g. `.repos/orgA/service`)
357
- if (normalizedRepo.includes("/")) {
358
- const namespacedCandidates = [
359
- path.resolve(resolvedReposDir, normalizedRepo),
360
- path.resolve(resolvedReposDir, `${normalizedRepo}.git`),
361
- ];
362
- for (const rawCandidate of namespacedCandidates) {
363
- const verified = resolveCandidateInReposDirSync(resolvedReposDir, reposRealDir, rawCandidate);
364
- if (verified &&
365
- !hasConflictingOriginRemote(verified.candidateDir, normalizedRepo, expectedNetworkUrlKeys)) {
366
- return verified.candidateDir;
367
- }
368
- }
369
- }
370
- // 2. Exact normalized `gitUrl` match across 1-level subdirectories (rejects >1 distinct matches as ambiguous)
371
- if (expectedNetworkUrlKeys.size > 0) {
372
- const exactScan = scanReposDirByRemoteUrl(resolvedReposDir, reposRealDir, normalizedRepo, normalizedRepoKey, expectedNetworkUrlKeys, "exact_url");
373
- if (exactScan.ambiguous) {
374
- return undefined;
375
- }
376
- if (exactScan.match) {
377
- return exactScan.match;
378
- }
379
- }
380
- // 3. Direct `<repo>` basename path inside `reposDir` when its `origin` remote does NOT conflict
381
- if (isSafeContainedRelativePath(baseRepoName)) {
382
- const basenameCandidates = [
383
- path.resolve(resolvedReposDir, baseRepoName),
384
- path.resolve(resolvedReposDir, `${baseRepoName}.git`),
385
- ];
386
- for (const rawCandidate of basenameCandidates) {
387
- const verified = resolveCandidateInReposDirSync(resolvedReposDir, reposRealDir, rawCandidate);
388
- if (verified &&
389
- !hasConflictingOriginRemote(verified.candidateDir, normalizedRepo, expectedNetworkUrlKeys)) {
390
- return verified.candidateDir;
391
- }
392
- }
393
- }
394
- // 4. Namespace-path remote fallback ONLY when no expected `gitUrl` was known (rejects >1 distinct matches)
395
- if (expectedNetworkUrlKeys.size === 0) {
396
- const fallbackScan = scanReposDirByRemoteUrl(resolvedReposDir, reposRealDir, normalizedRepo, normalizedRepoKey, expectedNetworkUrlKeys, "namespace_fallback");
397
- if (!fallbackScan.ambiguous && fallbackScan.match) {
398
- return fallbackScan.match;
399
- }
400
- }
401
- return undefined;
402
- }
403
- return undefined;
404
- }
405
- /**
406
- * Resolves all repositories referenced across `wiki.config.yaml` and loaded scenes to verified
407
- * existing local POSIX Git repository paths (keyed by `repo` identifier).
408
- */
409
- export function resolveSceneRepoLocalPaths(wiki, options = {}) {
410
- const repoGitUrls = new Map();
411
- for (const cfgRepo of wiki.config.repositories ?? []) {
412
- if (!repoGitUrls.has(cfgRepo.repo)) {
413
- repoGitUrls.set(cfgRepo.repo, cfgRepo.gitUrl);
414
- }
415
- }
416
- for (const scene of wiki.scenes.values()) {
417
- for (const repoRef of scene.frontmatter.repositories) {
418
- if (!repoGitUrls.has(repoRef.repo) || repoRef.gitUrl) {
419
- repoGitUrls.set(repoRef.repo, repoRef.gitUrl);
420
- }
421
- }
422
- for (const anchor of scene.frontmatter.anchors ?? []) {
423
- if (anchor.repo && !repoGitUrls.has(anchor.repo)) {
424
- repoGitUrls.set(anchor.repo, undefined);
425
- }
426
- }
427
- }
428
- const resolvedMap = {};
429
- const sortedRepos = Array.from(repoGitUrls.keys()).sort((a, b) => a.localeCompare(b));
430
- for (const repo of sortedRepos) {
431
- const gitUrl = repoGitUrls.get(repo);
432
- const candidate = resolveLocalRepoDir(wiki, repo, {
433
- ...options,
434
- ...(gitUrl ? { gitUrl } : {}),
435
- });
436
- if (candidate && fsSync.existsSync(candidate) && isGitRepoRoot(candidate)) {
437
- resolvedMap[repo] = toPosixPath(candidate);
438
- }
439
- }
440
- return resolvedMap;
441
- }
442
- export function resolveLocalSourceDir(wikiOrRootDir, configOrSourceName, sourceNameOrOptions, maybeOptions) {
443
- let rootDir;
444
- let config;
445
- let sourceName;
446
- let options;
447
- if (typeof wikiOrRootDir === "string") {
448
- rootDir = wikiOrRootDir;
449
- config = configOrSourceName;
450
- sourceName = sourceNameOrOptions;
451
- options = maybeOptions ?? {};
452
- }
453
- else {
454
- rootDir = wikiOrRootDir.rootDir;
455
- config = wikiOrRootDir.config;
456
- sourceName = configOrSourceName;
457
- options = sourceNameOrOptions ?? {};
458
- }
459
- const trimmedSource = sourceName.trim();
460
- if (!trimmedSource) {
461
- return undefined;
462
- }
463
- const normalizedSource = toPosixPath(trimmedSource);
464
- const baseSourceName = normalizedSource.split("/").pop() ?? normalizedSource;
465
- const explicit = options.sourcePaths?.[sourceName] ??
466
- options.sourcePaths?.[normalizedSource] ??
467
- options.sourcePaths?.[baseSourceName];
468
- if (explicit) {
469
- return path.resolve(explicit);
470
- }
471
- const effectiveSourcesDir = options.sourcesDir?.trim() || process.env.OLW_SOURCES_DIR?.trim() || undefined;
472
- const configuredExact = config.sources?.find((s) => toPosixPath(s.source.trim()).toLowerCase() === normalizedSource.toLowerCase());
473
- if (configuredExact?.localPath) {
474
- const candidate = path.resolve(rootDir, configuredExact.localPath);
475
- if (fsSync.existsSync(candidate) && isDirectorySync(candidate)) {
476
- return candidate;
477
- }
478
- }
479
- if (effectiveSourcesDir) {
480
- if (!isSafeContainedRelativePath(normalizedSource)) {
481
- return undefined;
482
- }
483
- const resolvedSourcesDir = path.resolve(effectiveSourcesDir);
484
- if (!fsSync.existsSync(resolvedSourcesDir)) {
485
- return undefined;
486
- }
487
- let sourcesRealDir;
488
- try {
489
- sourcesRealDir = fsSync.realpathSync(resolvedSourcesDir);
490
- }
491
- catch {
492
- return undefined;
493
- }
494
- const directCandidate = path.resolve(resolvedSourcesDir, normalizedSource);
495
- const verifiedDirect = resolveCandidateInReposDirSync(resolvedSourcesDir, sourcesRealDir, directCandidate);
496
- if (verifiedDirect) {
497
- return verifiedDirect.candidateDir;
498
- }
499
- if (normalizedSource.includes("/") && isSafeContainedRelativePath(baseSourceName)) {
500
- const baseCandidate = path.resolve(resolvedSourcesDir, baseSourceName);
501
- const verifiedBase = resolveCandidateInReposDirSync(resolvedSourcesDir, sourcesRealDir, baseCandidate);
502
- if (verifiedBase) {
503
- return verifiedBase.candidateDir;
504
- }
505
- }
506
- }
507
- return undefined;
508
- }
509
- /**
510
- * Resolves all corpus sources referenced across `wiki.config.yaml` and loaded scenes to verified
511
- * existing local POSIX directory paths (keyed by `source` identifier).
512
- */
513
- export function resolveSceneSourceLocalPaths(wiki, options = {}) {
514
- const sourceNames = new Set();
515
- for (const cfgSrc of wiki.config.sources ?? []) {
516
- sourceNames.add(cfgSrc.source);
517
- }
518
- for (const scene of wiki.scenes.values()) {
519
- for (const srcRef of scene.frontmatter.sources ?? []) {
520
- sourceNames.add(srcRef.source);
521
- }
522
- for (const anchor of scene.frontmatter.anchors ?? []) {
523
- if (anchor.source) {
524
- sourceNames.add(anchor.source);
525
- }
526
- }
527
- }
528
- const resolvedMap = {};
529
- const sortedSources = Array.from(sourceNames).sort((a, b) => a.localeCompare(b));
530
- for (const source of sortedSources) {
531
- const candidate = resolveLocalSourceDir(wiki, source, options);
532
- if (candidate && fsSync.existsSync(candidate) && isDirectorySync(candidate)) {
533
- resolvedMap[source] = toPosixPath(candidate);
534
- }
535
- }
536
- return resolvedMap;
537
- }
538
- export async function computeFileSha256(filePath, cache) {
539
- const cached = cache?.get(filePath);
540
- if (cached) {
541
- return cached;
542
- }
543
- const digest = await new Promise((resolve, reject) => {
544
- const hash = crypto.createHash("sha256");
545
- const stream = fsSync.createReadStream(filePath);
546
- stream.on("data", (chunk) => hash.update(chunk));
547
- stream.on("error", reject);
548
- stream.on("end", () => resolve(hash.digest("hex")));
549
- });
550
- cache?.set(filePath, digest);
551
- return digest;
552
- }
553
- async function resolveContainedRegularFile(resolvedRootDir, rootRealDir, ownerLabel, ownerKind, normRelFile) {
554
- const targetFile = path.resolve(resolvedRootDir, normRelFile);
555
- if (!isSafeContainedRelativePath(normRelFile) ||
556
- !isPathStrictlyInsideRoot(resolvedRootDir, targetFile)) {
557
- return {
558
- ok: false,
559
- message: `File "${normRelFile}" escapes ${ownerKind} root "${ownerLabel}"`,
560
- };
561
- }
562
- try {
563
- const lstat = await fs.lstat(targetFile);
564
- const targetRealFile = await fs.realpath(targetFile);
565
- if (!isPathStrictlyInsideRoot(rootRealDir, targetRealFile)) {
566
- return {
567
- ok: false,
568
- message: `File "${normRelFile}" resolves via symlink/junction outside ${ownerKind} root "${ownerLabel}"`,
569
- };
570
- }
571
- const stat = lstat.isSymbolicLink() ? await fs.stat(targetRealFile) : lstat;
572
- if (!stat.isFile()) {
573
- return {
574
- ok: false,
575
- message: `Path "${normRelFile}" in ${ownerKind} "${ownerLabel}" is not a regular file`,
576
- };
577
- }
578
- return { ok: true, realFilePath: targetRealFile };
579
- }
580
- catch {
581
- let ancestor = path.dirname(targetFile);
582
- while (isPathStrictlyInsideRoot(resolvedRootDir, ancestor)) {
583
- try {
584
- const ancestorReal = await fs.realpath(ancestor);
585
- if (!isPathStrictlyInsideRoot(rootRealDir, ancestorReal)) {
586
- return {
587
- ok: false,
588
- message: `Path "${normRelFile}" traverses a symlink/junction outside ${ownerKind} root "${ownerLabel}"`,
589
- };
590
- }
591
- break;
592
- }
593
- catch {
594
- ancestor = path.dirname(ancestor);
595
- }
596
- }
597
- return {
598
- ok: false,
599
- message: `File "${normRelFile}" not found in ${ownerKind} "${ownerLabel}"`,
600
- };
601
- }
602
- }
603
- export async function verifySourceAnchorOnDisk(sourceDir, anchor) {
604
- const sourceLabel = anchor.source ?? "unknown-source";
605
- if (!sourceDir) {
606
- return {
607
- ok: false,
608
- code: "ANCHOR_SOURCE_UNREACHABLE",
609
- message: `No local path configured for corpus source "${sourceLabel}"`,
610
- };
611
- }
612
- const resolvedSourceDir = path.resolve(sourceDir);
613
- let sourceRealDir;
614
- try {
615
- await fs.access(resolvedSourceDir);
616
- sourceRealDir = await fs.realpath(resolvedSourceDir);
617
- if (!(await fs.stat(sourceRealDir)).isDirectory()) {
618
- return {
619
- ok: false,
620
- code: "ANCHOR_SOURCE_UNREACHABLE",
621
- message: `Corpus source path "${sourceDir}" for "${sourceLabel}" is not a directory`,
622
- };
623
- }
624
- }
625
- catch {
626
- return {
627
- ok: false,
628
- code: "ANCHOR_SOURCE_UNREACHABLE",
629
- message: `Corpus source directory "${sourceDir}" for "${sourceLabel}" does not exist`,
630
- };
631
- }
632
- const normAnchorFile = toPosixPath(anchor.file).replace(/^(?:\.\/|\/)+/, "");
633
- const fileCheck = await resolveContainedRegularFile(resolvedSourceDir, sourceRealDir, sourceLabel, "source", normAnchorFile);
634
- if (!fileCheck.ok) {
635
- return {
636
- ok: false,
637
- code: "BROKEN_ANCHOR_FILE",
638
- message: `Anchor ${fileCheck.message}`,
639
- };
640
- }
641
- if (anchor.symbol) {
642
- const content = await fs.readFile(fileCheck.realFilePath, "utf8");
643
- if (!containsSymbol(content, anchor.symbol)) {
644
- return {
645
- ok: false,
646
- code: "BROKEN_ANCHOR_SYMBOL",
647
- message: `Anchor symbol "${anchor.symbol}" not found in "${normAnchorFile}" (${sourceLabel})`,
648
- };
649
- }
650
- }
651
- return { ok: true };
652
- }
653
- export async function verifyCorpusSourceRefOnDisk(sourceDir, sourceRef, fallbackDocFile, sha256Cache) {
654
- if (!sourceDir) {
655
- return {
656
- ok: false,
657
- code: "SOURCE_UNREACHABLE",
658
- message: `No local path configured for corpus source "${sourceRef.source}"`,
659
- };
660
- }
661
- const resolvedSourceDir = path.resolve(sourceDir);
662
- let sourceRealDir;
663
- try {
664
- await fs.access(resolvedSourceDir);
665
- sourceRealDir = await fs.realpath(resolvedSourceDir);
666
- if (!(await fs.stat(sourceRealDir)).isDirectory()) {
667
- return {
668
- ok: false,
669
- code: "SOURCE_UNREACHABLE",
670
- message: `Corpus source path "${sourceDir}" for "${sourceRef.source}" is not a directory`,
671
- };
672
- }
673
- }
674
- catch {
675
- return {
676
- ok: false,
677
- code: "SOURCE_UNREACHABLE",
678
- message: `Corpus source directory "${sourceDir}" for "${sourceRef.source}" does not exist`,
679
- };
680
- }
681
- const rawTargetRel = sourceRef.path ?? (sourceRef.sha256 ? fallbackDocFile : undefined);
682
- if (!rawTargetRel) {
683
- if (sourceRef.sha256) {
684
- return {
685
- ok: false,
686
- code: "BROKEN_SOURCE_FILE",
687
- message: `Source "${sourceRef.source}" specifies sha256 without a file path`,
688
- };
689
- }
690
- return { ok: true };
691
- }
692
- const normRel = toPosixPath(rawTargetRel).replace(/^(?:\.\/|\/)+/, "");
693
- const fileCheck = await resolveContainedRegularFile(resolvedSourceDir, sourceRealDir, sourceRef.source, "source", normRel);
694
- if (!fileCheck.ok) {
695
- return {
696
- ok: false,
697
- code: "BROKEN_SOURCE_FILE",
698
- normPath: normRel,
699
- message: fileCheck.message,
700
- };
701
- }
702
- if (sourceRef.sha256) {
703
- const actualSha256 = await computeFileSha256(fileCheck.realFilePath, sha256Cache);
704
- if (actualSha256.toLowerCase() !== sourceRef.sha256.toLowerCase()) {
705
- return {
706
- ok: false,
707
- code: "SOURCE_SHA256_MISMATCH",
708
- normPath: normRel,
709
- actualSha256,
710
- message: `Source "${sourceRef.source}" file "${normRel}" SHA-256 mismatch (pinned ${sourceRef.sha256.slice(0, 12)}..., actual ${actualSha256.slice(0, 12)}...)`,
711
- };
712
- }
713
- }
714
- return { ok: true, normPath: normRel };
715
- }
716
- async function verifyAnchorOnDisk(repoDir, anchor) {
717
- if (!repoDir) {
718
- return {
719
- ok: false,
720
- code: "ANCHOR_REPO_UNREACHABLE",
721
- message: `No local checkout path configured for repository "${anchor.repo}"`,
722
- };
723
- }
724
- try {
725
- await fs.access(repoDir);
726
- }
727
- catch {
728
- return {
729
- ok: false,
730
- code: "ANCHOR_REPO_UNREACHABLE",
731
- message: `Repository checkout "${repoDir}" for "${anchor.repo}" does not exist`,
732
- };
733
- }
734
- const normAnchorFile = toPosixPath(anchor.file).replace(/^(?:\.\/|\/)+/, "");
735
- const resolvedRepoDir = path.resolve(repoDir);
736
- const targetFile = path.resolve(resolvedRepoDir, normAnchorFile);
737
- if (!isSafeContainedRelativePath(normAnchorFile) ||
738
- !isPathStrictlyInsideRoot(resolvedRepoDir, targetFile)) {
739
- return {
740
- ok: false,
741
- code: "BROKEN_ANCHOR_FILE",
742
- message: `Anchor file "${normAnchorFile}" escapes repository root "${anchor.repo}"`,
743
- };
744
- }
745
- let repoRealDir = resolvedRepoDir;
746
- try {
747
- repoRealDir = await fs.realpath(resolvedRepoDir);
748
- }
749
- catch {
750
- return {
751
- ok: false,
752
- code: "ANCHOR_REPO_UNREACHABLE",
753
- message: `Repository checkout "${repoDir}" for "${anchor.repo}" could not be resolved`,
754
- };
755
- }
756
- const isBareRepo = isGitRepoRoot(resolvedRepoDir) && (await isBareGitRepository(resolvedRepoDir));
757
- // Bare Git repository: verify `HEAD:<file>` exists strictly as a `"blob"` (rejecting `"tree"` directories)
758
- if (isBareRepo) {
759
- const headSha = await resolveGitCommit(resolvedRepoDir, "HEAD");
760
- if (!headSha) {
761
- return {
762
- ok: false,
763
- code: "ANCHOR_REPO_UNREACHABLE",
764
- message: `Repository "${anchor.repo}" at "${resolvedRepoDir}" has no resolvable HEAD commit`,
765
- };
766
- }
767
- const gitBlob = await inspectGitFileAtRef(resolvedRepoDir, headSha, normAnchorFile, Boolean(anchor.symbol));
768
- if (!gitBlob.exists) {
769
- return {
770
- ok: false,
771
- code: "BROKEN_ANCHOR_FILE",
772
- message: `Anchor file "${normAnchorFile}" not found as blob in bare repo "${anchor.repo}"`,
773
- };
774
- }
775
- if (anchor.symbol && (!gitBlob.content || !containsSymbol(gitBlob.content, anchor.symbol))) {
776
- return {
777
- ok: false,
778
- code: "BROKEN_ANCHOR_SYMBOL",
779
- message: `Anchor symbol "${anchor.symbol}" not found in "${normAnchorFile}" (${anchor.repo})`,
780
- };
781
- }
782
- return { ok: true };
783
- }
784
- // Non-bare working-tree checkout: inspect live file on disk ONLY (never fall back to deleted files in `HEAD`!)
785
- let content;
786
- let fileExists = false;
787
- try {
788
- const lstat = await fs.lstat(targetFile);
789
- const targetRealFile = await fs.realpath(targetFile);
790
- if (!isPathStrictlyInsideRoot(repoRealDir, targetRealFile)) {
791
- return {
792
- ok: false,
793
- code: "BROKEN_ANCHOR_FILE",
794
- message: `Anchor file "${normAnchorFile}" resolves via symlink/junction outside repository root "${anchor.repo}"`,
795
- };
796
- }
797
- const stat = lstat.isSymbolicLink() ? await fs.stat(targetRealFile) : lstat;
798
- if (!stat.isFile()) {
799
- return {
800
- ok: false,
801
- code: "BROKEN_ANCHOR_FILE",
802
- message: `Anchor path "${normAnchorFile}" in repo "${anchor.repo}" is not a regular file`,
803
- };
804
- }
805
- fileExists = true;
806
- if (anchor.symbol) {
807
- content = await fs.readFile(targetRealFile, "utf8");
808
- }
809
- }
810
- catch {
811
- let ancestor = path.dirname(targetFile);
812
- while (isPathStrictlyInsideRoot(resolvedRepoDir, ancestor)) {
813
- try {
814
- const ancestorReal = await fs.realpath(ancestor);
815
- if (!isPathStrictlyInsideRoot(repoRealDir, ancestorReal)) {
816
- return {
817
- ok: false,
818
- code: "BROKEN_ANCHOR_FILE",
819
- message: `Anchor path "${normAnchorFile}" traverses a symlink/junction outside repository root "${anchor.repo}"`,
820
- };
821
- }
822
- break;
823
- }
824
- catch {
825
- ancestor = path.dirname(ancestor);
826
- }
827
- }
828
- }
829
- if (!fileExists) {
830
- return {
831
- ok: false,
832
- code: "BROKEN_ANCHOR_FILE",
833
- message: `Anchor file "${normAnchorFile}" not found in working tree of repo "${anchor.repo}"`,
834
- };
835
- }
836
- if (anchor.symbol && (!content || !containsSymbol(content, anchor.symbol))) {
837
- return {
838
- ok: false,
839
- code: "BROKEN_ANCHOR_SYMBOL",
840
- message: `Anchor symbol "${anchor.symbol}" not found in "${normAnchorFile}" (${anchor.repo})`,
841
- };
842
- }
843
- return { ok: true };
844
- }
845
28
  function detectDependencyCycles(wiki) {
846
29
  const visited = new Set();
847
30
  const inStack = new Set();