md2site-cli 0.2.0__py3-none-any.whl

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.
md2site/links.py ADDED
@@ -0,0 +1,1403 @@
1
+ """Link resolution and token rewriting across docs and repository sources."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ import posixpath
7
+ import re
8
+ from collections.abc import Callable, Mapping, Sequence
9
+ from dataclasses import dataclass
10
+ from pathlib import Path, PurePosixPath
11
+ from typing import Literal
12
+ from urllib.parse import quote, unquote
13
+
14
+ from markdown_it.token import Token
15
+
16
+ from md2site.config import Config
17
+ from md2site.diagnostics import (
18
+ MD2S001,
19
+ MD2S002,
20
+ MD2S003,
21
+ MD2S004,
22
+ MD2S005,
23
+ MD2S006,
24
+ MD2S007,
25
+ MD2S008,
26
+ MD2S010,
27
+ MD2S011,
28
+ Collector,
29
+ suggest_match,
30
+ )
31
+ from md2site.model import AssetCopy, Page, Site
32
+ from md2site.paths import quote_posix_path, rel_url
33
+ from md2site.slug import _base_slug
34
+ from md2site.wikilinks import (
35
+ WikilinkIndex,
36
+ build_wikilink_index,
37
+ resolve_wikilink_embed,
38
+ resolve_wikilink_page,
39
+ )
40
+
41
+ Kind = Literal["external", "mailto_tel", "anchor", "absolute", "relative", "empty"]
42
+
43
+ _FRAG_LINE_RE = re.compile(r"^L(\d+)(?:-L?(\d+))?$")
44
+ _COLON_LINE_RE = re.compile(r":(\d+)(?:-(\d+))?$")
45
+ _WINDOWS_DRIVE_RE = re.compile(r"^([A-Za-z]:)/(.*)$")
46
+ _INDEX_CANDIDATES = ("index.md", "index.markdown", "README.md", "README.markdown")
47
+ _MD_EXTENSIONS = frozenset({".md", ".markdown"})
48
+
49
+
50
+ @dataclass(frozen=True)
51
+ class Resolution:
52
+ """Result of resolving a relative or root-relative link target."""
53
+
54
+ kind: Literal["page", "doc_asset", "repo_file", "broken"]
55
+ target: Path | None
56
+ fragment: str | None
57
+ line_spec: str | None
58
+ page: Page | None = None
59
+ case_mismatch_of: str | None = None
60
+ escapes_repo: bool = False
61
+ broken_code: str | None = None
62
+ query: str | None = None
63
+
64
+
65
+ def classify(href: str) -> Kind:
66
+ """Classify an ``href``/``src`` string into its link category."""
67
+ stripped = href.strip()
68
+ if not stripped:
69
+ return "empty"
70
+ if stripped.startswith("#"):
71
+ return "anchor"
72
+ lower = stripped.lower()
73
+ if lower.startswith(("http://", "https://")):
74
+ return "external"
75
+ if lower.startswith(("mailto:", "tel:")):
76
+ return "mailto_tel"
77
+ if stripped.startswith("/"):
78
+ return "absolute"
79
+ return "relative"
80
+
81
+
82
+ def _normalize_line_spec(start: str, end: str | None) -> str:
83
+ if end is not None:
84
+ return f"L{start}-L{end}"
85
+ return f"L{start}"
86
+
87
+
88
+ def _extract_path_fragment_and_lines(
89
+ href: str,
90
+ ) -> tuple[str, str | None, str | None, str | None, str | None]:
91
+ """Split ``href`` into ``(path, query, fragment, frag_line_spec, colon_line_spec)``."""
92
+ if "#" in href:
93
+ pre_frag, raw_frag = href.split("#", 1)
94
+ else:
95
+ pre_frag, raw_frag = href, None
96
+
97
+ if "?" in pre_frag:
98
+ path_part, raw_query = pre_frag.split("?", 1)
99
+ if not raw_query:
100
+ raw_query = None
101
+ else:
102
+ path_part, raw_query = pre_frag, None
103
+
104
+ frag_line_spec: str | None = None
105
+ if raw_frag is not None:
106
+ frag_match = _FRAG_LINE_RE.match(raw_frag)
107
+ if frag_match:
108
+ frag_line_spec = _normalize_line_spec(frag_match.group(1), frag_match.group(2))
109
+
110
+ colon_line_spec: str | None = None
111
+ # Avoid stripping `:80` or Windows `C:` when there is no path before colon.
112
+ colon_match = _COLON_LINE_RE.search(path_part)
113
+ if colon_match and colon_match.start() > 1:
114
+ colon_line_spec = _normalize_line_spec(colon_match.group(1), colon_match.group(2))
115
+ path_part = path_part[: colon_match.start()]
116
+
117
+ return path_part, raw_query, raw_frag, frag_line_spec, colon_line_spec
118
+
119
+
120
+ def _norm_path(path: Path) -> Path:
121
+ return Path(os.path.normpath(str(path)))
122
+
123
+
124
+ def _lexical_join(base: Path, rel_posix: str) -> Path:
125
+ """Join ``base`` with a relative POSIX path lexically without touching disk."""
126
+ combined = posixpath.normpath(posixpath.join(base.as_posix(), rel_posix))
127
+ return Path(combined)
128
+
129
+
130
+ def _is_within(path: Path, root: Path) -> bool:
131
+ try:
132
+ path.relative_to(root)
133
+ return True
134
+ except ValueError:
135
+ return False
136
+
137
+
138
+ def _rel_posix(path: Path, root: Path) -> PurePosixPath:
139
+ rel = path.relative_to(root).as_posix()
140
+ return PurePosixPath(".") if rel == "." else PurePosixPath(rel)
141
+
142
+
143
+ def resolve_relative(
144
+ page: Page,
145
+ href: str,
146
+ *,
147
+ docs_dir: Path,
148
+ repo_root: Path,
149
+ pages_by_rel: Mapping[PurePosixPath, Page],
150
+ exists: Callable[[Path], bool],
151
+ is_dir: Callable[[Path], bool] | None = None,
152
+ case_lookup: Callable[[Path], Path | None] | None = None,
153
+ ) -> Resolution:
154
+ """Resolve a relative or docs-root-absolute target purely via injected predicates."""
155
+ stripped = href.strip()
156
+ path_part, raw_query, raw_frag, frag_line_spec, colon_line_spec = (
157
+ _extract_path_fragment_and_lines(stripped)
158
+ )
159
+
160
+ is_root_abs = path_part.startswith("/")
161
+ clean_raw = path_part.replace("\\", "/")
162
+ ends_with_slash = clean_raw.endswith("/")
163
+ decoded = unquote(clean_raw)
164
+ if is_root_abs:
165
+ decoded = decoded.lstrip("/")
166
+
167
+ docs_norm = _norm_path(docs_dir)
168
+ repo_norm = _norm_path(repo_root)
169
+
170
+ if is_root_abs:
171
+ base_dir = docs_norm
172
+ else:
173
+ page_dir = page.rel.parent
174
+ base_dir = docs_norm if page_dir == PurePosixPath(".") else docs_norm / page_dir
175
+
176
+ rel_norm = decoded.lstrip("/") if is_root_abs else decoded
177
+ target_abs = (
178
+ docs_norm
179
+ if (is_root_abs and not rel_norm) or rel_norm in ("", ".")
180
+ else _lexical_join(base_dir, rel_norm)
181
+ )
182
+
183
+ if not _is_within(target_abs, repo_norm):
184
+ return Resolution(
185
+ kind="broken",
186
+ target=target_abs,
187
+ fragment=raw_frag,
188
+ line_spec=colon_line_spec or frag_line_spec,
189
+ escapes_repo=True,
190
+ broken_code=MD2S007,
191
+ query=raw_query,
192
+ )
193
+
194
+ pages_lower: dict[str, Page] = {k.as_posix().lower(): v for k, v in pages_by_rel.items()}
195
+
196
+ if _is_within(target_abs, docs_norm):
197
+ doc_rel = _rel_posix(target_abs, docs_norm)
198
+
199
+ # 1. Exact page match
200
+ if doc_rel != PurePosixPath(".") and doc_rel in pages_by_rel:
201
+ matched_page = pages_by_rel[doc_rel]
202
+ return Resolution(
203
+ kind="page",
204
+ target=matched_page.src,
205
+ fragment=raw_frag,
206
+ line_spec=None,
207
+ page=matched_page,
208
+ query=raw_query,
209
+ )
210
+
211
+ # 2. Directory index match (e.g. "dir/", "dir", "./", "/")
212
+ dir_prefix = "" if doc_rel == PurePosixPath(".") else doc_rel.as_posix()
213
+ check_as_dir = (
214
+ ends_with_slash
215
+ or doc_rel == PurePosixPath(".")
216
+ or doc_rel.suffix == ""
217
+ or (is_dir is not None and is_dir(target_abs))
218
+ )
219
+ if check_as_dir:
220
+ for idx_name in _INDEX_CANDIDATES:
221
+ cand_str = idx_name if not dir_prefix else f"{dir_prefix}/{idx_name}"
222
+ cand_rel = PurePosixPath(cand_str)
223
+ if cand_rel in pages_by_rel:
224
+ matched_page = pages_by_rel[cand_rel]
225
+ return Resolution(
226
+ kind="page",
227
+ target=matched_page.src,
228
+ fragment=raw_frag,
229
+ line_spec=None,
230
+ page=matched_page,
231
+ query=raw_query,
232
+ )
233
+ ci_page = pages_lower.get(cand_str.lower())
234
+ if ci_page is not None:
235
+ return Resolution(
236
+ kind="page",
237
+ target=ci_page.src,
238
+ fragment=raw_frag,
239
+ line_spec=None,
240
+ page=ci_page,
241
+ case_mismatch_of=ci_page.rel.as_posix(),
242
+ query=raw_query,
243
+ )
244
+ if ends_with_slash or (is_dir is not None and is_dir(target_abs)):
245
+ return Resolution(
246
+ kind="broken",
247
+ target=target_abs,
248
+ fragment=raw_frag,
249
+ line_spec=None,
250
+ broken_code=MD2S001,
251
+ query=raw_query,
252
+ )
253
+
254
+ # 3. Case-insensitive fallback for pages (runs before filesystem asset check
255
+ # so case-insensitive macOS/Windows filesystems don't treat Setup.md as doc_asset)
256
+ if doc_rel != PurePosixPath("."):
257
+ ci_page = pages_lower.get(doc_rel.as_posix().lower())
258
+ if ci_page is not None:
259
+ return Resolution(
260
+ kind="page",
261
+ target=ci_page.src,
262
+ fragment=raw_frag,
263
+ line_spec=None,
264
+ page=ci_page,
265
+ case_mismatch_of=ci_page.rel.as_posix(),
266
+ query=raw_query,
267
+ )
268
+
269
+ # 4. Non-Markdown doc asset (exact case check first, then case-insensitive fallback)
270
+ target_is_dir = is_dir is not None and is_dir(target_abs)
271
+ if doc_rel != PurePosixPath(".") and not target_is_dir and exists(target_abs):
272
+ mismatch_rel: str | None = None
273
+ if case_lookup is not None:
274
+ actual = case_lookup(target_abs)
275
+ if actual is not None and _rel_posix(actual, docs_norm) != doc_rel:
276
+ mismatch_rel = _rel_posix(actual, docs_norm).as_posix()
277
+ target_abs = actual
278
+ return Resolution(
279
+ kind="doc_asset",
280
+ target=target_abs,
281
+ fragment=raw_frag,
282
+ line_spec=colon_line_spec or frag_line_spec,
283
+ case_mismatch_of=mismatch_rel,
284
+ query=raw_query,
285
+ )
286
+
287
+ if doc_rel != PurePosixPath(".") and case_lookup is not None:
288
+ actual = case_lookup(target_abs)
289
+ if actual is not None and (is_dir is None or not is_dir(actual)):
290
+ actual_rel = _rel_posix(actual, docs_norm).as_posix()
291
+ return Resolution(
292
+ kind="doc_asset",
293
+ target=actual,
294
+ fragment=raw_frag,
295
+ line_spec=colon_line_spec or frag_line_spec,
296
+ case_mismatch_of=actual_rel,
297
+ query=raw_query,
298
+ )
299
+
300
+ is_md_like = (
301
+ doc_rel.suffix.lower() in _MD_EXTENSIONS or ends_with_slash or doc_rel.suffix == ""
302
+ )
303
+ return Resolution(
304
+ kind="broken",
305
+ target=target_abs,
306
+ fragment=raw_frag,
307
+ line_spec=colon_line_spec or frag_line_spec,
308
+ broken_code=MD2S001 if is_md_like else MD2S002,
309
+ query=raw_query,
310
+ )
311
+
312
+ # Outside docs_dir, inside repo_root -> repo_file
313
+ line_spec = colon_line_spec or frag_line_spec
314
+ repo_frag = None if frag_line_spec else raw_frag
315
+ target_is_dir = is_dir is not None and is_dir(target_abs)
316
+ if not target_is_dir and exists(target_abs):
317
+ mismatch_repo: str | None = None
318
+ if case_lookup is not None:
319
+ actual = case_lookup(target_abs)
320
+ if actual is not None and _rel_posix(actual, repo_norm) != _rel_posix(
321
+ target_abs, repo_norm
322
+ ):
323
+ mismatch_repo = _rel_posix(actual, repo_norm).as_posix()
324
+ target_abs = actual
325
+ return Resolution(
326
+ kind="repo_file",
327
+ target=target_abs,
328
+ fragment=repo_frag,
329
+ line_spec=line_spec,
330
+ case_mismatch_of=mismatch_repo,
331
+ query=raw_query,
332
+ )
333
+
334
+ if case_lookup is not None:
335
+ actual = case_lookup(target_abs)
336
+ if actual is not None and (is_dir is None or not is_dir(actual)):
337
+ return Resolution(
338
+ kind="repo_file",
339
+ target=actual,
340
+ fragment=repo_frag,
341
+ line_spec=line_spec,
342
+ case_mismatch_of=_rel_posix(actual, repo_norm).as_posix(),
343
+ query=raw_query,
344
+ )
345
+
346
+ return Resolution(
347
+ kind="broken",
348
+ target=target_abs,
349
+ fragment=repo_frag,
350
+ line_spec=line_spec,
351
+ broken_code=MD2S002,
352
+ query=raw_query,
353
+ )
354
+
355
+
356
+ def format_editor_url(
357
+ scheme: str,
358
+ target_abs: Path | str,
359
+ line_spec: str | None = None,
360
+ ) -> str:
361
+ """Format an editor deep-link URI such as ``vscode://file/...[:line]``."""
362
+ raw = str(target_abs).replace("\\", "/")
363
+ win_match = _WINDOWS_DRIVE_RE.match(raw)
364
+ if win_match:
365
+ drive = win_match.group(1)
366
+ rest = win_match.group(2).lstrip("/")
367
+ encoded_rest = "/".join(quote(seg, safe="") for seg in rest.split("/") if seg)
368
+ uri = f"{scheme}://file/{drive}/{encoded_rest}"
369
+ else:
370
+ trimmed = raw.lstrip("/")
371
+ encoded = "/".join(quote(seg, safe="") for seg in trimmed.split("/") if seg)
372
+ uri = f"{scheme}://file/{encoded}"
373
+
374
+ if line_spec:
375
+ start_line = line_spec.lstrip("L").split("-", 1)[0]
376
+ if start_line.isdigit():
377
+ uri += f":{start_line}"
378
+ return uri
379
+
380
+
381
+ def format_remote_url(
382
+ remote_repo_url: str,
383
+ remote_branch: str,
384
+ repo_rel: PurePosixPath,
385
+ line_spec: str | None = None,
386
+ query: str | None = None,
387
+ ) -> str:
388
+ """Format a remote repository blob URL with optional query and ``#L..`` line anchor."""
389
+ base = remote_repo_url.rstrip("/")
390
+ branch = quote(remote_branch, safe="/")
391
+ encoded_rel = quote_posix_path(repo_rel)
392
+ url = f"{base}/blob/{branch}/{encoded_rel}"
393
+ if query:
394
+ url += f"?{query}"
395
+ if line_spec:
396
+ url += f"#{line_spec}"
397
+ return url
398
+
399
+
400
+ def _format_file_uri(
401
+ target_abs: Path,
402
+ *,
403
+ line_spec: str | None = None,
404
+ fragment: str | None = None,
405
+ query: str | None = None,
406
+ ) -> str:
407
+ url = target_abs.resolve().as_uri()
408
+ if query:
409
+ url += f"?{query}"
410
+ if line_spec:
411
+ url += f"#{line_spec}"
412
+ elif fragment:
413
+ url += f"#{quote(fragment, safe='')}"
414
+ return url
415
+
416
+
417
+ def _format_relative_fs_url_checked(
418
+ from_dir: Path,
419
+ target_abs: Path,
420
+ *,
421
+ line_spec: str | None = None,
422
+ fragment: str | None = None,
423
+ query: str | None = None,
424
+ ) -> tuple[str, bool]:
425
+ """Format a relative FS URL and report ``(url, cross_drive_fallback_used)``."""
426
+ # Note: relative repo-file links assume output_dir stays on a reachable mount.
427
+ try:
428
+ rel_raw = os.path.relpath(str(target_abs), start=str(from_dir)).replace(os.sep, "/")
429
+ except ValueError:
430
+ return (
431
+ _format_file_uri(
432
+ target_abs,
433
+ line_spec=line_spec,
434
+ fragment=fragment,
435
+ query=query,
436
+ ),
437
+ True,
438
+ )
439
+ encoded_parts = [
440
+ part if part in (".", "..") else quote(part, safe="") for part in rel_raw.split("/")
441
+ ]
442
+ url = "/".join(encoded_parts)
443
+ if not url.startswith(("./", "../")):
444
+ url = f"./{url}"
445
+ if query:
446
+ url += f"?{query}"
447
+ if line_spec:
448
+ url += f"#{line_spec}"
449
+ elif fragment:
450
+ url += f"#{quote(fragment, safe='')}"
451
+ return url, False
452
+
453
+
454
+ def _format_relative_fs_url(
455
+ from_dir: Path,
456
+ target_abs: Path,
457
+ *,
458
+ line_spec: str | None = None,
459
+ fragment: str | None = None,
460
+ query: str | None = None,
461
+ ) -> str:
462
+ url, _ = _format_relative_fs_url_checked(
463
+ from_dir,
464
+ target_abs,
465
+ line_spec=line_spec,
466
+ fragment=fragment,
467
+ query=query,
468
+ )
469
+ return url
470
+
471
+
472
+ @dataclass
473
+ class SiteIndex:
474
+ """Precomputed index of pages, heading IDs, wikilink tables, and cached dir scans."""
475
+
476
+ docs_dir: Path
477
+ repo_root: Path
478
+ pages_by_rel: dict[PurePosixPath, Page]
479
+ heading_ids: dict[PurePosixPath, set[str]]
480
+ heading_text_map: dict[PurePosixPath, dict[str, str]]
481
+ wikilinks: WikilinkIndex
482
+ docs_non_md_files: list[PurePosixPath]
483
+ dir_cache: dict[Path, dict[str, tuple[str, bool]]]
484
+
485
+ def list_dir(self, directory: Path) -> dict[str, tuple[str, bool]]:
486
+ """Return cached ``{name_lower: (actual_name, is_dir)}`` for ``directory``."""
487
+ norm_dir = _norm_path(directory)
488
+ if norm_dir not in self.dir_cache:
489
+ entries: dict[str, tuple[str, bool]] = {}
490
+ if norm_dir.is_dir():
491
+ try:
492
+ with os.scandir(norm_dir) as it:
493
+ for entry in sorted(it, key=lambda e: e.name):
494
+ entries.setdefault(
495
+ entry.name.lower(),
496
+ (entry.name, entry.is_dir(follow_symlinks=False)),
497
+ )
498
+ except OSError:
499
+ pass
500
+ self.dir_cache[norm_dir] = entries
501
+ return self.dir_cache[norm_dir]
502
+
503
+ def exists(self, path: Path) -> bool:
504
+ norm = _norm_path(path)
505
+ entries = self.list_dir(norm.parent)
506
+ exact = entries.get(norm.name.lower())
507
+ if exact is not None and exact[0] == norm.name:
508
+ return True
509
+ return norm.exists()
510
+
511
+ def is_dir(self, path: Path) -> bool:
512
+ norm = _norm_path(path)
513
+ entries = self.list_dir(norm.parent)
514
+ exact = entries.get(norm.name.lower())
515
+ if exact is not None and exact[0] == norm.name:
516
+ return exact[1]
517
+ return norm.is_dir()
518
+
519
+ def case_lookup(self, path: Path) -> Path | None:
520
+ """Walk from ``repo_root`` using exact directory entries to match case-insensitively."""
521
+ norm = _norm_path(path)
522
+ repo_norm = _norm_path(self.repo_root)
523
+ if not _is_within(norm, repo_norm):
524
+ return None
525
+ rel = norm.relative_to(repo_norm)
526
+ curr = repo_norm
527
+ for idx, part in enumerate(rel.parts):
528
+ entries = self.list_dir(curr)
529
+ found = entries.get(part.lower())
530
+ if found is None:
531
+ return None
532
+ actual_name, entry_is_dir = found
533
+ is_last = idx == len(rel.parts) - 1
534
+ if not is_last and not entry_is_dir:
535
+ return None
536
+ curr = curr / actual_name
537
+ return curr
538
+
539
+
540
+ def _scan_docs_non_md_files(docs_dir: Path, output_dir: Path) -> list[PurePosixPath]:
541
+ """List non-Markdown files under ``docs_dir`` (skipping output_dir and dot-dirs)."""
542
+ result: list[PurePosixPath] = []
543
+ docs_norm = docs_dir.resolve()
544
+ out_norm = output_dir.resolve()
545
+
546
+ def _walk(curr: Path, rel: PurePosixPath | None) -> None:
547
+ curr_res = curr.resolve()
548
+ if curr_res == out_norm or out_norm in curr_res.parents:
549
+ return
550
+ try:
551
+ with os.scandir(curr) as it:
552
+ entries = sorted(it, key=lambda e: e.name)
553
+ except OSError:
554
+ return
555
+ for entry in entries:
556
+ name = entry.name
557
+ entry_rel = PurePosixPath(name) if rel is None else rel / name
558
+ entry_path = Path(entry.path)
559
+ if entry.is_dir(follow_symlinks=False):
560
+ if name in (".git", "node_modules", ".venv", "__pycache__") or name.startswith("."):
561
+ continue
562
+ _walk(entry_path, entry_rel)
563
+ elif entry.is_file(follow_symlinks=True):
564
+ if Path(name).suffix.lower() in _MD_EXTENSIONS:
565
+ continue
566
+ result.append(entry_rel)
567
+
568
+ if docs_norm.is_dir():
569
+ _walk(docs_norm, None)
570
+ return sorted(result, key=lambda p: p.as_posix())
571
+
572
+
573
+ def build_index(site: Site) -> SiteIndex:
574
+ """Build lookup tables for pages, headings, wikilinks, and doc assets."""
575
+ docs_dir = site.config.docs_dir.resolve()
576
+ repo_root = site.config.repo_root.resolve()
577
+ pages_by_rel: dict[PurePosixPath, Page] = {}
578
+ heading_ids: dict[PurePosixPath, set[str]] = {}
579
+ heading_text_map: dict[PurePosixPath, dict[str, str]] = {}
580
+
581
+ for page in sorted(site.pages, key=lambda p: p.rel.as_posix()):
582
+ pages_by_rel[page.rel] = page
583
+ heading_ids[page.rel] = {h.id for h in page.headings}
584
+ text_map: dict[str, str] = {}
585
+ for h in page.headings:
586
+ text_map.setdefault(h.text.strip().lower(), h.id)
587
+ heading_text_map[page.rel] = text_map
588
+
589
+ site.by_rel = pages_by_rel
590
+ docs_non_md = _scan_docs_non_md_files(docs_dir, site.config.output_dir)
591
+
592
+ return SiteIndex(
593
+ docs_dir=docs_dir,
594
+ repo_root=repo_root,
595
+ pages_by_rel=pages_by_rel,
596
+ heading_ids=heading_ids,
597
+ heading_text_map=heading_text_map,
598
+ wikilinks=build_wikilink_index(site.pages),
599
+ docs_non_md_files=docs_non_md,
600
+ dir_cache={},
601
+ )
602
+
603
+
604
+ def _add_token_attr_word(token: Token, attr_name: str, word: str) -> None:
605
+ existing = token.attrGet(attr_name)
606
+ words = str(existing).split() if existing else []
607
+ if word not in words:
608
+ words.append(word)
609
+ token.attrSet(attr_name, " ".join(words))
610
+
611
+
612
+ def _page_suggestion_candidates(source_page: Page, index: SiteIndex) -> list[str]:
613
+ source_dir = (
614
+ "." if source_page.rel.parent == PurePosixPath(".") else source_page.rel.parent.as_posix()
615
+ )
616
+ cands: set[str] = set()
617
+ for p_rel in index.pages_by_rel:
618
+ cands.add(p_rel.as_posix())
619
+ rel_str = posixpath.relpath(p_rel.as_posix(), start=source_dir)
620
+ cands.add(rel_str)
621
+ if "/" not in rel_str:
622
+ cands.add(f"./{rel_str}")
623
+ return sorted(cands)
624
+
625
+
626
+ def _asset_suggestion_candidates(
627
+ source_page: Page,
628
+ target_abs: Path | None,
629
+ index: SiteIndex,
630
+ ) -> list[str]:
631
+ source_dir = (
632
+ "." if source_page.rel.parent == PurePosixPath(".") else source_page.rel.parent.as_posix()
633
+ )
634
+ cands: set[str] = set()
635
+ for f_rel in index.docs_non_md_files:
636
+ cands.add(f_rel.as_posix())
637
+ rel_str = posixpath.relpath(f_rel.as_posix(), start=source_dir)
638
+ cands.add(rel_str)
639
+ if "/" not in rel_str:
640
+ cands.add(f"./{rel_str}")
641
+
642
+ if target_abs is not None:
643
+ parent = _norm_path(target_abs).parent
644
+ entries = index.list_dir(parent)
645
+ page_fs_dir = (
646
+ index.docs_dir
647
+ if source_page.rel.parent == PurePosixPath(".")
648
+ else index.docs_dir / source_page.rel.parent
649
+ )
650
+ for actual_name, entry_is_dir in entries.values():
651
+ if entry_is_dir:
652
+ continue
653
+ cand_path = parent / actual_name
654
+ rel_str = os.path.relpath(str(cand_path), start=str(page_fs_dir)).replace(os.sep, "/")
655
+ cands.add(rel_str)
656
+ return sorted(cands)
657
+
658
+
659
+ def _wikilink_suggestion_candidates(index: SiteIndex) -> list[str]:
660
+ cands: set[str] = set()
661
+ for page in index.pages_by_rel.values():
662
+ cands.add(page.rel.stem)
663
+ cands.add(page.rel.with_suffix("").as_posix())
664
+ if page.title:
665
+ cands.add(page.title)
666
+ cands.update(a for a in page.aliases if a)
667
+ return sorted(cands)
668
+
669
+
670
+ def _resolve_heading_fragment(
671
+ target_page: Page,
672
+ raw_fragment: str,
673
+ index: SiteIndex,
674
+ *,
675
+ is_wikilink: bool,
676
+ ) -> tuple[str | None, bool]:
677
+ """Return ``(resolved_id, is_valid)`` for a heading fragment on ``target_page``."""
678
+ decoded = unquote(raw_fragment).strip()
679
+ ids = index.heading_ids.get(target_page.rel, set())
680
+ if decoded in ids:
681
+ return decoded, True
682
+
683
+ if is_wikilink:
684
+ by_text = index.heading_text_map.get(target_page.rel, {})
685
+ if decoded.lower() in by_text:
686
+ return by_text[decoded.lower()], True
687
+ slugged = _base_slug(decoded)
688
+ if slugged in ids:
689
+ return slugged, True
690
+
691
+ return None, False
692
+
693
+
694
+ def _register_asset(
695
+ src: Path,
696
+ dest_rel: PurePosixPath,
697
+ asset_map: dict[PurePosixPath, Path],
698
+ collector: Collector,
699
+ source_file: str,
700
+ line: int | None,
701
+ ) -> None:
702
+ resolved_src = src.resolve() if src.exists() else src
703
+ existing = asset_map.get(dest_rel)
704
+ if existing is None:
705
+ asset_map[dest_rel] = resolved_src
706
+ elif existing != resolved_src:
707
+ collector.add(
708
+ code=MD2S008,
709
+ file=source_file,
710
+ line=line,
711
+ message=(
712
+ f"Asset output collision at {dest_rel.as_posix()} (already claimed by {existing})"
713
+ ),
714
+ target=dest_rel.as_posix(),
715
+ )
716
+
717
+
718
+ def _find_matching_link_close(children: Sequence[Token], open_idx: int) -> int | None:
719
+ depth = 0
720
+ for idx in range(open_idx, len(children)):
721
+ if children[idx].type == "link_open":
722
+ depth += 1
723
+ elif children[idx].type == "link_close":
724
+ depth -= 1
725
+ if depth == 0:
726
+ return idx
727
+ return None
728
+
729
+
730
+ def _autolink_code_span(
731
+ code_text: str,
732
+ source_page: Page,
733
+ index: SiteIndex,
734
+ ) -> Resolution | None:
735
+ """Resolve an inline code path (e.g. ``src/server.py:42``) if it exists on disk."""
736
+ stripped = code_text.strip()
737
+ if not stripped or any(ch.isspace() for ch in stripped) or "://" in stripped:
738
+ return None
739
+ if stripped.startswith(("-", "<", ">", "#")):
740
+ return None
741
+
742
+ path_part, _raw_query, _raw_frag, _frag_line, colon_line = _extract_path_fragment_and_lines(
743
+ stripped
744
+ )
745
+ if "/" not in path_part and "." not in path_part:
746
+ return None
747
+
748
+ clean_path = path_part.replace("\\", "/").lstrip("./")
749
+ if not clean_path:
750
+ return None
751
+
752
+ # 1. Check relative to repo_root (e.g. `src/server.py`)
753
+ cand_repo = _lexical_join(index.repo_root, clean_path)
754
+ if (
755
+ _is_within(cand_repo, index.repo_root)
756
+ and index.exists(cand_repo)
757
+ and not index.is_dir(cand_repo)
758
+ ):
759
+ if _is_within(cand_repo, index.docs_dir):
760
+ doc_rel = _rel_posix(cand_repo, index.docs_dir)
761
+ if doc_rel in index.pages_by_rel:
762
+ return Resolution(
763
+ kind="page",
764
+ target=cand_repo,
765
+ fragment=None,
766
+ line_spec=None,
767
+ page=index.pages_by_rel[doc_rel],
768
+ )
769
+ return Resolution(
770
+ kind="doc_asset",
771
+ target=cand_repo,
772
+ fragment=None,
773
+ line_spec=colon_line,
774
+ )
775
+ return Resolution(
776
+ kind="repo_file",
777
+ target=cand_repo,
778
+ fragment=None,
779
+ line_spec=colon_line,
780
+ )
781
+
782
+ # 2. Check relative to page dir, then docs_dir
783
+ page_fs_dir = (
784
+ index.docs_dir
785
+ if source_page.rel.parent == PurePosixPath(".")
786
+ else index.docs_dir / source_page.rel.parent
787
+ )
788
+ for base in (page_fs_dir, index.docs_dir):
789
+ cand = _lexical_join(base, clean_path)
790
+ if _is_within(cand, index.repo_root) and index.exists(cand) and not index.is_dir(cand):
791
+ if _is_within(cand, index.docs_dir):
792
+ doc_rel = _rel_posix(cand, index.docs_dir)
793
+ if doc_rel in index.pages_by_rel:
794
+ return Resolution(
795
+ kind="page",
796
+ target=cand,
797
+ fragment=None,
798
+ line_spec=None,
799
+ page=index.pages_by_rel[doc_rel],
800
+ )
801
+ return Resolution(
802
+ kind="doc_asset",
803
+ target=cand,
804
+ fragment=None,
805
+ line_spec=colon_line,
806
+ )
807
+ return Resolution(
808
+ kind="repo_file",
809
+ target=cand,
810
+ fragment=None,
811
+ line_spec=colon_line,
812
+ )
813
+
814
+ return None
815
+
816
+
817
+ def _token_line_advance(token: Token) -> int:
818
+ """Return the number of source line breaks spanned by an inline child token."""
819
+ advance = 1 if token.type in ("softbreak", "hardbreak") else token.content.count("\n")
820
+ if token.children:
821
+ advance += sum(_token_line_advance(child) for child in token.children)
822
+ return advance
823
+
824
+
825
+ def resolve_site(site: Site) -> None:
826
+ """Resolve and rewrite all page links, wikilinks, and assets on ``site``."""
827
+ index = build_index(site)
828
+ collector = Collector(site.diagnostics)
829
+ asset_map: dict[PurePosixPath, Path] = {a.dest_rel: a.src for a in site.assets}
830
+ emitted_md2s010 = any(d.code == MD2S010 for d in site.diagnostics)
831
+ emitted_md2s011 = any(d.code == MD2S011 for d in site.diagnostics)
832
+ config: Config = site.config
833
+
834
+ def _emit_md2s010_once(file_rel: str, line: int | None) -> None:
835
+ nonlocal emitted_md2s010
836
+ if not emitted_md2s010:
837
+ collector.add(
838
+ code=MD2S010,
839
+ file=file_rel,
840
+ line=line,
841
+ message=(
842
+ f"source_link_mode '{config.source_link_mode}' requires remote_repo_url; "
843
+ "falling back to 'relative'"
844
+ ),
845
+ )
846
+ emitted_md2s010 = True
847
+
848
+ def _emit_md2s011_once(file_rel: str, line: int | None, target_ref: str) -> None:
849
+ nonlocal emitted_md2s011
850
+ if not emitted_md2s011:
851
+ collector.add(
852
+ code=MD2S011,
853
+ file=file_rel,
854
+ line=line,
855
+ message=(
856
+ "output_dir is on a different filesystem from repo_root in "
857
+ f"'{config.source_link_mode}' mode; falling back to file:// URI "
858
+ "(pass --mode remote or --mode editor for portable links)"
859
+ ),
860
+ target=target_ref,
861
+ )
862
+ emitted_md2s011 = True
863
+
864
+ def _apply_repo_file_href(
865
+ token: Token,
866
+ source_page: Page,
867
+ target_abs: Path,
868
+ line_spec: str | None,
869
+ fragment: str | None,
870
+ line: int | None,
871
+ query: str | None = None,
872
+ ) -> None:
873
+ mode = config.source_link_mode
874
+ if mode == "editor":
875
+ token.attrSet(
876
+ "href",
877
+ format_editor_url(config.editor_scheme, target_abs, line_spec),
878
+ )
879
+ return
880
+
881
+ has_remote = bool(config.remote_repo_url.strip())
882
+ remote_url = (
883
+ format_remote_url(
884
+ config.remote_repo_url,
885
+ config.remote_branch,
886
+ _rel_posix(target_abs, index.repo_root),
887
+ line_spec,
888
+ query=query,
889
+ )
890
+ if has_remote
891
+ else None
892
+ )
893
+
894
+ if mode == "remote":
895
+ if remote_url is not None:
896
+ token.attrSet("href", remote_url)
897
+ return
898
+ _emit_md2s010_once(source_page.rel.as_posix(), line)
899
+
900
+ html_dir = (config.output_dir / source_page.out_rel).parent
901
+ rel_href, cross_drive = _format_relative_fs_url_checked(
902
+ html_dir,
903
+ target_abs,
904
+ line_spec=line_spec,
905
+ fragment=fragment,
906
+ query=query,
907
+ )
908
+ if cross_drive:
909
+ if remote_url is not None:
910
+ rel_href = remote_url
911
+ else:
912
+ _emit_md2s011_once(source_page.rel.as_posix(), line, rel_href)
913
+
914
+ token.attrSet("href", rel_href)
915
+ if mode == "auto":
916
+ if remote_url is None:
917
+ _emit_md2s010_once(source_page.rel.as_posix(), line)
918
+ else:
919
+ token.attrSet("data-remote", remote_url)
920
+
921
+ for page in sorted(site.pages, key=lambda p: p.rel.as_posix()):
922
+ page_file = page.rel.as_posix()
923
+ fallback_line = 1
924
+
925
+ for token in page.tokens:
926
+ if token.map is not None:
927
+ fallback_line = token.map[0] + 1
928
+ if token.type != "inline" or not token.children:
929
+ continue
930
+
931
+ current_line = (token.map[0] + 1) if token.map is not None else fallback_line
932
+
933
+ children = token.children
934
+ check_code = config.autolink_code_paths
935
+ if not any(
936
+ c.type == "link_open"
937
+ or c.type == "image"
938
+ or (check_code and c.type == "code_inline")
939
+ for c in children
940
+ ):
941
+ continue
942
+
943
+ new_children: list[Token] = []
944
+ link_depth = 0
945
+ idx = 0
946
+
947
+ while idx < len(children):
948
+ child = children[idx]
949
+ line = current_line
950
+ current_line += _token_line_advance(child)
951
+
952
+ if child.type == "link_open":
953
+ link_depth += 1
954
+ if child.meta.get("_resolved"):
955
+ new_children.append(child)
956
+ idx += 1
957
+ continue
958
+
959
+ child.meta["_resolved"] = True
960
+ wl_meta = child.meta.get("wikilink")
961
+
962
+ if wl_meta is not None:
963
+ raw_target = str(wl_meta["target"])
964
+ raw_frag = wl_meta["fragment"]
965
+ if not raw_target and raw_frag:
966
+ # Same-page wikilink [[#Heading]]
967
+ resolved_id, valid = _resolve_heading_fragment(
968
+ page, raw_frag, index, is_wikilink=True
969
+ )
970
+ if valid and resolved_id is not None:
971
+ child.attrSet("href", f"#{quote(resolved_id, safe='')}")
972
+ else:
973
+ child.attrSet("href", f"#{quote(raw_frag, safe='')}")
974
+ _add_token_attr_word(child, "class", "broken-link")
975
+ child.attrSet("data-broken", "true")
976
+ collector.add(
977
+ code=MD2S005,
978
+ file=page_file,
979
+ line=line,
980
+ message=f"Heading anchor not found: #{raw_frag}",
981
+ target=f"#{raw_frag}",
982
+ suggestion=suggest_match(
983
+ _base_slug(raw_frag),
984
+ sorted(index.heading_ids.get(page.rel, set())),
985
+ ),
986
+ )
987
+ new_children.append(child)
988
+ idx += 1
989
+ continue
990
+
991
+ target_page, others, case_rel = resolve_wikilink_page(
992
+ page, raw_target, index.wikilinks
993
+ )
994
+ if target_page is None:
995
+ close_idx = _find_matching_link_close(children, idx)
996
+ child.tag = "span"
997
+ child.attrs = {
998
+ "class": "broken-link",
999
+ "title": "Unresolved wikilink",
1000
+ }
1001
+ if close_idx is not None:
1002
+ children[close_idx].tag = "span"
1003
+ collector.add(
1004
+ code=MD2S004,
1005
+ file=page_file,
1006
+ line=line,
1007
+ message=f"Unresolved wikilink: [[{wl_meta['raw']}]]",
1008
+ target=raw_target,
1009
+ suggestion=suggest_match(
1010
+ raw_target, _wikilink_suggestion_candidates(index)
1011
+ ),
1012
+ )
1013
+ new_children.append(child)
1014
+ idx += 1
1015
+ continue
1016
+
1017
+ if case_rel is not None:
1018
+ collector.add(
1019
+ code=MD2S006,
1020
+ file=page_file,
1021
+ line=line,
1022
+ message=(
1023
+ f"Case mismatch in wikilink '{raw_target}' "
1024
+ f"(matches '{case_rel}')"
1025
+ ),
1026
+ target=raw_target,
1027
+ suggestion=case_rel,
1028
+ )
1029
+ if others:
1030
+ collector.add(
1031
+ code=MD2S003,
1032
+ file=page_file,
1033
+ line=line,
1034
+ message=(
1035
+ f"Ambiguous wikilink '[[{raw_target}]]'; "
1036
+ f"resolved to {target_page.rel.as_posix()} "
1037
+ f"(other candidates: {', '.join(others)})"
1038
+ ),
1039
+ target=raw_target,
1040
+ suggestion=target_page.rel.as_posix(),
1041
+ )
1042
+
1043
+ url = rel_url(page.out_rel, target_page.out_rel)
1044
+ if raw_frag:
1045
+ resolved_id, valid = _resolve_heading_fragment(
1046
+ target_page, raw_frag, index, is_wikilink=True
1047
+ )
1048
+ if valid and resolved_id is not None:
1049
+ url += f"#{quote(resolved_id, safe='')}"
1050
+ else:
1051
+ url += f"#{quote(raw_frag, safe='')}"
1052
+ collector.add(
1053
+ code=MD2S005,
1054
+ file=page_file,
1055
+ line=line,
1056
+ message=(
1057
+ f"Heading anchor '#{raw_frag}' not found in "
1058
+ f"{target_page.rel.as_posix()}"
1059
+ ),
1060
+ target=f"{target_page.rel.as_posix()}#{raw_frag}",
1061
+ suggestion=suggest_match(
1062
+ _base_slug(raw_frag),
1063
+ sorted(index.heading_ids.get(target_page.rel, set())),
1064
+ ),
1065
+ )
1066
+ child.attrSet("href", url)
1067
+ new_children.append(child)
1068
+ idx += 1
1069
+ continue
1070
+
1071
+ # Standard Markdown link_open
1072
+ href = str(child.attrGet("href") or "")
1073
+ kind = classify(href)
1074
+
1075
+ if kind == "external":
1076
+ _add_token_attr_word(child, "class", "external")
1077
+ _add_token_attr_word(child, "rel", "noopener")
1078
+ elif kind in ("mailto_tel", "empty") or href.strip().lower().startswith(
1079
+ "data:"
1080
+ ):
1081
+ pass
1082
+ elif kind == "anchor":
1083
+ raw_frag = href.strip()[1:]
1084
+ resolved_id, valid = _resolve_heading_fragment(
1085
+ page, raw_frag, index, is_wikilink=False
1086
+ )
1087
+ if valid and resolved_id is not None:
1088
+ child.attrSet("href", f"#{quote(resolved_id, safe='')}")
1089
+ else:
1090
+ _add_token_attr_word(child, "class", "broken-link")
1091
+ child.attrSet("data-broken", "true")
1092
+ collector.add(
1093
+ code=MD2S005,
1094
+ file=page_file,
1095
+ line=line,
1096
+ message=f"Heading anchor not found: #{raw_frag}",
1097
+ target=f"#{raw_frag}",
1098
+ suggestion=suggest_match(
1099
+ unquote(raw_frag),
1100
+ sorted(index.heading_ids.get(page.rel, set())),
1101
+ ),
1102
+ )
1103
+ else:
1104
+ res = resolve_relative(
1105
+ page,
1106
+ href,
1107
+ docs_dir=index.docs_dir,
1108
+ repo_root=index.repo_root,
1109
+ pages_by_rel=index.pages_by_rel,
1110
+ exists=index.exists,
1111
+ is_dir=index.is_dir,
1112
+ case_lookup=index.case_lookup,
1113
+ )
1114
+ if res.case_mismatch_of is not None:
1115
+ collector.add(
1116
+ code=MD2S006,
1117
+ file=page_file,
1118
+ line=line,
1119
+ message=(
1120
+ f"Case mismatch for '{href}' (matches '{res.case_mismatch_of}')"
1121
+ ),
1122
+ target=href,
1123
+ suggestion=res.case_mismatch_of,
1124
+ )
1125
+ if res.kind == "page" and res.page is not None:
1126
+ url = rel_url(page.out_rel, res.page.out_rel)
1127
+ if res.query:
1128
+ url += f"?{res.query}"
1129
+ if res.fragment:
1130
+ resolved_id, valid = _resolve_heading_fragment(
1131
+ res.page, res.fragment, index, is_wikilink=False
1132
+ )
1133
+ if valid and resolved_id is not None:
1134
+ url += f"#{quote(resolved_id, safe='')}"
1135
+ else:
1136
+ url += f"#{quote(unquote(res.fragment), safe='')}"
1137
+ collector.add(
1138
+ code=MD2S005,
1139
+ file=page_file,
1140
+ line=line,
1141
+ message=(
1142
+ f"Heading anchor '#{res.fragment}' not found in "
1143
+ f"{res.page.rel.as_posix()}"
1144
+ ),
1145
+ target=f"{res.page.rel.as_posix()}#{res.fragment}",
1146
+ suggestion=suggest_match(
1147
+ unquote(res.fragment),
1148
+ sorted(index.heading_ids.get(res.page.rel, set())),
1149
+ ),
1150
+ )
1151
+ child.attrSet("href", url)
1152
+ elif res.kind == "doc_asset" and res.target is not None:
1153
+ dest_rel = _rel_posix(res.target, index.docs_dir)
1154
+ _register_asset(
1155
+ res.target, dest_rel, asset_map, collector, page_file, line
1156
+ )
1157
+ url = rel_url(page.out_rel, dest_rel)
1158
+ if res.query:
1159
+ url += f"?{res.query}"
1160
+ if res.fragment:
1161
+ url += f"#{quote(unquote(res.fragment), safe='')}"
1162
+ child.attrSet("href", url)
1163
+ elif res.kind == "repo_file" and res.target is not None:
1164
+ _apply_repo_file_href(
1165
+ child,
1166
+ page,
1167
+ res.target,
1168
+ res.line_spec,
1169
+ res.fragment,
1170
+ line,
1171
+ query=res.query,
1172
+ )
1173
+ else:
1174
+ code = res.broken_code or MD2S002
1175
+ raw_sug_target = href.split("#", 1)[0].split("?", 1)[0]
1176
+ if code == MD2S007:
1177
+ msg = f"Link target escapes repo_root: {href}"
1178
+ sug = None
1179
+ elif code == MD2S001:
1180
+ msg = f"Link target not found: {href}"
1181
+ sug = suggest_match(
1182
+ raw_sug_target, _page_suggestion_candidates(page, index)
1183
+ )
1184
+ else:
1185
+ msg = f"File or asset not found: {href}"
1186
+ sug = suggest_match(
1187
+ raw_sug_target,
1188
+ _asset_suggestion_candidates(page, res.target, index),
1189
+ )
1190
+ if code != MD2S007:
1191
+ _add_token_attr_word(child, "class", "broken-link")
1192
+ child.attrSet("data-broken", "true")
1193
+ collector.add(
1194
+ code=code,
1195
+ file=page_file,
1196
+ line=line,
1197
+ message=msg,
1198
+ target=href,
1199
+ suggestion=sug,
1200
+ )
1201
+
1202
+ new_children.append(child)
1203
+ idx += 1
1204
+ continue
1205
+
1206
+ if child.type == "link_close":
1207
+ if link_depth > 0:
1208
+ link_depth -= 1
1209
+ new_children.append(child)
1210
+ idx += 1
1211
+ continue
1212
+
1213
+ if child.type == "image":
1214
+ if child.meta.get("_resolved"):
1215
+ new_children.append(child)
1216
+ idx += 1
1217
+ continue
1218
+ child.meta["_resolved"] = True
1219
+ wl_meta = child.meta.get("wikilink")
1220
+
1221
+ if wl_meta is not None:
1222
+ raw_target = str(wl_meta["target"])
1223
+ asset_rel, others, case_rel = resolve_wikilink_embed(
1224
+ page, raw_target, index.docs_non_md_files
1225
+ )
1226
+ if asset_rel is None:
1227
+ label = str(wl_meta["label"])
1228
+ span_open = Token("link_open", "span", 1)
1229
+ span_open.attrs = {
1230
+ "class": "broken-link",
1231
+ "title": "Unresolved wikilink",
1232
+ }
1233
+ span_open.meta["_resolved"] = True
1234
+ span_text = Token("text", "", 0)
1235
+ span_text.content = label
1236
+ span_close = Token("link_close", "span", -1)
1237
+ collector.add(
1238
+ code=MD2S004,
1239
+ file=page_file,
1240
+ line=line,
1241
+ message=f"Unresolved wikilink embed: ![[{wl_meta['raw']}]]",
1242
+ target=raw_target,
1243
+ suggestion=suggest_match(
1244
+ raw_target,
1245
+ sorted(p.as_posix() for p in index.docs_non_md_files),
1246
+ ),
1247
+ )
1248
+ new_children.extend([span_open, span_text, span_close])
1249
+ idx += 1
1250
+ continue
1251
+ if case_rel is not None:
1252
+ collector.add(
1253
+ code=MD2S006,
1254
+ file=page_file,
1255
+ line=line,
1256
+ message=(
1257
+ f"Case mismatch in wikilink embed '{raw_target}' "
1258
+ f"(matches '{case_rel}')"
1259
+ ),
1260
+ target=raw_target,
1261
+ suggestion=case_rel,
1262
+ )
1263
+ if others:
1264
+ collector.add(
1265
+ code=MD2S003,
1266
+ file=page_file,
1267
+ line=line,
1268
+ message=(
1269
+ f"Ambiguous wikilink embed '![[{raw_target}]]'; "
1270
+ f"resolved to {asset_rel.as_posix()} "
1271
+ f"(other candidates: {', '.join(others)})"
1272
+ ),
1273
+ target=raw_target,
1274
+ suggestion=asset_rel.as_posix(),
1275
+ )
1276
+ _register_asset(
1277
+ index.docs_dir / asset_rel,
1278
+ asset_rel,
1279
+ asset_map,
1280
+ collector,
1281
+ page_file,
1282
+ line,
1283
+ )
1284
+ child.attrSet("src", rel_url(page.out_rel, asset_rel))
1285
+ new_children.append(child)
1286
+ idx += 1
1287
+ continue
1288
+
1289
+ src_val = str(child.attrGet("src") or "")
1290
+ kind = classify(src_val)
1291
+ if kind == "external":
1292
+ _add_token_attr_word(child, "class", "external")
1293
+ elif kind in (
1294
+ "mailto_tel",
1295
+ "empty",
1296
+ "anchor",
1297
+ ) or src_val.strip().lower().startswith("data:"):
1298
+ pass
1299
+ else:
1300
+ res = resolve_relative(
1301
+ page,
1302
+ src_val,
1303
+ docs_dir=index.docs_dir,
1304
+ repo_root=index.repo_root,
1305
+ pages_by_rel=index.pages_by_rel,
1306
+ exists=index.exists,
1307
+ is_dir=index.is_dir,
1308
+ case_lookup=index.case_lookup,
1309
+ )
1310
+ if res.case_mismatch_of is not None:
1311
+ collector.add(
1312
+ code=MD2S006,
1313
+ file=page_file,
1314
+ line=line,
1315
+ message=(
1316
+ f"Case mismatch for image '{src_val}' "
1317
+ f"(matches '{res.case_mismatch_of}')"
1318
+ ),
1319
+ target=src_val,
1320
+ suggestion=res.case_mismatch_of,
1321
+ )
1322
+ if res.kind == "doc_asset" and res.target is not None:
1323
+ dest_rel = _rel_posix(res.target, index.docs_dir)
1324
+ _register_asset(
1325
+ res.target, dest_rel, asset_map, collector, page_file, line
1326
+ )
1327
+ url = rel_url(page.out_rel, dest_rel)
1328
+ if res.query:
1329
+ url += f"?{res.query}"
1330
+ if res.fragment:
1331
+ url += f"#{quote(unquote(res.fragment), safe='')}"
1332
+ child.attrSet("src", url)
1333
+ elif res.kind == "repo_file" and res.target is not None:
1334
+ repo_rel = _rel_posix(res.target, index.repo_root)
1335
+ dest_rel = PurePosixPath("_external") / repo_rel
1336
+ _register_asset(
1337
+ res.target, dest_rel, asset_map, collector, page_file, line
1338
+ )
1339
+ url = rel_url(page.out_rel, dest_rel)
1340
+ if res.query:
1341
+ url += f"?{res.query}"
1342
+ if res.fragment:
1343
+ url += f"#{quote(unquote(res.fragment), safe='')}"
1344
+ child.attrSet("src", url)
1345
+ else:
1346
+ code = res.broken_code or MD2S002
1347
+ raw_sug_target = src_val.split("#", 1)[0].split("?", 1)[0]
1348
+ if code == MD2S007:
1349
+ msg = f"Image target escapes repo_root: {src_val}"
1350
+ sug = None
1351
+ else:
1352
+ msg = f"Image or asset not found: {src_val}"
1353
+ sug = suggest_match(
1354
+ raw_sug_target,
1355
+ _asset_suggestion_candidates(page, res.target, index),
1356
+ )
1357
+ _add_token_attr_word(child, "class", "broken-link")
1358
+ child.attrSet("data-broken", "true")
1359
+ collector.add(
1360
+ code=code,
1361
+ file=page_file,
1362
+ line=line,
1363
+ message=msg,
1364
+ target=src_val,
1365
+ suggestion=sug,
1366
+ )
1367
+
1368
+ new_children.append(child)
1369
+ idx += 1
1370
+ continue
1371
+
1372
+ if child.type == "code_inline" and config.autolink_code_paths and link_depth == 0:
1373
+ res = _autolink_code_span(child.content, page, index)
1374
+ if res is not None:
1375
+ open_tok = Token("link_open", "a", 1)
1376
+ open_tok.meta["_resolved"] = True
1377
+ if res.kind == "page" and res.page is not None:
1378
+ open_tok.attrSet("href", rel_url(page.out_rel, res.page.out_rel))
1379
+ elif res.kind == "doc_asset" and res.target is not None:
1380
+ dest_rel = _rel_posix(res.target, index.docs_dir)
1381
+ _register_asset(
1382
+ res.target, dest_rel, asset_map, collector, page_file, line
1383
+ )
1384
+ open_tok.attrSet("href", rel_url(page.out_rel, dest_rel))
1385
+ elif res.kind == "repo_file" and res.target is not None:
1386
+ _apply_repo_file_href(
1387
+ open_tok, page, res.target, res.line_spec, None, line
1388
+ )
1389
+ close_tok = Token("link_close", "a", -1)
1390
+ new_children.extend([open_tok, child, close_tok])
1391
+ idx += 1
1392
+ continue
1393
+
1394
+ new_children.append(child)
1395
+ idx += 1
1396
+
1397
+ token.children = new_children
1398
+
1399
+ site.assets = [
1400
+ AssetCopy(src=asset_map[dest], dest_rel=dest)
1401
+ for dest in sorted(asset_map, key=lambda p: p.as_posix())
1402
+ ]
1403
+ site.diagnostics = collector.sorted_items()