AppSurface Search
API Reference

Services

Type

AppSurfaceDocsMarkdownDownloadPolicyValidationService

Source

Validates that an enabled protected Markdown download route names a policy the host actually registered.

Remarks

Options validation catches missing or blank names. This startup check catches a misspelled name before AppSurface Docs maps an authorization-protected raw-source endpoint. The package deliberately resolves the host policy but never registers authentication schemes, identities, or a policy of its own.

Method

StartAsync

Task StartAsync(CancellationToken cancellationToken)

Resolves the configured named policy when Markdown download is enabled.

Method

StopAsync

Task StopAsync(CancellationToken cancellationToken)

Stops the validation service.

Type

AppSurfaceDocsVersionCatalogService

Source

Loads, validates, and resolves the configured AppSurface Docs version catalog.

Remarks

The service performs best-effort validation so a broken stored release tree becomes unavailable without preventing healthy versions or the live preview surface from loading. Validation is intentionally release-local: every version is checked independently for a readable tree root, the required landing and search pages, the search index, and the shared search runtime assets that exact-version pages depend on. Exact trees are otherwise treated as immutable, self-contained artifacts: outline-aware and rich-authoring exports should include the page-local runtimes they reference, while historical trees are not crawled or upgraded at host startup. Public AppSurfaceDocsResolvedVersion.AvailabilityIssue values are sanitized for archive UI consumption, while filesystem paths and exception details stay in structured logs only.

Method

GetCatalog

AppSurfaceDocsResolvedVersionCatalog GetCatalog()

Returns the resolved version catalog for the current host.

Returns

The resolved catalog including availability information for each published version. Returns AppSurfaceDocsResolvedVersionCatalog.Disabled when versioning is off for this host, AppSurfaceDocsResolvedVersionCatalog.EnabledWithoutCatalog when versioning is on but no catalog path was configured, and enabled-but-unavailable semantics when a configured catalog or trusted release root could not be loaded into a usable published-release set.

Property

InstanceName

string InstanceName { get; init; } Source

Gets the validated product identity included in safe alias diagnostics before the first lazy load.

Type

AppSurfaceDocsResolvedVersionCatalog

Source

Represents the resolved version catalog used by the current host.

Parameters

  • Status
    The high-level catalog resolution state for the current host. This distinguishes successful resolution from the three sentinel states where versioning is disabled, missing a catalog path, or configured but unavailable.
  • CatalogPath
    The catalog path associated with the resolved state. This stays null for the Disabled and EnabledWithoutCatalog sentinels, is typically an absolute filesystem path after successful resolution or file-based unavailability checks, and can remain the normalized configured value when Status is AppSurfaceDocsResolvedVersionCatalogStatus.Unavailable because absolute resolution failed before an unavailable catalog result was created.
  • Versions
    The resolved catalog entries in authored catalog order. Entries stay present even when a published tree is unavailable so archive, diagnostics, and fallback experiences can explain the broken release instead of silently hiding it.
  • RecommendedVersion
    The resolved recommended version when one is public and available. This can be null when versioning is disabled, no recommendation was configured, the configured identifier did not resolve, or the matching release was hidden or unavailable after validation.

Remarks

Disabled means the host is running with versioning off, so callers should treat the live docs surface as the only public experience and skip published-release archive UI entirely.

EnabledWithoutCatalog means versioning was turned on but no catalog path was configured, so callers can still expose the live preview surface but should not expect any published releases to resolve.

PublicVersions preserves the ordering from Versions after filtering by AppSurfaceDocsVersionVisibility.Public only. Public-but-unavailable releases remain in that list so the archive can surface their degraded status instead of pretending they do not exist.

Aliases contains operator-facing alias resolution state in authored order. Consumers that render the public archive must first create a safe projection; AppSurfaceDocsResolvedVersionAlias.ConfiguredVersion may identify hidden configuration and must not be serialized into reader-facing markup.

Method

CreateUnavailable

AppSurfaceDocsResolvedVersionCatalog CreateUnavailable(string? catalogPath, string? availabilityIssue = null)

Creates an enabled catalog result with no available versions because the backing catalog could not be used.

Parameters

  • catalogPath
    The resolved catalog path to surface with the unavailable sentinel. This is usually an absolute filesystem path, but can also be the normalized configured value when resolution failed before an absolute path could be constructed.
  • availabilityIssue
    Optional sanitized catalog-level availability explanation.

Returns

An enabled-but-unavailable catalog result.

Property

Aliases

IReadOnlyList<AppSurfaceDocsResolvedVersionAlias> Aliases { get; init; } Source

Gets the resolved aliases in authored order. Invalid entries and every member of duplicate-name groups remain available here for operator diagnostics.

Property

IsAliasNamespaceActive

bool IsAliasNamespaceActive { get; init; } Source

Gets whether alias declarations activate ownership of the configured alias namespace.

Property

Disabled

AppSurfaceDocsResolvedVersionCatalog Disabled { get; } Source

Gets the sentinel catalog result for hosts where versioning is disabled entirely.

Property

EnabledWithoutCatalog

AppSurfaceDocsResolvedVersionCatalog EnabledWithoutCatalog { get; } Source

Gets the sentinel catalog result for hosts where versioning is enabled but no catalog path was configured.

Property

PublicVersions

IReadOnlyList<AppSurfaceDocsResolvedVersion> PublicVersions { get; } Source

Gets the public versions that should appear in the archive.

Remarks

This list preserves the authored order from Versions after filtering only by AppSurfaceDocsVersionVisibility.Public . Versions stay in the list even when AppSurfaceDocsResolvedVersion.IsAvailable is false so archive consumers can show degraded-release messaging instead of silently dropping known public releases.

Property

AvailabilityIssue

string? AvailabilityIssue { get; init; } Source

Gets a sanitized catalog-level availability explanation when catalog or trusted-root configuration failed.

Remarks

Version-level failures continue to live on AppSurfaceDocsResolvedVersion.AvailabilityIssue . This property is for host-level failures such as a missing or unsafe trusted release root where no exact tree can be mounted safely.

Type

AppSurfaceDocsResolvedVersion

Source

Represents one resolved published docs version and its runtime availability.

Parameters

  • Version
    The non-null exact published version identifier from the catalog.
  • Label
    The non-null archive label shown to readers; catalog loading falls back to Version when no label is configured.
  • Summary
    Optional summary copy shown in the archive, or null when the catalog entry has no non-blank summary.
  • ExactTreePath
    The resolved absolute path to the exported exact-version subtree, or null when catalog path resolution failed before an exact tree could be selected.
  • ExactRootUrl
    The non-null canonical public root URL for the exact version.
  • SupportState
    The support-state badge surfaced in the archive.
  • Visibility
    The archive visibility state.
  • AdvisoryState
    The release-level advisory state.
  • IsAvailable
    Whether the exact-version tree validated successfully and may be mounted or recommended.
  • AvailabilityIssue
    Optional sanitized public-facing availability explanation when IsAvailable is false . Callers should branch on IsAvailable first, then display this value when present; they should not infer availability by parsing message text. Internal logs retain filesystem paths and exception details, but this message is safe to surface in archive UI and reader-facing diagnostics.
  • ReleaseManifestSha256
    Optional catalog-pinned release manifest digest. The value is null for unpinned legacy catalog entries and for entries whose configured digest is blank; a non-null value means the catalog requested release archive verification, not that verification necessarily succeeded.
  • ArchiveVerificationState
    Archive integrity state resolved for the exact-version tree. The default AppSurfaceDocsReleaseArchiveVerificationState.AvailableUnverifiedLegacy represents an available, shape-valid legacy tree without a catalog-pinned release manifest digest. Treat this state as meaningful only when IsAvailable is true ; unavailable versions report AppSurfaceDocsReleaseArchiveVerificationState.Unavailable and carry the public failure reason in AvailabilityIssue .
  • VerifiedReleaseArchive
    Verified archive file metadata used by runtime mounts. This value is null unless IsAvailable is true and ArchiveVerificationState is AppSurfaceDocsReleaseArchiveVerificationState.AvailableVerified . When non-null, callers may rely on that invariant instead of rechecking catalog digest details.
Type

AppSurfaceDocsHarvestHealthVisibility

Source

Resolves environment-aware visibility for AppSurface Docs harvest health routes and sidebar chrome.

Method

AreRoutesExposed

bool AreRoutesExposed(AppSurfaceDocsOptions options, IHostEnvironment environment)

Resolves whether the harvest health controller routes should be registered or allowed for the current host.

Remarks

This internal helper uses AppSurfaceDocsOptions.Harvest health route settings and the supplied host environment. Missing health options fall back to AppSurfaceDocsHarvestHealthExposure.DevelopmentOnly . Callers must pass the real host environment; the method null-checks both arguments before applying the environment-gated visibility contract.

Method

ShouldShowChrome

bool ShouldShowChrome(AppSurfaceDocsOptions options, IHostEnvironment environment)

Resolves whether the sidebar should show harvest health chrome for the current host.

Remarks

This internal helper uses AppSurfaceDocsOptions.Harvest health chrome settings and the supplied host environment. Missing health options fall back to AppSurfaceDocsHarvestHealthExposure.DevelopmentOnly . Callers use this for presentation chrome only; route exposure is resolved separately by AreRoutesExposed(AppSurfaceDocsOptions, IHostEnvironment) . The method null-checks both arguments before applying the environment-gated visibility contract.

Type

TextMateSharpAppSurfaceDocsCodeHighlighter

Source

TextMateSharp-backed implementation of AppSurface Docs' internal code-block highlighting contract.

Method

LoadGrammar

IGrammar? LoadGrammar(AppSurfaceDocsCodeLanguage language)

Loads the TextMate grammar for a normalized language, returning null when no grammar exists.

Parameters

  • language
    The normalized language descriptor.

Returns

The loaded grammar, or null when the language has no TextMate scope.

Method

AppendTokens

void AppendTokens(StringBuilder builder, string line, IReadOnlyList<IToken> tokens)

Appends a tokenized source line while preserving unclassified gaps and trailing text.

Parameters

  • builder
    The destination HTML builder.
  • line
    The original source line.
  • tokens
    TextMate tokens for the line.
Method

ResolveTokenClass

string? ResolveTokenClass(IReadOnlyList<string> scopes)

Maps TextMate scopes to AppSurface Docs' small semantic token vocabulary.

Parameters

  • scopes
    The scopes attached to a TextMate token.

Returns

The AppSurface Docs token modifier, or null for unstyled scopes.

Type

AppSurfaceDocsAliasRecoveryRenderer

Source

Renders the single owned-failure view through the existing Docs shell before committing any bytes.

Method

RenderAsync

Task<string> RenderAsync(HttpContext context, string archiveRoot)

Buffers the normal Razor view so GET and HEAD share headers and no partial recovery can be sent.

Parameters

  • context
    Authorized context carrying the actual Docs runtime endpoint metadata.
  • archiveRoot
    App-relative family archive URL; Razor adds PathBase once and encodes it.

Returns

The shell-rendered generic recovery document.

Type

AppSurfaceDocsParserInputBudget

Source

Provides parser-input admission for source harvesters that need to bound bytes before decoding or parsing.

Remarks

The helper reads at most maxFileSizeBytes + 1 bytes so oversized files can be rejected without loading the whole source into memory. Seekable streams still report their full file length in diagnostics when available.

Method

ReadUtf8SourceAsync

Task<AppSurfaceDocsParserInputReadResult> ReadUtf8SourceAsync(string filePath, string relativePath, long maxFileSizeBytes, string configurationKey, string diagnosticCode, string harvesterType, string sourceKindLabel, string generatedSourceGuidance, CancellationToken cancellationToken)

Reads a source file through a positive byte budget and decodes it for parser consumption when it is within budget.

Parameters

  • filePath
    Absolute or rooted file path to open for the bounded read.
  • relativePath
    Repository-relative display path used in emitted diagnostics.
  • maxFileSizeBytes
    Maximum number of bytes allowed before decoding; must be greater than zero.
  • configurationKey
    Configuration key shown in diagnostics so operators know which limit rejected the file.
  • diagnosticCode
    Diagnostic code to emit when the file exceeds maxFileSizeBytes .
  • harvesterType
    Harvester identifier recorded on emitted diagnostics.
  • sourceKindLabel
    Human-readable source kind, such as C#, included in diagnostic problem text.
  • generatedSourceGuidance
    Recovery guidance appended to oversized-file diagnostics.
  • cancellationToken
    Token observed while reading and decoding the source.

Returns

A read result with AppSurfaceDocsParserInputReadResult.Included set when the source is within budget and decoded, or skipped with a warning diagnostic when the budget is exceeded.

Remarks

The method throws ArgumentOutOfRangeException when maxFileSizeBytes is zero or negative. Files are decoded with StreamReader using UTF-8 as the default encoding and BOM detection enabled, so a recognized BOM is consumed instead of becoming source text. Oversized diagnostics use diagnosticCode , configurationKey , harvesterType , sourceKindLabel , and generatedSourceGuidance to describe the skipped file and recovery path.

Method

CreateFileTooLargeDiagnostic

DocHarvestDiagnostic CreateFileTooLargeDiagnostic(string diagnosticCode, string harvesterType, string relativePath, long observedSizeBytes, long maxFileSizeBytes, string configurationKey, string sourceKindLabel, string generatedSourceGuidance)

Creates the warning diagnostic emitted when a parser-input budget rejects a source file.

Parameters

  • diagnosticCode
    Diagnostic code that identifies the source-specific oversized-file condition.
  • harvesterType
    Harvester identifier attached to the diagnostic.
  • relativePath
    Repository-relative source path shown to operators.
  • observedSizeBytes
    Observed byte size, preferably the full file length when the stream is seekable.
  • maxFileSizeBytes
    Configured positive byte limit that rejected the file.
  • configurationKey
    Configuration key that controls maxFileSizeBytes .
  • sourceKindLabel
    Human-readable source kind included in the diagnostic problem.
  • generatedSourceGuidance
    Recovery guidance for generated or intentionally large source.

Returns

A non-strict warning diagnostic suitable for harvest health output.

Type

AppSurfaceDocsParserInputReadResult

Source

Represents the outcome of a bounded parser-input read.

Parameters

  • Included
    true when the source was within budget and Source contains decoded text; false when the source was skipped and Diagnostic explains why.
  • Source
    Decoded source text for included files, otherwise null .
  • Diagnostic
    Warning diagnostic for skipped files, otherwise null .

Remarks

Callers should branch on Included before using Source . Skipped results are intended to let harvesters continue processing sibling files while surfacing a visible diagnostic.

Method

Read

AppSurfaceDocsParserInputReadResult Read(string source)

Creates an included result for decoded source that stayed within the byte budget.

Parameters

  • source
    Decoded source text ready for parser consumption.

Returns

An included parser-input result with no diagnostic.

Method

Skipped

AppSurfaceDocsParserInputReadResult Skipped(DocHarvestDiagnostic diagnostic)

Creates a skipped result for a source file rejected before decoding or parsing.

Parameters

  • diagnostic
    Diagnostic that explains why the source was skipped and how to recover.

Returns

A skipped parser-input result with no decoded source.

Type

AppSurfaceDocsOperatorReadPolicyWarningService

Source

Logs a startup warning when non-development diagnostics reads are exposed without the shared read policy.

Remarks

The warning is advisory and does not fail startup. This preserves compatibility for hosts that intentionally enforce diagnostics access through their application pipeline, reverse proxy, or network boundary, while making risky package exposure visible during deployment.

Method

StartAsync

Task StartAsync(CancellationToken cancellationToken)

Logs the advisory startup warning when non-development diagnostics reads are exposed without a configured Diagnostics.OperatorReadPolicy .

Parameters

  • cancellationToken
    Unused; the startup warning performs no cancellable I/O.

Returns

A completed task after the advisory check has run.

Remarks

Startup is never failed by this check. The method returns without logging in Development, when the shared read policy is configured, or when ResolveExposedDiagnosticsSurfaces finds no exposed diagnostics surfaces. Otherwise, it logs the exposed surface names so operators can either configure the read policy or verify that host, reverse-proxy, or network authorization already protects those reads.

Method

StopAsync

Task StopAsync(CancellationToken cancellationToken)

Stops the advisory startup warning service.

Parameters

  • cancellationToken
    Unused; there is no shutdown work to cancel.

Returns

A completed task.

Remarks

The service does not hold background work or subscriptions after StartAsync returns, so stopping is a no-op and always completes synchronously.

Type

DocsRecoveryLinkBuilder

Source

Builds the small static recovery-link set shared by browser docs recovery surfaces.

Remarks

This builder only uses DocsUrlBuilder and built-in public-section route contracts. It must not inspect harvested docs, search snapshots, or the missing request path. That constraint keeps standalone 404 pages deterministic during cold starts and prevents stale or hostile request paths from shaping recovery navigation. Callers that need search-result or representative-document fallback behavior should keep that logic in the search surface and adapt these links only as static route-safe entries.

Type

AppSurfaceDocsReleaseArchiveVerifier

Source

Verifies catalog-pinned AppSurface Docs release archive manifests.

Remarks

The verifier treats the version catalog as trusted host configuration. It proves that the local exact-version tree matches the digest pinned by that catalog; it does not prove who built the archive or replace future signed attestation support.

Method

TryVerify

2 overloads
bool TryVerify(string exactTreePath, string expectedManifestSha256, out AppSurfaceDocsVerifiedReleaseArchive? archive, out AppSurfaceDocsArchiveVerificationFailure? failure)

Attempts to verify an exact-version tree against the manifest digest pinned in the version catalog.

Parameters

  • exactTreePath
    Exact-version export root.
  • expectedManifestSha256
    Catalog-pinned manifest digest.
  • archive
    Verified archive metadata when verification succeeds.
  • failure
    Verification failure when verification fails.

Returns

true when every required archive integrity check passes.

bool TryVerify(string exactTreePath, string expectedManifestSha256, AppSurfaceDocsReleaseArchiveFileSystem fileSystem, out AppSurfaceDocsVerifiedReleaseArchive? archive, out AppSurfaceDocsArchiveVerificationFailure? failure)

Attempts to verify an exact-version tree using the supplied filesystem adapter.

Parameters

  • exactTreePath
    Exact-version export root.
  • expectedManifestSha256
    Catalog-pinned manifest digest.
  • fileSystem
    Filesystem adapter used for verification reads.
  • archive
    Verified archive metadata when verification succeeds.
  • failure
    Verification failure when verification fails.

Returns

true when every required archive integrity check passes.

Method

FileMatches

bool FileMatches(IFileInfo fileInfo, AppSurfaceDocsReleaseArchiveFile expectedFile)

Recomputes an already-verified file digest from an IFileInfo before serving active content.

Parameters

  • fileInfo
    Resolved file to check.
  • expectedFile
    Manifest entry to compare against.

Returns

true when length and SHA-256 still match the manifest entry.

Type

AppSurfaceDocsReleaseArchiveFileSystem

Source

Filesystem adapter used by release archive verification.

Remarks

The production adapter reads the physical release tree. Tests use custom adapters to exercise portable failure branches such as unreadable files without depending on platform-specific chmod behavior.

Method

GetPathComparer

StringComparer GetPathComparer(string rootPath)

Gets the comparer used by the physical filesystem when resolving paths beneath an archive root.

Parameters

  • rootPath
    Existing exact release tree whose filesystem behavior is required.

Returns

The comparer matching the root's physical filesystem casing rules.

Method

ResolvePhysicalPathComparer

StringComparer ResolvePhysicalPathComparer(string rootPath, Func<string, bool> fileExists, Func<string, IEnumerable<string>> enumerateFileSystemEntries)

Resolves physical filesystem casing behavior without writing probe files into an immutable archive.

Parameters

  • rootPath
    Existing exact release tree.
  • fileExists
    File existence operation used for the read-only case-variant probe.
  • enumerateFileSystemEntries
    Filesystem enumeration used to reject ambiguous case-variant siblings.

Returns

An ordinal comparer matching the archive root's case behavior.

Method

FileExists

bool FileExists(string path)

Returns whether the path exists as a file.

Method

ReadAllBytes

byte[] ReadAllBytes(string path)

Reads all bytes from a file.

Method

GetLength

long GetLength(string path)

Returns the current file length in bytes.

Method

ComputeSha256

string ComputeSha256(string path)

Computes a lowercase SHA-256 digest for a file.

Method

EnumerateFiles

IEnumerable<string> EnumerateFiles(string rootPath)

Enumerates files under an exact release tree.

Property

Physical

AppSurfaceDocsReleaseArchiveFileSystem Physical { get; } Source

Gets the physical filesystem adapter used by runtime verification.

Type

AppSurfaceDocsReleaseArchiveFile

Source

Immutable file metadata from a verified release archive manifest.

Parameters

  • Path
    Archive-root-relative file path using slash separators.
  • Length
    Expected byte length.
  • ContentType
    Content type captured by export, when known.
  • Sha256
    Expected lowercase SHA-256 digest.
Type

AppSurfaceDocsVerifiedReleaseArchive

Source

Verified release archive metadata used by mounted published-tree handlers.

Method

TryGetFile

bool TryGetFile(string relativePath, out AppSurfaceDocsReleaseArchiveFile file)

Attempts to resolve verified metadata for a path the published-tree handler is about to serve.

Parameters

  • relativePath
    Archive-root-relative path using either platform or slash separators.
  • file
    Verified file metadata when present.

Returns

true when the path is covered by the release manifest.

Property

FileCount

int FileCount { get; } Source

Gets the number of files covered by the verified release manifest.

Property

CoveredPaths

IEnumerable<string> CoveredPaths { get; } Source

Gets the verified immutable inventory used for startup namespace collision checks.

Property

FrozenRouteManifest

AppSurfaceDocsFrozenRouteManifest FrozenRouteManifest { get; } Source

Gets the route manifest parsed from verified release archive bytes.

Type

AppSurfaceDocsArchiveVerificationFailure

Source

Stable archive verification diagnostic surfaced through logs and sanitized availability messages.

Parameters

  • Code
    Stable diagnostic code.
  • PublicMessage
    Sanitized public message.
  • Detail
    Operator-facing detail suitable for structured logs.
  • Path
    Archive-root-relative path associated with the failure, when applicable.
Type

AppSurfaceDocsMetadataHrefPolicy

Source

Normalizes browser-facing metadata hrefs that render as plain anchors.

Method

NormalizeTrustMigrationHref

AppSurfaceDocsMetadataHrefPolicyResult NormalizeTrustMigrationHref(string? href)

Normalizes trust.migration.href and classifies it as absent, safe to render, or rejected.

Parameters

  • href
    The authored migration href from Markdown front matter or sidecar metadata.

Returns

An explicit policy result that distinguishes missing optional metadata from rejected unsafe metadata.

Type

AppSurfaceDocsMetadataHrefPolicyResult

Source

Result returned by metadata href normalization.

Parameters

  • State
    Explicit policy state for the authored value.
  • Href
    The trimmed href when the value was allowed or rejected; null when absent.
Method

Absent

AppSurfaceDocsMetadataHrefPolicyResult Absent()

Creates an absent href result for missing optional metadata.

Returns

An absent result with no href.

Method

Allowed

AppSurfaceDocsMetadataHrefPolicyResult Allowed(string href)

Creates an allowed href result.

Parameters

  • href
    The normalized safe href.

Returns

An allowed result.

Method

Rejected

AppSurfaceDocsMetadataHrefPolicyResult Rejected(string href)

Creates a rejected href result.

Parameters

  • href
    The normalized href that failed policy validation.

Returns

A rejected result.

Type

AppSurfaceDocsAliasCollisionGuard

Source

Checks immutable startup inventories before publishing the newly reserved alias subtree.

Method

Validate

void Validate(AppSurfaceDocsResolvedVersionCatalog catalog, DocsUrlBuilder urls, ILogger? logger = null, string instanceName = "Default")

Rejects live/recommended ownership overlap without reserving anything for an inactive catalog.

Parameters

  • catalog
    Immutable catalog snapshot, including the declaration state.
  • urls
    The instance's normalized public routes.
  • logger
    Optional startup logger; no archive paths or descriptor copy is emitted.
  • instanceName
    Validated, bounded product identity.
Type

AppSurfaceDocsDiagnosticsVisibility

Source

Resolves environment-aware visibility for AppSurface Docs maintainer diagnostics routes.

Method

ShouldShowChrome

bool ShouldShowChrome(AppSurfaceDocsOptions options, IHostEnvironment environment)

Resolves whether the built-in sidebar should show route-inspector diagnostics chrome for the current host.

Remarks

The default follows local-development ergonomics: Development hosts show route-inspector discovery by default, while non-development hosts must opt in explicitly. This method controls only docs chrome. It does not expose or authorize the route-inspector response; use IsRouteInspectorExposed for route response policy.

Method

IsRouteInspectorExposed

bool IsRouteInspectorExposed(AppSurfaceDocsOptions options, IHostEnvironment environment)

Resolves whether the route-inspector controller routes should return responses for the current host.

Remarks

The route inspector exposes route identity intended for local development and trusted operators. Missing diagnostics options fall back to AppSurfaceDocsHarvestHealthExposure.DevelopmentOnly . Setting the exposure to AppSurfaceDocsHarvestHealthExposure.Always only allows the controller response; hosts remain responsible for authentication, authorization, or network controls in production.

Type

LocalizedDocRouteCandidate

Source

Represents one locale-prefixed public route candidate derived from a localized document variant.

Parameters

  • SourcePath
    Normalized source path for the localized variant.
  • Locale
    Configured locale code associated with the variant.
  • TranslationKey
    Stable translation identity shared by localized variants.
  • PublicRoutePath
    Locale-prefixed browser route candidate for the variant.

Remarks

Candidates are produced only for variants that have a public route and a configured locale route prefix. Source paths and public route paths are normalized relative docs paths, not absolute URLs.

Type

DocRouteIdentityCatalog

Source

Owns the route identity contract for one cached AppSurface Docs snapshot.

Remarks

The catalog deliberately separates source identity from public route identity: source path -> internal lookup and authoring provenance public route path -> browser-facing canonical URL redirect alias -> declared or Markdown source-shaped URL that redirects to public route Controllers render only public canonical winners. Declared aliases and Markdown source-shaped paths for public winners redirect to the canonical route, while non-Markdown source paths, collision losers, and reserved routes stay non-public. Link builders can still resolve source paths so authored Markdown stays source-friendly without rendering source-shaped URLs into the reader-facing surface.

Method

TryGetPublicRoutePathForSource

bool TryGetPublicRoutePathForSource(string sourcePath, out string publicRoutePath)

Resolves only an ordinal exact source identity, without canonical/alias lookup precedence. Snapshot metadata and recommendation facts use this after merge/deduplication so a source-shaped slug cannot impersonate another source. Legitimate fragment sources remain linkable under the existing fragment contract.

Method

BuildRouteManifest

AppSurfaceDocsRouteManifest BuildRouteManifest()

Builds a snapshot-local manifest of public canonical routes and redirect aliases for export consumers.

Returns

A deterministic route manifest for the current catalog snapshot.

Remarks

Use this when a downstream component needs a deterministic read model of canonical winners plus alias metadata. Prefer ResolvePublicRoute(string) for live request-time route decisions. The returned entries are ordered from _publicIdentityByRoutePath by public route path, then source path, using ordinal-ignore-case comparison so export output is stable across runs. Diagnostics start as a snapshot of Diagnostics and are passed through BuildRouteManifestEntry so implicit recovery-alias collisions discovered during manifest materialization are included in the returned AppSurfaceDocsRouteManifest . Pitfall: this method does not mutate catalog state, and callers should not rely on reference equality with external diagnostic collections or assume manifest-only diagnostics were computed before this call.

Method

BuildLocalizedRouteCandidates

IReadOnlyList<LocalizedDocRouteCandidate> BuildLocalizedRouteCandidates(LocalizedDocsGraph graph, AppSurfaceDocsLocalizationOptions options)

Builds locale-prefixed route candidates from a localized document graph.

Parameters

  • graph
    Localized graph built for the same docs snapshot.
  • options
    Localization options used to resolve locale route prefixes.

Returns

Sorted locale-prefixed candidates suitable for later route registration slices.

Remarks

Returns an empty list when the graph is disabled. Variants are skipped when they have no public route, or when their locale no longer maps to a configured route prefix. The method is snapshot-local and does not mutate catalog state.

Type

AppSurfaceDocsThemeResolver

Source

Resolves normalized AppSurface Docs theme options into render-ready CSS variables and shell attributes.

Remarks

The resolved theme is safe to cache as a singleton because it contains only preset names, density/chrome flags, and sanitized CSS custom property declarations. Razor views emit these values into the exported HTML so live docs, static export, and published archives share the same frozen visual contract.

Property

Theme

AppSurfaceDocsResolvedTheme Theme { get; } Source

Gets the render-ready theme used by AppSurface Docs layouts.

Type

AppSurfaceDocsResolvedTheme

Source

Render-ready AppSurface Docs theme values.

Parameters

  • Preset
    The selected public preset.
  • Density
    The selected public density.
  • Chrome
    The selected public chrome compactness.
  • PresetAttribute
    Kebab-case value emitted in data-docs-theme-preset .
  • DensityAttribute
    Kebab-case value emitted in data-docs-density .
  • ChromeAttribute
    Kebab-case value emitted in data-docs-chrome .
  • RootCssClass
    CSS classes emitted on the document root.
  • CssVariables
    Resolved CSS custom properties consumed by the package stylesheets.
  • CssVariableStyle
    Serialized CSS custom property declarations suitable for a style attribute.
  • RootColorScheme
    An optional Docs-owned color-scheme declaration emitted before package stylesheets.
  • UsesSharedTheme
    Whether the root consumes the shared AppSurface semantic pair.
  • CriticalCss
    Docs-owned critical CSS emitted before the package stylesheet when UsesSharedTheme is true .
Type

AppSurfaceDocsThemePolicy

Source

Centralizes normalization, validation, and render-ready resolution for the AppSurface Docs theme contract.

Remarks

Hosts configure AppSurfaceDocsThemeOptions , while this policy keeps every consumer on one resolved theme boundary. Run Normalize during post-configuration before calling Validate or Resolve .

Method

Normalize

void Normalize(AppSurfaceDocsThemeOptions theme)

Normalizes mutable theme options in place.

Parameters

  • theme
    The configured theme options to normalize.

Remarks

This method creates omitted nested sections and canonicalizes configured CSS hex colors. Call it during post-configuration before validation or resolution so those later operations observe a stable options shape.

Method

Validate

void Validate(AppSurfaceDocsThemeOptions? theme, List<string> failures)

Adds configuration failures for an AppSurface Docs theme.

Parameters

  • theme
    The normalized theme options to validate.
  • failures
    The destination for actionable validation messages.

Remarks

Contrast checks use the selected preset's canvas and raised backgrounds because v1 intentionally does not expose raw surface overrides. This makes the reported contrast guarantee match the surfaces the package renders.

Method

Resolve

AppSurfaceDocsResolvedTheme Resolve(AppSurfaceDocsThemeOptions? options)

Resolves theme options into the attributes and CSS variables consumed by rendered and exported docs.

Parameters

  • options
    The normalized theme options to resolve.

Returns

The immutable theme contract for layouts, search, and static output.

Remarks

Call Normalize before resolution for configured options. The null-tolerant fallback exists only to keep rendering defensive when no theme section is supplied.

Method

ResolveShared

AppSurfaceDocsResolvedTheme ResolveShared(AppSurfaceDocsResolvedTheme legacyTheme, AppSurfaceDocsThemeOptions? options, AppSurfaceThemeResolution resolution)

Maps a shared semantic pair into the AppSurface Docs internal CSS-variable graph.

Parameters

  • legacyTheme
    Resolved Docs compatibility values.
  • options
    Normalized Docs theme options, including supported legacy color overrides.
  • resolution
    The safe shared semantic pair selected by the host.

Returns

A Docs theme that consumes shared semantic variables without exposing Docs-local variables publicly.

Method

SetDerivedVariableForTesting

void SetDerivedVariableForTesting(Dictionary<string, string> variables, string name, string value, bool requireExistingKeys)

Exercises the derived-token inventory guard through the supported internal test seam.

Method

CanParseCssColorForTesting

bool CanParseCssColorForTesting(string value, string canvasColor)

Exercises CSS-color parsing branches without exposing the parsed implementation type.

Type

IDocHarvesterHealthParticipation

Source

Allows a harvester to publish diagnostics and docs while opting out of aggregate strict-health counts.

Remarks

Implement this for best-effort harvesters whose diagnostics should be visible to operators but whose empty, failed, timed-out, or canceled state must not decide whether DocHarvestHealthStatus.Failed is returned.

Property

ParticipatesInStrictHealth

bool ParticipatesInStrictHealth { get; } Source

Gets a value indicating whether this harvester participates in aggregate strict-health success and failure totals.

Type

AppSurfaceDocsVersionAliasCatalogResolver

Source

Parses alias declarations while retaining the provenance needed for safe operator and archive projections.

Method

Parse

AliasDeclaration Parse(JsonElement root)

Reads whether the alias namespace was declared and retains validatable alias metadata.

Parameters

  • root
    The already-validated catalog JSON root.

Returns

The declaration snapshot; it contains no retained JSON document state.

Method

Resolve

IReadOnlyList<AppSurfaceDocsResolvedVersionAlias> Resolve(AliasDeclaration declaration, IReadOnlyList<AppSurfaceDocsResolvedVersion> versions, bool targetResolutionAvailable = true)

Resolves parsed aliases by exact version identifier and creates immutable read models.

Parameters

  • declaration
    The parsed declaration snapshot.
  • versions
    The resolved exact versions in authored order.
  • targetResolutionAvailable
    Whether trusted-root resolution succeeded.

Returns

Resolved aliases in authored order, retaining conflicting entries for operator inspection.

Type

AliasDeclaration

Source

Snapshot of declaration activity and parsed entries.

Parameters

  • IsActive
    Whether a nonempty or malformed non-null declaration owns the namespace.
  • Items
    Authored alias entries in source order.
Type

AliasDraft

Source

One parsed alias with independent name, metadata, and explicit-visibility provenance.

Parameters

  • Index
    The authored array index.
  • Name
    The normalized name only when it passes the shared validator.
  • ConfiguredVersion
    The trimmed exact version identifier when it is a nonempty string.
  • Label
    The trimmed label or the normalized name when blank.
  • Summary
    The trimmed summary, or null when absent or blank.
  • Visibility
    The parsed visibility, defaulting to public for omitted or null values.
  • HasExplicitPublicVisibility
    Whether a valid explicit Public value was authored.
  • IsDefinitionValid
    Whether name and all metadata satisfy the alias descriptor contract.
  • DiagnosticCode
    The structured diagnostic code for an invalid definition, if any.
Type

AppSurfaceDocsResolvedVersionAlias

Source

Resolved alias state for host routing and operator diagnostics. This is a non-positional record so future additive fields do not change constructor or deconstruction contracts.

Remarks

ConfiguredVersion is operator-side configuration and may identify a hidden release. Public archive consumers must use a deliberate safe projection instead of serializing this record. TargetVersion is populated only for a known public target; it is the same resolved-version object used by exact-version mounts.

Property

Name

string? Name { get; init; } Source

Gets the normalized validated name, or null when the authored name is invalid.

Property

Label

string? Label { get; init; } Source

Gets the validated reader-facing label, or null when unavailable.

Property

Summary

string? Summary { get; init; } Source

Gets optional validated reader-facing summary text.

Property

Visibility

AppSurfaceDocsVersionVisibility? Visibility { get; init; } Source

Gets the valid configured visibility, or null when invalid.

Property

ConfiguredVersion

string? ConfiguredVersion { get; init; } Source

Gets the configured exact target identifier for operator inspection only.

Property

TargetVersion

AppSurfaceDocsResolvedVersion? TargetVersion { get; init; } Source

Gets the existing resolved public exact-version target, or null when not public or unresolved.

Property

RootUrl

string? RootUrl { get; init; } Source

Gets the alias root URL when the authored name is safe.

Property

IsAvailable

bool IsAvailable { get; init; } Source

Gets whether the alias can be mounted on its verified public target.

Property

IsDefinitionValid

bool IsDefinitionValid { get; init; } Source

Gets whether the authored alias passed shape, name, and metadata validation.

Property

HasExplicitPublicVisibility

bool HasExplicitPublicVisibility { get; init; } Source

Gets whether a valid explicit Public visibility value was authored.

Property

IsNameConflict

bool IsNameConflict { get; init; } Source

Gets whether another entry has the same normalized name.

Property

DiagnosticCode

string? DiagnosticCode { get; init; } Source

Gets the stable ASDOCSALIAS diagnostic code, or null .

Property

AvailabilityIssue

string? AvailabilityIssue { get; init; } Source

Gets a sanitized availability explanation suitable for deliberate public projection.

Type

AppSurfaceDocsHarvestPathPatternValidator

Source

Validates and normalizes repository-relative harvest path patterns and candidate paths.

Remarks

The validator is stateless and thread-safe. Callers should normalize or validate before matching: backslashes are converted to / , configured patterns are trimmed, and rooted, URI-like, drive-rooted, control-character, query, fragment, and parent-directory paths are rejected. NormalizeSlashes only changes separators; it does not perform validation by itself.

Method

IsValidConfiguredGlobPattern

bool IsValidConfiguredGlobPattern(string? pattern)

Returns whether a configured glob pattern is safe to evaluate as a repository-relative path policy rule.

Parameters

  • pattern
    The configured glob pattern. Null, empty, and whitespace-only values are invalid.

Returns

true when pattern is repository-relative after trimming and slash normalization; otherwise false .

Remarks

Patterns starting with / , ./ , or // , containing :// , drive roots, control characters, ? , # , or a .. segment are invalid. Validation does not prove that a glob can match an existing file; it only rejects unsafe path forms before matcher construction.

Method

TryNormalizeCandidatePath

bool TryNormalizeCandidatePath(string path, out string normalizedPath)

Attempts to normalize a candidate file or directory path before path-policy evaluation.

Parameters

  • path
    The candidate repository-relative path to normalize.
  • normalizedPath
    Receives the slash-normalized candidate path. When validation fails, this value contains the normalized input that failed validation so callers can log the inspected value.

Returns

true when path is a non-empty repository-relative path that is safe for policy evaluation; otherwise false .

Remarks

This method assumes callers have already chosen whether the path represents a file or directory. It trims no whitespace, so caller-provided spaces remain part of the candidate path; unsafe rooted, URI-like, drive-rooted, query, fragment, control-character, and parent-directory forms are rejected.

Method

NormalizeSlashes

string NormalizeSlashes(string value)

Converts Windows path separators in value to repository-style slash separators.

Parameters

  • value
    The path or pattern value whose separators should be normalized.

Returns

value with each \ character replaced by / .

Remarks

This helper does not trim, validate, collapse duplicate separators, or reject unsafe segments. Use one of the validation methods when accepting configuration or candidate paths from outside the policy implementation.

Method

DriveRootedPatternRegex

Regex DriveRootedPatternRegex()

Generates the expression used to reject Windows drive-rooted patterns after slash normalization.

Returns

A culture-invariant regular expression that matches values such as C:/repo .

Type

AppSurfaceDocsNamedInstancePreflightService

Source

Runs startup validation and harvest warmup for every finalized named AppSurface Docs runtime.

Remarks

Named Docs products own isolated options and aggregators, so the legacy singleton preflight services cannot validate or warm them. This service runs after endpoint mapping, when the registry has constructed the immutable runtime snapshots, and preserves the same Markdown-policy validation, diagnostics warning, and harvest startup semantics that AddAppSurfaceDocs() provides for a legacy single-instance host.

Method

StartingAsync

Task StartingAsync(CancellationToken cancellationToken)

Completes the pre-start lifecycle phase without touching named runtimes.

Parameters

  • cancellationToken
    Unused cancellation token supplied by the host.

Returns

A completed task because endpoint mapping has not necessarily run yet.

Remarks

Hosts built through WebStartup construct their endpoint table while the web host starts. Named Docs must wait for that work before resolving finalized runtimes, so strict preflight runs from StartedAsync .

Method

StartAsync

Task StartAsync(CancellationToken cancellationToken)

Completes the ordinary hosted-service start phase without touching named runtimes.

Parameters

  • cancellationToken
    Unused cancellation token supplied by the host.

Returns

A completed task because endpoint mapping may not yet have run.

Method

StartedAsync

Task StartedAsync(CancellationToken cancellationToken)

Validates and warms every named Docs runtime after all hosted services have started.

Parameters

  • cancellationToken
    Token observed by strict preflights.

Returns

A task that completes once all strict preflights complete or background warmups are scheduled.

Remarks

IHostedLifecycleService.StartedAsync runs after ordinary IHostedService.StartAsync calls. That ordering lets conventional ASP.NET Core hosts map endpoints before this service reads the finalized named Docs registry, while preserving startup failure behavior for strict validation.

Method

StoppingAsync

Task StoppingAsync(CancellationToken cancellationToken)

Completes the pre-stop lifecycle phase.

Parameters

  • cancellationToken
    Unused cancellation token supplied by the host.

Returns

A completed task because per-instance preflights own no shutdown work.

Method

StopAsync

Task StopAsync(CancellationToken cancellationToken)

Stops the preflight service.

Parameters

  • cancellationToken
    Unused cancellation token supplied by the host.

Returns

A completed task because per-instance preflights own no shutdown work.

Method

StoppedAsync

Task StoppedAsync(CancellationToken cancellationToken)

Completes the post-stop lifecycle phase.

Parameters

  • cancellationToken
    Unused cancellation token supplied by the host.

Returns

A completed task because per-instance preflights own no shutdown work.

Type

IAppSurfaceDocsHtmlSanitizer

Source

Sanitizes rendered AppSurface Docs HTML using the package's docs-specific allowlist.

Remarks

IAppSurfaceDocsHtmlSanitizer exists to normalize rendered package documentation fragments before AppSurface Docs displays them. It is not a general-purpose user-generated-content sanitizer, JavaScript policy, or replacement for a host-owned Content Security Policy. Unsupported elements or attributes may be removed.

Method

Sanitize

string Sanitize(string html)

Sanitizes the provided HTML fragment.

Parameters

  • html
    The rendered AppSurface Docs HTML fragment to sanitize.

Returns

The sanitized HTML fragment.

Remarks

Sanitize expects a non-null rendered AppSurface Docs HTML fragment, not a complete document or unrendered template. Implementations should throw ArgumentNullException when html is null and should preserve already-encoded text rather than double-encoding it.

Type

JavaScriptDocHarvester

Source

Harvests intentionally public JavaScript API doclets from policy-approved plain .js source files.

Remarks

The harvester is enabled by default through AppSurfaceDocsJavaScriptHarvestOptions.Enabled and scans repository-relative JavaScript candidates that pass the shared harvest path policy. V1 is deliberately strict: broad discovery requires @public , treats @internal , @private , and @ignore as hard exclusions, skips file and directory reparse points before reads or descent, and turns unsupported public shapes into harvest diagnostics instead of partial docs.

Method

HarvestAsync

2 overloads
Task<IReadOnlyList<DocNode>> HarvestAsync(string rootPath, CancellationToken cancellationToken = default)

Scans policy-approved JavaScript files under the repository root and returns generated AppSurface Docs API nodes.

Parameters

  • rootPath
    The repository root used to resolve include and exclude globs.
  • cancellationToken
    An optional token to observe while reading and parsing files.

Returns

Generated group pages plus fragment-addressable stub nodes for harvested JavaScript API items.

Task<IReadOnlyList<DocNode>> HarvestAsync(DocHarvestContext context, CancellationToken cancellationToken = default)

Scans JavaScript sources with the repository-scoped path policy captured for the current aggregation pass.

Parameters

  • context
    The harvest context containing the repository root and active path policy snapshot.
  • cancellationToken
    An optional token to observe while reading and parsing files.

Returns

Generated JavaScript API group pages and fragment-addressable API nodes.

Remarks

This overload is used by the aggregator so VCS ignore exclusions are applied consistently across traversal and file inclusion checks. Custom harvesters continue to use the public HarvestAsync(string, CancellationToken) contract.

Method

IsValidEventDetailPropertyName

bool IsValidEventDetailPropertyName(string value)

Validates whether a parsed @property name is a supported event detail field contract.

Parameters

  • value
    Parsed member name from the doclet property tag.

Returns

true when the member name represents a valid detail.* path; otherwise false .

Remarks

The validator trims whitespace, strips optional JSDoc property wrappers through StripOptionalPropertyWrapper , requires an ordinal detail. prefix, and validates each remaining segment with IsValidEventDetailPropertySegment . Array contracts use a trailing [] on a segment, such as detail.items[] or detail.items[].id . Common pitfalls are blank names, omitted detail. prefixes, empty segments, unsupported characters, and assuming case-insensitive matching.

Method

ClassifyHarvestCandidate

2 overloads
JavaScriptHarvestCandidate ClassifyHarvestCandidate(string rootPath, string candidatePath)

Classifies a JavaScript harvest candidate before the harvester reads a source file or descends into a directory.

Parameters

  • rootPath
    The repository root that bounds built-in JavaScript harvesting.
  • candidatePath
    The candidate file or directory path to inspect.

Returns

The candidate's normalized path metadata and safety state.

JavaScriptHarvestCandidate ClassifyHarvestCandidate(string rootPath, string candidatePath, Func<string, FileAttributes> getAttributes)

Classifies a JavaScript harvest candidate with a caller-supplied attribute reader for deterministic boundary tests.

Parameters

  • rootPath
    The repository root that bounds built-in JavaScript harvesting.
  • candidatePath
    The candidate file or directory path to inspect.
  • getAttributes
    Reads file-system attributes for an already-normalized in-root candidate.

Returns

The candidate's normalized path metadata and safety state.

Type

JavaScriptHarvestCandidate

Source

Captures the normalized path and boundary decision for a JavaScript harvest file-system candidate.

Parameters

  • Status
    The pre-read safety state for the candidate.
  • FullPath
    The normalized absolute candidate path.
  • RelativePath
    The repository-root-relative candidate path used in glob matching and diagnostics.
Type

AppSurfaceDocsStreamAuthorization

Source

Provides stable helpers for host-owned AppSurface Docs RazorWire stream authorization.

Remarks

Host applications that implement IRazorWireStreamAuthorizer , or legacy IRazorWireChannelAuthorizer compatibility policies, should use IsHarvestProgressChannel(string?) when applying production authorization rules to the AppSurface Docs live harvest progress stream. Prefer the predicate over raw string comparison so future docs-owned stream naming remains centralized.

Method

IsHarvestProgressChannel

bool IsHarvestProgressChannel(string? channel)

Determines whether a RazorWire channel is the AppSurface Docs live harvest progress channel.

Parameters

  • channel
    The requested RazorWire channel name.

Returns

true when channel exactly matches HarvestProgressChannel or a valid named product channel returned by GetHarvestProgressChannel ; otherwise false . Null, empty, malformed, and differently cased channel names do not match.

Method

IsLegacyHarvestProgressChannel

bool IsLegacyHarvestProgressChannel(string? channel)

Determines whether a RazorWire channel is the one legacy AppSurface Docs harvest-progress channel.

Parameters

  • channel
    The requested RazorWire channel name.

Returns

true only for an exact legacy Docs harvest-progress channel match.

Remarks

Legacy Docs registration owns only HarvestProgressChannel . Named Docs channels must be handled by AppSurfaceDocsNamedHarvestStreamAuthorizationFilter ; treating every named-looking channel as legacy Docs would override unrelated host channel policies that happen to use the same prefix.

Method

GetHarvestProgressChannel

string GetHarvestProgressChannel(string instanceName)

Builds the isolated harvest-progress channel name for one named Docs product.

Parameters

  • instanceName
    The Docs product name to normalize. It must contain 1-64 ASCII letters, digits, hyphens, or underscores.

Returns

A stable, lowercase RazorWire-safe channel name for the supplied product.

Exceptions

  • ArgumentException
    Thrown when instanceName is blank or is not a valid Docs product name.
Method

TryGetNamedInstanceFromHarvestProgressChannel

bool TryGetNamedInstanceFromHarvestProgressChannel(string? channel, out string? instanceName)

Attempts to read the Docs product name from a named harvest-progress channel.

Parameters

  • channel
    The requested RazorWire channel.
  • instanceName
    The canonical lowercase instance name when the channel belongs to a named Docs product.

Returns

true when channel is a named Docs harvest channel with a 1-64 character Docs product suffix; otherwise false .

Type

DocContentLinkRewriter

Source

Rewrites harvested documentation links so authored Markdown can use repository-relative source links while the rendered docs experience still navigates through canonical AppSurface Docs routes.

Method

PrefixPathBaseForDocsUrls

string PrefixPathBaseForDocsUrls(string html, string docsRootPath, string? requestPathBase, string routeRootPath = DocsUrlBuilder.DocsEntryPath)

Prefixes request PathBase for rooted docs-local anchor hrefs in rendered HTML content.

Parameters

  • html
    The rendered HTML fragment whose rooted docs-local links should honor the current request path base.
  • docsRootPath
    The current live docs root that owns source-backed documentation routes.
  • requestPathBase
    The request path base that should prefix rooted docs-local hrefs when present.
  • routeRootPath
    The route-family root that owns stable entry, archive, and exact-version routes.

Returns

The original fragment when no path base applies or no docs-local rooted links are present; otherwise a fragment whose docs-local anchor hrefs are prefixed so mounted apps stay inside their virtual root.

Remarks

This helper intentionally scopes itself to docs-local routes rather than all rooted links. Authored content may legitimately include other site-rooted links that should remain outside the docs shell, while docs-local links generated by RewriteInternalDocLinks(string,string,string,DocLinkTargetManifest) must stay within the current mounted app.

Type

MarkdownHarvester

Source

Harvester implementation that scans Markdown source files and converts them into documentation nodes.

Method

HarvestAsync

2 overloads
Task<IReadOnlyList<DocNode>> HarvestAsync(string rootPath, CancellationToken cancellationToken = default)

Harvests Markdown files under the specified root directory and converts each into a DocNode containing a display title, relative path, generated HTML, metadata, and page outline.

Parameters

  • rootPath
    The root directory to search recursively for `.md` files and an optional root `LICENSE` file.
  • cancellationToken
    An optional token to observe for cancellation requests.

Returns

A collection of DocNode objects representing each processed Markdown source file, including the display title, path relative to rootPath , generated HTML, metadata, and DocNode.Outline entries when outline headings are available.

Remarks

Skips files in excluded directories (for example "node_modules", "bin", "obj", and "Tests") and hidden dot-prefixed directories unless explicitly allowlisted. Dot-prefixed files are included. File and directory reparse points are skipped so symlinks and junctions cannot point the built-in harvester outside rootPath . The root LICENSE file is also included when present and not a reparse point so repository-relative license links can resolve in static exports. The special releases/unreleased.md path loads and composes validated append-only entries from releases/unreleased.entries before parsing and rendering. Because that rendered note is not byte-for-byte checked-in source, it is never retained for protected Markdown download. If a file's name is "README" (case-insensitive), its title is set to the parent directory name or "Home" for a repository root README. Before parsing, valid rich-authoring tabs render to placeholders, directive fences are normalized, and the generated tabs HTML replaces those placeholders. The resulting renderedMarkdownBody is parsed once; HTML is rendered from that AST and DocNode.Outline is populated from the same AST with ExtractOutline , then filtered through the resolved Markdown outline policy so callers can rely on display outline data being present when eligible headings are available. DocNode.RichAuthoringTabsTokens contains the generated tab tokens used by the trusted client runtime, while malformed rich-authoring directives remain literal and add harvest diagnostics available through IDocHarvesterDiagnosticProvider . Files that fail to process are skipped and an error is logged.

Task<IReadOnlyList<DocNode>> HarvestAsync(DocHarvestContext context, CancellationToken cancellationToken = default)

Harvests Markdown files with the repository-scoped path policy captured for the current aggregation pass.

Parameters

  • context
    The harvest context containing the repository root and active path policy snapshot.
  • cancellationToken
    An optional token to observe for cancellation requests.

Returns

Markdown documentation nodes generated from eligible repository files.

Remarks

This overload is used by the aggregator so VCS ignore exclusions are applied consistently across traversal and file inclusion checks. Custom harvesters continue to use the public HarvestAsync(string, CancellationToken) contract.

Method

HarvestWithSourceAsync

Task<MarkdownHarvestResult> HarvestWithSourceAsync(DocHarvestContext context, CancellationToken cancellationToken = default)

Harvests the built-in Markdown surface and, when enabled, retains eligible valid-UTF-8 source bytes for the aggregator's private download sidecar.

Remarks

This internal result is intentionally separate from DocNode so raw source never enters rendered HTML, search indexes, or the public harvester contract. The special releases/unreleased.md source is composed with validated append-only entries before parsing and rendering, so it cannot expose a source-faithful download even when protected source capture is enabled. The byte-reader seam is used only for Markdown source capture; metadata sidecars and disabled downloads continue through the configured text reader.

Method

TryDecodeValidUtf8

bool TryDecodeValidUtf8(byte[] bytes, out string content)

Attempts a strict UTF-8 decode and falls back to replacement decoding.

Parameters

  • bytes
    The raw Markdown source bytes.
  • content
    The decoded text with a leading byte-order mark removed. This is populated on both outcomes; when the return value is false , it contains the replacement-decoded content.

Returns

true when bytes is valid UTF-8; otherwise false .

Method

ReadMetadataSidecarAsync

Task<DocMetadata?> ReadMetadataSidecarAsync(string markdownFilePath, string relativeMarkdownPath, CancellationToken cancellationToken, ICollection<DocHarvestDiagnostic>? harvestDiagnostics = null)

Reads an optional paired sidecar metadata file for a Markdown source document.

Parameters

  • markdownFilePath
    The absolute Markdown file path.
  • relativeMarkdownPath
    The Markdown file path relative to the harvest root.
  • cancellationToken
    A token that can cancel sidecar discovery or file reads.
  • harvestDiagnostics
    Optional harvest diagnostic collection that receives sidecar metadata warnings.

Returns

The parsed sidecar metadata, or null when no valid sidecar applies.

Remarks

AppSurface Docs supports paired metadata files named {file}.yml and {file}.yaml such as README.md.yml . Reparse-point sidecars are ignored so metadata cannot be imported through a symlink or junction outside the harvest root. When both non-reparse extensions exist for the same Markdown file, AppSurface Docs logs a warning and ignores both sidecars until the ambiguity is removed. Inline front matter remains the primary metadata source and overrides any overlapping sidecar fields.

Method

ExtractOutline

IReadOnlyList<DocOutlineItem> ExtractOutline(MarkdownDocument document)

Extracts page-local outline entries from Markdown heading blocks.

Parameters

  • document
    The parsed Markdown document whose heading blocks should be inspected.

Returns

A source-ordered list of DocOutlineItem values. Each item contains the rendered fragment DocOutlineItem.Id , normalized reader-facing DocOutlineItem.Title , and original heading DocOutlineItem.Level .

Remarks

Only HeadingBlock descendants with levels between MinOutlineHeadingLevel and MaxOutlineHeadingLevel are included, which means the built-in Markdown harvester emits H2-H3 headings by default. Fragment IDs come from HtmlAttributesExtensions.GetAttributes(heading).Id and titles are produced by NormalizeHeadingText(ExtractInlineText(heading.Inline)) . Headings without a non-empty fragment ID or normalized title are silently omitted; consumers and tests should account for those drops and for whitespace normalization when comparing outline titles.

Method

ExtractLeadingTitle

string? ExtractLeadingTitle(MarkdownDocument document)

Extracts the document title from a leading Markdown H1 when one exists.

Parameters

  • document
    The parsed Markdown document whose first block may be a page-title H1.

Returns

The normalized heading text from the leading H1, or null when the document starts with another block or the H1 has no readable text.

Remarks

This mirrors details-page H1 suppression: only the leading H1 can become package-owned page chrome. Later H1 elements remain body structure and do not replace filename or metadata title fallback behavior.

Method

ExtractInlineText

string ExtractInlineText(ContainerInline? inline)

Extracts plain reader-facing text from a Markdig inline container for outline display.

Parameters

  • inline
    The inline container to flatten.

Returns

The extracted text, or an empty string when no inline content exists.

Method

NormalizeHeadingText

string NormalizeHeadingText(string value)

Normalizes heading text by collapsing whitespace without introducing leading spaces.

Parameters

  • value
    The raw heading text.

Returns

The normalized heading text.

Type

MarkdownHarvestResult

Source

Private built-in Markdown harvest output used to retain source bytes beside the rendered Docs graph.

Remarks

This type intentionally stays internal. Raw Markdown must not become part of DocNode , the search index, or the public custom-harvester contract.

Type

AppSurfaceDocsRichAuthoringMarkdownExtension

Source

Registers the bounded rich-authoring directives that AppSurface Docs owns.

Remarks

The extension deliberately builds on Markdig's fenced custom-container parser. The harvester first recognizes valid tabs and emits their complete server-rendered baseline; this extension then renders callouts, preserves generic custom containers, and leaves invalid rich directives visible as source markers with their body intact instead of guessing them into an interactive component.

Type

AppSurfaceDocsRichAuthoringRenderer

Source

Renders AppSurface Docs' package-owned rich-authoring custom containers.

Type

AppSurfaceDocsRichAuthoringSyntax

Source

Validates the deliberately small rich-authoring directive grammar and produces author diagnostics.

Method

NormalizeDirectiveFences

string NormalizeDirectiveFences(string markdown)

Normalizes package directives to Markdig's generic custom-container fence shape without changing authored code.

Parameters

  • markdown
    The Markdown source about to enter the Markdig pipeline.

Returns

Markdown whose supported directive opening fences have the parser-required separator.

Remarks

Markdig's generic custom-container extension recognizes ::: callout , while AppSurface Docs deliberately exposes the compact :::callout authoring grammar. The conversion is limited to actual Markdown lines and skips fenced code so syntax examples continue to render as literal code.

Method

RenderValidTabs

AppSurfaceDocsRichAuthoringTabsRenderResult RenderValidTabs(string markdown, string sourcePath, Func<string, string> renderPanelMarkdown)

Replaces valid package tabs with fixed server-rendered HTML before Markdig parses the surrounding Markdown.

Parameters

  • markdown
    The authored Markdown body.
  • sourcePath
    The source-relative documentation path used to namespace generated DOM IDs.
  • renderPanelMarkdown
    Renders one parsed panel body through the package Markdown pipeline.

Returns

A source-safe replacement plan for valid tabs and their complete server-rendered source-order baseline.

Remarks

Markdig custom containers intentionally do not nest containers with an identical author-facing fence. AppSurface Docs keeps the compact uniform ::: grammar by recognizing the bounded tabs structure before invoking Markdig, then delegates each panel's ordinary Markdown back to the same pipeline. Invalid groups are left untouched so the generic rich-authoring fallback remains visible and diagnostic-producing.

Type

AppSurfaceDocsRichAuthoringTabsRenderResult

Source

Holds valid tabs rendered into placeholders so directive normalization never reprocesses their generated HTML.

Type

AppSurfaceDocsRichAuthoringTabsReplacement

Source

Associates one source-safe tabs placeholder with its generated server HTML.

Type

AppSurfaceDocsRichAuthoringValidation

Source

Describes the result of validating one custom container against the rich-authoring grammar.

Type

AppSurfaceDocsHarvestPathRuleTrace

Source

Captures one rule evaluation step for internal harvest path diagnostics.

Parameters

  • Code
    The decision code represented by the trace step.
  • Scope
    The rule scope, such as global , Markdown , CSharp , or default-allow .
  • Pattern
    The configured pattern that matched, or null when the step has no pattern match.
  • DefaultGroup
    The default exclusion group involved in the step, or null when the step is not group-based.
  • Matched
    Whether the rule matched the candidate path.
  • SourcePath
    The repository-relative rule source path when a filesystem-backed rule matched.
  • LineNumber
    The one-based rule source line number when a filesystem-backed rule matched.
Type

IDocHarvesterDiagnosticProvider

Source

Exposes non-fatal diagnostics captured by a harvester during its most recent successful run.

Remarks

The aggregate health snapshot reads these diagnostics only after the harvester participates in the current snapshot. Failed, timed-out, canceled, or disabled harvesters surface through the primary harvester-health diagnostic instead.

Method

GetHarvestDiagnostics

IReadOnlyList<DocHarvestDiagnostic> GetHarvestDiagnostics()

Gets the diagnostics captured during the most recent completed harvester run.

Returns

Structured diagnostics suitable for inclusion in the aggregate harvest-health snapshot.

Type

PublishedSearchIndexDocumentPathPolicy

Source

Validates document paths carried by published AppSurface Docs search-index payloads.

Remarks

Published search indexes are archive metadata, not a general URL surface. Archive payloads must store canonical /docs -rooted document paths so the published-tree rewriter can safely rebase them for aliases, exact versions, custom route roots, and request path bases at serve time. The served-path entry point is a defense-in-depth check for already-rebased browser links; it must not be used to validate immutable archive contents.

Method

ValidateArchivePath

PublishedSearchIndexPathValidationResult ValidateArchivePath(string? value, PublishedSearchIndexArchivePathContext context)

Validates a path stored in an exact published release tree's search-index.json .

Parameters

  • value
    The candidate documents[*].path value.
  • context
    The immutable archive validation context.

Returns

A structured validation result whose PublishedSearchIndexPathValidationResult.Reason identifies the first rejected condition, or PublishedSearchIndexPathRejectionReason.None when the archive value is safe to store.

Remarks

Archive validation is intentionally stricter than served-link validation: stored paths must use canonical /docs/... forms and must not include request path bases, custom route roots, origins, or deployment aliases. The checks run from syntax and URL-shape hazards toward docs-root and version-family hazards. When several rejection reasons apply, callers should log or surface only the returned first reason plus PublishedSearchIndexPathValidationResult.RedactedValue ; do not log the original value.

Method

ValidateRecommendationArchivePath

PublishedSearchIndexPathValidationResult ValidateRecommendationArchivePath(string? value, PublishedSearchIndexArchivePathContext context)

Validates a nested recommendation URL stored in an immutable release archive.

Parameters

  • value
    The original complete recommendation URL, including any query or fragment.
  • context
    The exact archive version being validated.

Returns

A canonical stable- /docs route and its validated fragment, or a redacted rejection.

Remarks

Recommendation paths always store the stable export route, even when the top-level document-path policy accepts an already-versioned path for compatibility. The original value is passed through that existing policy first so URL shape, origin, suffix encoding, traversal, and reserved-route checks run before the query is discarded.

Method

ValidateServedPath

PublishedSearchIndexPathValidationResult ValidateServedPath(string? value, PublishedSearchIndexServedPathContext context)

Validates a browser-visible search result path after published-tree rewriting has applied the active docs root.

Parameters

  • value
    The candidate browser-visible path.
  • context
    The served docs surface context.

Returns

A structured validation result whose PublishedSearchIndexPathValidationResult.NormalizedPath is safe to use as a browser-visible link only when PublishedSearchIndexPathValidationResult.IsValid is true .

Remarks

Served validation accepts the active docs root and optional archive root after route rewriting has already happened. It still rejects executable schemes, off-root links, traversal, encoded separators, controls, and reserved docs endpoints before the value can enter client-side result rendering.

Method

ToDiagnosticCode

string ToDiagnosticCode(PublishedSearchIndexPathRejectionReason reason)

Converts a rejection reason to the stable lower-kebab diagnostic code used in logs, telemetry, and tests.

Parameters

  • reason
    The structured validation reason returned by the policy.

Returns

One of none , missing , whitespace , not-root-relative , scheme-url , absolute-url , protocol-relative , backslash , control-character , malformed-percent-encoding , encoded-separator , encoded-traversal , outside-docs-root , reserved-route , wrong-version , or unknown for future enum values.

Remarks

Use PublishedSearchIndexPathRejectionReason for code branching and this string only for stable diagnostics that may cross process, log, or test boundaries.

Type

PublishedSearchIndexArchivePathContext

Source

Immutable context for validating document paths stored in a published exact-version archive.

Parameters

  • Version
    The catalog version whose exact tree is being validated.
Type

PublishedSearchIndexServedPathContext

Source

Runtime context for validating already-rebased browser-visible search result paths.

Parameters

  • DocsRootPath
    The active browser-visible docs root, including request path base if present.
  • ArchiveRootPath
    The active browser-visible archive root, including request path base if present.
Type

PublishedSearchIndexPathValidationResult

Source

Structured result for a published search-index document path validation attempt.

Parameters

  • IsValid
    Whether the candidate path is safe for the target context.
  • Reason
    The stable branch-friendly rejection category, or PublishedSearchIndexPathRejectionReason.None when valid. Use PublishedSearchIndexDocumentPathPolicy.ToDiagnosticCode(PublishedSearchIndexPathRejectionReason) when a lower-kebab telemetry or log value is required.
  • NormalizedPath
    The validated path portion without query string or fragment when valid. This value is safe to log and to use for docs-root matching because unsafe suffixes and rejected inputs never appear here.
  • ValidatedFragment
    The validated fragment, including its leading # , when one was supplied.
  • RedactedValue
    A non-sensitive description of the rejected input for diagnostics. This is the only rejected-value field callers should include in operator-visible logs or reader-facing availability messages.
Method

Valid

PublishedSearchIndexPathValidationResult Valid(string normalizedPath, string? validatedFragment = null)

Creates a successful validation result for a normalized path-only value.

Parameters

  • normalizedPath
    The safe-to-log path portion with any query string or fragment removed.
  • validatedFragment
    The validated fragment, including its leading # , or null when none was supplied.

Returns

A valid result with PublishedSearchIndexPathRejectionReason.None .

Method

Invalid

PublishedSearchIndexPathValidationResult Invalid(PublishedSearchIndexPathRejectionReason reason, string redactedValue)

Creates a rejected validation result with a stable reason and redacted original value.

Parameters

  • reason
    The first rejection reason observed by the policy's ordered checks.
  • redactedValue
    A length-only or otherwise non-sensitive substitute for the rejected value.

Returns

An invalid result whose NormalizedPath is null .

Type

IAppSurfaceDocsCodeHighlighter

Source

Highlights Markdown code fences behind AppSurface Docs' internal HTML contract.

Remarks

Use this abstraction when Markdown rendering needs package-owned code HTML without coupling callers to a specific highlighter implementation. Implementations must return HTML-safe output for direct insertion into docs rendering templates, including escaped plaintext fallback for unsupported languages or failed highlighting.

Method

Highlight

AppSurfaceDocsHighlightedCode Highlight(AppSurfaceDocsCodeBlock block)

Renders a code block as either highlighted token markup or escaped plaintext fallback.

Parameters

  • block
    Non-null code block metadata and source text to render.

Returns

AppSurface Docs-owned code block HTML. Callers treat the returned value as immutable render output and insert it without additional escaping.

Exceptions

  • ArgumentNullException
    Thrown when block is null .
Type

AppSurfaceDocsSearchQualityReadModel

Source

Process-local, bounded aggregate read model for hosted AppSurface Docs search-quality review.

Remarks

This service accepts only validated, sanitized product-intelligence events. It stores no raw event payloads, raw search text, URLs, identity, cookies, request bodies, or free-form comments. The rolling window exists only to bound process memory while preserving enough recent aggregate signal for maintainer diagnostics.

Method

Record

void Record(AppSurfaceProductEventContract contract, IReadOnlyDictionary<string, string> properties)

Records one sanitized docs product-intelligence event into the bounded aggregate model.

Parameters

  • contract
    The event contract that validated the event.
  • properties
    Sanitized string properties returned by the registry.
Method

GetSnapshot

AppSurfaceDocsSearchQualityResponse GetSnapshot(AppSurfaceDocsOptions options)

Creates a maintainer-facing snapshot of the current aggregate model.

Parameters

  • options
    Current docs options used to report the resolved metrics mode.

Returns

A defensive aggregate snapshot.

Type

AppSurfaceDocsCodeLanguageCatalog

Source

Owns Markdown code-fence language normalization, safe CSS class suffixes, and TextMateSharp lookup ids.

Method

Normalize

AppSurfaceDocsCodeLanguage Normalize(string? language)

Normalizes an authored language token into AppSurface Docs' stable language contract.

Parameters

  • language
    The raw first info-string token.

Returns

A safe language descriptor for rendering and TextMate lookup.

Method

CreateSafeClassSlug

string CreateSafeClassSlug(string value)

Converts arbitrary language input into a CSS-safe lowercase ASCII slug.

Parameters

  • value
    The value to slug.

Returns

A lowercase slug containing only ASCII letters, digits, and hyphens.

Type

AppSurfaceDocsHarvestCoordinator

Source

Coordinates shared AppSurface Docs harvest work so startup warmup, first requests, and trusted operator rebuilds use one ordered source-backed loop.

Method

EnsureStarted

Task<DocHarvestHealthSnapshot> EnsureStarted()

Starts or reuses the shared initial harvest task.

Returns

The memoized harvest-health task for the current run. A new task is created when no task exists or when the prior task was canceled or faulted.

Remarks

Callers share one background harvest through this coordinator. The task itself runs with CancellationToken.None so one impatient request cannot cancel warmup for later requests.

Method

RequestRebuildAsync

ValueTask<AppSurfaceDocsHarvestRebuildRequestResult> RequestRebuildAsync(CancellationToken cancellationToken)

Requests a trusted operator rebuild of the full source-backed docs harvest.

Parameters

  • cancellationToken
    A token that cancels the request decision before any rebuild is queued.

Returns

AppSurfaceDocsHarvestRebuildRequestResult.Started when a fresh rebuild started immediately, AppSurfaceDocsHarvestRebuildRequestResult.Queued when the active run will be followed by one rebuild, or AppSurfaceDocsHarvestRebuildRequestResult.AlreadyQueued when a rebuild was already pending.

Remarks

The shared harvest itself runs with CancellationToken.None . Canceling the operator request cannot cancel a harvest already visible to other docs requests. When a rebuild is queued behind an active run, the active run's completion visit is suppressed so only the superseding rebuild returns the browser to the verified docs context.

Method

WaitForCompletionAsync

Task<bool> WaitForCompletionAsync(TimeSpan waitBudget, CancellationToken cancellationToken)

Waits for the shared initial harvest to complete within the provided wait budget.

Parameters

  • waitBudget
    The maximum time to wait. Non-positive values return false immediately.
  • cancellationToken
    A token used to cancel the caller's wait operation.

Returns

true when the harvest task completes within budget; otherwise false .

Remarks

The caller's token cancels only the wait, not the shared harvest task. Exceptions from the harvest task are observed when the task completes before the timeout.

Method

IsFatalHarvestException

bool IsFatalHarvestException(Exception exception)

Determines whether a queued rebuild continuation should avoid catching an exception that represents process-level failure rather than recoverable harvest failure.

Parameters

  • exception
    The exception observed from the active harvest task.

Returns

true for process-fatal exception types; otherwise false .

Property

CurrentProgress

AppSurfaceDocsHarvestProgressSnapshot CurrentProgress { get; } Source

Gets the latest redacted harvest progress snapshot published by the reporter.

Property

CompletionDelay

int CompletionDelay { get; } Source

Gets the completion-navigation delay, in milliseconds, used by the progress reporter.

Property

HasActiveOrQueuedHarvest

bool HasActiveOrQueuedHarvest { get; } Source

Gets a value indicating whether a harvest is running or a queued rebuild is waiting for the running harvest.

Type

DocLinkTargetManifest

Source

Enumerates the documentation targets harvested into an AppSurface Docs snapshot so link rewriting can avoid guessing from file extensions alone.

Remarks

The manifest stores both source paths, such as guides/start.md , and canonical browser paths, such as guides/start.md.html . Query strings and fragments are intentionally ignored because anchors and query parameters decorate a page target rather than defining a separate harvested document.

Method

FromNodes

DocLinkTargetManifest FromNodes(IEnumerable<DocNode> nodes)

Creates a manifest from harvested documentation nodes.

Parameters

  • nodes
    The harvested documentation nodes that may be linked through AppSurface Docs routes.

Returns

A manifest containing source and canonical target forms for the supplied nodes.

Method

FromPaths

DocLinkTargetManifest FromPaths(IEnumerable<string?> paths)

Creates a manifest from source or canonical documentation paths.

Parameters

  • paths
    The documentation paths to register as known link targets.

Returns

A manifest containing normalized source and canonical target forms.

Method

Contains

bool Contains(string? path)

Determines whether the supplied path resolves to a harvested documentation target.

Parameters

  • path
    A source or canonical documentation path, optionally rooted, queried, or fragmented.

Returns

true when the normalized target is in the manifest; otherwise false .

Type

AppSurfaceDocsHtmlSanitizer

Source

Sanitizes harvested AppSurface Docs HTML with the package-owned allowlist for docs content and highlighted code blocks.

Remarks

AppSurface Docs starts from the HtmlSanitizer defaults, adds the package-owned content tags section , article , header , details , summary , pre , code , and span , and allows the class , id , open , role , aria-label , and package-owned rich-authoring and code data-* attributes. The sanitizer explicitly removes style from the default attribute set so harvested Markdown, generated API HTML, and server-side highlighted code can keep structural hooks while inline presentation and unsafe markup are stripped. Callers should pass already-rendered AppSurface Docs HTML through this sanitizer before display or export; supported semantic wrappers and token spans are preserved, while scripts, event handlers, inline styles, and unsupported attributes are discarded.

Method

Sanitize

string Sanitize(string html)

Sanitizes rendered documentation HTML using the AppSurface Docs allowlist.

Parameters

  • html
    The rendered HTML to sanitize.

Returns

Safe HTML that preserves AppSurface Docs structural markup and removes unsupported tags or attributes.

Type

AppSurfaceDocsHarvestProgressSession

Source

Provides one package-owned harvester with a redacted, run-scoped progress reporting surface.

Remarks

This internal session accepts only a closed phase enum and numeric document deltas. It deliberately cannot carry a file name, path, source text, exception, percentage, or arbitrary activity string. Custom IDocHarvester implementations never receive this type and retain the established status-only progress contract.

Method

TransitionAsync

ValueTask TransitionAsync(AppSurfaceDocsHarvestProgressPhase phase)

Records a safe parser lifecycle transition.

Parameters

  • phase
    The next lifecycle phase. Waiting, terminal, stale, and non-sequential transitions are ignored.

Returns

A task that completes after the transition is retained and a live publication is scheduled.

Remarks

This method does not throw for an ignored transition. The server-issued progress identity prevents one harvester from mutating another harvester's state.

Method

ReportSourceUnitAsync

ValueTask ReportSourceUnitAsync(int documentsFoundDelta)

Records one inspected source unit and an optional output delta.

Parameters

  • documentsFoundDelta
    The non-negative number of documents found in the inspected source unit. Zero records source inspection without output.

Returns

A task that completes after the delta is recorded and any configured test pacing has elapsed.

Exceptions

  • ArgumentOutOfRangeException
    Thrown when documentsFoundDelta is negative.
  • OperationCanceledException
    Thrown when harvester cancellation interrupts configured pacing for a positive delta.

Remarks

A positive output delta is paced one document at a time only when the local test delay is configured. The delay follows the real report that found those documents; source units that yield no documents are never delayed.

Method

ReportOutputOnlyAsync

ValueTask ReportOutputOnlyAsync(int documentsFoundDelta)

Records materialized output that is not attributable to one newly inspected source unit.

Parameters

  • documentsFoundDelta
    The non-negative number of additional documents materialized without inspecting a source unit.

Returns

A task that completes after the delta is recorded and any configured test pacing has elapsed.

Exceptions

  • ArgumentOutOfRangeException
    Thrown when documentsFoundDelta is negative.
  • OperationCanceledException
    Thrown when harvester cancellation interrupts configured pacing for a positive delta.

Remarks

Zero is valid and is not paced. Negative values throw ArgumentOutOfRangeException from the reporter. Only positive deltas are delayed, so reporting a source unit that produces no documents never slows a harvester.

Type

AppSurfaceDocsHarvestFailurePreflightService

Source

Starts the optional AppSurface Docs harvest warmup and performs the strict harvest-health startup preflight.

Remarks

The service is always registered by AddAppSurfaceDocs() . By default it starts the same memoized harvest used by docs requests through their shared AppSurfaceDocsHarvestCoordinator . Blocking and strict startup await that same task, so completed warmup is immediately visible to requests even with a zero request-wait budget. Strict mode fails startup only when the aggregate snapshot is failed.

Method

StartAsync

Task StartAsync(CancellationToken cancellationToken)

Checks harvest health during host startup when strict harvest failure is enabled.

Parameters

  • cancellationToken
    Token observed while waiting for the cached harvest-health snapshot.

Returns

A completed task when strict mode is disabled or the aggregate status is not failed.

Exceptions

  • AppSurfaceDocsHarvestFailedException
    Thrown when AppSurfaceDocsHarvestOptions.FailOnFailure is enabled and the aggregate harvest status is DocHarvestHealthStatus.Failed .
Method

StopAsync

Task StopAsync(CancellationToken cancellationToken)

Stops the preflight service.

Parameters

  • cancellationToken
    Unused cancellation token supplied by the host.

Returns

A completed task because the preflight owns no background work.

Method

EnsureHarvestStarted

Task<DocHarvestHealthSnapshot> EnsureHarvestStarted()

Shares request readiness when available, preserving hosts that remove the optional coordinator.

Type

LocalizedDocsGraph

Source

Captures locale identity, grouping, and diagnostics for one docs snapshot.

Parameters

  • Enabled
    Whether localization graph behavior was enabled when the snapshot was built.
  • DefaultLocale
    Configured default locale, or null when disabled or unavailable.
  • DocSets
    Translation-key groups ordered for deterministic consumption.
  • VariantsBySourcePath
    Case-insensitive lookup from normalized source path to the first resolved variant.
  • Diagnostics
    Non-fatal authoring diagnostics emitted while resolving localization facts.

Remarks

The graph is the Phase 1 localization handoff between harvesters, route identity, navigation, fallback, and search projection code. Consumers should use this graph instead of re-inferring locale state from source paths.

Type

LocalizedDocSet

Source

Groups localized variants that represent the same conceptual documentation page.

Parameters

  • TranslationKey
    Stable page identity shared across locale variants.
  • DefaultLocaleSourcePath
    Source path for the default-locale variant, or null when missing.
  • Variants
    Resolved variants for this translation key, ordered by locale and source path.
  • FallbackMode
    Effective missing-translation fallback behavior for the group.
Type

LocalizedDocVariant

Source

Describes one resolved localized document variant.

Parameters

  • SourcePath
    Normalized source path for the variant.
  • Locale
    Configured locale code selected for the variant.
  • TranslationKey
    Stable translation identity used to group variants.
  • Title
    Localized title, metadata title, or harvested title in precedence order.
  • PublicRoutePath
    Existing public route path for the base document identity, or null when unavailable.
  • LocaleFallback
    Optional page-level fallback override authored by the variant.
  • LocaleWasInferred
    Whether locale came from inference/defaulting rather than explicit metadata.
  • TranslationKeyWasInferred
    Whether translation key came from source path inference.

Remarks

Locale and translation key may be authored in metadata, inferred from a configured filename suffix, inferred from a locale folder when a translation key is authored, or defaulted to the configured default locale. Public route paths are null when route identity rejected the source path.

Type

LocalizedDocsGraphBuilder

Source

Builds the locale-aware document graph used by later route, navigation, fallback, and search projections.

Remarks

This Phase 1 builder is intentionally internal. It records document identity and locale facts without changing the existing visible route or search behavior. Later slices should consume this graph instead of re-inferring locale state in controllers, views, or JavaScript.

Method

Build

LocalizedDocsGraph Build(IEnumerable<DocNode> docs, DocRouteIdentityCatalog routeIdentityCatalog)

Builds the localized graph for a docs snapshot.

Parameters

  • docs
    Harvested docs from the snapshot.
  • routeIdentityCatalog
    Route catalog for resolving public route candidates.

Returns

A disabled empty graph when localization is off, otherwise the resolved localization graph.

Remarks

The builder skips fragment stub source paths, reports unsupported locale signals, duplicate variants, missing bases, folder conflicts, disabled fallback gaps, and conflicting fallback overrides as diagnostics, then returns whatever safe graph data it can derive.

Type

AppSurfaceDocsIdentityResolver

Source

Resolves normalized AppSurface Docs identity options into render-ready browser chrome values.

Remarks

The resolved identity intentionally stores only app-relative or app-root paths. Razor views apply the current request path base at render time with Url.PathBaseAware(...) , so singleton identity resolution stays safe for virtual-directory deployments and tests that render the same service provider under multiple path bases.

Property

Identity

AppSurfaceDocsResolvedIdentity Identity { get; } Source

Gets the render-ready identity used by AppSurface Docs layouts.

Type

AppSurfaceDocsResolvedIdentity

Source

Render-ready AppSurface Docs identity.

Parameters

  • DisplayName
    Visible docs product name.
  • HomeHref
    App-root or application-relative brand home link.
  • Logo
    Optional resolved logo.
  • Favicons
    Resolved favicon link entries.
Property

WordmarkHighlightText

string? WordmarkHighlightText { get; init; } Source

Gets the first display-name substring rendered with highlight treatment by the built-in docs chrome.

Remarks

Null means the wordmark is rendered as plain text. The value is already trimmed and confirmed to appear in DisplayName , so Razor views can split the display name without repeating configuration policy.

Property

WordmarkHighlightColor

string? WordmarkHighlightColor { get; init; } Source

Gets the CSS hex color used for WordmarkHighlightText .

Remarks

Null keeps highlighted text in the surrounding wordmark color. Non-null values have already passed the AppSurface Docs CSS hex color allowlist.

Type

AppSurfaceDocsResolvedFavicon

Source

Render-ready AppSurface Docs favicon entry.

Parameters

  • Path
    App-root or application-relative favicon path.
  • Type
    Favicon MIME type.
Type

MarkdownFrontMatterParser

Source
Method

Extract

(string Markdown, DocMetadata? Metadata) Extract(string markdown)

Extracts inline Markdown front matter and returns the remaining Markdown with parsed metadata.

Parameters

  • markdown
    The Markdown source that may begin with YAML front matter.

Returns

A tuple containing the Markdown body and parsed DocMetadata when present and valid.

Remarks

This compatibility wrapper discards parser diagnostics. Invalid inline YAML returns the original Markdown with null metadata, and non-fatal authoring warnings such as invalid curation YAML or migration metadata are intentionally not surfaced. Call ExtractWithDiagnostics when callers need warnings.

Method

ExtractWithDiagnostics

(string Markdown, MarkdownMetadataParseResult Result) ExtractWithDiagnostics(string markdown)

Extracts inline Markdown front matter and returns the remaining Markdown with diagnostics-aware metadata.

Parameters

  • markdown
    The Markdown source that may begin with YAML front matter.

Returns

A tuple containing the Markdown body and a MarkdownMetadataParseResult whose MarkdownMetadataParseResult.Metadata contains parsed DocMetadata when present.

Remarks

This is the authoritative internal entry point for inline metadata parsing. Missing front matter returns the original Markdown and an empty diagnostic list. Invalid inline YAML returns a AppSurfaceDocsMetadataDiagnostic instead of throwing, and deliberately preserves the original Markdown so a malformed header remains visible to the reader. Callers should inspect MarkdownMetadataParseResult.Diagnostics for authoring warnings instead of relying on exceptions for inline metadata failures.

Method

ParseMetadataYaml

DocMetadata? ParseMetadataYaml(string yaml)

Parses a YAML metadata document into normalized documentation metadata.

Parameters

  • yaml
    The raw YAML content to deserialize.

Returns

The normalized metadata model, or null when the YAML document is empty or explicitly null.

Exceptions

  • YamlException
    Thrown when yaml cannot be parsed as YAML.

Remarks

This compatibility wrapper is shared by inline Markdown front matter and paired sidecar metadata files so both authoring styles normalize through the same schema, defaults, and empty-list handling. It returns only the MarkdownMetadataParseResult.Metadata value from ParseMetadataYamlWithDiagnostics(string) and intentionally discards schema, migration, and authoring diagnostics. Call ParseMetadataYamlWithDiagnostics(string) when callers need those warnings in addition to normalized DocMetadata .

Method

ParseMetadataYamlWithDiagnostics

MarkdownMetadataParseResult ParseMetadataYamlWithDiagnostics(string yaml)

Parses a YAML metadata document into a diagnostics-aware metadata result.

Parameters

  • yaml
    The raw YAML metadata document to deserialize.

Returns

A MarkdownMetadataParseResult containing optional normalized DocMetadata plus any AppSurfaceDocsMetadataDiagnostic warnings produced while normalizing supported metadata fields.

Remarks

This is the authoritative internal entry point for metadata documents that are already known to be YAML, including sidecar files. Empty documents and explicit YAML null values return null metadata and no diagnostics. An empty mapping literal such as {} still produces a normalized DocMetadata instance whose fields may all be null . YAML syntax errors still throw YamlException so sidecar callers can report the sidecar file failure through their existing error path; schema and migration warnings are returned through MarkdownMetadataParseResult.Diagnostics .

Method

GetMarkdownDownloadEligibility

MarkdownDownloadEligibility GetMarkdownDownloadEligibility(string markdown)

Determines whether inline front matter explicitly opts a Markdown document into protected source download.

Parameters

  • markdown
    The original Markdown text decoded from a valid UTF-8 source file.

Returns

A value that is eligible only for the exact top-level plain declaration download_markdown: true . A present declaration with another shape is marked invalid so harvest health can guide the document author.

Remarks

This intentionally does not use general metadata binding or paired sidecars. Download eligibility is a security declaration: quoted strings, nested fields, duplicate declarations, alternative casing, and truthy-looking values must not accidentally expose raw source.

Type

AppSurfaceDocsHarvestStreamAuthorizationFilter

Source

Enforces AppSurface Docs' reserved harvest-stream gate before host RazorWire stream authorizers run.

Remarks

This filter protects the docs-owned harvest progress channel even when a host registers an IRazorWireStreamAuthorizer after AddAppSurfaceDocs() and thereby replaces the normal Docs wrapper in Microsoft DI. The filter only gates the reserved AppSurface Docs channel; non-docs channels continue to the host authorizer unchanged.

Method

AuthorizeAsync

ValueTask<AppSurfaceAuthResult?> AuthorizeAsync(RazorWireStreamAuthorizationContext context)

Applies hidden-route and shared read-policy checks to the AppSurface Docs harvest progress channel.

Parameters

  • context
    Current stream authorization context.

Returns

null for non-docs channels or when the normal Docs wrapper is already active; otherwise a gate result that denies hidden routes or read-policy failures and lets host authorizers narrow successful reads.

Type

AppSurfaceDocsHarvestPathPolicy

Source

Applies AppSurface Docs harvest path rules for source-backed Markdown, C#, JavaScript, and Python documentation.

Remarks

Policy order is intentionally fixed: built-in source candidates are checked first, then global includes, source-specific includes, default exclusion groups and their allows, repository VCS ignore rules when a snapshot supplies them, global excludes, and source-specific excludes. Default groups protect build output, hidden directories, test projects, and C# source under examples . Directory pruning uses the same defaults and clear /** subtree excludes, but keeps a default-excluded subtree only when a configured group allow can match that directory or one of its descendants.

Method

CreateDefault

AppSurfaceDocsHarvestPathPolicy CreateDefault()

Creates a policy with package defaults and no configured include or exclude globs.

Method

Evaluate

AppSurfaceDocsHarvestPathDecision Evaluate(string relativePath, AppSurfaceDocsHarvestSourceKind sourceKind)

Evaluates a repository-relative path and returns the include/exclude decision with rule trace details.

Remarks

The input must be a normalized relative candidate. Invalid paths are excluded with AppSurfaceDocsHarvestPathDecisionCode.ExcludedByInvalidPath . Include misses use the Miss codes, while configured exclude and default-group denials use their corresponding ExcludedBy* codes.

Method

ShouldIncludeFilePath

bool ShouldIncludeFilePath(string relativePath, AppSurfaceDocsHarvestSourceKind sourceKind)

Returns whether relativePath is included by the path evaluator.

Method

EnumerateCandidateFiles

IEnumerable<string> EnumerateCandidateFiles(string rootPath, AppSurfaceDocsHarvestSourceKind sourceKind, string searchPattern, CancellationToken cancellationToken)

Enumerates candidate files under rootPath while pruning policy-excluded subtrees.

Remarks

The searchPattern is applied to each visited directory. File and directory reparse points are skipped before they can be harvested or traversed, so symlinks and junctions cannot point built-in harvesters outside the selected repository root. Cancellation is observed between directory visits.

Method

ShouldPruneDirectory

bool ShouldPruneDirectory(string relativeDirectory, AppSurfaceDocsHarvestSourceKind sourceKind)

Returns whether a normalized repository-relative directory can be skipped during traversal.

Remarks

Invalid directories are pruned. Default-excluded directories are pruned unless the matched group has an allow glob that can apply to a file inside the directory or a descendant. Configured subtree excludes prune only when a /** pattern matches the directory.

Method

IsKnownDefaultGroupId

bool IsKnownDefaultGroupId(string? groupId)

Returns whether groupId is a supported named default exclusion group.

Remarks

Matching is case-insensitive but name-only; numeric enum values are rejected so configuration stays stable.

Method

NormalizeDefaultGroupId

string NormalizeDefaultGroupId(string? groupId)

Normalizes a named default exclusion group to canonical casing, or returns the trimmed input when unsupported.

Type

AppSurfaceDocsHarvestPathMatcher

Source

Evaluates normalized repository-relative paths against ordered harvest glob patterns.

Remarks

Matching is case-insensitive. MatchFirst is order-dependent and returns the first configured pattern that matches the candidate. Directory helpers are conservative because pruning must never skip a file that a later allow pattern could include; callers should validate and normalize paths before invoking the matcher.

Method

MatchFirst

string? MatchFirst(string relativePath)

Returns the first configured pattern that matches relativePath , or null when none match.

Method

MatchDirectorySubtree

string? MatchDirectorySubtree(string relativeDirectory)

Returns the first /** subtree pattern that matches relativeDirectory itself.

Remarks

The matcher probes a sentinel child path under the directory. This keeps clear subtree excludes fast, but patterns that do not end in /** are ignored because they may describe only files or a narrower leaf match.

Method

MatchDirectoryOrDescendantSubtree

string? MatchDirectoryOrDescendantSubtree(string relativeDirectory)

Returns the first /** pattern that could match the directory or one of its descendants.

Method

MatchDirectoryOrDescendant

string? MatchDirectoryOrDescendant(string relativeDirectory)

Returns the first pattern that could match a file inside relativeDirectory or a descendant.

Remarks

This is intentionally broader than MatchDirectoryOrDescendantSubtree so file-level allow globs such as .github/workflows/*.yml keep the containing default-excluded directories enumerable.

Method

MatchFileInDirectoryOrDescendant

string? MatchFileInDirectoryOrDescendant(string relativeDirectory)

Returns the first pattern that could match a file directly inside relativeDirectory or below one of its descendants.

Remarks

Unlike MatchDirectoryOrDescendant , this helper is allowed to rule out nested directories when the remaining glob pattern can only match a file in the current directory, such as src/public*.js . Harvesters use it to avoid walking subtrees that cannot contribute matching files.

Property

HasPatterns

bool HasPatterns { get; } Source

Gets a value indicating whether any patterns were configured.

Type

PatternMatcher

Source

Wraps a single configured glob pattern and exposes case-insensitive match helpers.

Method

Matches

bool Matches(string relativePath)

Returns whether relativePath matches Pattern .

Method

MatchesDirectoryOrDescendant

bool MatchesDirectoryOrDescendant(string relativeDirectory)

Returns whether Pattern can apply to the directory or any descendant path.

Method

CouldMatchDirectoryOrDescendant

bool CouldMatchDirectoryOrDescendant(string relativeDirectory)

Returns whether Pattern could match any file under relativeDirectory .

Method

CouldMatchFileInDirectoryOrDescendant

bool CouldMatchFileInDirectoryOrDescendant(string relativeDirectory)

Returns whether Pattern could match a file under relativeDirectory .

Property

Pattern

string Pattern { get; } Source

Gets the original configured pattern.

Type

DocsUrlBuilder

Source

Builds canonical AppSurface Docs URLs for one AppSurface Docs route family.

Remarks

This builder centralizes the route contract so controllers, view components, views, and client scripts do not each guess how the docs surface is rooted. RouteRootPath is the stable route-family root used for archive and exact-version routes. CurrentDocsRootPath is the live source-backed docs root used for current docs, search, and current search-index routes. Most consumers should copy Routes rather than assembling route strings or calling lower-level builder methods directly.

Method

BuildHomeUrl

string BuildHomeUrl()

Builds the current live docs home URL.

Returns

The current docs home path.

Method

BuildSearchUrl

string BuildSearchUrl()

Builds the current live docs search workspace URL.

Returns

The app-relative search workspace URL for the current docs surface.

Method

BuildSearchIndexUrl

string BuildSearchIndexUrl()

Builds the current live docs search-index URL.

Returns

The app-relative search-index URL for the current docs surface.

Method

BuildSearchIndexRefreshUrl

string BuildSearchIndexRefreshUrl()

Builds the current live docs search-index refresh URL.

Returns

The app-relative operator refresh route for the current docs search index. Callers must send SearchIndexRefreshMethod with a valid MVC anti-forgery token and satisfy the host-configured AppSurface Docs search-index refresh policy.

Method

BuildHarvestUrl

string BuildHarvestUrl()

Builds the current live docs harvest observatory URL.

Returns

The app-relative operator harvest observatory URL for the current docs surface.

Method

BuildHarvestRebuildUrl

string BuildHarvestRebuildUrl()

Builds the current live docs harvest rebuild URL.

Returns

The app-relative operator rebuild route for the current docs harvest. Callers must send HarvestRebuildMethod with a valid MVC anti-forgery token and satisfy the host-configured AppSurface Docs operator-write policy.

Method

BuildHealthUrl

string BuildHealthUrl()

Builds the current live docs harvest health HTML URL.

Returns

The app-relative health page URL for the current docs surface.

Method

BuildHealthJsonUrl

string BuildHealthJsonUrl()

Builds the current live docs harvest health JSON URL.

Returns

The app-relative machine-readable health URL for the current docs surface.

Method

BuildRouteInspectorUrl

string BuildRouteInspectorUrl()

Builds the current live docs route inspector HTML URL.

Returns

The app-relative route inspector URL for the current docs surface.

Method

BuildRouteInspectorJsonUrl

string BuildRouteInspectorJsonUrl()

Builds the current live docs route inspector JSON URL.

Returns

The app-relative machine-readable route inspector URL for the current docs surface.

Method

BuildMetricsCollectUrl

string BuildMetricsCollectUrl()

Builds the current live docs metrics collection URL.

Returns

The app-relative browser metrics ingestion URL for the current docs surface.

Method

BuildSearchQualityUrl

string BuildSearchQualityUrl()

Builds the current live docs search-quality diagnostics URL.

Returns

The app-relative search-quality diagnostics URL for the current docs surface.

Method

BuildSectionUrl

string BuildSectionUrl(DocPublicSection section)

Builds a current-surface public section URL.

Parameters

  • section
    The section whose route should be built.

Returns

The canonical section URL rooted at the current docs surface.

Method

BuildDocUrl

2 overloads
string BuildDocUrl(string path)

Builds a current-surface canonical document URL.

Parameters

  • path
    The source or canonical documentation path.

Returns

The canonical document URL rooted at the current docs surface.

string BuildDocUrl(string docsRootPath, string path)

Builds a canonical document URL rooted at an explicit docs surface root.

Parameters

  • docsRootPath
    The app-relative docs root path.
  • path
    The source or canonical documentation path.

Returns

The canonical document URL.

Method

BuildMarkdownDownloadUrl

string BuildMarkdownDownloadUrl(string path)

Builds the protected Markdown attachment route for one canonical non-root Docs path.

Parameters

  • path
    The canonical Docs-relative path returned by the route identity catalog.

Returns

An app-relative, segment-encoded Markdown download URL.

Remarks

This method intentionally accepts only a clean canonical route path. It rejects aliases, source-shaped paths, traversal segments, separators that would change route identity, and the docs home so link rendering cannot create an address that the protected download endpoint will later reject.

Method

BuildAssetUrl

string BuildAssetUrl(string assetName)

Builds the current-surface search asset URL.

Parameters

  • assetName
    The asset file name, such as search.css .

Returns

The canonical asset URL rooted at the current docs surface.

Method

BuildVersionRootUrl

string BuildVersionRootUrl(string version)

Builds the exact-version root URL for one published docs release.

Parameters

  • version
    The exact published version identifier.

Returns

The canonical root URL for that version.

Method

BuildVersionDocUrl

string BuildVersionDocUrl(string version, string path)

Builds a canonical document URL rooted at a specific exact version.

Parameters

  • version
    The exact published version identifier.
  • path
    The source or canonical documentation path.

Returns

The canonical document URL rooted at the requested version.

Method

BuildAliasRootUrl

string BuildAliasRootUrl(string name)

Builds the root URL for one named exact-version alias.

Parameters

  • name
    The alias label, normalized using the catalog's shared ASCII route-name grammar.

Returns

The alias root under this route family, such as /docs/a/stable .

Exceptions

  • ArgumentNullException
    The alias name is null .
  • ArgumentException
    The alias name is not a valid 1–64 character route label.

Remarks

This method creates a URL only; it does not establish that a matching public alias is configured or available. Alias names are lowercased invariantly and allow ASCII letters and digits at their edges, with dot, underscore, and hyphen also allowed internally. Slashes, percent escapes, whitespace, and dot segments are rejected.

Method

BuildAliasDocUrl

string BuildAliasDocUrl(string name, string path)

Builds an alias-local document URL.

Parameters

  • name
    The alias label validated by BuildAliasRootUrl(string) .
  • path
    The document path and optional fragment.

Returns

The document URL rooted at the normalized alias route.

Exceptions

  • ArgumentNullException
    The alias name is null .
  • ArgumentException
    The alias name is invalid.

Remarks

Path encoding follows BuildVersionDocUrl(string, string) .

Method

BuildCanonicalHref

string BuildCanonicalHref(string appRelativeCanonicalUrl)

Builds the browser-facing canonical href for an app-relative canonical route.

Parameters

  • appRelativeCanonicalUrl
    The app-relative canonical route, such as /docs/start .

Returns

The app-relative canonical route when no public origin is configured, or an absolute public canonical URL when PublicOrigin is set.

Remarks

AppSurface Docs keeps route identity app-relative until the final render boundary. This method is that boundary for canonical metadata: it joins the configured origin with the already-selected canonical path without changing current, preview, archive, or exact-version route semantics.

Method

BuildVersionsUrl

string BuildVersionsUrl()

Builds the public archive URL.

Returns

The stable archive URL.

Method

IsCurrentDocsPath

bool IsCurrentDocsPath(string? path)

Determines whether the supplied request path is inside the current live docs surface.

Parameters

  • path
    The request path to check.

Returns

true when the path belongs to the current live docs surface; otherwise false .

Method

NormalizePublicOriginOrNull

string? NormalizePublicOriginOrNull(string? publicOrigin)

Normalizes a configured public origin for absolute canonical metadata.

Parameters

  • publicOrigin
    The configured origin, which may be null or already normalized.

Returns

The normalized origin, or null when the value is blank.

Exceptions

  • ArgumentException
    Thrown when the configured value is not an origin-only HTTP(S) URL.
Method

TryNormalizePublicOrigin

bool TryNormalizePublicOrigin(string? publicOrigin, out string? normalizedPublicOrigin)

Attempts to normalize a configured public origin for absolute canonical metadata.

Parameters

  • publicOrigin
    The configured origin, which may be null or already normalized.
  • normalizedPublicOrigin
    The normalized origin, or null when the value is blank.

Returns

true when the value is blank or a valid HTTP(S) origin; otherwise false .

Method

IsUnderRoot

bool IsUnderRoot(string? path, string docsRootPath)

Determines whether a request path belongs to the supplied docs root.

Parameters

  • path
    The incoming request path to evaluate.
  • docsRootPath
    The normalized docs root path configured for the live docs surface.

Returns

true when path resolves to the docs root itself or one of its child routes; otherwise false .

Remarks

Blank paths always return false . Root-mounted docs ( / ) use IsLikelyRootMountedDocsPath(string) so only known docs-like routes are treated as current docs traffic. Non-root mounts use case-insensitive exact and prefix matching against {docsRootPath}/... .

Method

JoinPath

string JoinPath(string docsRootPath, string relativePath)

Joins a normalized docs root with a relative docs route segment.

Parameters

  • docsRootPath
    The normalized app-relative docs root path.
  • relativePath
    The relative docs route to append.

Returns

The combined app-relative route path.

Remarks

Leading slashes on relativePath are ignored. null , empty, and whitespace-only relative paths return the docs root unchanged. When the docs root is / , the result stays root-mounted instead of producing a doubled slash. Callers are expected to pass already-normalized root paths and docs-relative segments rather than arbitrary URLs.

Method

NormalizeDocsRootPath

string NormalizeDocsRootPath(string? docsRootPath, bool versioningEnabled)

Normalizes a configured docs root into the app-relative route contract AppSurface Docs uses at runtime.

Parameters

  • docsRootPath
    The configured docs root, which may be null, relative-looking, or already normalized.
  • versioningEnabled
    Whether versioning is enabled and the default should therefore become /docs/next .

Returns

The normalized app-relative docs root path.

Method

NormalizeRouteRootPath

string NormalizeRouteRootPath(string? routeRootPath, string docsRootPath, bool versioningEnabled)

Normalizes a configured route-family root into the app-relative route contract AppSurface Docs uses at runtime.

Parameters

  • routeRootPath
    The configured route root, which may be null, relative-looking, or already normalized.
  • docsRootPath
    The normalized live docs root used when versioning is disabled and no route root is configured.
  • versioningEnabled
    Whether versioning is enabled and the default route family should remain /docs .

Returns

The normalized app-relative route-family root path.

Property

VersioningEnabled

bool VersioningEnabled { get; } Source

Gets a value indicating whether versioning is enabled for the current host.

Property

CurrentDocsRootPath

string CurrentDocsRootPath { get; } Source

Gets the canonical root path for the current live source-backed docs surface.

Property

RouteRootPath

string RouteRootPath { get; } Source

Gets the stable route-family root for this AppSurface Docs instance.

Remarks

The route root is the parent for the stable entry alias, version archive, and exact-version release trees. It is the same as CurrentDocsRootPath when versioning is disabled, and commonly the parent of the live preview root when versioning is enabled. For example, RouteRootPath=/foo/bar with DocsRootPath=/foo/bar/next keeps the archive at /foo/bar/versions while the live preview stays at /foo/bar/next .

Property

DocsEntryRootPath

string DocsEntryRootPath { get; } Source

Gets the docs entry path used as the stable public landing alias.

Property

DocsVersionPrefixPath

string DocsVersionPrefixPath { get; } Source

Gets the stable exact-version prefix for this route family.

Property

DocsVersionsRootPath

string DocsVersionsRootPath { get; } Source

Gets the stable archive path for this route family.

Property

Routes

AppSurfaceDocsRouteReferences Routes { get; } Source

Gets named AppSurface Docs routes that consumers should prefer over hardcoded route strings.

Property

PublicOrigin

string? PublicOrigin { get; } Source

Gets the configured public origin used for absolute canonical metadata, or null when unset.

Remarks

This value is an origin only, for example https://docs.example.com . It never includes the AppSurface Docs route root because canonical route identity is still owned by BuildDocUrl(string) , BuildVersionDocUrl(string, string) , and the route manifest.

Type

AppSurfaceDocsRouteReferences

Source

Named AppSurface Docs routes for one configured route family.

Remarks

Consumers should prefer this record when they need well-known AppSurface Docs destinations in host code, operator guidance, generated configuration, or documentation. The values are app-relative. Views and other presentation boundaries apply request PathBase separately before sending browser-facing URLs.

Method

Deconstruct

4 overloads
void Deconstruct(out string home, out string search, out string searchIndex, out string searchIndexRefresh, out string versions)

Deconstructs the original route set for callers that used the positional record contract.

Parameters

  • home
    The current live docs home route.
  • search
    The current live docs search workspace route.
  • searchIndex
    The current live docs search-index JSON route.
  • searchIndexRefresh
    The authenticated search-index refresh route.
  • versions
    The route-family archive route.
void Deconstruct(out string home, out string search, out string searchIndex, out string searchIndexRefresh, out string versions, out string health, out string healthJson)

Deconstructs the route set through harvest health diagnostics.

Parameters

  • home
    The current live docs home route.
  • search
    The current live docs search workspace route.
  • searchIndex
    The current live docs search-index JSON route.
  • searchIndexRefresh
    The authenticated search-index refresh route.
  • versions
    The route-family archive route.
  • health
    The current live docs harvest health HTML route.
  • healthJson
    The current live docs harvest health JSON route.
void Deconstruct(out string home, out string search, out string searchIndex, out string searchIndexRefresh, out string versions, out string health, out string healthJson, out string routeInspector, out string routeInspectorJson)

Deconstructs all known routes including diagnostics routes.

Parameters

  • home
    The current live docs home route.
  • search
    The current live docs search workspace route.
  • searchIndex
    The current live docs search-index JSON route.
  • searchIndexRefresh
    The authenticated search-index refresh route.
  • versions
    The route-family archive route.
  • health
    The current live docs harvest health HTML route.
  • healthJson
    The current live docs harvest health JSON route.
  • routeInspector
    The current live docs route inspector HTML route.
  • routeInspectorJson
    The current live docs route inspector JSON route.
void Deconstruct(out string home, out string search, out string searchIndex, out string searchIndexRefresh, out string versions, out string harvest, out string harvestRebuild, out string health, out string healthJson, out string routeInspector, out string routeInspectorJson)

Deconstructs all known routes including harvest rebuild and diagnostics routes.

Parameters

  • home
    The current live docs home route.
  • search
    The current live docs search workspace route.
  • searchIndex
    The current live docs search-index JSON route.
  • searchIndexRefresh
    The authenticated search-index refresh route.
  • versions
    The route-family archive route.
  • harvest
    The current live docs harvest observatory route.
  • harvestRebuild
    The authenticated harvest rebuild route.
  • health
    The current live docs harvest health HTML route.
  • healthJson
    The current live docs harvest health JSON route.
  • routeInspector
    The current live docs route inspector HTML route.
  • routeInspectorJson
    The current live docs route inspector JSON route.
Property

Home

string Home { get; init; } Source

Gets the current live docs home route.

Property

Search

string Search { get; init; } Source

Gets the current live docs search workspace route.

Property

SearchIndex

string SearchIndex { get; init; } Source

Gets the current live docs search-index JSON route.

Property

SearchIndexRefresh

string SearchIndexRefresh { get; init; } Source

Gets the authenticated search-index refresh route.

Property

SearchIndexRefreshMethod

string SearchIndexRefreshMethod { get; init; } Source

Gets the HTTP method callers must use with SearchIndexRefresh .

Property

Harvest

string Harvest { get; init; } Source

Gets the current live docs harvest observatory route.

Property

HarvestRebuild

string HarvestRebuild { get; init; } Source

Gets the authenticated harvest rebuild route.

Property

HarvestRebuildMethod

string HarvestRebuildMethod { get; init; } Source

Gets the HTTP method callers must use with HarvestRebuild .

Property

Versions

string Versions { get; init; } Source

Gets the route-family archive route, whether or not versioning endpoints are currently enabled.

Property

Health

string Health { get; init; } Source

Gets the current live docs harvest health HTML route.

Property

HealthJson

string HealthJson { get; init; } Source

Gets the current live docs harvest health JSON route.

Property

RouteInspector

string RouteInspector { get; init; } Source

Gets the current live docs route inspector HTML route.

Property

RouteInspectorJson

string RouteInspectorJson { get; init; } Source

Gets the current live docs route inspector JSON route.

Property

MetricsCollect

string MetricsCollect { get; init; } Source

Gets the current live docs metrics collection route.

Property

SearchQuality

string SearchQuality { get; init; } Source

Gets the current live docs search-quality diagnostics route.

Type

AppSurfaceDocsHighlightedCode

Source

Contains AppSurface Docs-owned HTML for a rendered Markdown code block.

Parameters

  • Html
    The complete sanitized-shape HTML fragment for the code block.
  • NormalizedLanguage
    The normalized language identifier used by AppSurface Docs.
  • IsHighlighted
    Whether token spans were emitted for the code body.
Type

AppSurfaceDocsCodeLanguage

Source

Describes AppSurface Docs' normalized view of an authored code-fence language token.

Parameters

  • NormalizedLanguage
    The stable AppSurface Docs language name.
  • ClassLanguage
    The safe suffix used by the conventional language-* class.
  • Label
    The reader-facing language label.
  • TextMateLanguageId
    The TextMateSharp language id, or null for plaintext fallback.
  • IsKnown
    Whether the authored token is part of AppSurface Docs' recognized language catalog.
  • IsPlainText
    Whether the language should render as escaped plaintext.
Type

AppSurfaceDocsRouteManifest

Source

Publishes the public route identity graph for one AppSurface Docs snapshot.

Remarks

The manifest is an internal read model, not a second router. It contains only public canonical winners plus redirect aliases that should recover to those winners. Collision losers, reserved routes, and invalid routes stay represented by diagnostics so export and future consumers do not guess a destination for ambiguous paths.

Type

AppSurfaceDocsRouteManifestEntry

Source

Describes one public AppSurface Docs page and the aliases that should redirect to it.

Parameters

  • SourcePath
    Harvested repository-relative source path for the canonical winner.
  • CanonicalRoutePath
    Docs-root-relative canonical route path.
  • CanonicalLiveUrl
    App-relative live URL for the canonical route.
  • RecoveryAliases
    Implicit source-shaped Markdown aliases for paste recovery.
  • DeclaredAliases
    Author-declared redirect aliases from metadata.
  • SourcePathIsMarkdown
    Whether SourcePath is a Markdown document.
Type

AppSurfaceDocsRouteAlias

Source

Describes one route alias that redirects to a canonical AppSurface Docs page.

Parameters

  • RoutePath
    Docs-root-relative alias route path.
  • LiveUrl
    App-relative live URL for the alias.
  • Kind
    The alias source category.
Type

DocOutlinePolicy

Source

Applies Markdown display-outline rules after metadata defaults and author overrides have been resolved.

Method

Apply

IReadOnlyList<DocOutlineItem> Apply(IReadOnlyList<DocOutlineItem> outline, DocMetadata? metadata)

Applies explicit outline metadata and automatic repeated-heading suppression to a harvested Markdown outline.

Parameters

  • outline
    The source-ordered harvested Markdown outline entries.
  • metadata
    The resolved document metadata, including derived defaults.

Returns

The outline entries to expose to readers and search heading metadata.

Remarks

This method filters the display outline only. The rendered Markdown HTML remains unchanged, so fragment links to hidden outline headings can still resolve when readers or search results point directly at the heading.

Type

CSharpDocHarvester

Source

Harvester implementation that scans C# source files for XML documentation comments.

Method

HarvestAsync

2 overloads
Task<IReadOnlyList<DocNode>> HarvestAsync(string rootPath, CancellationToken cancellationToken = default)

Collects XML documentation from C# source files under the specified root and produces DocNode entries containing titles, relative file paths with anchors, and HTML-formatted content.

Parameters

  • rootPath
    The root directory to recursively scan for .cs files.
  • cancellationToken
    An optional token to observe for cancellation requests.

Returns

A collection of DocNode objects; each contains a title, a relative file path including a fragment anchor, and the extracted HTML documentation.

Remarks

Skips files in excluded directories (for example "node_modules", "bin", "obj", "Tests", and "examples") and hidden dot-prefixed directories unless explicitly allowlisted. Dot-prefixed files are included. File and directory reparse points are skipped so symlinks and junctions cannot point the built-in harvester outside rootPath .

Task<IReadOnlyList<DocNode>> HarvestAsync(DocHarvestContext context, CancellationToken cancellationToken = default)

Collects XML documentation with the repository-scoped path policy captured for the current aggregation pass.

Parameters

  • context
    The harvest context containing the repository root and active path policy snapshot.
  • cancellationToken
    An optional token to observe for cancellation requests.

Returns

A collection of generated C# API documentation nodes.

Remarks

This overload is used by the aggregator so VCS ignore exclusions are applied consistently across traversal and file inclusion checks. Custom harvesters continue to use the public HarvestAsync(string, CancellationToken) contract.

Method

HarvestTypedAsync

Task<IReadOnlyList<DocNode>> HarvestTypedAsync(string rootPath, IHarvestPathPolicy pathPolicy, AppSurfaceDocsHarvestProgressSession? progress, CancellationToken cancellationToken)

Harvests built-in C# namespace pages into the internal semantic projection consumed by Razor.

Remarks

This is intentionally reachable only through the exact built-in aggregation overload. The public overload above continues to call the legacy HTML compatibility serializer so existing IDocHarvester consumers and derived harvesters retain their established contract.

Method

GetMethodId

string GetMethodId(MethodDeclarationSyntax method, string qualifiedTypeName)

Computes the safe ID for a method to be used in HTML content and stub nodes.

Parameters

  • method
    The method declaration syntax.
  • qualifiedTypeName
    The qualified name of the containing type.

Returns

The safe ID string for the method documentation section.

Method

GetPropertyId

string GetPropertyId(PropertyDeclarationSyntax property, string qualifiedTypeName)

Computes the safe ID for a property to be used in HTML content and stub nodes.

Parameters

  • property
    The property declaration syntax.
  • qualifiedTypeName
    The qualified name of the containing type.

Returns

The safe ID string for the property documentation section.

Method

GetHighlightedDisplaySignature

string GetHighlightedDisplaySignature(MethodDeclarationSyntax method)

Generates a syntax-highlighted HTML string representing a method signature for display.

Parameters

  • method
    The method declaration syntax.

Returns

An HTML fragment containing the highlighted signature.

Method

GetHighlightedPropertySignature

string GetHighlightedPropertySignature(PropertyDeclarationSyntax property)

Generates a syntax-highlighted HTML string representing a property signature for display.

Parameters

  • property
    The property declaration syntax.

Returns

An HTML fragment containing the highlighted signature.

Method

GetPropertyAccessorSignature

string GetPropertyAccessorSignature(PropertyDeclarationSyntax property)

Computes the accessors (get/set/init) for a property as a string for inclusion in signatures.

Parameters

  • property
    The property declaration syntax.

Returns

A string like "{ get; set; }" or "{ get; }".

Method

AppendHighlightedParameter

void AppendHighlightedParameter(StringBuilder builder, ParameterSyntax parameter)

Appends a syntax-highlighted parameter declaration to the provided StringBuilder.

Parameters

  • builder
    The StringBuilder to append to.
  • parameter
    The parameter declaration syntax.
Method

GetDisplayTypeName

string GetDisplayTypeName(TypeDeclarationSyntax typeDecl)

Gets the display name for a type declaration, including generic type parameter placeholders (e.g., <T>).

Parameters

  • typeDecl
    The type declaration syntax.

Returns

The display name string.

Method

GetTypeNameForQualifiedId

string GetTypeNameForQualifiedId(TypeDeclarationSyntax typeDecl)

Gets the type name for a qualified ID, appending backtick arity for generic types (e.g., MyType`1).

Parameters

  • typeDecl
    The type declaration syntax.

Returns

The type name string used in safe IDs.

Method

IsCompilerGeneratedCallerParameter

bool IsCompilerGeneratedCallerParameter(ParameterSyntax parameter)

Determines whether a parameter is a compiler-generated caller information parameter (for example, [CallerFilePath]).

Parameters

  • parameter
    The parameter declaration syntax.

Returns

true if the parameter should be hidden from documentation; otherwise, false .

Method

ExtractDoc

string? ExtractDoc(SyntaxNode node, string relativePath, ICollection<DocHarvestDiagnostic> diagnostics)

Extracts XML documentation from the leading trivia of a syntax node and converts it into HTML fragments.

Parameters

  • node
    The syntax node whose leading XML documentation comments will be parsed.
  • relativePath
    The repository-relative path used by structured documentation diagnostics.
  • diagnostics
    The harvest diagnostics that receive local XML depth-limit warnings.

Returns

The HTML string containing structured documentation sections, or null if no documentation is present or parsing fails.

Method

AppendTextSection

void AppendTextSection(StringBuilder html, string cssClass, XElement? section, string? heading = null)

Appends a simple text section (like summary or remarks) to the HTML builder.

Parameters

  • html
    The StringBuilder to append to.
  • cssClass
    The CSS class name for the section container.
  • section
    The XElement containing the documentation section.
  • heading
    Optional heading text for the section.
Method

AppendNamedListSection

void AppendNamedListSection(StringBuilder html, string cssClass, string heading, IEnumerable<XElement> entries, Func<XElement, string?> keySelector)

Appends a list of named entries (like parameters or exceptions) to the HTML builder.

Parameters

  • html
    The StringBuilder to append to.
  • cssClass
    The CSS class name for the section container.
  • heading
    The heading text for the section.
  • entries
    The collection of XElements to process.
  • keySelector
    A function that extracts the name or key for each entry.
Method

RenderBlockContent

string RenderBlockContent(XElement element)

Renders the content of an XElement as block-level HTML (wrapping in paragraphs if necessary).

Parameters

  • element
    The XElement to render.

Returns

An HTML fragment string.

Method

RenderInlineContent

string RenderInlineContent(XElement element)

Renders the content of an XElement as inline HTML.

Parameters

  • element
    The XElement to render.

Returns

An HTML fragment string.

Method

RenderNodes

string RenderNodes(IEnumerable<XNode> nodes, bool inlineContext)

Renders a collection of XML nodes into HTML strings.

Parameters

  • nodes
    The nodes to render.
  • inlineContext
    Indicates whether rendering occurs in an inline context (affects paragraph handling).

Returns

The combined HTML string.

Method

RenderNode

string RenderNode(XNode node, bool inlineContext)

Renders a single XML node into its corresponding HTML fragment.

Parameters

  • node
    The node to render.
  • inlineContext
    Indicates whether rendering occurs in an inline context.

Returns

The HTML fragment string.

Method

NormalizeWhitespace

string NormalizeWhitespace(string value)

Normalizes whitespace in the provided string by replacing all whitespace sequences with a single space.

Parameters

  • value
    The string to normalize.

Returns

The normalized string.

Method

AddOutlineItem

void AddOutlineItem(NamespaceDocPage namespacePage, string title, string id, int level)

Adds an outline item to a namespace page when the entry is complete and its target ID has not already been recorded.

Parameters

  • namespacePage
    The namespace page receiving the outline item.
  • title
    The reader-facing outline title.
  • id
    The fragment identifier for the rendered documentation section.
  • level
    The normalized outline level.
Method

SimplifyCref

string? SimplifyCref(string? cref)

Simplifies a "cref" attribute value by removing the type prefix (e.g., "M:", "T:").

Parameters

  • cref
    The cref value to simplify.

Returns

The simplified string, or null if the input was empty.

Method

GetOrCreateNamespacePage

NamespaceDocPage GetOrCreateNamespacePage(IDictionary<string, NamespaceDocPage> namespacePages, string namespaceName)

Gets an existing NamespaceDocPage for the specified namespace name, or creates a new one if it doesn't exist.

Parameters

  • namespacePages
    The dictionary of existing pages.
  • namespaceName
    The dotted namespace name.

Returns

The retrieved or newly created page.

Method

EnsureNamespaceHierarchy

void EnsureNamespaceHierarchy(IDictionary<string, NamespaceDocPage> namespacePages)

Builds the hierarchical structure for namespaces, ensuring parent pages exist and child links are added back into the content. Rebuilds namespacePages in place keyed by NamespaceDocPage.Path .

Parameters

  • namespacePages
    The dictionary containing all unique namespace pages encountered during harvesting.
Method

GetNamespaceName

string GetNamespaceName(SyntaxNode node)

Extracts the dotted namespace name for a given syntax node by traversing its ancestors.

Parameters

  • node
    The syntax node to process.

Returns

The full dotted namespace name, or "Global" if none is found.

Method

BuildNamespaceDocPath

string BuildNamespaceDocPath(string namespaceName)

Constructs the relative documentation route path for a given namespace name.

Parameters

  • namespaceName
    The dotted namespace name.

Returns

The relative route path string (e.g., "Namespaces/MyNamespace").

Method

GetNamespaceTitle

string GetNamespaceTitle(string fullNamespace)

Derives a display title for a namespace name.

Parameters

  • fullNamespace
    The dotted namespace name.

Returns

The display title; returns the last segment of the namespace or "Namespaces" for the root.

Method

GetParentNamespace

string GetParentNamespace(string namespaceName)

Gets the parent namespace name for a dotted namespace string.

Parameters

  • namespaceName
    The dotted namespace name.

Returns

The parent namespace name, or an empty string if it is a root namespace.

Method

GetQualifiedName

string GetQualifiedName(BaseTypeDeclarationSyntax node)

Builds the dot-delimited qualified name for a type or enum declaration, including enclosing types and namespaces.

Parameters

  • node
    The type or enum declaration syntax node to compute the qualified name for.

Returns

The qualified name as a dot-delimited string containing nested type and namespace segments.

Type

NamespaceDocPage

Source

Represents a single documentation page for a C# namespace, accumulating content from types within it.

Type

AppSurfaceDocsHarvestStreamAuthorizer

Source

Authorizes the AppSurface Docs harvest progress stream with result-bearing RazorWire authorization semantics.

Remarks

Use this wrapper when AppSurface Docs owns the harvest-progress channel but must preserve host RazorWire authorization for other channels. The harvest decision order is: harvest route visibility, configured shared diagnostics read policy, optional custom host authorizer narrowing, Development fallback, compatibility custom authorizers, then deny. Built-in RazorWire allow-all and deny-all authorizers are compatibility defaults and do not authorize the Docs harvest stream in non-Development hosts.

Method

AuthorizeAsync

ValueTask<AppSurfaceAuthResult> AuthorizeAsync(RazorWireStreamAuthorizationContext context)

Authorizes the requested Docs or host stream channel.

Parameters

  • context
    The RazorWire stream authorization context.

Returns

A passive AppSurface auth result for the stream subscription.

Type

DocMetadataFactory

Source

Builds normalized AppSurface Docs metadata defaults and fallbacks for harvested documentation nodes.

Method

CreateMarkdownMetadata

2 overloads
DocMetadata CreateMarkdownMetadata(string path, string resolvedTitle, DocMetadata? explicitMetadata, string? derivedSummary)

Creates normalized metadata for a Markdown documentation node without emitting normalization warnings.

Parameters

  • path
    The source path used for default section, page-type, and audience inference.
  • resolvedTitle
    The resolved display title for the Markdown node.
  • explicitMetadata
    Optional authored metadata that should override inferred defaults.
  • derivedSummary
    Optional summary text derived from the document body.

Returns

The merged metadata with inferred defaults, normalized nav-group handling, and fallback breadcrumbs.

DocMetadata CreateMarkdownMetadata(string path, string resolvedTitle, DocMetadata? explicitMetadata, string? derivedSummary, ILogger? logger)

Creates normalized metadata for a Markdown documentation node and optionally logs authored nav-group fallback warnings.

Parameters

  • path
    The source path used for default section, page-type, and audience inference.
  • resolvedTitle
    The resolved display title for the Markdown node.
  • explicitMetadata
    Optional authored metadata that should override inferred defaults.
  • derivedSummary
    Optional summary text derived from the document body.
  • logger
    An optional logger that receives warnings when authored nav_group values do not resolve to a built-in public section and AppSurface Docs falls back to the derived section assignment.

Returns

The merged metadata with normalized section labels, fallback breadcrumbs, and derived-field flags.

Remarks

This shared internal entry point normalizes explicit public-section selection, preserves authored metadata where valid, derives title/summary fallback semantics, and rebuilds default breadcrumbs when authors do not supply them explicitly.

Method

CreateApiReferenceMetadata

DocMetadata CreateApiReferenceMetadata(string title, string namespaceName)

Creates canonical metadata for an API-reference documentation node.

Parameters

  • title
    The display title for the API node.
  • namespaceName
    The owning namespace used for component inference and breadcrumb generation.

Returns

Metadata configured for API-reference navigation, contributor visibility, and namespace breadcrumbs.

Method

DeriveComponentFromPath

string? DeriveComponentFromPath(string path)

Derives the owning AppSurface component name from a documentation path when possible.

Parameters

  • path
    The documentation path whose segments should be inspected.

Returns

The inferred component name, or null when no component hint can be derived.

Method

DeriveComponentFromNamespace

string? DeriveComponentFromNamespace(string namespaceName)

Derives the owning AppSurface component name from a namespace.

Parameters

  • namespaceName
    The namespace to inspect.

Returns

The inferred component name, or null when the namespace is blank.

Type

AppSurfaceDocsFrozenRouteManifest

Source

Loads, validates, and writes the frozen route manifest stored inside exported exact-version docs trees.

Remarks

Frozen manifests are archive-local read models. They preserve the route identity that existed when an exact release tree was exported, but they do not replace DocRouteIdentityCatalog for live source-backed docs. New exports also bind every logical canonical identity to an ordinary HTML artifact beneath the complete export root and declare htmlUrlBase: export-root . Legacy v1 documents without these optional fields retain logical redirects and docs-relative HTML rewriting. Partial mappings, unsafe paths, unfinished exporter staging, and route namespace collisions disable the entire new manifest; verified archive loading rejects them before activation.

Method

WriteAsync

Task WriteAsync(string outputPath, AppSurfaceDocsRouteManifest routeManifest, CancellationToken cancellationToken)

Writes the frozen route manifest artifact to an export output directory.

Parameters

  • outputPath
    Export output root that represents one exact-version tree.
  • routeManifest
    Live route manifest captured from the source-backed docs snapshot.
  • cancellationToken
    Token observed while writing the artifact.

Returns

A task that completes once the manifest has been written.

Method

Serialize

string Serialize(AppSurfaceDocsRouteManifest routeManifest)

Serializes a frozen route manifest document only after strict validation succeeds.

Parameters

  • routeManifest
    Live route manifest captured from the source-backed docs snapshot.

Returns

The exact JSON payload used for the frozen route manifest artifact.

Exceptions

  • ArgumentNullException
    routeManifest is null .
  • InvalidOperationException
    The route manifest contains unsafe, duplicate, colliding, or ambiguous canonical routes or aliases.

Remarks

This writer-facing API validates with the same strict rules used for exact archive pins. It throws instead of dropping unsafe entries when a canonical route is missing or unsafe, when aliases are unsafe, self-referential, or collide with canonical routes, or when duplicate aliases point at different canonical routes. Use it when creating a new frozen manifest from trusted source-backed route metadata. Use the tolerant loading paths when reading an existing archive where an invalid manifest should degrade to an empty alias map instead of failing the caller.

Method

SerializeForExport

string SerializeForExport(AppSurfaceDocsRouteManifest routeManifest)

Stages live canonical URLs for exporter finalization before release-manifest hashing.

Parameters

  • routeManifest
    The source-backed snapshot whose canonical pages the exporter seeds.

Returns

Strictly validated route JSON containing private exportCanonicalLiveUrl members.

Remarks

This is an exporter handoff, not a consumable archive. The exporter must replace every staging member with the successful ordinary HTML outcome's whole-root canonicalArtifactPath and add htmlUrlBase: export-root before integrity hashing. Final archive loading rejects leftover staging data. Use Serialize for legacy logical-route fixtures that do not undergo this finalization.

Method

BuildManifestPath

string BuildManifestPath(string outputPath, string fileName)

Builds the on-disk path for a frozen route manifest filename beneath an exact-version export root.

Parameters

  • outputPath
    Export output root that represents one exact-version tree.
  • fileName
    Manifest filename to place beneath outputPath .

Returns

The manifest path under the export output root.

Method

Load

AppSurfaceDocsFrozenRouteManifest Load(IFileProvider fileProvider, ILogger logger, string sourceDescription)

Loads a frozen manifest from a mounted exact-version tree provider.

Parameters

  • fileProvider
    File provider rooted at the exact-version tree.
  • logger
    Logger used for malformed-manifest diagnostics.
  • sourceDescription
    Human-readable tree identity for logs.

Returns

The parsed manifest, or Empty when the manifest is missing or unusable.

Method

TryLoadVerified

bool TryLoadVerified(byte[] utf8Bytes, out AppSurfaceDocsFrozenRouteManifest manifest, out string issue)

Parses verified frozen route manifest bytes that have already matched a catalog-pinned release archive manifest.

Parameters

  • utf8Bytes
    The exact UTF-8 bytes covered by the verified release archive manifest.
  • manifest
    The immutable route manifest when parsing succeeds.
  • issue
    A human-readable parse or validation issue when parsing fails.

Returns

true when the verified bytes describe a supported frozen route manifest.

Method

TryResolveAlias

bool TryResolveAlias(string aliasRoutePath, out string canonicalRoutePath)

Attempts to resolve a docs-root-relative alias route to its frozen canonical route path.

Parameters

  • aliasRoutePath
    Docs-root-relative request path.
  • canonicalRoutePath
    Frozen canonical route path when an alias matches.

Returns

true when the alias is known by the frozen manifest; otherwise false .

Method

TryResolveCanonicalArtifactPath

bool TryResolveCanonicalArtifactPath(string canonicalRoutePath, out string artifactPath)

Resolves a logical canonical identity to its finalized archive HTML member and canonical fragment.

Parameters

  • canonicalRoutePath
    The logical identity, including the empty docs-root identity.
  • artifactPath
    Whole-export-root relative HTML member, with the frozen canonical fragment.

Returns

Whether this archive supplies a finalized mapping for the identity.

Method

IsSafeRoutePath

bool IsSafeRoutePath(string? routePath)

Checks whether a docs-root-relative route path is safe to use as a frozen alias or redirect target.

Parameters

  • routePath
    The docs-root-relative route path, optionally including a canonical fragment.

Returns

true when the route stays inside the docs archive namespace; otherwise false .

Method

CreateSnapshot

AppSurfaceDocsFrozenRouteManifest CreateSnapshot(FrozenRouteManifestDocument document, IReadOnlyDictionary<string, string> aliases, IReadOnlyDictionary<string, string> artifacts, bool htmlUsesExportRootUrls)

Keeps complete route identities even for a valid manifest with no redirects.

Property

PublicRoutePaths

IReadOnlyList<string> PublicRoutePaths { get; set; } Source

Gets canonical, source-shaped recovery and declared routes captured from verified bytes.

Remarks

The snapshot owns a read-only copy; consumers cannot change the routes shared by mounted aliases.

Property

HtmlUsesExportRootUrls

bool HtmlUsesExportRootUrls { get; } Source

Whether HTML URLs are relative to the complete export root rather than the legacy logical docs root.

Property

CanonicalArtifactPaths

IReadOnlyCollection<string> CanonicalArtifactPaths { get; } Source

Gets the ordinary HTML members that release verification must bind to this same archive.

Property

Empty

AppSurfaceDocsFrozenRouteManifest Empty { get; } Source

Gets the empty manifest used when an archive has no frozen route identity or when parsing failed.

Type

AppSurfaceDocsFrozenRouteManifestCache

Source

Caches the frozen route manifest for one mounted exact-version tree.

Method

GetManifest

AppSurfaceDocsFrozenRouteManifest GetManifest(ILogger logger)

Returns the cached manifest, loading it from the tree on first use.

Parameters

  • logger
    Logger used when a present manifest cannot be loaded.

Returns

The cached frozen route manifest, or an empty manifest when unavailable.

Property

UsesVerifiedSnapshot

bool UsesVerifiedSnapshot { get; } Source

Gets a value indicating whether this cache is backed by manifest data parsed during release archive verification.

Type

AppSurfaceDocsHarvestFileSystem

Source

Provides file-system traversal helpers for source-backed AppSurface Docs harvesting.

Remarks

Built-in harvesters treat the configured repository root as the read boundary. Candidate traversal therefore skips file and directory reparse points before a harvester can read content through a symlink, junction, or similar filesystem indirection. The helper preserves the existing lazy depth-first traversal shape and lets callers provide their own repository-relative directory-pruning policy.

Method

EnumerateCandidateFiles

IEnumerable<string> EnumerateCandidateFiles(string rootPath, string searchPattern, Func<string, bool> shouldPruneDirectory, CancellationToken cancellationToken)

Lazily enumerates candidate files under a repository root while skipping reparse-point files and directories.

Parameters

  • rootPath
    The absolute repository root to traverse.
  • searchPattern
    The file-system search pattern applied to each visited directory.
  • shouldPruneDirectory
    Callback that receives a forward-slash repository-relative directory path and returns whether the subtree should be skipped before its descendants are enumerated.
  • cancellationToken
    A token observed before each directory expansion.

Returns

Absolute file paths that match searchPattern and are not reparse points.

Remarks

File-system enumeration and attribute exceptions intentionally flow to callers, matching the existing harvester behavior for unreadable trees. This keeps operational failures visible instead of silently shrinking the public documentation surface.

Method

IsNonReparsePointFile

bool IsNonReparsePointFile(string filePath)

Returns whether filePath exists and is not a file-system reparse point.

Parameters

  • filePath
    The absolute file path to inspect.

Returns

true when the file exists and can be read as a normal source file candidate; otherwise false .

Remarks

Use this for explicit one-off source reads such as root LICENSE files and Markdown sidecars that do not flow through candidate traversal. Missing files return false . Attribute lookup exceptions still flow so callers do not accidentally hide filesystem failures.

Type

AppSurfaceDocsTrustedReleasePathGuard

Source

Validates physical paths that belong to the AppSurface Docs trusted release store.

Remarks

The guard is intentionally filesystem-backed and fail-closed. AppSurface Docs uses it before mounting published release trees and before reading request-time files from a mounted tree so catalog metadata cannot redirect a public docs route outside the operator-owned release store.

Method

NormalizePhysicalPath

string NormalizePhysicalPath(string path)

Converts a filesystem path to a full physical path and removes a trailing directory separator.

Parameters

  • path
    The path to canonicalize with Path.GetFullPath(string) .

Returns

The canonical physical path without a trailing directory separator.

Method

ResolveConfiguredRoot

string ResolveConfiguredRoot(string contentRootPath, string? configuredRootPath, string catalogDirectory)

Resolves the trusted release root from configuration, defaulting to the catalog directory when unset.

Parameters

  • contentRootPath
    The application content root used to anchor relative configured paths.
  • configuredRootPath
    The optional operator-configured trusted release root.
  • catalogDirectory
    The catalog directory used as the default trusted root.

Returns

The canonical trusted release root path.

Method

ResolveContentRootRelativePath

string ResolveContentRootRelativePath(string contentRootPath, string configuredPath)

Resolves an operator-configured path, preserving rooted paths and anchoring relative paths under the content root.

Parameters

  • contentRootPath
    The application content root used for relative configured paths.
  • configuredPath
    The configured path after caller-side trimming.

Returns

The full filesystem path represented by configuredPath .

Method

TryResolveCatalogTreePath

bool TryResolveCatalogTreePath(string trustedReleaseRootPath, string? configuredExactTreePath, out string? exactTreePath, out string? publicIssue, out string? internalDetail)

Resolves a catalog exactTreePath under the trusted release root after rejecting unsafe metadata.

Parameters

  • trustedReleaseRootPath
    The canonical trusted release root that must contain the release tree.
  • configuredExactTreePath
    The catalog value to resolve. It must be relative, non-empty, and free of hidden or parent-traversal segments.
  • exactTreePath
    Receives the canonical physical release tree path when resolution succeeds.
  • publicIssue
    Receives the user-safe availability message when resolution fails.
  • internalDetail
    Receives diagnostic detail for logs and tests when resolution fails.

Returns

true when the catalog path is safe to validate under the trusted root; otherwise, false .

Method

TryValidateDirectory

bool TryValidateDirectory(string directoryPath, string publicMissingIssue, string publicUnsafeIssue, out string? publicIssue, out string? internalDetail)

Validates that a physical directory exists and is not itself a symlink, junction, or reparse point.

Parameters

  • directoryPath
    The physical directory path to inspect.
  • publicMissingIssue
    The user-safe issue to report when the directory is missing.
  • publicUnsafeIssue
    The user-safe issue to report when the directory is unsafe or cannot be inspected.
  • publicIssue
    Receives the user-safe issue when validation fails.
  • internalDetail
    Receives diagnostic detail for logs and tests when validation fails.

Returns

true when the directory exists and is ordinary; otherwise, false .

Method

TryValidateFileCandidate

bool TryValidateFileCandidate(string exactTreeRootPath, string relativeFilePath, out string physicalFilePath, out string? denialReason)

Resolves and validates a file candidate beneath an exact release tree root.

Parameters

  • exactTreeRootPath
    The canonical release tree root that must contain the candidate file.
  • relativeFilePath
    The relative file path requested from the release tree. Rooted paths and parent traversal are rejected.
  • physicalFilePath
    Receives the canonical physical file path when the relative path can be resolved.
  • denialReason
    Receives the internal reason when the candidate is unsafe, missing, or unreadable.

Returns

true when the file candidate stays under the tree and has no reparse segments; otherwise, false .

Method

TryValidateNoReparseSegments

bool TryValidateNoReparseSegments(string trustedRootPath, string candidatePath, bool expectLeafFile, out string? denialReason)

Walks a candidate path from its trusted root and rejects any symlink, junction, or reparse point segment.

Parameters

  • trustedRootPath
    The physical root that must contain candidatePath .
  • candidatePath
    The physical path to validate.
  • expectLeafFile
    Whether the candidate leaf is expected to be a file instead of a directory.
  • denialReason
    Receives the internal reason when containment or segment validation fails.

Returns

true when every segment from root to candidate is ordinary; otherwise, false .

Method

IsSameOrDescendant

bool IsSameOrDescendant(string trustedRootPath, string candidatePath)

Determines whether a canonical candidate path is equal to or physically beneath a trusted root path.

Parameters

  • trustedRootPath
    The trusted root path to compare after canonicalization.
  • candidatePath
    The candidate path to compare after canonicalization.

Returns

true when the candidate equals the root or starts below it using platform path comparison semantics.

Method

IsPathMetadataException

bool IsPathMetadataException(Exception ex)

Classifies exceptions that can occur while normalizing paths or reading filesystem metadata.

Parameters

  • ex
    The exception thrown by path or metadata access.

Returns

true when callers should convert the exception into a fail-closed validation denial.

Method

TryValidateSegment

bool TryValidateSegment(string path, bool expectFile, out string? denialReason)

Validates one physical path segment as an ordinary file or directory.

Parameters

  • path
    The physical path segment to inspect.
  • expectFile
    Whether the path is expected to be a file; otherwise a directory is expected.
  • denialReason
    Receives the internal reason when the segment is missing, a reparse point, or unreadable.

Returns

true when the segment exists and is not a link or reparse point; otherwise, false .

Method

IsLinkOrReparsePoint

bool IsLinkOrReparsePoint(FileSystemInfo info)

Detects whether a filesystem entry is a symlink, junction, or other reparse point.

Parameters

  • info
    The filesystem metadata entry to inspect.

Returns

true when the entry has reparse attributes or a link target.

Method

ContainsParentTraversal

bool ContainsParentTraversal(string path)

Checks catalog metadata for parent-directory traversal segments.

Parameters

  • path
    The catalog path value to inspect.

Returns

true when any path segment is exactly .. .

Method

ContainsHiddenSegment

bool ContainsHiddenSegment(string path)

Checks catalog metadata for hidden release tree segments while allowing a leading current-directory marker.

Parameters

  • path
    The catalog path value to inspect.

Returns

true when any non-current-directory segment starts with . .

Property

PhysicalPathComparer

StringComparer PhysicalPathComparer { get; } Source

Gets the comparer used for canonical physical paths on the current platform.

Property

PhysicalPathComparison

StringComparison PhysicalPathComparison { get; } Source

Gets the comparison mode used when checking whether one canonical physical path contains another.

Type

DocsSearchIndexPayload

Source

Cached search-index payload for the live source-backed docs surface.

Parameters

  • Metadata
    Static metadata emitted alongside the indexed documents.
  • Documents
    Searchable docs entries in the shape consumed by the built-in MiniSearch client.
Type

DocsSearchIndexMetadata

Source

Metadata emitted with each docs search-index payload.

Parameters

  • GeneratedAtUtc
    UTC timestamp for when the snapshot was generated.
  • Version
    Schema version understood by the search client.
  • Engine
    Client-side search engine identifier.
Type

DocsSearchIndexDocument

Source

Search document entry emitted for the built-in docs search experience.

Parameters

  • Id
    Stable identifier for the indexed document.
  • Path
    Browser-facing docs URL used for result navigation.
  • Title
    Display title shown in search results.
  • Summary
    Summary text favored for recovery and preview UI.
  • Headings
    Normalized heading titles harvested from the document outline.
  • BodyText
    Full normalized body text indexed for recall.
  • Snippet
    Short excerpt shown in search results.
  • PageType
    Page-type facet value.
  • PageTypeLabel
    Resolved page-type badge label.
  • PageTypeVariant
    Resolved page-type badge variant.
  • Audience
    Audience facet value when explicitly authored.
  • Component
    Component facet value when explicitly authored.
  • Aliases
    Alternative phrases that should match the page.
  • Keywords
    Additional authored search keywords.
  • Status
    Status facet value.
  • NavGroup
    Public navigation group label when present.
  • PublicSection
    Resolved public-section slug when the page participates in a public section.
  • PublicSectionLabel
    Human-readable public-section label.
  • IsSectionLanding
    Whether this record is the resolved landing page for its public section.
  • Order
    Authored order hint used for browse sorting.
  • SequenceKey
    Optional authored sequence key for related content.
  • CanonicalSlug
    Optional canonical slug used for route continuity.
  • RelatedPages
    Authored related-page references used for recovery links.
  • Breadcrumbs
    Authored breadcrumb labels displayed in result chrome.
  • SourcePath
    Repository-relative source path retained for provenance and custom integrations.
  • EntryPoints
    Namespace README entry-point terms projected for richer search consumers.
  • Language
    Normalized programming language for generated API documentation.
  • LanguageLabel
    Reader-facing programming language label for generated API documentation.
  • SummaryPresentation
    Optional bounded, display-only rich presentation for the raw summary.
  • ApiLifecycle
    Optional generated-symbol lifecycle: public , alpha , or beta . Omitted for all other documents.
  • ApiLifecycleLabel
    Optional reader-facing label paired with ApiLifecycle : Public API , Alpha , or Beta . Omitted for all other documents.
  • IsDeprecated
    Optional deprecation flag. true is emitted only with generated-symbol metadata; false and missing values are omitted for other documents.
  • IsGeneratedApiSymbol
    Optional true marker emitted only for validated, provenanced built-in generated API fragments. Consumers must not infer lifecycle from ordinary page metadata.

Remarks

The Path value is cached relative to the live docs surface root and can be rebased onto a request PathBase at response time without rebuilding the full snapshot. Lists are serialized as JSON arrays so the browser client can preserve exact ordering for headings, aliases, related pages, and breadcrumbs.

Property

RecommendedPages

IReadOnlyList<DocsSearchIndexRecommendation> RecommendedPages { get; init; } Source

Gets complete authored-first next reads, including nonsearch targets; old indexes may omit this member.

Type

DocsSearchIndexRecommendation

Source

A complete JSON next-read row. TargetId is the stable canonical identity (including an approved fragment); Path is surface-specific. Source is explicitly authored/automatic. Consumers need no documents-array lookup and should use generic presentation for future optional explanation or badge values. Old indexes treat a missing list as empty.

Type

DocWayfindingSnapshot

Source

Resolved sequence and authored links owned by one snapshot; public projections detach every row.

Type

DocsSearchSummaryPresentationNode

Source

A bounded, display-only Markdown projection for a docs search-result summary.

Parameters

  • Kind
    The display node kind: text , strong , emphasis , or code .
  • Text
    Leaf text for text and code nodes.
  • Children
    Child display nodes for strong and emphasis nodes.

Remarks

This representation intentionally exposes only text, strong, emphasis, and code nodes. It is not an HTML or hyperlink transport and is kept separate from DocsSearchIndexDocument.Summary so existing consumers retain the raw summary text they use for ranking or custom presentation.

Type

DocsSearchIndexEntryPoint

Source

Search projection for one namespace README entry point.

Parameters

  • Label
    Reader-facing entry label.
  • Summary
    Optional entry summary.
  • Target
    Resolved generated anchor target when authored.
  • Href
    Resolved fragment or app-relative href when available.
  • Keywords
    Additional search terms authored on the entry point.
Type

DocsSearchIndexProjection

Source

Describes a requested search-index projection for the cached docs snapshot.

Parameters

  • Locale
    Optional active locale code. Blank values are treated as the default projection; non-blank values are trimmed and lower-cased before cache lookup so request casing does not create duplicate entries.
  • IncludeAllLocales
    Reserved switch for a future all-locales search payload. Phase 1 preserves the existing default payload contract.
Type

DocsSearchIndexProjectionCache

Source

Caches search-index payloads projected from one immutable docs snapshot.

Remarks

Phase 1 always returns the default payload, but the cache reserves normalized per-locale keys so later slices can compute locale-specific payloads without changing DocAggregator callers. Access to the mutable projection dictionary is guarded by a private lock, and cache growth is capped because projection values can come from requests.

Method

GetPayload

DocsSearchIndexPayload GetPayload(DocsSearchIndexProjection projection)

Gets the cached payload for a normalized projection.

Parameters

  • projection
    Projection request to normalize and resolve.

Returns

The default payload in Phase 1, or a cached projection payload in later localization slices.

Remarks

When localization is disabled, or when the projection has no locale, the default payload is returned without growing the projection cache. During Phase 1, locale projections also return the default payload; the cache entry is a bounded placeholder for later locale-specific payload generation.

Method

NormalizeProjection

DocsSearchIndexProjection NormalizeProjection(DocsSearchIndexProjection projection)

Normalizes a projection key before cache lookup.

Parameters

  • projection
    Projection request supplied by the caller.

Returns

A projection whose locale is null for blank input, or trimmed and lower-case invariant otherwise.

Property

CachedProjectionCount

int CachedProjectionCount { get; } Source

Gets the number of seeded projection entries, exposed so tests can verify the cache bound without reflection.

Type

MarkdownDownloadSource

Source

Private source bytes and canonical identity returned by the current Docs snapshot for an authorized Markdown download.

Remarks

This is intentionally internal: controllers may turn the bytes into a protected attachment, but callers cannot use it as a general raw-content API and it never participates in DocNode serialization or search.

Type

DocAggregator

Source

Service responsible for aggregating documentation from multiple harvesters and caching the results.

Method

GetDocsAsync

Task<IReadOnlyList<DocNode>> GetDocsAsync(CancellationToken cancellationToken = default)

Retrieves all harvested documentation nodes sorted by their Path.

Parameters

  • cancellationToken
    An optional token to observe for cancellation requests.

Returns

A read-only list of all DocNode objects ordered by their Path.

Method

GetHarvestHealthAsync

Task<DocHarvestHealthSnapshot> GetHarvestHealthAsync(CancellationToken cancellationToken = default)

Returns structured health for the current AppSurface Docs harvest snapshot.

Parameters

  • cancellationToken
    An optional token to observe while waiting for the cached snapshot.

Returns

Structured harvest health that distinguishes valid empty docs from failed or degraded harvests.

Remarks

The health snapshot is produced by the same memoized harvest used by GetDocsAsync(CancellationToken) . If no docs snapshot exists yet, calling this method triggers the same snapshot generation as a docs read. Caller cancellation cancels only the caller's wait; it does not cancel or poison the shared snapshot computation.

Method

GetDocByPathAsync

Task<DocNode?> GetDocByPathAsync(string path, CancellationToken cancellationToken = default)

Retrieves a documentation node for a source path or canonical docs path.

Parameters

  • path
    The source or canonical documentation path to look up.
  • cancellationToken
    An optional token to observe while waiting for the cached snapshot.

Returns

The matching DocNode , or null if no node exists for the given path.

Remarks

The lookup awaits the cached docs snapshot, then delegates to the snapshot's DocPathResolver so legacy source paths, generated canonical .html paths, fragments, separators, and casing follow the same matching rules used by details pages and curated links.

Method

ResolvePublicRouteAsync

Task<DocRouteResolution> ResolvePublicRouteAsync(string path, CancellationToken cancellationToken = default)

Resolves a requested browser-facing docs route against the current snapshot route catalog.

Parameters

  • path
    The non-null request path to resolve. Callers may pass a docs-relative route such as packages , a rooted docs path such as /docs/packages , or a source-shaped path. Markdown source-shaped paths for public winners resolve as redirects to their clean public routes; non-Markdown source paths, collision losers, and reserved routes remain non-public.
  • cancellationToken
    An optional token observed while waiting for the cached docs snapshot.

Returns

A DocRouteResolution whose kind tells callers whether the request is the canonical public route, a declared or Markdown source-shaped alias that should redirect to DocRouteResolution.PublicRoutePath , an internal non-Markdown source match, a collision or reserved-route loser, or an unresolved path.

Remarks

This method does not redirect or mutate the snapshot. It awaits GetCachedDocsSnapshotAsync , then delegates to DocRouteIdentityCatalog.ResolvePublicRoute(string) so controllers and link builders branch on the same route identity semantics. Markdown source-shaped redirects let links copied from GitHub or editor paths recover to their published canonical routes instead of falling into the generic 404 page.

Method

GetMarkdownDownloadSourceAsync

Task<MarkdownDownloadSource?> GetMarkdownDownloadSourceAsync(string path, CancellationToken cancellationToken = default)

Retrieves source-faithful Markdown bytes for one exact canonical public route in the current Docs snapshot.

Remarks

Raw source stays private to the snapshot and is returned only for built-in Markdown documents that explicitly opted in during harvest. Aliases, source-shaped paths, generated documents, the root landing page, and missing source entries return null rather than exposing repository identity.

Method

GetRouteManifestAsync

Task<AppSurfaceDocsRouteManifest> GetRouteManifestAsync(CancellationToken cancellationToken = default)

Gets the route manifest for the current cached docs snapshot.

Parameters

  • cancellationToken
    Token observed while waiting for the snapshot.

Returns

The final public route manifest derived from the same catalog used for live docs routing.

Remarks

The manifest is produced from the final route identity catalog after namespace README merging and duplicate path resolution. Export consumes this in-process so it can write source-shaped redirect artifacts without crawling an HTTP manifest endpoint or duplicating route rules.

Method

GetDocDetailsAsync

Task<DocDetailsViewModel?> GetDocDetailsAsync(string path, CancellationToken cancellationToken = default)

Builds the typed details view model for the specified documentation page.

Parameters

  • path
    The documentation path to resolve.
  • cancellationToken
    An optional token to observe for cancellation requests.

Returns

A DocDetailsViewModel containing the resolved page, its in-page outline, and wayfinding links, or null when the page cannot be resolved.

Method

GetSearchIndexPayloadAsync

2 overloads
Task<DocsSearchIndexPayload> GetSearchIndexPayloadAsync(CancellationToken cancellationToken = default)

Returns the docs search-index payload generated during docs aggregation.

Parameters

  • cancellationToken
    An optional token to observe for cancellation requests.

Returns

A typed payload containing the search metadata and documents emitted by the live docs surface. The payload is cached before response serialization so callers can rebase rooted paths, such as /docs/guide.html , onto a request PathBase without reparsing or reserializing an intermediate JSON node graph.

Task<DocsSearchIndexPayload> GetSearchIndexPayloadAsync(DocsSearchIndexProjection projection, CancellationToken cancellationToken = default)

Returns a cached search-index projection for future locale-aware search consumers.

Parameters

  • projection
    The requested search projection key.
  • cancellationToken
    An optional token to observe for cancellation requests.

Returns

The matching search payload. Phase 1 preserves the existing payload schema for every projection while reserving the snapshot-owned cache seam that localized search will fill in Phase 3.

Method

GetPublicSectionsAsync

Task<IReadOnlyList<DocSectionSnapshot>> GetPublicSectionsAsync(CancellationToken cancellationToken = default)

Returns the normalized public-section snapshots derived from the harvested docs corpus.

Parameters

  • cancellationToken
    An optional token to observe for cancellation requests.

Returns

The ordered public sections visible in the current docs snapshot.

Method

GetPublicSectionAsync

Task<DocSectionSnapshot?> GetPublicSectionAsync(DocPublicSection section, CancellationToken cancellationToken = default)

Returns one normalized public-section snapshot when the section is present in the current docs snapshot.

Parameters

  • section
    The public section to resolve.
  • cancellationToken
    An optional token to observe for cancellation requests.

Returns

The matching section snapshot, or null when the section has no visible public pages.

Method

InvalidateCache

void InvalidateCache()

Invalidates the cached docs snapshot so docs and search-index are rebuilt on next access.

Method

GetCachedDocsSnapshotAsync

Task<CachedDocsSnapshot> GetCachedDocsSnapshotAsync()

Retrieves the cached docs snapshot, harvesting docs and generating the search-index payload when absent.

Returns

A cached snapshot containing both docs and search-index payload.

Remarks

When harvesting, each active harvester is invoked; failures from individual harvesters are caught and logged. Contents are sanitized before being cached. If multiple nodes share the same Path, a warning is logged and the first occurrence is retained. The search-index payload is generated from the same harvested snapshot. Caller cancellation does not cancel shared snapshot computation; callers can cancel their own wait. Harvester execution is bounded by a timeout so a single slow harvester cannot block snapshot regeneration indefinitely. The memoized cache entry is created with the configured absolute expiration from AppSurfaceDocsOptions.CacheExpirationMinutes .

Method

AwaitHarvesterResultOrTimeoutAsync

Task<T> AwaitHarvesterResultOrTimeoutAsync<T>(Task<T> harvesterTask, CancellationToken timeoutToken)

Awaits one harvester task while giving a completed result precedence when it races the timeout cancellation.

Remarks

The shared timeout token cancels both the harvester and this wait. Once the wait returns a result, callers must preserve it rather than re-reading the timeout token: that token can transition after a valid result crossed the boundary. A task that has not completed when cancellation wins is classified by the caller as timed out.

Method

ResolveTypedNamespaceEntryPointHrefs

Dictionary<string, DocNode> ResolveTypedNamespaceEntryPointHrefs(IReadOnlyDictionary<string, DocNode> docsByPath, DocRouteIdentityCatalog routeIdentityCatalog)

Resolves docs-local namespace entry-point hrefs in the built-in typed C# projection against the final route identity catalog.

Remarks

Namespace README metadata is authored before route identity is available and can therefore use a source-shaped generated C# path. The typed renderer must receive a canonical browser URL directly: unlike legacy HTML, its Razor output is never passed through DocContentLinkRewriter . Fragment entry points stay local to the page; app-relative destinations must resolve to a known route beneath the active Docs root before Razor sees them. This prevents trusted metadata from turning the internal typed rendering path into a same-origin navigation escape hatch.

Method

ResolveGitLastUpdatedUtcAsync

Task<DateTimeOffset?> ResolveGitLastUpdatedUtcAsync(string repositoryRoot, string sourcePath, ILogger logger, CancellationToken cancellationToken, Func<string, IReadOnlyList<string>, string, ILogger, CancellationToken, Task<CommandResult>>? executeProcessAsync = null)

Resolves the last committed UTC timestamp for a source path from local git history.

Parameters

  • repositoryRoot
    The repository root used as the git working directory.
  • sourcePath
    The repository-relative source path to inspect.
  • logger
    Logger used for diagnostic output when git is unavailable or returns unusable data.
  • cancellationToken
    Cancellation used to abort the lookup when snapshot generation times out.
  • executeProcessAsync
    Optional process-execution seam used by tests to simulate git output and failure modes without mutating machine-level PATH state.

Returns

The exact last-updated UTC timestamp when git returns a parseable ISO 8601 commit date; otherwise null .

Method

BuildPublicSections

IReadOnlyList<DocSectionSnapshot> BuildPublicSections(IEnumerable<DocNode> docs, ILogger logger)

Builds the public-section snapshots from the harvested docs corpus.

Parameters

  • docs
    The harvested docs to classify.
  • logger
    Logger used for section-landing conflict warnings.

Returns

The ordered public sections that have at least one visible page.

Method

BuildSearchIndexPayload

(DocsSearchIndexPayload Payload, int RecordCount) BuildSearchIndexPayload(IEnumerable<DocNode> docs, IReadOnlyList<DocSectionSnapshot> publicSections, DocRouteIdentityCatalog routeIdentityCatalog, DocRecommendationPolicyResult recommendations)

Builds the search-index payload from the harvested documentation nodes.

Parameters

  • docs
    The documentation nodes to index.
  • publicSections
    The resolved public sections used to derive landing winners.
  • routeIdentityCatalog
    The snapshot route catalog used to emit public canonical paths.
  • recommendations
    Complete rows resolved by the same snapshot policy, before any response mount.

Returns

A tuple containing the serializable payload and the number of records indexed.

Method

NormalizeSearchText

string NormalizeSearchText(string? text)

Decodes HTML entities and normalizes whitespace in the provided text for search indexing.

Parameters

  • text
    The text to normalize.

Returns

The normalized text.

Method

ShouldUseSearchSnippetForRichAuthoringSummary

bool ShouldUseSearchSnippetForRichAuthoringSummary(string content, string? summary)

Determines whether a rendered rich-authoring page must use its reader-facing snippet instead of a raw Markdown summary.

Parameters

  • content
    The sanitized, rendered document HTML.
  • summary
    The metadata summary derived from source Markdown, when present.

Returns

true when the summary contains rich-authoring fence syntax for content that rendered successfully; otherwise, false .

Remarks

Invalid directives intentionally render as literal source and retain their authored markers. This guard therefore requires both a raw fence in the summary and package-rendered rich markup before it substitutes the already normalized snippet.

Method

BuildSearchDocUrl

2 overloads
string BuildSearchDocUrl(string path)

Constructs a browser-facing URL for a documentation path.

Parameters

  • path
    The relative documentation path.

Returns

A URL string starting with "/docs".

string BuildSearchDocUrl(string docsRootPath, string path)

Constructs a browser-facing URL for a documentation path rooted at a specific docs surface.

Parameters

  • docsRootPath
    The app-relative docs root path.
  • path
    The relative documentation path.

Returns

A URL string rooted at docsRootPath .

Method

TruncateSnippetAtWordBoundary

string TruncateSnippetAtWordBoundary(string text, int maxLength)

Truncates a text snippet at the last word boundary before the maximum length is exceeded.

Parameters

  • text
    The text to truncate.
  • maxLength
    The maximum allowed length of the snippet.

Returns

The truncated text with an ellipsis if it was shortened.

Method

BuildWayfindingSnapshot

(IReadOnlyDictionary<string, DocWayfindingSnapshot> Wayfinding, DocRecommendationPolicyResult Recommendations) BuildWayfindingSnapshot(IReadOnlyList<DocNode> docs, DocPathResolver resolver, IReadOnlyList<DocSectionSnapshot> sections)

Resolves all legacy wayfinding and new recommendations once after merge, canonical collision resolution and section landing selection. A shared canonical link map supplies sequence neighbors and policy facts; authored destinations are projected separately. Their title fallback index is created once on demand within this build. Response projections detach links. Results publish atomically with the search projection in the cached generation.

Method

DetachRecommendations

DocsSearchIndexPayload DetachRecommendations(DocsSearchIndexPayload payload)

Detaches the new nested mutable collections without changing the locale graph or cached ranking.

Method

GetRecommendationMeasurementsAsync

Task<DocRecommendationMeasurements> GetRecommendationMeasurementsAsync(CancellationToken cancellationToken = default)

Returns build-time candidate counts without exposing the snapshot or a request-time ranking operation.

Method

BuildRelatedTitleLookup

IReadOnlyDictionary<string, DocNode> BuildRelatedTitleLookup(IReadOnlyList<DocNode> docs)

Indexes readable authored destinations by display title, preserving the related-page resolver's order/title/path winner and stable input ordering for ties. The build-local lookup is populated only when route resolution fails.

Method

MergeNamespaceReadmes

IReadOnlyList<DocHarvestDiagnostic> MergeNamespaceReadmes(List<DocNode> nodes, string repositoryRoot, bool renderEntryPointPanel, ILogger logger)

Merges authored namespace-intro content into the corresponding namespace overview pages.

Parameters

  • nodes
    The list of documentation nodes to process. Consumed namespace README and NAMESPACE.md sources are removed from this list, and unresolved NAMESPACE.md sources are hidden after diagnostics are recorded.
  • repositoryRoot
    Repository root used to resolve colocated project files for NAMESPACE.md intros.
  • renderEntryPointPanel
    Whether to render validated namespace entry-point metadata into the merged namespace content.
  • logger
    Logger used for namespace entry-point target diagnostics.

Returns

Non-fatal harvest diagnostics produced while merging authored namespace-intro metadata.

Method

MergeNamespaceIntroIntoContent

string MergeNamespaceIntroIntoContent(string namespaceContent, string readmeContent)

Inserts README content into a namespace overview page after the auto-generated namespace groups.

Parameters

  • namespaceContent
    The auto-generated HTML content for the namespace page.
  • readmeContent
    The HTML content from the README file. A leading rendered Markdown H1 is removed before the README is wrapped because namespace overview pages render their primary H1 in the surrounding details shell.

Returns

The merged HTML content, with any leading README H1 omitted from the namespace intro section.

Method

FindMatchingSectionEnd

int FindMatchingSectionEnd(string content, int sectionStart)

Finds the index of the closing </section> tag that matches a <section> tag starting at the specified index.

Parameters

  • content
    The HTML content to search.
  • sectionStart
    The starting index of the <section> tag.

Returns

The index of the closing tag, or -1 if no match is found.

Method

IsReadmePath

bool IsReadmePath(string path)

Determines whether the specified path points to a documentation README file.

Parameters

  • path
    The path to check.

Returns

true if the path identifies a README.md file; otherwise, false .

Method

ExtractNamespaceNameFromNamespacePath

string ExtractNamespaceNameFromNamespacePath(string path)

Extracts the dotted namespace name from a documentation path under the "Namespaces/" directory.

Parameters

  • path
    The path to process.

Returns

The extracted namespace name.

Method

ExtractNamespaceNameFromReadmePath

2 overloads
string? ExtractNamespaceNameFromReadmePath(string path)

Attempts to extract a namespace name from a README path by looking at the parent directory name.

Parameters

  • path
    The README path to process.

Returns

The extracted namespace name, or null if it cannot be determined.

string? ExtractNamespaceNameFromReadmePath(string path, IEnumerable<string>? knownNamespaceNames)

Extracts a namespace name from a README path, optionally matching against a list of known namespaces.

Parameters

  • path
    The README path to process.
  • knownNamespaceNames
    Optional list of known namespaces to match directory segments against. When provided, README paths are only treated as namespace introductions when the matching namespace folder appears under a trusted container directory such as docs or Namespaces .

Returns

The extracted namespace name, or null if it cannot be determined.

Method

HasNamespaceReadmePrefix

bool HasNamespaceReadmePrefix(IReadOnlyList<string> parts, int namespaceStartIndex)

Determines whether the matched namespace folder appears in one of the supported namespace README locations.

Parameters

  • parts
    The normalized directory path segments that precede README.md .
  • namespaceStartIndex
    The index where the matched namespace name begins within parts .

Returns

true when the namespace folder lives under a trusted container like docs or Namespaces ; otherwise, false .

Method

NormalizeLookupPath

string NormalizeLookupPath(string path)

Normalizes a documentation path for lookup by trimming slashes and removing fragment anchors.

Parameters

  • path
    The path to normalize.

Returns

The normalized lookup path.

Method

GetFragment

string? GetFragment(string path)

Extracts the fragment anchor (after the '#') from a documentation path.

Parameters

  • path
    The path to process.

Returns

The fragment string, or null if no fragment is present.

Property

SnapshotCacheDuration

TimeSpan SnapshotCacheDuration { get; } Source

Gets the configured absolute lifetime for the shared docs snapshot cache.

Type

AppSurfaceDocsAliasRequestClassifier

Source

Classifies the received request before routing can normalize away alias ownership evidence.

Remarks

Raw escaped path → one strict decoded validation view → application-relative ownership → safety. The decoded view never becomes a filesystem path. Ownership survives every safety failure.

Method

Classify

AppSurfaceDocsAliasRequest? Classify(HttpContext context, IReadOnlyList<string> owners)

Finds an owner in raw, decoded, then framework coordinates and validates the selected path.

Parameters

  • context
    Received context after host PathBase setup.
  • owners
    Disjoint active alias namespace roots.

Returns

Sticky owner and accepted label, or null for an unowned request.

Method

TryExtractPath

bool TryExtractPath(string? target, out string path)

Extracts origin/HTTP absolute-form paths without URI path normalization.

Type

AppSurfaceDocsAliasRequest

Source

Sticky ownership state; unsafe requests retain the same owner and authorization endpoint.

Parameters

  • NamespaceRoot
    Selected app-relative active namespace.
  • Name
    Accepted normalized ASCII label, or null for unknown/unsafe input.
  • IsSafe
    Whether the received raw and framework paths passed the boundary.
Type

PythonDocHarvester

Source

Harvests explicit Python module, class, function, and method docstrings without executing Python source.

Remarks

This built-in harvester is deliberately a bounded product spike. It parses only policy-approved .py files with the Tree-sitter Python grammar, requires a literal top-level __all__ public boundary, and projects plain docstring text rather than a Google, NumPy, or Sphinx documentation dialect. It never imports a module, starts a Python interpreter, evaluates an expression, or derives a general Python visibility policy from an absent boundary.

Method

HarvestAsync

2 overloads
Task<IReadOnlyList<DocNode>> HarvestAsync(string rootPath, CancellationToken cancellationToken = default)

Scans policy-approved Python files under the repository root and returns generated AppSurface Docs API nodes.

Parameters

  • rootPath
    The repository root used to resolve include and exclude globs.
  • cancellationToken
    An optional token to observe while reading and parsing files.

Returns

Generated Python module pages plus fragment-addressable symbol nodes.

Task<IReadOnlyList<DocNode>> HarvestAsync(DocHarvestContext context, CancellationToken cancellationToken = default)

Scans Python sources with the repository-scoped path policy captured for the current aggregation pass.

Parameters

  • context
    The harvest context containing the repository root and active path policy snapshot.
  • cancellationToken
    An optional token to observe while reading and parsing files.

Returns

Generated Python module pages plus fragment-addressable symbol nodes.

Type

AppSurfaceDocsCodeBlock

Source

Represents the authored Markdown code-fence input that AppSurface Docs can render as highlighted or plain code.

Parameters

  • Code
    The literal code block body, or null when an upstream renderer provides no text.
  • Language
    The first whitespace-delimited Markdown info-string token, or null when omitted.

Remarks

AppSurfaceDocsCodeBlock stores only the first whitespace-delimited info-string token in Language because the renderer treats that token as the language hint. It does not parse full info-string attributes. Language may be null when the info string is omitted, and Code may be null when an upstream renderer provides no text, so callers must handle both defensively.

Type

AppSurfaceDocsVersionAliasName

Source

Applies the shared URL-safe grammar for documentation version aliases.

Method

TryNormalize

bool TryNormalize(string? value, out string name)

Trims and lowercases a candidate alias, accepting 1–64 ASCII characters with alphanumeric edges and alphanumeric, dot, underscore, or hyphen interior characters.

Parameters

  • value
    The authored alias name.
  • name
    The normalized alias name when valid; otherwise an empty string.

Returns

true when the candidate is safe for the alias route segment.

Type

DocPolyglotOwnershipLinker

Source

Connects accepted Python module pages with their explicitly declared C# host types.

Remarks

Both markers are emitted only by built-in static harvesters. The linker intentionally waits until every harvester has succeeded, then requires one accepted Python module and one documented C# owner for each module path. Ambiguous or unmatched declarations disappear from rendered HTML instead of creating a best-effort or potentially broken relationship. The marker values are percent-encoded repository-relative paths so source text never becomes markup.

Method

CreatePythonModuleMarker

string CreatePythonModuleMarker(string relativePath)

Creates a marker for an accepted Python module source path.

Method

CreateCSharpOwnerMarker

string CreateCSharpOwnerMarker(string relativePath, string anchorId, string displayName)

Creates a marker for a documented C# type that explicitly owns a Python module.

Type

AppSurfaceDocsOperatorReadPolicyEvaluator

Source

Evaluates host-owned ASP.NET Core policies for AppSurface Docs diagnostics read surfaces.

Remarks

This adapter is intentionally local to the Docs package. It keeps the diagnostics-read policy independent from the internal Auth.AspNetCore evaluator while preserving ASP.NET Core policy authentication, challenge, forbid, and setup failure semantics for the harvest progress stream.

Method

AuthorizeAsync

2 overloads
ValueTask<AppSurfaceAuthResult> AuthorizeAsync(HttpContext httpContext, string policyName, CancellationToken cancellationToken = default)

Evaluates the configured diagnostics read policy against the current request.

Parameters

  • httpContext
    Current HTTP request context.
  • policyName
    Non-blank host-owned ASP.NET Core authorization policy name.
  • cancellationToken
    Cancellation observed before and during policy lookup.

Returns

A passive AppSurface auth result representing the policy outcome.

ValueTask<AppSurfaceAuthResult> AuthorizeAsync(HttpContext httpContext, IReadOnlyList<IAuthorizeData> authorizationData, CancellationToken cancellationToken = default)

Evaluates the complete ASP.NET Core authorization metadata applied to a named Docs endpoint group.

Parameters

  • httpContext
    Current HTTP request context.
  • authorizationData
    Authorization metadata captured from the named Docs endpoint group.
  • cancellationToken
    Cancellation observed before and during policy lookup.

Returns

A passive AppSurface auth result representing the combined policy outcome.

Remarks

This preserves default-policy, role, authentication-scheme, and multiple-policy semantics for RazorWire streams, which are not conventional HTTP endpoints and therefore cannot receive ASP.NET Core endpoint authorization automatically.

Type

IHarvestPathPolicy

Source

Defines the repository-relative path policy used by AppSurface Docs harvesters.

Remarks

Implementations combine configured include or exclude rules with traversal pruning so harvesters can avoid enumerating large excluded directory trees. All paths passed to this contract must be repository-relative and normalized with forward slashes. Absolute paths, parent-directory traversal, and platform-specific separators should be normalized by the caller before evaluation.

Method

Evaluate

AppSurfaceDocsHarvestPathDecision Evaluate(string relativePath, AppSurfaceDocsHarvestSourceKind sourceKind)

Evaluates whether a repository-relative file path should be harvested for the specified source kind.

Parameters

  • relativePath
    Repository-relative file path normalized with forward slashes.
  • sourceKind
    The harvester source kind requesting the decision.

Returns

A decision containing the final inclusion result and diagnostic trace entries.

Method

ShouldIncludeFilePath

bool ShouldIncludeFilePath(string relativePath, AppSurfaceDocsHarvestSourceKind sourceKind)

Determines whether a repository-relative file path should be included for the specified source kind.

Parameters

  • relativePath
    Repository-relative file path normalized with forward slashes.
  • sourceKind
    The harvester source kind requesting the decision.

Returns

true when the file should be read by the harvester; otherwise false .

Method

ShouldPruneDirectory

bool ShouldPruneDirectory(string relativeDirectory, AppSurfaceDocsHarvestSourceKind sourceKind)

Determines whether a repository-relative directory can be skipped before its descendants are enumerated.

Parameters

  • relativeDirectory
    Repository-relative directory path normalized with forward slashes.
  • sourceKind
    The harvester source kind requesting the decision.

Returns

true when the directory subtree is excluded and can be pruned.

Method

EnumerateCandidateFiles

IEnumerable<string> EnumerateCandidateFiles(string rootPath, AppSurfaceDocsHarvestSourceKind sourceKind, string searchPattern, CancellationToken cancellationToken)

Lazily enumerates candidate files below a repository root while applying directory pruning and skipping reparse points.

Parameters

  • rootPath
    Absolute repository root to traverse.
  • sourceKind
    The harvester source kind requesting candidates.
  • searchPattern
    A file-system search pattern such as *.md .
  • cancellationToken
    A token observed before each directory is expanded.

Returns

Absolute file paths that match searchPattern , are not below a pruned directory, and are not file-system reparse points.

Remarks

File-level include checks are intentionally separate; callers must still pass returned files through ShouldIncludeFilePath after converting them back to repository-relative paths. Implementations skip reparse-point files and directories before yielding or descending so candidate traversal does not follow symlinks, junctions, or similar filesystem indirection outside the selected repository root.

Type

AppSurfaceDocsHeadingSuppressor

Source

Applies page-shell heading rules to harvested documentation HTML at render time.

Method

SuppressLeadingMarkdownH1

string SuppressLeadingMarkdownH1(string content, bool shellOwnsH1)

Removes the leading rendered Markdown h1 element when the details page shell already renders the page H1.

Parameters

  • content
    The sanitized harvested HTML body to render inside the details page content surface.
  • shellOwnsH1
    true when the page shell renders the semantic H1 from Models.DocDetailsViewModel.Title ; false when the harvested body remains responsible for its own top-level heading.

Returns

The original content when the shell does not own the H1 or when the body does not begin with an h1 ; otherwise the body with that first rendered h1 removed.

Remarks

Only the leading H1 is suppressed. Later H1 elements remain visible because they are authored body structure, not duplicated page chrome.

Method

GetFirstMeaningfulTokenIndex

int GetFirstMeaningfulTokenIndex(string content)

Finds the first non-trivia token in harvested HTML.

Parameters

  • content
    The harvested HTML body that may begin with whitespace, a BOM, comments, or content.

Returns

The index of the first non-trivia token, or -1 when the body is empty or contains only ignorable trivia.

Remarks

Only leading comments are skipped. Other elements, text, or malformed comments remain authored content and are preserved by the suppressor.

Type

DocRecommendationPageFacts

Source

Final-snapshot facts consumed by the pure recommendation policy. Callers resolve authored references and sequence neighbors with the existing route resolver before constructing these facts; only canonical route winners belong here.

Type

DocRecommendation

Source

A snapshot-owned recommendation. Response projections must detach the page and reason collection.

Type

DocRecommendationMeasurements

Source

Diagnostic counts for the candidate union, before source-specific filtering; no runtime tuning surface.

Type

DocRecommendationPolicyResult

Source

Complete, immutable results and measurements from one policy build.

Type

DocRecommendationPolicy

Source

Selects at most three automatic next reads after an uncapped authored prefix, using only final canonical snapshot metadata. Inverted indexes generate candidates; section, audience and sequence alone never qualify an ordinary page.

Remarks

Terms are ordinal case-insensitive, trimmed and whitespace-collapsed, with no stemming or punctuation rewriting. Common terms occur on at least five eligible targets and more than one quarter of that target corpus. Derived component/audience values are ignored. Source opt-out does not change target membership or term frequencies. All tie breaks are explicit; input order and current culture have no influence on ranking.

Method

Build

DocRecommendationPolicyResult Build(IReadOnlyList<DocRecommendationPageFacts> pages)

Builds a detached, read-only result for every canonical source. Authored entries retain exact fragment identities and order; automatic entries exclude the owning pages of the source, sequence neighbors and authored entries.

Method

ReasonText

string ReasonText(string primaryReasonCode, bool sharedComponent = false)

Maps stable primary reason codes to the default built-in caption, including future-code fallback.

Type

AppSurfaceDocsPublishedTreeHandler

Source

Serves one or more published AppSurface Docs trees from static export artifacts.

Remarks

Published trees are usually exported from the stable /docs surface and then mounted later under the configured route-family root or {RouteRootPath}/v/{version} . This handler resolves extensionless requests back to the exporter’s .html files and rewrites stable-root HTML or search-index payloads so the mounted tree stays version-local.

Method

TryHandleAsync

Task<bool> TryHandleAsync(HttpContext httpContext)

Attempts to serve the current request from one of the configured published trees.

Parameters

  • httpContext
    The current HTTP request context.

Returns

true when a published tree handled the request; otherwise false .

Method

HandleOwnedAliasAsync

Task HandleOwnedAliasAsync(HttpContext context, AppSurfaceDocsAliasRequest selection)

Consumes an owned alias request terminally after the host's authorization middleware.

Parameters

  • context
    Authorized request with sticky received-path ownership state.
  • selection
    Raw safety/label state selected before routing.
Method

TryServeMountAsync

Task<bool> TryServeMountAsync(HttpContext context, AppSurfaceDocsPublishedTreeMount mount, string requestPath)

Serves exactly the selected mount; a false result never changes that selection.

Method

WriteAliasRecoveryAsync

Task WriteAliasRecoveryAsync(HttpContext context, Microsoft.Extensions.Primitives.StringValues hostContentSecurityPolicy)

Uses one generic, encoded Docs recovery response for all owned GET/HEAD failures.

Method

BuildExportedDocsCandidatePaths

IEnumerable<string> BuildExportedDocsCandidatePaths(AppSurfaceDocsPublishedTreeMount mount, string requestPath)

Resolves root-export document files without changing the selected verified archive or its bytes.

Remarks

CDN exports retain the original /docs directory while shared search assets live at the tree root. Flat archives keep their existing precedence. Only verified, inventory-covered HTML candidates qualify for this layout.

Method

BuildHtmlDocumentCandidatePaths

IReadOnlyList<string> BuildHtmlDocumentCandidatePaths(string relativeRequestPath)

Builds only the ordinary HTML file candidates that the published route resolver would use for a docs route.

Parameters

  • relativeRequestPath
    The decoded path below the selected mount root.

Returns

Exact .html , route.html , or route/index.html candidates in serving order.

Property

IsAliasNamespaceActive

bool IsAliasNamespaceActive { get; } Source

Gets whether a catalog actively reserves this instance's alias namespace, including zero mounts.

Type

AppSurfaceDocsPublishedTreeMount

Source

Describes one published exact-version tree that should be mounted into the active host.

Remarks

When multiple AppSurfaceDocsPublishedTreeMount instances overlap, callers should treat the longest MountRootPath as the winning mount because the request handler resolves mounts from most-specific to least-specific roots before serving content. CanonicalRootPath controls only canonical-link metadata: normal navigation, search payloads, assets, and frozen-manifest redirects continue to use MountRootPath .

Property

MountRootPath

string MountRootPath { get; } Source

Gets the request-path root where the tree should appear.

Property

AliasName

string? AliasName { get; } Source

Gets the normalized catalog label for dictionary dispatch, or null for legacy mounts.

Property

FileProvider

IFileProvider FileProvider { get; } Source

Gets the static file provider for the tree contents.

Property

ExactTreeRootPath

string? ExactTreeRootPath { get; } Source

Gets the resolved physical root for the exact published tree, when path-guard checks should run.

Property

CanonicalRootPath

string CanonicalRootPath { get; } Source

Gets the app-relative route root canonical metadata should prefer for this mount.

Property

FrozenRouteManifest

AppSurfaceDocsFrozenRouteManifestCache? FrozenRouteManifest { get; } Source

Gets the lazy cache for the tree's frozen route manifest, when one should be consulted.

Property

ArchiveVerificationState

AppSurfaceDocsReleaseArchiveVerificationState ArchiveVerificationState { get; } Source

Gets the archive-integrity state resolved before this tree was mounted.

Property

VerifiedReleaseArchive

AppSurfaceDocsVerifiedReleaseArchive? VerifiedReleaseArchive { get; } Source

Gets verified archive file metadata, when this mount is backed by a catalog-pinned release manifest.

Type

AppSurfaceDocsPublishedTreeContentRewriter

Source

Rewrites stable-root published-tree content so the same artifact can be served from different mount roots.

Remarks

Rewrites are mount-aware rather than file-aware. The active AppSurfaceDocsPublishedTreeMount decides which root wins, and then the rewriter adjusts exported stable-root URLs so they point at that mounted surface. The default stable /docs surface only needs HTML rewrites when the host adds a non-empty request PathBase ; when the mount root and route root are still /docs and no PathBase applies, the exported HTML is already correct and is returned unchanged unless a distinct canonical root, public origin, or generated critical-style nonce applies.

Method

RewriteHtml

string RewriteHtml(string html, string mountRootPath, string previewRootPath = "/docs/next", string routeRootPath = DocsUrlBuilder.DocsEntryPath, string? requestPathBase = null, string? canonicalRootPath = null, string? publicOrigin = null, bool htmlUsesExportRootUrls = false)

Rewrites stable-root HTML so docs-local links, assets, and client config point at the supplied mount root.

Parameters

  • html
    The exported HTML document.
  • mountRootPath
    The request-path root where the tree is being served.
  • previewRootPath
    The live preview docs root that should stay untouched when encountered.
  • routeRootPath
    The route-family root that owns archive and exact-version routes.
  • requestPathBase
    The current host path base that should prefix rewritten app-relative docs URLs.
  • canonicalRootPath
    The app-relative route root canonical metadata should prefer for this mount.
  • publicOrigin
    The runtime public origin used for absolute canonical metadata, or null to preserve exported origins.
  • htmlUsesExportRootUrls
    Whether verified frozen metadata declares bare URLs relative to the complete export root.

Returns

The rewritten HTML document.

Remarks

This method rewrites exported stable-root docs links, assets, and the inline window.__appSurfaceDocsConfig payload matched by DocsClientConfigRegex so the document behaves like it was originally emitted for mountRootPath . As part of that rewrite, the legacy docsVersionsUrl client field is removed because version archive navigation is rendered server-side. When mountRootPath and routeRootPath are both the default /docs , legacy rewrites only occur if requestPathBase is non-empty so sub-path-hosted apps still emit /some-base/docs/... links. Request-scoped CSP nonces are always removed from the generated AppSurface preference bootstrap and critical-theme styles, because published output must remain a deterministic, reusable artifact. The handler recognizes only the package's published bootstrap hash when allowing scripts in a versioned Docs response; all other inline scripts remain blocked. New verified htmlUrlBase: export-root manifests instead project local HTML attributes and generated redirect refresh URLs from the complete export root beneath the mount, even at stable /docs . Absolute external URLs and explicitly ignored authoring anchors stay unchanged. This flag must come from the verified frozen snapshot, not request data or live metadata.

Method

RewriteSearchIndexJson

string RewriteSearchIndexJson(string json, string mountRootPath, string previewRootPath = "/docs/next", string routeRootPath = DocsUrlBuilder.DocsEntryPath, string? requestPathBase = null)

Rewrites a published search-index payload so mounted document URLs stay inside the active docs surface.

Parameters

  • json
    The exported search-index payload.
  • mountRootPath
    The request-path root where the tree is being served.
  • previewRootPath
    The live preview docs root that should stay untouched when encountered.
  • routeRootPath
    The route-family root that owns archive and exact-version routes.
  • requestPathBase
    The current host path base that should prefix rewritten app-relative docs URLs.

Returns

The original payload when it is not a JSON object with a top-level documents array or when no top-level document path or nested recommendation path requires rewriting; otherwise a payload whose rewritten links stay inside the selected docs mount.

Remarks

Top-level document paths retain their established mounted-URL rules. For each recommendation row, the original complete URL is validated as a canonical archive recommendation before its path is rebased; the metadata query is discarded and only the validated fragment is retained. Other row identity, display, and reason fields are unchanged. A default stable /docs mount remains byte-preserving unless a nested query must be removed.

Type

AppSurfaceDocsCodeBlockMarkdownExtension

Source

Registers AppSurface Docs' fenced-code renderer with Markdig.

Method

CreateDefaultHighlighter

IAppSurfaceDocsCodeHighlighter CreateDefaultHighlighter(ILogger<TextMateSharpAppSurfaceDocsCodeHighlighter> logger)

Creates the default TextMateSharp-backed AppSurface Docs highlighter.

Parameters

  • logger
    Logger used to emit diagnostics when grammar loading or highlighting falls back.

Returns

The default AppSurface Docs code highlighter.

Type

AppSurfaceDocsCodeBlockRenderer

Source

Renders Markdown fenced code blocks through AppSurface Docs' highlighter contract.

Method

ExtractLanguage

string? ExtractLanguage(FencedCodeBlock block)

Extracts the first language token from a fenced code block's info string.

Parameters

  • block
    The fenced code block to inspect.

Returns

The first language token, or null when the fence has no info string.

Type

DocFeaturedPageResolver

Source

Resolves authored reader-intent landing curation metadata into browser-facing AppSurface Docs featured-page groups.

Remarks

The resolver accepts the normalized featured_page_groups metadata on a landing document, matches each authored destination against harvested docs by source or canonical path, skips destinations that are missing, hidden, blank, or duplicated, and returns only groups that still contain at least one visible page. Logging is intentionally warning-level because curation mistakes degrade first-run docs navigation without breaking application startup.

Method

ResolveGroups

IReadOnlyList<DocLandingFeaturedPageGroupViewModel> ResolveGroups(DocNode? landingDoc, IReadOnlyList<DocNode> docs)

Resolves grouped featured-page metadata from landingDoc against the harvested docs corpus.

Parameters

  • landingDoc
    The root or section landing document that owns the curation metadata, or null when the caller has no landing page to resolve.
  • docs
    The harvested docs corpus used for destination lookup.

Returns

A list of resolved featured-page groups ordered by authored group order, then authored position. The method returns an empty list when landingDoc is null , when the landing doc has no featured_page_groups , or when every authored group is filtered out during resolution. Groups with no visible destinations after validation are omitted. Destinations that resolve to docs without a public DocNode.CanonicalPath are skipped with a warning because collision losers and reserved routes are intentionally not linkable. Duplicate destinations are suppressed across all groups, so a page resolved earlier in authored order will not appear again later in the landing. Browser-facing DocLandingFeaturedPageViewModel.Href values are rooted at the current live docs surface from DocsUrlBuilder , not hardcoded to /docs , and authored canonical input paths are matched against that same configured live docs root before the configured route-family root and legacy stable /docs prefix fallback are considered.

Type

IDocHarvesterActivation

Source

Lets an optional harvester tell AppSurface Docs whether it should participate in the current source snapshot.

Remarks

Disabled optional harvesters are omitted from aggregate harvest-health accounting so a deliberately disabled feature cannot convert an otherwise all-failed snapshot into a degraded one. Direct calls to the harvester may still return an empty document set for compatibility.

Property

IsEnabled

bool IsEnabled { get; } Source

Gets a value indicating whether the harvester should run and count toward harvest-health totals.

Type

AppSurfaceDocsHarvestPathDecision

Source

Describes the include, exclude, or prune outcome for one normalized harvest path.

Parameters

  • Included
    Indicates whether the path remains eligible for harvesting.
  • RelativePath
    The normalized repository-relative path that was evaluated.
  • SourceKind
    The source type whose harvest policy was applied.
  • Code
    The policy decision code explaining the outcome.
  • Trace
    The ordered rule matches that contributed to the decision.
  • MatchedDefaultGroups
    The default exclusion groups that matched the path.
Type

AppSurfaceDocsMetadataDiagnostic

Source

Describes one non-fatal AppSurface Docs metadata authoring problem discovered while parsing or normalizing metadata.

Parameters

  • Code
    Stable diagnostic code suitable for tests, logs, and documentation.
  • FieldPath
    Metadata field path associated with the warning, such as featured_page_groups[0].pages .
  • Problem
    Reader-facing summary of what is wrong.
  • Cause
    Explanation of why AppSurface Docs cannot safely use the authored value as-is.
  • Fix
    Suggested author action that resolves the warning.
Type

MarkdownMetadataParseResult

Source

Carries normalized metadata together with non-fatal diagnostics from a Markdown metadata parse.

Parameters

  • Metadata
    The parsed metadata, or null when no usable metadata document was present.
  • Diagnostics
    Warnings produced while parsing or normalizing metadata fields.
Property

DownloadEligibility

MarkdownDownloadEligibility DownloadEligibility { get; init; } Source

Gets the strict inline opt-in result for protected Markdown download.

Remarks

This remains internal parsing state. It lets the Markdown harvester reuse the same front-matter split and YAML validation already required for rendered metadata instead of reparsing the document solely for raw-source eligibility. Sidecar parsing leaves the default MarkdownDownloadEligibility.NotDeclared value because sidecars cannot grant download access.

Type

AppSurfaceDocsHarvestChannelAuthorizer

Source

Authorizes the AppSurface Docs harvest progress stream with harvest visibility and host-owned stream policy.

Method

CanSubscribeAsync

ValueTask<bool> CanSubscribeAsync(HttpContext context, string channel)

Determines whether the current request can subscribe to the requested RazorWire channel.

Parameters

  • context
    The current HTTP context.
  • channel
    The requested channel name.

Returns

true when channel passes harvest visibility checks and optional delegated authorization; otherwise false .

Remarks

AppSurfaceDocsStreamAuthorization.IsHarvestProgressChannel(string?) identifies the harvest progress stream so only that channel is tied to AppSurfaceDocsHarvestHealthVisibility.AreRoutesExposed(AppSurfaceDocsOptions, IHostEnvironment) . The method has no shared mutable state beyond reading constructor dependencies, but the delegated authorizer may perform asynchronous policy checks.

Type

AppSurfaceDocsHarvesterRegistration

Source

Associates one configured harvester instance with its redacted display name.

Parameters

  • ProgressId
    Unique, server-only callback identity for the configured harvester instance.
  • HarvesterType
    Redacted concrete type name shown to the operator.
  • IsBuiltInProgressHarvester
    Whether the registration belongs to a package-owned parser that reports detailed progress.
Method

Create

IReadOnlyList<AppSurfaceDocsHarvesterRegistration> Create(IReadOnlyList<string> harvesterTypes)

Creates registrations with unique server-only identities for the supplied harvester type names.

Parameters

  • harvesterTypes
    The redacted harvester type names to register.

Returns

Registrations that preserve input order and distinguish repeated type names.

Type

AppSurfaceDocsHarvestProgressReporter

Source

Captures redacted live harvest progress and publishes bounded RazorWire updates for late-subscribing docs pages.

Method

BeginRunAsync

2 overloads
ValueTask<string> BeginRunAsync(IReadOnlyList<string> harvesterTypes)

Begins a new harvest run and publishes the initial waiting snapshot.

Parameters

  • harvesterTypes
    The redacted harvester type names expected in the run.

Returns

The generated run identifier used to correlate later progress callbacks.

Remarks

The snapshot update is protected by the reporter gate and live publication is scheduled after the lock is released. Parser execution never waits for a stream hub response. Because this overload only receives display names, its registrations remain status-only; BeginRunAsync(IReadOnlyList{AppSurfaceDocsHarvesterRegistration}) carries the trusted package-owned parser marker. Passing null throws ArgumentNullException .

ValueTask<string> BeginRunAsync(IReadOnlyList<AppSurfaceDocsHarvesterRegistration> harvesterRegistrations)

Begins a new harvest run with stable, server-only identities for each configured harvester instance.

Parameters

  • harvesterRegistrations
    Redacted display names paired with unique callback identities.

Returns

The generated run identifier used to correlate later progress callbacks.

Method

SuppressCompletionVisitForCurrentOrNextRun

string? SuppressCompletionVisitForCurrentOrNextRun()

Suppresses the terminal browser visit for the active run, or for the next run if the coordinator has scheduled work before the run has published its identifier.

Returns

The run identifier that was suppressed, or null when suppression was deferred to the next run.

Remarks

A run can be terminal in the snapshot while its asynchronous completion publish is still in progress. Completed snapshots are therefore still eligible for suppression so a queued rebuild cannot race with a stale terminal visit.

Method

RebuildQueuedAsync

ValueTask RebuildQueuedAsync(string? supersededRunId)

Records that a trusted rebuild is queued behind the active run.

Parameters

  • supersededRunId
    The active run identifier returned by SuppressCompletionVisitForCurrentOrNextRun , or null when the suppression applies to the next unpublished run.

Returns

A completed task after the updated snapshot has been retained and publication has been scheduled.

Remarks

When a run identifier is supplied, the queued-state update is ignored if a newer run has already replaced the superseded snapshot. This keeps delayed queued notifications from decorating a fresh rebuild run.

Method

HarvesterStartedAsync

ValueTask HarvesterStartedAsync(string runId, string progressId)

Marks a harvester as running for the correlated harvest run.

Parameters

  • runId
    The run identifier returned from the matching begin call.
  • progressId
    The server-only identity of the harvester instance to update.

Returns

A completed task after the updated snapshot has been retained and publication has been scheduled.

Method

HarvesterCompletedAsync

ValueTask HarvesterCompletedAsync(string runId, string progressId, DocHarvesterHealthStatus status, int docCount)

Marks a harvester as terminal and records its document count.

Parameters

  • runId
    The run identifier returned from the matching begin call.
  • progressId
    The server-only identity of the harvester instance to update.
  • status
    The terminal health status reported by the harvester.
  • docCount
    The non-negative document count reported by the harvester.

Returns

A completed task after the updated snapshot has been retained and publication has been scheduled.

Method

HarvesterDocumentCountUpdatedAsync

ValueTask HarvesterDocumentCountUpdatedAsync(string runId, string progressId, int docCount)

Updates the in-progress document count for a harvester.

Parameters

  • runId
    The run identifier returned from the matching begin call.
  • progressId
    The server-only identity of the harvester instance to update.
  • docCount
    The current non-negative document count.

Returns

A completed task after the updated snapshot has been retained and publication has been scheduled.

Method

CreateSession

AppSurfaceDocsHarvestProgressSession CreateSession(string runId, string progressId, int testingDelayPerDocumentMilliseconds = 0, CancellationToken cancellationToken = default)

Creates a safe, run-scoped session for one package-owned harvester.

Parameters

  • runId
    The run identifier returned from the matching begin call.
  • progressId
    The server-only identity of the package-owned harvester instance.
  • testingDelayPerDocumentMilliseconds
    Optional test-only delay applied once per positive output document.
  • cancellationToken
    Harvester cancellation token used to stop test pacing with the parser.

Remarks

The session accepts only closed phase values and numeric deltas. It intentionally has no source-path or display text parameters, so built-in parser telemetry cannot widen the progress redaction boundary.

Method

TransitionAsync

ValueTask TransitionAsync(string runId, string progressId, AppSurfaceDocsHarvestProgressPhase phase)

Advances one package-owned harvester through its next safe lifecycle phase.

Parameters

  • runId
    The active run identifier returned when a run begins.
  • progressId
    The server-only identity assigned to the package-owned harvester.
  • phase
    The requested next lifecycle phase.

Returns

A completed task after an accepted transition has been retained and publication has been scheduled.

Remarks

Stale run identifiers and unknown progress identities are ignored. Only the next sequential phase is accepted; waiting and terminal phases are reporter-owned and cannot be set by a harvester session. This preserves the redaction boundary and prevents a delayed parser callback from mutating another harvester or a later run.

Method

ReportSourceUnit

void ReportSourceUnit(string runId, string progressId, int documentsFoundDelta)

Records one inspected source unit and the documents it produced for a package-owned harvester.

Parameters

  • runId
    The active run identifier returned when a run begins.
  • progressId
    The server-only identity assigned to the package-owned harvester.
  • documentsFoundDelta
    The non-negative number of documents produced by the inspected source unit.

Exceptions

  • ArgumentOutOfRangeException
    Thrown when documentsFoundDelta is negative.

Remarks

A zero delta still records the inspected source unit. Stale run identifiers and unknown progress identities are ignored after input validation. Accepted reports are coalesced into ordinary live publication, so callers must not expect a stream update for every source unit.

Method

ReportOutputOnly

void ReportOutputOnly(string runId, string progressId, int documentsFoundDelta)

Records output materialized without inspecting a new source unit for a package-owned harvester.

Parameters

  • runId
    The active run identifier returned when a run begins.
  • progressId
    The server-only identity assigned to the package-owned harvester.
  • documentsFoundDelta
    The non-negative number of additional documents materialized by the harvester.

Exceptions

  • ArgumentOutOfRangeException
    Thrown when documentsFoundDelta is negative.

Remarks

This method deliberately does not increment source-unit telemetry. Stale run identifiers and unknown progress identities are ignored after input validation. Accepted reports are coalesced into ordinary live publication, so callers must not expect a stream update for every output delta.

Method

ActivityAsync

ValueTask ActivityAsync(string runId, string message)

Adds a bounded activity message to the current run.

Parameters

  • runId
    The run identifier returned from the matching begin call.
  • message
    The redacted activity message to prepend.

Returns

A completed task after the updated snapshot has been retained and publication has been scheduled.

Remarks

Messages are kept newest-first and capped to the renderer's activity budget. A stale runId is ignored, and blank messages throw ArgumentException .

Method

CompleteRunAsync

ValueTask CompleteRunAsync(string runId, DocHarvestHealthSnapshot health)

Completes the correlated run from the final harvest-health snapshot.

Parameters

  • runId
    The run identifier returned from the matching begin call.
  • health
    The final redacted health snapshot used to populate terminal state, counts, and diagnostics.

Returns

A completed task after the updated snapshot has been retained and publication has been scheduled.

Remarks

A failed aggregate health status maps to AppSurfaceDocsHarvestRunState.Failed ; all other terminal statuses map to AppSurfaceDocsHarvestRunState.Completed . A stale runId is ignored.

Method

FailRunAsync

ValueTask FailRunAsync(string runId)

Terminalizes a begun run when aggregation fails after individual harvester execution.

Remarks

The original aggregation exception remains owned by the caller. This rescue publishes only a generic redacted failure state so an operator is not left with a permanently active observatory if snapshot post-processing fails.

Method

IsQueuedRebuildRun

bool IsQueuedRebuildRun(string? supersededRunId)

Determines whether a queued-rebuild status update still belongs to the currently retained running snapshot.

Parameters

  • supersededRunId
    The run identifier captured when the rebuild was queued, or null when the queue marker was deferred until the next run published its identifier.

Returns

true when the current snapshot is the run that should carry queued state.

Remarks

This guard prevents delayed queued-state publishes from decorating a fresh rebuild after the original run has already completed. Callers must hold _gate while invoking this helper so the snapshot and deferred marker are compared atomically.

Property

CurrentSnapshot

AppSurfaceDocsHarvestProgressSnapshot CurrentSnapshot { get; } Source

Gets the latest redacted harvest progress snapshot.

Remarks

Access is synchronized through the reporter gate so callers receive a consistent snapshot instance. The returned record is immutable by convention through init-only properties.

Property

CompletionDelay

int CompletionDelay { get; } Source

Gets the client-side completion navigation delay in milliseconds.

Property

StreamChannelName

string StreamChannelName { get; } Source

Gets the RazorWire stream channel owned by this Docs runtime.

Property

TimeProvider

TimeProvider TimeProvider { get; } Source

Gets the time source shared with run-scoped test pacing and rate measurement.

Property

SuppressedCompletionVisitCount

int SuppressedCompletionVisitCount { get; } Source

Gets the number of run identifiers whose terminal completion visit is currently suppressed.

Remarks

This test seam keeps suppression cleanup verifiable without exposing the mutable set or using reflection. Production callers should use SuppressCompletionVisitForCurrentOrNextRun instead of observing this count.

Type

AppSurfaceDocsHarvestProgressRenderer

Source

Renders encoded harvest progress HTML fragments for the AppSurface Docs observatory.

Remarks

The renderer accepts already-redacted progress snapshots and emits bounded markup for full pages and Turbo stream updates. It HTML-encodes text and attribute values, truncates activity to eight entries and diagnostics to four, and treats AppSurfaceDocsHarvestRunState.Completed and AppSurfaceDocsHarvestRunState.Failed as terminal states. The renderer intentionally does not accept request-derived return URLs; Razor views should emit those values through normal attribute or link rendering after validating that they are app-relative.

Method

Render

string Render(AppSurfaceDocsHarvestProgressSnapshot snapshot, int completionDelayMilliseconds)

Renders the observatory fragment for a harvest progress snapshot.

Parameters

  • snapshot
    The redacted snapshot to render.
  • completionDelayMilliseconds
    The completion navigation delay in milliseconds.

Returns

An encoded HTML fragment for the observatory surface.

Remarks

When the snapshot is completed, the fragment includes the completion marker and delay used by the client script to refresh after the configured delay. Failed runs render diagnostics but do not auto-refresh. The containing Razor view owns request-derived return links so they are emitted by Razor's encoder rather than this raw fragment.

Method

RenderHtml

IHtmlContent RenderHtml(AppSurfaceDocsHarvestProgressSnapshot snapshot, int completionDelayMilliseconds)

Renders the observatory fragment as HTML-safe content for Razor views.

Parameters

  • snapshot
    The redacted snapshot to render.
  • completionDelayMilliseconds
    The completion navigation delay in milliseconds.

Returns

HTML-safe observatory markup with all dynamic text encoded.

Remarks

Use this method from package-owned Razor views instead of Html.Raw . Request-derived navigation values belong in the surrounding view model and should be emitted by Razor attributes or anchors after validation.

Method

RenderTurboStream

string RenderTurboStream(AppSurfaceDocsHarvestProgressSnapshot snapshot, int completionDelayMilliseconds)

Renders a Turbo stream update for the harvest observatory target.

Parameters

  • snapshot
    The redacted snapshot to render.
  • completionDelayMilliseconds
    The completion navigation delay in milliseconds.

Returns

A Turbo stream update that replaces the observatory content.

Remarks

The outer page owns navigation timing and request-derived return links; the emitted fragment only carries completion state for client-side refresh scheduling.

Type

AppSurfaceDocsWordmarkHtml

Source

Renders configured AppSurface Docs wordmarks for package-owned Razor views.

Remarks

This helper keeps the docs chrome's encoded wordmark markup in one place so layout and landing views share the same highlight splitting, CSS variable placement, and plain-text fallback. It only consumes resolved identity values; the options post-configuration and validator remain the source of truth for trimming, matching, and color safety.

Method

Render

IHtmlContent Render(AppSurfaceDocsResolvedIdentity identity, string cssClass, string elementName = "span")

Renders the resolved identity display name with the optional configured wordmark highlight.

Parameters

  • identity
    Resolved identity for the current docs host.
  • cssClass
    CSS classes for the outer wordmark element.
  • elementName
    The package-owned element to render. Supported values are span and h1 .

Returns

HTML-safe wordmark markup with all display text encoded.

Type

DocsSearchSummaryPresentationProjector

Source

Projects authored Markdown summaries into the small, safe display contract used by docs search results.

Remarks

The projector deliberately uses Markdig's base parser rather than the Docs rendering pipeline. Search-result previews need semantic inline formatting, not HTML, extensions, attributes, links, or renderer behavior. Its output is bounded to protect browser consumers even when a summary is author-authored or sourced from an external index.

Method

Project

IReadOnlyList<DocsSearchSummaryPresentationNode>? Project(string? summary)

Projects one raw Markdown summary, returning null when it has no reader-facing content.

Parameters

  • summary
    The raw summary retained unchanged in the legacy search-index field.

Returns

A bounded display tree, or null when no usable text remains.

Method

TryClassifySuppressedHtmlTag

bool TryClassifySuppressedHtmlTag(string tag, out bool isClosing, out bool isSelfClosing)

Classifies the raw HTML tags that suppress their inline contents from a search summary.

Parameters

  • tag
    Raw HTML tag text reported by the Markdown parser.
  • isClosing
    Whether tag closes a suppressed element.
  • isSelfClosing
    Whether tag is self-closing.

Returns

true when the tag is a script or style element; otherwise, false .

Type

ProjectionBuilder

Source

Accumulates the bounded presentation tree while enforcing node and scalar budgets.

Remarks

Internal visibility permits direct verification of defensive budget guards that valid Markdown cannot reach.

Method

BeginBlock

void BeginBlock()

Records a boundary between reader-visible Markdown blocks.

Method

AddContainer

MutableNode? AddContainer(List<MutableNode> target, string kind, int depth)

Adds a formatted container when the depth and node budgets allow it.

Parameters

  • target
    The parent node collection.
  • kind
    The safe presentation-node kind.
  • depth
    The candidate container depth.

Returns

The added node, or null after budget truncation.

Method

AppendText

void AppendText(List<MutableNode> target, string kind, string? value, int depth)

Normalizes and appends a bounded text or code leaf.

Parameters

  • target
    The parent node collection.
  • kind
    The safe presentation-node kind.
  • value
    The raw text to append.
  • depth
    The leaf depth.
Method

RemoveNode

void RemoveNode()

Reclaims the node count after a newly created empty container is discarded.

Method

Build

IReadOnlyList<DocsSearchSummaryPresentationNode>? Build()

Materializes a safe immutable presentation tree.

Returns

The immutable nodes, or null when no reader-visible text remains.

Property

Root

List<MutableNode> Root { get; } Source

Gets the mutable top-level nodes collected for the current projection.

Property

IsTruncated

bool IsTruncated { get; set; } Source

Gets whether the builder has emitted its terminal truncation marker.

Type

MutableNode

Source

Holds one mutable presentation node until projection construction completes.

Method

ToImmutable

DocsSearchSummaryPresentationNode? ToImmutable()

Converts this node and its valid descendants into the public immutable contract.

Returns

The immutable node, or null when no visible content remains.

Property

Kind

string Kind { get; } Source

Gets the safe presentation-node kind.

Property

Text

StringBuilder Text { get; } Source

Gets the mutable text leaf content.

Property

Children

List<MutableNode> Children { get; } Source

Gets the child nodes for formatted containers.

Type

AppSurfaceDocsIdentityPath

Source

Normalizes and validates browser paths used by AppSurface Docs identity options.

Remarks

Keep this helper as the single policy point for brand asset and home-link paths. The options post-configurator, validator, and resolved identity service all depend on the same rules so path behavior cannot drift between appsettings, environment variables, startup validation, and Razor rendering.

Method

NormalizeTextOrNull

string? NormalizeTextOrNull(string? value)

Trims a text option value and treats blank text as omitted.

Parameters

  • value
    Raw configured text value.

Returns

The trimmed text, or null when the value is null, empty, or whitespace.

Method

NormalizeDisplayName

string NormalizeDisplayName(string? displayName)

Resolves the visible AppSurface Docs display name.

Parameters

  • displayName
    Configured display name.

Returns

The trimmed display name, or AppSurfaceDocsIdentityOptions.DefaultDisplayName when blank.

Method

NormalizeBrowserPathOrNull

string? NormalizeBrowserPathOrNull(string? value)

Normalizes a browser path when it is valid and preserves invalid non-blank text for later validation errors.

Parameters

  • value
    Configured app-root or application-relative browser path.

Returns

A normalized path when valid, the trimmed original value when invalid, or null when blank.

Method

NormalizeCssHexColorOrNull

string? NormalizeCssHexColorOrNull(string? value)

Normalizes a CSS hex color and preserves invalid non-blank text for later validation errors.

Parameters

  • value
    Configured CSS hex color.

Returns

A lower-invariant CSS hex color when valid, the trimmed original value when invalid, or null when blank.

Method

TryNormalizeCssHexColor

bool TryNormalizeCssHexColor(string? value, out string? normalizedColor, out string error)

Validates and normalizes a CSS hex color suitable for the package-owned wordmark style variable.

Parameters

  • value
    Configured color value.
  • normalizedColor
    Lower-invariant color when valid or blank; otherwise null.
  • error
    Validation error message when invalid; otherwise an empty string.

Returns

True when the value is blank, a three-digit hex color, or a six-digit hex color; otherwise false.

Method

TryNormalizeBrowserPath

bool TryNormalizeBrowserPath(string? value, out string? normalizedPath, out string error)

Validates and normalizes an app-root or application-relative browser path.

Parameters

  • value
    Configured path value.
  • normalizedPath
    Normalized path when the value is valid or blank; otherwise null .
  • error
    Validation error message when invalid; otherwise an empty string.

Returns

true when the value is blank, starts with / , or starts with ~/ and does not contain remote URL, data URL, query string, fragment, backslash, or traversal segments; otherwise false .

Type

AppSurfaceDocsHarvestPathPolicySnapshot

Source

Captures the configured harvest path policy and repository VCS ignore policy used for one harvest snapshot.

Remarks

The snapshot keeps VCS ignore parsing stable for a single aggregation pass and exposes only normalized, repository-relative decisions to harvesters through IHarvestPathPolicy . The configured policy is evaluated first, and VCS ignore decisions are applied as an additional exclusion layer with allow-glob restoration for intentionally public ignored content.

Method

EnumerateCandidateFiles

IEnumerable<string> EnumerateCandidateFiles(string rootPath, AppSurfaceDocsHarvestSourceKind sourceKind, string searchPattern, CancellationToken cancellationToken)

Remarks

Traversal is lazy and depth-first using the shared AppSurface Docs harvest filesystem helper. File paths are yielded as absolute paths, directory paths are normalized to forward-slash repository-relative values before pruning, and directory reparse points are skipped to avoid following symlinks or junctions outside the repository. File reparse points are skipped for the same reason, so symlinked files cannot point harvesters at content outside the repository boundary. Cancellation is checked before each directory expansion, so callers can stop large repository walks without waiting for every descendant to be listed. The method throws ArgumentNullException for a null rootPath or searchPattern ; file-system enumeration exceptions are allowed to flow to the harvester so the aggregation layer can report the failure consistently.

Method

GetVcsIgnoreDiagnostics

AppSurfaceDocsHarvestVcsIgnoreDiagnostics GetVcsIgnoreDiagnostics()

Gets repository VCS ignore loading diagnostics for this harvest snapshot.

Returns

VCS ignore status, loaded ignore files, and warning information.

Method

CreateVcsIgnoreHealthDiagnostics

IReadOnlyList<DocHarvestDiagnostic> CreateVcsIgnoreHealthDiagnostics()

Creates health diagnostics that summarize VCS ignore behavior for the snapshot.

Returns

Diagnostics safe for harvest health reporting. Sample paths are redacted before client exposure.

Type

AppSurfaceDocsHarvestPathPolicySnapshotFactory

Source

Creates per-harvest path policy snapshots for a repository root.

Remarks

A new snapshot should be created for each aggregation pass so changes to repository ignore files are observed at the beginning of the next harvest while remaining stable for all harvesters in the current pass.

Method

Create

AppSurfaceDocsHarvestPathPolicySnapshot Create(string repositoryRoot)

Creates a path policy snapshot for the supplied repository root.

Parameters

  • repositoryRoot
    The absolute repository root whose VCS ignore files should be read.

Returns

A snapshot combining configured path rules with repository VCS ignore rules.

Type

DocHarvestContext

Source

Carries repository-scoped harvest dependencies shared by built-in harvesters during one aggregation pass.

Parameters

  • RepositoryRoot
    The absolute repository root that harvesters should scan.
  • PathPolicy
    The path policy snapshot exposed through the harvester path-policy contract.
  • Progress
    The optional safe progress session for one package-owned harvester.

Remarks

The context keeps harvesters on a single policy instance for consistent VCS ignore decisions. Consumers should treat PathPolicy as the authority for traversal and file inclusion, and should not cache the context beyond the aggregation pass that created it.

Type

DocPathResolver

Source

Resolves authored, source, and canonical AppSurface Docs paths against a harvested documentation corpus.

Remarks

AppSurface Docs accepts paths from several authoring surfaces: browser routes, source-relative Markdown metadata, generated canonical paths, and route-prefixed links. This resolver is the shared source of truth for trimming route separators, ignoring lookup fragments when selecting candidate buckets, preserving exact fragment matches when available, and ranking fallback candidates when a fragment-specific page is not present.

Method

Create

DocPathResolver Create(IEnumerable<DocNode> docs)

Builds a resolver for a docs snapshot.

Parameters

  • docs
    The harvested docs whose source and canonical paths should be resolvable.

Returns

A resolver that can match source paths, canonical route paths, and route-relative variants.

Method

Resolve

2 overloads
DocNode? Resolve(string path)

Resolves a path exactly as authored, using AppSurface Docs source and canonical matching rules.

Parameters

  • path
    The authored source or canonical path to resolve.

Returns

The best matching doc node, or null when no harvested doc matches.

DocNode? Resolve(string path, params string[] routeRootPaths)

Resolves a path by preserving authored source-relative matches before stripping known docs route roots from browser-facing inputs.

Parameters

  • path
    The authored or browser-facing path to resolve.
  • routeRootPaths
    Route roots, such as the configured live docs root and the stable /docs root.

Returns

The best matching doc node, or null when neither route-relative variants nor the original path match.

Method

NormalizeLookupPath

string NormalizeLookupPath(string path)

Normalizes a documentation path for lookup by trimming route separators and removing fragment anchors.

Parameters

  • path
    The path to normalize.

Returns

The normalized lookup path.

Method

NormalizeCanonicalPath

string NormalizeCanonicalPath(string path)

Normalizes a documentation path for canonical comparison by trimming route separators while preserving fragments.

Parameters

  • path
    The path to normalize.

Returns

The normalized canonical path.

Method

GetFragment

string? GetFragment(string path)

Extracts a fragment from a documentation path after canonical normalization.

Parameters

  • path
    The path that may contain a fragment anchor.

Returns

The fragment without the leading # , or null when no non-empty fragment exists.

Type

DocRoutePath

Source

Normalizes harvested non-Markdown source paths into legacy browser-facing routes used by AppSurface Docs.

Remarks

A harvested source path is the repository-relative or generated path assigned to a DocNode before AppSurface Docs publishes it. This helper is intentionally narrow: it exists for generated or imported non-Markdown sources such as XML API reference pages, generated JSON or YAML API specs, and imported HTML fragments that still use the historical .html route shape. Markdown documents should use DocRouteIdentityCatalog instead, because that catalog owns clean public routes, redirect aliases, collisions, and reserved-route diagnostics.

Method

BuildCanonicalPath

string BuildCanonicalPath(string sourcePath)

Constructs a legacy browser-facing path for a harvested non-Markdown documentation source path.

Parameters

  • sourcePath
    The harvested source path, optionally including a fragment.

Returns

The legacy docs route path, including the .html suffix used by generated API docs and any original fragment identifier. Markdown public routes are owned by DocRouteIdentityCatalog .

Remarks

Use this method only when a source must keep the generated-docs compatibility contract where Namespaces/Foo.Bar becomes Namespaces/Foo.Bar.html . It trims leading and trailing separators, preserves fragments, normalizes backslashes to slashes, and appends .html unless the final file name already has that suffix. The word "canonical" in the method name refers to this legacy generated-doc route canonicalization; it does not mean the clean Markdown route contract. For authored Markdown pages, callers should query DocRouteIdentityCatalog so explicit canonical_slug , redirect aliases, public-route collisions, and reserved-route checks all remain centralized.

Enum

AppSurfaceDocsResolvedVersionCatalogStatus

Source

Describes how the current host resolved its published-version catalog state.

Remarks

Numeric values are explicit and stable because callers may serialize or persist catalog-resolution state across process boundaries.

Enum

AppSurfaceDocsReleaseArchiveVerificationState

Source

Describes the archive-integrity state resolved for a published AppSurface Docs version.

Remarks

Numeric values are explicit and stable because catalog diagnostics, command output, and downstream consumers may serialize or persist these states outside the current process.

Enum

AppSurfaceDocsHarvestPathDecisionCode

Source

Describes the rule outcome that caused a harvest path decision or trace entry.

Enum

JavaScriptHarvestCandidateStatus

Source

Describes how the built-in JavaScript harvester may treat a file-system candidate before reading or traversal.

Enum

AppSurfaceDocsRichAuthoringKind

Source

Identifies a package-owned rich-authoring directive family.

Enum

PublishedSearchIndexPathRejectionReason

Source

Stable rejection categories for published search-index document path validation.

Remarks

Use enum members for local control flow and PublishedSearchIndexDocumentPathPolicy.ToDiagnosticCode(PublishedSearchIndexPathRejectionReason) for telemetry, log fields, and persisted diagnostics. The policy returns the first matching category in its ordered checks, so a value that is both off-root and reserved reports the earlier root or syntax failure.

Enum

AppSurfaceDocsHarvestRebuildRequestResult

Source

Result of a trusted operator request to rebuild the live AppSurface Docs harvest.

Remarks

The default enum value, 0 , is not a valid rebuild request result. Callers that bind, deserialize, or display unknown values should treat them as "no request result." While a harvest is active, rebuild requests are coalesced so at most one superseding rebuild is queued behind the active run. The numeric member values are part of the public compatibility contract and must not be reordered or renumbered.

Enum

MarkdownDownloadEligibility

Source

Describes whether an inline Markdown source declaration grants protected download eligibility.

Enum

AppSurfaceDocsRouteAliasKind

Source

Identifies why an AppSurface Docs route alias exists.

Enum

AppSurfaceDocsHarvestDefaultExclusionGroup

Source

Enumerates package-defined default exclusion groups used by harvest path policy evaluation.

Remarks

Member names are stable internal configuration IDs consumed by DisabledGroups and AllowGlobs . Do not rename existing members without a migration plan; append new members for new groups.

Enum

AppSurfaceDocsHarvestSourceKind

Source

Identifies the content source type being evaluated by the harvest path policy.