import type { PractitionerRole } from "fhir/r4"; export type AdoptOwnNewRoleOutcome = "ignored" | "adopted" | "refresh-failed" | "stale"; interface AdoptOwnNewRoleDeps { isMine: (role: PractitionerRole) => boolean; reMint: () => Promise; adopt: (role: PractitionerRole) => void; /** False once the session or practice that saw the role has changed. */ stillCurrent: () => boolean; onRefreshFailed: () => void; } // A role added to yourself opens its workspace only with a token that carries its scopes, so the // workspace waits for a successful refresh; a failed one keeps the saved role and the old session. export async function adoptOwnNewRole(role: PractitionerRole, deps: AdoptOwnNewRoleDeps): Promise { if (!deps.isMine(role)) return "ignored"; const token = await deps.reMint().catch(() => null); if (!deps.stillCurrent()) return "stale"; if (!token) { deps.onRefreshFailed(); return "refresh-failed"; } deps.adopt(role); return "adopted"; }