import { environment } from "../environments/environment"; const FHIR_ID = /^[A-Za-z0-9\-.]{1,64}$/; const LOCAL_BASES = [environment.fhirClinicalApi, environment.fhirBaseApi]; const pathUnder = (reference: string, bases: readonly string[]): string | undefined => { let url: URL; try { url = new URL(reference); } catch { return undefined; } if (url.search || url.hash || url.username || url.password) return undefined; const full = url.origin + url.pathname; for (const base of bases) { const root = new URL(base); const prefix = root.origin + root.pathname.replace(/\/+$/, "") + "/"; if (full.startsWith(prefix)) return full.slice(prefix.length); } return undefined; }; // The id a reference names only when it is the current version of a `type` resource: `Type/id`, or an absolute url // under one of this deployment's own FHIR bases. Another server's url, and versioned, contained or queried forms, name nothing. export const referencedId = (reference: string | undefined, type: string, localBases: readonly string[] = LOCAL_BASES): string | undefined => { if (typeof reference !== "string" || !reference) return undefined; const absolute = /^[A-Za-z][A-Za-z0-9+.-]*:/.test(reference); if (!absolute && (reference.includes("?") || reference.includes("#"))) return undefined; const path = absolute ? pathUnder(reference, localBases) : reference; const parts = path?.split("/") ?? []; return parts.length === 2 && parts[0] === type && FHIR_ID.test(parts[1]) ? parts[1] : undefined; };