From a8534cb4beac04b087bd67f08d806a1148e49675 Mon Sep 17 00:00:00 2001 From: Joe Shook Date: Sun, 29 Nov 2026 06:48:36 -0800 Subject: [PATCH 01/13] Directory: find UDAP endpoints by probing .well-known/udap NDH STU2 removed the Endpoint extensions the Directory page used to spot UDAP (base-ext-dynamicRegistration) and the dynamic-registration-trust-profile search parameter. Nothing in the IG marks an Endpoint as UDAP any more, so every Endpoint with an http(s) address now gets a UDAP node, resolved by fetching {address}/.well-known/udap. - Probes run in the background, six at a time with a 20 s timeout each; an address shared by several Endpoints is fetched once. The tree updates as each probe finishes. - A response counts as UDAP only when it lists a UDAP version or carries signed_metadata, so an HTML page or OperationOutcome served with 200 does not. Endpoints without UDAP show "No UDAP metadata at ...". - Probing walks the whole tree. Before, only the first level was checked, so Endpoints under an Organization stayed on their spinner. - A duplicate Endpoint no longer stops the rest from being added. - The default Endpoint search is status=active instead of the removed dynamic-registration-trust-profile=udap. - The STU1 SMART and mTLS extensions are still read. Co-Authored-By: Claude Opus 5.5 --- Shared/Pages/Directory.razor | 30 ++++--- Shared/Pages/Directory.razor.cs | 152 ++++++++++++++++++++++---------- 2 files changed, 124 insertions(+), 58 deletions(-) diff --git a/Shared/Pages/Directory.razor b/Shared/Pages/Directory.razor index b22573d..2c3bbef 100644 --- a/Shared/Pages/Directory.razor +++ b/Shared/Pages/Directory.razor @@ -284,19 +284,19 @@ @switch (presenter.Type) { - case "udap": - - - - + case UdapType: + @if (!presenter.IsLoading) + { + - - View Metadata - - + + View Metadata + + + } @if (presenter.Untrusted != null && presenter.Untrusted.Any()) { @@ -330,7 +330,7 @@ @if (presenter.IsLoading) { - (Validating Metadata...) + Probing @presenter.Link ... } else if (@presenter.Untrusted != null && @presenter.Untrusted.Any()) { @@ -353,6 +353,12 @@ break; + case UdapAbsentType: + + No UDAP metadata at @presenter.Link + + break; + case "smart": diff --git a/Shared/Pages/Directory.razor.cs b/Shared/Pages/Directory.razor.cs index 1c5a170..6914534 100644 --- a/Shared/Pages/Directory.razor.cs +++ b/Shared/Pages/Directory.razor.cs @@ -51,6 +51,10 @@ public partial class Directory private string _postSearchString = string.Empty; private List? _postSearchParams; private const string ValidStyle = "pre udap-indent-1"; + private const string UdapType = "udap"; + private const string UdapAbsentType = "udap-absent"; + private const int MaxConcurrentProbes = 6; + private static readonly TimeSpan ProbeTimeout = TimeSpan.FromSeconds(20); private FhirResults _fhirResults = new FhirResults(); private string? _outComeMessage; private List? _entries; @@ -93,7 +97,9 @@ private async T.Task AddSearchParam() } else if (_fhirSearch.ResourceName == "Endpoint") { - searchParam = new FhirSearchParam("dynamic-registration-trust-profile", "", null, "udap"); + // NDH STU2 dropped the dynamic-registration-trust-profile search parameter. UDAP support is found + // by probing each endpoint's .well-known/udap instead, so start from the active endpoints. + searchParam = new FhirSearchParam("status", "", null, "active"); } @@ -350,7 +356,7 @@ private async T.Task BuildTreeviewForEndpoints(IEnumerable endpoi var endpointResource = endpoint.ToPoco(); if (storeChildren.Any(ts => ts.Value?.Id == endpointResource.Id)) { - return; + continue; } var endPointTreeItem = new TreeItemData(endpointResource.Id, endpointResource.Name, $"{endpointResource?.TypeName}/{endpointResource?.Id}"); @@ -358,25 +364,29 @@ private async T.Task BuildTreeviewForEndpoints(IEnumerable endpoi storeChildren.Add(endPointTreeItem); + // NDH STU2 removed the base-ext-dynamicRegistration extension, and nothing else on Endpoint marks it + // as UDAP. Every http(s) endpoint gets a UDAP node that AugmentHandler resolves by probing + // {address}/.well-known/udap. + if (IsHttpAddress(endpointResource.Address)) + { + endpointChildren.Add(new TreeItemData( + id: endpointResource.Id, + name: endpointResource.Name, + resourceReference: $"{endpointResource.TypeName}/{endpointResource.Id}", + icon: Icons.Material.TwoTone.DynamicForm, + iconColor: Color.Default, + link: AppendUdapWellKnown(endpointResource.Address), + type: UdapType + )); + } + + // STU1 extension, still read for directories that carry it. var dynamicEndpointTypes = endpointResource.ToTypedElement().Select( $"extension.where($this.url in 'http://hl7.org/fhir/us/ndh/StructureDefinition/base-ext-dynamicRegistration').descendants().select($this.descendants().coding.code)"); foreach (var dynamicEndpointType in dynamicEndpointTypes) { - if (dynamicEndpointType.Value?.ToString() == "udap") - { - endpointChildren.Add(new TreeItemData( - id: endpointResource.Id, - name: endpointResource.Name, - resourceReference: $"{endpointResource?.TypeName}/{endpointResource?.Id}", - icon: Icons.Material.TwoTone.DynamicForm, - iconColor: Color.Error, - link: AppendUdapWellKnown(endpointResource.Address), - type: dynamicEndpointType.Value?.ToString() - )); - } - if (dynamicEndpointType.Value?.ToString() == "smart") { var results = @@ -445,44 +455,94 @@ await MetadataService.GetSmartMetadata( treeStore.Children = storeChildren; } + /// + /// Probes .well-known/udap for every UDAP node still loading, at any depth of the tree (an Endpoint sits + /// under its Organization or PractitionerRole). Nodes that share an address are probed once. The tree + /// re-renders as each probe finishes. + /// private async T.Task AugmentHandler() { - if (_fhirResults.TreeViewStore.Children != null) + var probesByLink = Flatten(_fhirResults.TreeViewStore.Children) + .Select(item => item.Value) + .OfType() + .Where(entry => entry is { IsLoading: true, Type: UdapType, Link: not null }) + .GroupBy(entry => entry.Link!, StringComparer.OrdinalIgnoreCase) + .ToList(); + + if (probesByLink.Count == 0) { - var tasks = _fhirResults.TreeViewStore.Children.Where(c => - c.Children != null && c.Children.Any()) - .SelectMany(c => c.Children) - .Where(treeItemData => treeItemData.Value != null - && treeItemData.Value.IsLoading - && treeItemData.Value.Type == "udap") - .Select(async treeItemData => - { - var fhirHierarchyEntry = treeItemData.Value; - - if(fhirHierarchyEntry == null) - { - return; - } + return; + } - await T.Task.Yield(); - var results = await MetadataService.GetUdapMetadataVerificationModel( - $"{fhirHierarchyEntry.Link}", null, default); - - if (results == null) - { - return; - } - - fhirHierarchyEntry.IsLoading = false; - fhirHierarchyEntry.UdapMetadata = results; - fhirHierarchyEntry.Untrusted = results.Untrusted; - fhirHierarchyEntry.TokenErrors = results.TokenErrors; - fhirHierarchyEntry.Problems = results.Problems; - }); - await T.Task.WhenAll(tasks); + using var throttle = new SemaphoreSlim(MaxConcurrentProbes); + + await T.Task.WhenAll(probesByLink.Select(async group => + { + await throttle.WaitAsync(); + MetadataVerificationModel? result; + try + { + result = await ProbeUdap(group.Key); + } + finally + { + throttle.Release(); + } + + foreach (var entry in group) + { + ApplyProbeResult(entry, result); + } + + await InvokeAsync(StateHasChanged); + })); + } + + private async T.Task ProbeUdap(string link) + { + using var timeout = new CancellationTokenSource(ProbeTimeout); + try + { + return await MetadataService.GetUdapMetadataVerificationModel(link, null, timeout.Token); + } + catch (OperationCanceledException) + { + return null; } } + private static void ApplyProbeResult(FhirHierarchyEntry entry, MetadataVerificationModel? result) + { + entry.IsLoading = false; + + if (!PublishesUdap(result?.UdapServerMetaData)) + { + entry.Type = UdapAbsentType; + return; + } + + entry.UdapMetadata = result; + entry.Untrusted = result!.Untrusted; + entry.TokenErrors = result.TokenErrors; + entry.Problems = result.Problems; + } + + /// + /// A 200 that is not UDAP metadata (an HTML page, an OperationOutcome) can still deserialize into an empty + /// . Count it as UDAP only when it names a UDAP version or carries signed metadata. + /// + private static bool PublishesUdap(UdapMetadata? metadata) => + metadata != null + && (metadata.UdapVersionsSupported?.Count > 0 || !string.IsNullOrEmpty(metadata.SignedMetadata)); + + private static IEnumerable> Flatten( + IEnumerable>? items) => + items?.SelectMany(item => Flatten(item.Children).Prepend(item)) ?? []; + + private static bool IsHttpAddress(string? address) => + Uri.TryCreate(address, UriKind.Absolute, out var uri) + && (uri.Scheme == Uri.UriSchemeHttps || uri.Scheme == Uri.UriSchemeHttp); + private string? AppendUdapWellKnown(string endpointResourceAddress) { if (!endpointResourceAddress.Contains(UdapConstants.Discovery.DiscoveryEndpoint)) From ee6628c191781376320cd8d136d0f5aa3c7109a9 Mon Sep 17 00:00:00 2001 From: Joe Shook Date: Sun, 29 Nov 2026 07:27:04 -0800 Subject: [PATCH 02/13] Directory probe: don't make each probed Endpoint the session's FHIR server The validated metadata call (GET /Metadata) stores the URL it checks as the session's FHIR server, which Patient Search and the access token follow. The Directory page probes every Endpoint it lists through that call, so after a search the session pointed at whichever Endpoint was probed last, and Patient Search would send the token there. IDiscoveryService.ProbeUdapMetadata validates the same way with probe=true, and the server leaves the session alone. MAUI, which has no server session, uses the interface's default (the usual call). Co-Authored-By: Claude Opus 5.5 --- Client/Services/DiscoveryService.cs | 16 +++++++++++++++- Server/Controllers/MetadataController.cs | 10 ++++++++-- Shared/Pages/Directory.razor.cs | 2 +- Shared/Services/IDiscoveryService.cs | 9 +++++++++ 4 files changed, 33 insertions(+), 4 deletions(-) diff --git a/Client/Services/DiscoveryService.cs b/Client/Services/DiscoveryService.cs index 7e5cf2e..63d61e4 100644 --- a/Client/Services/DiscoveryService.cs +++ b/Client/Services/DiscoveryService.cs @@ -36,7 +36,15 @@ public DiscoveryService(HttpClient httpClient, ILogger logger) /// /// /// - public async Task GetUdapMetadataVerificationModel(string metadataUrl, string? community, CancellationToken token) + public Task GetUdapMetadataVerificationModel(string metadataUrl, string? community, CancellationToken token) => + GetUdapMetadataVerificationModel(metadataUrl, community, probe: false, token); + + /// + public Task ProbeUdapMetadata(string metadataUrl, CancellationToken token) => + GetUdapMetadataVerificationModel(metadataUrl, null, probe: true, token); + + private async Task GetUdapMetadataVerificationModel( + string metadataUrl, string? community, bool probe, CancellationToken token) { try { @@ -46,6 +54,12 @@ public DiscoveryService(HttpClient httpClient, ILogger logger) { var udapMetadataUrl = $"Metadata?metadataUrl={metadataUrl}"; + if (probe) + { + // Validate without making this URL the session's FHIR server. + udapMetadataUrl += "&probe=true"; + } + if (community != null) { udapMetadataUrl += $"&{UdapConstants.Community}={community}"; diff --git a/Server/Controllers/MetadataController.cs b/Server/Controllers/MetadataController.cs index 6bc9502..3caeb7c 100644 --- a/Server/Controllers/MetadataController.cs +++ b/Server/Controllers/MetadataController.cs @@ -49,7 +49,9 @@ public MetadataController(IUdapClient udapClient, HttpClient httpClient, IOption // get fully validated metadata from .well-known/udap [HttpGet] - public async Task Get([FromQuery] string metadataUrl, [FromQuery] string community) + // probe=true (the Directory page checking each Endpoint) validates without making metadataUrl the session's + // FHIR server, which Patient Search and the access token follow. + public async Task Get([FromQuery] string metadataUrl, [FromQuery] string community, [FromQuery] bool probe = false) { var anchorString = HttpContext.Session.GetString(UdapEdConstants.UDAP_ANCHOR_CERTIFICATE); @@ -83,7 +85,11 @@ public async Task Get([FromQuery] string metadataUrl, [FromQuery] // Show the metadata even when it failed validation, next to the problems found. The UdapClient keeps // only validated metadata in UdapServerMetadata; the response carries what was downloaded. result.UdapServerMetaData = _udapClient.UdapServerMetadata ?? response.UnvalidatedMetadata; - HttpContext.Session.SetString(UdapEdConstants.BASE_URL, metadataUrl); + + if (!probe) + { + HttpContext.Session.SetString(UdapEdConstants.BASE_URL, metadataUrl); + } return Ok(result); } diff --git a/Shared/Pages/Directory.razor.cs b/Shared/Pages/Directory.razor.cs index 6914534..4d5a77e 100644 --- a/Shared/Pages/Directory.razor.cs +++ b/Shared/Pages/Directory.razor.cs @@ -503,7 +503,7 @@ await T.Task.WhenAll(probesByLink.Select(async group => using var timeout = new CancellationTokenSource(ProbeTimeout); try { - return await MetadataService.GetUdapMetadataVerificationModel(link, null, timeout.Token); + return await MetadataService.ProbeUdapMetadata(link, timeout.Token); } catch (OperationCanceledException) { diff --git a/Shared/Services/IDiscoveryService.cs b/Shared/Services/IDiscoveryService.cs index b5faa28..eea77c5 100644 --- a/Shared/Services/IDiscoveryService.cs +++ b/Shared/Services/IDiscoveryService.cs @@ -16,6 +16,15 @@ namespace UdapEd.Shared.Services; public interface IDiscoveryService { Task GetUdapMetadataVerificationModel(string metadataUrl, string? community, CancellationToken token); + + /// + /// Fetches and validates UDAP metadata like , without making + /// the session's FHIR server. The Directory page probes every Endpoint it lists; + /// the session's server (and the access token sent to it) must stay the one the user chose. + /// Apps without a server session fetch the metadata the usual way. + /// + Task ProbeUdapMetadata(string metadataUrl, CancellationToken token) => + GetUdapMetadataVerificationModel(metadataUrl, null, token); Task GetCapabilityStatement(string url, CancellationToken token); Task GetSmartMetadata(string metadataUrl, CancellationToken token); Task UploadAnchorCertificate(string certBytes); From 75ff6e4771655d891af57cf41c88d8afc41981f7 Mon Sep 17 00:00:00 2001 From: Joe Shook Date: Sun, 29 Nov 2026 08:15:11 -0800 Subject: [PATCH 03/13] Directory: default to the NDH reference server, which allows anonymous search ndh-server.fast.hl7.org/fhir is the NDH RI used at Connectathon 43 and answers searches without a token. national-directory.fast.hl7.org/fhir returns 401 Bearer, so it needs a UDAP token first. Co-Authored-By: Claude Opus 5.5 --- Shared/Pages/Directory.razor.cs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/Shared/Pages/Directory.razor.cs b/Shared/Pages/Directory.razor.cs index 4d5a77e..0eebae6 100644 --- a/Shared/Pages/Directory.razor.cs +++ b/Shared/Pages/Directory.razor.cs @@ -46,7 +46,9 @@ public partial class Directory [Inject] public required IDialogService DialogService { get; set; } [Inject] public HtmlSanitizer HtmlSanitizer { get; set; } private ErrorBoundary? _errorBoundary; - private readonly FhirSearch _fhirSearch = new(){BaseUrl = "https://national-directory.fast.hl7.org/fhir"}; + // The NDH reference implementation used at Connectathon 43 (Sept 2026): open to anonymous search. + // national-directory.fast.hl7.org/fhir answers searches with 401 Bearer, so it needs a UDAP token first. + private readonly FhirSearch _fhirSearch = new(){BaseUrl = "https://ndh-server.fast.hl7.org/fhir"}; private string _searchString = string.Empty; private string _postSearchString = string.Empty; private List? _postSearchParams; From 0ab2a3642cd23054213af0deea15acbac79375cc Mon Sep 17 00:00:00 2001 From: Joe Shook Date: Sun, 29 Nov 2026 08:28:28 -0800 Subject: [PATCH 04/13] Directory: pick-list of known directories, CMS NPD by default; show Organization names - The Base Url field offers the CMS National Provider Directory (default), the HL7 NDH reference server and the HL7 FAST directory, with a note on each; any other URL can still be typed. - The result list showed each Organization's id twice: the name and id were passed to TreeItemData(id, name) in the wrong order. Co-Authored-By: Claude Opus 5.5 --- Shared/Pages/Directory.razor | 10 +++++++++- Shared/Pages/Directory.razor.cs | 26 ++++++++++++++++++++++---- 2 files changed, 31 insertions(+), 5 deletions(-) diff --git a/Shared/Pages/Directory.razor b/Shared/Pages/Directory.razor index 2c3bbef..b553615 100644 --- a/Shared/Pages/Directory.razor +++ b/Shared/Pages/Directory.razor @@ -14,7 +14,15 @@ - + diff --git a/Shared/Pages/Directory.razor.cs b/Shared/Pages/Directory.razor.cs index 0eebae6..c179825 100644 --- a/Shared/Pages/Directory.razor.cs +++ b/Shared/Pages/Directory.razor.cs @@ -46,9 +46,26 @@ public partial class Directory [Inject] public required IDialogService DialogService { get; set; } [Inject] public HtmlSanitizer HtmlSanitizer { get; set; } private ErrorBoundary? _errorBoundary; - // The NDH reference implementation used at Connectathon 43 (Sept 2026): open to anonymous search. - // national-directory.fast.hl7.org/fhir answers searches with 401 Bearer, so it needs a UDAP token first. - private readonly FhirSearch _fhirSearch = new(){BaseUrl = "https://ndh-server.fast.hl7.org/fhir"}; + /// + /// Directories known to answer NDH searches, offered in the Base Url field (any other URL can be typed). + /// The first is the default. Checked 2026-11-29. + /// + private static readonly IReadOnlyList<(string Url, string Note)> KnownDirectories = + [ + ("https://directory.cms.gov/fhir", "CMS National Provider Directory (anonymous search)"), + ("https://ndh-server.fast.hl7.org/fhir", "HL7 NDH reference server, Connectathon 43 (anonymous search)"), + ("https://national-directory.fast.hl7.org/fhir", "HL7 FAST directory (needs a UDAP B2B token)") + ]; + + private readonly FhirSearch _fhirSearch = new(){BaseUrl = KnownDirectories[0].Url}; + + private T.Task> SearchKnownDirectories(string? text, CancellationToken token) => + T.Task.FromResult(KnownDirectories.Select(d => d.Url) + .Where(u => string.IsNullOrWhiteSpace(text) || u == _fhirSearch.BaseUrl + || u.Contains(text, StringComparison.OrdinalIgnoreCase))); + + private static string? DirectoryNote(string? url) => + KnownDirectories.FirstOrDefault(d => string.Equals(d.Url, url, StringComparison.OrdinalIgnoreCase)).Note; private string _searchString = string.Empty; private string _postSearchString = string.Empty; private List? _postSearchParams; @@ -309,7 +326,8 @@ private async T.Task SearchHandler(FhirResultModel result var domainResource = referenceContext.ToPoco(); var nameElement = domainResource.ToTypedElement().Children("name").FirstOrDefault(); var resource = referenceContext.ToPoco(); - var orgEntry = new TreeItemData(nameElement?.Value?.ToString() ?? resource?.Id ?? "Unknown", resource?.Id ?? "Unknown", $"{resource?.TypeName}/{resource?.Id}"); + // TreeItemData takes (id, name): the list shows the name, falling back to the id. + var orgEntry = new TreeItemData(resource?.Id ?? "Unknown", nameElement?.Value?.ToString() ?? resource?.Id ?? "Unknown", $"{resource?.TypeName}/{resource?.Id}"); treeChildren.Add(orgEntry); } From b9710cd86e44ea6876504ebea2af22b130909cad Mon Sep 17 00:00:00 2001 From: Joe Shook Date: Sun, 29 Nov 2026 12:15:12 -0800 Subject: [PATCH 05/13] Directory: search what the directory supports, link endpoints both ways, page results Searches that worked against the CMS NPD directly failed or showed the wrong endpoints in UdapEd: - Parameters and includes came from the bundled NDH IG CapabilityStatement only. They now come from the directory's /metadata, topped up with the IG's (CMS honors _include=Organization:endpoint without advertising it). Parameter names accept free text. - Endpoints were attached only through Endpoint.managingOrganization, which CMS never sets, so they landed under the wrong Organization or none. The tree now resolves Organization.endpoint (and PractitionerRole.endpoint, ...) forward and managingOrganization backward, shows a shared endpoint under every Organization that names it, and lists included Practitioners and Organizations under each match. - The GET box accepts a pasted example: a query, Resource?query or a full URL. - Values are percent-encoded; _count is set; Next/Previous follow Bundle links. - POST search splits form pairs on the first '=' only. Co-Authored-By: Claude Opus 5.5 --- Server/Controllers/FhirController.cs | 4 +- Shared/Pages/Directory.razor | 750 +++++++++----------- Shared/Pages/Directory.razor.cs | 721 ++++++++++--------- Shared/Search/DirectoryBundle.cs | 240 +++++++ Shared/Search/DirectoryCapabilities.cs | 134 ++++ Shared/Search/DirectoryQuery.cs | 109 +++ _tests/UtilityTests/DirectorySearchTests.cs | 186 +++++ 7 files changed, 1373 insertions(+), 771 deletions(-) create mode 100644 Shared/Search/DirectoryBundle.cs create mode 100644 Shared/Search/DirectoryCapabilities.cs create mode 100644 Shared/Search/DirectoryQuery.cs create mode 100644 _tests/UtilityTests/DirectorySearchTests.cs diff --git a/Server/Controllers/FhirController.cs b/Server/Controllers/FhirController.cs index 3fde17b..2c26132 100644 --- a/Server/Controllers/FhirController.cs +++ b/Server/Controllers/FhirController.cs @@ -409,8 +409,8 @@ public async Task PostSearch([FromBody] SearchForm searchForm) foreach (var pair in searchForm.FormUrlEncoded) { - var item = pair.Split('='); - searchParams.Add(item[0], item[1]); + var item = pair.Split('=', 2); + searchParams.Add(item[0], item.Length > 1 ? item[1] : string.Empty); } var bundle = await fhirClient.SearchUsingPostAsync(searchParams, searchForm.Resource); diff --git a/Shared/Pages/Directory.razor b/Shared/Pages/Directory.razor index b553615..8f664cc 100644 --- a/Shared/Pages/Directory.razor +++ b/Shared/Pages/Directory.razor @@ -7,467 +7,383 @@ - - - - - - - - - - - - @foreach (var resource in _supportedResources) - { - @resource - } - - - - - - - - - Search parameter - - - - - - - - - - - - - - @if (_fhirSearch.SearchParams.Any()) - { - - - Search Parameter - Modifier - Value - - - - - - - - @{ - var paramDefs = CapabilityLookup.SearchParamMap.SingleOrDefault(m => m.Resource == _fhirSearch.ResourceName)?.ParamDefinitions; - } - @if (paramDefs != null) - { - foreach (var paramDef in paramDefs) - { - @paramDef.Code - } - } - - - - - @if (@context.Name != "active" && @context.Name != "partof") - { - - - @foreach (SearchModifier item in SearchModifierValueSet.SearchModifiers) - { - @item.Name - } - - } - - - @if (context.ModifierName != "Missing") - { - @if (@context.Name != "active") - { - - } - else - { - @(@context.Value) - } - } - - - - - - - - - } - - - - - - - - Includes - - - @foreach (var include in CapabilityLookup.IncludeMap.Where(m => m.Key == _fhirSearch.ResourceName).SelectMany(m => m.Value)) - { - if (!_fhirSearch.Includes.ContainsKey(include)) - { - _fhirSearch.Includes.Add(include, false); - } - - } - - - - - - - - - Reverse Includes - - - @foreach (var revInclude in CapabilityLookup.ReverseIncludeMap.Where(m => m.Key == _fhirSearch.ResourceName).SelectMany(m => m.Value)) + + + + + + + + + @foreach (var resource in Resources) + { + @resource + } + + + + + + + + Search parameters + + + @if (_fhirSearch.SearchParams.Any()) + { + + + Parameter + Modifier + Value + + + + + + + + + @foreach (SearchModifier item in SearchModifierValueSet.SearchModifiers) { - if (!_fhirSearch.RevIncludes.ContainsKey(revInclude)) - { - _fhirSearch.RevIncludes.Add(revInclude, false); - } - - + @item.Name } - - - - - - - - - - - - - - @($"GET {_fhirSearch.BaseUrl}/{_fhirSearch.ResourceName}") - - - - - - @if (IsSearching) - { - - Searching - } - else - { - Search - } - - - - - - - - @($"POST {_fhirSearch.BaseUrl}/{_fhirSearch.ResourceName}/_search") - - - - - - @if (IsSearching) - { - - Searching - } - else - { - Search - } - - - - - - - - - - - - Get - + + + + + + + + + + + } + + + + + + Includes + + + @foreach (var include in _capabilities.IncludesFor(_fhirSearch.ResourceName)) + { + + } + + + + + + + + + Reverse Includes + + + @foreach (var revInclude in _capabilities.RevIncludesFor(_fhirSearch.ResourceName)) + { + + } + + + + + + @CapabilitiesNote + + + + - + + + + + + @($"GET {_fhirSearch.BaseUrl}/{_fhirSearch.ResourceName}") + + + + + @if (_isSearching) + { + + Searching + } + else + { + Search + } + + + + + + + + @($"POST {_fhirSearch.BaseUrl}/{_fhirSearch.ResourceName}/_search") + + + + + @if (_isSearching) + { + + Searching + } + else + { + Search + } + + + + + + - + + @if (_outComeMessage != null) { - @(new MarkupString(_outComeMessage)) + @(new MarkupString(_outComeMessage)) } @if (!_fhirResults.RawFhir.IsNullOrEmpty()) { - - - - @* @if (_fhirResults.Entries != null) *@ - @* { *@ - @* @foreach (var entry in _fhirResults.Entries) *@ - @* { *@ - @* *@ - @*
@_fhirJsonSerializer.SerializeToString(entry)
*@ - @*
*@ - @* } *@ - @* } *@ - - @_fhirSearch.ResourceName List - - + + + + @_fhirSearch.ResourceName + @_fhirResults.Summary + + @if (_fhirResults.Bundle?.FirstUrl is { } first && _fhirResults.Bundle.PreviousUrl != null) + { + First + } + @if (_fhirResults.Bundle?.PreviousUrl is { } previous) + { + Previous + } + @if (_fhirResults.Bundle?.NextUrl is { } next) + { + Next + } + + + @if (_fhirResults.TreeViewStore.Count == 0) + { + No matches. + } + + @{ var presenter = item.Value!; } - + - - - @if (presenter.Link == null) + + @switch (presenter.Type) { - @($"{presenter.Name} ({presenter.ResourceReference})") - } - else - { - - @switch (presenter.Type) - { - case UdapType: - - @if (!presenter.IsLoading) - { - + case ResourceType: + @presenter.Name + @if (presenter.Detail != null) + { + @presenter.Detail + } + @presenter.ResourceReference + break; + + case RelatedType: + + @presenter.Detail: @presenter.Name + @presenter.ResourceReference + break; + + case UnresolvedType: + + + @presenter.ResourceReference is not in these results. Tick the endpoint include to fetch it. + + break; + + case EndpointType: + + @presenter.Name + @if (!string.IsNullOrEmpty(presenter.Detail)) + { + @presenter.Detail + } + @presenter.ResourceReference + break; - - View Metadata - - - } + case UdapType: + @if (presenter.IsLoading) + { + + Probing @presenter.Link ... + } + else + { + + + View UDAP metadata + + @if (presenter.Untrusted != null && presenter.Untrusted.Any()) { - - @foreach (string note in presenter.Untrusted) - { -
  • @note
  • - } -
    - } - @if (presenter.TokenErrors != null && presenter.TokenErrors.Any()) - { - - @foreach (string note in presenter.TokenErrors) - { -
  • @note
  • - } -
    - } - @if (presenter.Problems != null && presenter.Problems.Any()) - { - - @foreach (string note in presenter.Problems) - { -
  • @note
  • - } -
    - } - - - @if (presenter.IsLoading) - { - - Probing @presenter.Link ... - } - else if (@presenter.Untrusted != null && @presenter.Untrusted.Any()) - { - Load UDAP Trust anchor - + StartIcon="@Icons.Material.Filled.Upload">Load UDAP Trust anchor } else { - Dynamically register with UDAP - + } - - break; - - case UdapAbsentType: - - No UDAP metadata at @presenter.Link - - break; - - case "smart": - - - - - - - SMART: @($" {presenter.Name} (Endpoint/{presenter.Id})") - - - - - View Metadata - + } + break; + + case UdapAbsentType: + No UDAP metadata at @presenter.Link + break; + + case "smart": + + + View SMART configuration + + + break; + + case "x509-mtls-certificate": + + @presenter.MtlsServerCertificate?.TrimForDisplay(30, "...") + @if (presenter.Untrusted != null && presenter.Untrusted.Any()) + { + Load mTLS Trust Anchor + } + else + { + Search + - break; - - case "x509-mtls-certificate": - - - - - - - - mTLS: @($" {presenter.Name} (Endpoint/{presenter.Id})") - - - - @presenter.MtlsServerCertificate?.TrimForDisplay(30, "...") - - @if (presenter.Untrusted != null && presenter.Untrusted.Any()) - { - - - - @foreach (string note in presenter.Untrusted) - { - @note - } - - - - Load mTls Trust Anchor - - } - else - { - Search - - - } - - break; - - default: - - @presenter.Type: @($" {presenter.Name} (Endpoint/{presenter.Id})") - - break; + } + break; - } + default: + @presenter.Type: @presenter.Name (@presenter.ResourceReference) + break; } -
    -
    + @{ + var alerts = new[] + { + (Severity.Error, presenter.Untrusted), + (Severity.Error, presenter.TokenErrors), + (Severity.Info, presenter.Problems) + }; + } + @foreach (var (severity, notes) in alerts) + { + @if (notes != null && notes.Any()) + { + + @foreach (var note in notes) + { +
  • @note
  • + } +
    + } + } +
    -
    -
    - - - - -
    +
    + + + + } - - - - +
                 @ex.Message
    -      
    +
    - \ No newline at end of file + diff --git a/Shared/Pages/Directory.razor.cs b/Shared/Pages/Directory.razor.cs index c179825..1e7b9d3 100644 --- a/Shared/Pages/Directory.razor.cs +++ b/Shared/Pages/Directory.razor.cs @@ -2,7 +2,7 @@ // /* // Authors: // Joseph Shook Joseph.Shook@Surescripts.com -// +// // See LICENSE in the project root for license information. // */ #endregion @@ -20,7 +20,6 @@ using Udap.Common.Extensions; #pragma warning disable SDK0001 // ToTypedElement is experimental in Firely SDK 6 -#pragma warning disable SDK0002 // ToScopedNode is experimental in Firely SDK 6 using Udap.Model; using UdapEd.Shared.Components; using UdapEd.Shared.Extensions; @@ -44,8 +43,9 @@ public partial class Directory [Inject] IMutualTlsService MtlsService { get; set; } = null!; [Inject] private ICapabilityLookup CapabilityLookup { get; set; } = null!; [Inject] public required IDialogService DialogService { get; set; } - [Inject] public HtmlSanitizer HtmlSanitizer { get; set; } + [Inject] public HtmlSanitizer HtmlSanitizer { get; set; } = null!; private ErrorBoundary? _errorBoundary; + /// /// Directories known to answer NDH searches, offered in the Base Url field (any other URL can be typed). /// The first is the default. Checked 2026-11-29. @@ -57,7 +57,36 @@ public partial class Directory ("https://national-directory.fast.hl7.org/fhir", "HL7 FAST directory (needs a UDAP B2B token)") ]; - private readonly FhirSearch _fhirSearch = new(){BaseUrl = KnownDirectories[0].Url}; + private const int DefaultPageSize = 20; + private const string ValidStyle = "pre udap-indent-1"; + private const string ResourceType = "resource"; + private const string RelatedType = "related"; + private const string EndpointType = "endpoint"; + private const string UnresolvedType = "unresolved"; + private const string UdapType = "udap"; + private const string UdapAbsentType = "udap-absent"; + private const int MaxConcurrentProbes = 6; + private static readonly TimeSpan ProbeTimeout = TimeSpan.FromSeconds(20); + + private readonly FhirSearch _fhirSearch = new() + { + BaseUrl = KnownDirectories[0].Url, + ResourceName = "Organization", + ResultCountPerPage = DefaultPageSize + }; + + private DirectoryCapabilities _igCapabilities = new(); + private DirectoryCapabilities _capabilities = new(); + private string? _capabilitiesLoadedFor; + private string _searchString = string.Empty; + private string _postSearchString = string.Empty; + private List? _postSearchParams; + private FhirResults _fhirResults = new(); + private string? _outComeMessage; + private bool _isSearching; + + private IReadOnlyList Resources => + _capabilities.Resources.Count > 0 ? _capabilities.Resources : DirectoryCapabilities.DefaultResources; private T.Task> SearchKnownDirectories(string? text, CancellationToken token) => T.Task.FromResult(KnownDirectories.Select(d => d.Url) @@ -66,38 +95,19 @@ private T.Task> SearchKnownDirectories(string? text, Cancell private static string? DirectoryNote(string? url) => KnownDirectories.FirstOrDefault(d => string.Equals(d.Url, url, StringComparison.OrdinalIgnoreCase)).Note; - private string _searchString = string.Empty; - private string _postSearchString = string.Empty; - private List? _postSearchParams; - private const string ValidStyle = "pre udap-indent-1"; - private const string UdapType = "udap"; - private const string UdapAbsentType = "udap-absent"; - private const int MaxConcurrentProbes = 6; - private static readonly TimeSpan ProbeTimeout = TimeSpan.FromSeconds(20); - private FhirResults _fhirResults = new FhirResults(); - private string? _outComeMessage; - private List? _entries; - private FhirJsonSerializer _fhirJsonSerializer = new FhirJsonSerializer(); -/// -/// Hl7.Fhir.Model.ModelInfo.SupportedResources is a source of truth for Resource names -/// -private readonly List _supportedResources = new List() - { - "Practitioner", "PractitionerRole", "Organization", "OrganizationAffiliation", - "InsurancePlan", "Endpoint", "Location" - }; + private string CapabilitiesNote => + _capabilities.Source != null + ? $"Parameters and includes from {_capabilities.Source}, plus the NDH IG's." + : "Parameters and includes from the NDH IG (the directory's CapabilityStatement could not be read)."; - /// - /// Method invoked when the component is ready to start, having received its - /// initial parameters from its parent in the render tree. - /// Override this method if you will perform an asynchronous operation and - /// want the component to refresh when that operation is completed. - /// - /// A representing any asynchronous operation. protected override async T.Task OnInitializedAsync() { await CapabilityLookup.Build(); + _igCapabilities = DirectoryCapabilities.From(CapabilityLookup); + _capabilities = _igCapabilities; + BuildSearch(); + await LoadDirectoryCapabilities(); await base.OnInitializedAsync(); } @@ -106,383 +116,397 @@ protected override void OnParametersSet() _errorBoundary?.Recover(); } - private async T.Task AddSearchParam() + private async T.Task BaseUrlChanged() + { + await LoadDirectoryCapabilities(); + BuildSearch(); + } + + /// + /// Reads the directory's CapabilityStatement so the page offers the parameters and includes that directory + /// supports. Falls back to the NDH IG's when /metadata cannot be read. + /// + private async T.Task LoadDirectoryCapabilities() { - var searchParam = new FhirSearchParam(); + var baseUrl = _fhirSearch.BaseUrl?.Trim().TrimEnd('/'); - if (_fhirSearch.ResourceName == "Organization") + if (string.Equals(baseUrl, _capabilitiesLoadedFor, StringComparison.OrdinalIgnoreCase)) { - searchParam = new FhirSearchParam("name", "", null, "FhirLabsOrg"); + return; } - else if (_fhirSearch.ResourceName == "Endpoint") + + _capabilitiesLoadedFor = baseUrl; + _capabilities = _igCapabilities; + + if (!IsHttpAddress(baseUrl)) { - // NDH STU2 dropped the dynamic-registration-trust-profile search parameter. UDAP support is found - // by probing each endpoint's .well-known/udap instead, so start from the active endpoints. - searchParam = new FhirSearchParam("status", "", null, "active"); + return; } - - if (_fhirSearch.SearchParams.Any()) + try { - var paramLookups = CapabilityLookup.SearchParamMap - .Where(m => m.Resource == _fhirSearch.ResourceName) - .SelectMany(s => s.ParamDefinitions) - .ToList(); + var result = await FhirService.Get($"{baseUrl}/metadata"); - if (!paramLookups.Any()) + if (result.Result is CapabilityStatement capabilityStatement + && string.Equals(baseUrl, _capabilitiesLoadedFor, StringComparison.OrdinalIgnoreCase)) { - return; + _capabilities = DirectoryCapabilities.From(capabilityStatement, $"{baseUrl}/metadata") + .MergedWith(_igCapabilities); } + } + catch (Exception) + { + // Keep the NDH IG capabilities. + } - foreach (var param in paramLookups) - { - if (_fhirSearch.SearchParams.Any(pl => pl.Name == param.Code)) - { - continue; - } - - searchParam.Name = param.Code!; - searchParam.ModifierName = SearchModifierValueSet.SearchModifiers.First().Name; - searchParam.Modifier = SearchModifierValueSet.SearchModifiers.First().Value; - if (searchParam.Name == "active") - { - searchParam.Value = "true"; - } - else if(searchParam.Value != "FhirLabsOrg") - { - searchParam.Value = string.Empty; - } - - break; - } + if (!Resources.Contains(_fhirSearch.ResourceName)) + { + _fhirSearch.ResourceName = Resources.FirstOrDefault() ?? string.Empty; + _fhirSearch.ResetParameters(); } - searchParam.Id = _fhirSearch.SearchParams.Any() ? _fhirSearch.SearchParams.Max(sp => sp.Id) + 1 : 0; - _fhirSearch.SearchParams.Add(searchParam); + StateHasChanged(); + } - await T.Task.Delay(1); + private void ResourceChanged() + { + _fhirSearch.ResetParameters(); BuildSearch(); } + private T.Task> SearchParamNames(string? text, CancellationToken token) => + T.Task.FromResult(_capabilities.SearchParamsFor(_fhirSearch.ResourceName) + .Where(code => string.IsNullOrWhiteSpace(text) || code.Contains(text, StringComparison.OrdinalIgnoreCase))); + + private void AddSearchParam() + { + var used = _fhirSearch.SearchParams.Select(p => p.Name).ToHashSet(); + var name = DefaultParam(_fhirSearch.ResourceName) is { } preferred && !used.Contains(preferred.Name) + ? preferred + : (_capabilities.SearchParamsFor(_fhirSearch.ResourceName).FirstOrDefault(code => !used.Contains(code)) ?? string.Empty, + null); + + _fhirSearch.SearchParams.Add(new FhirSearchParam(name.Name, string.Empty, null, name.Value ?? string.Empty) + { + Id = _fhirSearch.SearchParams.Count == 0 ? 0 : _fhirSearch.SearchParams.Max(sp => sp.Id) + 1 + }); + + BuildSearch(); + } + + /// The first parameter worth offering per resource. + private static (string Name, string? Value)? DefaultParam(string resource) => resource switch + { + "Organization" or "Practitioner" or "Location" or "HealthcareService" or "InsurancePlan" => ("name", null), + // NDH STU2 dropped the dynamic-registration-trust-profile search parameter. UDAP support is found by + // probing each endpoint's .well-known/udap, so start from the FHIR endpoints. + "Endpoint" => ("connection-type", "hl7-fhir-rest"), + _ => null + }; + private void DeleteParam(FhirSearchParam fhirSearchParam) { - _fhirSearch.SearchParams?.Remove(fhirSearchParam); + _fhirSearch.SearchParams.Remove(fhirSearchParam); BuildSearch(); - StateHasChanged(); } - - private void ActiveModifierChanged(bool obj) + + private static bool IncludeChecked(Dictionary map, string key) => map.GetValueOrDefault(key); + + private void SetInclude(Dictionary map, string key, bool value) { + map[key] = value; BuildSearch(); } private void BuildSearch() { - _searchString = string.Empty; - _postSearchString = string.Empty; - var queryParameters = new List(); + var parameters = _fhirSearch.SearchParams + .Select(p => (Name: p.Name ?? string.Empty, + Modifier: SearchModifierValueSet.SearchModifiers.Find(sm => sm.Name == p.ModifierName)?.Value, + p.Value)) + .ToList(); + var includes = _fhirSearch.Includes.Where(i => i.Value).Select(i => i.Key).ToList(); + var revIncludes = _fhirSearch.RevIncludes.Where(i => i.Value).Select(i => i.Key).ToList(); + + _searchString = DirectoryQuery.Build(parameters, includes, revIncludes, _fhirSearch.ResultCountPerPage); + + // The POST form carries raw values: the server form-encodes them. + _postSearchParams = parameters + .Where(p => !string.IsNullOrWhiteSpace(p.Name)) + .Select(p => $"{(string.IsNullOrEmpty(p.Modifier) ? p.Name : $"{p.Name}:{p.Modifier}")}={p.Value}") + .Concat(includes.Select(i => $"_include={i}")) + .Concat(revIncludes.Select(i => $"_revinclude={i}")) + .Concat(_fhirSearch.ResultCountPerPage > 0 ? [$"_count={_fhirSearch.ResultCountPerPage}"] : []) + .ToList(); + _postSearchString = string.Join("\n", _postSearchParams); + } - foreach (var param in _fhirSearch.SearchParams) + private void PageSizeChanged(int size) + { + _fhirSearch.ResultCountPerPage = size; + BuildSearch(); + } + + private void BuildManualPostSearch(string text) + { + _postSearchParams = text.Split('\n', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries).ToList(); + } + + /// + /// The GET box takes a query, Resource?query or a full URL pasted from a directory's documentation. + /// A pasted base URL or resource replaces the page's. + /// + private async T.Task ResolveGetUrl() + { + var parsed = DirectoryQuery.Parse(_searchString); + + if (parsed.BaseUrl != null + && !string.Equals(parsed.BaseUrl, _fhirSearch.BaseUrl?.TrimEnd('/'), StringComparison.OrdinalIgnoreCase)) { - var modifier = SearchModifierValueSet.SearchModifiers.Find(sm => sm.Name == param.ModifierName)?.Value; - queryParameters.Add($"{param.Name}{modifier.Prefix(":")}={param.Value}"); - + _fhirSearch.BaseUrl = parsed.BaseUrl; + await LoadDirectoryCapabilities(); } - foreach (var include in _fhirSearch.Includes.Where(i => i.Value)) + if (parsed.ResourceName != null && parsed.ResourceName != _fhirSearch.ResourceName) { - queryParameters.Add($"_include={include.Key}"); + // The parameter table described the old resource; the pasted query is what runs. + _fhirSearch.ResourceName = parsed.ResourceName; + _fhirSearch.ResetParameters(); } - foreach (var revInclude in _fhirSearch.RevIncludes.Where(i => i.Value)) + _searchString = parsed.Query; + + if (string.IsNullOrWhiteSpace(_fhirSearch.BaseUrl) || string.IsNullOrWhiteSpace(_fhirSearch.ResourceName)) { - queryParameters.Add($"_revinclude={revInclude.Key}"); + _outComeMessage = "Pick a directory base URL and a resource, or paste a full search URL."; + return null; } - _searchString = string.Join('&', queryParameters); - _postSearchString = string.Join("\n", queryParameters); - _postSearchParams = queryParameters; - + return DirectoryQuery.Url(_fhirSearch.BaseUrl, _fhirSearch.ResourceName, parsed.Query); } - private void BuildManualGetSearch(string obj) + private async T.Task SearchGet() { - _searchString = obj; - } + var url = await ResolveGetUrl(); - private void BuildManualPostSearch(string obj) - { - _postSearchParams = obj.Split("\n").ToList(); + if (url != null) + { + await RunSearch(() => FhirService.SearchGet(url)); + } } - private bool IsSearching = false; - - private async T.Task SearchGet() - { - IsSearching = true; - try + private T.Task SearchPost() => + RunSearch(() => FhirService.SearchPost(new SearchForm { - _fhirResults = new FhirResults(); + Url = _fhirSearch.BaseUrl, + Resource = _fhirSearch.ResourceName, + FormUrlEncoded = _postSearchParams ?? [] + })); - StateHasChanged(); - await T.Task.Delay(100); + /// Follows a Bundle paging link (next, previous, first) exactly as the server gave it. + private T.Task GoToPage(string url) => RunSearch(() => FhirService.SearchGet(url)); - var result = - await FhirService.SearchGet($" {_fhirSearch.BaseUrl}/{_fhirSearch.ResourceName}?{_searchString}"); - await SearchHandler(result); - StateHasChanged(); - await AugmentHandler(); - } - finally - { - IsSearching = false; - } - } - - private async T.Task SearchPost() + private async T.Task RunSearch(Func>> search) { - IsSearching = true; + _isSearching = true; + _fhirResults = new FhirResults(); + _outComeMessage = null; + StateHasChanged(); + try { - _fhirResults = new FhirResults(); - - StateHasChanged(); - await T.Task.Delay(100); - - var formSearch = new SearchForm() - { - Url = _fhirSearch.BaseUrl, - Resource = _fhirSearch.ResourceName, - FormUrlEncoded = _postSearchParams - }; - - var result = await FhirService.SearchPost(formSearch); - await SearchHandler(result); - StateHasChanged(); - await AugmentHandler(); + await SearchHandler(await search()); + } + catch (Exception ex) + { + _outComeMessage = HtmlSanitizer.Sanitize(ex.Message); } finally { - IsSearching = false; + _isSearching = false; } + + StateHasChanged(); + await AugmentHandler(); } - private async T.Task SearchHandler(FhirResultModel result) + private async T.Task SearchHandler(FhirResultModel result) { if (result.UnAuthorized) { - _outComeMessage = HttpStatusCode.Unauthorized.ToString(); + _outComeMessage = $"{HttpStatusCode.Unauthorized}. This directory needs an access token: get one on the B2B page first."; + return; } - else if (result.HttpStatusCode == HttpStatusCode.PreconditionFailed) + + if (result.HttpStatusCode == HttpStatusCode.PreconditionFailed) { - // await DiscoveryService.SetBaseFhirUrl(AppState.BaseUrl); _outComeMessage = "PreconditionFailed"; + return; } - else if (result.OperationOutcome != null) + if (result.OperationOutcome != null) { - _fhirResults.Entries = null; - string? errorMessage = null; - - foreach (var issue in result.OperationOutcome.Issue) - { - errorMessage += $"Error:: Details: {issue.Details?.Text}.
    " - + $"Diagnostics: {HtmlSanitizer.Sanitize(issue.Diagnostics)}.
    " - + $"IssueType: {issue.Code}.
    "; - } + _outComeMessage = string.Concat(result.OperationOutcome.Issue.Select(issue => + $"Error:: Details: {issue.Details?.Text}.
    " + + $"Diagnostics: {HtmlSanitizer.Sanitize(issue.Diagnostics)}.
    " + + $"IssueType: {issue.Code}.
    ")); + return; + } - _outComeMessage = errorMessage; + if (result.HttpStatusCode != null) + { + _fhirResults.HttpStatus = $"HTTP/{result.Version} {(int)result.HttpStatusCode} {result.HttpStatusCode}"; } - else + + if (result.Result == null) { - _outComeMessage = null; + return; + } - if (result.HttpStatusCode != null) - { - _fhirResults.HttpStatus = $"HTTP/{result.Version} {(int)result.HttpStatusCode} {result.HttpStatusCode}"; - } + _fhirResults.RawFhir = await new FhirJsonSerializer().SerializeToStringAsync(result.Result); + var bundle = new DirectoryBundle(result.Result, _fhirSearch.ResourceName); + _fhirResults.Bundle = bundle; - if (result.Result != null) - { - _fhirResults.RawFhir = await new FhirJsonSerializer() - .SerializeToStringAsync(result.Result); + foreach (var match in bundle.Matches) + { + _fhirResults.TreeViewStore.Add(match is Endpoint endpoint + ? await EndpointNode(endpoint, bundle) + : await ResourceNode(match, bundle)); + } + } - var scopeNode = result.Result.ToTypedElement().ToScopedNode(); - var references = scopeNode.Select( - "Bundle.entry.resource.descendants().select(reference)"); + /// A matched resource with its endpoints and the related resources the search included. + private async T.Task> ResourceNode(Resource match, DirectoryBundle bundle) + { + var node = new TreeItemData(match.Id, bundle.DisplayName(match), DirectoryBundle.Reference(match), + type: ResourceType, isLoading: false, detail: NpiDetail(match)); + var children = new List>(); + var (endpoints, unresolved) = bundle.EndpointsOf(match); - if (_fhirSearch.ResourceName == "Endpoint") - { - var endpoints = - scopeNode.Select( - $"Bundle.entry.resource.select($this).where($this is Endpoint)"); - await BuildTreeviewForEndpoints(endpoints); - return; - } + foreach (var endpoint in endpoints) + { + children.Add(await EndpointNode(endpoint, bundle)); + } - var treeChildren = new List>(); - foreach (var referenceContext in scopeNode.Select($"Bundle.entry.resource.where($this.is ({_fhirSearch.ResourceName}))")) - { - var domainResource = referenceContext.ToPoco(); - var nameElement = domainResource.ToTypedElement().Children("name").FirstOrDefault(); - var resource = referenceContext.ToPoco(); - // TreeItemData takes (id, name): the list shows the name, falling back to the id. - var orgEntry = new TreeItemData(resource?.Id ?? "Unknown", nameElement?.Value?.ToString() ?? resource?.Id ?? "Unknown", $"{resource?.TypeName}/{resource?.Id}"); + foreach (var reference in unresolved) + { + children.Add(new TreeItemData(reference, reference, reference, type: UnresolvedType, isLoading: false)); + } - treeChildren.Add(orgEntry); - } - _fhirResults.TreeViewStore.Children = treeChildren; - - foreach (var referenceItem in references) - { - //Organization/FhirLabsOrg - var parentReferencedId = - scopeNode.Select( - $"Bundle.entry.where($this.resource is {_fhirSearch.ResourceName} and $this.fullUrl.endsWith('{referenceItem.Value}')).resource.id"); - - foreach (var typedElement in parentReferencedId) - { - - var parentEntry = _fhirResults.TreeViewStore.Children?.FirstOrDefault(tv => tv.Value?.Id == typedElement.Value as string) as TreeItemData; - - // Get Endpoint addresses - var endpoints = - scopeNode.Select( - $"Bundle.entry.resource.select($this).where($this is Endpoint and $this.descendants().reference.endsWith('{_fhirSearch.ResourceName}/{typedElement.Value}'))"); - - await BuildTreeviewForEndpoints(endpoints, parentEntry); - } - } + foreach (var (relation, related) in bundle.RelatedTo(match)) + { + children.Add(new TreeItemData(related.Id, bundle.DisplayName(related), DirectoryBundle.Reference(related), + type: RelatedType, isLoading: false, detail: relation)); + } - _fhirResults.Entries = result.Result?.Entry - .Where(e => e.Resource != null) - .Select(e => e) - .ToList(); - } - else - { - _fhirResults.RawFhir = string.Empty; - } + if (children.Count > 0) + { + node.Children = children; } + + return node; } - private async T.Task BuildTreeviewForEndpoints(IEnumerable endpoints, TreeItemData? parentEntry = null) + private static string? NpiDetail(Resource resource) { - var treeStore = parentEntry ?? _fhirResults.TreeViewStore; - var storeChildren = (treeStore.Children as List>) ?? new List>(); + var npis = DirectoryBundle.Npis(resource).ToList(); + return npis.Count == 0 ? null : $"NPI {string.Join(", ", npis)}"; + } - foreach (var endpoint in endpoints) + /// + /// An Endpoint with what can be learned about its security: every http(s) address gets a UDAP node that + /// resolves by probing {address}/.well-known/udap. NDH STU2 removed the + /// extensions that used to say so; the STU1 ones are still read for directories that carry them. + /// + private async T.Task> EndpointNode(Endpoint endpoint, DirectoryBundle bundle) + { + var detail = string.Join(" · ", new[] { - var endpointResource = endpoint.ToPoco(); - if (storeChildren.Any(ts => ts.Value?.Id == endpointResource.Id)) - { - continue; - } - - var endPointTreeItem = new TreeItemData(endpointResource.Id, endpointResource.Name, $"{endpointResource?.TypeName}/{endpointResource?.Id}"); - var endpointChildren = new List>(); - - storeChildren.Add(endPointTreeItem); + endpoint.ConnectionType?.Code, + endpoint.Status is { } status && status != Endpoint.EndpointStatus.Active ? status.ToString().ToLowerInvariant() : null, + endpoint.Name != null ? endpoint.Address : null + }.Where(s => !string.IsNullOrEmpty(s))); - // NDH STU2 removed the base-ext-dynamicRegistration extension, and nothing else on Endpoint marks it - // as UDAP. Every http(s) endpoint gets a UDAP node that AugmentHandler resolves by probing - // {address}/.well-known/udap. - if (IsHttpAddress(endpointResource.Address)) - { - endpointChildren.Add(new TreeItemData( - id: endpointResource.Id, - name: endpointResource.Name, - resourceReference: $"{endpointResource.TypeName}/{endpointResource.Id}", - icon: Icons.Material.TwoTone.DynamicForm, - iconColor: Color.Default, - link: AppendUdapWellKnown(endpointResource.Address), - type: UdapType - )); - } - - // STU1 extension, still read for directories that carry it. - var dynamicEndpointTypes = endpointResource.ToTypedElement().Select( - $"extension.where($this.url in 'http://hl7.org/fhir/us/ndh/StructureDefinition/base-ext-dynamicRegistration').descendants().select($this.descendants().coding.code)"); + var node = new TreeItemData(endpoint.Id, bundle.DisplayName(endpoint), DirectoryBundle.Reference(endpoint), + link: endpoint.Address, type: EndpointType, isLoading: false, detail: detail); + var children = new List>(); + if (IsHttpAddress(endpoint.Address)) + { + children.Add(new TreeItemData( + id: endpoint.Id, + name: endpoint.Name ?? endpoint.Address, + resourceReference: DirectoryBundle.Reference(endpoint), + icon: Icons.Material.TwoTone.DynamicForm, + iconColor: Color.Default, + link: AppendUdapWellKnown(endpoint.Address), + type: UdapType)); + } - foreach (var dynamicEndpointType in dynamicEndpointTypes) - { - if (dynamicEndpointType.Value?.ToString() == "smart") - { - var results = - await MetadataService.GetSmartMetadata( - $"{endpointResource.Address.EnsureTrailingSlash()}.well-known/smart-configuration", default); - - endpointChildren.Add(new TreeItemData( - endpointResource.Id, - endpointResource.Name, - $"{endpointResource?.TypeName}/{endpointResource?.Id}", - Icons.Material.TwoTone.SmartDisplay, - results == null ? Color.Error : Color.Success, - endpointResource.Address, - dynamicEndpointType.Value?.ToString())); - } - } + await AddLegacyExtensionNodes(endpoint, children); + if (children.Count > 0) + { + node.Children = children; + } - var mTlsEndpointTypes = endpointResource.ToTypedElement().Select( - $"extension.where($this.url = 'http://hl7.org/fhir/us/ndh/StructureDefinition/base-ext-secureExchangeArtifacts').select($this.where($this.descendants().coding.code in 'x509-mtls-certificate'))"); + return node; + } + /// NDH STU1 extensions: base-ext-dynamicRegistration (SMART) and the mTLS certificate. + private async T.Task AddLegacyExtensionNodes(Endpoint endpoint, List> children) + { + var typed = endpoint.ToTypedElement(); + var dynamicEndpointTypes = typed.Select( + "extension.where($this.url in 'http://hl7.org/fhir/us/ndh/StructureDefinition/base-ext-dynamicRegistration').descendants().select($this.descendants().coding.code)"); - foreach (var mTlsEndpointType in mTlsEndpointTypes) + foreach (var dynamicEndpointType in dynamicEndpointTypes) + { + if (dynamicEndpointType.Value?.ToString() != "smart") { - var mtlsEncodeCertificate = GetMtlsServerCertificate(mTlsEndpointType); - var notifications = await MtlsService.VerifyMtlsTrust(mtlsEncodeCertificate); - - endpointChildren.Add(new TreeItemData( - endpointResource.Id, - endpointResource.Name, - $"{endpointResource?.TypeName}/{endpointResource?.Id}", - Icons.Material.TwoTone.DynamicForm, - notifications != null && notifications.Any() ? Color.Error : Color.Success, - endpointResource.Address, - mTlsEndpointType.Select("extension.descendants().coding.code").First().Value?.ToString(), - null, - notifications, - null, - null, - mtlsEncodeCertificate - )); + continue; } - if (endpointChildren.Count > 0) - { - endPointTreeItem.Children = endpointChildren; - } + var results = await MetadataService.GetSmartMetadata( + $"{endpoint.Address.EnsureTrailingSlash()}.well-known/smart-configuration", default); + + children.Add(new TreeItemData(endpoint.Id, endpoint.Name ?? endpoint.Address, DirectoryBundle.Reference(endpoint), + Icons.Material.TwoTone.SmartDisplay, + results == null ? Color.Error : Color.Success, + endpoint.Address, + "smart", + isLoading: false)); + } + var mTlsEndpointTypes = typed.Select( + "extension.where($this.url = 'http://hl7.org/fhir/us/ndh/StructureDefinition/base-ext-secureExchangeArtifacts').select($this.where($this.descendants().coding.code in 'x509-mtls-certificate'))"); - // var nondynamicEndpointTypes = endpointResource.ToTypedElement().Select( - // $"extension.where($this.url != 'http://hl7.org/fhir/us/ndh/StructureDefinition/base-ext-dynamicRegistration').descendants().select($this.descendants().coding.code)"); - // - // foreach (var nonDynamicEndpointType in nondynamicEndpointTypes) - // { - // endPointTreeItem.TreeItems.Add(new FhirHierarchyEntries() - // { - // Id = endpointResource.Id, - // Name = endpointResource.Name, - // Link = endpointResource.Address, - // Type = nonDynamicEndpointType.Value?.ToString(), - // // IconColor = Color.Default, - // // Icon = Icons.Material.TwoTone.Link - // }); - // } - } - treeStore.Children = storeChildren; + foreach (var mTlsEndpointType in mTlsEndpointTypes) + { + var certificate = GetMtlsServerCertificate(mTlsEndpointType); + var notifications = certificate == null ? null : await MtlsService.VerifyMtlsTrust(certificate); + + children.Add(new TreeItemData(endpoint.Id, endpoint.Name ?? endpoint.Address, DirectoryBundle.Reference(endpoint), + Icons.Material.TwoTone.DynamicForm, + notifications != null && notifications.Any() ? Color.Error : Color.Success, + endpoint.Address, + mTlsEndpointType.Select("extension.descendants().coding.code").First().Value?.ToString(), + null, + notifications, + null, + null, + certificate, + isLoading: false)); + } } /// - /// Probes .well-known/udap for every UDAP node still loading, at any depth of the tree (an Endpoint sits - /// under its Organization or PractitionerRole). Nodes that share an address are probed once. The tree - /// re-renders as each probe finishes. + /// Probes .well-known/udap for every UDAP node still loading, at any depth of the tree. Nodes that share an + /// address (an endpoint shared by two organizations) are probed once. The tree re-renders as each probe finishes. /// private async T.Task AugmentHandler() { - var probesByLink = Flatten(_fhirResults.TreeViewStore.Children) + var probesByLink = Flatten(_fhirResults.TreeViewStore) .Select(item => item.Value) .OfType() .Where(entry => entry is { IsLoading: true, Type: UdapType, Link: not null }) @@ -563,21 +587,16 @@ private static bool IsHttpAddress(string? address) => Uri.TryCreate(address, UriKind.Absolute, out var uri) && (uri.Scheme == Uri.UriSchemeHttps || uri.Scheme == Uri.UriSchemeHttp); - private string? AppendUdapWellKnown(string endpointResourceAddress) - { - if (!endpointResourceAddress.Contains(UdapConstants.Discovery.DiscoveryEndpoint)) - { - return endpointResourceAddress.EnsureTrailingSlash() + UdapConstants.Discovery.DiscoveryEndpoint; - } - - return endpointResourceAddress; - } + private static string AppendUdapWellKnown(string endpointResourceAddress) => + endpointResourceAddress.Contains(UdapConstants.Discovery.DiscoveryEndpoint) + ? endpointResourceAddress + : endpointResourceAddress.EnsureTrailingSlash() + UdapConstants.Discovery.DiscoveryEndpoint; private static string? GetMtlsServerCertificate(ITypedElement mTlsEndpointType) { try { - return mTlsEndpointType.Select("extension.where(url = 'certificate').value").FirstOrDefault().Value.ToString(); + return mTlsEndpointType.Select("extension.where(url = 'certificate').value").FirstOrDefault()?.Value?.ToString(); } catch { return "Can't parse"; } } @@ -606,16 +625,17 @@ private async T.Task OpenUdapAnchorDialogAsync() public class TreeItemData : TreeItemData { - public TreeItemData(string id, string name, + public TreeItemData(string id, string name, string resourceReference, string? icon = null, Color? iconColor = null, - string? link = null, string? type = null, - MetadataVerificationModel? metadata = null, + string? link = null, string? type = null, + MetadataVerificationModel? metadata = null, List? untrusted = null, List? tokenErrors = null, List? problems = null, string? mtlCertificate = null, - bool isLoading = true) : base(new FhirHierarchyEntry()) + bool isLoading = true, + string? detail = null) : base(new FhirHierarchyEntry()) { Value!.Id = id; Value.Name = name; @@ -630,55 +650,52 @@ public TreeItemData(string id, string name, Value.Problems = problems; Value.MtlsServerCertificate = mtlCertificate; Value.IsLoading = isLoading; + Value.Detail = detail; + Expanded = true; } } public record FhirHierarchyEntry { - public string Id; - public string Name; - public string ResourceReference; + public string Id = string.Empty; + public string Name = string.Empty; + public string ResourceReference = string.Empty; public string? Type; public string? Link; + public string? Detail; public bool IsLoading { get; set; } = true; public string? Icon { get; set; } public Color IconColor { get; set; } = Color.Warning; - public string? Metadata { get; set; } - - public List? Untrusted { get; set; } = null; - public List? TokenErrors { get; set; } = null; - public List? Problems { get; set; } = null; - public MetadataVerificationModel? UdapMetadata { get; set; } = null; + public List? Untrusted { get; set; } + public List? TokenErrors { get; set; } + public List? Problems { get; set; } + public MetadataVerificationModel? UdapMetadata { get; set; } public string? MtlsServerCertificate { get; set; } } - - record FhirResults + private sealed class FhirResults { - public string HttpStatus { get; set; } - public string RawFhir { get; set; } - public List? Entries { get; set; } - public TreeItemData TreeViewStore = new () { Children = new List>() }; - } - + public string? HttpStatus { get; set; } + public string? RawFhir { get; set; } + public DirectoryBundle? Bundle { get; set; } + public List> TreeViewStore { get; } = []; - public class ObjectToFhirBoolConverter : IReversibleConverter - { - public bool? Convert(string input) + public string Summary { - return input switch + get { - "true" => true, - "false" => false, - _ => null - }; - } + if (Bundle == null) + { + return string.Empty; + } - public string ConvertBack(bool? input) - { - return input == true ? "true" : "false"; + var count = Bundle.Matches.Count; + var total = Bundle.Total is { } t ? $" of {t}" : string.Empty; + var more = Bundle.NextUrl != null ? ", more on the next page" : string.Empty; + return $"{count}{total} matches on this page{more}"; + } } } } diff --git a/Shared/Search/DirectoryBundle.cs b/Shared/Search/DirectoryBundle.cs new file mode 100644 index 0000000..fc5d10f --- /dev/null +++ b/Shared/Search/DirectoryBundle.cs @@ -0,0 +1,240 @@ +#region (c) 2026 Joseph Shook. All rights reserved. +// /* +// Authors: +// Joseph Shook Joseph.Shook@Surescripts.com +// +// See LICENSE in the project root for license information. +// */ +#endregion + +using Hl7.Fhir.Model; + +namespace UdapEd.Shared.Search; + +/// +/// One page of directory search results, indexed so that references resolve to the resources in the Bundle. +/// Endpoints are linked in both directions: forward (Organization.endpoint, PractitionerRole.endpoint, +/// ...) and backward (Endpoint.managingOrganization). Directories differ in which side they fill in: the +/// CMS NPD only fills the forward side. +/// +public sealed class DirectoryBundle +{ + public const string NpiSystem = "http://hl7.org/fhir/sid/us-npi"; + + private readonly Dictionary _byReference = new(StringComparer.Ordinal); + private readonly List _resources = []; + + public DirectoryBundle(Bundle bundle, string? searchedResource) + { + foreach (var entry in bundle.Entry.Where(e => e.Resource != null)) + { + var resource = entry.Resource; + _resources.Add(resource); + _byReference.TryAdd(Reference(resource), resource); + + if (!string.IsNullOrEmpty(entry.FullUrl)) + { + _byReference.TryAdd(entry.FullUrl, resource); + } + } + + var anyMode = bundle.Entry.Any(e => e.Search?.Mode != null); + Matches = bundle.Entry + .Where(e => e.Resource != null && e.Resource is not OperationOutcome) + .Where(e => anyMode + ? e.Search?.Mode == Bundle.SearchEntryMode.Match + : e.Resource.TypeName == searchedResource) + .Select(e => e.Resource) + .ToList(); + + Total = bundle.Total; + NextUrl = LinkUrl(bundle, "next"); + PreviousUrl = LinkUrl(bundle, "previous") ?? LinkUrl(bundle, "prev"); + FirstUrl = LinkUrl(bundle, "first"); + } + + public IReadOnlyList Matches { get; } + public int? Total { get; } + public string? NextUrl { get; } + public string? PreviousUrl { get; } + public string? FirstUrl { get; } + + public static string Reference(Resource resource) => $"{resource.TypeName}/{resource.Id}"; + + /// + /// Resolves a relative (Endpoint/123) or absolute reference against the Bundle. Absolute references + /// fall back to their last two path segments, since servers mix the two forms. + /// + public Resource? Resolve(string? reference) + { + if (string.IsNullOrEmpty(reference)) + { + return null; + } + + if (_byReference.TryGetValue(reference, out var resource)) + { + return resource; + } + + var relative = RelativeReference(reference); + return relative != null && _byReference.TryGetValue(relative, out resource) ? resource : null; + } + + /// The endpoints a resource points at that are in the Bundle, plus the references that are not. + public (List Resolved, List Unresolved) EndpointsOf(Resource resource) + { + var resolved = new List(); + var unresolved = new List(); + + foreach (var reference in EndpointReferences(resource)) + { + if (Resolve(reference) is Endpoint endpoint) + { + resolved.Add(endpoint); + } + else + { + unresolved.Add(reference); + } + } + + var self = Reference(resource); + resolved.AddRange(_resources.OfType() + .Where(e => SameReference(e.ManagingOrganization?.Reference, self))); + + return (resolved.DistinctBy(e => e.Id).ToList(), unresolved.Distinct().ToList()); + } + + /// + /// Non-Endpoint resources in the Bundle that are related to a match: the ones it references + /// (PractitionerRole.practitioner, Organization.partOf) and the ones that reference it (a _revinclude). + /// + public IEnumerable<(string Relation, Resource Resource)> RelatedTo(Resource match) + { + var self = Reference(match); + var seen = new HashSet { self }; + + foreach (var (path, reference) in References(match)) + { + if (path == "endpoint" || Resolve(reference) is not { } target || target is Endpoint) + { + continue; + } + + if (seen.Add(Reference(target))) + { + yield return (path, target); + } + } + + foreach (var other in _resources.Where(r => r is not Endpoint && !Matches.Contains(r))) + { + var back = References(other).FirstOrDefault(r => SameReference(r.Reference, self)); + + if (back.Reference != null && seen.Add(Reference(other))) + { + yield return ($"{other.TypeName}.{back.Path}", other); + } + } + } + + public string DisplayName(Resource resource) + { + var name = resource switch + { + Organization o => o.Name, + Practitioner p => HumanName(p.Name.FirstOrDefault()), + PractitionerRole role => Join( + role.Practitioner?.Display ?? (Resolve(role.Practitioner?.Reference) is Practitioner p + ? HumanName(p.Name.FirstOrDefault()) : null), + role.Organization?.Display ?? (Resolve(role.Organization?.Reference) as Organization)?.Name, + CodeText(role.Code.FirstOrDefault())), + OrganizationAffiliation affiliation => Join( + affiliation.ParticipatingOrganization?.Display + ?? (Resolve(affiliation.ParticipatingOrganization?.Reference) as Organization)?.Name, + CodeText(affiliation.Code.FirstOrDefault())), + Location l => l.Name, + HealthcareService h => h.Name, + InsurancePlan i => i.Name, + Endpoint e => e.Name ?? e.Address, + _ => null + }; + + return string.IsNullOrWhiteSpace(name) ? Reference(resource) : name; + } + + /// NPIs carried by a resource, for display next to its name. + public static IEnumerable Npis(Resource resource) + { + var identifiers = resource switch + { + Organization o => o.Identifier, + Practitioner p => p.Identifier, + PractitionerRole r => r.Identifier, + Location l => l.Identifier, + _ => [] + }; + + return identifiers.Where(i => i.System == NpiSystem && !string.IsNullOrEmpty(i.Value)).Select(i => i.Value); + } + + private static IEnumerable EndpointReferences(Resource resource) => + References(resource).Where(r => r.Path == "endpoint").Select(r => r.Reference); + + /// Top-level references of a resource with the element they sit in. + private static IEnumerable<(string Path, string Reference)> References(Resource resource) + { + foreach (var child in resource.NamedChildren) + { + if (child.Value is ResourceReference { Reference: { Length: > 0 } single }) + { + yield return (child.ElementName, single); + } + } + } + + private static bool SameReference(string? reference, string relative) => + reference != null && (reference == relative || RelativeReference(reference) == relative); + + private static string? RelativeReference(string reference) + { + var parts = reference.Split('?')[0].TrimEnd('/').Split('/'); + + if (parts.Length >= 4 && parts[^2] == "_history") + { + parts = parts[..^2]; + } + + return parts.Length >= 2 ? $"{parts[^2]}/{parts[^1]}" : null; + } + + private static string? LinkUrl(Bundle bundle, string relation) => + bundle.Link.FirstOrDefault(l => l.Relation == relation)?.Url; + + private static string? HumanName(HumanName? name) + { + if (name == null) + { + return null; + } + + if (!string.IsNullOrWhiteSpace(name.Text)) + { + return name.Text; + } + + return JoinWith(" ", name.Prefix.Concat(name.Given).Append(name.Family).Concat(name.Suffix).ToArray()); + } + + private static string? CodeText(CodeableConcept? concept) => + concept?.Text ?? concept?.Coding.Select(c => c.Display ?? c.Code).FirstOrDefault(c => c != null); + + private static string? Join(params string?[] parts) => JoinWith(" · ", parts); + + private static string? JoinWith(string separator, string?[] parts) + { + var present = parts.Where(p => !string.IsNullOrWhiteSpace(p)).ToList(); + return present.Count == 0 ? null : string.Join(separator, present); + } +} diff --git a/Shared/Search/DirectoryCapabilities.cs b/Shared/Search/DirectoryCapabilities.cs new file mode 100644 index 0000000..41e092d --- /dev/null +++ b/Shared/Search/DirectoryCapabilities.cs @@ -0,0 +1,134 @@ +#region (c) 2026 Joseph Shook. All rights reserved. +// /* +// Authors: +// Joseph Shook Joseph.Shook@Surescripts.com +// +// See LICENSE in the project root for license information. +// */ +#endregion + +using Hl7.Fhir.Model; +using UdapEd.Shared.Services.Search; + +namespace UdapEd.Shared.Search; + +/// +/// The resources, search parameters, includes and reverse includes the Directory page offers. Read from the +/// directory's own CapabilityStatement, then topped up with the NDH IG's, because directories honor more than +/// they advertise (the CMS NPD answers _include=Organization:endpoint without listing it). +/// +public sealed class DirectoryCapabilities +{ + public static readonly IReadOnlyList DefaultResources = + [ + "Organization", "Practitioner", "PractitionerRole", "Endpoint", "Location", "HealthcareService", + "OrganizationAffiliation", "InsurancePlan" + ]; + + public List Resources { get; } = []; + public Dictionary> SearchParams { get; } = new(); + public Dictionary> Includes { get; } = new(); + public Dictionary> RevIncludes { get; } = new(); + + /// Where the directory-specific part came from; null when only the NDH IG is known. + public string? Source { get; private init; } + + public IReadOnlyList SearchParamsFor(string? resource) => Lookup(SearchParams, resource); + public IReadOnlyList IncludesFor(string? resource) => Lookup(Includes, resource); + public IReadOnlyList RevIncludesFor(string? resource) => Lookup(RevIncludes, resource); + + public static DirectoryCapabilities From(CapabilityStatement capabilityStatement, string source) + { + var capabilities = new DirectoryCapabilities { Source = source }; + + foreach (var resource in capabilityStatement.Rest.SelectMany(r => r.Resource)) + { + if (string.IsNullOrEmpty(resource.Type)) + { + continue; + } + + capabilities.Add(resource.Type, + resource.SearchParam.Select(p => p.Name), + resource.SearchInclude, + resource.SearchRevInclude); + } + + return capabilities; + } + + public static DirectoryCapabilities From(ICapabilityLookup lookup) + { + var capabilities = new DirectoryCapabilities(); + + foreach (var map in lookup.SearchParamMap) + { + capabilities.Add(map.Resource, + map.ParamDefinitions?.Select(d => d.Code) ?? [], + lookup.IncludeMap.GetValueOrDefault(map.Resource) ?? [], + lookup.ReverseIncludeMap.GetValueOrDefault(map.Resource) ?? []); + } + + return capabilities; + } + + /// + /// This directory's capabilities first, then anything the fallback adds for the same resources. The resource + /// list stays the directory's own when it published one. + /// + public DirectoryCapabilities MergedWith(DirectoryCapabilities fallback) + { + var merged = new DirectoryCapabilities { Source = Source }; + + foreach (var resource in Resources) + { + merged.Add(resource, SearchParamsFor(resource), IncludesFor(resource), RevIncludesFor(resource)); + } + + foreach (var resource in fallback.Resources) + { + if (Resources.Count > 0 && !Resources.Contains(resource)) + { + continue; + } + + merged.Add(resource, fallback.SearchParamsFor(resource), fallback.IncludesFor(resource), + fallback.RevIncludesFor(resource)); + } + + return merged; + } + + private void Add(string resource, IEnumerable searchParams, IEnumerable includes, + IEnumerable revIncludes) + { + if (!Resources.Contains(resource)) + { + Resources.Add(resource); + } + + Append(SearchParams, resource, searchParams); + Append(Includes, resource, includes); + Append(RevIncludes, resource, revIncludes); + } + + private static void Append(Dictionary> map, string resource, IEnumerable values) + { + if (!map.TryGetValue(resource, out var list)) + { + list = []; + map[resource] = list; + } + + foreach (var value in values) + { + if (!string.IsNullOrWhiteSpace(value) && !list.Contains(value)) + { + list.Add(value); + } + } + } + + private static IReadOnlyList Lookup(Dictionary> map, string? resource) => + resource != null && map.TryGetValue(resource, out var list) ? list : []; +} diff --git a/Shared/Search/DirectoryQuery.cs b/Shared/Search/DirectoryQuery.cs new file mode 100644 index 0000000..8ba8470 --- /dev/null +++ b/Shared/Search/DirectoryQuery.cs @@ -0,0 +1,109 @@ +#region (c) 2026 Joseph Shook. All rights reserved. +// /* +// Authors: +// Joseph Shook Joseph.Shook@Surescripts.com +// +// See LICENSE in the project root for license information. +// */ +#endregion + +namespace UdapEd.Shared.Search; + +/// +/// Turns what a user types or pastes into the Directory page's GET box into a search URL. Accepts a bare query +/// (name=mayo), a resource-relative query (Organization?name=mayo) or a full URL copied from a +/// directory's documentation (https://directory.cms.gov/fhir/Organization?name=mayo). +/// +public static class DirectoryQuery +{ + public sealed record Parsed(string? BaseUrl, string? ResourceName, string Query); + + public static Parsed Parse(string? input) + { + var text = (input ?? string.Empty).Trim(); + + if (text.StartsWith("GET ", StringComparison.OrdinalIgnoreCase)) + { + text = text[4..].Trim(); + } + + var queryStart = text.IndexOf('?'); + var path = queryStart >= 0 ? text[..queryStart] : text; + var query = queryStart >= 0 ? text[(queryStart + 1)..] : string.Empty; + + if (Uri.TryCreate(path, UriKind.Absolute, out var uri) + && (uri.Scheme == Uri.UriSchemeHttps || uri.Scheme == Uri.UriSchemeHttp)) + { + var trimmed = path.TrimEnd('/'); + var lastSlash = trimmed.LastIndexOf('/'); + var lastSegment = lastSlash >= 0 ? trimmed[(lastSlash + 1)..] : string.Empty; + + return IsResourceName(lastSegment) && lastSlash > uri.GetLeftPart(UriPartial.Authority).Length + ? new Parsed(trimmed[..lastSlash], lastSegment, query) + : new Parsed(trimmed, null, query); + } + + var relative = path.Trim('/'); + + if (queryStart >= 0) + { + return IsResourceName(relative) + ? new Parsed(null, relative, query) + : new Parsed(null, null, relative.Length == 0 ? query : text); + } + + // No '?': a lone resource name, or a query without one ("name=mayo"). + return IsResourceName(relative) ? new Parsed(null, relative, string.Empty) : new Parsed(null, null, text); + } + + /// + /// Builds the query string for the parameters, includes and page size. Values are percent-encoded except + /// for the characters FHIR search gives meaning to (| token separators, , OR lists, :). + /// + public static string Build(IEnumerable<(string Name, string? Modifier, string? Value)> parameters, + IEnumerable includes, IEnumerable revIncludes, int? count) + { + var parts = new List(); + + foreach (var (name, modifier, value) in parameters) + { + if (string.IsNullOrWhiteSpace(name)) + { + continue; + } + + var key = string.IsNullOrEmpty(modifier) ? name.Trim() : $"{name.Trim()}:{modifier}"; + parts.Add($"{key}={EscapeValue(value)}"); + } + + parts.AddRange(includes.Select(i => $"_include={i}")); + parts.AddRange(revIncludes.Select(i => $"_revinclude={i}")); + + if (count is > 0) + { + parts.Add($"_count={count}"); + } + + return string.Join('&', parts); + } + + public static string EscapeValue(string? value) => + Uri.EscapeDataString(value ?? string.Empty) + .Replace("%7C", "|", StringComparison.OrdinalIgnoreCase) + .Replace("%2C", ",", StringComparison.OrdinalIgnoreCase) + .Replace("%3A", ":", StringComparison.OrdinalIgnoreCase); + + /// + /// Search URL for a base, resource and query. A query that already holds a full URL (a Bundle paging link) + /// is returned as is. + /// + public static string Url(string baseUrl, string resourceName, string? query) + { + var url = $"{baseUrl.Trim().TrimEnd('/')}/{resourceName.Trim()}"; + return string.IsNullOrWhiteSpace(query) ? url : $"{url}?{query.Trim().TrimStart('?')}"; + } + + /// FHIR resource type names are PascalCase letters, e.g. Organization or PractitionerRole. + public static bool IsResourceName(string? segment) => + !string.IsNullOrEmpty(segment) && char.IsUpper(segment[0]) && segment.All(char.IsAsciiLetter); +} diff --git a/_tests/UtilityTests/DirectorySearchTests.cs b/_tests/UtilityTests/DirectorySearchTests.cs new file mode 100644 index 0000000..2cd12e8 --- /dev/null +++ b/_tests/UtilityTests/DirectorySearchTests.cs @@ -0,0 +1,186 @@ +#region (c) 2026 Joseph Shook. All rights reserved. +// /* +// Authors: +// Joseph Shook Joseph.Shook@Surescripts.com +// +// See LICENSE in the project root for license information. +// */ +#endregion + +using Hl7.Fhir.Model; +using Shouldly; +using UdapEd.Shared.Search; + +namespace UtilityTests; + +public class DirectorySearchTests +{ + [Theory] + [InlineData("name=mayo", null, null, "name=mayo")] + [InlineData("?name=mayo", null, null, "name=mayo")] + [InlineData("Organization?name=mayo", null, "Organization", "name=mayo")] + [InlineData("/Practitioner?family=smith&_count=5", null, "Practitioner", "family=smith&_count=5")] + [InlineData("PractitionerRole", null, "PractitionerRole", "")] + [InlineData("https://directory.cms.gov/fhir/Organization?identifier=1023405065", + "https://directory.cms.gov/fhir", "Organization", "identifier=1023405065")] + [InlineData("GET https://directory.cms.gov/fhir/Endpoint?connection-type=hl7-fhir-rest", + "https://directory.cms.gov/fhir", "Endpoint", "connection-type=hl7-fhir-rest")] + [InlineData("https://directory.cms.gov/fhir?name=x", "https://directory.cms.gov/fhir", null, "name=x")] + public void ParsesWhatIsPastedIntoTheGetBox(string input, string? baseUrl, string? resource, string query) + { + var parsed = DirectoryQuery.Parse(input); + + parsed.BaseUrl.ShouldBe(baseUrl); + parsed.ResourceName.ShouldBe(resource); + parsed.Query.ShouldBe(query); + } + + [Fact] + public void BuildsAnEncodedQueryWithIncludesAndCount() + { + var query = DirectoryQuery.Build( + [("name", null, "plymouth bay"), ("identifier", null, "http://hl7.org/fhir/sid/us-npi|1023405065"), + ("name", "contains", "o'neil & sons"), ("", null, "ignored")], + ["Organization:endpoint"], ["PractitionerRole:organization"], 20); + + query.ShouldBe("name=plymouth%20bay&identifier=http:%2F%2Fhl7.org%2Ffhir%2Fsid%2Fus-npi|1023405065" + + "&name:contains=o%27neil%20%26%20sons&_include=Organization:endpoint" + + "&_revinclude=PractitionerRole:organization&_count=20"); + } + + [Fact] + public void LinksEndpointsReferencedForwardAndBackward() + { + var bundle = new Bundle { Type = Bundle.BundleType.Searchset }; + // CMS NPD shape: the Organization points at the Endpoint, the Endpoint has no managingOrganization, + // and two organizations share one endpoint. + bundle.Entry.Add(Match(new Organization + { + Id = "org1", Name = "PLYMOUTH BAY ORTHOPEDIC", + Endpoint = [new ResourceReference("Endpoint/ep1")], + Identifier = [new Identifier(DirectoryBundle.NpiSystem, "1053582031")] + })); + bundle.Entry.Add(Match(new Organization + { + Id = "org2", Name = "PLYMOUTH BAY ORTHOPEDIC ASSOCIATES", + Endpoint = [new ResourceReference("https://directory.cms.gov/fhir/Endpoint/ep1"), new ResourceReference("Endpoint/missing")] + })); + // NDH RI shape: only the Endpoint points back at its Organization. + bundle.Entry.Add(Match(new Organization { Id = "org3", Name = "Back Reference Clinic" })); + bundle.Entry.Add(Include(new Endpoint { Id = "ep1", Address = "https://fhir4.healow.com/fhir/r4/CEIGAA" })); + bundle.Entry.Add(Include(new Endpoint + { + Id = "ep2", Address = "https://example.org/fhir", ManagingOrganization = new ResourceReference("Organization/org3") + })); + + var directory = new DirectoryBundle(bundle, "Organization"); + + directory.Matches.Select(m => m.Id).ShouldBe(["org1", "org2", "org3"]); + + var org1 = directory.EndpointsOf(directory.Matches[0]); + org1.Resolved.Select(e => e.Id).ShouldBe(["ep1"]); + org1.Unresolved.ShouldBeEmpty(); + + var org2 = directory.EndpointsOf(directory.Matches[1]); + org2.Resolved.Select(e => e.Id).ShouldBe(["ep1"]); + org2.Unresolved.ShouldBe(["Endpoint/missing"]); + + directory.EndpointsOf(directory.Matches[2]).Resolved.Select(e => e.Id).ShouldBe(["ep2"]); + DirectoryBundle.Npis(directory.Matches[0]).ShouldBe(["1053582031"]); + } + + [Fact] + public void ShowsPractitionerRoleByItsIncludedPractitionerAndOrganization() + { + var bundle = new Bundle { Type = Bundle.BundleType.Searchset }; + bundle.Entry.Add(Match(new PractitionerRole + { + Id = "role1", + Practitioner = new ResourceReference("Practitioner/p1"), + Organization = new ResourceReference("Organization/o1") + })); + bundle.Entry.Add(Include(new Practitioner + { + Id = "p1", Name = [new HumanName { Family = "Smith", Given = ["Jane"] }] + })); + bundle.Entry.Add(Include(new Organization { Id = "o1", Name = "Acme Clinic" })); + + var directory = new DirectoryBundle(bundle, "PractitionerRole"); + var role = directory.Matches.Single(); + + directory.DisplayName(role).ShouldBe("Jane Smith · Acme Clinic"); + directory.RelatedTo(role).Select(r => (r.Relation, r.Resource.Id)).ShouldBe([("practitioner", "p1"), ("organization", "o1")]); + } + + [Fact] + public void ReadsPagingLinks() + { + var bundle = new Bundle { Type = Bundle.BundleType.Searchset, Total = 42 }; + bundle.Link.Add(new Bundle.LinkComponent { Relation = "next", Url = "https://directory.cms.gov/fhir/Organization?name=x&page=2" }); + + var directory = new DirectoryBundle(bundle, "Organization"); + + directory.NextUrl.ShouldBe("https://directory.cms.gov/fhir/Organization?name=x&page=2"); + directory.PreviousUrl.ShouldBeNull(); + directory.Total.ShouldBe(42); + } + + [Fact] + public void PrefersTheDirectoryCapabilitiesAndKeepsTheIgExtras() + { + var directory = new CapabilityStatement + { + Rest = + [ + new CapabilityStatement.RestComponent + { + Resource = + [ + new CapabilityStatement.ResourceComponent + { + Type = "Organization", + SearchParam = [new CapabilityStatement.SearchParamComponent { Name = "name" }], + SearchInclude = ["Organization:partof"] + } + ] + } + ] + }; + var ig = new CapabilityStatement + { + Rest = + [ + new CapabilityStatement.RestComponent + { + Resource = + [ + new CapabilityStatement.ResourceComponent + { + Type = "Organization", + SearchParam = [new CapabilityStatement.SearchParamComponent { Name = "endpoint" }], + SearchInclude = ["Organization:endpoint", "Organization:partof"] + }, + new CapabilityStatement.ResourceComponent { Type = "CareTeam" } + ] + } + ] + }; + + var merged = DirectoryCapabilities.From(directory, "cms").MergedWith(DirectoryCapabilities.From(ig, "ig")); + + merged.Resources.ShouldBe(["Organization"]); + merged.SearchParamsFor("Organization").ShouldBe(["name", "endpoint"]); + merged.IncludesFor("Organization").ShouldBe(["Organization:partof", "Organization:endpoint"]); + merged.Source.ShouldBe("cms"); + } + + private static Bundle.EntryComponent Match(Resource resource) => Entry(resource, Bundle.SearchEntryMode.Match); + private static Bundle.EntryComponent Include(Resource resource) => Entry(resource, Bundle.SearchEntryMode.Include); + + private static Bundle.EntryComponent Entry(Resource resource, Bundle.SearchEntryMode mode) => new() + { + FullUrl = $"https://directory.cms.gov/fhir/{resource.TypeName}/{resource.Id}", + Resource = resource, + Search = new Bundle.SearchComponent { Mode = mode } + }; +} From 367613e259085a1348bdc68912fcc37e51c79995 Mon Sep 17 00:00:00 2001 From: Joe Shook Date: Sun, 29 Nov 2026 12:44:31 -0800 Subject: [PATCH 06/13] Directory: wildcard includes, references inside extensions, readable FHIR view - Includes offer Resource:* and reverse includes offer *. When a directory rejects an _include (HAPI-2018 for a bare "PractitionerRole"), the error says what the value should look like. - Related resources are found through references inside extensions too, so a PractitionerRole shows its NDH network (base-ext-network-reference). - The FHIR tab pretty-prints the Bundle, and the Monaco editor tracks its container instead of a fixed 200px layout taken while the tab was hidden; it is read only. Co-Authored-By: Claude Opus 5.5 --- Shared/Components/FhirEditor.razor | 10 ++++--- Shared/Pages/Directory.razor | 4 +-- Shared/Pages/Directory.razor.cs | 10 ++++++- Shared/Search/DirectoryBundle.cs | 29 +++++++++++++++++---- _tests/UtilityTests/DirectorySearchTests.cs | 16 ++++++++++++ 5 files changed, 57 insertions(+), 12 deletions(-) diff --git a/Shared/Components/FhirEditor.razor b/Shared/Components/FhirEditor.razor index 5d94ff5..77506f7 100644 --- a/Shared/Components/FhirEditor.razor +++ b/Shared/Components/FhirEditor.razor @@ -81,9 +81,13 @@ Language = _language, GlyphMargin = false, Value = _editorContent, - ShowFoldingControls = "false", + ShowFoldingControls = "always", AutoDetectHighContrast = false, - + // The editor can start inside a hidden tab; let Monaco track its container's size. + AutomaticLayout = true, + ReadOnly = true, + ScrollBeyondLastLine = false, + WordWrap = "on", }; } @@ -97,8 +101,6 @@ } await UpdateTheme(); - await _editor.Layout(new Dimension() { Height = 600, Width = 200 }); - await JS.InvokeVoidAsync("setMonacoEditorResize", _editor.Id); await _editor.SetValue(_editorContent ?? string.Empty); } diff --git a/Shared/Pages/Directory.razor b/Shared/Pages/Directory.razor index 8f664cc..aa5454f 100644 --- a/Shared/Pages/Directory.razor +++ b/Shared/Pages/Directory.razor @@ -102,7 +102,7 @@ Includes - @foreach (var include in _capabilities.IncludesFor(_fhirSearch.ResourceName)) + @foreach (var include in _capabilities.IncludesFor(_fhirSearch.ResourceName).Prepend($"{_fhirSearch.ResourceName}:*")) { Reverse Includes - @foreach (var revInclude in _capabilities.RevIncludesFor(_fhirSearch.ResourceName)) + @foreach (var revInclude in _capabilities.RevIncludesFor(_fhirSearch.ResourceName).Prepend("*")) { result) $"Error:: Details: {issue.Details?.Text}.
    " + $"Diagnostics: {HtmlSanitizer.Sanitize(issue.Diagnostics)}.
    " + $"IssueType: {issue.Code}.
    ")); + + if (result.OperationOutcome.Issue.Any(i => i.Diagnostics?.Contains("_include", StringComparison.Ordinal) == true)) + { + _outComeMessage += "An _include or _revinclude names a resource and a search parameter, " + + "e.g. PractitionerRole:practitioner, or every reference with PractitionerRole:*."; + } + return; } @@ -363,7 +370,8 @@ private async T.Task SearchHandler(FhirResultModel result) return; } - _fhirResults.RawFhir = await new FhirJsonSerializer().SerializeToStringAsync(result.Result); + _fhirResults.RawFhir = await new FhirJsonSerializer(new SerializerSettings { Pretty = true }) + .SerializeToStringAsync(result.Result); var bundle = new DirectoryBundle(result.Result, _fhirSearch.ResourceName); _fhirResults.Bundle = bundle; diff --git a/Shared/Search/DirectoryBundle.cs b/Shared/Search/DirectoryBundle.cs index fc5d10f..7dd75e0 100644 --- a/Shared/Search/DirectoryBundle.cs +++ b/Shared/Search/DirectoryBundle.cs @@ -182,14 +182,33 @@ public static IEnumerable Npis(Resource resource) private static IEnumerable EndpointReferences(Resource resource) => References(resource).Where(r => r.Path == "endpoint").Select(r => r.Reference); - /// Top-level references of a resource with the element they sit in. - private static IEnumerable<(string Path, string Reference)> References(Resource resource) + /// + /// The references in a resource, labelled by the top-level element they sit in. References inside an + /// extension are labelled by the extension's name (NDH carries PractitionerRole's network that way, in + /// base-ext-network-reference). Contained resources are skipped. + /// + private static IEnumerable<(string Path, string Reference)> References(Base node, string? path = null) { - foreach (var child in resource.NamedChildren) + foreach (var child in node.NamedChildren) { - if (child.Value is ResourceReference { Reference: { Length: > 0 } single }) + var label = child.Value is Extension extension + ? extension.Url?.Split('/').LastOrDefault()?.Replace("base-ext-", string.Empty) ?? child.ElementName + : path ?? child.ElementName; + + switch (child.Value) { - yield return (child.ElementName, single); + case ResourceReference { Reference: { Length: > 0 } reference }: + yield return (label, reference); + break; + case Resource: + case PrimitiveType: + break; + case Base nested: + foreach (var found in References(nested, label)) + { + yield return found; + } + break; } } } diff --git a/_tests/UtilityTests/DirectorySearchTests.cs b/_tests/UtilityTests/DirectorySearchTests.cs index 2cd12e8..ef4b389 100644 --- a/_tests/UtilityTests/DirectorySearchTests.cs +++ b/_tests/UtilityTests/DirectorySearchTests.cs @@ -112,6 +112,22 @@ public void ShowsPractitionerRoleByItsIncludedPractitionerAndOrganization() directory.RelatedTo(role).Select(r => (r.Relation, r.Resource.Id)).ShouldBe([("practitioner", "p1"), ("organization", "o1")]); } + [Fact] + public void FollowsReferencesInsideExtensions() + { + var bundle = new Bundle { Type = Bundle.BundleType.Searchset }; + var role = new PractitionerRole { Id = "role1", Practitioner = new ResourceReference("Practitioner/p1") }; + role.Extension.Add(new Extension("http://hl7.org/fhir/us/ndh/StructureDefinition/base-ext-network-reference", + new ResourceReference("Organization/Network1"))); + bundle.Entry.Add(Match(role)); + bundle.Entry.Add(Include(new Organization { Id = "Network1", Name = "Network1" })); + + var directory = new DirectoryBundle(bundle, "PractitionerRole"); + + directory.RelatedTo(directory.Matches.Single()).Select(r => (r.Relation, r.Resource.Id)) + .ShouldBe([("network-reference", "Network1")]); + } + [Fact] public void ReadsPagingLinks() { From 844f395da285780fd2c2a22a593622d3aa16b1d1 Mon Sep 17 00:00:00 2001 From: Joe Shook Date: Sun, 29 Nov 2026 13:15:32 -0800 Subject: [PATCH 07/13] Directory: keep a typed Base Url on Enter; show the request that was sent - The Base Url suggestions listed the current URL even when it did not match what was typed, so Enter put the old directory back (CMS) and searches meant for the HL7 reference server went to CMS. Suggestions now only match the text. - The results card shows the exact GET/POST that was sent. - An OperationOutcome holding only warnings (a directory ignoring an unknown parameter) shows as a warning, with its diagnostics. Co-Authored-By: Claude Opus 5.5 --- Shared/Pages/Directory.razor | 8 ++++++- Shared/Pages/Directory.razor.cs | 38 +++++++++++++++++++++++---------- 2 files changed, 34 insertions(+), 12 deletions(-) diff --git a/Shared/Pages/Directory.razor b/Shared/Pages/Directory.razor index aa5454f..e6e7647 100644 --- a/Shared/Pages/Directory.razor +++ b/Shared/Pages/Directory.razor @@ -198,9 +198,15 @@ + @if (_lastRequest != null) + { + + Sent: @_lastRequest + + } @if (_outComeMessage != null) { - @(new MarkupString(_outComeMessage)) + @(new MarkupString(_outComeMessage)) } @if (!_fhirResults.RawFhir.IsNullOrEmpty()) { diff --git a/Shared/Pages/Directory.razor.cs b/Shared/Pages/Directory.razor.cs index 8a33f0c..61db836 100644 --- a/Shared/Pages/Directory.razor.cs +++ b/Shared/Pages/Directory.razor.cs @@ -83,15 +83,26 @@ public partial class Directory private List? _postSearchParams; private FhirResults _fhirResults = new(); private string? _outComeMessage; + private Severity _outComeSeverity = Severity.Error; + /// The request the results came from, so it is clear which directory answered. + private string? _lastRequest; private bool _isSearching; private IReadOnlyList Resources => _capabilities.Resources.Count > 0 ? _capabilities.Resources : DirectoryCapabilities.DefaultResources; - private T.Task> SearchKnownDirectories(string? text, CancellationToken token) => - T.Task.FromResult(KnownDirectories.Select(d => d.Url) - .Where(u => string.IsNullOrWhiteSpace(text) || u == _fhirSearch.BaseUrl - || u.Contains(text, StringComparison.OrdinalIgnoreCase))); + /// + /// Suggestions for the Base Url field. Everything while the field is empty or still holds a known URL; + /// otherwise only the URLs containing what was typed, so Enter never swaps a typed URL for the old one. + /// + private T.Task> SearchKnownDirectories(string? text, CancellationToken token) + { + var urls = KnownDirectories.Select(d => d.Url).ToList(); + var showAll = string.IsNullOrWhiteSpace(text) || urls.Contains(text.Trim(), StringComparer.OrdinalIgnoreCase); + return T.Task.FromResult(showAll + ? urls.AsEnumerable() + : urls.Where(u => u.Contains(text!.Trim(), StringComparison.OrdinalIgnoreCase))); + } private static string? DirectoryNote(string? url) => KnownDirectories.FirstOrDefault(d => string.Equals(d.Url, url, StringComparison.OrdinalIgnoreCase)).Note; @@ -291,12 +302,12 @@ private async T.Task SearchGet() if (url != null) { - await RunSearch(() => FhirService.SearchGet(url)); + await RunSearch($"GET {url}", () => FhirService.SearchGet(url)); } } private T.Task SearchPost() => - RunSearch(() => FhirService.SearchPost(new SearchForm + RunSearch($"POST {_fhirSearch.BaseUrl}/{_fhirSearch.ResourceName}/_search", () => FhirService.SearchPost(new SearchForm { Url = _fhirSearch.BaseUrl, Resource = _fhirSearch.ResourceName, @@ -304,13 +315,15 @@ private T.Task SearchPost() => })); /// Follows a Bundle paging link (next, previous, first) exactly as the server gave it. - private T.Task GoToPage(string url) => RunSearch(() => FhirService.SearchGet(url)); + private T.Task GoToPage(string url) => RunSearch($"GET {url}", () => FhirService.SearchGet(url)); - private async T.Task RunSearch(Func>> search) + private async T.Task RunSearch(string request, Func>> search) { _isSearching = true; + _lastRequest = request; _fhirResults = new FhirResults(); _outComeMessage = null; + _outComeSeverity = Severity.Error; StateHasChanged(); try @@ -346,10 +359,13 @@ private async T.Task SearchHandler(FhirResultModel result) if (result.OperationOutcome != null) { + // A directory that ignores a parameter answers 200 with a warning and no matches (the CMS NPD does). + _outComeSeverity = result.OperationOutcome.Issue.All(i => + i.Severity is OperationOutcome.IssueSeverity.Warning or OperationOutcome.IssueSeverity.Information) + ? Severity.Warning + : Severity.Error; _outComeMessage = string.Concat(result.OperationOutcome.Issue.Select(issue => - $"Error:: Details: {issue.Details?.Text}.
    " - + $"Diagnostics: {HtmlSanitizer.Sanitize(issue.Diagnostics)}.
    " - + $"IssueType: {issue.Code}.
    ")); + $"{issue.Severity}: {HtmlSanitizer.Sanitize(issue.Diagnostics ?? issue.Details?.Text)} ({issue.Code})
    ")); if (result.OperationOutcome.Issue.Any(i => i.Diagnostics?.Contains("_include", StringComparison.Ordinal) == true)) { From e7f459186882680c59278b094c74f0a320856c1d Mon Sep 17 00:00:00 2001 From: Joe Shook Date: Sun, 29 Nov 2026 13:17:50 -0800 Subject: [PATCH 08/13] Directory: put the URL in the Base Url field first among its suggestions The autocomplete selects the first suggestion on Enter or blur. With every known directory listed, CMS came first and replaced a typed HL7 reference server URL. Co-Authored-By: Claude Opus 5.5 --- Shared/Pages/Directory.razor.cs | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/Shared/Pages/Directory.razor.cs b/Shared/Pages/Directory.razor.cs index 61db836..713f932 100644 --- a/Shared/Pages/Directory.razor.cs +++ b/Shared/Pages/Directory.razor.cs @@ -92,16 +92,20 @@ public partial class Directory _capabilities.Resources.Count > 0 ? _capabilities.Resources : DirectoryCapabilities.DefaultResources; /// - /// Suggestions for the Base Url field. Everything while the field is empty or still holds a known URL; - /// otherwise only the URLs containing what was typed, so Enter never swaps a typed URL for the old one. + /// Suggestions for the Base Url field. The autocomplete highlights the first suggestion and Enter or leaving + /// the field selects it, so the URL in the field always comes first: a typed URL is never swapped for another. /// private T.Task> SearchKnownDirectories(string? text, CancellationToken token) { + var typed = text?.Trim() ?? string.Empty; var urls = KnownDirectories.Select(d => d.Url).ToList(); - var showAll = string.IsNullOrWhiteSpace(text) || urls.Contains(text.Trim(), StringComparer.OrdinalIgnoreCase); - return T.Task.FromResult(showAll - ? urls.AsEnumerable() - : urls.Where(u => u.Contains(text!.Trim(), StringComparison.OrdinalIgnoreCase))); + var exact = urls.Any(u => string.Equals(u, typed, StringComparison.OrdinalIgnoreCase)); + + IEnumerable suggestions = typed.Length == 0 || exact + ? urls.OrderByDescending(u => string.Equals(u, typed, StringComparison.OrdinalIgnoreCase)) + : urls.Where(u => u.Contains(typed, StringComparison.OrdinalIgnoreCase)); + + return T.Task.FromResult(suggestions); } private static string? DirectoryNote(string? url) => From 6c5b199decd69f7dd1b4d23ccabbf19f111be751 Mon Sep 17 00:00:00 2001 From: Joe Shook Date: Sun, 29 Nov 2026 13:20:06 -0800 Subject: [PATCH 09/13] Directory: Base Url is a plain text field with a menu of known directories MudAutocomplete re-selected its first suggestion when the field lost focus, replacing a typed URL with the CMS NPD. A text field keeps exactly what was typed; the menu beside it fills in a known directory. Co-Authored-By: Claude Opus 5.5 --- Shared/Pages/Directory.razor | 31 +++++++++++++++++++++---------- Shared/Pages/Directory.razor.cs | 17 +++-------------- 2 files changed, 24 insertions(+), 24 deletions(-) diff --git a/Shared/Pages/Directory.razor b/Shared/Pages/Directory.razor index e6e7647..d681032 100644 --- a/Shared/Pages/Directory.razor +++ b/Shared/Pages/Directory.razor @@ -12,16 +12,27 @@ - + + + + @foreach (var known in KnownDirectories) + { + + @known.Url + @known.Note + + } + + Resources => _capabilities.Resources.Count > 0 ? _capabilities.Resources : DirectoryCapabilities.DefaultResources; - /// - /// Suggestions for the Base Url field. The autocomplete highlights the first suggestion and Enter or leaving - /// the field selects it, so the URL in the field always comes first: a typed URL is never swapped for another. - /// - private T.Task> SearchKnownDirectories(string? text, CancellationToken token) + private async T.Task PickDirectory(string url) { - var typed = text?.Trim() ?? string.Empty; - var urls = KnownDirectories.Select(d => d.Url).ToList(); - var exact = urls.Any(u => string.Equals(u, typed, StringComparison.OrdinalIgnoreCase)); - - IEnumerable suggestions = typed.Length == 0 || exact - ? urls.OrderByDescending(u => string.Equals(u, typed, StringComparison.OrdinalIgnoreCase)) - : urls.Where(u => u.Contains(typed, StringComparison.OrdinalIgnoreCase)); - - return T.Task.FromResult(suggestions); + _fhirSearch.BaseUrl = url; + await BaseUrlChanged(); } private static string? DirectoryNote(string? url) => From 18123b2c3249cca31b8f510740da0ac2edf86ac7 Mon Sep 17 00:00:00 2001 From: Joe Shook Date: Sun, 29 Nov 2026 13:31:57 -0800 Subject: [PATCH 10/13] Directory: mark options the directory does not advertise; new parameters start blank - Parameters, includes and reverse includes known only from the NDH IG show greyed with "(NDH IG)": the directory's CapabilityStatement does not list them and it may ignore them. Advertised parameters sort first, alphabetically. - Adding a parameter no longer fills in the directory's first listed parameter (PractitionerRole got "practitioner" on CMS, "date" on the HL7 RI). Only resources with an obvious first parameter get one (name; Endpoint connection-type). Co-Authored-By: Claude Opus 5.5 --- Shared/Pages/Directory.razor | 25 ++++++++++++++++---- Shared/Pages/Directory.razor.cs | 26 ++++++++++++++++++--- Shared/Search/DirectoryCapabilities.cs | 17 ++++++++++++++ _tests/UtilityTests/DirectorySearchTests.cs | 6 +++++ 4 files changed, 66 insertions(+), 8 deletions(-) diff --git a/Shared/Pages/Directory.razor b/Shared/Pages/Directory.razor index d681032..d4c9095 100644 --- a/Shared/Pages/Directory.razor +++ b/Shared/Pages/Directory.razor @@ -77,7 +77,18 @@ CoerceValue="true" MaxItems="null" Dense="true" - Variant="Variant.Outlined" /> + Variant="Variant.Outlined"> + + @if (_capabilities.IsAdvertised("param", _fhirSearch.ResourceName, paramCode)) + { + @paramCode + } + else + { + @paramCode (NDH IG) + } + + @foreach (var include in _capabilities.IncludesFor(_fhirSearch.ResourceName).Prepend($"{_fhirSearch.ResourceName}:*")) { - + ValueChanged="@(v => SetInclude(_fhirSearch.Includes, include, v))"> + @IncludeLabel("include", include) + }
    @@ -132,9 +145,11 @@ @foreach (var revInclude in _capabilities.RevIncludesFor(_fhirSearch.ResourceName).Prepend("*")) { - + ValueChanged="@(v => SetInclude(_fhirSearch.RevIncludes, revInclude, v))"> + @IncludeLabel("revinclude", revInclude) + } diff --git a/Shared/Pages/Directory.razor.cs b/Shared/Pages/Directory.razor.cs index 3c34a4a..cd79ae1 100644 --- a/Shared/Pages/Directory.razor.cs +++ b/Shared/Pages/Directory.razor.cs @@ -102,7 +102,7 @@ private async T.Task PickDirectory(string url) private string CapabilitiesNote => _capabilities.Source != null - ? $"Parameters and includes from {_capabilities.Source}, plus the NDH IG's." + ? $"Resources, parameters and includes from {_capabilities.Source}. Greyed options marked (NDH IG) are not listed there and the directory may ignore them." : "Parameters and includes from the NDH IG (the directory's CapabilityStatement could not be read)."; protected override async T.Task OnInitializedAsync() @@ -180,15 +180,18 @@ private void ResourceChanged() private T.Task> SearchParamNames(string? text, CancellationToken token) => T.Task.FromResult(_capabilities.SearchParamsFor(_fhirSearch.ResourceName) + .OrderByDescending(code => _capabilities.IsAdvertised("param", _fhirSearch.ResourceName, code)) + .ThenBy(code => code, StringComparer.Ordinal) .Where(code => string.IsNullOrWhiteSpace(text) || code.Contains(text, StringComparison.OrdinalIgnoreCase))); private void AddSearchParam() { + // A new row starts blank, except for the first row of a resource with an obvious first parameter. + // Guessing the directory's first listed parameter picked unhelpful ones (PractitionerRole: practitioner, date). var used = _fhirSearch.SearchParams.Select(p => p.Name).ToHashSet(); var name = DefaultParam(_fhirSearch.ResourceName) is { } preferred && !used.Contains(preferred.Name) ? preferred - : (_capabilities.SearchParamsFor(_fhirSearch.ResourceName).FirstOrDefault(code => !used.Contains(code)) ?? string.Empty, - null); + : (string.Empty, null); _fhirSearch.SearchParams.Add(new FhirSearchParam(name.Name, string.Empty, null, name.Value ?? string.Empty) { @@ -216,6 +219,23 @@ private void DeleteParam(FhirSearchParam fhirSearchParam) private static bool IncludeChecked(Dictionary map, string key) => map.GetValueOrDefault(key); + /// + /// Wildcards (Resource:*, *) and what the directory advertises read plainly; options known only + /// from the NDH IG are greyed and tagged, since the directory may ignore them. + /// + private RenderFragment IncludeLabel(string kind, string value) => builder => + { + var plain = value.EndsWith('*') || _capabilities.IsAdvertised(kind, _fhirSearch.ResourceName, value); + builder.OpenElement(0, "span"); + if (!plain) + { + builder.AddAttribute(1, "class", "mud-text-secondary"); + builder.AddAttribute(2, "title", "In the NDH IG; this directory's CapabilityStatement does not list it"); + } + builder.AddContent(3, plain ? value : $"{value} (NDH IG)"); + builder.CloseElement(); + }; + private void SetInclude(Dictionary map, string key, bool value) { map[key] = value; diff --git a/Shared/Search/DirectoryCapabilities.cs b/Shared/Search/DirectoryCapabilities.cs index 41e092d..4234894 100644 --- a/Shared/Search/DirectoryCapabilities.cs +++ b/Shared/Search/DirectoryCapabilities.cs @@ -33,6 +33,16 @@ public sealed class DirectoryCapabilities /// Where the directory-specific part came from; null when only the NDH IG is known. public string? Source { get; private init; } + /// Entries the directory's own CapabilityStatement lists, keyed "kind|resource|value". + private readonly HashSet _advertised = new(StringComparer.Ordinal); + + /// + /// Whether the directory itself advertises a search parameter ("param"), include ("include") or reverse + /// include ("revinclude"). True for everything when no directory CapabilityStatement was read. + /// + public bool IsAdvertised(string kind, string? resource, string value) => + Source == null || _advertised.Contains($"{kind}|{resource}|{value}"); + public IReadOnlyList SearchParamsFor(string? resource) => Lookup(SearchParams, resource); public IReadOnlyList IncludesFor(string? resource) => Lookup(Includes, resource); public IReadOnlyList RevIncludesFor(string? resource) => Lookup(RevIncludes, resource); @@ -85,6 +95,8 @@ public DirectoryCapabilities MergedWith(DirectoryCapabilities fallback) merged.Add(resource, SearchParamsFor(resource), IncludesFor(resource), RevIncludesFor(resource)); } + merged._advertised.UnionWith(Source == null ? [] : AllEntries()); + foreach (var resource in fallback.Resources) { if (Resources.Count > 0 && !Resources.Contains(resource)) @@ -99,6 +111,11 @@ public DirectoryCapabilities MergedWith(DirectoryCapabilities fallback) return merged; } + private IEnumerable AllEntries() => + SearchParams.SelectMany(kv => kv.Value.Select(v => $"param|{kv.Key}|{v}")) + .Concat(Includes.SelectMany(kv => kv.Value.Select(v => $"include|{kv.Key}|{v}"))) + .Concat(RevIncludes.SelectMany(kv => kv.Value.Select(v => $"revinclude|{kv.Key}|{v}"))); + private void Add(string resource, IEnumerable searchParams, IEnumerable includes, IEnumerable revIncludes) { diff --git a/_tests/UtilityTests/DirectorySearchTests.cs b/_tests/UtilityTests/DirectorySearchTests.cs index ef4b389..4164807 100644 --- a/_tests/UtilityTests/DirectorySearchTests.cs +++ b/_tests/UtilityTests/DirectorySearchTests.cs @@ -188,6 +188,12 @@ public void PrefersTheDirectoryCapabilitiesAndKeepsTheIgExtras() merged.SearchParamsFor("Organization").ShouldBe(["name", "endpoint"]); merged.IncludesFor("Organization").ShouldBe(["Organization:partof", "Organization:endpoint"]); merged.Source.ShouldBe("cms"); + merged.IsAdvertised("include", "Organization", "Organization:partof").ShouldBeTrue(); + merged.IsAdvertised("include", "Organization", "Organization:endpoint").ShouldBeFalse(); + merged.IsAdvertised("param", "Organization", "name").ShouldBeTrue(); + merged.IsAdvertised("param", "Organization", "endpoint").ShouldBeFalse(); + DirectoryCapabilities.From(ig, "ig").MergedWith(new DirectoryCapabilities()) + .IsAdvertised("param", "Organization", "endpoint").ShouldBeTrue(); } private static Bundle.EntryComponent Match(Resource resource) => Entry(resource, Bundle.SearchEntryMode.Match); From 71c2b3dee761743a5412c4fe8aa45ef660d61e30 Mon Sep 17 00:00:00 2001 From: Joe Shook Date: Sun, 29 Nov 2026 14:14:13 -0800 Subject: [PATCH 11/13] Directory: show wire data and the outgoing request; drop the FAST directory - Directory searches (GetSearch, PostSearch, Get) now run through the request capture handler and return the wire headers on success, not only on errors. The results card shows the HTTP status, the time the directory took, the entry count, compressed and decompressed bytes, and the outgoing request with its headers, as the Patient pages do. - RequestCaptureHandler times the call to the FHIR server (X-Fhir-Elapsed-Ms); the web client reads it into FhirResultModel.FhirElapsedMs. - https://national-directory.fast.hl7.org/fhir is gone from the known directories and from udap_urls.json; it is no longer used. Co-Authored-By: Claude Opus 5.5 --- Client/Services/FhirService.cs | 20 +++++++--- Client/wwwroot/Packages/udap_urls.json | 1 - Server/Controllers/FhirController.cs | 31 ++++++++++++---- Server/Services/Fhir/RequestCaptureHandler.cs | 13 ++++++- Shared/Model/FhirResultModel.cs | 2 + Shared/Pages/Directory.razor | 37 +++++++++++++++++++ Shared/Pages/Directory.razor.cs | 23 ++++++++---- Shared/Search/DirectoryBundle.cs | 3 ++ Shared/UdapEdConstants.cs | 1 + Shared/wwwroot/Packages/udap_urls.json | 1 - 10 files changed, 109 insertions(+), 23 deletions(-) diff --git a/Client/Services/FhirService.cs b/Client/Services/FhirService.cs index 9c58fb8..17c588b 100644 --- a/Client/Services/FhirService.cs +++ b/Client/Services/FhirService.cs @@ -295,23 +295,27 @@ public async Task> SearchGet(string queryParameters) { var controller = await GetControllerPath(); var response = await _httpClient.PostAsJsonAsync($"{controller}/GetSearch", queryParameters); - - return await SearchHandler(response); + var result = await SearchHandler(response); + EnrichResult(response, result); + return result; } public async Task> SearchPost(SearchForm searchForm) { var controller = await GetControllerPath(); var response = await _httpClient.PostAsJsonAsync($"{controller}/PostSearch", searchForm); - - return await SearchHandler(response); + var result = await SearchHandler(response); + EnrichResult(response, result); + return result; } public async Task> Get(string resourcePath) { var controller = await GetControllerPath(); var response = await _httpClient.PostAsJsonAsync($"{controller}/Get", resourcePath); - return await GetHandler(response); + var result = await GetHandler(response); + EnrichResult(response, result); + return result; } private async Task> GetHandler(HttpResponseMessage response) @@ -653,6 +657,12 @@ private void EnrichResult(HttpResponseMessage responseMessage, FhirResultMode } } + if (responseMessage.Headers.TryGetValues(UdapEdConstants.FhirClient.FhirElapsedMs, out var elapsedValues) + && long.TryParse(elapsedValues.FirstOrDefault(), out var elapsedMs)) + { + resultModel.FhirElapsedMs = elapsedMs; + } + if (responseMessage.Headers.TryGetValues(UdapEdConstants.FhirClient.FhirOutgoingRequest, out var reqValues)) { var base64 = reqValues.FirstOrDefault(); diff --git a/Client/wwwroot/Packages/udap_urls.json b/Client/wwwroot/Packages/udap_urls.json index a8d5a3e..aacd506 100644 --- a/Client/wwwroot/Packages/udap_urls.json +++ b/Client/wwwroot/Packages/udap_urls.json @@ -6,7 +6,6 @@ "https://dev-mtx-interop.meditech.com/v2/uscore/STU6", "https://securefhir.zimt.work/udap-public", "https://identity-matching.fast.hl7.org/fhir", - "https://national-directory.fast.hl7.org/fhir", "https://udap.fhir.poolnook.me/evernorth", "https://fhir-udap.azurewebsites.net", "https://ihe-nimbus.epic.com/Interconnect-FHIR/api/fhir/r4" diff --git a/Server/Controllers/FhirController.cs b/Server/Controllers/FhirController.cs index 2c26132..59d587c 100644 --- a/Server/Controllers/FhirController.cs +++ b/Server/Controllers/FhirController.cs @@ -356,14 +356,13 @@ public async Task GetSearch([FromBody] string fullSearch) { try { - //Todo maybe inject in the future, so we don't exhaust underlying HttpClient - var httpClient = new HttpClient(_customDecompressionHandler); + using var httpClient = DirectoryHttpClient(); var fhirClient = new FhirClient(fullSearch, httpClient, new FhirClientSettings() { PreferredFormat = ResourceFormat.Json }); - Console.WriteLine(fullSearch); var bundle = await fhirClient.GetAsync(fullSearch); var bundleJson = await new FhirJsonSerializer().SerializeToStringAsync(bundle); + CopyCustomHeadersToResponse(); return Ok(bundleJson); } catch (FhirOperationException ex) @@ -402,8 +401,7 @@ public async Task PostSearch([FromBody] SearchForm searchForm) { try { - //Todo maybe inject in the future, so we don't exhaust underlying HttpClient - var httpClient = new HttpClient(_customDecompressionHandler); + using var httpClient = DirectoryHttpClient(); var fhirClient = new FhirClient(searchForm.Url, httpClient, new FhirClientSettings() { PreferredFormat = ResourceFormat.Json }); var searchParams = new SearchParams(); @@ -416,6 +414,7 @@ public async Task PostSearch([FromBody] SearchForm searchForm) var bundle = await fhirClient.SearchUsingPostAsync(searchParams, searchForm.Resource); var bundleJson = await new FhirJsonSerializer().SerializeToStringAsync(bundle); + CopyCustomHeadersToResponse(); return Ok(bundleJson); } catch (FhirOperationException ex) @@ -454,13 +453,13 @@ public async Task Get([FromBody] string resourcePath) { try { - var httpClient = new HttpClient(_customDecompressionHandler); + using var httpClient = DirectoryHttpClient(); var fhirClient = new FhirClient(resourcePath, httpClient, new FhirClientSettings() { PreferredFormat = ResourceFormat.Json }); - - Console.WriteLine(resourcePath); + var resource = await fhirClient.GetAsync(resourcePath); var resourceJson = await new FhirJsonSerializer().SerializeToStringAsync(resource); + CopyCustomHeadersToResponse(); return Ok(resourceJson); } catch (FhirOperationException ex) @@ -494,6 +493,22 @@ public async Task Get([FromBody] string resourcePath) } } + /// + /// GetSearch, PostSearch and Get go to whatever absolute URL the page sends (a directory, its /metadata), so + /// they skip the session's FhirClientWithUrlProvider and its access token. This pipeline still asks for + /// compression and records the wire sizes, the outgoing request and the elapsed time for the page. + /// + private HttpClient DirectoryHttpClient() + { + var services = HttpContext.RequestServices; + var accessor = services.GetRequiredService(); + + return new HttpClient(new CustomDecompressionHandler(services.GetRequiredService(), accessor) + { + InnerHandler = new RequestCaptureHandler(accessor) { InnerHandler = new HttpClientHandler() } + }); + } + private void CopyCustomHeadersToResponse() { foreach (var kvp in HttpContext.Items.Where(i => i.Key is string key && key.StartsWith("X-"))) diff --git a/Server/Services/Fhir/RequestCaptureHandler.cs b/Server/Services/Fhir/RequestCaptureHandler.cs index 621c7c4..4d1e8bd 100644 --- a/Server/Services/Fhir/RequestCaptureHandler.cs +++ b/Server/Services/Fhir/RequestCaptureHandler.cs @@ -7,6 +7,7 @@ // */ #endregion +using System.Diagnostics; using System.Text; using System.Text.Json; using UdapEd.Shared; @@ -71,6 +72,16 @@ protected override async Task SendAsync( Convert.ToBase64String(Encoding.UTF8.GetBytes(json)); } - return await base.SendAsync(request, cancellationToken); + // Time the call to the FHIR server alone: this handler is innermost, so the UdapEd hop is not counted. + var stopwatch = Stopwatch.StartNew(); + var response = await base.SendAsync(request, cancellationToken); + stopwatch.Stop(); + + if (httpContext != null) + { + httpContext.Items[UdapEdConstants.FhirClient.FhirElapsedMs] = stopwatch.ElapsedMilliseconds.ToString(); + } + + return response; } } diff --git a/Shared/Model/FhirResultModel.cs b/Shared/Model/FhirResultModel.cs index 9ad253b..db0022c 100644 --- a/Shared/Model/FhirResultModel.cs +++ b/Shared/Model/FhirResultModel.cs @@ -21,6 +21,8 @@ public class FhirResultModel public Version? Version { get; private set; } public int? FhirCompressedSize { get; set; } public int? FhirDecompressedSize { get; set; } + /// Milliseconds the FHIR server took to answer, timed by UdapEd's server. + public long? FhirElapsedMs { get; set; } public OutgoingRequestInfo? OutgoingRequestInfo { get; set; } // Public flags (kept as fields to match existing signature) diff --git a/Shared/Pages/Directory.razor b/Shared/Pages/Directory.razor index d4c9095..493fbb8 100644 --- a/Shared/Pages/Directory.razor +++ b/Shared/Pages/Directory.razor @@ -229,6 +229,43 @@ Sent: @_lastRequest + @if (!_isSearching && (_fhirResults.HttpStatus != null || _fhirResults.ElapsedMs != null)) + { + + @if (_fhirResults.HttpStatus != null) + { + HTTP @_fhirResults.HttpStatus + } + @if (_fhirResults.ElapsedMs != null) + { + @_fhirResults.ElapsedMs.Value.ToString("N0") ms + } + @if (_fhirResults.Bundle != null) + { + @_fhirResults.Bundle.EntryCount entries + } + + } + + @if (_fhirResults.OutgoingRequest is { } outgoing) + { + + +
    @($"{outgoing.Method} {outgoing.Url} HTTP/1.1")
    + @foreach (var header in outgoing.Headers) + { +
    @header.Name: @header.Value
    + } + @if (outgoing.Body != null) + { +
    @outgoing.Body
    + } +
    +
    + } } @if (_outComeMessage != null) { diff --git a/Shared/Pages/Directory.razor.cs b/Shared/Pages/Directory.razor.cs index cd79ae1..7ac688e 100644 --- a/Shared/Pages/Directory.razor.cs +++ b/Shared/Pages/Directory.razor.cs @@ -53,8 +53,7 @@ public partial class Directory private static readonly IReadOnlyList<(string Url, string Note)> KnownDirectories = [ ("https://directory.cms.gov/fhir", "CMS National Provider Directory (anonymous search)"), - ("https://ndh-server.fast.hl7.org/fhir", "HL7 NDH reference server, Connectathon 43 (anonymous search)"), - ("https://national-directory.fast.hl7.org/fhir", "HL7 FAST directory (needs a UDAP B2B token)") + ("https://ndh-server.fast.hl7.org/fhir", "HL7 NDH reference server, Connectathon 43 (anonymous search)") ]; private const int DefaultPageSize = 20; @@ -358,6 +357,17 @@ private async T.Task RunSearch(string request, Func result) { + // What went over the wire, kept for errors as well as results. + _fhirResults.CompressedSize = result.FhirCompressedSize; + _fhirResults.DecompressedSize = result.FhirDecompressedSize; + _fhirResults.ElapsedMs = result.FhirElapsedMs; + _fhirResults.OutgoingRequest = result.OutgoingRequestInfo; + + if (result.HttpStatusCode != null) + { + _fhirResults.HttpStatus = $"{(int)result.HttpStatusCode} {result.HttpStatusCode}"; + } + if (result.UnAuthorized) { _outComeMessage = $"{HttpStatusCode.Unauthorized}. This directory needs an access token: get one on the B2B page first."; @@ -389,11 +399,6 @@ private async T.Task SearchHandler(FhirResultModel result) return; } - if (result.HttpStatusCode != null) - { - _fhirResults.HttpStatus = $"HTTP/{result.Version} {(int)result.HttpStatusCode} {result.HttpStatusCode}"; - } - if (result.Result == null) { return; @@ -715,6 +720,10 @@ public record FhirHierarchyEntry private sealed class FhirResults { public string? HttpStatus { get; set; } + public int? CompressedSize { get; set; } + public int? DecompressedSize { get; set; } + public long? ElapsedMs { get; set; } + public OutgoingRequestInfo? OutgoingRequest { get; set; } public string? RawFhir { get; set; } public DirectoryBundle? Bundle { get; set; } public List> TreeViewStore { get; } = []; diff --git a/Shared/Search/DirectoryBundle.cs b/Shared/Search/DirectoryBundle.cs index 7dd75e0..781db51 100644 --- a/Shared/Search/DirectoryBundle.cs +++ b/Shared/Search/DirectoryBundle.cs @@ -48,6 +48,7 @@ public DirectoryBundle(Bundle bundle, string? searchedResource) .ToList(); Total = bundle.Total; + EntryCount = bundle.Entry.Count; NextUrl = LinkUrl(bundle, "next"); PreviousUrl = LinkUrl(bundle, "previous") ?? LinkUrl(bundle, "prev"); FirstUrl = LinkUrl(bundle, "first"); @@ -55,6 +56,8 @@ public DirectoryBundle(Bundle bundle, string? searchedResource) public IReadOnlyList Matches { get; } public int? Total { get; } + /// All entries on the page: matches, includes and outcomes. + public int EntryCount { get; } public string? NextUrl { get; } public string? PreviousUrl { get; } public string? FirstUrl { get; } diff --git a/Shared/UdapEdConstants.cs b/Shared/UdapEdConstants.cs index 94a44a2..6ad98fc 100644 --- a/Shared/UdapEdConstants.cs +++ b/Shared/UdapEdConstants.cs @@ -69,5 +69,6 @@ public static class FhirClient public const string FhirCompressedSize = "X-Fhir-Compressed-Size"; public const string FhirDecompressedSize = "X-Fhir-Decompressed-Size"; public const string FhirOutgoingRequest = "X-Fhir-Outgoing-Request"; + public const string FhirElapsedMs = "X-Fhir-Elapsed-Ms"; } } \ No newline at end of file diff --git a/Shared/wwwroot/Packages/udap_urls.json b/Shared/wwwroot/Packages/udap_urls.json index a8d5a3e..aacd506 100644 --- a/Shared/wwwroot/Packages/udap_urls.json +++ b/Shared/wwwroot/Packages/udap_urls.json @@ -6,7 +6,6 @@ "https://dev-mtx-interop.meditech.com/v2/uscore/STU6", "https://securefhir.zimt.work/udap-public", "https://identity-matching.fast.hl7.org/fhir", - "https://national-directory.fast.hl7.org/fhir", "https://udap.fhir.poolnook.me/evernorth", "https://fhir-udap.azurewebsites.net", "https://ihe-nimbus.epic.com/Interconnect-FHIR/api/fhir/r4" From 5c727ada63eb338c2c83e9c4c410d941b955e656 Mon Sep 17 00:00:00 2001 From: Joe Shook Date: Sun, 29 Nov 2026 14:19:30 -0800 Subject: [PATCH 12/13] Directory: click a result to open it in a resource viewer Names in the results tree (matches, related resources, endpoints, references not in the page) open FhirResourceDialog: the resource as readable rows (names, identifiers, contacts, addresses, codes, periods, NDH extensions by name) with its JSON on a second tab. References inside it are links; one already in the search Bundle opens at once, anything else is read from the directory. Back walks the trail. Co-Authored-By: Claude Opus 5.5 --- Shared/Components/FhirResourceDialog.razor | 250 +++++++++++++++++++++ Shared/Pages/Directory.razor | 14 +- Shared/Pages/Directory.razor.cs | 49 ++++ 3 files changed, 309 insertions(+), 4 deletions(-) create mode 100644 Shared/Components/FhirResourceDialog.razor diff --git a/Shared/Components/FhirResourceDialog.razor b/Shared/Components/FhirResourceDialog.razor new file mode 100644 index 0000000..fe5c4af --- /dev/null +++ b/Shared/Components/FhirResourceDialog.razor @@ -0,0 +1,250 @@ +@* + Shows one FHIR resource as readable sections, with its JSON alongside. References are links: a resource + already in hand (the search Bundle) opens at once, anything else goes through Resolve. Back walks the trail. +*@ +@using Hl7.Fhir.Model +@using Hl7.Fhir.Serialization +@using Task = System.Threading.Tasks.Task + + + + + @if (_trail.Count > 1) + { + + } + @Current.TypeName + @Title(Current) + @($"{Current.TypeName}/{Current.Id}") + + @if (_error != null) + { + @_error + } + + +
    + @if (Current.Meta is { } meta) + { + + @if (meta.LastUpdated != null) + { + Last updated @meta.LastUpdated.Value.ToString("u") + } + @foreach (var profile in meta.Profile) + { + Profile: @ShortUrl(profile) + } + + } + @Elements(Current, topLevel: true) +
    +
    + +
    @Json(Current)
    +
    +
    +
    + + Close + +
    + +@code { + [CascadingParameter] IMudDialogInstance MudDialog { get; set; } = null!; + + /// The resource to show first. + [Parameter] public Resource Resource { get; set; } = null!; + + /// Turns a reference into a resource: the search Bundle first, then the directory. + [Parameter] public Func>? Resolve { get; set; } + + /// Display name for a resource; the dialog falls back to the resource id. + [Parameter] public Func? DisplayName { get; set; } + + private readonly List _trail = []; + private string? _error; + + private Resource Current => _trail.Count > 0 ? _trail[^1] : Resource; + + /// Elements that are bookkeeping rather than content; meta is shown in the header line. + private static readonly HashSet SkippedTopLevel = ["id", "meta", "text", "contained", "implicitRules", "language"]; + + protected override void OnInitialized() + { + _trail.Add(Resource); + } + + private string Title(Resource resource) => DisplayName?.Invoke(resource) ?? resource.Id ?? resource.TypeName; + + private void Back() + { + if (_trail.Count > 1) + { + _trail.RemoveAt(_trail.Count - 1); + _error = null; + } + } + + private async Task Follow(string reference) + { + _error = null; + Resource? target = null; + + try + { + target = Resolve == null ? null : await Resolve(reference); + } + catch (Exception ex) + { + _error = $"Could not read {reference}: {ex.Message}"; + return; + } + + if (target == null) + { + _error = $"Could not read {reference}."; + return; + } + + _trail.Add(target); + } + + private static string Json(Resource resource) => + new FhirJsonSerializer(new SerializerSettings { Pretty = true }).SerializeToString(resource); + + private static string ShortUrl(string? url) => + url == null ? string.Empty : url.TrimEnd('/').Split('/').LastOrDefault() ?? url; + + /// The element name, or the extension's name for an extension. + private static string Label(ElementValue child) => + child.Value is Extension extension ? ShortUrl(extension.Url).Replace("base-ext-", string.Empty) : child.ElementName; + + /// The children of an element, grouped by name so repeats sit together. + private RenderFragment Elements(Base node, bool topLevel = false) => __builder => + { + var groups = node.NamedChildren + .Where(c => !topLevel || !SkippedTopLevel.Contains(c.ElementName)) + .GroupBy(Label) + .ToList(); + + + @foreach (var group in groups) + { + + + + + } +
    + @group.Key + + @foreach (var child in group) + { +
    @Value(child.Value)
    + } +
    + }; + + /// One value: the common datatypes read as a line, anything else nests. + private RenderFragment Value(object? value) => __builder => + { + switch (value) + { + case null: + break; + case ResourceReference reference: + var label = reference.Display ?? reference.Reference ?? reference.Identifier?.Value ?? "(reference)"; + if (!string.IsNullOrEmpty(reference.Reference)) + { + @label + @if (reference.Display != null) + { + @reference.Reference + } + } + else + { + @label + } + break; + case Extension extension when extension.Value != null && extension.Extension.Count == 0: + @Value(extension.Value) + break; + case Extension extension: + @SubExtensions(extension) + break; + case Coding coding: + @CodingText(coding) + break; + case CodeableConcept concept: + + @(concept.Text ?? string.Join(", ", concept.Coding.Select(CodingText))) + + break; + case Hl7.Fhir.Model.Identifier identifier: + + @identifier.Value + + @(string.Join(" · ", new[] { identifier.Type?.Text ?? identifier.Type?.Coding.FirstOrDefault()?.Code, ShortUrl(identifier.System) }.Where(s => !string.IsNullOrEmpty(s)))) + + + break; + case HumanName name: + + @(name.Text ?? string.Join(" ", name.Prefix.Concat(name.Given).Append(name.Family).Concat(name.Suffix).Where(s => !string.IsNullOrEmpty(s)))) + + break; + case ContactPoint contact: + + @contact.Value + @string.Join(" · ", new[] { contact.System?.ToString(), contact.Use?.ToString() }.Where(s => s != null)) + + break; + case Hl7.Fhir.Model.Address address: + + @(address.Text ?? string.Join(", ", address.Line.Append(address.City).Append(string.Join(" ", new[] { address.State, address.PostalCode }.Where(s => !string.IsNullOrEmpty(s)))).Append(address.Country).Where(s => !string.IsNullOrEmpty(s)))) + + break; + case Period period: + @(period.StartElement?.Value ?? "…") – @(period.EndElement?.Value ?? "ongoing") + break; + case FhirUrl or FhirUri or Canonical when value.ToString() is { } url && url.StartsWith("http", StringComparison.OrdinalIgnoreCase): + @url + break; + case PrimitiveType primitive: + @primitive.ToString() + break; + case Base complex: +
    @Elements(complex)
    + break; + default: + @value.ToString() + break; + } + }; + + private static string CodingText(Coding coding) => + coding.Display != null ? $"{coding.Display} ({coding.Code})" : coding.Code ?? string.Empty; + + /// A complex extension read as its sub-extensions, labelled by their short urls. + private RenderFragment SubExtensions(Extension extension) => __builder => + { + + @foreach (var sub in extension.Extension) + { + + + + + } + @if (extension.Value != null) + { + + } +
    + @ShortUrl(sub.Url) + @Value(sub)
    @Value(extension.Value)
    + }; +} diff --git a/Shared/Pages/Directory.razor b/Shared/Pages/Directory.razor index 493fbb8..f3488d1 100644 --- a/Shared/Pages/Directory.razor +++ b/Shared/Pages/Directory.razor @@ -314,7 +314,8 @@ @switch (presenter.Type) { case ResourceType: - @presenter.Name + @presenter.Name @if (presenter.Detail != null) { @presenter.Detail @@ -324,20 +325,25 @@ case RelatedType: - @presenter.Detail: @presenter.Name + @presenter.Detail: + @presenter.Name @presenter.ResourceReference break; case UnresolvedType: + @presenter.ResourceReference - @presenter.ResourceReference is not in these results. Tick the endpoint include to fetch it. + is not in these results: click to read it, or tick the endpoint include. break; case EndpointType: - @presenter.Name + @presenter.Name @if (!string.IsNullOrEmpty(presenter.Detail)) { @presenter.Detail diff --git a/Shared/Pages/Directory.razor.cs b/Shared/Pages/Directory.razor.cs index 7ac688e..e012141 100644 --- a/Shared/Pages/Directory.razor.cs +++ b/Shared/Pages/Directory.razor.cs @@ -449,6 +449,55 @@ private async T.Task> ResourceNode(Resource mat return node; } + /// Opens a result in the resource viewer, which follows further references the same way. + private async T.Task OpenResource(string reference) + { + var resource = await ResolveReference(reference); + + if (resource == null) + { + _outComeSeverity = Severity.Warning; + _outComeMessage = $"Could not read {HtmlSanitizer.Sanitize(reference)}."; + return; + } + + var parameters = new DialogParameters + { + { d => d.Resource, resource }, + { d => d.Resolve, ResolveReference }, + { d => d.DisplayName, r => _fhirResults.Bundle?.DisplayName(r) ?? new DirectoryBundle(new Bundle(), null).DisplayName(r) } + }; + + await DialogService.ShowAsync(null, parameters, new DialogOptions + { + MaxWidth = MaxWidth.Large, FullWidth = true, CloseButton = true, CloseOnEscapeKey = true + }); + } + + /// + /// A reference from the results: taken from the search Bundle when it is there, otherwise read from the + /// directory (relative references resolve against the Base Url). + /// + private async T.Task ResolveReference(string reference) + { + if (_fhirResults.Bundle?.Resolve(reference) is { } inBundle) + { + return inBundle; + } + + if (reference.StartsWith('#')) + { + return null; + } + + var url = Uri.TryCreate(reference, UriKind.Absolute, out _) + ? reference + : $"{_fhirSearch.BaseUrl.Trim().TrimEnd('/')}/{reference.TrimStart('/')}"; + var result = await FhirService.Get(url); + + return result.Result is OperationOutcome ? null : result.Result; + } + private static string? NpiDetail(Resource resource) { var npis = DirectoryBundle.Npis(resource).ToList(); From ade5c8fd45e9dd9d9ae6fda09959e4c30ec411f0 Mon Sep 17 00:00:00 2001 From: Joe Shook Date: Mon, 30 Nov 2026 11:22:36 -0800 Subject: [PATCH 13/13] Bump asset version to 0.9.2507 Co-Authored-By: Claude Opus 5.5 --- Client/wwwroot/index.html | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/Client/wwwroot/index.html b/Client/wwwroot/index.html index bddd2ef..579b8b4 100644 --- a/Client/wwwroot/index.html +++ b/Client/wwwroot/index.html @@ -22,10 +22,10 @@ - - - - + + + + @@ -44,12 +44,12 @@ 🗙 - - - - + + + + - +