@mindbill/browser 0.50.0 → 0.50.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.ts +1 -0
- package/dist/index.js +28 -0
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.d.ts
CHANGED
|
@@ -1348,6 +1348,7 @@ type BillReferenceClientOptions = Omit<BillLifecycleClientOptions, "billId">;
|
|
|
1348
1348
|
/** Browser-session options for an atomic immutable bill submission. */
|
|
1349
1349
|
type BillSubmissionClientOptions = BillReferenceClientOptions;
|
|
1350
1350
|
type BillSubmissionClient = {
|
|
1351
|
+
previewCms1500: (bill: BrowserBillSubmissionInput["bill"]) => Promise<Blob>;
|
|
1351
1352
|
submitBill: (input: BrowserBillSubmissionInput, options?: {
|
|
1352
1353
|
idempotencyKey?: string;
|
|
1353
1354
|
}) => Promise<BrowserBillSubmissionResult>;
|
package/dist/index.js
CHANGED
|
@@ -693,7 +693,35 @@ function createBillSubmissionClient({
|
|
|
693
693
|
const bill = envelope;
|
|
694
694
|
return { billId: bill.id, bill };
|
|
695
695
|
};
|
|
696
|
+
const previewCms1500 = async (bill) => {
|
|
697
|
+
const controller = new AbortController();
|
|
698
|
+
let browserSession = await mintSession(controller.signal);
|
|
699
|
+
const perform = (current) => {
|
|
700
|
+
const base = (current.apiBaseUrl ?? apiBaseUrl).replace(/\/$/, "");
|
|
701
|
+
return fetcher(`${base}/partner/v2/bills/preview-cms1500`, {
|
|
702
|
+
method: "POST",
|
|
703
|
+
headers: {
|
|
704
|
+
authorization: `Bearer ${current.token}`,
|
|
705
|
+
"content-type": "application/json"
|
|
706
|
+
},
|
|
707
|
+
body: JSON.stringify(bill),
|
|
708
|
+
signal: controller.signal
|
|
709
|
+
});
|
|
710
|
+
};
|
|
711
|
+
let response = await perform(browserSession);
|
|
712
|
+
if (response.status === 401) {
|
|
713
|
+
session = null;
|
|
714
|
+
browserSession = await mintSession(controller.signal, true);
|
|
715
|
+
response = await perform(browserSession);
|
|
716
|
+
}
|
|
717
|
+
if (!response.ok) throw await responseError(response, "The CMS-1500 preview could not be generated.");
|
|
718
|
+
if (!response.headers.get("content-type")?.includes("application/pdf")) {
|
|
719
|
+
throw new Error("The billing service returned an invalid CMS-1500 preview.");
|
|
720
|
+
}
|
|
721
|
+
return response.blob();
|
|
722
|
+
};
|
|
696
723
|
return {
|
|
724
|
+
previewCms1500,
|
|
697
725
|
submitBill,
|
|
698
726
|
clearSession() {
|
|
699
727
|
session = null;
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/claim-fees.ts","../src/rfa-directory.ts","../src/second-review-corrections.ts","../src/rfa-lifecycle.ts","../src/report-autofill.ts","../src/rfa-draft-actions.ts","../src/rfa-packets.ts","../src/rfa-status.ts","../src/index.ts"],"sourcesContent":["import type { BillFeeQuoteInput, BillFeeQuoteBasis } from \"./index\";\n\n/** One patient's complete services for one provider/group. Dates are service dates, not publication dates. */\nexport type CaClaimFeeQuoteInput = {\n lines: Array<Omit<BillFeeQuoteInput, \"billingProviderId\" | \"payerId\" | \"physicianContext\"> & {\n id: string;\n serviceCounty?: string;\n physicianContext?: Omit<NonNullable<BillFeeQuoteInput[\"physicianContext\"]>, \"providerKind\"> & {\n providerKind: NonNullable<BillFeeQuoteInput[\"physicianContext\"]>[\"providerKind\"] | \"clinical_social_worker\";\n telehealthModality?: \"audio_video\" | \"audio_only\";\n cmsSpecialtyCode?: string;\n };\n }>;\n completeDateOfServiceContext: boolean;\n ordinaryMultipleSurgeryContext?: boolean;\n};\nexport type CaFeeCitation = { id: string; url: string; sha256?: string; effectiveFrom?: string; effectiveThrough?: string };\nexport type CaFeeCalculation = {\n method: \"rbrvs\" | \"therapy_mppr\"; locality: string; serviceZip?: string; serviceCounty?: string;\n setting: \"facility\" | \"nonfacility\"; units: number; conversionFactor: string; providerPercent: number;\n baseMaximumCents?: number; cmsIndicators?: Record<string, string>;\n sourceFiles?: Array<{ kind: string; filename: string }>;\n components: Array<{ name: string; rvu: string; gpci: string; payableUnits: number }>;\n rounding: string;\n};\nexport type CaClaimEditFinding = {\n type: string; lineIds: string[]; message: string; citationUrl: string;\n column1?: string; column2?: string; modifierIndicator?: number; code?: string; limit?: number;\n submittedUnits?: number; adjudicationIndicator?: number; scope?: \"line\" | \"patient_provider_date\";\n};\nexport type CaClaimFeeFinding = { code: string; lineIds: string[]; message: string; citationUrl?: string; edit?: CaClaimEditFinding };\nexport type CaClaimLineQuote = ({ status: \"priced\"; amountCents: number; scheduleMaximumCents: number;\n basis: BillFeeQuoteBasis | \"ca_ambulance\"; notes: string[];\n feeBreakdown?: { method: string; inputs: Array<{ label: string; value: string }>; steps: Array<{ label: string; value: string }> };\n} | { status: \"requires_review\" | \"not_separately_payable\"; reason: string }) & {\n provenance: CaFeeCitation[]; calculation?: CaFeeCalculation;\n};\nexport type CaClaimFeeQuoteResult = {\n status: \"priced\" | \"requires_review\" | \"not_separately_payable\";\n lines: Array<{ id: string; input: CaClaimFeeQuoteInput[\"lines\"][number]; quote: CaClaimLineQuote;\n assessment: CaClaimFeeQuoteResult[\"status\"]; findings: CaClaimFeeFinding[];\n paymentAdjustment?: { rule: \"ca_multiple_surgery\"; rank: number; percent: 100 | 50;\n unadjustedScheduleMaximumCents: number; scheduleMaximumCents: number; amountCents: number; citationUrl: string };\n }>;\n totals: { submittedChargeCents: number | null; pricedSubtotalCents: number;\n estimatedPayableCents: number | null; scheduleMaximumCents: number | null; reviewLineCount: number };\n claimEdits: Array<{ dateOfService: string; lineIds: string[]; status: \"evaluated\" | \"requires_review\" | \"source_unavailable\" | \"not_applicable\";\n reason?: string; findings: CaClaimEditFinding[]; provenance?: unknown;\n supportedDateRange?: { from: string; through: string }; supportedDateIntervals?: Array<{ from: string; through: string }>;\n }>;\n limitations: string[];\n};\n\nconst record = (v: unknown): v is Record<string, unknown> => !!v && typeof v === \"object\" && !Array.isArray(v);\nconst strings = (v: unknown): v is string[] => Array.isArray(v) && v.every((x) => typeof x === \"string\");\nconst money = (v: unknown) => Number.isSafeInteger(v) && (v as number) >= 0;\nconst status = (v: unknown) => [\"priced\", \"requires_review\", \"not_separately_payable\"].includes(v as string);\nconst finding = (v: unknown) => record(v) && typeof v.message === \"string\" && strings(v.lineIds) && (v.citationUrl === undefined || typeof v.citationUrl === \"string\");\n/** Validate the transport before a browser displays an allowance. Unknown/partial results fail closed. */\nexport function parseCaClaimFeeQuote(value: unknown, input: CaClaimFeeQuoteInput): CaClaimFeeQuoteResult {\n const invalid = () => { throw new Error(\"Claim fee quote returned an invalid response.\"); };\n if (!record(value) || !status(value.status) || !Array.isArray(value.lines) || value.lines.length !== input.lines.length || !strings(value.limitations) || !record(value.totals) || !Array.isArray(value.claimEdits)) return invalid();\n const totals = value.totals;\n if (!money(totals.pricedSubtotalCents) || !money(totals.reviewLineCount) || [totals.submittedChargeCents, totals.estimatedPayableCents, totals.scheduleMaximumCents].some((v) => v !== null && !money(v))) return invalid();\n if (value.status === \"requires_review\" && totals.estimatedPayableCents !== null) return invalid();\n const expected = new Set(input.lines.map((line) => line.id));\n for (const line of value.lines) {\n if (!record(line) || typeof line.id !== \"string\" || !expected.delete(line.id) || !record(line.input) || typeof line.input.code !== \"string\" || line.input.id !== line.id || line.input.code !== input.lines.find((r) => r.id === line.id)?.code || line.input.dateOfService !== input.lines.find((r) => r.id === line.id)?.dateOfService || !status(line.assessment) || !record(line.quote) || !Array.isArray(line.findings) || !line.findings.every(finding)) return invalid();\n const quote = line.quote;\n if (!status(quote.status) || !Array.isArray(quote.provenance) || !quote.provenance.every((s) => record(s) && typeof s.id === \"string\" && typeof s.url === \"string\" && (s.effectiveFrom === undefined || typeof s.effectiveFrom === \"string\") && (s.effectiveThrough === undefined || typeof s.effectiveThrough === \"string\"))) return invalid();\n if (quote.status === \"priced\") {\n if (!money(quote.amountCents) || !money(quote.scheduleMaximumCents) || typeof quote.basis !== \"string\" || !strings(quote.notes)) return invalid();\n } else if (typeof quote.reason !== \"string\") return invalid();\n if (quote.calculation !== undefined) {\n const c = quote.calculation;\n if (!record(c) || typeof c.locality !== \"string\" || typeof c.conversionFactor !== \"string\" || !Number.isFinite(c.providerPercent) || ![\"facility\", \"nonfacility\"].includes(c.setting as string) || (c.sourceFiles !== undefined && (!Array.isArray(c.sourceFiles) || !c.sourceFiles.every((f) => record(f) && typeof f.kind === \"string\" && typeof f.filename === \"string\"))) || (c.cmsIndicators !== undefined && (!record(c.cmsIndicators) || !Object.values(c.cmsIndicators).every((v) => typeof v === \"string\"))) || !Array.isArray(c.components) || !c.components.every((r) => record(r) && typeof r.name === \"string\" && typeof r.rvu === \"string\" && typeof r.gpci === \"string\" && typeof r.payableUnits === \"number\")) return invalid();\n }\n if (quote.feeBreakdown !== undefined) {\n const b = quote.feeBreakdown;\n if (!record(b) || ![b.inputs, b.steps].every((rows) => Array.isArray(rows) && rows.every((r) => record(r) && typeof r.label === \"string\" && typeof r.value === \"string\"))) return invalid();\n }\n if (line.paymentAdjustment !== undefined) {\n const a = line.paymentAdjustment;\n if (!record(a) || !money(a.amountCents) || !money(a.scheduleMaximumCents) || !money(a.unadjustedScheduleMaximumCents) || typeof a.citationUrl !== \"string\" || ![100,50].includes(a.percent as number) || !money(a.rank)) return invalid();\n }\n }\n if (!value.claimEdits.every((edit) => record(edit) && typeof edit.dateOfService === \"string\" && strings(edit.lineIds) && [\"evaluated\", \"requires_review\", \"source_unavailable\", \"not_applicable\"].includes(edit.status as string) && Array.isArray(edit.findings) && edit.findings.every(finding) && (edit.reason === undefined || typeof edit.reason === \"string\"))) return invalid();\n return value as unknown as CaClaimFeeQuoteResult;\n}\n","import type { BillClaimsAdministratorDirectory } from \"./index\";\n\nexport type RfaAuthorizationDestinationOption = {\n method: \"fax\" | \"email\";\n destination: string;\n label: string;\n phone?: string;\n /** Recipient attention line, retained on the reviewed delivery cover. */\n recipientName?: string;\n};\n\n/** Accept fax numbers only, never telephone notes, email addresses, or extensions. */\nexport function normalizeRfaFax(value: string): string | null {\n const input = value.trim();\n if (/^\\+[1-9]\\d{7,14}$/.test(input)) return input;\n if (!/^\\+?[\\d ().-]+$/.test(input)) return null;\n const digits = input.replace(/\\D/g, \"\");\n if (digits.length === 10 && !input.startsWith(\"+\")) return `+1${digits}`;\n return digits.length === 11 && digits.startsWith(\"1\") ? `+${digits}` : null;\n}\n\n/** Returns choices only. Selecting or transmitting a destination is a separate user action. */\nexport function rfaAuthorizationDestinations(directory: BillClaimsAdministratorDirectory | null): RfaAuthorizationDestinationOption[] {\n if (!directory || [\"adjuster_specific_required\", \"daisybill_unverified\", \"profile_not_published\"].includes(directory.authorizationStatus ?? \"\")) return [];\n return (directory.authorization ?? []).flatMap((contact) => {\n const common = { label: contact.location || contact.name || \"Authorization department\", ...(contact.name ? { recipientName: contact.name } : {}), ...(contact.phone ? { phone: contact.phone } : {}) };\n const options: RfaAuthorizationDestinationOption[] = [];\n const fax = contact.fax ? normalizeRfaFax(contact.fax) : null;\n if (fax && contact.method !== \"email\") options.push({ ...common, method: \"fax\", destination: fax });\n if (contact.email?.trim() && contact.method !== \"fax\") options.push({ ...common, method: \"email\", destination: contact.email.trim() });\n return options;\n });\n}\n\nexport function rfaAuthorizationGuidance(directory: BillClaimsAdministratorDirectory | null): string {\n switch (directory?.authorizationStatus) {\n case \"central_fax\": return \"Select the central authorization fax after confirming it applies to this claim.\";\n case \"central_email\": return \"Authorization is routed by email. Confirm the recipient for this claim before sending the reviewed packet.\";\n case \"claim_handling_location_routes\": return \"Choose the office handling this claim. Authorization destinations vary by office.\";\n case \"adjuster_specific_required\": return \"Obtain the authorization destination from the handling adjuster.\";\n case \"daisybill_unverified\": return \"The directory has not verified an authorization destination. Confirm it with the handling adjuster.\";\n case \"profile_not_published\": return \"No authorization destination is currently published. Confirm a current destination with the handling adjuster.\";\n default: return \"Select an authorization contact or enter a destination confirmed with the handling adjuster.\";\n }\n}\n","import type { SecondReviewLineInput } from \"./index\";\n\nexport type CorrectionDraft = {\n correctBilling: boolean;\n units: string;\n modifiers: string;\n charge: string;\n chargeReviewed: boolean;\n};\n\nexport function parseSecondReviewCorrection(draft: CorrectionDraft): SecondReviewLineInput[\"correction\"] {\n if (!draft.correctBilling) return undefined;\n const units = Number(draft.units);\n const charge = Number(draft.charge);\n const modifiers = draft.modifiers.trim().toUpperCase().split(/[\\s,]+/).filter(Boolean);\n if (!draft.units.trim() || !Number.isInteger(units) || units < 1 || units > 10_000) {\n throw new Error(\"Corrected units must be a whole number from 1 to 10,000.\");\n }\n if (modifiers.length > 4 || new Set(modifiers).size !== modifiers.length || modifiers.some((value) => !/^[A-Z0-9]{2}$/.test(value))) {\n throw new Error(\"Enter up to four unique two-character modifiers, separated by commas. Leave blank to remove modifiers.\");\n }\n if (!draft.charge.trim() || !Number.isFinite(charge) || charge < 0 || charge > 999_999.99 || Math.abs(charge * 100 - Math.round(charge * 100)) > 0.000001) {\n throw new Error(\"Enter the corrected charge in dollars and cents.\");\n }\n if (!draft.chargeReviewed) throw new Error(\"Confirm that you reviewed the corrected charge. It is not recalculated automatically.\");\n return { units, modifiers, charge };\n}\n","import type { BillLifecycleSession, OrganizationClientOptions, RfaRecord } from \"./index\";\n\nexport type RfaReceiptInput = {\n channel: \"fax\" | \"email\" | \"edi\" | \"portal\" | \"mail\" | \"manual\";\n receivedAt: string;\n proofDocumentId?: string;\n providerMessageId?: string;\n};\nexport type RfaInformationRequestInput = { requestedAt: string; requestText: string; dueAt?: string };\nexport type RfaInformationResponseInput = { respondedAt: string; responseDocumentIds: string[] };\nexport type RfaTreatmentDecisionInput = {\n itemId: string; outcome: \"approved\" | \"modified\" | \"denied\";\n authorizationNumber?: string; authorizedProcedureCode?: string; authorizedQuantity?: number; authorizedUnits?: number;\n effectiveFrom?: string; effectiveTo?: string; decisionReason?: string; reviewerName?: string; reviewerPhone?: string;\n};\nexport type RfaDecisionsInput = { decidedAt: string; responseDocumentId: string; imrDocumentId?: string; decisions: RfaTreatmentDecisionInput[] };\nexport type RfaScheduling = {\n itemId: string; serviceDescription: string; outcome: string; eligible: boolean;\n authorizationToken: string; version: number; disposition: \"pending\" | \"scheduled\" | \"no_appointment\" | \"canceled\";\n current: boolean; appointmentAt: string | null; providerName: string | null; location: string | null;\n reason: string | null; updatedAt: string | null;\n};\nexport type RfaSchedulingInput = { expectedVersion: number; authorizationToken: string } & (\n { disposition: \"scheduled\"; appointmentAt: string; providerName: string; location: string } |\n { disposition: \"no_appointment\" | \"canceled\"; reason: string }\n);\nexport type RfaTreatmentClosureInput = { closed: boolean; reason: string; expectedVersion: number };\nexport type RfaTreatmentClosure = { closed: boolean; reason: string; version: number; updatedAt: string; updatedBy: string };\nexport type RfaDecisionCorrectionInput = { itemId: string; expectedDecisionEventId: string; reason: string; replacement: RfaDecisionsInput };\nexport type RfaHistoryEvent = { id: string; sequence: number; eventType: string; actor: string; payload: Record<string, unknown>; occurredAt: string | null };\nexport type RfaFollowUp = {\n id: string; rfaId: string; claimId: string; responseDocumentId: string | null; responseFilename: string | null;\n kind: string; status: string; dueAt: string; assigneeReference: string | null; snoozedUntil: string | null;\n lastOutcome: string | null; lastNote: string | null; createdAt: string; updatedAt: string; resolvedAt: string | null;\n};\nexport type RfaFollowUpUpdate = {\n assigneeReference?: string | null; snoozedUntil?: string | null;\n outcome?: \"message_left\" | \"decision_pending\" | \"decision_issued\" | \"not_on_file\" | \"reviewed\";\n note?: string;\n responseReview?: { disposition: \"no_new_decision\"; noNewDecisionConfirmed: true } | { disposition: \"decisions_recorded\"; allDecisionsRecordedConfirmed: true };\n};\nexport type RfaInboundFax = {\n id: string; receivedAt: string; fromFax: string | null; fromName: string | null; pages: number | null;\n ocrStatus: string | null; matchedRfaId: string | null; documentId: string | null; previewUrl: string;\n suggestedRfaIds: string[];\n};\nexport type RfaInboundFaxMatch = { faxId: string; rfaId: string; documentId: string; alreadyAttached: boolean };\nexport type RfaFollowUpList = { data: RfaFollowUp[]; nextCursor: string | null };\nexport type RfaLifecycleClient = {\n listInboundFaxes(query?: { includeMatched?: boolean; cursor?: string; limit?: number }): Promise<{ data: RfaInboundFax[]; hasMore: boolean; nextCursor: string | null }>;\n getInboundFaxContent(faxId: string): Promise<Blob>;\n matchInboundFax(faxId: string, rfaId: string, idempotencyKey: string): Promise<RfaInboundFaxMatch>;\n listScheduling(id: string): Promise<RfaScheduling[]>;\n updateScheduling(id: string, itemId: string, input: RfaSchedulingInput, idempotencyKey: string): Promise<RfaScheduling[]>;\n updateTreatmentClosure(id: string, itemId: string, input: RfaTreatmentClosureInput, idempotencyKey: string): Promise<RfaRecord>;\n correctDecision(id: string, input: RfaDecisionCorrectionInput, idempotencyKey: string): Promise<RfaRecord>;\n listHistory(id: string): Promise<RfaHistoryEvent[]>;\n addNote(id: string, text: string, idempotencyKey: string): Promise<RfaHistoryEvent>;\n recordReceipt(id: string, input: RfaReceiptInput, idempotencyKey: string): Promise<RfaRecord>;\n recordInformationRequest(id: string, input: RfaInformationRequestInput, idempotencyKey: string): Promise<RfaRecord>;\n recordInformationResponse(id: string, requestId: string, input: RfaInformationResponseInput, idempotencyKey: string): Promise<RfaRecord>;\n recordDecisions(id: string, input: RfaDecisionsInput, idempotencyKey: string): Promise<RfaRecord>;\n listFollowUps(query?: { patientId?: string; renderingProviderId?: string; claimId?: string; includeResolved?: boolean; limit?: number; cursor?: string }): Promise<RfaFollowUpList>;\n updateFollowUp(id: string, input: RfaFollowUpUpdate, idempotencyKey: string): Promise<RfaFollowUp>;\n clearSession(): void;\n};\n/** Records clinical workflow evidence. These methods never send faxes or reconcile notification queues. */\nexport function createRfaLifecycleClient({ sessionEndpoint = \"/api/mindbill/session\", getSession, apiBaseUrl = \"https://app.mindbill.org\", fetch: fetchOverride }: OrganizationClientOptions = {}): RfaLifecycleClient {\n const fetcher = fetchOverride ?? globalThis.fetch;\n let session: BillLifecycleSession | null = null;\n let pending: Promise<BillLifecycleSession> | null = null;\n const failure = async (response: Response): Promise<Error> => {\n const body = await response.json().catch(() => null) as { detail?: unknown; message?: unknown } | null;\n const detail = body?.detail ?? body?.message;\n return new Error(typeof detail === \"string\" ? detail : `The RFA request failed (${response.status}).`);\n };\n const mint = (force = false): Promise<BillLifecycleSession> => {\n if (!force && session && (!session.expiresAt || Date.parse(session.expiresAt) > Date.now() + 30_000)) return Promise.resolve(session);\n if (pending) return pending;\n pending = (async () => {\n const value: unknown = getSession ? await getSession({ signal: new AbortController().signal }) : await (async () => {\n const response = await fetcher(sessionEndpoint, { method: \"POST\", credentials: \"same-origin\", headers: { \"content-type\": \"application/json\" }, body: \"{}\" });\n if (!response.ok) throw await failure(response);\n return response.json();\n })();\n const envelope = value as { session?: unknown; data?: unknown } | null;\n const candidate = (envelope?.session ?? envelope?.data ?? value) as BillLifecycleSession | null;\n if (!candidate || typeof candidate.token !== \"string\" || candidate.token.length < 8) throw new Error(\"The RFA session endpoint did not return a browser session token.\");\n session = { token: candidate.token, ...(typeof candidate.expiresAt === \"string\" ? { expiresAt: candidate.expiresAt } : {}), ...(typeof candidate.apiBaseUrl === \"string\" ? { apiBaseUrl: candidate.apiBaseUrl } : {}) };\n return session;\n })().finally(() => { pending = null; });\n return pending;\n };\n const responseFor = async (path: string, init: RequestInit = {}): Promise<Response> => {\n const perform = (active: BillLifecycleSession) => {\n const headers = new Headers(init.headers); headers.set(\"authorization\", `Bearer ${active.token}`);\n if (init.body) headers.set(\"content-type\", \"application/json\");\n return fetcher(`${(active.apiBaseUrl ?? apiBaseUrl).replace(/\\/$/, \"\")}/partner/v2/${path}`, { ...init, headers });\n };\n let response = await perform(await mint());\n if (response.status === 401) response = await perform(await mint(true));\n if (!response.ok) throw await failure(response);\n return response;\n };\n const request = async <T>(path: string, init: RequestInit = {}): Promise<T> => (await responseFor(path, init)).json() as Promise<T>;\n const mutate = async <T extends { id: string }>(path: string, input: unknown, key: string, method = \"POST\"): Promise<T> => {\n if (!key.trim()) throw new Error(\"An idempotency key is required.\");\n const result = await request<{ data: T }>(path, { method, headers: { \"idempotency-key\": key }, body: JSON.stringify(input) });\n if (!result.data?.id) throw new Error(\"The RFA response was invalid.\");\n return result.data;\n };\n const path = (id: string, suffix: string) => `rfas/${encodeURIComponent(id)}/${suffix}`;\n const readArray = async <T>(route: string, init?: RequestInit): Promise<T[]> => {\n const result = await request<{ data: T[] }>(route, init);\n if (!Array.isArray(result.data)) throw new Error(\"The RFA response was invalid.\");\n return result.data;\n };\n return {\n listInboundFaxes: async (query = {}) => {\n const params = new URLSearchParams();\n for (const [key, value] of Object.entries(query)) if (value !== undefined) params.set(key, String(value));\n const result = await request<{ data: RfaInboundFax[]; hasMore: boolean; nextCursor: string | null }>(`rfa-inbound-faxes${params.size ? `?${params}` : \"\"}`);\n if (!Array.isArray(result.data) || typeof result.hasMore !== \"boolean\" || (result.nextCursor !== null && typeof result.nextCursor !== \"string\") || (result.hasMore && !result.nextCursor)) throw new Error(\"The inbound fax response was invalid.\");\n return result;\n },\n getInboundFaxContent: async faxId => (await responseFor(`rfa-inbound-faxes/${encodeURIComponent(faxId)}/content`)).blob(),\n matchInboundFax: async (faxId, rfaId, key) => {\n if (!key.trim()) throw new Error(\"An idempotency key is required.\");\n if (!rfaId.trim()) throw new Error(\"Choose an authorization request.\");\n const result = await request<{ data: RfaInboundFaxMatch }>(`rfa-inbound-faxes/${encodeURIComponent(faxId)}/match`, { method: \"POST\", headers: { \"idempotency-key\": key }, body: JSON.stringify({ rfaId }) });\n if (!result.data?.documentId || result.data.faxId !== faxId || result.data.rfaId !== rfaId) throw new Error(\"The fax match response was invalid.\");\n return result.data;\n },\n listScheduling: id => readArray<RfaScheduling>(path(id, \"scheduling\")),\n updateScheduling: (id, itemId, input, key) => {\n if (!key.trim()) return Promise.reject(new Error(\"An idempotency key is required.\"));\n return readArray<RfaScheduling>(path(id, `items/${encodeURIComponent(itemId)}/scheduling`), { method: \"PATCH\", headers: { \"idempotency-key\": key }, body: JSON.stringify(input) });\n },\n updateTreatmentClosure: (id, itemId, input, key) => {\n const reason = input.reason.trim();\n if (!reason || reason.length > 2000) return Promise.reject(new Error(\"Enter a reason of 1–2000 characters.\"));\n if (!Number.isInteger(input.expectedVersion) || input.expectedVersion < 0) return Promise.reject(new Error(\"Refresh to load the current treatment version.\"));\n return mutate(path(id, `items/${encodeURIComponent(itemId)}/closure`), { ...input, reason }, key, \"PATCH\");\n },\n correctDecision: (id, input, key) => mutate(path(id, \"decision-corrections\"), input, key),\n listHistory: id => readArray<RfaHistoryEvent>(path(id, \"events\")),\n addNote: (id, text, key) => {\n if (!text.trim()) return Promise.reject(new Error(\"Enter a note.\"));\n return mutate<RfaHistoryEvent>(path(id, \"events\"), { text: text.trim() }, key);\n },\n recordReceipt: (id, input, key) => {\n if (!input.proofDocumentId?.trim() && !input.providerMessageId?.trim()) return Promise.reject(new Error(\"Receipt requires a proof document or provider reference.\"));\n return mutate(path(id, \"transmissions\"), { ...input, direction: \"inbound\", status: \"received\", occurredAt: input.receivedAt }, key);\n },\n recordInformationRequest: (id, input, key) => mutate(path(id, \"information-requests\"), input, key),\n recordInformationResponse: (id, requestId, input, key) => mutate(path(id, `information-requests/${encodeURIComponent(requestId)}`), input, key),\n recordDecisions: (id, input, key) => mutate(path(id, \"decisions\"), input, key),\n listFollowUps: async (query = {}) => {\n const params = new URLSearchParams();\n for (const [key, value] of Object.entries(query)) if (value !== undefined) params.set(key, String(value));\n const result = await request<RfaFollowUpList>(`rfa-follow-ups${params.size ? `?${params}` : \"\"}`);\n if (!Array.isArray(result.data) || !(result.nextCursor === null || typeof result.nextCursor === \"string\")) throw new Error(\"The RFA follow-up response was invalid.\");\n return result;\n },\n updateFollowUp: (id, input, key) => mutate(`rfa-follow-ups/${encodeURIComponent(id)}`, input, key, \"PATCH\"),\n clearSession: () => { session = null; },\n };\n}\n","import type { BillLifecycleSession, OrganizationClientOptions } from \"./index\";\n\nexport type ReportAutofillField = { key: string; value: string; sourceText: string; confidence: \"high\" | \"medium\" };\nexport type ReportAutofillMatch = { status: \"matched\" | \"ambiguous\" | \"none\"; candidates: Array<{ id: string; name: string }>; selectedId?: string };\nexport type ReportAutofillResult = {\n model: \"gpt-5.6-luna\"; requiresReview: true; fields: ReportAutofillField[];\n matches: Record<\"patient\" | \"billingProvider\" | \"renderingProvider\" | \"serviceLocation\", ReportAutofillMatch>;\n warnings: string[];\n};\nexport type ReportAutofillClient = { analyze(report: File): Promise<ReportAutofillResult>; clearSession(): void };\n/** Available only by written agreement, with an organization-wide autofill:run session. Does not save a document or submit a bill. */\nexport function createReportAutofillClient({ sessionEndpoint = \"/api/mindbill/session\", getSession, apiBaseUrl = \"https://app.mindbill.org\", fetch: fetchOverride }: OrganizationClientOptions = {}): ReportAutofillClient {\n const fetcher = fetchOverride ?? globalThis.fetch;\n let session: BillLifecycleSession | null = null;\n const error = async (response: Response) => {\n const body = await response.json().catch(() => null) as { detail?: unknown; message?: unknown } | null;\n return new Error(typeof body?.detail === \"string\" ? body.detail : typeof body?.message === \"string\" ? body.message : `Report analysis failed (${response.status}).`);\n };\n const mint = async (): Promise<BillLifecycleSession> => {\n if (session && (!session.expiresAt || Date.parse(session.expiresAt) > Date.now() + 30_000)) return session;\n const value: unknown = getSession ? await getSession({ signal: new AbortController().signal }) : await (async () => {\n const response = await fetcher(sessionEndpoint, { method: \"POST\", credentials: \"same-origin\", headers: { \"content-type\": \"application/json\" }, body: \"{}\" });\n if (!response.ok) throw await error(response);\n return response.json();\n })();\n const envelope = value as { session?: unknown; data?: unknown } | null;\n const candidate = (envelope?.session ?? envelope?.data ?? value) as BillLifecycleSession | null;\n if (!candidate || typeof candidate.token !== \"string\" || candidate.token.length < 8) throw new Error(\"The report session endpoint did not return a browser session token.\");\n session = candidate;\n return candidate;\n };\n return {\n clearSession: () => { session = null; },\n analyze: async report => {\n if (report.type !== \"application/pdf\") throw new Error(\"Choose a PDF report.\");\n if (!report.size || report.size > 25 * 1024 * 1024) throw new Error(\"Choose a non-empty PDF report no larger than 25 MB.\");\n const perform = async () => {\n const active = await mint(); const body = new FormData(); body.append(\"report\", report);\n return fetcher(`${(active.apiBaseUrl ?? apiBaseUrl).replace(/\\/$/, \"\")}/partner/v2/report-autofill`, { method: \"POST\", headers: { authorization: `Bearer ${active.token}` }, body });\n };\n let response = await perform();\n if (response.status === 401) { session = null; response = await perform(); }\n if (!response.ok) throw await error(response);\n const envelope = await response.json() as { data?: ReportAutofillResult };\n const result = envelope.data;\n if (!result || result.requiresReview !== true || !Array.isArray(result.fields) || !Array.isArray(result.warnings) || !result.matches\n || result.fields.some(field => !field || typeof field.key !== \"string\" || typeof field.value !== \"string\" || typeof field.sourceText !== \"string\" || ![\"high\", \"medium\"].includes(field.confidence))\n || result.warnings.some(warning => typeof warning !== \"string\")\n || ([\"patient\", \"billingProvider\", \"renderingProvider\", \"serviceLocation\"] as const).some(kind => {\n const match = result.matches[kind];\n return !match || ![\"matched\", \"ambiguous\", \"none\"].includes(match.status) || !Array.isArray(match.candidates) || match.candidates.some(candidate => !candidate || typeof candidate.id !== \"string\" || typeof candidate.name !== \"string\");\n })) throw new Error(\"The report analysis response was invalid.\");\n return result;\n },\n };\n}\n","import type { BillLifecycleSession, OrganizationClientOptions, RfaRecord } from \"./index\";\n\nexport type RfaDraftActionsClient = {\n /** Copies the request content into a new unsigned draft. Attachments and delivery are not copied. */\n copy(id: string, expectedRevision: number, idempotencyKey: string): Promise<RfaRecord>;\n /** Cancels only an unchanged, unsigned, unsubmitted draft; audit history is retained. */\n cancelDraft(id: string, expectedRevision: number, idempotencyKey: string): Promise<RfaRecord>;\n clearSession(): void;\n};\n\nexport function createRfaDraftActionsClient({ sessionEndpoint = \"/api/mindbill/session\", getSession, apiBaseUrl = \"https://app.mindbill.org\", fetch: fetchOverride }: OrganizationClientOptions = {}): RfaDraftActionsClient {\n const fetcher = fetchOverride ?? globalThis.fetch;\n let session: BillLifecycleSession | null = null;\n let pending: Promise<BillLifecycleSession> | null = null;\n const failure = async (response: Response) => {\n const body = await response.json().catch(() => null) as { detail?: unknown; message?: unknown; error?: { message?: unknown } } | null;\n const detail = body?.detail ?? body?.message ?? body?.error?.message;\n return new Error(typeof detail === \"string\" ? detail : `The RFA request failed (${response.status}).`);\n };\n const mint = (force = false): Promise<BillLifecycleSession> => {\n if (!force && session && (!session.expiresAt || Date.parse(session.expiresAt) > Date.now() + 30_000)) return Promise.resolve(session);\n if (pending) return pending;\n pending = (async () => {\n const value: unknown = getSession ? await getSession({ signal: new AbortController().signal }) : await (async () => {\n const response = await fetcher(sessionEndpoint, { method: \"POST\", credentials: \"same-origin\", headers: { \"content-type\": \"application/json\" }, body: \"{}\" });\n if (!response.ok) throw await failure(response);\n return response.json();\n })();\n const envelope = value as { session?: unknown; data?: unknown } | null;\n const candidate = (envelope?.session ?? envelope?.data ?? value) as BillLifecycleSession | null;\n if (!candidate || typeof candidate.token !== \"string\" || candidate.token.length < 8) throw new Error(\"The RFA session endpoint did not return a browser session token.\");\n session = { token: candidate.token, ...(typeof candidate.expiresAt === \"string\" ? { expiresAt: candidate.expiresAt } : {}), ...(typeof candidate.apiBaseUrl === \"string\" ? { apiBaseUrl: candidate.apiBaseUrl } : {}) };\n return session;\n })().finally(() => { pending = null; });\n return pending;\n };\n const mutate = async (id: string, expectedRevision: number, idempotencyKey: string, action: \"copy\" | \"cancel\"): Promise<RfaRecord> => {\n if (!id.trim()) throw new Error(\"An RFA ID is required.\");\n if (!Number.isSafeInteger(expectedRevision) || expectedRevision < 1) throw new Error(\"The current RFA content revision is required.\");\n if (!idempotencyKey.trim()) throw new Error(\"An idempotency key is required.\");\n const perform = (active: BillLifecycleSession) => fetcher(`${(active.apiBaseUrl ?? apiBaseUrl).replace(/\\/$/, \"\")}/partner/v2/rfas/${encodeURIComponent(id)}${action === \"copy\" ? \"/copy\" : \"\"}`, {\n method: action === \"copy\" ? \"POST\" : \"PATCH\", headers: { authorization: `Bearer ${active.token}`, \"content-type\": \"application/json\", \"idempotency-key\": idempotencyKey }, body: JSON.stringify(action === \"copy\" ? { expectedRevision } : { status: \"canceled\", draftOnly: true, expectedRevision }),\n });\n let response = await perform(await mint());\n if (response.status === 401) response = await perform(await mint(true));\n if (!response.ok) throw await failure(response);\n const result = await response.json() as { data?: RfaRecord };\n if (!result.data?.id) throw new Error(\"The RFA response was invalid.\");\n return result.data;\n };\n return {\n copy: (id, revision, key) => mutate(id, revision, key, \"copy\"),\n cancelDraft: (id, revision, key) => mutate(id, revision, key, \"cancel\"),\n clearSession: () => { session = null; },\n };\n}\n","import type { BillLifecycleSession, OrganizationClientOptions } from \"./index\";\n\nexport type RfaSavedPacket = { id: string; source: \"download\" | \"submission\"; sha256: string; sizeBytes: number; contentRevision: number; createdAt: string };\nexport type RfaPacketTransmission = { id: string; packetId: string | null; purpose: \"submission\" | \"forward\"; channel: string; status: string; destination: string | null; occurredAt: string; receivedAt: string | null };\nexport type RfaPacketHistory = { packets: RfaSavedPacket[]; transmissions: RfaPacketTransmission[] };\nexport type RfaForwardInput = { packetId: string; channel: \"fax\" | \"email\"; to: string };\nexport type RfaForwardResult = { transmissionId: string; packetId: string };\nexport type RfaPacketsClient = {\n list(id: string): Promise<RfaPacketHistory>;\n get(id: string, packetId: string): Promise<Blob>;\n /** Forwards retained bytes without changing the original submission or review deadline. */\n forward(id: string, input: RfaForwardInput, idempotencyKey: string): Promise<RfaForwardResult>;\n clearSession(): void;\n};\n\nexport function createRfaPacketsClient({ sessionEndpoint = \"/api/mindbill/session\", getSession, apiBaseUrl = \"https://app.mindbill.org\", fetch: fetchOverride }: OrganizationClientOptions = {}): RfaPacketsClient {\n const fetcher = fetchOverride ?? globalThis.fetch;\n let session: BillLifecycleSession | null = null;\n let pending: Promise<BillLifecycleSession> | null = null;\n const failure = async (response: Response) => {\n const body = await response.json().catch(() => null) as { detail?: unknown; message?: unknown; error?: { message?: unknown } } | null;\n const detail = body?.detail ?? body?.message ?? (typeof body?.error === \"string\" ? body.error : body?.error?.message);\n return new Error(typeof detail === \"string\" ? detail : `The RFA request failed (${response.status}).`);\n };\n const mint = (force = false): Promise<BillLifecycleSession> => {\n if (!force && session && (!session.expiresAt || Date.parse(session.expiresAt) > Date.now() + 30_000)) return Promise.resolve(session);\n if (pending) return pending;\n pending = (async () => {\n const value: unknown = getSession ? await getSession({ signal: new AbortController().signal }) : await (async () => {\n const response = await fetcher(sessionEndpoint, { method: \"POST\", credentials: \"same-origin\", headers: { \"content-type\": \"application/json\" }, body: \"{}\" });\n if (!response.ok) throw await failure(response);\n return response.json();\n })();\n const envelope = value as { session?: unknown; data?: unknown } | null;\n const candidate = (envelope?.session ?? envelope?.data ?? value) as BillLifecycleSession | null;\n if (!candidate || typeof candidate.token !== \"string\" || candidate.token.length < 8) throw new Error(\"The RFA session endpoint did not return a browser session token.\");\n session = { token: candidate.token, ...(typeof candidate.expiresAt === \"string\" ? { expiresAt: candidate.expiresAt } : {}), ...(typeof candidate.apiBaseUrl === \"string\" ? { apiBaseUrl: candidate.apiBaseUrl } : {}) };\n return session;\n })().finally(() => { pending = null; });\n return pending;\n };\n const request = async (id: string, path: string, init?: RequestInit): Promise<Response> => {\n if (!id.trim()) throw new Error(\"An RFA ID is required.\");\n const perform = (active: BillLifecycleSession) => fetcher(`${(active.apiBaseUrl ?? apiBaseUrl).replace(/\\/$/, \"\")}/partner/v2/rfas/${encodeURIComponent(id)}${path}`, {\n ...init, headers: { ...init?.headers, authorization: `Bearer ${active.token}` },\n });\n let response = await perform(await mint());\n if (response.status === 401) response = await perform(await mint(true));\n if (!response.ok) throw await failure(response);\n return response;\n };\n return {\n async list(id) {\n const result = await (await request(id, \"/packets\")).json() as { data?: RfaPacketHistory };\n if (!result.data || !Array.isArray(result.data.packets) || !Array.isArray(result.data.transmissions)) throw new Error(\"The saved packet response was invalid.\");\n return result.data;\n },\n async get(id, packetId) {\n if (!packetId.trim()) throw new Error(\"A saved packet ID is required.\");\n const response = await request(id, `/packets/${encodeURIComponent(packetId)}`);\n if (!response.headers.get(\"content-type\")?.toLowerCase().startsWith(\"application/pdf\")) throw new Error(\"The saved packet response was not a PDF.\");\n return response.blob();\n },\n async forward(id, input, idempotencyKey) {\n if (!input.packetId.trim()) throw new Error(\"A saved packet ID is required.\");\n if (!idempotencyKey.trim()) throw new Error(\"An idempotency key is required.\");\n const to = input.to.trim();\n if (input.channel === \"fax\" ? !/^\\+[1-9]\\d{7,14}$/.test(to) : input.channel !== \"email\" || to.length > 254 || !/^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/.test(to)) throw new Error(\"Enter a valid recipient email or fax number with country code.\");\n const result = await (await request(id, \"/forwards\", { method: \"POST\", headers: { \"content-type\": \"application/json\", \"idempotency-key\": idempotencyKey }, body: JSON.stringify({ packetId: input.packetId, channel: input.channel, to: input.channel === \"email\" ? to.toLowerCase() : to }) })).json() as { data?: RfaForwardResult };\n if (!result.data?.transmissionId || result.data.packetId !== input.packetId) throw new Error(\"The forwarding response was invalid. Check delivery history before retrying.\");\n return result.data;\n },\n clearSession: () => { session = null; },\n };\n}\n","import type { RfaRecord } from \"./index\";\n\nexport type RfaLifecycleStatus = \"incomplete\" | \"sent\" | \"failed\" | \"received\" | \"closed\" | \"canceled\";\nexport const RFA_LIFECYCLE_LABELS: Readonly<Record<RfaLifecycleStatus, string>> = {\n incomplete: \"Incomplete\", sent: \"Sent\", failed: \"Failed\", received: \"Received\", closed: \"Closed\", canceled: \"Canceled\",\n};\ntype LifecycleRecord = Pick<RfaRecord, \"status\"> & Partial<Pick<RfaRecord, \"lifecycleStatus\" | \"submittedAt\" | \"receivedAt\" | \"transmissions\">>;\nconst timestamp = (value: string | null | undefined): number => value ? Date.parse(value) || 0 : 0;\n\n/** Prefer the API lifecycle. Older responses are derived from the current submission's evidence. */\nexport function getRfaLifecycleStatus(rfa: LifecycleRecord): RfaLifecycleStatus {\n if (rfa.lifecycleStatus && Object.hasOwn(RFA_LIFECYCLE_LABELS, rfa.lifecycleStatus)) return rfa.lifecycleStatus;\n if (rfa.status === \"canceled\") return \"canceled\";\n if ([\"closed\", \"approved\", \"modified\", \"denied\", \"mixed\"].includes(rfa.status)) return \"closed\";\n const submissions = (rfa.transmissions ?? []).filter(value => !value.purpose || value.purpose === \"submission\");\n const latest = submissions.filter(value => value.direction === \"outbound\").sort((a, b) =>\n timestamp(b.occurredAt) - timestamp(a.occurredAt) || b.id.localeCompare(a.id))[0];\n if (latest) {\n const received = latest.receivedAt || submissions.some(value => value.direction === \"inbound\" && value.status === \"received\"\n && timestamp(value.receivedAt ?? value.occurredAt) >= timestamp(latest.occurredAt));\n if (received) return \"received\";\n return latest.status === \"failed\" ? \"failed\" : \"sent\";\n }\n if (rfa.receivedAt || [\"received\", \"under_review\", \"information_requested\"].includes(rfa.status)) return \"received\";\n if (rfa.submittedAt || rfa.status === \"submitted\") return \"sent\";\n return \"incomplete\";\n}\n","import { parseCaClaimFeeQuote, type CaClaimFeeQuoteInput, type CaClaimFeeQuoteResult } from \"./claim-fees\";\n/** Paper claim family; clearinghouse transport is selected by the server. */\nexport type ClaimForm = \"cms1500\" | \"ub04\" | \"ada\" | \"ncpdp\";\n/** JSON fields validated by the server's form-specific contract. */\nexport type BillFormValue = string | number | boolean | null | BillFormValue[] | { [key: string]: BillFormValue };\nexport type BillFormData = {\n institutional?: { [key: string]: BillFormValue };\n dental?: { [key: string]: BillFormValue };\n pharmacy?: { [key: string]: BillFormValue };\n};\n/** Service-line metadata, including revenue, tooth, and prescription details. */\nexport type BillLineFormData = BillFormData;\n\nexport type { CaClaimFeeQuoteInput, CaClaimFeeQuoteResult, CaClaimLineQuote, CaFeeCalculation, CaFeeCitation, CaClaimEditFinding, CaClaimFeeFinding } from \"./claim-fees\";\nexport { normalizeRfaFax, rfaAuthorizationDestinations, rfaAuthorizationGuidance } from \"./rfa-directory\";\nexport type { RfaAuthorizationDestinationOption } from \"./rfa-directory\";\nexport const DEFAULT_API_BASE_URL = \"https://app.mindbill.org\";\nexport const DEFAULT_SESSION_ENDPOINT = \"/api/mindbill/session\";\nexport { parseSecondReviewCorrection, type CorrectionDraft } from \"./second-review-corrections\";\n\nexport type BillReviewDocumentType =\n | \"final_report\"\n | \"letter_of_attestation\"\n | \"proof_of_service\"\n | \"form_122\"\n | \"return_to_work_voucher\"\n | \"w9\"\n | \"medical_records\"\n | \"appeal\"\n | \"other\";\n\nexport type BillReviewBillingProvider = {\n name: string;\n taxId: string;\n taxIdType?: \"EIN\" | \"SSN\";\n taxIdConfigured?: boolean;\n taxIdLast4?: string;\n npi: string;\n billType: \"Professional\" | \"Institutional\" | \"Dental\" | \"Pharmacy\";\n phone?: string;\n billingStreet?: string;\n billingCity?: string;\n billingState?: string;\n billingZip?: string;\n};\n\nexport type BillReviewClinician = {\n /** Canonical opaque provider ID, when available. */\n id?: string;\n name: string;\n specialty: string;\n npi: string;\n taxonomy?: string;\n licenseNumber?: string;\n licenseState?: string;\n signaturePng?: string;\n signatureKey?: string;\n isQME?: boolean;\n isAME?: boolean;\n email?: string;\n active?: boolean;\n};\n\nexport type BillReviewLocation = {\n billingProviderId?: string;\n name: string;\n nickname?: string;\n street: string;\n city: string;\n state: string;\n zip: string;\n county?: string;\n posCode?: string;\n isPrimary?: boolean;\n active?: boolean;\n};\n\n/** Verified, server-provided fee explanation. Display strings only; never recalculate fees from these values. */\nexport type BillLineFeeBreakdown = {\n method: string;\n inputs: Array<{ label: string; value: string }>;\n steps: Array<{ label: string; value: string }>;\n notes: string[];\n};\n\nexport type BillReviewLineItem = {\n formData?: BillLineFormData;\n drug?: BilledDrug;\n id?: string;\n code: string;\n modifiers: string[];\n units: number;\n charge: number;\n feeSchedule?: number;\n /** Omitted when no verified fee explanation is available for this saved line. */\n pricing?: { breakdown?: BillLineFeeBreakdown };\n serviceDate?: string | null;\n serviceDateEnd?: string | null;\n diagnosisPointers?: number[];\n};\n\nexport type BillReviewAttachment = {\n id: string;\n filename: string;\n description?: string | null;\n documentType: string;\n reportType?: string | null;\n source?: string;\n addedAt?: string;\n contentUrl?: string;\n};\n\n/** One selectable payer (subpayor) under a claims administrator. */\nexport type BillReviewPayerOption = {\n id: string;\n label: string;\n /** Directory-provided default marker. Interactive forms still require an explicit choice. */\n default?: boolean;\n active?: boolean;\n aliases?: string[];\n hint?: string | null;\n affiliatedEntities?: string[];\n route?: string | null;\n optionType?: string | null;\n deliveryType?: string | null;\n clearinghouse?: string | null;\n payerId?: string | null;\n /** Original directory route when live delivery uses a replacement clearinghouse. */\n sourceClearinghouse?: string | null;\n /** Original directory payer ID when live delivery uses a replacement route. */\n sourcePayerId?: string | null;\n clearinghousePayerIds?: Record<string, string>;\n preferredClearinghouse?: string | null;\n};\n\nexport type BillReviewPayer = {\n id: string;\n name: string;\n hasElectronic?: boolean;\n states?: string[];\n confidence?: \"high\" | \"medium\" | \"directory\";\n recommended?: boolean;\n signals?: Array<{\n kind: \"name\" | \"claim_number\";\n state: \"match\" | \"warning\";\n label: string;\n }>;\n /** True when a bill for this claims administrator must name one of `payers`. */\n payerSelectionRequired?: boolean;\n /** Selectable payers (subpayors) under this claims administrator. */\n payers?: BillReviewPayerOption[];\n aliases?: string[];\n affiliatedEntities?: string[];\n claimNumberHint?: string | null;\n claimNumberPatterns?: BillClaimsAdministratorPattern[];\n route?: string | null;\n};\n\n/** A directory suggestion derived from host-provided evidence. Suggestions are never auto-applied. */\nexport type BillReviewPayerSuggestion = BillReviewPayer & {\n deterministic: boolean;\n reason: string;\n /** A uniquely proven routing payer under a multi-payer claims administrator. */\n selectedPayerId?: string;\n};\n\n/** Host-system evidence shown alongside claims-administrator suggestions. */\nexport type BillClaimsAdministratorSource = {\n source: \"eams\" | \"report\" | string;\n label: string;\n name: string;\n url?: string;\n};\n\n/**\n * The directory-marked default payer option, or null when none is marked.\n * Interactive forms should still require an explicit routing-payer choice.\n */\nexport function defaultBillReviewPayerOption(\n payer: Pick<BillReviewPayer, \"payerSelectionRequired\" | \"payers\">,\n): BillReviewPayerOption | null {\n if (!payer.payerSelectionRequired) return null;\n return payer.payers?.find((option) => option.default) ?? null;\n}\n\nexport type BillPostalPlace = { city: string; state: string };\nexport type BillDiagnosisCode = { code: string; description: string };\n\nexport type BillReviewFeatures = {\n authorizationNumber?: boolean;\n serviceDateRange?: boolean;\n wcabNumber?: boolean;\n codingPresets?: boolean;\n};\n\nexport type BillReviewClaimPatternStatus = {\n state: \"match\" | \"warning\" | \"unknown\";\n label: string;\n detail?: string;\n suggestion?: string;\n};\n\nexport type BillReviewData = {\n options?: Pick<OrganizationProfileData, \"billingProviders\" | \"renderingProviders\" | \"locations\">;\n bill: {\n claimForm?: ClaimForm;\n formData?: BillFormData;\n id: string;\n billNumber: string | number;\n status: string;\n transmissionState?: string;\n billingMode: \"med_legal\" | \"professional\";\n dos: string;\n dosEnd?: string | null;\n authorizationNumber?: string | null;\n billingSnapshot?: {\n billingProvider?: BillReviewBillingProvider;\n renderingProvider?: BillReviewClinician;\n placeOfService?: BillReviewLocation;\n } | null;\n lineItems: BillReviewLineItem[];\n attachments: BillReviewAttachment[];\n totalCharge: number;\n totalPaid: number;\n balanceDue: number;\n };\n patient: {\n /** Canonical opaque patient ID, when available. */\n id?: string;\n name: string;\n firstName?: string;\n middleName?: string;\n lastName?: string;\n dob?: string;\n phone?: string;\n address?: {\n line1?: string;\n city?: string;\n state?: string;\n postalCode?: string;\n };\n };\n injury: {\n claimNumber?: string;\n employer?: string;\n doi?: string;\n injuryEndDate?: string;\n cumulativeTrauma?: boolean;\n adjNumber?: string;\n medicalProviderNetworkId?: string | null;\n claimsAdminId?: string;\n claimsAdminName?: string;\n injuryDescription?: string;\n /** Diagnosis codes enriched with their human-readable ICD-10 descriptions. */\n diagnoses?: BillDiagnosisCode[];\n /** @deprecated Prefer diagnoses so users can understand each code. */\n diagnosisCodes?: string[];\n claimPatternStatus?: BillReviewClaimPatternStatus;\n };\n};\n\nexport type BillReviewSaveInput = {\n formData?: BillFormData;\n claimsAdminId: string;\n /** The chosen payer (subpayor) when the claims administrator requires payer selection. */\n payerId?: string;\n patientOverrides?: {\n firstName: string;\n middleName?: string;\n lastName: string;\n dob?: string;\n };\n injuryOverrides?: {\n claimNumber?: string;\n employer?: string;\n doi?: string;\n injuryEndDate?: string;\n cumulativeTrauma?: boolean;\n adjNumber?: string;\n medicalProviderNetworkId?: string | null;\n };\n dos: string;\n dosEnd?: string | null;\n authorizationNumber?: string | null;\n billingProvider?: BillReviewBillingProvider;\n renderingProvider?: BillReviewClinician;\n placeOfService?: BillReviewLocation;\n lineItems: Array<{\n formData?: BillLineFormData;\n drug?: BilledDrug;\n id?: string;\n code: string;\n modifiers: string[];\n units: number;\n charge?: number;\n serviceDate?: string | null;\n serviceDateEnd?: string | null;\n diagnosisPointers?: number[];\n }>;\n};\n\nfunction pickDefined(\n source: object,\n keys: readonly string[],\n): Record<string, unknown> {\n const record = source as Record<string, unknown>;\n return Object.fromEntries(\n keys.flatMap((key) => record[key] === undefined ? [] : [[key, record[key]]]),\n );\n}\n\n/**\n * Removes read-only snapshot metadata before a review mutation is sent.\n * Lifecycle reads can include display-only fields such as entity IDs; the v2\n * write contract accepts only the values that should be frozen onto the bill.\n */\nexport function sanitizeBillReviewSaveInput(\n input: BillReviewSaveInput,\n): BillReviewSaveInput {\n return {\n claimsAdminId: input.claimsAdminId,\n ...(input.formData !== undefined ? { formData: input.formData } : {}),\n ...(input.payerId !== undefined ? { payerId: input.payerId } : {}),\n ...(input.patientOverrides ? {\n patientOverrides: pickDefined(input.patientOverrides, [\n \"firstName\", \"middleName\", \"lastName\", \"dob\",\n ]) as NonNullable<BillReviewSaveInput[\"patientOverrides\"]>,\n } : {}),\n ...(input.injuryOverrides ? {\n injuryOverrides: pickDefined(input.injuryOverrides, [\n \"claimNumber\", \"employer\", \"doi\", \"injuryEndDate\",\n \"cumulativeTrauma\", \"adjNumber\", \"medicalProviderNetworkId\",\n ]) as NonNullable<BillReviewSaveInput[\"injuryOverrides\"]>,\n } : {}),\n dos: input.dos,\n ...(input.dosEnd !== undefined ? { dosEnd: input.dosEnd } : {}),\n ...(input.authorizationNumber !== undefined\n ? { authorizationNumber: input.authorizationNumber }\n : {}),\n ...(input.billingProvider ? {\n billingProvider: pickDefined(input.billingProvider, [\n \"name\", \"taxId\", \"taxIdType\", \"taxIdConfigured\", \"npi\", \"billType\", \"phone\", \"billingStreet\",\n \"billingCity\", \"billingState\", \"billingZip\",\n ]) as BillReviewBillingProvider,\n } : {}),\n ...(input.renderingProvider ? {\n renderingProvider: pickDefined(input.renderingProvider, [\n \"name\", \"specialty\", \"npi\", \"taxonomy\", \"licenseNumber\",\n \"licenseState\", \"signaturePng\", \"signatureKey\", \"isQME\", \"isAME\",\n \"email\", \"active\",\n ]) as BillReviewClinician,\n } : {}),\n ...(input.placeOfService ? {\n placeOfService: pickDefined(input.placeOfService, [\n \"billingProviderId\", \"name\", \"nickname\", \"street\", \"city\", \"state\",\n \"zip\", \"county\", \"posCode\", \"isPrimary\", \"active\",\n ]) as BillReviewLocation,\n } : {}),\n lineItems: input.lineItems.map((line) => pickDefined(line, [\n \"id\", \"code\", \"modifiers\", \"units\", \"charge\", \"serviceDate\",\n \"serviceDateEnd\", \"diagnosisPointers\", \"formData\", \"drug\",\n ]) as BillReviewSaveInput[\"lineItems\"][number]),\n };\n}\n\nexport type BillSubmissionRoute = \"ebill\" | \"fax\" | \"mail\" | \"email\";\nexport type BillDeliveryOption = {\n route: BillSubmissionRoute;\n label: string;\n detail: string;\n fallback: boolean;\n confidence: string;\n payerName: string;\n target?: string;\n chKey?: string;\n payerId?: string;\n printAndMail?: boolean;\n costUsd?: number;\n};\nexport type BillDeliveryOptions = {\n payerName: string;\n recommended: BillDeliveryOption;\n options: BillDeliveryOption[];\n contacts: {\n faxNumber?: string | null;\n claimsEmail?: string | null;\n portalUrl?: string | null;\n mailingAddress?: string | null;\n adjusterName?: string | null;\n adjusterPhone?: string | null;\n adjusterEmail?: string | null;\n };\n};\nexport type BillActorInput = {\n /** Human-readable name shown for user-initiated audit history. */\n actorName?: string;\n};\n\nexport type AddBillNoteInput = BillActorInput & {\n note: string;\n};\n\nexport type SubmitBillInput = BillActorInput & {\n route: BillSubmissionRoute;\n destination?: {\n faxNumber?: string;\n email?: string;\n mailingAddress?: string;\n };\n attention?: string;\n subject?: string;\n note?: string;\n /** CC recipients for the email route (at most 10). */\n cc?: string[];\n};\nexport type BillLifecycleActionId =\n | \"resubmit\"\n | \"second_review\"\n | \"independent_bill_review\"\n | \"view_eor\"\n | \"post_payment\"\n | \"close\"\n | \"reopen\"\n | \"send_duplicate\"\n | \"report_bill_status\"\n | \"submit_new_bill\";\n\nexport type BillLifecycleAction = {\n id: BillLifecycleActionId;\n label: string;\n enabled: boolean;\n primary?: boolean;\n reason?: string;\n};\n\nexport type BillEorDocument = {\n id: string;\n filename: string;\n description: string | null;\n addedAt: string;\n contentUrl: string;\n};\n\nexport type BillActivityRecord = {\n id: string;\n type: string;\n createdAt: string;\n title?: string;\n description: string;\n actor: string | null;\n delivery: BillSubmissionRoute | null;\n amount: number | null;\n accepted: boolean | null;\n stcCategory: string | null;\n};\n\n/** One user-facing bill history row (Date / Action / User / Details).\n * Server-presented: the wording is authored by MindBill so every surface (MindBill\n * app, React, Angular, embeds) reads identically. */\nexport type BillHistoryEntry = {\n id: string;\n /** Immutable bill attempt that produced this event. Present on unified chain history. */\n attemptId?: string;\n /** ISO timestamp for ordering and the Date column. */\n date: string;\n /** Short Action label — \"Original Bill\", \"277 Accept\", \"Payment\", \"Note\", … */\n action: string;\n kind:\n | \"created\"\n | \"submission\"\n | \"ack\"\n | \"eor\"\n | \"payment\"\n | \"review\"\n | \"close\"\n | \"reopen\"\n | \"note\"\n | \"portal\"\n | \"task\"\n | \"system\";\n /** Who acted: a biller name, MindBill automation, or the responding clearinghouse. */\n actor: string | null;\n /** The one-line Details column. */\n summary: string;\n /** Drives row highlighting: submissions are pale blue, notes pale yellow. */\n tone: \"submission\" | \"note\" | \"neutral\" | \"problem\" | \"success\";\n amount?: number;\n /** Expandable content; absent → the row is not expandable. */\n details?: {\n rows?: Array<{ label: string; value: string }>;\n documents?: Array<{ id: string; filename: string }>;\n complianceDueDates?: Array<{ date: string; text: string }>;\n codes?: Array<{ code: string; text: string }>;\n text?: string;\n };\n};\n\n/** One immutable transmission attempt within a logical bill chain. */\nexport type BillAttemptSummary = {\n /** Unique transmission identity. Draft attempts fall back to the bill record ID. */\n id: string;\n /** Underlying bill record. Multiple transmissions may share this value. */\n billId?: string;\n submissionId?: string;\n billNumber?: string | number;\n label: string;\n deliveryLabel?: string;\n sentAt?: string;\n ackLabel?: string;\n ackAt?: string;\n status?: string;\n complianceLabel?: string;\n complianceAt?: string;\n /** Server-resolved payer outcome; no client-side deadline inference. */\n outcomeLabel?: string;\n outcomeAt?: string;\n outcomeDateLabel?: string;\n outcomeWorkingDays?: number;\n /** The latest attempt that receives lifecycle mutations. */\n isCurrent: boolean;\n};\n\nexport type BillPaymentRecord = {\n id: string;\n method: \"check\" | \"eft\";\n checkNumber: string;\n status: string | null;\n depositDate: string | null;\n checkReceived: boolean | null;\n receivedDate: string | null;\n amount: number;\n principalAmount: number;\n feeAmount: number | null;\n feeReason: string | null;\n source: \"paper\" | \"835\" | \"portal\";\n postedAt: string;\n updatedAt: string | null;\n note: string | null;\n};\n\nexport type BillRemittanceSummary = {\n billedAmount: number;\n expectedAmount: number;\n payerAllowedAmount: number | null;\n payerReportedPaid: number | null;\n postedPrincipal: number;\n postedAdditional: number;\n totalPostedCash: number;\n balanceDue: number;\n denialReason: string | null;\n};\n\nexport type BillLifecycleDelivery = {\n payerName: string;\n contacts: BillDeliveryOptions[\"contacts\"];\n /**\n * Partner-safe directory details. `id` is an opaque MindBill directory ID;\n * Values are safe, partner-facing directory details; internal database identifiers are opaque.\n */\n directory?: BillClaimsAdministratorDirectory | null;\n};\n\nexport type BillClaimsAdministratorContact = {\n location?: string | null;\n method?: \"fax\" | \"email\";\n name?: string | null;\n phone?: string | null;\n email?: string | null;\n fax?: string | null;\n portalUrl?: string | null;\n address?: string | null;\n note?: string | null;\n};\n\nexport type BillClaimsAdministratorMailingAddress = {\n company?: string | null;\n address: string;\n notes?: string | null;\n submissionTypes?: string[];\n billTreatmentTypes?: string[];\n};\n\nexport type BillClaimsAdministratorPattern = {\n length?: number | string | null;\n pattern: string;\n example?: string | null;\n matches?: boolean | null;\n};\n\nexport type BillClaimsAdministratorPayer = {\n name: string;\n route?: string | null;\n aliases?: string[];\n hint?: string | null;\n affiliatedEntities?: string[];\n optionType?: string | null;\n deliveryType?: string | null;\n clearinghouse?: string | null;\n payerId?: string | null;\n sourceClearinghouse?: string | null;\n sourcePayerId?: string | null;\n clearinghousePayerIds?: Record<string, string>;\n preferredClearinghouse?: string | null;\n};\n\nexport type BillReviewPayerPage = {\n results: BillReviewPayer[];\n suggestions?: BillReviewPayerSuggestion[];\n total: number;\n nextOffset?: number;\n recommendedId?: string;\n};\n\nexport type BillReviewPayerListInput = {\n query?: string;\n claimNumber?: string;\n sourceClaimsAdministratorName?: string;\n employerName?: string;\n limit?: number;\n offset?: number;\n};\n\nexport type BillClaimsAdministratorAuthorizationStatus = \"central_fax\" | \"central_email\" | \"claim_handling_location_routes\" | \"adjuster_specific_required\" | \"daisybill_unverified\" | \"profile_not_published\";\n\nexport type BillClaimsAdministratorDirectory = {\n authorizationStatus?: BillClaimsAdministratorAuthorizationStatus;\n authorizationSource?: { url: string; observedAt: string };\n id?: string;\n name?: string;\n type?: string | null;\n description?: string | null;\n website?: string | null;\n aliases?: string[];\n affiliatedEntities?: string[];\n hours?: string | null;\n claimNumberHint?: string | null;\n billProcessingWorkflow?: string | null;\n billProcessingWorkflowNotes?: string | null;\n telephoneNumbers?: string[];\n emailAddresses?: string[];\n webPortals?: string[];\n payers?: BillClaimsAdministratorPayer[];\n authorizationNotice?: string | null;\n billReview?: BillClaimsAdministratorContact[];\n authorization?: BillClaimsAdministratorContact[];\n mailingAddresses?: BillClaimsAdministratorMailingAddress[];\n claimNumberPatterns?: BillClaimsAdministratorPattern[];\n};\n\n/** End-user-safe details explaining why the latest submission was rejected. */\nexport type BillRejectionIssue = {\n code?: string | null;\n description: string;\n /** Bill-submission field paths implicated by this issue. */\n fieldPaths?: string[];\n};\n\nexport type BillRejection = {\n reason: string;\n code?: string | null;\n issues?: BillRejectionIssue[];\n receivedAt?: string | null;\n source?: string | null;\n};\n\nexport type BillTeamNote = { id: string; body: string; author: string; createdAt: string; pinned: boolean };\n\nexport type BillCourtesyCopyInput = {\n to: string[];\n cc?: string[];\n subject: string;\n bodyText: string;\n includeCms1500?: boolean;\n documentIds?: string[];\n};\nexport type BillCourtesyCopyPreview = {\n filename: string; documentCount: number; packetHash: string; pdfBase64: string;\n environment: \"sandbox\" | \"live\";\n};\nexport type BillCourtesyCopyResult = { ok: boolean; sent: boolean; simulated?: boolean; dryRun?: boolean; messageId?: string };\n\n/** Historical financial balances are unavailable, not zero. */\nexport type HistoricalBillReviewData = Omit<BillReviewData, \"bill\"> & {\n bill: Omit<BillReviewData[\"bill\"], \"totalPaid\" | \"balanceDue\"> & {\n totalPaid: number | null;\n balanceDue: number | null;\n };\n};\nexport type BillSubmissionDetail = {\n attemptId: string;\n billId: string;\n source: \"submission_snapshot\" | \"bill_record\" | \"unavailable\";\n capturedAt?: string | null;\n detail: HistoricalBillReviewData | null;\n /** Exact retained files for this attempt; never regenerated from current bill values. */\n artifacts?: Array<{ id: string; label: string; kind: \"submitted_attachment\" | \"submitted_edi\"; contentType: string }>;\n};\n\nexport type BillLifecycleData = BillReviewData & {\n environment: \"sandbox\" | \"live\";\n lifecycle: {\n state: string;\n nativeStatus: string;\n submittedAt?: string | null;\n agingDays?: number | null;\n updatedAt?: string | null;\n actions: BillLifecycleAction[];\n };\n eors: BillEorDocument[];\n activity: BillActivityRecord[];\n /** Presented history rows. Optional: absent when the API\n * predates the presented-history rollout — fall back to `activity`. */\n history?: BillHistoryEntry[];\n /** Canonical team notes, shared with the MindBill app. Absent on older APIs. */\n notes?: BillTeamNote[];\n /** Immutable submissions that share this bill's unified history. */\n attempts?: BillAttemptSummary[];\n /** Per-attempt details. Older APIs may omit this; never substitute the current bill. */\n submissionDetails?: BillSubmissionDetail[];\n payments: BillPaymentRecord[];\n remittance: BillRemittanceSummary;\n delivery: BillLifecycleDelivery;\n rejection?: BillRejection | null;\n};\n\nexport type BillLifecycleSession = {\n token: string;\n expiresAt?: string;\n apiBaseUrl?: string;\n};\n\nexport type BillLifecycleSessionRequest = {\n signal: AbortSignal;\n};\n\nexport type BillLifecycleSessionProvider = (\n request: BillLifecycleSessionRequest,\n) => Promise<BillLifecycleSession>;\n\nexport type CloseBillInput = BillActorInput & { reason: string };\nexport type ReopenBillInput = BillActorInput & { reason: string };\nexport type PostBillPaymentInput = BillActorInput & {\n amount: number;\n penaltyAmount?: number;\n interestAmount?: number;\n method: \"check\" | \"eft\";\n checkNumber?: string;\n depositDate: string;\n note?: string;\n};\nexport type SecondReviewLineInput = {\n lineItemId: string;\n reason: string;\n /** SBR-1 box for this service line. Omitted leaves the box blank. */\n serviceAuthorized?: boolean;\n /** Absolute corrected values for this Second Review only; charge is explicitly reviewed, never inferred. */\n correction?: { units: number; modifiers: string[]; charge: number };\n};\n\nexport type SubmitSecondReviewInput = BillActorInput & {\n /** @deprecated Prefer `lineItems[].reason`; retained for older hosts. */\n reason?: string;\n /** @deprecated MindBill derives this from the payer response on the server. */\n payerClaimControlNumber?: string;\n disputedAmount?: number;\n attachmentIds: string[];\n route: BillSubmissionRoute;\n /** New PDFs to include with the Second Review. */\n documents?: BrowserBillSubmissionDocument[];\n destination?: SubmitBillInput[\"destination\"];\n attention?: string;\n subject?: string;\n note?: string;\n cc?: string[];\n /** Line-by-line SBR-1 selections, reasons, and authorization answers. */\n lineItems?: SecondReviewLineInput[];\n /** @deprecated Prefer `lineItems`; omitted = the whole bill. */\n lineItemIds?: string[];\n /** @deprecated Prefer `lineItems[].serviceAuthorized`. */\n serviceAuthorized?: boolean;\n};\n\nexport type ReportBillStatusId =\n | \"message_left\"\n | \"eor_pending\"\n | \"eor_sent\"\n | \"bill_not_on_file\"\n | \"forwarded\";\n\nexport type ReportBillStatusOption = {\n id: ReportBillStatusId;\n label: string;\n description: string;\n};\n\n/** The five supported outcomes of a bill payment-status phone call. */\nexport const REPORT_BILL_STATUS_OPTIONS: ReportBillStatusOption[] = [\n {\n id: \"message_left\",\n label: \"Message Left Requesting Bill Payment Status\",\n description: \"Claims Administrator/Bill Review representative unavailable.\",\n },\n {\n id: \"eor_pending\",\n label: \"Explanation of Review (EOR) Pending\",\n description: \"Claims Administrator/Bill Review reported the bill is still in process and an EOR has not been generated or sent.\",\n },\n {\n id: \"eor_sent\",\n label: \"Explanation of Review (EOR) Sent\",\n description: \"Claims Administrator/Bill Review reported sending an EOR to the provider.\",\n },\n {\n id: \"bill_not_on_file\",\n label: \"Bill Not On File\",\n description: \"Claims Administrator/Bill Review reported not receiving the bill.\",\n },\n {\n id: \"forwarded\",\n label: \"Bill Forwarded to Different Payer / Network\",\n description: \"Claims Administrator/Bill Review reported forwarding the bill to a different payer.\",\n },\n];\n\n/**\n * Outcome of a phone call to the Claims Administrator / Bill Review vendor\n * about an outstanding bill, recorded through the lifecycle actions endpoint.\n */\nexport type ReportBillStatusInput = BillActorInput & {\n status: ReportBillStatusId;\n company?: string;\n representativeName?: string;\n representativeRole?: string;\n phone?: string;\n callReference?: string;\n note?: string;\n};\n\n/**\n * Payload for the \"report_bill_status\" lifecycle action: records the outcome\n * of a phone call to the Claims Administrator / Bill Review vendor about an\n * outstanding bill. Posted through the generic lifecycle actions endpoint.\n */\nexport type ReportBillStatusActionInput = ReportBillStatusInput & {\n action: \"report_bill_status\";\n};\n\n/**\n * Payload for the \"send_duplicate\" lifecycle action. A duplicate is a fresh,\n * editable bill snapshot linked to the submitted original. The original stays\n * immutable; the biller must review the snapshot and explicitly confirm its\n * delivery route before this action is posted.\n */\nexport type SendDuplicateBillInput = ResubmitBillInput;\n\nexport type ReportBillStatusContacts = {\n claimsAdmin: {\n name: string;\n hoursOfOperation?: string;\n phones: Array<{ label: string; value: string }>;\n } | null;\n billReview: { name: string; phone?: string } | null;\n};\n\n/**\n * Partner-safe \"who to call\" summary for the Report Bill Status flow, derived\n * from the lifecycle delivery block (payer contacts + optional directory).\n */\nexport function reportBillStatusContacts(\n delivery: BillLifecycleDelivery,\n): ReportBillStatusContacts {\n const payerName = delivery.payerName?.trim();\n const directory = delivery.directory ?? null;\n const phones: Array<{ label: string; value: string }> = [];\n const adjusterPhone = delivery.contacts.adjusterPhone?.trim();\n if (adjusterPhone) {\n const adjusterName = delivery.contacts.adjusterName?.trim();\n phones.push({\n label: adjusterName ? `Adjuster (${adjusterName})` : \"Adjuster\",\n value: adjusterPhone,\n });\n }\n const hours = directory?.hours?.trim();\n const claimsAdmin = payerName\n ? {\n name: payerName,\n ...(hours ? { hoursOfOperation: hours } : {}),\n phones,\n }\n : null;\n const billReviewContact = (directory?.billReview ?? []).find(\n (contact) => contact.name?.trim() || contact.phone?.trim(),\n );\n const billReview = billReviewContact\n ? {\n name: billReviewContact.name?.trim() || \"Bill Review\",\n ...(billReviewContact.phone?.trim() ? { phone: billReviewContact.phone.trim() } : {}),\n }\n : null;\n return { claimsAdmin, billReview };\n}\n\n/**\n * Default Second Bill Review dispute reason for an invalid med-legal denial.\n * Prefilled (editable) in the SBR panel.\n */\nexport const SECOND_REVIEW_REASON_TEMPLATE =\n \"This is an appeal of the invalid denial of this med-legal bill; per LC §4622 and the OMFS/MLFS, payment is due as billed.\";\n\n/** Days allowed to request Second Review after service of the denial EOR. */\nexport const SECOND_REVIEW_WINDOW_DAYS = 90;\n\nexport type SecondReviewDeadline = {\n /** ISO date (yyyy-mm-dd) of the latest denial/EOR document. */\n eorDate: string;\n /** ISO date (yyyy-mm-dd) 90 days after the EOR date. */\n deadline: string;\n};\n\n/**\n * The 90-day Second Review window anchored on the latest EOR date, or null\n * when the lifecycle data provides no parseable denial/EOR date.\n */\nexport function secondReviewDeadline(\n eors: Array<Pick<BillEorDocument, \"addedAt\">>,\n): SecondReviewDeadline | null {\n const times = eors\n .map((eor) => Date.parse(eor.addedAt))\n .filter((time) => Number.isFinite(time));\n if (!times.length) return null;\n const eorTime = Math.max(...times);\n const isoDate = (time: number): string => new Date(time).toISOString().slice(0, 10);\n return {\n eorDate: isoDate(eorTime),\n deadline: isoDate(eorTime + SECOND_REVIEW_WINDOW_DAYS * 86_400_000),\n };\n}\n/**\n * A corrected immutable snapshot submitted as the next attempt on the same bill.\n * The logical bill ID remains stable; only the submission/control-number attempt advances.\n */\nexport type ResubmitBillInput = BillActorInput & {\n reason?: string;\n bill: BrowserBillCreateInput;\n /** Explicit delivery route confirmed by the biller for this new attempt. */\n submission?: Omit<SubmitBillInput, keyof BillActorInput>;\n documents?: BrowserBillSubmissionDocument[];\n};\n/**\n * \"Submit New Bill\" from a CLOSED bill: the same snapshot payload shape as a\n * resubmission, but the server creates a FRESH original bill linked to the closed\n * predecessor — the closed bill stays closed and keeps its record, and the\n * submissions ribbon/timeline chains both records.\n */\nexport type SubmitNewBillInput = ResubmitBillInput;\nexport type SandboxSimulationScenario = \"accepted\" | \"rejected\" | \"processed\" | \"denied\" | \"partial_payment\" | \"paid\";\nexport type SimulateSandboxBillInput = {\n scenario: SandboxSimulationScenario;\n amount?: number;\n reasonCode?: string;\n};\n\nexport type BrowserBillAddress = {\n line1: string;\n line2?: string;\n city: string;\n state: string;\n postalCode: string;\n};\n\n/** Complete bill snapshot accepted by the browser create endpoint. */\nexport type BrowserBillCreateInput = {\n claimForm?: ClaimForm;\n formData?: BillFormData;\n externalId?: string;\n billingMode?: \"med_legal\" | \"professional\";\n patient: {\n id?: string;\n externalId?: string;\n firstName: string;\n middleName?: string;\n lastName: string;\n dateOfBirth: string;\n ssn?: string;\n gender?: \"M\" | \"F\" | \"X\";\n phone?: string;\n address: BrowserBillAddress;\n };\n claim: {\n id?: string;\n externalId?: string;\n claimNumber: string;\n adjNumber?: string;\n medicalProviderNetworkId?: string | null;\n employer: string;\n dateOfInjury: string;\n injuryState?: string;\n description?: string;\n claimsAdministrator: {\n id: string;\n name: string;\n /** The chosen payer (subpayor) when the claims administrator requires payer selection. */\n payerId?: string;\n };\n };\n service: { date: string; endDate?: string | null; authorizationNumber?: string | null };\n billingProvider: { id?: string; name: string; taxId: string; taxIdType?: \"EIN\" | \"SSN\"; npi: string; phone: string; address: BrowserBillAddress } | { savedProviderId: string } | { sourceBillId: string };\n renderingProvider: {\n name: string;\n specialty?: string;\n npi: string;\n taxonomy: string;\n licenseNumber?: string;\n licenseState?: string;\n isQme?: boolean;\n isAme?: boolean;\n };\n serviceLocation: { name?: string; address: BrowserBillAddress; placeOfServiceCode: string };\n diagnoses: string[];\n serviceLines: Array<{\n formData?: BillLineFormData;\n code: string;\n modifiers?: string[];\n units?: number;\n charge?: number;\n serviceDate?: string;\n serviceDateEnd?: string | null;\n diagnosisPointers?: number[];\n /** Calculation context revalidated by the server before bill creation. */\n feeContext?: BillFeeContext;\n drug?: BilledDrug;\n /** Existing authorized RFA item linked to this service line. */\n rfaItemId?: string;\n }>;\n};\n\n/** Canonical immutable PDF snapshot sent with a bill submission. */\nexport type BrowserBillSubmissionDocument = {\n externalId?: string;\n filename: string;\n description?: string;\n documentType: BillReviewDocumentType;\n /** Opaque PWK report-type code selected by the component (for example OZ:J4). */\n reportTypeCode?: string;\n contentBase64: string;\n};\n\nexport type BrowserBillSubmissionInput = BillActorInput & {\n /** Usually omitted: MindBill stamps the customer from the server-issued session.\n * If supplied, it must match the session customer restriction. */\n customerExternalId?: string;\n bill: BrowserBillCreateInput;\n submission?: {\n route?: BillSubmissionRoute;\n destination?: SubmitBillInput[\"destination\"];\n attention?: string;\n subject?: string;\n note?: string;\n cc?: string[];\n };\n documents?: BrowserBillSubmissionDocument[];\n};\n\nexport type BrowserSubmittedBill = Record<string, unknown> & {\n id: string;\n customerExternalId?: string | null;\n externalId?: string | null;\n state?: string;\n};\n\nexport type BrowserBillSubmissionResult = {\n billId: string;\n bill: BrowserSubmittedBill;\n};\n\nexport type BillLifecycleClientOptions = {\n /** ID of an already-submitted bill. Bills are created only by the atomic server API. */\n billId: string;\n sessionEndpoint?: string | undefined;\n getSession?: BillLifecycleSessionProvider | undefined;\n apiBaseUrl?: string | undefined;\n fetch?: typeof globalThis.fetch | undefined;\n};\n\n/** Browser-session options for pre-submission reference-data lookups. */\nexport type BillReferenceClientOptions = Omit<BillLifecycleClientOptions, \"billId\">;\n\n/** Browser-session options for an atomic immutable bill submission. */\nexport type BillSubmissionClientOptions = BillReferenceClientOptions;\n\nexport type BillSubmissionClient = {\n submitBill: (\n input: BrowserBillSubmissionInput,\n options?: { idempotencyKey?: string },\n ) => Promise<BrowserBillSubmissionResult>;\n clearSession: () => void;\n};\n\n/** Input for the pre-submission delivery preview keyed on a payer-directory id. */\nexport type BillDeliveryPreviewInput = {\n claimsAdministratorId: string;\n /** Selected payer child when the administrator exposes multiple payer routes. */\n payerId?: string;\n /** Two-letter state; defaults to CA server-side. */\n injuryState?: string;\n};\n\nexport type BillProcedureCodeSearchInput = {\n query?: string;\n limit?: number;\n jurisdiction?: \"CA\" | \"NY\" | \"OWCP\";\n};\n\n/** Catalog membership does not imply that a fee is available for a service date. */\nexport type BillProcedureCodePage = {\n results: Array<{ code: string }>;\n total: number;\n limit: number;\n jurisdiction: \"CA\" | \"NY\" | \"OWCP\";\n catalogAsOf: string | null;\n};\n\nexport type BillFeeSource = {\n id: string;\n url: string;\n sha256?: string;\n effectiveFrom: string;\n effectiveThrough: string;\n};\n\n/** Drug identifiers and quantities printed on the professional claim. */\nexport type BilledDrug = {\n ndcNumber: string;\n metricQuantity: string;\n unitOfMeasure: \"UN\" | \"ML\" | \"GR\";\n administered?: {\n drugName: string;\n administeredAmount: string;\n doseUnit: \"mg\" | \"mcg\" | \"g\" | \"mL\" | \"units\";\n hcpcsCode: string;\n amountPerHcpcsUnit: string;\n amountPerNdcUnit: string;\n hcpcsUnitSource: string;\n productLabelSource: string;\n unitDefinitionsVerified: true;\n };\n};\n\n/** Minutes since midnight on the service date; end must follow start. */\nexport type CaAnesthesiaInterval = { startMinute: number; endMinute: number };\n/** Opaque references to the actual physician and service record. */\nexport type CaAnesthesiaEvent = { physicianRef: string; recordRef: string; minute: number };\nexport type CaAnesthesiaParticipation = CaAnesthesiaInterval & { physicianRef: string; recordRef: string };\nexport type CaAnesthesiaOptionalParticipation = CaAnesthesiaParticipation | { applicability: \"not_indicated\"; recordRef: string };\nexport type CaMedicalDirectionCase = {\n caseRef: string;\n anesthetistRole: \"crna\" | \"anesthesiologist_assistant\" | \"intern\" | \"resident\" | \"student_nurse_anesthetist\";\n qualificationRecordRef: string;\n procedure: \"cataract\" | \"iridectomy\" | \"other\";\n interval: CaAnesthesiaInterval;\n activities: {\n preAnestheticEvaluation: CaAnesthesiaEvent;\n prescribedPlan: CaAnesthesiaEvent;\n demandingProcedures: CaAnesthesiaParticipation[];\n induction: CaAnesthesiaOptionalParticipation;\n emergence: CaAnesthesiaOptionalParticipation;\n qualifiedAnesthetistProcedures: CaAnesthesiaEvent;\n frequentMonitoring: { recordRef: string; observations: CaAnesthesiaEvent[] };\n indicatedPostAnesthesiaCare: CaAnesthesiaEvent;\n };\n};\n/** All overlapping cases across all payers, including cases outside this bill. */\nexport type CaMedicalDirection = {\n physicianRef: string;\n groupPhysicianRefs: string[];\n billedCaseRef: string;\n rosterScope: \"all_overlapping_cases_all_payers\";\n rosterRecordRef: string;\n cases: CaMedicalDirectionCase[];\n physicalPresenceAndImmediateAvailability: CaAnesthesiaParticipation[];\n otherPatientServices: Array<{\n kind: \"emergency\" | \"labor_analgesia\" | \"obstetric_monitoring\" | \"receiving_patient\" | \"recovery_care\" | \"other\";\n interval: CaAnesthesiaInterval;\n recordRef: string;\n }>;\n};\nexport type CaMonitoredAnesthesiaCare = {\n medicallyNecessary: true;\n intraoperativePhysiologicalMonitoring: true;\n preparedForGeneralAnesthesiaOrAdverseReaction: true;\n perioperativeAnesthesiaCare: true;\n underlyingProcedureProvider: \"different_provider\" | \"same_provider\";\n underlyingProcedure: \"nerve_block_or_injection\" | \"other\";\n};\n/** Clinical facts supplement AA or QK; monitored care also requires QS. */\nexport type CaAnesthesiaContext = {\n providerKind: \"physician\";\n actualMinutes: number;\n placeOfService: string;\n completeSameDayServices: true;\n otherSameDayServices: boolean;\n codingRequirementsSatisfied: true;\n monitoredCare?: CaMonitoredAnesthesiaCare;\n} & ({ personallyPerformedAlone: true; medicalDirection?: never } | { personallyPerformedAlone: false; medicalDirection: CaMedicalDirection });\n\nexport type CaPadbContext = {\n providerKind: \"physician\";\n placeOfService: \"11\";\n productKind: \"injectable\";\n bundledOrPackaged: false;\n codingRequirementsSatisfied: true;\n completeSameDayServices: true;\n sameDayServices: Array<{ code: string; units: number }>;\n};\n\nexport type CaTherapyContext = {\n providerKind?: \"physical_therapist\" | \"other\";\n personallyPerformed?: boolean;\n hospitalPatient?: boolean;\n incidentToPhysicianService?: boolean;\n assistantInvolved?: boolean;\n placeOfService?: string;\n /** Whether an initial evaluation already occurred in this care episode, including prior dates. Omit when unknown. */\n priorInitialEvaluationInEpisode?: boolean;\n /** Required for timed treatment; initial evaluations are untimed. */\n directOneOnOneMinutes?: number;\n totalVisitMinutes?: number;\n visitsOnDate?: number;\n completeSameDayServices?: boolean;\n otherSameDayServices?: boolean;\n globalPeriodApplies?: boolean;\n hpsaBonusEligible?: boolean;\n };\n\n/** Actual technical imaging facts. All fields are required when this context is supplied. */\nexport type CaTechnicalComponentContext = {\n /** Whether the billing provider or group furnished the service; purchased or outsourced services require review. */\n performedByBillingProviderGroup: boolean;\n patientHospitalStatus: \"not_hospital_patient\" | \"hospital_inpatient_or_outpatient\";\n supervisionLevel: \"general\" | \"direct\" | \"personal\";\n /** Actual session label, 1–64 letters/digits/._:-, beginning with a letter or digit. Never a patient identifier. */\n imagingSessionReference: string;\n /** All imaging for this patient/provider group/date is included, including separately billed services. */\n completeSameDayImagingServices: boolean;\n};\n\n/** Documented interpretation and imaging-session facts; an omitted completeness fact remains unknown. */\nexport type CaProfessionalComponentContext = {\n interpretationLocation: \"same_as_patient_service\" | \"different_from_patient_service\";\n supervisionLevel?: \"general\" | \"direct\" | \"personal\";\n /** Actual session label, 1–64 letters/digits/._:-, beginning with a letter or digit. Never a patient identifier. */\n imagingSessionReference?: string;\n /** All imaging for this patient/provider group/date is included, including separately billed services. */\n completeSameDayImagingServices?: boolean;\n};\n\nexport type BillFeeQuoteInput = {\n drug?: BilledDrug;\n padbContext?: CaPadbContext;\n anesthesiaContext?: CaAnesthesiaContext;\n billingProviderId?: string;\n payerId?: string;\n code: string;\n dateOfService: string;\n chargeCents?: number;\n units?: number;\n modifiers?: string[];\n pages?: number;\n reportKind?: \"progress\" | \"permanent_stationary_pr3\" | \"permanent_stationary_pr4\";\n hasFeeAgreement?: boolean;\n serviceZip?: string;\n /** Explicit physical interpretation location for a professional component. */\n professionalComponentContext?: CaProfessionalComponentContext;\n technicalComponentContext?: CaTechnicalComponentContext;\n /** California equipment pricing uses worker residence, independently of service location. */\n dmeposContext?: {\n residenceZip: string;\n /** Continuous rental month for this equipment item; only for applicable RR lines. */\n rentalMonth?: number;\n /** Actual prior payments for this item, including rentals; explicit zero means no prior payments. */\n priorPaymentsCents?: number;\n };\n /** Supply verified service facts; omitted context can require review. */\n physicianContext?: {\n providerKind: \"physician\" | \"physician_assistant\" | \"nurse_practitioner\" | \"clinical_nurse_specialist\" | \"other\";\n incidentToPhysicianService?: boolean;\n placeOfService: string;\n standaloneService: boolean;\n globalPeriodApplies: boolean;\n hpsaBonusEligible: boolean;\n };\n therapyContext?: CaTherapyContext;\n catalogContext?: {\n codingRequirementsSatisfied: boolean;\n statusIAlternative?: \"none\" | \"cpt\" | \"drug\";\n completeSurgicalPackage?: boolean;\n };\n prolongedServiceContext?: {\n totalMinutes: number;\n relatedEvaluationDate: string;\n ongoingPatientManagement: boolean;\n personallyPerformed: boolean;\n timeCountedInOtherServices: boolean;\n completeSameDayServices: boolean;\n sameDayServices: Array<{ code: string; units: number }>;\n };\n reportQualification?:\n | { kind: \"psychiatric_report\"; requestedBy: \"wcab\" | \"administrative_director\"; medicalLegalEvaluation: boolean; reportPayableUnderMedicalLegalSchedule: boolean }\n | { kind: \"consultation_report\"; requestedBy: \"wcab\" | \"administrative_director\" | \"qme\" | \"ame\"; medicalLegalEvaluation: boolean; reportPayableUnderMedicalLegalSchedule: boolean }\n | { kind: \"chart_notes\"; requestedBy: \"claims_administrator\"; writtenRequest: boolean }\n | { kind: \"duplicate_report\"; requestedBy: \"claims_administrator\"; writtenRequest: boolean; relatedToBilling: boolean; initialRequiredCopy: boolean };\n};\n\n/** Authoritative service, provider, payer and location fields come from the submitted bill. */\nexport type BillFeeContext = Omit<BillFeeQuoteInput, \"code\" | \"dateOfService\" | \"units\" | \"modifiers\" | \"chargeCents\" | \"billingProviderId\" | \"payerId\" | \"serviceZip\" | \"drug\">;\n\n/** Fee families returned by the California and practice-contract quote endpoint. */\nexport const BILL_FEE_QUOTE_BASES = [\n \"ca_report\", \"ca_physician_rbrvs\", \"ca_therapy_rbrvs\", \"ca_clfs\",\n \"ca_simple_dispensed_drug\", \"ca_dmepos\", \"ca_padb\", \"ca_anesthesia\", \"payer_contract\",\n] as const;\nexport type BillFeeQuoteBasis = typeof BILL_FEE_QUOTE_BASES[number];\n\nexport type BillFeeQuote =\n | {\n status: \"priced\";\n /** Total for the service line in cents, already accounting for units. */\n amountCents: number;\n scheduleMaximumCents: number;\n basis: BillFeeQuoteBasis;\n anesthesia?: { actualMinutes: number; baseUnits: number; timeUnitsTenths: number; conversionFactorCents: number; locality: string; medicalDirection?: { concurrentCases: number; baseReductionPercent: number; physicianPaymentPercent: 50 } };\n provenance: BillFeeSource[];\n notes: string[];\n }\n | { status: \"requires_review\" | \"not_separately_payable\"; reason: string; provenance: BillFeeSource[] };\n\n/** Public DWC directory record. Only Approved records are selectable. */\nexport type MedicalProviderNetwork = {\n id: string;\n name: string;\n applicantName: string;\n applicantType?: string;\n status: \"Approved\" | \"Terminated\" | \"Withdrawn\";\n approvalDate?: string | null;\n website?: string | null;\n};\n\nexport type BillReferenceClient = {\n listMedicalProviderNetworks: () => Promise<MedicalProviderNetwork[]>;\n listClaimsAdministrators: (input?: BillReviewPayerListInput) => Promise<BillReviewPayerPage>;\n searchClaimsAdministrators: (query: string, claimNumber?: string) => Promise<BillReviewPayer[]>;\n getClaimsAdministratorDirectory: (id: string, injuryState?: string) => Promise<BillClaimsAdministratorDirectory>;\n searchDiagnosisCodes: (query: string, limit?: number, offset?: number) => Promise<BillDiagnosisCode[]>;\n searchProcedureCodes: (input?: BillProcedureCodeSearchInput) => Promise<BillProcedureCodePage>;\n quoteFee: (input: BillFeeQuoteInput) => Promise<BillFeeQuote>;\n quoteClaimFees: (input: CaClaimFeeQuoteInput) => Promise<CaClaimFeeQuoteResult>;\n lookupPostalCode: (postalCode: string) => Promise<BillPostalPlace | null>;\n /**\n * Delivery-route preview (recommended route + selectable options + payer\n * contacts) for a claims administrator BEFORE the bill exists — powers the\n * send-route picker shown at submit time.\n */\n getDeliveryPreview: (input: BillDeliveryPreviewInput) => Promise<BillDeliveryOptions>;\n clearSession: () => void;\n};\n\nexport type BillLifecycleClient = {\n getBillId: () => string;\n getLifecycle: (signal?: AbortSignal) => Promise<BillLifecycleData>;\n listMedicalProviderNetworks: () => Promise<MedicalProviderNetwork[]>;\n listClaimsAdministrators: (input?: BillReviewPayerListInput) => Promise<BillReviewPayerPage>;\n searchClaimsAdministrators: (query: string, claimNumber?: string) => Promise<BillReviewPayer[]>;\n getClaimsAdministratorDirectory: (id: string, injuryState?: string) => Promise<BillClaimsAdministratorDirectory>;\n searchDiagnosisCodes: (query: string, limit?: number, offset?: number) => Promise<BillDiagnosisCode[]>;\n searchProcedureCodes: (input?: BillProcedureCodeSearchInput) => Promise<BillProcedureCodePage>;\n quoteFee: (input: BillFeeQuoteInput) => Promise<BillFeeQuote>;\n quoteClaimFees: (input: CaClaimFeeQuoteInput) => Promise<CaClaimFeeQuoteResult>;\n lookupPostalCode: (postalCode: string) => Promise<BillPostalPlace | null>;\n getDeliveryOptions: () => Promise<BillDeliveryOptions>;\n getDeliveryPreview: (input: BillDeliveryPreviewInput) => Promise<BillDeliveryOptions>;\n getAttachment: (attachmentId: string) => Promise<Blob>;\n getEor: (documentId: string) => Promise<Blob>;\n getPacket: () => Promise<Blob>;\n getSubmissionArtifact: (attemptId: string, artifactId: string) => Promise<Blob>;\n /** Prepare a self-filing packet. Does not file IBR or send anything to a payer. */\n prepareIbrPacket: () => Promise<Blob>;\n previewCourtesyCopy: (input: BillCourtesyCopyInput) => Promise<BillCourtesyCopyPreview>;\n /** Reuse the same key when retrying the same send after a network interruption. */\n sendCourtesyCopy: (input: BillCourtesyCopyInput & { packetHash: string }, idempotencyKey: string) => Promise<BillCourtesyCopyResult>;\n addNote: (input: AddBillNoteInput) => Promise<BillLifecycleData>;\n closeBill: (input: CloseBillInput) => Promise<BillLifecycleData>;\n reopenBill: (input: ReopenBillInput) => Promise<BillLifecycleData>;\n postPayment: (input: PostBillPaymentInput) => Promise<BillLifecycleData>;\n submitSecondReview: (input: SubmitSecondReviewInput) => Promise<BillLifecycleData>;\n resubmitBill: (input: ResubmitBillInput) => Promise<BillLifecycleData>;\n submitNewBill: (input: SubmitNewBillInput) => Promise<BillLifecycleData>;\n sendDuplicateBill: (input: SendDuplicateBillInput) => Promise<BillLifecycleData>;\n reportBillStatus: (input: ReportBillStatusInput) => Promise<BillLifecycleData>;\n simulateSandbox: (input: SimulateSandboxBillInput) => Promise<BillLifecycleData>;\n clearSession: () => void;\n};\n\nasync function responseError(response: Response, fallback: string): Promise<Error> {\n const body: unknown = await response.json().catch(() => null);\n const detail = body && typeof body === \"object\"\n ? (body as { detail?: unknown; message?: unknown; error?: unknown }).detail\n ?? (body as { message?: unknown }).message\n ?? (body as { error?: unknown }).error\n : null;\n return new Error(typeof detail === \"string\" ? detail : fallback);\n}\n\nfunction isSessionFresh(session: BillLifecycleSession | null): boolean {\n if (!session) return false;\n if (!session.expiresAt) return true;\n const expiresAt = new Date(session.expiresAt).getTime();\n return Number.isFinite(expiresAt) && expiresAt > Date.now() + 30_000;\n}\n\nfunction normalizeSession(value: unknown): BillLifecycleSession {\n if (!value || typeof value !== \"object\") {\n throw new Error(\"The billing session endpoint returned an invalid response.\");\n }\n const candidate = value as { token?: unknown; expiresAt?: unknown; apiBaseUrl?: unknown; session?: unknown; data?: unknown };\n const nested = candidate.session ?? candidate.data;\n const session = nested && typeof nested === \"object\" ? nested as typeof candidate : candidate;\n if (typeof session.token !== \"string\" || session.token.length < 8) {\n throw new Error(\"The billing session endpoint did not return a browser session token.\");\n }\n return {\n token: session.token,\n ...(typeof session.expiresAt === \"string\" ? { expiresAt: session.expiresAt } : {}),\n ...(typeof session.apiBaseUrl === \"string\" ? { apiBaseUrl: session.apiBaseUrl } : {}),\n };\n}\n\nfunction normalizeLifecycle(value: unknown): BillLifecycleData {\n if (!value || typeof value !== \"object\") {\n throw new Error(\"The billing service returned an invalid bill lifecycle.\");\n }\n const data = value as Partial<BillLifecycleData>;\n if (\n ![\"sandbox\", \"live\"].includes(data.environment ?? \"\")\n || !data.bill\n || !data.patient\n || !data.injury\n || !data.lifecycle\n || !Array.isArray(data.lifecycle.actions)\n || !Array.isArray(data.eors)\n || !Array.isArray(data.activity)\n || !Array.isArray(data.payments)\n || !data.remittance\n || typeof data.remittance !== \"object\"\n || !data.delivery\n || typeof data.delivery !== \"object\"\n || !data.delivery.contacts\n || typeof data.delivery.contacts !== \"object\"\n || (data.rejection != null && (\n typeof data.rejection !== \"object\"\n || typeof data.rejection.reason !== \"string\"\n || (data.rejection.issues != null && (\n !Array.isArray(data.rejection.issues)\n || data.rejection.issues.some((issue) => (\n !issue\n || typeof issue !== \"object\"\n || typeof issue.description !== \"string\"\n || (issue.code != null && typeof issue.code !== \"string\")\n ))\n ))\n ))\n ) {\n throw new Error(\"The billing service returned an invalid bill lifecycle.\");\n }\n return data as BillLifecycleData;\n}\n\nfunction normalizeDeliveryOptions(value: unknown): BillDeliveryOptions {\n if (!value || typeof value !== \"object\") {\n throw new Error(\"The billing service returned invalid delivery options.\");\n }\n const data = value as Partial<BillDeliveryOptions>;\n if (\n typeof data.payerName !== \"string\"\n || !data.recommended\n || typeof data.recommended !== \"object\"\n || ![\"ebill\", \"fax\", \"mail\", \"email\"].includes(data.recommended.route ?? \"\")\n || !Array.isArray(data.options)\n || !data.contacts\n ) {\n throw new Error(\"The billing service returned invalid delivery options.\");\n }\n return data as BillDeliveryOptions;\n}\n\nfunction idempotencyKey(): string {\n if (typeof globalThis.crypto?.randomUUID === \"function\") return globalThis.crypto.randomUUID();\n return `mb-${Date.now()}-${Math.random().toString(36).slice(2)}`;\n}\n\n/**\n * Browser-safe client for one atomic create-and-submit operation.\n *\n * The browser session is short-lived and origin-bound. The host application\n * never needs the Partner API document schema or a long-lived API key.\n */\nexport function createBillSubmissionClient({\n sessionEndpoint = DEFAULT_SESSION_ENDPOINT,\n getSession,\n apiBaseUrl = DEFAULT_API_BASE_URL,\n fetch: fetchOverride,\n}: BillSubmissionClientOptions = {}): BillSubmissionClient {\n const fetcher = fetchOverride ?? globalThis.fetch;\n if (typeof fetcher !== \"function\") throw new Error(\"A Fetch API implementation is required.\");\n let session: BillLifecycleSession | null = null;\n let sessionRequest: Promise<BillLifecycleSession> | null = null;\n\n const mintSession = async (signal: AbortSignal, force = false): Promise<BillLifecycleSession> => {\n if (!force && isSessionFresh(session)) return session as BillLifecycleSession;\n if (!force && sessionRequest) return sessionRequest;\n const pending = getSession\n ? getSession({ signal })\n : fetcher(sessionEndpoint, {\n method: \"POST\",\n credentials: \"same-origin\",\n headers: { \"content-type\": \"application/json\" },\n body: JSON.stringify({}),\n signal,\n }).then(async (response) => {\n if (!response.ok) throw await responseError(response, \"The billing session could not be created.\");\n return response.json();\n });\n const request = Promise.resolve(pending).then(normalizeSession).then((nextSession) => {\n session = nextSession;\n return nextSession;\n }).finally(() => {\n if (sessionRequest === request) sessionRequest = null;\n });\n sessionRequest = request;\n return request;\n };\n\n const submitBill = async (\n input: BrowserBillSubmissionInput,\n options: { idempotencyKey?: string } = {},\n ): Promise<BrowserBillSubmissionResult> => {\n const controller = new AbortController();\n const requestIdempotencyKey = options.idempotencyKey ?? idempotencyKey();\n let browserSession = await mintSession(controller.signal);\n const perform = (current: BillLifecycleSession) => {\n const base = (current.apiBaseUrl ?? apiBaseUrl).replace(/\\/$/, \"\");\n return fetcher(`${base}/partner/v2/bills`, {\n method: \"POST\",\n headers: {\n authorization: `Bearer ${current.token}`,\n \"content-type\": \"application/json\",\n \"idempotency-key\": requestIdempotencyKey,\n },\n body: JSON.stringify(input),\n signal: controller.signal,\n });\n };\n let response = await perform(browserSession);\n if (response.status === 401) {\n session = null;\n browserSession = await mintSession(controller.signal, true);\n response = await perform(browserSession);\n }\n if (!response.ok) throw await responseError(response, \"The bill could not be submitted.\");\n const body: unknown = await response.json().catch(() => null);\n const envelope = body && typeof body === \"object\" && \"data\" in body\n ? (body as { data?: unknown }).data\n : body;\n if (!envelope || typeof envelope !== \"object\" || typeof (envelope as { id?: unknown }).id !== \"string\") {\n throw new Error(\"The billing service submitted the bill but returned an invalid bill ID.\");\n }\n const bill = envelope as BrowserSubmittedBill;\n return { billId: bill.id, bill };\n };\n\n return {\n submitBill,\n clearSession() { session = null; sessionRequest = null; },\n };\n}\n\n/** Browser-safe, framework-neutral client for an already-submitted bill. */\nexport function createBillLifecycleClient({\n billId,\n sessionEndpoint = DEFAULT_SESSION_ENDPOINT,\n getSession,\n apiBaseUrl = DEFAULT_API_BASE_URL,\n fetch: fetchOverride,\n}: BillLifecycleClientOptions): BillLifecycleClient {\n const fetcher = fetchOverride ?? globalThis.fetch;\n if (typeof fetcher !== \"function\") throw new Error(\"A Fetch API implementation is required.\");\n let session: BillLifecycleSession | null = null;\n let sessionRequest: Promise<BillLifecycleSession> | null = null;\n const currentBillId = billId.trim();\n if (!currentBillId) throw new Error(\"billId is required for the submitted-bill lifecycle client.\");\n\n const mintSession = async (signal: AbortSignal, force = false): Promise<BillLifecycleSession> => {\n if (!force && isSessionFresh(session)) return session as BillLifecycleSession;\n if (!force && sessionRequest) return sessionRequest;\n const pending = getSession\n ? getSession({ signal })\n : fetcher(sessionEndpoint, {\n method: \"POST\",\n credentials: \"same-origin\",\n headers: { \"content-type\": \"application/json\" },\n body: JSON.stringify({}),\n signal,\n }).then(async (response) => {\n if (!response.ok) throw await responseError(response, \"The billing session could not be created.\");\n return response.json();\n });\n const request = Promise.resolve(pending).then(normalizeSession).then((nextSession) => {\n session = nextSession;\n return nextSession;\n }).finally(() => {\n if (sessionRequest === request) sessionRequest = null;\n });\n sessionRequest = request;\n return request;\n };\n\n const request = async (path: string, init: RequestInit = {}, providedSignal?: AbortSignal): Promise<Response> => {\n const controller = providedSignal ? null : new AbortController();\n const signal = providedSignal ?? controller?.signal;\n if (!signal) throw new Error(\"An AbortSignal could not be created.\");\n let browserSession = await mintSession(signal);\n const perform = (current: BillLifecycleSession) => {\n const base = (current.apiBaseUrl ?? apiBaseUrl).replace(/\\/$/, \"\");\n const headers = new Headers(init.headers);\n headers.set(\"authorization\", `Bearer ${current.token}`);\n return fetcher(`${base}${path}`, { ...init, headers, signal });\n };\n let response = await perform(browserSession);\n if (response.status === 401) {\n session = null;\n browserSession = await mintSession(signal, true);\n response = await perform(browserSession);\n }\n return response;\n };\n\n const billPath = (suffix = \"\"): string =>\n `/partner/v2/bills/${encodeURIComponent(currentBillId)}${suffix}`;\n\n const loadLifecycle = async (signal?: AbortSignal) => {\n const response = await request(billPath(\"/lifecycle\"), {}, signal);\n if (!response.ok) throw await responseError(response, \"Bill lifecycle could not be loaded.\");\n const body = await response.json() as { data?: unknown };\n return normalizeLifecycle(body.data);\n };\n\n const listMedicalProviderNetworks = async (): Promise<MedicalProviderNetwork[]> => {\n const response = await request(\"/partner/v2/medical-provider-networks\");\n if (!response.ok) throw await responseError(response, \"Medical provider networks could not be loaded.\");\n const body = await response.json() as { data?: unknown };\n if (!Array.isArray(body.data)) throw new Error(\"Medical provider networks returned an invalid response.\");\n return body.data.flatMap((value): MedicalProviderNetwork[] => {\n if (!value || typeof value !== \"object\") return [];\n const row = value as Record<string, unknown>;\n if (row.status !== \"Approved\" || typeof row.id !== \"string\" || typeof row.name !== \"string\" || typeof row.applicantName !== \"string\") return [];\n return [{ id: row.id, name: row.name, applicantName: row.applicantName, status: \"Approved\",\n ...(typeof row.applicantType === \"string\" ? { applicantType: row.applicantType } : {}),\n ...(typeof row.approvalDate === \"string\" ? { approvalDate: row.approvalDate } : {}),\n ...(typeof row.website === \"string\" ? { website: row.website } : {}),\n }];\n });\n };\n\n const listClaimsAdministrators = async (input: BillReviewPayerListInput = {}): Promise<BillReviewPayerPage> => {\n const params = new URLSearchParams();\n if (input.query?.trim()) params.set(\"q\", input.query.trim());\n if (input.claimNumber?.trim()) params.set(\"claimNumber\", input.claimNumber.trim());\n if (input.sourceClaimsAdministratorName?.trim()) params.set(\"sourceClaimsAdministratorName\", input.sourceClaimsAdministratorName.trim());\n if (input.employerName?.trim()) params.set(\"employerName\", input.employerName.trim());\n const limit = Math.max(1, Math.min(100, Math.floor(input.limit ?? 50)));\n const offset = Math.max(0, Math.floor(input.offset ?? 0));\n params.set(\"limit\", String(limit));\n if (offset) params.set(\"offset\", String(offset));\n const response = await request(`/partner/v2/claims-administrators?${params.toString()}`);\n if (!response.ok) throw await responseError(response, \"Claims administrator search is unavailable.\");\n const body = await response.json() as { results?: unknown; suggestions?: unknown; total?: unknown; nextOffset?: unknown; recommendedId?: unknown };\n if (!Array.isArray(body.results)) throw new Error(\"Claims administrator search returned an invalid response.\");\n const normalizePayer = (value: unknown): BillReviewPayer | null => {\n if (!value || typeof value !== \"object\") return null;\n const payer = value as Record<string, unknown>;\n if (typeof payer.id !== \"string\" || typeof payer.name !== \"string\") return null;\n const payers = Array.isArray(payer.payers) ? payer.payers.flatMap((option): BillReviewPayerOption[] => {\n if (!option || typeof option !== \"object\") return [];\n const candidate = option as Record<string, unknown>;\n const id = typeof candidate.id === \"string\" ? candidate.id : typeof candidate.key === \"string\" ? candidate.key : null;\n if (!id || typeof candidate.label !== \"string\") return [];\n return [{\n id,\n label: candidate.label,\n ...(typeof candidate.default === \"boolean\" ? { default: candidate.default } : {}),\n ...(typeof candidate.active === \"boolean\" ? { active: candidate.active } : {}),\n ...(Array.isArray(candidate.aliases) ? { aliases: candidate.aliases.filter((item): item is string => typeof item === \"string\") } : {}),\n ...(typeof candidate.hint === \"string\" ? { hint: candidate.hint } : {}),\n ...(Array.isArray(candidate.affiliatedEntities) ? { affiliatedEntities: candidate.affiliatedEntities.filter((item): item is string => typeof item === \"string\") } : {}),\n ...(typeof candidate.route === \"string\" ? { route: candidate.route } : {}),\n ...(typeof candidate.optionType === \"string\" ? { optionType: candidate.optionType } : {}),\n ...(typeof candidate.deliveryType === \"string\" ? { deliveryType: candidate.deliveryType } : {}),\n ...(typeof candidate.clearinghouse === \"string\" ? { clearinghouse: candidate.clearinghouse } : {}),\n ...(typeof candidate.payerId === \"string\" ? { payerId: candidate.payerId } : {}),\n ...(typeof candidate.sourceClearinghouse === \"string\" ? { sourceClearinghouse: candidate.sourceClearinghouse } : {}),\n ...(typeof candidate.sourcePayerId === \"string\" ? { sourcePayerId: candidate.sourcePayerId } : {}),\n ...(candidate.clearinghousePayerIds && typeof candidate.clearinghousePayerIds === \"object\" && !Array.isArray(candidate.clearinghousePayerIds)\n ? { clearinghousePayerIds: Object.fromEntries(Object.entries(candidate.clearinghousePayerIds).filter((entry): entry is [string, string] => typeof entry[1] === \"string\")) }\n : {}),\n ...(typeof candidate.preferredClearinghouse === \"string\" ? { preferredClearinghouse: candidate.preferredClearinghouse } : {}),\n }];\n }) : undefined;\n const claimNumberPatterns = Array.isArray(payer.claimNumberPatterns) ? payer.claimNumberPatterns.flatMap((value): BillClaimsAdministratorPattern[] => {\n if (!value || typeof value !== \"object\") return [];\n const pattern = value as Record<string, unknown>;\n if (typeof pattern.pattern !== \"string\") return [];\n return [{\n pattern: pattern.pattern,\n ...(typeof pattern.length === \"string\" || typeof pattern.length === \"number\" ? { length: pattern.length } : {}),\n ...(typeof pattern.example === \"string\" ? { example: pattern.example } : {}),\n ...(typeof pattern.matches === \"boolean\" || pattern.matches === null ? { matches: pattern.matches as boolean | null } : {}),\n }];\n }) : undefined;\n return {\n id: payer.id,\n name: payer.name,\n ...(typeof payer.hasElectronic === \"boolean\" ? { hasElectronic: payer.hasElectronic } : {}),\n ...(Array.isArray(payer.states) ? { states: payer.states.filter((state): state is string => typeof state === \"string\") } : {}),\n ...([\"high\", \"medium\", \"directory\"].includes(String(payer.confidence)) ? { confidence: payer.confidence as NonNullable<BillReviewPayer[\"confidence\"]> } : {}),\n ...(typeof payer.recommended === \"boolean\" ? { recommended: payer.recommended } : {}),\n ...(typeof payer.payerSelectionRequired === \"boolean\" ? { payerSelectionRequired: payer.payerSelectionRequired } : {}),\n ...(payers ? { payers } : {}),\n ...(Array.isArray(payer.aliases) ? { aliases: payer.aliases.filter((item): item is string => typeof item === \"string\") } : {}),\n ...(Array.isArray(payer.affiliatedEntities) ? { affiliatedEntities: payer.affiliatedEntities.filter((item): item is string => typeof item === \"string\") } : {}),\n ...(typeof payer.claimNumberHint === \"string\" ? { claimNumberHint: payer.claimNumberHint } : {}),\n ...(claimNumberPatterns ? { claimNumberPatterns } : {}),\n ...(typeof payer.route === \"string\" ? { route: payer.route } : {}),\n ...(Array.isArray(payer.signals) ? { signals: payer.signals.flatMap((signal) => {\n if (!signal || typeof signal !== \"object\") return [];\n const candidate = signal as Record<string, unknown>;\n if (![\"name\", \"claim_number\"].includes(String(candidate.kind)) || ![\"match\", \"warning\"].includes(String(candidate.state)) || typeof candidate.label !== \"string\") return [];\n return [{ kind: candidate.kind as \"name\" | \"claim_number\", state: candidate.state as \"match\" | \"warning\", label: candidate.label }];\n }) } : {}),\n };\n };\n const results = body.results.flatMap((value): BillReviewPayer[] => {\n const payer = normalizePayer(value);\n return payer ? [payer] : [];\n });\n const suggestions = Array.isArray(body.suggestions) ? body.suggestions.flatMap((value): BillReviewPayerSuggestion[] => {\n const payer = normalizePayer(value);\n if (!payer || !value || typeof value !== \"object\") return [];\n const suggestion = value as Record<string, unknown>;\n if (typeof suggestion.deterministic !== \"boolean\" || typeof suggestion.reason !== \"string\") return [];\n return [{ ...payer, deterministic: suggestion.deterministic, reason: suggestion.reason, ...(typeof suggestion.selectedPayerId === \"string\" ? { selectedPayerId: suggestion.selectedPayerId } : {}) }];\n }) : [];\n const total = typeof body.total === \"number\" && Number.isFinite(body.total) ? Math.max(results.length, Math.floor(body.total)) : offset + results.length;\n return {\n results,\n ...(suggestions.length ? { suggestions } : {}),\n total,\n ...(typeof body.nextOffset === \"number\" && Number.isFinite(body.nextOffset) ? { nextOffset: Math.floor(body.nextOffset) } : {}),\n ...(typeof body.recommendedId === \"string\" ? { recommendedId: body.recommendedId } : {}),\n };\n };\n\n const searchClaimsAdministrators = async (query: string, claimNumber?: string): Promise<BillReviewPayer[]> =>\n (await listClaimsAdministrators({ query, ...(claimNumber ? { claimNumber } : {}) })).results;\n\n const getClaimsAdministratorDirectory = async (id: string, injuryState?: string): Promise<BillClaimsAdministratorDirectory> => {\n const params = new URLSearchParams();\n if (injuryState?.trim()) params.set(\"injuryState\", injuryState.trim());\n const response = await request(`/partner/v2/claims-administrators/${encodeURIComponent(id)}${params.size ? `?${params}` : \"\"}`);\n if (!response.ok) throw await responseError(response, \"Claims administrator details are unavailable.\");\n const body = await response.json() as { data?: unknown };\n if (!body.data || typeof body.data !== \"object\") throw new Error(\"Claims administrator details returned an invalid response.\");\n return body.data as BillClaimsAdministratorDirectory;\n };\n\n const searchDiagnosisCodes = async (query: string, limit = 30, offset = 0): Promise<BillDiagnosisCode[]> => {\n const params = new URLSearchParams({ q: query.trim(), limit: String(Math.max(1, Math.min(100, limit))) });\n if (offset > 0) params.set(\"offset\", String(Math.max(0, Math.floor(offset))));\n const response = await request(`/partner/v2/diagnosis-codes?${params.toString()}`);\n if (!response.ok) throw await responseError(response, \"Diagnosis-code search is unavailable.\");\n const body = await response.json() as { results?: unknown };\n if (!Array.isArray(body.results)) throw new Error(\"Diagnosis-code search returned an invalid response.\");\n return body.results.flatMap((value): BillDiagnosisCode[] => {\n if (!value || typeof value !== \"object\") return [];\n const candidate = value as { code?: unknown; description?: unknown };\n return typeof candidate.code === \"string\" && typeof candidate.description === \"string\"\n ? [{ code: candidate.code, description: candidate.description }]\n : [];\n });\n };\n\n const searchProcedureCodes = async (input: BillProcedureCodeSearchInput = {}): Promise<BillProcedureCodePage> => {\n const limit = Number.isFinite(input.limit) ? Math.max(1, Math.min(100, Math.floor(input.limit!))) : 30;\n const params = new URLSearchParams({ q: input.query?.trim() ?? \"\", limit: String(limit), jurisdiction: input.jurisdiction?.trim().toUpperCase() || \"CA\" });\n const response = await request(`/partner/v2/procedure-codes?${params}`);\n if (!response.ok) throw await responseError(response, \"Procedure-code search is unavailable.\");\n const body = await response.json() as Partial<BillProcedureCodePage>;\n if (!Array.isArray(body.results) || typeof body.total !== \"number\" || !Number.isFinite(body.total) || body.total < 0 || typeof body.limit !== \"number\" || !Number.isFinite(body.limit) || body.limit < 1 || ![\"CA\", \"NY\", \"OWCP\"].includes(body.jurisdiction ?? \"\") || !(body.catalogAsOf === null || typeof body.catalogAsOf === \"string\")) {\n throw new Error(\"Procedure-code search returned an invalid response.\");\n }\n return {\n results: body.results.flatMap((entry) => entry && typeof entry.code === \"string\" && entry.code.trim() ? [{ code: entry.code }] : []),\n total: body.total,\n limit: body.limit,\n jurisdiction: body.jurisdiction!,\n catalogAsOf: body.catalogAsOf,\n };\n };\n\n const quoteClaimFees = async (input: CaClaimFeeQuoteInput): Promise<CaClaimFeeQuoteResult> => {\n const response = await request(\"/partner/v2/fee-quotes/ca/claim\", {\n method: \"POST\", headers: { \"content-type\": \"application/json\" }, body: JSON.stringify(input),\n });\n if (!response.ok) throw await responseError(response, \"Claim fee pricing is unavailable.\");\n const body = await response.json() as { data?: unknown };\n return parseCaClaimFeeQuote(body.data, input);\n };\n\n const quoteFee = async (input: BillFeeQuoteInput): Promise<BillFeeQuote> => {\n const response = await request(\"/partner/v2/fee-quotes\", {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\" },\n body: JSON.stringify(input),\n });\n if (!response.ok) throw await responseError(response, \"Fee-schedule pricing is unavailable.\");\n const body = await response.json() as { data?: BillFeeQuote };\n const quote = body.data;\n if (!quote || !Array.isArray(quote.provenance)) throw new Error(\"Fee quote returned an invalid response.\");\n if (quote.status === \"priced\") {\n if (!Number.isSafeInteger(quote.amountCents) || quote.amountCents < 0 || !Number.isSafeInteger(quote.scheduleMaximumCents) || quote.scheduleMaximumCents < 0 || !BILL_FEE_QUOTE_BASES.includes(quote.basis) || !Array.isArray(quote.notes) || quote.notes.some((note) => typeof note !== \"string\")) throw new Error(\"Fee quote returned an invalid response.\");\n } else if ((quote.status !== \"requires_review\" && quote.status !== \"not_separately_payable\") || typeof quote.reason !== \"string\") {\n throw new Error(\"Fee quote returned an invalid response.\");\n }\n return quote;\n };\n\n const lookupPostalCode = async (postalCode: string): Promise<BillPostalPlace | null> => {\n const params = new URLSearchParams({ postalCode: postalCode.trim() });\n const response = await request(`/partner/v2/postal-codes?${params.toString()}`);\n if (response.status === 404) return null;\n if (!response.ok) throw await responseError(response, \"ZIP lookup is unavailable.\");\n const body = await response.json() as { city?: unknown; state?: unknown };\n if (typeof body.city !== \"string\" || typeof body.state !== \"string\") {\n throw new Error(\"ZIP lookup returned an invalid response.\");\n }\n return { city: body.city, state: body.state };\n };\n\n const mutation = async (path: string, init: RequestInit, fallback: string) => {\n const headers = new Headers(init.headers);\n headers.set(\"idempotency-key\", idempotencyKey());\n const response = await request(path, { ...init, headers });\n if (!response.ok) throw await responseError(response, fallback);\n return response;\n };\n const action = async (input: Record<string, unknown>, fallback: string): Promise<BillLifecycleData> => {\n const response = await mutation(billPath(\"/actions\"), {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\" },\n body: JSON.stringify(input),\n }, fallback);\n const body = await response.json() as { data?: unknown };\n return normalizeLifecycle(body.data);\n };\n const simulateSandbox = async (input: SimulateSandboxBillInput): Promise<BillLifecycleData> => {\n await mutation(`/partner/v2/sandbox/bills/${encodeURIComponent(currentBillId)}/simulate`, {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\" },\n body: JSON.stringify(input),\n }, \"Sandbox lifecycle could not be simulated.\");\n return loadLifecycle();\n };\n return {\n getBillId() { return currentBillId; },\n clearSession() { session = null; sessionRequest = null; },\n getLifecycle: loadLifecycle,\n listMedicalProviderNetworks,\n listClaimsAdministrators,\n searchClaimsAdministrators,\n getClaimsAdministratorDirectory,\n searchDiagnosisCodes,\n searchProcedureCodes,\n quoteFee,\n quoteClaimFees,\n lookupPostalCode,\n async getDeliveryOptions() {\n const response = await request(billPath(\"/delivery-options\"));\n if (!response.ok) throw await responseError(response, \"Delivery options could not be loaded.\");\n const body = await response.json() as { data?: unknown };\n return normalizeDeliveryOptions(body.data ?? body);\n },\n async getDeliveryPreview(input) {\n const params = new URLSearchParams({ claimsAdministratorId: input.claimsAdministratorId.trim() });\n if (input.payerId?.trim()) params.set(\"payerId\", input.payerId.trim());\n if (input.injuryState?.trim()) params.set(\"injuryState\", input.injuryState.trim());\n const response = await request(`/partner/v2/delivery-preview?${params.toString()}`);\n if (!response.ok) throw await responseError(response, \"Delivery routes could not be loaded.\");\n const body = await response.json() as { data?: unknown };\n return normalizeDeliveryOptions(body.data ?? body);\n },\n async getAttachment(attachmentId) {\n const response = await request(billPath(`/documents/${encodeURIComponent(attachmentId)}`));\n if (!response.ok) throw await responseError(response, \"Document could not be opened.\");\n return response.blob();\n },\n async getEor(documentId) {\n const response = await request(billPath(`/eors/${encodeURIComponent(documentId)}`));\n if (!response.ok) throw await responseError(response, \"EOR could not be opened.\");\n return response.blob();\n },\n async getPacket() {\n const response = await request(billPath(\"/packet\"));\n if (!response.ok) throw await responseError(response, \"Submission packet could not be downloaded.\");\n return response.blob();\n },\n async getSubmissionArtifact(attemptId, artifactId) {\n const response = await request(billPath(`/submissions/${encodeURIComponent(attemptId)}/artifacts/${encodeURIComponent(artifactId)}`));\n if (!response.ok) throw await responseError(response, \"The retained submission file could not be downloaded.\");\n return response.blob();\n },\n async prepareIbrPacket() {\n const prepared = await mutation(billPath(\"/actions\"), {\n method: \"POST\", headers: { \"content-type\": \"application/json\" },\n body: JSON.stringify({ action: \"independent_bill_review\" }),\n }, \"IBR packet could not be prepared.\");\n const body = await prepared.json() as { packetUrl?: unknown };\n // Never forward the browser bearer token to an arbitrary response URL.\n if (typeof body.packetUrl !== \"string\" || !/^\\/partner\\/v2\\/(?:browser\\/)?bills\\/[A-Za-z0-9_-]+\\/ibr-packet$/.test(body.packetUrl)) throw new Error(\"The billing service returned an invalid IBR packet path.\");\n // The server may resolve a root bill to its current linked bill.\n const response = await request(body.packetUrl);\n if (!response.ok) throw await responseError(response, \"IBR packet could not be downloaded.\");\n return response.blob();\n },\n async previewCourtesyCopy(input) {\n const response = await request(billPath(\"/courtesy-forward\"), {\n method: \"POST\", headers: { \"content-type\": \"application/json\" }, body: JSON.stringify({ ...input, mode: \"preview\" }),\n });\n if (!response.ok) throw await responseError(response, \"Courtesy copy could not be previewed.\");\n return response.json() as Promise<BillCourtesyCopyPreview>;\n },\n async sendCourtesyCopy(input, key) {\n if (!key.trim() || key.length > 255) throw new Error(\"A stable idempotency key is required to send a courtesy copy.\");\n const response = await request(billPath(\"/courtesy-forward\"), {\n method: \"POST\", headers: { \"content-type\": \"application/json\", \"idempotency-key\": key },\n body: JSON.stringify({ ...input, mode: \"send\" }),\n });\n if (!response.ok) throw await responseError(response, \"Courtesy copy could not be sent. Retry with the same key to check the result safely.\");\n return response.json() as Promise<BillCourtesyCopyResult>;\n },\n addNote(input) { return action({ action: \"add_note\", ...input }, \"Note could not be added.\"); },\n closeBill(input) { return action({ action: \"close\", ...input }, \"Bill could not be closed.\"); },\n reopenBill(input) { return action({ action: \"reopen\", ...input }, \"Bill could not be reopened.\"); },\n postPayment(input) { return action({ action: \"post_payment\", penaltyAmount: 0, interestAmount: 0, ...input, checkNumber: input.checkNumber ?? \"\" }, \"Payment could not be posted.\"); },\n submitSecondReview(input) { return action({ action: \"second_review\", ...input }, \"Second Review could not be submitted.\"); },\n resubmitBill(input) { return action({ action: \"resubmit\", ...input }, \"Bill could not be resubmitted.\"); },\n submitNewBill(input) { return action({ action: \"submit_new_bill\", ...input }, \"The new bill could not be submitted.\"); },\n sendDuplicateBill(input) { return action({ action: \"send_duplicate\", ...input }, \"Duplicate bill could not be sent.\"); },\n reportBillStatus(input) { return action({ action: \"report_bill_status\", ...input }, \"Bill status could not be reported.\"); },\n simulateSandbox,\n };\n}\n\n/**\n * Browser-safe client for reference data needed before a bill exists.\n *\n * Partners can pass the same short-lived session provider used by the submitted-bill\n * lifecycle without inventing a draft bill or exposing payer directory credentials.\n */\nexport function createBillReferenceClient(\n options: BillReferenceClientOptions = {},\n): BillReferenceClient {\n const lifecycle = createBillLifecycleClient({\n ...options,\n billId: \"pre-submission-reference-data\",\n });\n return {\n listMedicalProviderNetworks: lifecycle.listMedicalProviderNetworks,\n listClaimsAdministrators: lifecycle.listClaimsAdministrators,\n searchClaimsAdministrators: lifecycle.searchClaimsAdministrators,\n getClaimsAdministratorDirectory: lifecycle.getClaimsAdministratorDirectory,\n searchDiagnosisCodes: lifecycle.searchDiagnosisCodes,\n searchProcedureCodes: lifecycle.searchProcedureCodes,\n quoteFee: lifecycle.quoteFee,\n quoteClaimFees: lifecycle.quoteClaimFees,\n lookupPostalCode: lifecycle.lookupPostalCode,\n getDeliveryPreview: lifecycle.getDeliveryPreview,\n clearSession: lifecycle.clearSession,\n };\n}\n\n// ---------------------------------------------------------------------------\n// Organization profile client (INC-1470): backs the embeddable\n// OrganizationOnboarding / BillingSettings components. Requires a browser\n// session minted with organization:manage for administrative operations.\n// Read-only saved billing profiles need only an org-wide bills:create session.\n\n/** Convert masked profile state to a write without clearing an unchanged saved SSN. */\nexport function organizationTaxIdWrite<T extends { taxId?: string; taxIdType?: \"EIN\" | \"SSN\"; taxIdLast4?: string; taxIdConfigured?: boolean }>(value: T): Omit<T, \"taxIdLast4\" | \"taxIdConfigured\"> {\n const input = { ...value };\n delete input.taxIdLast4;\n delete input.taxIdConfigured;\n if (value.taxIdType === \"SSN\" && value.taxIdConfigured && !value.taxId?.trim()) delete input.taxId;\n return input;\n}\n\nexport type OrganizationPracticeIdentity = {\n name?: string; legalName?: string; taxId?: string; npi?: string;\n taxIdType?: \"EIN\" | \"SSN\";\n /** Read-only metadata. Saved SSNs are never returned in taxId. */\n taxIdLast4?: string; taxIdConfigured?: boolean;\n phone?: string; email?: string; website?: string;\n};\n\nexport type OrganizationBillingProviderInput = {\n id?: string; externalId?: string; name: string; taxId?: string; npi: string;\n taxIdType?: \"EIN\" | \"SSN\";\n /** Read-only metadata; omit taxId on updates to preserve a saved SSN. */\n taxIdLast4?: string; taxIdConfigured?: boolean;\n billType?: \"Professional\" | \"Institutional\"; phone?: string;\n billingStreet?: string; billingCity?: string; billingState?: string; billingZip?: string;\n};\n\nexport type OrganizationLocationInput = {\n id?: string; externalId?: string; name: string; street: string; city: string;\n state: string; zip: string; nickname?: string; posCode?: string;\n isPrimary?: boolean; active?: boolean;\n};\n\nexport type OrganizationRenderingProviderInput = {\n id?: string; externalId?: string; name: string; npi: string; specialty?: string;\n taxonomy?: string; licenseNumber?: string; licenseState?: string;\n isQME?: boolean; isAME?: boolean; email?: string; active?: boolean;\n};\n\nexport type OrganizationChecklistItem = { id: string; label: string; complete: boolean };\n\nexport type OrganizationProfileData = {\n organizationId: string;\n practiceIdentity: OrganizationPracticeIdentity;\n billingProviders: Array<OrganizationBillingProviderInput & { id: string }>;\n /** Optional for compatibility with older organization-profile responses. */\n renderingProviders?: Array<OrganizationRenderingProviderInput & { id: string }>;\n locations: Array<OrganizationLocationInput & { id: string }>;\n w9: { filename: string; addDate: string; taxYear?: number } | null;\n onboarding: { status: string | null; complete: boolean; checklist: OrganizationChecklistItem[] };\n};\n\nexport type OrganizationClientOptions = {\n sessionEndpoint?: string;\n getSession?: BillLifecycleSessionProvider;\n apiBaseUrl?: string;\n fetch?: typeof globalThis.fetch;\n};\n\nexport type OrganizationTeamRole = \"admin\" | \"manager\" | \"biller\" | \"payments\" | \"viewer\";\nexport type OrganizationTeamMember = {\n id: string; email: string; name: string; role: string; active: boolean;\n createdAt: string; canManage: boolean;\n};\nexport type OrganizationTeam = {\n members: OrganizationTeamMember[];\n roles: Array<{ id: OrganizationTeamRole; label: string; permissions: string[] }>;\n capabilities: { canManage: boolean; canAdd: boolean };\n identityDomain: \"mindbill\";\n};\nexport type OrganizationClaimsAdministratorInput = {\n name: string; fax?: string; email?: string; mailingAddress?: string; notes?: string;\n};\nexport type OrganizationClaimsAdministrator = {\n id: string; name: string; fax: string | null; email: string | null;\n mailingAddress: string | null; notes: string | null; submissionMethod: string;\n active: boolean; createdAt: string;\n};\n\nexport type OrganizationClient = {\n /** Requires explicit team:manage; organization:manage alone does not grant team access. */\n getTeam: () => Promise<OrganizationTeam>;\n updateTeamMember: (id: string, input: { role?: OrganizationTeamRole; active?: boolean }) => Promise<OrganizationTeamMember>;\n getClaimsAdministrators: () => Promise<OrganizationClaimsAdministrator[]>;\n createClaimsAdministrator: (input: OrganizationClaimsAdministratorInput) => Promise<OrganizationClaimsAdministrator>;\n updateClaimsAdministrator: (id: string, input: OrganizationClaimsAdministratorInput) => Promise<OrganizationClaimsAdministrator>;\n deleteClaimsAdministrator: (id: string) => Promise<{ id: string; deleted: true }>;\n\n getOrganization: () => Promise<OrganizationProfileData>;\n /** Masked saved profiles for bill entry; requires org-wide bills:create. */\n getBillingProfile: () => Promise<OrganizationProfileData>;\n saveBillingProfile: (input: {\n practiceIdentity?: OrganizationPracticeIdentity;\n billingProviders?: OrganizationBillingProviderInput[];\n renderingProviders?: OrganizationRenderingProviderInput[];\n }) => Promise<OrganizationProfileData>;\n saveLocations: (locations: OrganizationLocationInput[]) => Promise<OrganizationProfileData>;\n saveW9: (input: { filename: string; contentBase64: string; taxYear?: number }) => Promise<OrganizationProfileData>;\n};\n\nexport function createOrganizationClient({\n sessionEndpoint = DEFAULT_SESSION_ENDPOINT,\n getSession,\n apiBaseUrl = DEFAULT_API_BASE_URL,\n fetch: fetchOverride,\n}: OrganizationClientOptions = {}): OrganizationClient {\n const fetcher = fetchOverride ?? globalThis.fetch;\n if (typeof fetcher !== \"function\") throw new Error(\"A Fetch API implementation is required.\");\n let session: BillLifecycleSession | null = null;\n\n const mintSession = async (force = false): Promise<BillLifecycleSession> => {\n if (!force && isSessionFresh(session)) return session as BillLifecycleSession;\n const pending = getSession\n ? getSession({ signal: new AbortController().signal })\n : fetcher(sessionEndpoint, {\n method: \"POST\",\n credentials: \"same-origin\",\n headers: { \"content-type\": \"application/json\" },\n body: JSON.stringify({}),\n }).then(async (response) => {\n if (!response.ok) throw await responseError(response, \"The organization session could not be created.\");\n return response.json();\n });\n session = normalizeSession(await Promise.resolve(pending));\n return session;\n };\n\n const request = async <T = OrganizationProfileData>(path: string, init: RequestInit = {}): Promise<T> => {\n let current = await mintSession();\n const perform = (active: BillLifecycleSession) => {\n const base = (active.apiBaseUrl ?? apiBaseUrl).replace(/\\/$/, \"\");\n const headers = new Headers(init.headers);\n headers.set(\"authorization\", `Bearer ${active.token}`);\n if (init.body) headers.set(\"content-type\", \"application/json\");\n return fetcher(`${base}${path}`, { ...init, headers });\n };\n let response = await perform(current);\n if (response.status === 401) {\n current = await mintSession(true);\n response = await perform(current);\n }\n if (!response.ok) throw await responseError(response, \"The organization request failed.\");\n const body = (await response.json()) as { data?: T };\n if (!body.data || typeof body.data !== \"object\") {\n throw new Error(\"The organization response was invalid.\");\n }\n return body.data;\n };\n\n return {\n getTeam: () => request<OrganizationTeam>(\"/partner/v2/organization/team\"),\n updateTeamMember: (id, input) => request<OrganizationTeamMember>(`/partner/v2/organization/team/${encodeURIComponent(id)}`, { method: \"PATCH\", body: JSON.stringify(input) }),\n getClaimsAdministrators: () => request<OrganizationClaimsAdministrator[]>(\"/partner/v2/organization/claims-administrators\"),\n createClaimsAdministrator: (input) => request<OrganizationClaimsAdministrator>(\"/partner/v2/organization/claims-administrators\", { method: \"POST\", body: JSON.stringify(input) }),\n updateClaimsAdministrator: (id, input) => request<OrganizationClaimsAdministrator>(`/partner/v2/organization/claims-administrators/${encodeURIComponent(id)}`, { method: \"PATCH\", body: JSON.stringify(input) }),\n deleteClaimsAdministrator: (id) => request<{ id: string; deleted: true }>(`/partner/v2/organization/claims-administrators/${encodeURIComponent(id)}`, { method: \"DELETE\" }),\n getOrganization: () => request(\"/partner/v2/organization\"),\n getBillingProfile: () => request(\"/partner/v2/organization/billing-profile\"),\n saveBillingProfile: (input) =>\n request(\"/partner/v2/organization/billing-profile\", { method: \"PUT\", body: JSON.stringify({\n ...input,\n ...(input.practiceIdentity ? { practiceIdentity: organizationTaxIdWrite(input.practiceIdentity) } : {}),\n ...(input.billingProviders ? { billingProviders: input.billingProviders.map(organizationTaxIdWrite) } : {}),\n }) }),\n saveLocations: (locations) =>\n request(\"/partner/v2/organization/locations\", { method: \"PUT\", body: JSON.stringify({ locations }) }),\n saveW9: (input) =>\n request(\"/partner/v2/organization/w9\", { method: \"PUT\", body: JSON.stringify(input) }),\n };\n}\n\n// ---------------------------------------------------------------------------\n// Bill Tasks dashboard: a pure, framework-neutral\n// aggregation shared by the React and Angular components. Hosts flatten their\n// own work items and get back per-section rows bucketed by age in days.\n\nexport type BillTasksAgingBucket = {\n id: string;\n label: string;\n /** Exclusive lower bound in days. The first bucket also admits day 0. */\n minDays: number;\n /** Inclusive upper bound in days; null means unbounded. */\n maxDays: number | null;\n};\n\nexport const BILL_TASKS_AGING_BUCKETS: BillTasksAgingBucket[] = [\n { id: \"1-30\", label: \"1-30 Days Ago\", minDays: 0, maxDays: 30 },\n { id: \"31-60\", label: \"31-60 Days Ago\", minDays: 30, maxDays: 60 },\n { id: \"61-90\", label: \"61-90 Days Ago\", minDays: 60, maxDays: 90 },\n { id: \"91-180\", label: \"91-180 Days Ago\", minDays: 90, maxDays: 180 },\n { id: \"181+\", label: \"181+ Days Ago\", minDays: 180, maxDays: null },\n];\n\nexport type BillTasksDashboardItem = {\n sectionId: string;\n rowId: string;\n rowLabel: string;\n ageDays: number;\n balanceDue?: number;\n /** Opaque bill reference echoed back in click-through payloads. */\n ref?: string;\n};\n\nexport type BillTasksDashboardRow = {\n id: string;\n label: string;\n /** One count per aging bucket, in bucket order. */\n counts: number[];\n total: number;\n /** Summed item balanceDue per bucket; optional for older count-only payloads. */\n balances?: number[];\n balanceTotal?: number;\n /** Collected item refs per aging bucket, in bucket order. */\n refs: string[][];\n};\n\nexport type BillTasksDashboardTone = \"violet\" | \"red\" | \"blue\" | \"green\" | \"amber\" | \"neutral\";\n\nexport type BillTasksDashboardSectionInput = {\n id: string;\n label: string;\n /** Shown under the section label as \"by {agingBasisLabel}\". */\n agingBasisLabel: string;\n tone: BillTasksDashboardTone;\n};\n\nexport type BillTasksDashboardSection = BillTasksDashboardSectionInput & {\n rows: BillTasksDashboardRow[];\n /** Per-bucket totals across the section's rows. */\n totals: number[];\n total: number;\n balanceTotals?: number[];\n balanceTotal?: number;\n empty: boolean;\n};\n\nexport type BillTasksDashboardData = {\n sections: BillTasksDashboardSection[];\n grandTotals: number[];\n grandTotal: number;\n /** Work-item sums, not deduplicated financial A/R across task categories. */\n grandBalanceTotals?: number[];\n grandBalanceTotal?: number;\n};\n\n/**\n * Bucket index for an item age: a bucket admits `minDays < ageDays <= maxDays`\n * (`maxDays: null` = unbounded) and the first bucket also admits day 0.\n * Ages beyond every bucket clamp into the last bucket.\n */\nexport function billTasksAgingBucketIndex(\n ageDays: number,\n buckets: BillTasksAgingBucket[] = BILL_TASKS_AGING_BUCKETS,\n): number {\n const days = Math.max(0, Math.floor(ageDays));\n const index = buckets.findIndex((bucket, position) =>\n (bucket.maxDays === null || days <= bucket.maxDays)\n && (days > bucket.minDays || position === 0));\n return index === -1 ? buckets.length - 1 : index;\n}\n\n/**\n * Aggregates flat work items into the Bill Tasks dashboard.\n * Sections render in the given order even when empty; rows appear in\n * first-seen item order within their section.\n */\nexport function buildBillTasksDashboard(\n items: BillTasksDashboardItem[],\n sections: BillTasksDashboardSectionInput[],\n buckets: BillTasksAgingBucket[] = BILL_TASKS_AGING_BUCKETS,\n): BillTasksDashboardData {\n const zeros = () => buckets.map(() => 0);\n const built = sections.map((section): BillTasksDashboardSection => ({\n ...section,\n rows: [],\n totals: zeros(),\n total: 0,\n balanceTotals: zeros(),\n balanceTotal: 0,\n empty: true,\n }));\n const sectionById = new Map(built.map((section) => [section.id, section]));\n const rowByKey = new Map<string, BillTasksDashboardRow>();\n const grandTotals = zeros();\n let grandTotal = 0;\n const grandBalanceTotals = zeros();\n let grandBalanceTotal = 0;\n\n for (const item of items) {\n const section = sectionById.get(item.sectionId);\n if (!section) continue;\n const key = `${item.sectionId}\\u0000${item.rowId}`;\n let row = rowByKey.get(key);\n if (!row) {\n row = {\n id: item.rowId,\n label: item.rowLabel,\n counts: zeros(),\n total: 0,\n balances: zeros(),\n balanceTotal: 0,\n refs: buckets.map(() => []),\n };\n rowByKey.set(key, row);\n section.rows.push(row);\n section.empty = false;\n }\n const bucketIndex = billTasksAgingBucketIndex(item.ageDays, buckets);\n const balance = Number.isFinite(item.balanceDue) ? item.balanceDue! : 0;\n row.counts[bucketIndex] = (row.counts[bucketIndex] ?? 0) + 1;\n row.total += 1;\n row.balances![bucketIndex] = (row.balances![bucketIndex] ?? 0) + balance;\n row.balanceTotal = (row.balanceTotal ?? 0) + balance;\n if (item.ref) row.refs[bucketIndex]?.push(item.ref);\n section.totals[bucketIndex] = (section.totals[bucketIndex] ?? 0) + 1;\n section.total += 1;\n section.balanceTotals![bucketIndex] = (section.balanceTotals![bucketIndex] ?? 0) + balance;\n section.balanceTotal = (section.balanceTotal ?? 0) + balance;\n grandTotals[bucketIndex] = (grandTotals[bucketIndex] ?? 0) + 1;\n grandTotal += 1;\n grandBalanceTotals[bucketIndex] = (grandBalanceTotals[bucketIndex] ?? 0) + balance;\n grandBalanceTotal += balance;\n }\n\n return { sections: built, grandTotals, grandTotal, grandBalanceTotals, grandBalanceTotal };\n}\n\n\n/** Contacts snapshotted on a request and included in the reviewed form. */\nexport type RfaContact = {\n name?: string; contactName?: string; address?: string; city?: string; state?: string;\n zip?: string; phone?: string; fax?: string; email?: string;\n};\nexport type RfaDeliveryPreviewInput = { documentIds: string[]; channel: \"fax\" | \"email\" | \"download\"; to?: string; recipientName?: string; message?: string };\nexport type RfaDeliveryPreview = { packetId: string; sha256: string; contentRevision: number };\nexport type RfaSubmitInput = Omit<RfaDeliveryPreview, \"contentRevision\"> & { channel: \"fax\" | \"email\"; to: string; recipientName?: string; message?: string; nonBusinessDates?: string[] };\n/** An unsigned RFA preparation draft. Signing and sending are separate operations. */\nexport type RfaCreateDraftInput = {\n claimId: string; patientId: string; renderingProviderId: string; employeeName: string; providerName: string;\n externalId?: string; claimsAdminId?: string; writtenConfirmation?: boolean;\n requestingPractice?: RfaContact | null; authorizationContact?: RfaContact | null;\n requestType?: \"new\" | \"resubmission_material_change\" | \"oral_authorization_confirmation\";\n reviewType?: \"prospective\" | \"concurrent\" | \"retrospective\"; expedited?: boolean;\n placeOfServiceCode?: string; providerNpi?: string; providerPhone?: string; providerFax?: string;\n claimNumber?: string; dateOfInjury?: string; rationale?: string; materialChange?: string;\n items: Array<{ externalId?: string; diagnosisCode: string; diagnosisDescription?: string; serviceDescription: string; procedureCode?: string;\n quantity?: number; units?: number; frequency?: string; duration?: string; requestedFrom?: string; requestedTo?: string; metadata?: Record<string, unknown> }>;\n metadata?: Record<string, unknown>;\n};\n/** Full replacement of editable request content; retained service rows keep their IDs. */\nexport type RfaUpdateDraftInput = Omit<RfaCreateDraftInput, \"externalId\" | \"claimId\" | \"patientId\" | \"renderingProviderId\" | \"items\"> & {\n expectedRevision: number;\n items: Array<Omit<RfaCreateDraftInput[\"items\"][number], \"externalId\"> & { id?: string }>;\n};\nexport type RfaRecord = {\n contentRevision: number; id: string; claimId: string; patientId: string; renderingProviderId: string; claimsAdminId: string | null;\n employeeName: string; providerName: string; claimNumber: string | null; status: string;\n /** Delivery/review lifecycle, separate from the clinical status and item outcomes. */\n lifecycleStatus?: import(\"./rfa-status\").RfaLifecycleStatus;\n requestType?: RfaCreateDraftInput[\"requestType\"]; writtenConfirmation?: boolean;\n requestingPractice?: RfaContact | null; authorizationContact?: RfaContact | null;\n placeOfServiceCode?: string | null; providerNpi?: string | null; providerPhone?: string | null; providerFax?: string | null;\n dateOfInjury?: string | null; rationale?: string | null; materialChange?: string | null; metadata?: Record<string, unknown>;\n reviewType: string; expedited: boolean; createdAt: string | null; updatedAt: string | null;\n signedAt: string | null; submittedAt: string | null; receivedAt: string | null;\n decisionDueAt: string | null; decisionDeadlineBasis: string | null;\n incompleteReason: string | null; deferredReason: string | null; closedReason: string | null;\n readiness: { ready: boolean; missing: string[] };\n items: Array<{ id: string; diagnosisCode: string; diagnosisDescription?: string; serviceDescription: string; procedureCode: string | null;\n frequency?: string | null; duration?: string | null; requestedFrom?: string | null; requestedTo?: string | null; metadata?: Record<string, unknown>;\n outcome: string; quantity: number | null; units: number | null; authorizationNumber: string | null; decisionReason: string | null;\n decisionClosure?: import(\"./rfa-lifecycle\").RfaTreatmentClosure | null;\n currentDecisionEventId?: string | null; currentResponseDocumentId?: string | null; currentImrDocumentId?: string | null;\n authorizedProcedureCode?: string | null; authorizedQuantity?: number | null; authorizedUnits?: number | null;\n effectiveFrom?: string | null; effectiveTo?: string | null; decidedAt?: string | null; reviewerName?: string | null; reviewerPhone?: string | null }>;\n documents: Array<{ id: string; documentType: string; filename: string; contentUrl: string; contentRevision: number | null; createdAt: string | null }>;\n transmissions: Array<{ id: string; purpose?: string; direction: string; channel: string; status: string; destination: string | null;\n occurredAt: string | null; receivedAt: string | null; proofDocumentId: string | null; providerMessageId: string | null }>;\n informationRequests: Array<{ id: string; requestText: string; requestedAt: string | null; dueAt: string | null; respondedAt: string | null }>;\n events: Array<{ id: string; type: string; occurredAt: string | null; text?: string }>;\n};\nexport type RfaAgingBucket = \"0_5\" | \"6_14\" | \"15_30\" | \"31_plus\";\nexport type RfaAgingSummary = { byBucket: Record<RfaAgingBucket, number>; byLifecycleStatus: Record<import(\"./rfa-status\").RfaLifecycleStatus, Record<RfaAgingBucket, number>> };\nexport type RfaListQuery = { agingBucket?: RfaAgingBucket; patientId?: string; search?: string; sortBy?: \"createdAt\" | \"employeeName\" | \"providerName\" | \"submittedAt\" | \"status\" | \"lifecycleStatus\"; sortDirection?: \"asc\" | \"desc\"; claimId?: string; renderingProviderId?: string; status?: string; lifecycleStatus?: import(\"./rfa-status\").RfaLifecycleStatus; createdFrom?: string; createdTo?: string; limit?: number; cursor?: string };\nexport type RfaListResult = { data: RfaRecord[]; nextCursor: string | null; summary: { total: number; byStatus: Record<string, number>; aging?: RfaAgingSummary; byLifecycleStatus?: Partial<Record<import(\"./rfa-status\").RfaLifecycleStatus, number>> } };\nexport type RfaSigningPreviewInput = { billingProviderId?: string; diagnosisDescriptions: Record<string, string> };\nexport type RfaSigningPreview = { id: string; contentHash: string; contentRevision: number; renderingProviderId: string; previewDocumentId: string; expiresAt: string };\nexport type RfaSignInput = { snapshotId: string; contentHash: string; renderingProviderId: string; physicianAuthorized: true; actorReference: string };\nexport type RfaFaxInput = { to: string; documentIds: string[]; nonBusinessDates?: string[] };\nexport type RfaUploadDocumentInput = { file: File; documentType: \"clinical_report\" | \"supporting_record\" | \"ur_response\" | \"imr_form\" | \"other\"; contentRevision: number };\nexport type RfaCreationClaim = { claimId: string; patientId: string; employeeName: string; claimNumber?: string; dateOfInjury?: string; claimsAdminId?: string; diagnosisCodes?: string[] };\nexport type RfaCreationProvider = { id: string; name: string; npi?: string };\nexport type RfaCreationContext = { claims: RfaCreationClaim[]; renderingProviders: RfaCreationProvider[]; nextCursor: string | null; renderingProvidersNextCursor: string | null };\nexport type RfaCreationContextQuery = { search?: string; cursor?: string; providerSearch?: string; providerCursor?: string; limit?: number; claimId?: string; renderingProviderId?: string };\nexport type RfaProvisionClaimInput = {\n patient: Omit<BrowserBillCreateInput[\"patient\"], \"id\" | \"externalId\"> & { externalId: string };\n claim: Omit<BrowserBillCreateInput[\"claim\"], \"id\" | \"externalId\"> & { externalId: string };\n};\nexport type RfaProvisionClaimResult = { patientId: string; claimId: string; patientExternalId: string; claimExternalId: string; created: { patient: boolean; claim: boolean } };\nexport type RfaClient = {\n provisionClaim?: (input: RfaProvisionClaimInput, options?: { idempotencyKey?: string }) => Promise<RfaProvisionClaimResult>;\n searchClaimsAdministrators?: (query: string, claimNumber?: string) => Promise<BillReviewPayer[]>;\n saveProviderSignature?: (providerId: string, input: { contentBase64: string; physicianAuthorized: true; actorReference: string }, options?: { idempotencyKey?: string }) => Promise<{ providerId: string; signatureConfigured: true }>;\n\n getCreationContext: (query?: RfaCreationContextQuery) => Promise<RfaCreationContext>;\n list: (query?: RfaListQuery) => Promise<RfaListResult>;\n get: (rfaId: string) => Promise<RfaRecord>;\n createDraft: (draft: RfaCreateDraftInput, idempotencyKey: string) => Promise<RfaRecord>;\n updateDraft: (rfaId: string, draft: RfaUpdateDraftInput, idempotencyKey: string) => Promise<RfaRecord>;\n getDocument: (rfaId: string, documentId: string) => Promise<Blob>;\n uploadDocument: (rfaId: string, input: RfaUploadDocumentInput, idempotencyKey: string) => Promise<RfaRecord>;\n prepareSigning: (rfaId: string, input: RfaSigningPreviewInput, idempotencyKey: string) => Promise<RfaSigningPreview>;\n sign: (rfaId: string, input: RfaSignInput, idempotencyKey: string) => Promise<RfaRecord>;\n prepareDelivery: (rfaId: string, input: RfaDeliveryPreviewInput, key?: string) => Promise<RfaDeliveryPreview>;\n getPacket: (rfaId: string, packetId: string) => Promise<Blob>;\n submit: (rfaId: string, input: RfaSubmitInput, idempotencyKey: string) => Promise<RfaRecord>;\n previewPacket: (rfaId: string, documentIds: string[]) => Promise<Blob>;\n sendFax: (rfaId: string, input: RfaFaxInput, idempotencyKey: string) => Promise<RfaRecord>;\n refreshFaxes: (rfaId: string, idempotencyKey: string) => Promise<RfaRecord>;\n};\n/** Uses short-lived browser credentials. Never pass a partner API key. */\nexport function createRfaClient({ sessionEndpoint = DEFAULT_SESSION_ENDPOINT, getSession, apiBaseUrl = DEFAULT_API_BASE_URL, fetch: fetchOverride }: OrganizationClientOptions = {}): RfaClient {\n const fetcher = fetchOverride ?? globalThis.fetch;\n let session: BillLifecycleSession | null = null;\n let pending: Promise<BillLifecycleSession> | null = null;\n const mint = (force = false): Promise<BillLifecycleSession> => {\n if (!force && isSessionFresh(session)) return Promise.resolve(session as BillLifecycleSession);\n if (pending) return pending;\n pending = (async () => {\n const value = getSession ? await getSession({ signal: new AbortController().signal }) : await (async () => {\n const response = await fetcher(sessionEndpoint, { method: \"POST\", credentials: \"same-origin\", headers: { \"content-type\": \"application/json\" }, body: \"{}\" });\n if (!response.ok) throw await responseError(response, \"The RFA session could not be created.\");\n return response.json();\n })();\n session = normalizeSession(value); return session;\n })().finally(() => { pending = null; });\n return pending;\n };\n const request = async (path: string, init: RequestInit = {}, browser = false, resource = \"rfas\") => {\n const perform = (active: BillLifecycleSession) => {\n const headers = new Headers(init.headers); headers.set(\"authorization\", `Bearer ${active.token}`);\n if (init.body && !(init.body instanceof FormData)) headers.set(\"content-type\", \"application/json\");\n return fetcher(`${(active.apiBaseUrl ?? apiBaseUrl).replace(/\\/$/, \"\")}/partner/v2/${browser ? \"browser/\" : \"\"}${resource}${path}`, { ...init, headers });\n };\n let response = await perform(await mint());\n if (response.status === 401) response = await perform(await mint(true));\n if (!response.ok) throw await responseError(response, \"The RFA request failed.\");\n return response;\n };\n const record = async (path: string, init?: RequestInit): Promise<RfaRecord> => {\n const body = await (await request(path, init)).json() as { data?: RfaRecord };\n if (!body.data?.id) throw new Error(\"The RFA response was invalid.\");\n return body.data;\n };\n const mutation = (body: unknown, key: string): RequestInit => {\n if (!key.trim()) throw new Error(\"An idempotency key is required.\");\n return { method: \"POST\", headers: { \"idempotency-key\": key }, body: JSON.stringify(body) };\n };\n const path = (id: string, suffix: string) => `/${encodeURIComponent(id)}/${suffix}`;\n return {\n provisionClaim: async (input, options) => {\n const response = await request(\"\", mutation(input, options?.idempotencyKey ?? globalThis.crypto.randomUUID()), false, \"claims\");\n const body = await response.json() as RfaProvisionClaimResult;\n if (!body.patientId || !body.claimId) throw new Error(\"The saved patient and injury response was invalid.\");\n return body;\n },\n searchClaimsAdministrators: (query, claimNumber) => createBillReferenceClient({ sessionEndpoint, ...(getSession ? { getSession } : {}), apiBaseUrl, ...(fetchOverride ? { fetch: fetchOverride } : {}) }).searchClaimsAdministrators(query, claimNumber),\n saveProviderSignature: async (providerId, input, options) => {\n const response = await request(`/providers/${encodeURIComponent(providerId)}/signature`, mutation(input, options?.idempotencyKey ?? globalThis.crypto.randomUUID()), true);\n const body = await response.json() as { data: { providerId: string; signatureConfigured: true } };\n if (body.data?.signatureConfigured !== true) throw new Error(\"The physician signature could not be confirmed.\");\n return body.data;\n },\n getCreationContext: async (query = {}) => {\n const params = new URLSearchParams();\n for (const [name, value] of Object.entries(query)) if (value !== undefined && value !== \"\") params.set(name, String(value));\n const body = await (await request(`/creation-context${params.size ? `?${params}` : \"\"}`, {}, true)).json() as { data?: RfaCreationContext };\n if (!Array.isArray(body.data?.claims) || !Array.isArray(body.data?.renderingProviders)) throw new Error(\"The RFA creation context was invalid.\");\n return body.data;\n },\n list: async (query = {}) => {\n const params = new URLSearchParams();\n for (const [key, value] of Object.entries(query)) if (value !== undefined && value !== \"\") params.set(key, String(value));\n const body = await (await request(params.size ? `?${params}` : \"\")).json() as RfaListResult;\n if (!Array.isArray(body.data) || !body.summary) throw new Error(\"The RFA list response was invalid.\");\n return body;\n },\n get: (id) => record(`/${encodeURIComponent(id)}`),\n createDraft: (draft, idempotencyKey) => {\n if (!idempotencyKey.trim()) return Promise.reject(new Error(\"An idempotency key is required.\"));\n const unsigned = { ...draft } as RfaCreateDraftInput & { signedAt?: unknown }; delete unsigned.signedAt;\n unsigned.items = draft.items.map(item => { const copy = { ...item } as typeof item & { id?: unknown }; delete copy.id; return copy; });\n return record(\"\", { method: \"POST\", headers: { \"idempotency-key\": idempotencyKey }, body: JSON.stringify(unsigned) });\n },\n updateDraft: (id, draft, key) => {\n if (!Number.isInteger(draft.expectedRevision) || draft.expectedRevision < 1) return Promise.reject(new Error(\"A positive expected content revision is required.\"));\n const body = { ...draft } as RfaUpdateDraftInput & Record<string, unknown>;\n for (const field of [\"externalId\", \"claimId\", \"patientId\", \"renderingProviderId\", \"signedAt\"]) delete body[field];\n body.items = draft.items.map(item => { const copy = { ...item } as typeof item & { externalId?: unknown }; delete copy.externalId; return copy; });\n return record(path(id, \"draft\"), { ...mutation(body, key), method: \"PATCH\" });\n },\n uploadDocument: (id, input, key) => {\n if (!key.trim()) return Promise.reject(new Error(\"An idempotency key is required.\"));\n if (input.file.size < 1 || input.file.size > 25 * 1024 * 1024) return Promise.reject(new Error(\"Choose a PDF up to 25 MB.\"));\n const body = new FormData(); body.set(\"file\", input.file); body.set(\"documentType\", input.documentType); body.set(\"contentRevision\", String(input.contentRevision));\n return record(path(id, \"documents\"), { method: \"POST\", headers: { \"idempotency-key\": key }, body });\n },\n prepareSigning: async (id, input, key) => {\n const body = await (await request(path(id, \"signing-preview\"), mutation(input, key))).json() as { data: RfaSigningPreview };\n if (!body.data?.id || !body.data.contentHash || !body.data.previewDocumentId) throw new Error(\"The signing preview was invalid.\");\n return body.data;\n },\n sign: (id, input, key) => {\n if (input.physicianAuthorized !== true || !input.actorReference.trim()) return Promise.reject(new Error(\"Physician authorization and signer identity are required.\"));\n return record(path(id, \"sign\"), mutation(input, key));\n },\n prepareDelivery: async (id, input, key) => {\n const body = await (await request(path(id, \"delivery-preview\"), mutation(input, key ?? idempotencyKey()))).json() as { data: RfaDeliveryPreview };\n if (!body.data?.packetId || !body.data.sha256 || !body.data.contentRevision) throw new Error(\"The delivery preview was invalid.\");\n return body.data;\n },\n getPacket: async (id, packetId) => (await request(path(id, `packets/${encodeURIComponent(packetId)}`))).blob(),\n submit: async (id, input, key) => {\n const body = await (await request(path(id, \"submit\"), mutation(input, key))).json() as { data: { transmissionId: string; packetId: string } };\n if (!body.data?.transmissionId || !body.data.packetId) throw new Error(\"The submission response was invalid. Refresh before trying again.\");\n return record(`/${encodeURIComponent(id)}`);\n },\n previewPacket: async (id, documentIds) => (await request(path(id, \"packet\"), { method: \"POST\", body: JSON.stringify({ documentIds }) })).blob(),\n sendFax: (id, input, key) => record(path(id, \"fax\"), mutation(input, key)),\n refreshFaxes: (id, key) => record(path(id, \"fax/refresh\"), mutation({}, key)),\n getDocument: async (id, documentId) => (await request(`/${encodeURIComponent(id)}/documents/${encodeURIComponent(documentId)}`)).blob(),\n };\n}\n\nexport * from \"./rfa-lifecycle\";\nexport { createReportAutofillClient } from \"./report-autofill\";\nexport type { ReportAutofillClient, ReportAutofillField, ReportAutofillMatch, ReportAutofillResult } from \"./report-autofill\";\n\nexport * from \"./rfa-draft-actions\";\n\nexport * from \"./rfa-packets\";\n\nexport * from \"./rfa-status\";\n"],"mappings":";AAqDA,IAAM,SAAS,CAAC,MAA6C,CAAC,CAAC,KAAK,OAAO,MAAM,YAAY,CAAC,MAAM,QAAQ,CAAC;AAC7G,IAAM,UAAU,CAAC,MAA8B,MAAM,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC,MAAM,OAAO,MAAM,QAAQ;AACvG,IAAM,QAAQ,CAAC,MAAe,OAAO,cAAc,CAAC,KAAM,KAAgB;AAC1E,IAAM,SAAS,CAAC,MAAe,CAAC,UAAU,mBAAmB,wBAAwB,EAAE,SAAS,CAAW;AAC3G,IAAM,UAAU,CAAC,MAAe,OAAO,CAAC,KAAK,OAAO,EAAE,YAAY,YAAY,QAAQ,EAAE,OAAO,MAAM,EAAE,gBAAgB,UAAa,OAAO,EAAE,gBAAgB;AAEtJ,SAAS,qBAAqB,OAAgB,OAAoD;AACvG,QAAM,UAAU,MAAM;AAAE,UAAM,IAAI,MAAM,+CAA+C;AAAA,EAAG;AAC1F,MAAI,CAAC,OAAO,KAAK,KAAK,CAAC,OAAO,MAAM,MAAM,KAAK,CAAC,MAAM,QAAQ,MAAM,KAAK,KAAK,MAAM,MAAM,WAAW,MAAM,MAAM,UAAU,CAAC,QAAQ,MAAM,WAAW,KAAK,CAAC,OAAO,MAAM,MAAM,KAAK,C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G,GAAG,CAAC;AAAA,IAC5E,aAAa,OAAO,IAAI,gBAAgB,MAAM,QAAQ,IAAI,mBAAmB,EAAE,CAAC,cAAc,mBAAmB,UAAU,CAAC,EAAE,GAAG,KAAK;AAAA,EACxI;AACF;","names":["path","idempotencyKey","idempotencyKey","record","request","value","path","idempotencyKey"]}
|
|
1
|
+
{"version":3,"sources":["../src/claim-fees.ts","../src/rfa-directory.ts","../src/second-review-corrections.ts","../src/rfa-lifecycle.ts","../src/report-autofill.ts","../src/rfa-draft-actions.ts","../src/rfa-packets.ts","../src/rfa-status.ts","../src/index.ts"],"sourcesContent":["import type { BillFeeQuoteInput, BillFeeQuoteBasis } from \"./index\";\n\n/** One patient's complete services for one provider/group. Dates are service dates, not publication dates. */\nexport type CaClaimFeeQuoteInput = {\n lines: Array<Omit<BillFeeQuoteInput, \"billingProviderId\" | \"payerId\" | \"physicianContext\"> & {\n id: string;\n serviceCounty?: string;\n physicianContext?: Omit<NonNullable<BillFeeQuoteInput[\"physicianContext\"]>, \"providerKind\"> & {\n providerKind: NonNullable<BillFeeQuoteInput[\"physicianContext\"]>[\"providerKind\"] | \"clinical_social_worker\";\n telehealthModality?: \"audio_video\" | \"audio_only\";\n cmsSpecialtyCode?: string;\n };\n }>;\n completeDateOfServiceContext: boolean;\n ordinaryMultipleSurgeryContext?: boolean;\n};\nexport type CaFeeCitation = { id: string; url: string; sha256?: string; effectiveFrom?: string; effectiveThrough?: string };\nexport type CaFeeCalculation = {\n method: \"rbrvs\" | \"therapy_mppr\"; locality: string; serviceZip?: string; serviceCounty?: string;\n setting: \"facility\" | \"nonfacility\"; units: number; conversionFactor: string; providerPercent: number;\n baseMaximumCents?: number; cmsIndicators?: Record<string, string>;\n sourceFiles?: Array<{ kind: string; filename: string }>;\n components: Array<{ name: string; rvu: string; gpci: string; payableUnits: number }>;\n rounding: string;\n};\nexport type CaClaimEditFinding = {\n type: string; lineIds: string[]; message: string; citationUrl: string;\n column1?: string; column2?: string; modifierIndicator?: number; code?: string; limit?: number;\n submittedUnits?: number; adjudicationIndicator?: number; scope?: \"line\" | \"patient_provider_date\";\n};\nexport type CaClaimFeeFinding = { code: string; lineIds: string[]; message: string; citationUrl?: string; edit?: CaClaimEditFinding };\nexport type CaClaimLineQuote = ({ status: \"priced\"; amountCents: number; scheduleMaximumCents: number;\n basis: BillFeeQuoteBasis | \"ca_ambulance\"; notes: string[];\n feeBreakdown?: { method: string; inputs: Array<{ label: string; value: string }>; steps: Array<{ label: string; value: string }> };\n} | { status: \"requires_review\" | \"not_separately_payable\"; reason: string }) & {\n provenance: CaFeeCitation[]; calculation?: CaFeeCalculation;\n};\nexport type CaClaimFeeQuoteResult = {\n status: \"priced\" | \"requires_review\" | \"not_separately_payable\";\n lines: Array<{ id: string; input: CaClaimFeeQuoteInput[\"lines\"][number]; quote: CaClaimLineQuote;\n assessment: CaClaimFeeQuoteResult[\"status\"]; findings: CaClaimFeeFinding[];\n paymentAdjustment?: { rule: \"ca_multiple_surgery\"; rank: number; percent: 100 | 50;\n unadjustedScheduleMaximumCents: number; scheduleMaximumCents: number; amountCents: number; citationUrl: string };\n }>;\n totals: { submittedChargeCents: number | null; pricedSubtotalCents: number;\n estimatedPayableCents: number | null; scheduleMaximumCents: number | null; reviewLineCount: number };\n claimEdits: Array<{ dateOfService: string; lineIds: string[]; status: \"evaluated\" | \"requires_review\" | \"source_unavailable\" | \"not_applicable\";\n reason?: string; findings: CaClaimEditFinding[]; provenance?: unknown;\n supportedDateRange?: { from: string; through: string }; supportedDateIntervals?: Array<{ from: string; through: string }>;\n }>;\n limitations: string[];\n};\n\nconst record = (v: unknown): v is Record<string, unknown> => !!v && typeof v === \"object\" && !Array.isArray(v);\nconst strings = (v: unknown): v is string[] => Array.isArray(v) && v.every((x) => typeof x === \"string\");\nconst money = (v: unknown) => Number.isSafeInteger(v) && (v as number) >= 0;\nconst status = (v: unknown) => [\"priced\", \"requires_review\", \"not_separately_payable\"].includes(v as string);\nconst finding = (v: unknown) => record(v) && typeof v.message === \"string\" && strings(v.lineIds) && (v.citationUrl === undefined || typeof v.citationUrl === \"string\");\n/** Validate the transport before a browser displays an allowance. Unknown/partial results fail closed. */\nexport function parseCaClaimFeeQuote(value: unknown, input: CaClaimFeeQuoteInput): CaClaimFeeQuoteResult {\n const invalid = () => { throw new Error(\"Claim fee quote returned an invalid response.\"); };\n if (!record(value) || !status(value.status) || !Array.isArray(value.lines) || value.lines.length !== input.lines.length || !strings(value.limitations) || !record(value.totals) || !Array.isArray(value.claimEdits)) return invalid();\n const totals = value.totals;\n if (!money(totals.pricedSubtotalCents) || !money(totals.reviewLineCount) || [totals.submittedChargeCents, totals.estimatedPayableCents, totals.scheduleMaximumCents].some((v) => v !== null && !money(v))) return invalid();\n if (value.status === \"requires_review\" && totals.estimatedPayableCents !== null) return invalid();\n const expected = new Set(input.lines.map((line) => line.id));\n for (const line of value.lines) {\n if (!record(line) || typeof line.id !== \"string\" || !expected.delete(line.id) || !record(line.input) || typeof line.input.code !== \"string\" || line.input.id !== line.id || line.input.code !== input.lines.find((r) => r.id === line.id)?.code || line.input.dateOfService !== input.lines.find((r) => r.id === line.id)?.dateOfService || !status(line.assessment) || !record(line.quote) || !Array.isArray(line.findings) || !line.findings.every(finding)) return invalid();\n const quote = line.quote;\n if (!status(quote.status) || !Array.isArray(quote.provenance) || !quote.provenance.every((s) => record(s) && typeof s.id === \"string\" && typeof s.url === \"string\" && (s.effectiveFrom === undefined || typeof s.effectiveFrom === \"string\") && (s.effectiveThrough === undefined || typeof s.effectiveThrough === \"string\"))) return invalid();\n if (quote.status === \"priced\") {\n if (!money(quote.amountCents) || !money(quote.scheduleMaximumCents) || typeof quote.basis !== \"string\" || !strings(quote.notes)) return invalid();\n } else if (typeof quote.reason !== \"string\") return invalid();\n if (quote.calculation !== undefined) {\n const c = quote.calculation;\n if (!record(c) || typeof c.locality !== \"string\" || typeof c.conversionFactor !== \"string\" || !Number.isFinite(c.providerPercent) || ![\"facility\", \"nonfacility\"].includes(c.setting as string) || (c.sourceFiles !== undefined && (!Array.isArray(c.sourceFiles) || !c.sourceFiles.every((f) => record(f) && typeof f.kind === \"string\" && typeof f.filename === \"string\"))) || (c.cmsIndicators !== undefined && (!record(c.cmsIndicators) || !Object.values(c.cmsIndicators).every((v) => typeof v === \"string\"))) || !Array.isArray(c.components) || !c.components.every((r) => record(r) && typeof r.name === \"string\" && typeof r.rvu === \"string\" && typeof r.gpci === \"string\" && typeof r.payableUnits === \"number\")) return invalid();\n }\n if (quote.feeBreakdown !== undefined) {\n const b = quote.feeBreakdown;\n if (!record(b) || ![b.inputs, b.steps].every((rows) => Array.isArray(rows) && rows.every((r) => record(r) && typeof r.label === \"string\" && typeof r.value === \"string\"))) return invalid();\n }\n if (line.paymentAdjustment !== undefined) {\n const a = line.paymentAdjustment;\n if (!record(a) || !money(a.amountCents) || !money(a.scheduleMaximumCents) || !money(a.unadjustedScheduleMaximumCents) || typeof a.citationUrl !== \"string\" || ![100,50].includes(a.percent as number) || !money(a.rank)) return invalid();\n }\n }\n if (!value.claimEdits.every((edit) => record(edit) && typeof edit.dateOfService === \"string\" && strings(edit.lineIds) && [\"evaluated\", \"requires_review\", \"source_unavailable\", \"not_applicable\"].includes(edit.status as string) && Array.isArray(edit.findings) && edit.findings.every(finding) && (edit.reason === undefined || typeof edit.reason === \"string\"))) return invalid();\n return value as unknown as CaClaimFeeQuoteResult;\n}\n","import type { BillClaimsAdministratorDirectory } from \"./index\";\n\nexport type RfaAuthorizationDestinationOption = {\n method: \"fax\" | \"email\";\n destination: string;\n label: string;\n phone?: string;\n /** Recipient attention line, retained on the reviewed delivery cover. */\n recipientName?: string;\n};\n\n/** Accept fax numbers only, never telephone notes, email addresses, or extensions. */\nexport function normalizeRfaFax(value: string): string | null {\n const input = value.trim();\n if (/^\\+[1-9]\\d{7,14}$/.test(input)) return input;\n if (!/^\\+?[\\d ().-]+$/.test(input)) return null;\n const digits = input.replace(/\\D/g, \"\");\n if (digits.length === 10 && !input.startsWith(\"+\")) return `+1${digits}`;\n return digits.length === 11 && digits.startsWith(\"1\") ? `+${digits}` : null;\n}\n\n/** Returns choices only. Selecting or transmitting a destination is a separate user action. */\nexport function rfaAuthorizationDestinations(directory: BillClaimsAdministratorDirectory | null): RfaAuthorizationDestinationOption[] {\n if (!directory || [\"adjuster_specific_required\", \"daisybill_unverified\", \"profile_not_published\"].includes(directory.authorizationStatus ?? \"\")) return [];\n return (directory.authorization ?? []).flatMap((contact) => {\n const common = { label: contact.location || contact.name || \"Authorization department\", ...(contact.name ? { recipientName: contact.name } : {}), ...(contact.phone ? { phone: contact.phone } : {}) };\n const options: RfaAuthorizationDestinationOption[] = [];\n const fax = contact.fax ? normalizeRfaFax(contact.fax) : null;\n if (fax && contact.method !== \"email\") options.push({ ...common, method: \"fax\", destination: fax });\n if (contact.email?.trim() && contact.method !== \"fax\") options.push({ ...common, method: \"email\", destination: contact.email.trim() });\n return options;\n });\n}\n\nexport function rfaAuthorizationGuidance(directory: BillClaimsAdministratorDirectory | null): string {\n switch (directory?.authorizationStatus) {\n case \"central_fax\": return \"Select the central authorization fax after confirming it applies to this claim.\";\n case \"central_email\": return \"Authorization is routed by email. Confirm the recipient for this claim before sending the reviewed packet.\";\n case \"claim_handling_location_routes\": return \"Choose the office handling this claim. Authorization destinations vary by office.\";\n case \"adjuster_specific_required\": return \"Obtain the authorization destination from the handling adjuster.\";\n case \"daisybill_unverified\": return \"The directory has not verified an authorization destination. Confirm it with the handling adjuster.\";\n case \"profile_not_published\": return \"No authorization destination is currently published. Confirm a current destination with the handling adjuster.\";\n default: return \"Select an authorization contact or enter a destination confirmed with the handling adjuster.\";\n }\n}\n","import type { SecondReviewLineInput } from \"./index\";\n\nexport type CorrectionDraft = {\n correctBilling: boolean;\n units: string;\n modifiers: string;\n charge: string;\n chargeReviewed: boolean;\n};\n\nexport function parseSecondReviewCorrection(draft: CorrectionDraft): SecondReviewLineInput[\"correction\"] {\n if (!draft.correctBilling) return undefined;\n const units = Number(draft.units);\n const charge = Number(draft.charge);\n const modifiers = draft.modifiers.trim().toUpperCase().split(/[\\s,]+/).filter(Boolean);\n if (!draft.units.trim() || !Number.isInteger(units) || units < 1 || units > 10_000) {\n throw new Error(\"Corrected units must be a whole number from 1 to 10,000.\");\n }\n if (modifiers.length > 4 || new Set(modifiers).size !== modifiers.length || modifiers.some((value) => !/^[A-Z0-9]{2}$/.test(value))) {\n throw new Error(\"Enter up to four unique two-character modifiers, separated by commas. Leave blank to remove modifiers.\");\n }\n if (!draft.charge.trim() || !Number.isFinite(charge) || charge < 0 || charge > 999_999.99 || Math.abs(charge * 100 - Math.round(charge * 100)) > 0.000001) {\n throw new Error(\"Enter the corrected charge in dollars and cents.\");\n }\n if (!draft.chargeReviewed) throw new Error(\"Confirm that you reviewed the corrected charge. It is not recalculated automatically.\");\n return { units, modifiers, charge };\n}\n","import type { BillLifecycleSession, OrganizationClientOptions, RfaRecord } from \"./index\";\n\nexport type RfaReceiptInput = {\n channel: \"fax\" | \"email\" | \"edi\" | \"portal\" | \"mail\" | \"manual\";\n receivedAt: string;\n proofDocumentId?: string;\n providerMessageId?: string;\n};\nexport type RfaInformationRequestInput = { requestedAt: string; requestText: string; dueAt?: string };\nexport type RfaInformationResponseInput = { respondedAt: string; responseDocumentIds: string[] };\nexport type RfaTreatmentDecisionInput = {\n itemId: string; outcome: \"approved\" | \"modified\" | \"denied\";\n authorizationNumber?: string; authorizedProcedureCode?: string; authorizedQuantity?: number; authorizedUnits?: number;\n effectiveFrom?: string; effectiveTo?: string; decisionReason?: string; reviewerName?: string; reviewerPhone?: string;\n};\nexport type RfaDecisionsInput = { decidedAt: string; responseDocumentId: string; imrDocumentId?: string; decisions: RfaTreatmentDecisionInput[] };\nexport type RfaScheduling = {\n itemId: string; serviceDescription: string; outcome: string; eligible: boolean;\n authorizationToken: string; version: number; disposition: \"pending\" | \"scheduled\" | \"no_appointment\" | \"canceled\";\n current: boolean; appointmentAt: string | null; providerName: string | null; location: string | null;\n reason: string | null; updatedAt: string | null;\n};\nexport type RfaSchedulingInput = { expectedVersion: number; authorizationToken: string } & (\n { disposition: \"scheduled\"; appointmentAt: string; providerName: string; location: string } |\n { disposition: \"no_appointment\" | \"canceled\"; reason: string }\n);\nexport type RfaTreatmentClosureInput = { closed: boolean; reason: string; expectedVersion: number };\nexport type RfaTreatmentClosure = { closed: boolean; reason: string; version: number; updatedAt: string; updatedBy: string };\nexport type RfaDecisionCorrectionInput = { itemId: string; expectedDecisionEventId: string; reason: string; replacement: RfaDecisionsInput };\nexport type RfaHistoryEvent = { id: string; sequence: number; eventType: string; actor: string; payload: Record<string, unknown>; occurredAt: string | null };\nexport type RfaFollowUp = {\n id: string; rfaId: string; claimId: string; responseDocumentId: string | null; responseFilename: string | null;\n kind: string; status: string; dueAt: string; assigneeReference: string | null; snoozedUntil: string | null;\n lastOutcome: string | null; lastNote: string | null; createdAt: string; updatedAt: string; resolvedAt: string | null;\n};\nexport type RfaFollowUpUpdate = {\n assigneeReference?: string | null; snoozedUntil?: string | null;\n outcome?: \"message_left\" | \"decision_pending\" | \"decision_issued\" | \"not_on_file\" | \"reviewed\";\n note?: string;\n responseReview?: { disposition: \"no_new_decision\"; noNewDecisionConfirmed: true } | { disposition: \"decisions_recorded\"; allDecisionsRecordedConfirmed: true };\n};\nexport type RfaInboundFax = {\n id: string; receivedAt: string; fromFax: string | null; fromName: string | null; pages: number | null;\n ocrStatus: string | null; matchedRfaId: string | null; documentId: string | null; previewUrl: string;\n suggestedRfaIds: string[];\n};\nexport type RfaInboundFaxMatch = { faxId: string; rfaId: string; documentId: string; alreadyAttached: boolean };\nexport type RfaFollowUpList = { data: RfaFollowUp[]; nextCursor: string | null };\nexport type RfaLifecycleClient = {\n listInboundFaxes(query?: { includeMatched?: boolean; cursor?: string; limit?: number }): Promise<{ data: RfaInboundFax[]; hasMore: boolean; nextCursor: string | null }>;\n getInboundFaxContent(faxId: string): Promise<Blob>;\n matchInboundFax(faxId: string, rfaId: string, idempotencyKey: string): Promise<RfaInboundFaxMatch>;\n listScheduling(id: string): Promise<RfaScheduling[]>;\n updateScheduling(id: string, itemId: string, input: RfaSchedulingInput, idempotencyKey: string): Promise<RfaScheduling[]>;\n updateTreatmentClosure(id: string, itemId: string, input: RfaTreatmentClosureInput, idempotencyKey: string): Promise<RfaRecord>;\n correctDecision(id: string, input: RfaDecisionCorrectionInput, idempotencyKey: string): Promise<RfaRecord>;\n listHistory(id: string): Promise<RfaHistoryEvent[]>;\n addNote(id: string, text: string, idempotencyKey: string): Promise<RfaHistoryEvent>;\n recordReceipt(id: string, input: RfaReceiptInput, idempotencyKey: string): Promise<RfaRecord>;\n recordInformationRequest(id: string, input: RfaInformationRequestInput, idempotencyKey: string): Promise<RfaRecord>;\n recordInformationResponse(id: string, requestId: string, input: RfaInformationResponseInput, idempotencyKey: string): Promise<RfaRecord>;\n recordDecisions(id: string, input: RfaDecisionsInput, idempotencyKey: string): Promise<RfaRecord>;\n listFollowUps(query?: { patientId?: string; renderingProviderId?: string; claimId?: string; includeResolved?: boolean; limit?: number; cursor?: string }): Promise<RfaFollowUpList>;\n updateFollowUp(id: string, input: RfaFollowUpUpdate, idempotencyKey: string): Promise<RfaFollowUp>;\n clearSession(): void;\n};\n/** Records clinical workflow evidence. These methods never send faxes or reconcile notification queues. */\nexport function createRfaLifecycleClient({ sessionEndpoint = \"/api/mindbill/session\", getSession, apiBaseUrl = \"https://app.mindbill.org\", fetch: fetchOverride }: OrganizationClientOptions = {}): RfaLifecycleClient {\n const fetcher = fetchOverride ?? globalThis.fetch;\n let session: BillLifecycleSession | null = null;\n let pending: Promise<BillLifecycleSession> | null = null;\n const failure = async (response: Response): Promise<Error> => {\n const body = await response.json().catch(() => null) as { detail?: unknown; message?: unknown } | null;\n const detail = body?.detail ?? body?.message;\n return new Error(typeof detail === \"string\" ? detail : `The RFA request failed (${response.status}).`);\n };\n const mint = (force = false): Promise<BillLifecycleSession> => {\n if (!force && session && (!session.expiresAt || Date.parse(session.expiresAt) > Date.now() + 30_000)) return Promise.resolve(session);\n if (pending) return pending;\n pending = (async () => {\n const value: unknown = getSession ? await getSession({ signal: new AbortController().signal }) : await (async () => {\n const response = await fetcher(sessionEndpoint, { method: \"POST\", credentials: \"same-origin\", headers: { \"content-type\": \"application/json\" }, body: \"{}\" });\n if (!response.ok) throw await failure(response);\n return response.json();\n })();\n const envelope = value as { session?: unknown; data?: unknown } | null;\n const candidate = (envelope?.session ?? envelope?.data ?? value) as BillLifecycleSession | null;\n if (!candidate || typeof candidate.token !== \"string\" || candidate.token.length < 8) throw new Error(\"The RFA session endpoint did not return a browser session token.\");\n session = { token: candidate.token, ...(typeof candidate.expiresAt === \"string\" ? { expiresAt: candidate.expiresAt } : {}), ...(typeof candidate.apiBaseUrl === \"string\" ? { apiBaseUrl: candidate.apiBaseUrl } : {}) };\n return session;\n })().finally(() => { pending = null; });\n return pending;\n };\n const responseFor = async (path: string, init: RequestInit = {}): Promise<Response> => {\n const perform = (active: BillLifecycleSession) => {\n const headers = new Headers(init.headers); headers.set(\"authorization\", `Bearer ${active.token}`);\n if (init.body) headers.set(\"content-type\", \"application/json\");\n return fetcher(`${(active.apiBaseUrl ?? apiBaseUrl).replace(/\\/$/, \"\")}/partner/v2/${path}`, { ...init, headers });\n };\n let response = await perform(await mint());\n if (response.status === 401) response = await perform(await mint(true));\n if (!response.ok) throw await failure(response);\n return response;\n };\n const request = async <T>(path: string, init: RequestInit = {}): Promise<T> => (await responseFor(path, init)).json() as Promise<T>;\n const mutate = async <T extends { id: string }>(path: string, input: unknown, key: string, method = \"POST\"): Promise<T> => {\n if (!key.trim()) throw new Error(\"An idempotency key is required.\");\n const result = await request<{ data: T }>(path, { method, headers: { \"idempotency-key\": key }, body: JSON.stringify(input) });\n if (!result.data?.id) throw new Error(\"The RFA response was invalid.\");\n return result.data;\n };\n const path = (id: string, suffix: string) => `rfas/${encodeURIComponent(id)}/${suffix}`;\n const readArray = async <T>(route: string, init?: RequestInit): Promise<T[]> => {\n const result = await request<{ data: T[] }>(route, init);\n if (!Array.isArray(result.data)) throw new Error(\"The RFA response was invalid.\");\n return result.data;\n };\n return {\n listInboundFaxes: async (query = {}) => {\n const params = new URLSearchParams();\n for (const [key, value] of Object.entries(query)) if (value !== undefined) params.set(key, String(value));\n const result = await request<{ data: RfaInboundFax[]; hasMore: boolean; nextCursor: string | null }>(`rfa-inbound-faxes${params.size ? `?${params}` : \"\"}`);\n if (!Array.isArray(result.data) || typeof result.hasMore !== \"boolean\" || (result.nextCursor !== null && typeof result.nextCursor !== \"string\") || (result.hasMore && !result.nextCursor)) throw new Error(\"The inbound fax response was invalid.\");\n return result;\n },\n getInboundFaxContent: async faxId => (await responseFor(`rfa-inbound-faxes/${encodeURIComponent(faxId)}/content`)).blob(),\n matchInboundFax: async (faxId, rfaId, key) => {\n if (!key.trim()) throw new Error(\"An idempotency key is required.\");\n if (!rfaId.trim()) throw new Error(\"Choose an authorization request.\");\n const result = await request<{ data: RfaInboundFaxMatch }>(`rfa-inbound-faxes/${encodeURIComponent(faxId)}/match`, { method: \"POST\", headers: { \"idempotency-key\": key }, body: JSON.stringify({ rfaId }) });\n if (!result.data?.documentId || result.data.faxId !== faxId || result.data.rfaId !== rfaId) throw new Error(\"The fax match response was invalid.\");\n return result.data;\n },\n listScheduling: id => readArray<RfaScheduling>(path(id, \"scheduling\")),\n updateScheduling: (id, itemId, input, key) => {\n if (!key.trim()) return Promise.reject(new Error(\"An idempotency key is required.\"));\n return readArray<RfaScheduling>(path(id, `items/${encodeURIComponent(itemId)}/scheduling`), { method: \"PATCH\", headers: { \"idempotency-key\": key }, body: JSON.stringify(input) });\n },\n updateTreatmentClosure: (id, itemId, input, key) => {\n const reason = input.reason.trim();\n if (!reason || reason.length > 2000) return Promise.reject(new Error(\"Enter a reason of 1–2000 characters.\"));\n if (!Number.isInteger(input.expectedVersion) || input.expectedVersion < 0) return Promise.reject(new Error(\"Refresh to load the current treatment version.\"));\n return mutate(path(id, `items/${encodeURIComponent(itemId)}/closure`), { ...input, reason }, key, \"PATCH\");\n },\n correctDecision: (id, input, key) => mutate(path(id, \"decision-corrections\"), input, key),\n listHistory: id => readArray<RfaHistoryEvent>(path(id, \"events\")),\n addNote: (id, text, key) => {\n if (!text.trim()) return Promise.reject(new Error(\"Enter a note.\"));\n return mutate<RfaHistoryEvent>(path(id, \"events\"), { text: text.trim() }, key);\n },\n recordReceipt: (id, input, key) => {\n if (!input.proofDocumentId?.trim() && !input.providerMessageId?.trim()) return Promise.reject(new Error(\"Receipt requires a proof document or provider reference.\"));\n return mutate(path(id, \"transmissions\"), { ...input, direction: \"inbound\", status: \"received\", occurredAt: input.receivedAt }, key);\n },\n recordInformationRequest: (id, input, key) => mutate(path(id, \"information-requests\"), input, key),\n recordInformationResponse: (id, requestId, input, key) => mutate(path(id, `information-requests/${encodeURIComponent(requestId)}`), input, key),\n recordDecisions: (id, input, key) => mutate(path(id, \"decisions\"), input, key),\n listFollowUps: async (query = {}) => {\n const params = new URLSearchParams();\n for (const [key, value] of Object.entries(query)) if (value !== undefined) params.set(key, String(value));\n const result = await request<RfaFollowUpList>(`rfa-follow-ups${params.size ? `?${params}` : \"\"}`);\n if (!Array.isArray(result.data) || !(result.nextCursor === null || typeof result.nextCursor === \"string\")) throw new Error(\"The RFA follow-up response was invalid.\");\n return result;\n },\n updateFollowUp: (id, input, key) => mutate(`rfa-follow-ups/${encodeURIComponent(id)}`, input, key, \"PATCH\"),\n clearSession: () => { session = null; },\n };\n}\n","import type { BillLifecycleSession, OrganizationClientOptions } from \"./index\";\n\nexport type ReportAutofillField = { key: string; value: string; sourceText: string; confidence: \"high\" | \"medium\" };\nexport type ReportAutofillMatch = { status: \"matched\" | \"ambiguous\" | \"none\"; candidates: Array<{ id: string; name: string }>; selectedId?: string };\nexport type ReportAutofillResult = {\n model: \"gpt-5.6-luna\"; requiresReview: true; fields: ReportAutofillField[];\n matches: Record<\"patient\" | \"billingProvider\" | \"renderingProvider\" | \"serviceLocation\", ReportAutofillMatch>;\n warnings: string[];\n};\nexport type ReportAutofillClient = { analyze(report: File): Promise<ReportAutofillResult>; clearSession(): void };\n/** Available only by written agreement, with an organization-wide autofill:run session. Does not save a document or submit a bill. */\nexport function createReportAutofillClient({ sessionEndpoint = \"/api/mindbill/session\", getSession, apiBaseUrl = \"https://app.mindbill.org\", fetch: fetchOverride }: OrganizationClientOptions = {}): ReportAutofillClient {\n const fetcher = fetchOverride ?? globalThis.fetch;\n let session: BillLifecycleSession | null = null;\n const error = async (response: Response) => {\n const body = await response.json().catch(() => null) as { detail?: unknown; message?: unknown } | null;\n return new Error(typeof body?.detail === \"string\" ? body.detail : typeof body?.message === \"string\" ? body.message : `Report analysis failed (${response.status}).`);\n };\n const mint = async (): Promise<BillLifecycleSession> => {\n if (session && (!session.expiresAt || Date.parse(session.expiresAt) > Date.now() + 30_000)) return session;\n const value: unknown = getSession ? await getSession({ signal: new AbortController().signal }) : await (async () => {\n const response = await fetcher(sessionEndpoint, { method: \"POST\", credentials: \"same-origin\", headers: { \"content-type\": \"application/json\" }, body: \"{}\" });\n if (!response.ok) throw await error(response);\n return response.json();\n })();\n const envelope = value as { session?: unknown; data?: unknown } | null;\n const candidate = (envelope?.session ?? envelope?.data ?? value) as BillLifecycleSession | null;\n if (!candidate || typeof candidate.token !== \"string\" || candidate.token.length < 8) throw new Error(\"The report session endpoint did not return a browser session token.\");\n session = candidate;\n return candidate;\n };\n return {\n clearSession: () => { session = null; },\n analyze: async report => {\n if (report.type !== \"application/pdf\") throw new Error(\"Choose a PDF report.\");\n if (!report.size || report.size > 25 * 1024 * 1024) throw new Error(\"Choose a non-empty PDF report no larger than 25 MB.\");\n const perform = async () => {\n const active = await mint(); const body = new FormData(); body.append(\"report\", report);\n return fetcher(`${(active.apiBaseUrl ?? apiBaseUrl).replace(/\\/$/, \"\")}/partner/v2/report-autofill`, { method: \"POST\", headers: { authorization: `Bearer ${active.token}` }, body });\n };\n let response = await perform();\n if (response.status === 401) { session = null; response = await perform(); }\n if (!response.ok) throw await error(response);\n const envelope = await response.json() as { data?: ReportAutofillResult };\n const result = envelope.data;\n if (!result || result.requiresReview !== true || !Array.isArray(result.fields) || !Array.isArray(result.warnings) || !result.matches\n || result.fields.some(field => !field || typeof field.key !== \"string\" || typeof field.value !== \"string\" || typeof field.sourceText !== \"string\" || ![\"high\", \"medium\"].includes(field.confidence))\n || result.warnings.some(warning => typeof warning !== \"string\")\n || ([\"patient\", \"billingProvider\", \"renderingProvider\", \"serviceLocation\"] as const).some(kind => {\n const match = result.matches[kind];\n return !match || ![\"matched\", \"ambiguous\", \"none\"].includes(match.status) || !Array.isArray(match.candidates) || match.candidates.some(candidate => !candidate || typeof candidate.id !== \"string\" || typeof candidate.name !== \"string\");\n })) throw new Error(\"The report analysis response was invalid.\");\n return result;\n },\n };\n}\n","import type { BillLifecycleSession, OrganizationClientOptions, RfaRecord } from \"./index\";\n\nexport type RfaDraftActionsClient = {\n /** Copies the request content into a new unsigned draft. Attachments and delivery are not copied. */\n copy(id: string, expectedRevision: number, idempotencyKey: string): Promise<RfaRecord>;\n /** Cancels only an unchanged, unsigned, unsubmitted draft; audit history is retained. */\n cancelDraft(id: string, expectedRevision: number, idempotencyKey: string): Promise<RfaRecord>;\n clearSession(): void;\n};\n\nexport function createRfaDraftActionsClient({ sessionEndpoint = \"/api/mindbill/session\", getSession, apiBaseUrl = \"https://app.mindbill.org\", fetch: fetchOverride }: OrganizationClientOptions = {}): RfaDraftActionsClient {\n const fetcher = fetchOverride ?? globalThis.fetch;\n let session: BillLifecycleSession | null = null;\n let pending: Promise<BillLifecycleSession> | null = null;\n const failure = async (response: Response) => {\n const body = await response.json().catch(() => null) as { detail?: unknown; message?: unknown; error?: { message?: unknown } } | null;\n const detail = body?.detail ?? body?.message ?? body?.error?.message;\n return new Error(typeof detail === \"string\" ? detail : `The RFA request failed (${response.status}).`);\n };\n const mint = (force = false): Promise<BillLifecycleSession> => {\n if (!force && session && (!session.expiresAt || Date.parse(session.expiresAt) > Date.now() + 30_000)) return Promise.resolve(session);\n if (pending) return pending;\n pending = (async () => {\n const value: unknown = getSession ? await getSession({ signal: new AbortController().signal }) : await (async () => {\n const response = await fetcher(sessionEndpoint, { method: \"POST\", credentials: \"same-origin\", headers: { \"content-type\": \"application/json\" }, body: \"{}\" });\n if (!response.ok) throw await failure(response);\n return response.json();\n })();\n const envelope = value as { session?: unknown; data?: unknown } | null;\n const candidate = (envelope?.session ?? envelope?.data ?? value) as BillLifecycleSession | null;\n if (!candidate || typeof candidate.token !== \"string\" || candidate.token.length < 8) throw new Error(\"The RFA session endpoint did not return a browser session token.\");\n session = { token: candidate.token, ...(typeof candidate.expiresAt === \"string\" ? { expiresAt: candidate.expiresAt } : {}), ...(typeof candidate.apiBaseUrl === \"string\" ? { apiBaseUrl: candidate.apiBaseUrl } : {}) };\n return session;\n })().finally(() => { pending = null; });\n return pending;\n };\n const mutate = async (id: string, expectedRevision: number, idempotencyKey: string, action: \"copy\" | \"cancel\"): Promise<RfaRecord> => {\n if (!id.trim()) throw new Error(\"An RFA ID is required.\");\n if (!Number.isSafeInteger(expectedRevision) || expectedRevision < 1) throw new Error(\"The current RFA content revision is required.\");\n if (!idempotencyKey.trim()) throw new Error(\"An idempotency key is required.\");\n const perform = (active: BillLifecycleSession) => fetcher(`${(active.apiBaseUrl ?? apiBaseUrl).replace(/\\/$/, \"\")}/partner/v2/rfas/${encodeURIComponent(id)}${action === \"copy\" ? \"/copy\" : \"\"}`, {\n method: action === \"copy\" ? \"POST\" : \"PATCH\", headers: { authorization: `Bearer ${active.token}`, \"content-type\": \"application/json\", \"idempotency-key\": idempotencyKey }, body: JSON.stringify(action === \"copy\" ? { expectedRevision } : { status: \"canceled\", draftOnly: true, expectedRevision }),\n });\n let response = await perform(await mint());\n if (response.status === 401) response = await perform(await mint(true));\n if (!response.ok) throw await failure(response);\n const result = await response.json() as { data?: RfaRecord };\n if (!result.data?.id) throw new Error(\"The RFA response was invalid.\");\n return result.data;\n };\n return {\n copy: (id, revision, key) => mutate(id, revision, key, \"copy\"),\n cancelDraft: (id, revision, key) => mutate(id, revision, key, \"cancel\"),\n clearSession: () => { session = null; },\n };\n}\n","import type { BillLifecycleSession, OrganizationClientOptions } from \"./index\";\n\nexport type RfaSavedPacket = { id: string; source: \"download\" | \"submission\"; sha256: string; sizeBytes: number; contentRevision: number; createdAt: string };\nexport type RfaPacketTransmission = { id: string; packetId: string | null; purpose: \"submission\" | \"forward\"; channel: string; status: string; destination: string | null; occurredAt: string; receivedAt: string | null };\nexport type RfaPacketHistory = { packets: RfaSavedPacket[]; transmissions: RfaPacketTransmission[] };\nexport type RfaForwardInput = { packetId: string; channel: \"fax\" | \"email\"; to: string };\nexport type RfaForwardResult = { transmissionId: string; packetId: string };\nexport type RfaPacketsClient = {\n list(id: string): Promise<RfaPacketHistory>;\n get(id: string, packetId: string): Promise<Blob>;\n /** Forwards retained bytes without changing the original submission or review deadline. */\n forward(id: string, input: RfaForwardInput, idempotencyKey: string): Promise<RfaForwardResult>;\n clearSession(): void;\n};\n\nexport function createRfaPacketsClient({ sessionEndpoint = \"/api/mindbill/session\", getSession, apiBaseUrl = \"https://app.mindbill.org\", fetch: fetchOverride }: OrganizationClientOptions = {}): RfaPacketsClient {\n const fetcher = fetchOverride ?? globalThis.fetch;\n let session: BillLifecycleSession | null = null;\n let pending: Promise<BillLifecycleSession> | null = null;\n const failure = async (response: Response) => {\n const body = await response.json().catch(() => null) as { detail?: unknown; message?: unknown; error?: { message?: unknown } } | null;\n const detail = body?.detail ?? body?.message ?? (typeof body?.error === \"string\" ? body.error : body?.error?.message);\n return new Error(typeof detail === \"string\" ? detail : `The RFA request failed (${response.status}).`);\n };\n const mint = (force = false): Promise<BillLifecycleSession> => {\n if (!force && session && (!session.expiresAt || Date.parse(session.expiresAt) > Date.now() + 30_000)) return Promise.resolve(session);\n if (pending) return pending;\n pending = (async () => {\n const value: unknown = getSession ? await getSession({ signal: new AbortController().signal }) : await (async () => {\n const response = await fetcher(sessionEndpoint, { method: \"POST\", credentials: \"same-origin\", headers: { \"content-type\": \"application/json\" }, body: \"{}\" });\n if (!response.ok) throw await failure(response);\n return response.json();\n })();\n const envelope = value as { session?: unknown; data?: unknown } | null;\n const candidate = (envelope?.session ?? envelope?.data ?? value) as BillLifecycleSession | null;\n if (!candidate || typeof candidate.token !== \"string\" || candidate.token.length < 8) throw new Error(\"The RFA session endpoint did not return a browser session token.\");\n session = { token: candidate.token, ...(typeof candidate.expiresAt === \"string\" ? { expiresAt: candidate.expiresAt } : {}), ...(typeof candidate.apiBaseUrl === \"string\" ? { apiBaseUrl: candidate.apiBaseUrl } : {}) };\n return session;\n })().finally(() => { pending = null; });\n return pending;\n };\n const request = async (id: string, path: string, init?: RequestInit): Promise<Response> => {\n if (!id.trim()) throw new Error(\"An RFA ID is required.\");\n const perform = (active: BillLifecycleSession) => fetcher(`${(active.apiBaseUrl ?? apiBaseUrl).replace(/\\/$/, \"\")}/partner/v2/rfas/${encodeURIComponent(id)}${path}`, {\n ...init, headers: { ...init?.headers, authorization: `Bearer ${active.token}` },\n });\n let response = await perform(await mint());\n if (response.status === 401) response = await perform(await mint(true));\n if (!response.ok) throw await failure(response);\n return response;\n };\n return {\n async list(id) {\n const result = await (await request(id, \"/packets\")).json() as { data?: RfaPacketHistory };\n if (!result.data || !Array.isArray(result.data.packets) || !Array.isArray(result.data.transmissions)) throw new Error(\"The saved packet response was invalid.\");\n return result.data;\n },\n async get(id, packetId) {\n if (!packetId.trim()) throw new Error(\"A saved packet ID is required.\");\n const response = await request(id, `/packets/${encodeURIComponent(packetId)}`);\n if (!response.headers.get(\"content-type\")?.toLowerCase().startsWith(\"application/pdf\")) throw new Error(\"The saved packet response was not a PDF.\");\n return response.blob();\n },\n async forward(id, input, idempotencyKey) {\n if (!input.packetId.trim()) throw new Error(\"A saved packet ID is required.\");\n if (!idempotencyKey.trim()) throw new Error(\"An idempotency key is required.\");\n const to = input.to.trim();\n if (input.channel === \"fax\" ? !/^\\+[1-9]\\d{7,14}$/.test(to) : input.channel !== \"email\" || to.length > 254 || !/^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/.test(to)) throw new Error(\"Enter a valid recipient email or fax number with country code.\");\n const result = await (await request(id, \"/forwards\", { method: \"POST\", headers: { \"content-type\": \"application/json\", \"idempotency-key\": idempotencyKey }, body: JSON.stringify({ packetId: input.packetId, channel: input.channel, to: input.channel === \"email\" ? to.toLowerCase() : to }) })).json() as { data?: RfaForwardResult };\n if (!result.data?.transmissionId || result.data.packetId !== input.packetId) throw new Error(\"The forwarding response was invalid. Check delivery history before retrying.\");\n return result.data;\n },\n clearSession: () => { session = null; },\n };\n}\n","import type { RfaRecord } from \"./index\";\n\nexport type RfaLifecycleStatus = \"incomplete\" | \"sent\" | \"failed\" | \"received\" | \"closed\" | \"canceled\";\nexport const RFA_LIFECYCLE_LABELS: Readonly<Record<RfaLifecycleStatus, string>> = {\n incomplete: \"Incomplete\", sent: \"Sent\", failed: \"Failed\", received: \"Received\", closed: \"Closed\", canceled: \"Canceled\",\n};\ntype LifecycleRecord = Pick<RfaRecord, \"status\"> & Partial<Pick<RfaRecord, \"lifecycleStatus\" | \"submittedAt\" | \"receivedAt\" | \"transmissions\">>;\nconst timestamp = (value: string | null | undefined): number => value ? Date.parse(value) || 0 : 0;\n\n/** Prefer the API lifecycle. Older responses are derived from the current submission's evidence. */\nexport function getRfaLifecycleStatus(rfa: LifecycleRecord): RfaLifecycleStatus {\n if (rfa.lifecycleStatus && Object.hasOwn(RFA_LIFECYCLE_LABELS, rfa.lifecycleStatus)) return rfa.lifecycleStatus;\n if (rfa.status === \"canceled\") return \"canceled\";\n if ([\"closed\", \"approved\", \"modified\", \"denied\", \"mixed\"].includes(rfa.status)) return \"closed\";\n const submissions = (rfa.transmissions ?? []).filter(value => !value.purpose || value.purpose === \"submission\");\n const latest = submissions.filter(value => value.direction === \"outbound\").sort((a, b) =>\n timestamp(b.occurredAt) - timestamp(a.occurredAt) || b.id.localeCompare(a.id))[0];\n if (latest) {\n const received = latest.receivedAt || submissions.some(value => value.direction === \"inbound\" && value.status === \"received\"\n && timestamp(value.receivedAt ?? value.occurredAt) >= timestamp(latest.occurredAt));\n if (received) return \"received\";\n return latest.status === \"failed\" ? \"failed\" : \"sent\";\n }\n if (rfa.receivedAt || [\"received\", \"under_review\", \"information_requested\"].includes(rfa.status)) return \"received\";\n if (rfa.submittedAt || rfa.status === \"submitted\") return \"sent\";\n return \"incomplete\";\n}\n","import { parseCaClaimFeeQuote, type CaClaimFeeQuoteInput, type CaClaimFeeQuoteResult } from \"./claim-fees\";\n/** Paper claim family; clearinghouse transport is selected by the server. */\nexport type ClaimForm = \"cms1500\" | \"ub04\" | \"ada\" | \"ncpdp\";\n/** JSON fields validated by the server's form-specific contract. */\nexport type BillFormValue = string | number | boolean | null | BillFormValue[] | { [key: string]: BillFormValue };\nexport type BillFormData = {\n institutional?: { [key: string]: BillFormValue };\n dental?: { [key: string]: BillFormValue };\n pharmacy?: { [key: string]: BillFormValue };\n};\n/** Service-line metadata, including revenue, tooth, and prescription details. */\nexport type BillLineFormData = BillFormData;\n\nexport type { CaClaimFeeQuoteInput, CaClaimFeeQuoteResult, CaClaimLineQuote, CaFeeCalculation, CaFeeCitation, CaClaimEditFinding, CaClaimFeeFinding } from \"./claim-fees\";\nexport { normalizeRfaFax, rfaAuthorizationDestinations, rfaAuthorizationGuidance } from \"./rfa-directory\";\nexport type { RfaAuthorizationDestinationOption } from \"./rfa-directory\";\nexport const DEFAULT_API_BASE_URL = \"https://app.mindbill.org\";\nexport const DEFAULT_SESSION_ENDPOINT = \"/api/mindbill/session\";\nexport { parseSecondReviewCorrection, type CorrectionDraft } from \"./second-review-corrections\";\n\nexport type BillReviewDocumentType =\n | \"final_report\"\n | \"letter_of_attestation\"\n | \"proof_of_service\"\n | \"form_122\"\n | \"return_to_work_voucher\"\n | \"w9\"\n | \"medical_records\"\n | \"appeal\"\n | \"other\";\n\nexport type BillReviewBillingProvider = {\n name: string;\n taxId: string;\n taxIdType?: \"EIN\" | \"SSN\";\n taxIdConfigured?: boolean;\n taxIdLast4?: string;\n npi: string;\n billType: \"Professional\" | \"Institutional\" | \"Dental\" | \"Pharmacy\";\n phone?: string;\n billingStreet?: string;\n billingCity?: string;\n billingState?: string;\n billingZip?: string;\n};\n\nexport type BillReviewClinician = {\n /** Canonical opaque provider ID, when available. */\n id?: string;\n name: string;\n specialty: string;\n npi: string;\n taxonomy?: string;\n licenseNumber?: string;\n licenseState?: string;\n signaturePng?: string;\n signatureKey?: string;\n isQME?: boolean;\n isAME?: boolean;\n email?: string;\n active?: boolean;\n};\n\nexport type BillReviewLocation = {\n billingProviderId?: string;\n name: string;\n nickname?: string;\n street: string;\n city: string;\n state: string;\n zip: string;\n county?: string;\n posCode?: string;\n isPrimary?: boolean;\n active?: boolean;\n};\n\n/** Verified, server-provided fee explanation. Display strings only; never recalculate fees from these values. */\nexport type BillLineFeeBreakdown = {\n method: string;\n inputs: Array<{ label: string; value: string }>;\n steps: Array<{ label: string; value: string }>;\n notes: string[];\n};\n\nexport type BillReviewLineItem = {\n formData?: BillLineFormData;\n drug?: BilledDrug;\n id?: string;\n code: string;\n modifiers: string[];\n units: number;\n charge: number;\n feeSchedule?: number;\n /** Omitted when no verified fee explanation is available for this saved line. */\n pricing?: { breakdown?: BillLineFeeBreakdown };\n serviceDate?: string | null;\n serviceDateEnd?: string | null;\n diagnosisPointers?: number[];\n};\n\nexport type BillReviewAttachment = {\n id: string;\n filename: string;\n description?: string | null;\n documentType: string;\n reportType?: string | null;\n source?: string;\n addedAt?: string;\n contentUrl?: string;\n};\n\n/** One selectable payer (subpayor) under a claims administrator. */\nexport type BillReviewPayerOption = {\n id: string;\n label: string;\n /** Directory-provided default marker. Interactive forms still require an explicit choice. */\n default?: boolean;\n active?: boolean;\n aliases?: string[];\n hint?: string | null;\n affiliatedEntities?: string[];\n route?: string | null;\n optionType?: string | null;\n deliveryType?: string | null;\n clearinghouse?: string | null;\n payerId?: string | null;\n /** Original directory route when live delivery uses a replacement clearinghouse. */\n sourceClearinghouse?: string | null;\n /** Original directory payer ID when live delivery uses a replacement route. */\n sourcePayerId?: string | null;\n clearinghousePayerIds?: Record<string, string>;\n preferredClearinghouse?: string | null;\n};\n\nexport type BillReviewPayer = {\n id: string;\n name: string;\n hasElectronic?: boolean;\n states?: string[];\n confidence?: \"high\" | \"medium\" | \"directory\";\n recommended?: boolean;\n signals?: Array<{\n kind: \"name\" | \"claim_number\";\n state: \"match\" | \"warning\";\n label: string;\n }>;\n /** True when a bill for this claims administrator must name one of `payers`. */\n payerSelectionRequired?: boolean;\n /** Selectable payers (subpayors) under this claims administrator. */\n payers?: BillReviewPayerOption[];\n aliases?: string[];\n affiliatedEntities?: string[];\n claimNumberHint?: string | null;\n claimNumberPatterns?: BillClaimsAdministratorPattern[];\n route?: string | null;\n};\n\n/** A directory suggestion derived from host-provided evidence. Suggestions are never auto-applied. */\nexport type BillReviewPayerSuggestion = BillReviewPayer & {\n deterministic: boolean;\n reason: string;\n /** A uniquely proven routing payer under a multi-payer claims administrator. */\n selectedPayerId?: string;\n};\n\n/** Host-system evidence shown alongside claims-administrator suggestions. */\nexport type BillClaimsAdministratorSource = {\n source: \"eams\" | \"report\" | string;\n label: string;\n name: string;\n url?: string;\n};\n\n/**\n * The directory-marked default payer option, or null when none is marked.\n * Interactive forms should still require an explicit routing-payer choice.\n */\nexport function defaultBillReviewPayerOption(\n payer: Pick<BillReviewPayer, \"payerSelectionRequired\" | \"payers\">,\n): BillReviewPayerOption | null {\n if (!payer.payerSelectionRequired) return null;\n return payer.payers?.find((option) => option.default) ?? null;\n}\n\nexport type BillPostalPlace = { city: string; state: string };\nexport type BillDiagnosisCode = { code: string; description: string };\n\nexport type BillReviewFeatures = {\n authorizationNumber?: boolean;\n serviceDateRange?: boolean;\n wcabNumber?: boolean;\n codingPresets?: boolean;\n};\n\nexport type BillReviewClaimPatternStatus = {\n state: \"match\" | \"warning\" | \"unknown\";\n label: string;\n detail?: string;\n suggestion?: string;\n};\n\nexport type BillReviewData = {\n options?: Pick<OrganizationProfileData, \"billingProviders\" | \"renderingProviders\" | \"locations\">;\n bill: {\n claimForm?: ClaimForm;\n formData?: BillFormData;\n id: string;\n billNumber: string | number;\n status: string;\n transmissionState?: string;\n billingMode: \"med_legal\" | \"professional\";\n dos: string;\n dosEnd?: string | null;\n authorizationNumber?: string | null;\n billingSnapshot?: {\n billingProvider?: BillReviewBillingProvider;\n renderingProvider?: BillReviewClinician;\n placeOfService?: BillReviewLocation;\n } | null;\n lineItems: BillReviewLineItem[];\n attachments: BillReviewAttachment[];\n totalCharge: number;\n totalPaid: number;\n balanceDue: number;\n };\n patient: {\n /** Canonical opaque patient ID, when available. */\n id?: string;\n name: string;\n firstName?: string;\n middleName?: string;\n lastName?: string;\n dob?: string;\n phone?: string;\n address?: {\n line1?: string;\n city?: string;\n state?: string;\n postalCode?: string;\n };\n };\n injury: {\n claimNumber?: string;\n employer?: string;\n doi?: string;\n injuryEndDate?: string;\n cumulativeTrauma?: boolean;\n adjNumber?: string;\n medicalProviderNetworkId?: string | null;\n claimsAdminId?: string;\n claimsAdminName?: string;\n injuryDescription?: string;\n /** Diagnosis codes enriched with their human-readable ICD-10 descriptions. */\n diagnoses?: BillDiagnosisCode[];\n /** @deprecated Prefer diagnoses so users can understand each code. */\n diagnosisCodes?: string[];\n claimPatternStatus?: BillReviewClaimPatternStatus;\n };\n};\n\nexport type BillReviewSaveInput = {\n formData?: BillFormData;\n claimsAdminId: string;\n /** The chosen payer (subpayor) when the claims administrator requires payer selection. */\n payerId?: string;\n patientOverrides?: {\n firstName: string;\n middleName?: string;\n lastName: string;\n dob?: string;\n };\n injuryOverrides?: {\n claimNumber?: string;\n employer?: string;\n doi?: string;\n injuryEndDate?: string;\n cumulativeTrauma?: boolean;\n adjNumber?: string;\n medicalProviderNetworkId?: string | null;\n };\n dos: string;\n dosEnd?: string | null;\n authorizationNumber?: string | null;\n billingProvider?: BillReviewBillingProvider;\n renderingProvider?: BillReviewClinician;\n placeOfService?: BillReviewLocation;\n lineItems: Array<{\n formData?: BillLineFormData;\n drug?: BilledDrug;\n id?: string;\n code: string;\n modifiers: string[];\n units: number;\n charge?: number;\n serviceDate?: string | null;\n serviceDateEnd?: string | null;\n diagnosisPointers?: number[];\n }>;\n};\n\nfunction pickDefined(\n source: object,\n keys: readonly string[],\n): Record<string, unknown> {\n const record = source as Record<string, unknown>;\n return Object.fromEntries(\n keys.flatMap((key) => record[key] === undefined ? [] : [[key, record[key]]]),\n );\n}\n\n/**\n * Removes read-only snapshot metadata before a review mutation is sent.\n * Lifecycle reads can include display-only fields such as entity IDs; the v2\n * write contract accepts only the values that should be frozen onto the bill.\n */\nexport function sanitizeBillReviewSaveInput(\n input: BillReviewSaveInput,\n): BillReviewSaveInput {\n return {\n claimsAdminId: input.claimsAdminId,\n ...(input.formData !== undefined ? { formData: input.formData } : {}),\n ...(input.payerId !== undefined ? { payerId: input.payerId } : {}),\n ...(input.patientOverrides ? {\n patientOverrides: pickDefined(input.patientOverrides, [\n \"firstName\", \"middleName\", \"lastName\", \"dob\",\n ]) as NonNullable<BillReviewSaveInput[\"patientOverrides\"]>,\n } : {}),\n ...(input.injuryOverrides ? {\n injuryOverrides: pickDefined(input.injuryOverrides, [\n \"claimNumber\", \"employer\", \"doi\", \"injuryEndDate\",\n \"cumulativeTrauma\", \"adjNumber\", \"medicalProviderNetworkId\",\n ]) as NonNullable<BillReviewSaveInput[\"injuryOverrides\"]>,\n } : {}),\n dos: input.dos,\n ...(input.dosEnd !== undefined ? { dosEnd: input.dosEnd } : {}),\n ...(input.authorizationNumber !== undefined\n ? { authorizationNumber: input.authorizationNumber }\n : {}),\n ...(input.billingProvider ? {\n billingProvider: pickDefined(input.billingProvider, [\n \"name\", \"taxId\", \"taxIdType\", \"taxIdConfigured\", \"npi\", \"billType\", \"phone\", \"billingStreet\",\n \"billingCity\", \"billingState\", \"billingZip\",\n ]) as BillReviewBillingProvider,\n } : {}),\n ...(input.renderingProvider ? {\n renderingProvider: pickDefined(input.renderingProvider, [\n \"name\", \"specialty\", \"npi\", \"taxonomy\", \"licenseNumber\",\n \"licenseState\", \"signaturePng\", \"signatureKey\", \"isQME\", \"isAME\",\n \"email\", \"active\",\n ]) as BillReviewClinician,\n } : {}),\n ...(input.placeOfService ? {\n placeOfService: pickDefined(input.placeOfService, [\n \"billingProviderId\", \"name\", \"nickname\", \"street\", \"city\", \"state\",\n \"zip\", \"county\", \"posCode\", \"isPrimary\", \"active\",\n ]) as BillReviewLocation,\n } : {}),\n lineItems: input.lineItems.map((line) => pickDefined(line, [\n \"id\", \"code\", \"modifiers\", \"units\", \"charge\", \"serviceDate\",\n \"serviceDateEnd\", \"diagnosisPointers\", \"formData\", \"drug\",\n ]) as BillReviewSaveInput[\"lineItems\"][number]),\n };\n}\n\nexport type BillSubmissionRoute = \"ebill\" | \"fax\" | \"mail\" | \"email\";\nexport type BillDeliveryOption = {\n route: BillSubmissionRoute;\n label: string;\n detail: string;\n fallback: boolean;\n confidence: string;\n payerName: string;\n target?: string;\n chKey?: string;\n payerId?: string;\n printAndMail?: boolean;\n costUsd?: number;\n};\nexport type BillDeliveryOptions = {\n payerName: string;\n recommended: BillDeliveryOption;\n options: BillDeliveryOption[];\n contacts: {\n faxNumber?: string | null;\n claimsEmail?: string | null;\n portalUrl?: string | null;\n mailingAddress?: string | null;\n adjusterName?: string | null;\n adjusterPhone?: string | null;\n adjusterEmail?: string | null;\n };\n};\nexport type BillActorInput = {\n /** Human-readable name shown for user-initiated audit history. */\n actorName?: string;\n};\n\nexport type AddBillNoteInput = BillActorInput & {\n note: string;\n};\n\nexport type SubmitBillInput = BillActorInput & {\n route: BillSubmissionRoute;\n destination?: {\n faxNumber?: string;\n email?: string;\n mailingAddress?: string;\n };\n attention?: string;\n subject?: string;\n note?: string;\n /** CC recipients for the email route (at most 10). */\n cc?: string[];\n};\nexport type BillLifecycleActionId =\n | \"resubmit\"\n | \"second_review\"\n | \"independent_bill_review\"\n | \"view_eor\"\n | \"post_payment\"\n | \"close\"\n | \"reopen\"\n | \"send_duplicate\"\n | \"report_bill_status\"\n | \"submit_new_bill\";\n\nexport type BillLifecycleAction = {\n id: BillLifecycleActionId;\n label: string;\n enabled: boolean;\n primary?: boolean;\n reason?: string;\n};\n\nexport type BillEorDocument = {\n id: string;\n filename: string;\n description: string | null;\n addedAt: string;\n contentUrl: string;\n};\n\nexport type BillActivityRecord = {\n id: string;\n type: string;\n createdAt: string;\n title?: string;\n description: string;\n actor: string | null;\n delivery: BillSubmissionRoute | null;\n amount: number | null;\n accepted: boolean | null;\n stcCategory: string | null;\n};\n\n/** One user-facing bill history row (Date / Action / User / Details).\n * Server-presented: the wording is authored by MindBill so every surface (MindBill\n * app, React, Angular, embeds) reads identically. */\nexport type BillHistoryEntry = {\n id: string;\n /** Immutable bill attempt that produced this event. Present on unified chain history. */\n attemptId?: string;\n /** ISO timestamp for ordering and the Date column. */\n date: string;\n /** Short Action label — \"Original Bill\", \"277 Accept\", \"Payment\", \"Note\", … */\n action: string;\n kind:\n | \"created\"\n | \"submission\"\n | \"ack\"\n | \"eor\"\n | \"payment\"\n | \"review\"\n | \"close\"\n | \"reopen\"\n | \"note\"\n | \"portal\"\n | \"task\"\n | \"system\";\n /** Who acted: a biller name, MindBill automation, or the responding clearinghouse. */\n actor: string | null;\n /** The one-line Details column. */\n summary: string;\n /** Drives row highlighting: submissions are pale blue, notes pale yellow. */\n tone: \"submission\" | \"note\" | \"neutral\" | \"problem\" | \"success\";\n amount?: number;\n /** Expandable content; absent → the row is not expandable. */\n details?: {\n rows?: Array<{ label: string; value: string }>;\n documents?: Array<{ id: string; filename: string }>;\n complianceDueDates?: Array<{ date: string; text: string }>;\n codes?: Array<{ code: string; text: string }>;\n text?: string;\n };\n};\n\n/** One immutable transmission attempt within a logical bill chain. */\nexport type BillAttemptSummary = {\n /** Unique transmission identity. Draft attempts fall back to the bill record ID. */\n id: string;\n /** Underlying bill record. Multiple transmissions may share this value. */\n billId?: string;\n submissionId?: string;\n billNumber?: string | number;\n label: string;\n deliveryLabel?: string;\n sentAt?: string;\n ackLabel?: string;\n ackAt?: string;\n status?: string;\n complianceLabel?: string;\n complianceAt?: string;\n /** Server-resolved payer outcome; no client-side deadline inference. */\n outcomeLabel?: string;\n outcomeAt?: string;\n outcomeDateLabel?: string;\n outcomeWorkingDays?: number;\n /** The latest attempt that receives lifecycle mutations. */\n isCurrent: boolean;\n};\n\nexport type BillPaymentRecord = {\n id: string;\n method: \"check\" | \"eft\";\n checkNumber: string;\n status: string | null;\n depositDate: string | null;\n checkReceived: boolean | null;\n receivedDate: string | null;\n amount: number;\n principalAmount: number;\n feeAmount: number | null;\n feeReason: string | null;\n source: \"paper\" | \"835\" | \"portal\";\n postedAt: string;\n updatedAt: string | null;\n note: string | null;\n};\n\nexport type BillRemittanceSummary = {\n billedAmount: number;\n expectedAmount: number;\n payerAllowedAmount: number | null;\n payerReportedPaid: number | null;\n postedPrincipal: number;\n postedAdditional: number;\n totalPostedCash: number;\n balanceDue: number;\n denialReason: string | null;\n};\n\nexport type BillLifecycleDelivery = {\n payerName: string;\n contacts: BillDeliveryOptions[\"contacts\"];\n /**\n * Partner-safe directory details. `id` is an opaque MindBill directory ID;\n * Values are safe, partner-facing directory details; internal database identifiers are opaque.\n */\n directory?: BillClaimsAdministratorDirectory | null;\n};\n\nexport type BillClaimsAdministratorContact = {\n location?: string | null;\n method?: \"fax\" | \"email\";\n name?: string | null;\n phone?: string | null;\n email?: string | null;\n fax?: string | null;\n portalUrl?: string | null;\n address?: string | null;\n note?: string | null;\n};\n\nexport type BillClaimsAdministratorMailingAddress = {\n company?: string | null;\n address: string;\n notes?: string | null;\n submissionTypes?: string[];\n billTreatmentTypes?: string[];\n};\n\nexport type BillClaimsAdministratorPattern = {\n length?: number | string | null;\n pattern: string;\n example?: string | null;\n matches?: boolean | null;\n};\n\nexport type BillClaimsAdministratorPayer = {\n name: string;\n route?: string | null;\n aliases?: string[];\n hint?: string | null;\n affiliatedEntities?: string[];\n optionType?: string | null;\n deliveryType?: string | null;\n clearinghouse?: string | null;\n payerId?: string | null;\n sourceClearinghouse?: string | null;\n sourcePayerId?: string | null;\n clearinghousePayerIds?: Record<string, string>;\n preferredClearinghouse?: string | null;\n};\n\nexport type BillReviewPayerPage = {\n results: BillReviewPayer[];\n suggestions?: BillReviewPayerSuggestion[];\n total: number;\n nextOffset?: number;\n recommendedId?: string;\n};\n\nexport type BillReviewPayerListInput = {\n query?: string;\n claimNumber?: string;\n sourceClaimsAdministratorName?: string;\n employerName?: string;\n limit?: number;\n offset?: number;\n};\n\nexport type BillClaimsAdministratorAuthorizationStatus = \"central_fax\" | \"central_email\" | \"claim_handling_location_routes\" | \"adjuster_specific_required\" | \"daisybill_unverified\" | \"profile_not_published\";\n\nexport type BillClaimsAdministratorDirectory = {\n authorizationStatus?: BillClaimsAdministratorAuthorizationStatus;\n authorizationSource?: { url: string; observedAt: string };\n id?: string;\n name?: string;\n type?: string | null;\n description?: string | null;\n website?: string | null;\n aliases?: string[];\n affiliatedEntities?: string[];\n hours?: string | null;\n claimNumberHint?: string | null;\n billProcessingWorkflow?: string | null;\n billProcessingWorkflowNotes?: string | null;\n telephoneNumbers?: string[];\n emailAddresses?: string[];\n webPortals?: string[];\n payers?: BillClaimsAdministratorPayer[];\n authorizationNotice?: string | null;\n billReview?: BillClaimsAdministratorContact[];\n authorization?: BillClaimsAdministratorContact[];\n mailingAddresses?: BillClaimsAdministratorMailingAddress[];\n claimNumberPatterns?: BillClaimsAdministratorPattern[];\n};\n\n/** End-user-safe details explaining why the latest submission was rejected. */\nexport type BillRejectionIssue = {\n code?: string | null;\n description: string;\n /** Bill-submission field paths implicated by this issue. */\n fieldPaths?: string[];\n};\n\nexport type BillRejection = {\n reason: string;\n code?: string | null;\n issues?: BillRejectionIssue[];\n receivedAt?: string | null;\n source?: string | null;\n};\n\nexport type BillTeamNote = { id: string; body: string; author: string; createdAt: string; pinned: boolean };\n\nexport type BillCourtesyCopyInput = {\n to: string[];\n cc?: string[];\n subject: string;\n bodyText: string;\n includeCms1500?: boolean;\n documentIds?: string[];\n};\nexport type BillCourtesyCopyPreview = {\n filename: string; documentCount: number; packetHash: string; pdfBase64: string;\n environment: \"sandbox\" | \"live\";\n};\nexport type BillCourtesyCopyResult = { ok: boolean; sent: boolean; simulated?: boolean; dryRun?: boolean; messageId?: string };\n\n/** Historical financial balances are unavailable, not zero. */\nexport type HistoricalBillReviewData = Omit<BillReviewData, \"bill\"> & {\n bill: Omit<BillReviewData[\"bill\"], \"totalPaid\" | \"balanceDue\"> & {\n totalPaid: number | null;\n balanceDue: number | null;\n };\n};\nexport type BillSubmissionDetail = {\n attemptId: string;\n billId: string;\n source: \"submission_snapshot\" | \"bill_record\" | \"unavailable\";\n capturedAt?: string | null;\n detail: HistoricalBillReviewData | null;\n /** Exact retained files for this attempt; never regenerated from current bill values. */\n artifacts?: Array<{ id: string; label: string; kind: \"submitted_attachment\" | \"submitted_edi\"; contentType: string }>;\n};\n\nexport type BillLifecycleData = BillReviewData & {\n environment: \"sandbox\" | \"live\";\n lifecycle: {\n state: string;\n nativeStatus: string;\n submittedAt?: string | null;\n agingDays?: number | null;\n updatedAt?: string | null;\n actions: BillLifecycleAction[];\n };\n eors: BillEorDocument[];\n activity: BillActivityRecord[];\n /** Presented history rows. Optional: absent when the API\n * predates the presented-history rollout — fall back to `activity`. */\n history?: BillHistoryEntry[];\n /** Canonical team notes, shared with the MindBill app. Absent on older APIs. */\n notes?: BillTeamNote[];\n /** Immutable submissions that share this bill's unified history. */\n attempts?: BillAttemptSummary[];\n /** Per-attempt details. Older APIs may omit this; never substitute the current bill. */\n submissionDetails?: BillSubmissionDetail[];\n payments: BillPaymentRecord[];\n remittance: BillRemittanceSummary;\n delivery: BillLifecycleDelivery;\n rejection?: BillRejection | null;\n};\n\nexport type BillLifecycleSession = {\n token: string;\n expiresAt?: string;\n apiBaseUrl?: string;\n};\n\nexport type BillLifecycleSessionRequest = {\n signal: AbortSignal;\n};\n\nexport type BillLifecycleSessionProvider = (\n request: BillLifecycleSessionRequest,\n) => Promise<BillLifecycleSession>;\n\nexport type CloseBillInput = BillActorInput & { reason: string };\nexport type ReopenBillInput = BillActorInput & { reason: string };\nexport type PostBillPaymentInput = BillActorInput & {\n amount: number;\n penaltyAmount?: number;\n interestAmount?: number;\n method: \"check\" | \"eft\";\n checkNumber?: string;\n depositDate: string;\n note?: string;\n};\nexport type SecondReviewLineInput = {\n lineItemId: string;\n reason: string;\n /** SBR-1 box for this service line. Omitted leaves the box blank. */\n serviceAuthorized?: boolean;\n /** Absolute corrected values for this Second Review only; charge is explicitly reviewed, never inferred. */\n correction?: { units: number; modifiers: string[]; charge: number };\n};\n\nexport type SubmitSecondReviewInput = BillActorInput & {\n /** @deprecated Prefer `lineItems[].reason`; retained for older hosts. */\n reason?: string;\n /** @deprecated MindBill derives this from the payer response on the server. */\n payerClaimControlNumber?: string;\n disputedAmount?: number;\n attachmentIds: string[];\n route: BillSubmissionRoute;\n /** New PDFs to include with the Second Review. */\n documents?: BrowserBillSubmissionDocument[];\n destination?: SubmitBillInput[\"destination\"];\n attention?: string;\n subject?: string;\n note?: string;\n cc?: string[];\n /** Line-by-line SBR-1 selections, reasons, and authorization answers. */\n lineItems?: SecondReviewLineInput[];\n /** @deprecated Prefer `lineItems`; omitted = the whole bill. */\n lineItemIds?: string[];\n /** @deprecated Prefer `lineItems[].serviceAuthorized`. */\n serviceAuthorized?: boolean;\n};\n\nexport type ReportBillStatusId =\n | \"message_left\"\n | \"eor_pending\"\n | \"eor_sent\"\n | \"bill_not_on_file\"\n | \"forwarded\";\n\nexport type ReportBillStatusOption = {\n id: ReportBillStatusId;\n label: string;\n description: string;\n};\n\n/** The five supported outcomes of a bill payment-status phone call. */\nexport const REPORT_BILL_STATUS_OPTIONS: ReportBillStatusOption[] = [\n {\n id: \"message_left\",\n label: \"Message Left Requesting Bill Payment Status\",\n description: \"Claims Administrator/Bill Review representative unavailable.\",\n },\n {\n id: \"eor_pending\",\n label: \"Explanation of Review (EOR) Pending\",\n description: \"Claims Administrator/Bill Review reported the bill is still in process and an EOR has not been generated or sent.\",\n },\n {\n id: \"eor_sent\",\n label: \"Explanation of Review (EOR) Sent\",\n description: \"Claims Administrator/Bill Review reported sending an EOR to the provider.\",\n },\n {\n id: \"bill_not_on_file\",\n label: \"Bill Not On File\",\n description: \"Claims Administrator/Bill Review reported not receiving the bill.\",\n },\n {\n id: \"forwarded\",\n label: \"Bill Forwarded to Different Payer / Network\",\n description: \"Claims Administrator/Bill Review reported forwarding the bill to a different payer.\",\n },\n];\n\n/**\n * Outcome of a phone call to the Claims Administrator / Bill Review vendor\n * about an outstanding bill, recorded through the lifecycle actions endpoint.\n */\nexport type ReportBillStatusInput = BillActorInput & {\n status: ReportBillStatusId;\n company?: string;\n representativeName?: string;\n representativeRole?: string;\n phone?: string;\n callReference?: string;\n note?: string;\n};\n\n/**\n * Payload for the \"report_bill_status\" lifecycle action: records the outcome\n * of a phone call to the Claims Administrator / Bill Review vendor about an\n * outstanding bill. Posted through the generic lifecycle actions endpoint.\n */\nexport type ReportBillStatusActionInput = ReportBillStatusInput & {\n action: \"report_bill_status\";\n};\n\n/**\n * Payload for the \"send_duplicate\" lifecycle action. A duplicate is a fresh,\n * editable bill snapshot linked to the submitted original. The original stays\n * immutable; the biller must review the snapshot and explicitly confirm its\n * delivery route before this action is posted.\n */\nexport type SendDuplicateBillInput = ResubmitBillInput;\n\nexport type ReportBillStatusContacts = {\n claimsAdmin: {\n name: string;\n hoursOfOperation?: string;\n phones: Array<{ label: string; value: string }>;\n } | null;\n billReview: { name: string; phone?: string } | null;\n};\n\n/**\n * Partner-safe \"who to call\" summary for the Report Bill Status flow, derived\n * from the lifecycle delivery block (payer contacts + optional directory).\n */\nexport function reportBillStatusContacts(\n delivery: BillLifecycleDelivery,\n): ReportBillStatusContacts {\n const payerName = delivery.payerName?.trim();\n const directory = delivery.directory ?? null;\n const phones: Array<{ label: string; value: string }> = [];\n const adjusterPhone = delivery.contacts.adjusterPhone?.trim();\n if (adjusterPhone) {\n const adjusterName = delivery.contacts.adjusterName?.trim();\n phones.push({\n label: adjusterName ? `Adjuster (${adjusterName})` : \"Adjuster\",\n value: adjusterPhone,\n });\n }\n const hours = directory?.hours?.trim();\n const claimsAdmin = payerName\n ? {\n name: payerName,\n ...(hours ? { hoursOfOperation: hours } : {}),\n phones,\n }\n : null;\n const billReviewContact = (directory?.billReview ?? []).find(\n (contact) => contact.name?.trim() || contact.phone?.trim(),\n );\n const billReview = billReviewContact\n ? {\n name: billReviewContact.name?.trim() || \"Bill Review\",\n ...(billReviewContact.phone?.trim() ? { phone: billReviewContact.phone.trim() } : {}),\n }\n : null;\n return { claimsAdmin, billReview };\n}\n\n/**\n * Default Second Bill Review dispute reason for an invalid med-legal denial.\n * Prefilled (editable) in the SBR panel.\n */\nexport const SECOND_REVIEW_REASON_TEMPLATE =\n \"This is an appeal of the invalid denial of this med-legal bill; per LC §4622 and the OMFS/MLFS, payment is due as billed.\";\n\n/** Days allowed to request Second Review after service of the denial EOR. */\nexport const SECOND_REVIEW_WINDOW_DAYS = 90;\n\nexport type SecondReviewDeadline = {\n /** ISO date (yyyy-mm-dd) of the latest denial/EOR document. */\n eorDate: string;\n /** ISO date (yyyy-mm-dd) 90 days after the EOR date. */\n deadline: string;\n};\n\n/**\n * The 90-day Second Review window anchored on the latest EOR date, or null\n * when the lifecycle data provides no parseable denial/EOR date.\n */\nexport function secondReviewDeadline(\n eors: Array<Pick<BillEorDocument, \"addedAt\">>,\n): SecondReviewDeadline | null {\n const times = eors\n .map((eor) => Date.parse(eor.addedAt))\n .filter((time) => Number.isFinite(time));\n if (!times.length) return null;\n const eorTime = Math.max(...times);\n const isoDate = (time: number): string => new Date(time).toISOString().slice(0, 10);\n return {\n eorDate: isoDate(eorTime),\n deadline: isoDate(eorTime + SECOND_REVIEW_WINDOW_DAYS * 86_400_000),\n };\n}\n/**\n * A corrected immutable snapshot submitted as the next attempt on the same bill.\n * The logical bill ID remains stable; only the submission/control-number attempt advances.\n */\nexport type ResubmitBillInput = BillActorInput & {\n reason?: string;\n bill: BrowserBillCreateInput;\n /** Explicit delivery route confirmed by the biller for this new attempt. */\n submission?: Omit<SubmitBillInput, keyof BillActorInput>;\n documents?: BrowserBillSubmissionDocument[];\n};\n/**\n * \"Submit New Bill\" from a CLOSED bill: the same snapshot payload shape as a\n * resubmission, but the server creates a FRESH original bill linked to the closed\n * predecessor — the closed bill stays closed and keeps its record, and the\n * submissions ribbon/timeline chains both records.\n */\nexport type SubmitNewBillInput = ResubmitBillInput;\nexport type SandboxSimulationScenario = \"accepted\" | \"rejected\" | \"processed\" | \"denied\" | \"partial_payment\" | \"paid\";\nexport type SimulateSandboxBillInput = {\n scenario: SandboxSimulationScenario;\n amount?: number;\n reasonCode?: string;\n};\n\nexport type BrowserBillAddress = {\n line1: string;\n line2?: string;\n city: string;\n state: string;\n postalCode: string;\n};\n\n/** Complete bill snapshot accepted by the browser create endpoint. */\nexport type BrowserBillCreateInput = {\n claimForm?: ClaimForm;\n formData?: BillFormData;\n externalId?: string;\n billingMode?: \"med_legal\" | \"professional\";\n patient: {\n id?: string;\n externalId?: string;\n firstName: string;\n middleName?: string;\n lastName: string;\n dateOfBirth: string;\n ssn?: string;\n gender?: \"M\" | \"F\" | \"X\";\n phone?: string;\n address: BrowserBillAddress;\n };\n claim: {\n id?: string;\n externalId?: string;\n claimNumber: string;\n adjNumber?: string;\n medicalProviderNetworkId?: string | null;\n employer: string;\n dateOfInjury: string;\n injuryState?: string;\n description?: string;\n claimsAdministrator: {\n id: string;\n name: string;\n /** The chosen payer (subpayor) when the claims administrator requires payer selection. */\n payerId?: string;\n };\n };\n service: { date: string; endDate?: string | null; authorizationNumber?: string | null };\n billingProvider: { id?: string; name: string; taxId: string; taxIdType?: \"EIN\" | \"SSN\"; npi: string; phone: string; address: BrowserBillAddress } | { savedProviderId: string } | { sourceBillId: string };\n renderingProvider: {\n name: string;\n specialty?: string;\n npi: string;\n taxonomy: string;\n licenseNumber?: string;\n licenseState?: string;\n isQme?: boolean;\n isAme?: boolean;\n };\n serviceLocation: { name?: string; address: BrowserBillAddress; placeOfServiceCode: string };\n diagnoses: string[];\n serviceLines: Array<{\n formData?: BillLineFormData;\n code: string;\n modifiers?: string[];\n units?: number;\n charge?: number;\n serviceDate?: string;\n serviceDateEnd?: string | null;\n diagnosisPointers?: number[];\n /** Calculation context revalidated by the server before bill creation. */\n feeContext?: BillFeeContext;\n drug?: BilledDrug;\n /** Existing authorized RFA item linked to this service line. */\n rfaItemId?: string;\n }>;\n};\n\n/** Canonical immutable PDF snapshot sent with a bill submission. */\nexport type BrowserBillSubmissionDocument = {\n externalId?: string;\n filename: string;\n description?: string;\n documentType: BillReviewDocumentType;\n /** Opaque PWK report-type code selected by the component (for example OZ:J4). */\n reportTypeCode?: string;\n contentBase64: string;\n};\n\nexport type BrowserBillSubmissionInput = BillActorInput & {\n /** Usually omitted: MindBill stamps the customer from the server-issued session.\n * If supplied, it must match the session customer restriction. */\n customerExternalId?: string;\n bill: BrowserBillCreateInput;\n submission?: {\n route?: BillSubmissionRoute;\n destination?: SubmitBillInput[\"destination\"];\n attention?: string;\n subject?: string;\n note?: string;\n cc?: string[];\n };\n documents?: BrowserBillSubmissionDocument[];\n};\n\nexport type BrowserSubmittedBill = Record<string, unknown> & {\n id: string;\n customerExternalId?: string | null;\n externalId?: string | null;\n state?: string;\n};\n\nexport type BrowserBillSubmissionResult = {\n billId: string;\n bill: BrowserSubmittedBill;\n};\n\nexport type BillLifecycleClientOptions = {\n /** ID of an already-submitted bill. Bills are created only by the atomic server API. */\n billId: string;\n sessionEndpoint?: string | undefined;\n getSession?: BillLifecycleSessionProvider | undefined;\n apiBaseUrl?: string | undefined;\n fetch?: typeof globalThis.fetch | undefined;\n};\n\n/** Browser-session options for pre-submission reference-data lookups. */\nexport type BillReferenceClientOptions = Omit<BillLifecycleClientOptions, \"billId\">;\n\n/** Browser-session options for an atomic immutable bill submission. */\nexport type BillSubmissionClientOptions = BillReferenceClientOptions;\n\nexport type BillSubmissionClient = {\n previewCms1500: (bill: BrowserBillSubmissionInput[\"bill\"]) => Promise<Blob>;\n submitBill: (\n input: BrowserBillSubmissionInput,\n options?: { idempotencyKey?: string },\n ) => Promise<BrowserBillSubmissionResult>;\n clearSession: () => void;\n};\n\n/** Input for the pre-submission delivery preview keyed on a payer-directory id. */\nexport type BillDeliveryPreviewInput = {\n claimsAdministratorId: string;\n /** Selected payer child when the administrator exposes multiple payer routes. */\n payerId?: string;\n /** Two-letter state; defaults to CA server-side. */\n injuryState?: string;\n};\n\nexport type BillProcedureCodeSearchInput = {\n query?: string;\n limit?: number;\n jurisdiction?: \"CA\" | \"NY\" | \"OWCP\";\n};\n\n/** Catalog membership does not imply that a fee is available for a service date. */\nexport type BillProcedureCodePage = {\n results: Array<{ code: string }>;\n total: number;\n limit: number;\n jurisdiction: \"CA\" | \"NY\" | \"OWCP\";\n catalogAsOf: string | null;\n};\n\nexport type BillFeeSource = {\n id: string;\n url: string;\n sha256?: string;\n effectiveFrom: string;\n effectiveThrough: string;\n};\n\n/** Drug identifiers and quantities printed on the professional claim. */\nexport type BilledDrug = {\n ndcNumber: string;\n metricQuantity: string;\n unitOfMeasure: \"UN\" | \"ML\" | \"GR\";\n administered?: {\n drugName: string;\n administeredAmount: string;\n doseUnit: \"mg\" | \"mcg\" | \"g\" | \"mL\" | \"units\";\n hcpcsCode: string;\n amountPerHcpcsUnit: string;\n amountPerNdcUnit: string;\n hcpcsUnitSource: string;\n productLabelSource: string;\n unitDefinitionsVerified: true;\n };\n};\n\n/** Minutes since midnight on the service date; end must follow start. */\nexport type CaAnesthesiaInterval = { startMinute: number; endMinute: number };\n/** Opaque references to the actual physician and service record. */\nexport type CaAnesthesiaEvent = { physicianRef: string; recordRef: string; minute: number };\nexport type CaAnesthesiaParticipation = CaAnesthesiaInterval & { physicianRef: string; recordRef: string };\nexport type CaAnesthesiaOptionalParticipation = CaAnesthesiaParticipation | { applicability: \"not_indicated\"; recordRef: string };\nexport type CaMedicalDirectionCase = {\n caseRef: string;\n anesthetistRole: \"crna\" | \"anesthesiologist_assistant\" | \"intern\" | \"resident\" | \"student_nurse_anesthetist\";\n qualificationRecordRef: string;\n procedure: \"cataract\" | \"iridectomy\" | \"other\";\n interval: CaAnesthesiaInterval;\n activities: {\n preAnestheticEvaluation: CaAnesthesiaEvent;\n prescribedPlan: CaAnesthesiaEvent;\n demandingProcedures: CaAnesthesiaParticipation[];\n induction: CaAnesthesiaOptionalParticipation;\n emergence: CaAnesthesiaOptionalParticipation;\n qualifiedAnesthetistProcedures: CaAnesthesiaEvent;\n frequentMonitoring: { recordRef: string; observations: CaAnesthesiaEvent[] };\n indicatedPostAnesthesiaCare: CaAnesthesiaEvent;\n };\n};\n/** All overlapping cases across all payers, including cases outside this bill. */\nexport type CaMedicalDirection = {\n physicianRef: string;\n groupPhysicianRefs: string[];\n billedCaseRef: string;\n rosterScope: \"all_overlapping_cases_all_payers\";\n rosterRecordRef: string;\n cases: CaMedicalDirectionCase[];\n physicalPresenceAndImmediateAvailability: CaAnesthesiaParticipation[];\n otherPatientServices: Array<{\n kind: \"emergency\" | \"labor_analgesia\" | \"obstetric_monitoring\" | \"receiving_patient\" | \"recovery_care\" | \"other\";\n interval: CaAnesthesiaInterval;\n recordRef: string;\n }>;\n};\nexport type CaMonitoredAnesthesiaCare = {\n medicallyNecessary: true;\n intraoperativePhysiologicalMonitoring: true;\n preparedForGeneralAnesthesiaOrAdverseReaction: true;\n perioperativeAnesthesiaCare: true;\n underlyingProcedureProvider: \"different_provider\" | \"same_provider\";\n underlyingProcedure: \"nerve_block_or_injection\" | \"other\";\n};\n/** Clinical facts supplement AA or QK; monitored care also requires QS. */\nexport type CaAnesthesiaContext = {\n providerKind: \"physician\";\n actualMinutes: number;\n placeOfService: string;\n completeSameDayServices: true;\n otherSameDayServices: boolean;\n codingRequirementsSatisfied: true;\n monitoredCare?: CaMonitoredAnesthesiaCare;\n} & ({ personallyPerformedAlone: true; medicalDirection?: never } | { personallyPerformedAlone: false; medicalDirection: CaMedicalDirection });\n\nexport type CaPadbContext = {\n providerKind: \"physician\";\n placeOfService: \"11\";\n productKind: \"injectable\";\n bundledOrPackaged: false;\n codingRequirementsSatisfied: true;\n completeSameDayServices: true;\n sameDayServices: Array<{ code: string; units: number }>;\n};\n\nexport type CaTherapyContext = {\n providerKind?: \"physical_therapist\" | \"other\";\n personallyPerformed?: boolean;\n hospitalPatient?: boolean;\n incidentToPhysicianService?: boolean;\n assistantInvolved?: boolean;\n placeOfService?: string;\n /** Whether an initial evaluation already occurred in this care episode, including prior dates. Omit when unknown. */\n priorInitialEvaluationInEpisode?: boolean;\n /** Required for timed treatment; initial evaluations are untimed. */\n directOneOnOneMinutes?: number;\n totalVisitMinutes?: number;\n visitsOnDate?: number;\n completeSameDayServices?: boolean;\n otherSameDayServices?: boolean;\n globalPeriodApplies?: boolean;\n hpsaBonusEligible?: boolean;\n };\n\n/** Actual technical imaging facts. All fields are required when this context is supplied. */\nexport type CaTechnicalComponentContext = {\n /** Whether the billing provider or group furnished the service; purchased or outsourced services require review. */\n performedByBillingProviderGroup: boolean;\n patientHospitalStatus: \"not_hospital_patient\" | \"hospital_inpatient_or_outpatient\";\n supervisionLevel: \"general\" | \"direct\" | \"personal\";\n /** Actual session label, 1–64 letters/digits/._:-, beginning with a letter or digit. Never a patient identifier. */\n imagingSessionReference: string;\n /** All imaging for this patient/provider group/date is included, including separately billed services. */\n completeSameDayImagingServices: boolean;\n};\n\n/** Documented interpretation and imaging-session facts; an omitted completeness fact remains unknown. */\nexport type CaProfessionalComponentContext = {\n interpretationLocation: \"same_as_patient_service\" | \"different_from_patient_service\";\n supervisionLevel?: \"general\" | \"direct\" | \"personal\";\n /** Actual session label, 1–64 letters/digits/._:-, beginning with a letter or digit. Never a patient identifier. */\n imagingSessionReference?: string;\n /** All imaging for this patient/provider group/date is included, including separately billed services. */\n completeSameDayImagingServices?: boolean;\n};\n\nexport type BillFeeQuoteInput = {\n drug?: BilledDrug;\n padbContext?: CaPadbContext;\n anesthesiaContext?: CaAnesthesiaContext;\n billingProviderId?: string;\n payerId?: string;\n code: string;\n dateOfService: string;\n chargeCents?: number;\n units?: number;\n modifiers?: string[];\n pages?: number;\n reportKind?: \"progress\" | \"permanent_stationary_pr3\" | \"permanent_stationary_pr4\";\n hasFeeAgreement?: boolean;\n serviceZip?: string;\n /** Explicit physical interpretation location for a professional component. */\n professionalComponentContext?: CaProfessionalComponentContext;\n technicalComponentContext?: CaTechnicalComponentContext;\n /** California equipment pricing uses worker residence, independently of service location. */\n dmeposContext?: {\n residenceZip: string;\n /** Continuous rental month for this equipment item; only for applicable RR lines. */\n rentalMonth?: number;\n /** Actual prior payments for this item, including rentals; explicit zero means no prior payments. */\n priorPaymentsCents?: number;\n };\n /** Supply verified service facts; omitted context can require review. */\n physicianContext?: {\n providerKind: \"physician\" | \"physician_assistant\" | \"nurse_practitioner\" | \"clinical_nurse_specialist\" | \"other\";\n incidentToPhysicianService?: boolean;\n placeOfService: string;\n standaloneService: boolean;\n globalPeriodApplies: boolean;\n hpsaBonusEligible: boolean;\n };\n therapyContext?: CaTherapyContext;\n catalogContext?: {\n codingRequirementsSatisfied: boolean;\n statusIAlternative?: \"none\" | \"cpt\" | \"drug\";\n completeSurgicalPackage?: boolean;\n };\n prolongedServiceContext?: {\n totalMinutes: number;\n relatedEvaluationDate: string;\n ongoingPatientManagement: boolean;\n personallyPerformed: boolean;\n timeCountedInOtherServices: boolean;\n completeSameDayServices: boolean;\n sameDayServices: Array<{ code: string; units: number }>;\n };\n reportQualification?:\n | { kind: \"psychiatric_report\"; requestedBy: \"wcab\" | \"administrative_director\"; medicalLegalEvaluation: boolean; reportPayableUnderMedicalLegalSchedule: boolean }\n | { kind: \"consultation_report\"; requestedBy: \"wcab\" | \"administrative_director\" | \"qme\" | \"ame\"; medicalLegalEvaluation: boolean; reportPayableUnderMedicalLegalSchedule: boolean }\n | { kind: \"chart_notes\"; requestedBy: \"claims_administrator\"; writtenRequest: boolean }\n | { kind: \"duplicate_report\"; requestedBy: \"claims_administrator\"; writtenRequest: boolean; relatedToBilling: boolean; initialRequiredCopy: boolean };\n};\n\n/** Authoritative service, provider, payer and location fields come from the submitted bill. */\nexport type BillFeeContext = Omit<BillFeeQuoteInput, \"code\" | \"dateOfService\" | \"units\" | \"modifiers\" | \"chargeCents\" | \"billingProviderId\" | \"payerId\" | \"serviceZip\" | \"drug\">;\n\n/** Fee families returned by the California and practice-contract quote endpoint. */\nexport const BILL_FEE_QUOTE_BASES = [\n \"ca_report\", \"ca_physician_rbrvs\", \"ca_therapy_rbrvs\", \"ca_clfs\",\n \"ca_simple_dispensed_drug\", \"ca_dmepos\", \"ca_padb\", \"ca_anesthesia\", \"payer_contract\",\n] as const;\nexport type BillFeeQuoteBasis = typeof BILL_FEE_QUOTE_BASES[number];\n\nexport type BillFeeQuote =\n | {\n status: \"priced\";\n /** Total for the service line in cents, already accounting for units. */\n amountCents: number;\n scheduleMaximumCents: number;\n basis: BillFeeQuoteBasis;\n anesthesia?: { actualMinutes: number; baseUnits: number; timeUnitsTenths: number; conversionFactorCents: number; locality: string; medicalDirection?: { concurrentCases: number; baseReductionPercent: number; physicianPaymentPercent: 50 } };\n provenance: BillFeeSource[];\n notes: string[];\n }\n | { status: \"requires_review\" | \"not_separately_payable\"; reason: string; provenance: BillFeeSource[] };\n\n/** Public DWC directory record. Only Approved records are selectable. */\nexport type MedicalProviderNetwork = {\n id: string;\n name: string;\n applicantName: string;\n applicantType?: string;\n status: \"Approved\" | \"Terminated\" | \"Withdrawn\";\n approvalDate?: string | null;\n website?: string | null;\n};\n\nexport type BillReferenceClient = {\n listMedicalProviderNetworks: () => Promise<MedicalProviderNetwork[]>;\n listClaimsAdministrators: (input?: BillReviewPayerListInput) => Promise<BillReviewPayerPage>;\n searchClaimsAdministrators: (query: string, claimNumber?: string) => Promise<BillReviewPayer[]>;\n getClaimsAdministratorDirectory: (id: string, injuryState?: string) => Promise<BillClaimsAdministratorDirectory>;\n searchDiagnosisCodes: (query: string, limit?: number, offset?: number) => Promise<BillDiagnosisCode[]>;\n searchProcedureCodes: (input?: BillProcedureCodeSearchInput) => Promise<BillProcedureCodePage>;\n quoteFee: (input: BillFeeQuoteInput) => Promise<BillFeeQuote>;\n quoteClaimFees: (input: CaClaimFeeQuoteInput) => Promise<CaClaimFeeQuoteResult>;\n lookupPostalCode: (postalCode: string) => Promise<BillPostalPlace | null>;\n /**\n * Delivery-route preview (recommended route + selectable options + payer\n * contacts) for a claims administrator BEFORE the bill exists — powers the\n * send-route picker shown at submit time.\n */\n getDeliveryPreview: (input: BillDeliveryPreviewInput) => Promise<BillDeliveryOptions>;\n clearSession: () => void;\n};\n\nexport type BillLifecycleClient = {\n getBillId: () => string;\n getLifecycle: (signal?: AbortSignal) => Promise<BillLifecycleData>;\n listMedicalProviderNetworks: () => Promise<MedicalProviderNetwork[]>;\n listClaimsAdministrators: (input?: BillReviewPayerListInput) => Promise<BillReviewPayerPage>;\n searchClaimsAdministrators: (query: string, claimNumber?: string) => Promise<BillReviewPayer[]>;\n getClaimsAdministratorDirectory: (id: string, injuryState?: string) => Promise<BillClaimsAdministratorDirectory>;\n searchDiagnosisCodes: (query: string, limit?: number, offset?: number) => Promise<BillDiagnosisCode[]>;\n searchProcedureCodes: (input?: BillProcedureCodeSearchInput) => Promise<BillProcedureCodePage>;\n quoteFee: (input: BillFeeQuoteInput) => Promise<BillFeeQuote>;\n quoteClaimFees: (input: CaClaimFeeQuoteInput) => Promise<CaClaimFeeQuoteResult>;\n lookupPostalCode: (postalCode: string) => Promise<BillPostalPlace | null>;\n getDeliveryOptions: () => Promise<BillDeliveryOptions>;\n getDeliveryPreview: (input: BillDeliveryPreviewInput) => Promise<BillDeliveryOptions>;\n getAttachment: (attachmentId: string) => Promise<Blob>;\n getEor: (documentId: string) => Promise<Blob>;\n getPacket: () => Promise<Blob>;\n getSubmissionArtifact: (attemptId: string, artifactId: string) => Promise<Blob>;\n /** Prepare a self-filing packet. Does not file IBR or send anything to a payer. */\n prepareIbrPacket: () => Promise<Blob>;\n previewCourtesyCopy: (input: BillCourtesyCopyInput) => Promise<BillCourtesyCopyPreview>;\n /** Reuse the same key when retrying the same send after a network interruption. */\n sendCourtesyCopy: (input: BillCourtesyCopyInput & { packetHash: string }, idempotencyKey: string) => Promise<BillCourtesyCopyResult>;\n addNote: (input: AddBillNoteInput) => Promise<BillLifecycleData>;\n closeBill: (input: CloseBillInput) => Promise<BillLifecycleData>;\n reopenBill: (input: ReopenBillInput) => Promise<BillLifecycleData>;\n postPayment: (input: PostBillPaymentInput) => Promise<BillLifecycleData>;\n submitSecondReview: (input: SubmitSecondReviewInput) => Promise<BillLifecycleData>;\n resubmitBill: (input: ResubmitBillInput) => Promise<BillLifecycleData>;\n submitNewBill: (input: SubmitNewBillInput) => Promise<BillLifecycleData>;\n sendDuplicateBill: (input: SendDuplicateBillInput) => Promise<BillLifecycleData>;\n reportBillStatus: (input: ReportBillStatusInput) => Promise<BillLifecycleData>;\n simulateSandbox: (input: SimulateSandboxBillInput) => Promise<BillLifecycleData>;\n clearSession: () => void;\n};\n\nasync function responseError(response: Response, fallback: string): Promise<Error> {\n const body: unknown = await response.json().catch(() => null);\n const detail = body && typeof body === \"object\"\n ? (body as { detail?: unknown; message?: unknown; error?: unknown }).detail\n ?? (body as { message?: unknown }).message\n ?? (body as { error?: unknown }).error\n : null;\n return new Error(typeof detail === \"string\" ? detail : fallback);\n}\n\nfunction isSessionFresh(session: BillLifecycleSession | null): boolean {\n if (!session) return false;\n if (!session.expiresAt) return true;\n const expiresAt = new Date(session.expiresAt).getTime();\n return Number.isFinite(expiresAt) && expiresAt > Date.now() + 30_000;\n}\n\nfunction normalizeSession(value: unknown): BillLifecycleSession {\n if (!value || typeof value !== \"object\") {\n throw new Error(\"The billing session endpoint returned an invalid response.\");\n }\n const candidate = value as { token?: unknown; expiresAt?: unknown; apiBaseUrl?: unknown; session?: unknown; data?: unknown };\n const nested = candidate.session ?? candidate.data;\n const session = nested && typeof nested === \"object\" ? nested as typeof candidate : candidate;\n if (typeof session.token !== \"string\" || session.token.length < 8) {\n throw new Error(\"The billing session endpoint did not return a browser session token.\");\n }\n return {\n token: session.token,\n ...(typeof session.expiresAt === \"string\" ? { expiresAt: session.expiresAt } : {}),\n ...(typeof session.apiBaseUrl === \"string\" ? { apiBaseUrl: session.apiBaseUrl } : {}),\n };\n}\n\nfunction normalizeLifecycle(value: unknown): BillLifecycleData {\n if (!value || typeof value !== \"object\") {\n throw new Error(\"The billing service returned an invalid bill lifecycle.\");\n }\n const data = value as Partial<BillLifecycleData>;\n if (\n ![\"sandbox\", \"live\"].includes(data.environment ?? \"\")\n || !data.bill\n || !data.patient\n || !data.injury\n || !data.lifecycle\n || !Array.isArray(data.lifecycle.actions)\n || !Array.isArray(data.eors)\n || !Array.isArray(data.activity)\n || !Array.isArray(data.payments)\n || !data.remittance\n || typeof data.remittance !== \"object\"\n || !data.delivery\n || typeof data.delivery !== \"object\"\n || !data.delivery.contacts\n || typeof data.delivery.contacts !== \"object\"\n || (data.rejection != null && (\n typeof data.rejection !== \"object\"\n || typeof data.rejection.reason !== \"string\"\n || (data.rejection.issues != null && (\n !Array.isArray(data.rejection.issues)\n || data.rejection.issues.some((issue) => (\n !issue\n || typeof issue !== \"object\"\n || typeof issue.description !== \"string\"\n || (issue.code != null && typeof issue.code !== \"string\")\n ))\n ))\n ))\n ) {\n throw new Error(\"The billing service returned an invalid bill lifecycle.\");\n }\n return data as BillLifecycleData;\n}\n\nfunction normalizeDeliveryOptions(value: unknown): BillDeliveryOptions {\n if (!value || typeof value !== \"object\") {\n throw new Error(\"The billing service returned invalid delivery options.\");\n }\n const data = value as Partial<BillDeliveryOptions>;\n if (\n typeof data.payerName !== \"string\"\n || !data.recommended\n || typeof data.recommended !== \"object\"\n || ![\"ebill\", \"fax\", \"mail\", \"email\"].includes(data.recommended.route ?? \"\")\n || !Array.isArray(data.options)\n || !data.contacts\n ) {\n throw new Error(\"The billing service returned invalid delivery options.\");\n }\n return data as BillDeliveryOptions;\n}\n\nfunction idempotencyKey(): string {\n if (typeof globalThis.crypto?.randomUUID === \"function\") return globalThis.crypto.randomUUID();\n return `mb-${Date.now()}-${Math.random().toString(36).slice(2)}`;\n}\n\n/**\n * Browser-safe client for one atomic create-and-submit operation.\n *\n * The browser session is short-lived and origin-bound. The host application\n * never needs the Partner API document schema or a long-lived API key.\n */\nexport function createBillSubmissionClient({\n sessionEndpoint = DEFAULT_SESSION_ENDPOINT,\n getSession,\n apiBaseUrl = DEFAULT_API_BASE_URL,\n fetch: fetchOverride,\n}: BillSubmissionClientOptions = {}): BillSubmissionClient {\n const fetcher = fetchOverride ?? globalThis.fetch;\n if (typeof fetcher !== \"function\") throw new Error(\"A Fetch API implementation is required.\");\n let session: BillLifecycleSession | null = null;\n let sessionRequest: Promise<BillLifecycleSession> | null = null;\n\n const mintSession = async (signal: AbortSignal, force = false): Promise<BillLifecycleSession> => {\n if (!force && isSessionFresh(session)) return session as BillLifecycleSession;\n if (!force && sessionRequest) return sessionRequest;\n const pending = getSession\n ? getSession({ signal })\n : fetcher(sessionEndpoint, {\n method: \"POST\",\n credentials: \"same-origin\",\n headers: { \"content-type\": \"application/json\" },\n body: JSON.stringify({}),\n signal,\n }).then(async (response) => {\n if (!response.ok) throw await responseError(response, \"The billing session could not be created.\");\n return response.json();\n });\n const request = Promise.resolve(pending).then(normalizeSession).then((nextSession) => {\n session = nextSession;\n return nextSession;\n }).finally(() => {\n if (sessionRequest === request) sessionRequest = null;\n });\n sessionRequest = request;\n return request;\n };\n\n const submitBill = async (\n input: BrowserBillSubmissionInput,\n options: { idempotencyKey?: string } = {},\n ): Promise<BrowserBillSubmissionResult> => {\n const controller = new AbortController();\n const requestIdempotencyKey = options.idempotencyKey ?? idempotencyKey();\n let browserSession = await mintSession(controller.signal);\n const perform = (current: BillLifecycleSession) => {\n const base = (current.apiBaseUrl ?? apiBaseUrl).replace(/\\/$/, \"\");\n return fetcher(`${base}/partner/v2/bills`, {\n method: \"POST\",\n headers: {\n authorization: `Bearer ${current.token}`,\n \"content-type\": \"application/json\",\n \"idempotency-key\": requestIdempotencyKey,\n },\n body: JSON.stringify(input),\n signal: controller.signal,\n });\n };\n let response = await perform(browserSession);\n if (response.status === 401) {\n session = null;\n browserSession = await mintSession(controller.signal, true);\n response = await perform(browserSession);\n }\n if (!response.ok) throw await responseError(response, \"The bill could not be submitted.\");\n const body: unknown = await response.json().catch(() => null);\n const envelope = body && typeof body === \"object\" && \"data\" in body\n ? (body as { data?: unknown }).data\n : body;\n if (!envelope || typeof envelope !== \"object\" || typeof (envelope as { id?: unknown }).id !== \"string\") {\n throw new Error(\"The billing service submitted the bill but returned an invalid bill ID.\");\n }\n const bill = envelope as BrowserSubmittedBill;\n return { billId: bill.id, bill };\n };\n\n const previewCms1500 = async (bill: BrowserBillSubmissionInput[\"bill\"]): Promise<Blob> => {\n const controller = new AbortController();\n let browserSession = await mintSession(controller.signal);\n const perform = (current: BillLifecycleSession) => {\n const base = (current.apiBaseUrl ?? apiBaseUrl).replace(/\\/$/, \"\");\n return fetcher(`${base}/partner/v2/bills/preview-cms1500`, {\n method: \"POST\",\n headers: {\n authorization: `Bearer ${current.token}`,\n \"content-type\": \"application/json\",\n },\n body: JSON.stringify(bill),\n signal: controller.signal,\n });\n };\n let response = await perform(browserSession);\n if (response.status === 401) {\n session = null;\n browserSession = await mintSession(controller.signal, true);\n response = await perform(browserSession);\n }\n if (!response.ok) throw await responseError(response, \"The CMS-1500 preview could not be generated.\");\n if (!response.headers.get(\"content-type\")?.includes(\"application/pdf\")) {\n throw new Error(\"The billing service returned an invalid CMS-1500 preview.\");\n }\n return response.blob();\n };\n\n return {\n previewCms1500,\n submitBill,\n clearSession() { session = null; sessionRequest = null; },\n };\n}\n\n/** Browser-safe, framework-neutral client for an already-submitted bill. */\nexport function createBillLifecycleClient({\n billId,\n sessionEndpoint = DEFAULT_SESSION_ENDPOINT,\n getSession,\n apiBaseUrl = DEFAULT_API_BASE_URL,\n fetch: fetchOverride,\n}: BillLifecycleClientOptions): BillLifecycleClient {\n const fetcher = fetchOverride ?? globalThis.fetch;\n if (typeof fetcher !== \"function\") throw new Error(\"A Fetch API implementation is required.\");\n let session: BillLifecycleSession | null = null;\n let sessionRequest: Promise<BillLifecycleSession> | null = null;\n const currentBillId = billId.trim();\n if (!currentBillId) throw new Error(\"billId is required for the submitted-bill lifecycle client.\");\n\n const mintSession = async (signal: AbortSignal, force = false): Promise<BillLifecycleSession> => {\n if (!force && isSessionFresh(session)) return session as BillLifecycleSession;\n if (!force && sessionRequest) return sessionRequest;\n const pending = getSession\n ? getSession({ signal })\n : fetcher(sessionEndpoint, {\n method: \"POST\",\n credentials: \"same-origin\",\n headers: { \"content-type\": \"application/json\" },\n body: JSON.stringify({}),\n signal,\n }).then(async (response) => {\n if (!response.ok) throw await responseError(response, \"The billing session could not be created.\");\n return response.json();\n });\n const request = Promise.resolve(pending).then(normalizeSession).then((nextSession) => {\n session = nextSession;\n return nextSession;\n }).finally(() => {\n if (sessionRequest === request) sessionRequest = null;\n });\n sessionRequest = request;\n return request;\n };\n\n const request = async (path: string, init: RequestInit = {}, providedSignal?: AbortSignal): Promise<Response> => {\n const controller = providedSignal ? null : new AbortController();\n const signal = providedSignal ?? controller?.signal;\n if (!signal) throw new Error(\"An AbortSignal could not be created.\");\n let browserSession = await mintSession(signal);\n const perform = (current: BillLifecycleSession) => {\n const base = (current.apiBaseUrl ?? apiBaseUrl).replace(/\\/$/, \"\");\n const headers = new Headers(init.headers);\n headers.set(\"authorization\", `Bearer ${current.token}`);\n return fetcher(`${base}${path}`, { ...init, headers, signal });\n };\n let response = await perform(browserSession);\n if (response.status === 401) {\n session = null;\n browserSession = await mintSession(signal, true);\n response = await perform(browserSession);\n }\n return response;\n };\n\n const billPath = (suffix = \"\"): string =>\n `/partner/v2/bills/${encodeURIComponent(currentBillId)}${suffix}`;\n\n const loadLifecycle = async (signal?: AbortSignal) => {\n const response = await request(billPath(\"/lifecycle\"), {}, signal);\n if (!response.ok) throw await responseError(response, \"Bill lifecycle could not be loaded.\");\n const body = await response.json() as { data?: unknown };\n return normalizeLifecycle(body.data);\n };\n\n const listMedicalProviderNetworks = async (): Promise<MedicalProviderNetwork[]> => {\n const response = await request(\"/partner/v2/medical-provider-networks\");\n if (!response.ok) throw await responseError(response, \"Medical provider networks could not be loaded.\");\n const body = await response.json() as { data?: unknown };\n if (!Array.isArray(body.data)) throw new Error(\"Medical provider networks returned an invalid response.\");\n return body.data.flatMap((value): MedicalProviderNetwork[] => {\n if (!value || typeof value !== \"object\") return [];\n const row = value as Record<string, unknown>;\n if (row.status !== \"Approved\" || typeof row.id !== \"string\" || typeof row.name !== \"string\" || typeof row.applicantName !== \"string\") return [];\n return [{ id: row.id, name: row.name, applicantName: row.applicantName, status: \"Approved\",\n ...(typeof row.applicantType === \"string\" ? { applicantType: row.applicantType } : {}),\n ...(typeof row.approvalDate === \"string\" ? { approvalDate: row.approvalDate } : {}),\n ...(typeof row.website === \"string\" ? { website: row.website } : {}),\n }];\n });\n };\n\n const listClaimsAdministrators = async (input: BillReviewPayerListInput = {}): Promise<BillReviewPayerPage> => {\n const params = new URLSearchParams();\n if (input.query?.trim()) params.set(\"q\", input.query.trim());\n if (input.claimNumber?.trim()) params.set(\"claimNumber\", input.claimNumber.trim());\n if (input.sourceClaimsAdministratorName?.trim()) params.set(\"sourceClaimsAdministratorName\", input.sourceClaimsAdministratorName.trim());\n if (input.employerName?.trim()) params.set(\"employerName\", input.employerName.trim());\n const limit = Math.max(1, Math.min(100, Math.floor(input.limit ?? 50)));\n const offset = Math.max(0, Math.floor(input.offset ?? 0));\n params.set(\"limit\", String(limit));\n if (offset) params.set(\"offset\", String(offset));\n const response = await request(`/partner/v2/claims-administrators?${params.toString()}`);\n if (!response.ok) throw await responseError(response, \"Claims administrator search is unavailable.\");\n const body = await response.json() as { results?: unknown; suggestions?: unknown; total?: unknown; nextOffset?: unknown; recommendedId?: unknown };\n if (!Array.isArray(body.results)) throw new Error(\"Claims administrator search returned an invalid response.\");\n const normalizePayer = (value: unknown): BillReviewPayer | null => {\n if (!value || typeof value !== \"object\") return null;\n const payer = value as Record<string, unknown>;\n if (typeof payer.id !== \"string\" || typeof payer.name !== \"string\") return null;\n const payers = Array.isArray(payer.payers) ? payer.payers.flatMap((option): BillReviewPayerOption[] => {\n if (!option || typeof option !== \"object\") return [];\n const candidate = option as Record<string, unknown>;\n const id = typeof candidate.id === \"string\" ? candidate.id : typeof candidate.key === \"string\" ? candidate.key : null;\n if (!id || typeof candidate.label !== \"string\") return [];\n return [{\n id,\n label: candidate.label,\n ...(typeof candidate.default === \"boolean\" ? { default: candidate.default } : {}),\n ...(typeof candidate.active === \"boolean\" ? { active: candidate.active } : {}),\n ...(Array.isArray(candidate.aliases) ? { aliases: candidate.aliases.filter((item): item is string => typeof item === \"string\") } : {}),\n ...(typeof candidate.hint === \"string\" ? { hint: candidate.hint } : {}),\n ...(Array.isArray(candidate.affiliatedEntities) ? { affiliatedEntities: candidate.affiliatedEntities.filter((item): item is string => typeof item === \"string\") } : {}),\n ...(typeof candidate.route === \"string\" ? { route: candidate.route } : {}),\n ...(typeof candidate.optionType === \"string\" ? { optionType: candidate.optionType } : {}),\n ...(typeof candidate.deliveryType === \"string\" ? { deliveryType: candidate.deliveryType } : {}),\n ...(typeof candidate.clearinghouse === \"string\" ? { clearinghouse: candidate.clearinghouse } : {}),\n ...(typeof candidate.payerId === \"string\" ? { payerId: candidate.payerId } : {}),\n ...(typeof candidate.sourceClearinghouse === \"string\" ? { sourceClearinghouse: candidate.sourceClearinghouse } : {}),\n ...(typeof candidate.sourcePayerId === \"string\" ? { sourcePayerId: candidate.sourcePayerId } : {}),\n ...(candidate.clearinghousePayerIds && typeof candidate.clearinghousePayerIds === \"object\" && !Array.isArray(candidate.clearinghousePayerIds)\n ? { clearinghousePayerIds: Object.fromEntries(Object.entries(candidate.clearinghousePayerIds).filter((entry): entry is [string, string] => typeof entry[1] === \"string\")) }\n : {}),\n ...(typeof candidate.preferredClearinghouse === \"string\" ? { preferredClearinghouse: candidate.preferredClearinghouse } : {}),\n }];\n }) : undefined;\n const claimNumberPatterns = Array.isArray(payer.claimNumberPatterns) ? payer.claimNumberPatterns.flatMap((value): BillClaimsAdministratorPattern[] => {\n if (!value || typeof value !== \"object\") return [];\n const pattern = value as Record<string, unknown>;\n if (typeof pattern.pattern !== \"string\") return [];\n return [{\n pattern: pattern.pattern,\n ...(typeof pattern.length === \"string\" || typeof pattern.length === \"number\" ? { length: pattern.length } : {}),\n ...(typeof pattern.example === \"string\" ? { example: pattern.example } : {}),\n ...(typeof pattern.matches === \"boolean\" || pattern.matches === null ? { matches: pattern.matches as boolean | null } : {}),\n }];\n }) : undefined;\n return {\n id: payer.id,\n name: payer.name,\n ...(typeof payer.hasElectronic === \"boolean\" ? { hasElectronic: payer.hasElectronic } : {}),\n ...(Array.isArray(payer.states) ? { states: payer.states.filter((state): state is string => typeof state === \"string\") } : {}),\n ...([\"high\", \"medium\", \"directory\"].includes(String(payer.confidence)) ? { confidence: payer.confidence as NonNullable<BillReviewPayer[\"confidence\"]> } : {}),\n ...(typeof payer.recommended === \"boolean\" ? { recommended: payer.recommended } : {}),\n ...(typeof payer.payerSelectionRequired === \"boolean\" ? { payerSelectionRequired: payer.payerSelectionRequired } : {}),\n ...(payers ? { payers } : {}),\n ...(Array.isArray(payer.aliases) ? { aliases: payer.aliases.filter((item): item is string => typeof item === \"string\") } : {}),\n ...(Array.isArray(payer.affiliatedEntities) ? { affiliatedEntities: payer.affiliatedEntities.filter((item): item is string => typeof item === \"string\") } : {}),\n ...(typeof payer.claimNumberHint === \"string\" ? { claimNumberHint: payer.claimNumberHint } : {}),\n ...(claimNumberPatterns ? { claimNumberPatterns } : {}),\n ...(typeof payer.route === \"string\" ? { route: payer.route } : {}),\n ...(Array.isArray(payer.signals) ? { signals: payer.signals.flatMap((signal) => {\n if (!signal || typeof signal !== \"object\") return [];\n const candidate = signal as Record<string, unknown>;\n if (![\"name\", \"claim_number\"].includes(String(candidate.kind)) || ![\"match\", \"warning\"].includes(String(candidate.state)) || typeof candidate.label !== \"string\") return [];\n return [{ kind: candidate.kind as \"name\" | \"claim_number\", state: candidate.state as \"match\" | \"warning\", label: candidate.label }];\n }) } : {}),\n };\n };\n const results = body.results.flatMap((value): BillReviewPayer[] => {\n const payer = normalizePayer(value);\n return payer ? [payer] : [];\n });\n const suggestions = Array.isArray(body.suggestions) ? body.suggestions.flatMap((value): BillReviewPayerSuggestion[] => {\n const payer = normalizePayer(value);\n if (!payer || !value || typeof value !== \"object\") return [];\n const suggestion = value as Record<string, unknown>;\n if (typeof suggestion.deterministic !== \"boolean\" || typeof suggestion.reason !== \"string\") return [];\n return [{ ...payer, deterministic: suggestion.deterministic, reason: suggestion.reason, ...(typeof suggestion.selectedPayerId === \"string\" ? { selectedPayerId: suggestion.selectedPayerId } : {}) }];\n }) : [];\n const total = typeof body.total === \"number\" && Number.isFinite(body.total) ? Math.max(results.length, Math.floor(body.total)) : offset + results.length;\n return {\n results,\n ...(suggestions.length ? { suggestions } : {}),\n total,\n ...(typeof body.nextOffset === \"number\" && Number.isFinite(body.nextOffset) ? { nextOffset: Math.floor(body.nextOffset) } : {}),\n ...(typeof body.recommendedId === \"string\" ? { recommendedId: body.recommendedId } : {}),\n };\n };\n\n const searchClaimsAdministrators = async (query: string, claimNumber?: string): Promise<BillReviewPayer[]> =>\n (await listClaimsAdministrators({ query, ...(claimNumber ? { claimNumber } : {}) })).results;\n\n const getClaimsAdministratorDirectory = async (id: string, injuryState?: string): Promise<BillClaimsAdministratorDirectory> => {\n const params = new URLSearchParams();\n if (injuryState?.trim()) params.set(\"injuryState\", injuryState.trim());\n const response = await request(`/partner/v2/claims-administrators/${encodeURIComponent(id)}${params.size ? `?${params}` : \"\"}`);\n if (!response.ok) throw await responseError(response, \"Claims administrator details are unavailable.\");\n const body = await response.json() as { data?: unknown };\n if (!body.data || typeof body.data !== \"object\") throw new Error(\"Claims administrator details returned an invalid response.\");\n return body.data as BillClaimsAdministratorDirectory;\n };\n\n const searchDiagnosisCodes = async (query: string, limit = 30, offset = 0): Promise<BillDiagnosisCode[]> => {\n const params = new URLSearchParams({ q: query.trim(), limit: String(Math.max(1, Math.min(100, limit))) });\n if (offset > 0) params.set(\"offset\", String(Math.max(0, Math.floor(offset))));\n const response = await request(`/partner/v2/diagnosis-codes?${params.toString()}`);\n if (!response.ok) throw await responseError(response, \"Diagnosis-code search is unavailable.\");\n const body = await response.json() as { results?: unknown };\n if (!Array.isArray(body.results)) throw new Error(\"Diagnosis-code search returned an invalid response.\");\n return body.results.flatMap((value): BillDiagnosisCode[] => {\n if (!value || typeof value !== \"object\") return [];\n const candidate = value as { code?: unknown; description?: unknown };\n return typeof candidate.code === \"string\" && typeof candidate.description === \"string\"\n ? [{ code: candidate.code, description: candidate.description }]\n : [];\n });\n };\n\n const searchProcedureCodes = async (input: BillProcedureCodeSearchInput = {}): Promise<BillProcedureCodePage> => {\n const limit = Number.isFinite(input.limit) ? Math.max(1, Math.min(100, Math.floor(input.limit!))) : 30;\n const params = new URLSearchParams({ q: input.query?.trim() ?? \"\", limit: String(limit), jurisdiction: input.jurisdiction?.trim().toUpperCase() || \"CA\" });\n const response = await request(`/partner/v2/procedure-codes?${params}`);\n if (!response.ok) throw await responseError(response, \"Procedure-code search is unavailable.\");\n const body = await response.json() as Partial<BillProcedureCodePage>;\n if (!Array.isArray(body.results) || typeof body.total !== \"number\" || !Number.isFinite(body.total) || body.total < 0 || typeof body.limit !== \"number\" || !Number.isFinite(body.limit) || body.limit < 1 || ![\"CA\", \"NY\", \"OWCP\"].includes(body.jurisdiction ?? \"\") || !(body.catalogAsOf === null || typeof body.catalogAsOf === \"string\")) {\n throw new Error(\"Procedure-code search returned an invalid response.\");\n }\n return {\n results: body.results.flatMap((entry) => entry && typeof entry.code === \"string\" && entry.code.trim() ? [{ code: entry.code }] : []),\n total: body.total,\n limit: body.limit,\n jurisdiction: body.jurisdiction!,\n catalogAsOf: body.catalogAsOf,\n };\n };\n\n const quoteClaimFees = async (input: CaClaimFeeQuoteInput): Promise<CaClaimFeeQuoteResult> => {\n const response = await request(\"/partner/v2/fee-quotes/ca/claim\", {\n method: \"POST\", headers: { \"content-type\": \"application/json\" }, body: JSON.stringify(input),\n });\n if (!response.ok) throw await responseError(response, \"Claim fee pricing is unavailable.\");\n const body = await response.json() as { data?: unknown };\n return parseCaClaimFeeQuote(body.data, input);\n };\n\n const quoteFee = async (input: BillFeeQuoteInput): Promise<BillFeeQuote> => {\n const response = await request(\"/partner/v2/fee-quotes\", {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\" },\n body: JSON.stringify(input),\n });\n if (!response.ok) throw await responseError(response, \"Fee-schedule pricing is unavailable.\");\n const body = await response.json() as { data?: BillFeeQuote };\n const quote = body.data;\n if (!quote || !Array.isArray(quote.provenance)) throw new Error(\"Fee quote returned an invalid response.\");\n if (quote.status === \"priced\") {\n if (!Number.isSafeInteger(quote.amountCents) || quote.amountCents < 0 || !Number.isSafeInteger(quote.scheduleMaximumCents) || quote.scheduleMaximumCents < 0 || !BILL_FEE_QUOTE_BASES.includes(quote.basis) || !Array.isArray(quote.notes) || quote.notes.some((note) => typeof note !== \"string\")) throw new Error(\"Fee quote returned an invalid response.\");\n } else if ((quote.status !== \"requires_review\" && quote.status !== \"not_separately_payable\") || typeof quote.reason !== \"string\") {\n throw new Error(\"Fee quote returned an invalid response.\");\n }\n return quote;\n };\n\n const lookupPostalCode = async (postalCode: string): Promise<BillPostalPlace | null> => {\n const params = new URLSearchParams({ postalCode: postalCode.trim() });\n const response = await request(`/partner/v2/postal-codes?${params.toString()}`);\n if (response.status === 404) return null;\n if (!response.ok) throw await responseError(response, \"ZIP lookup is unavailable.\");\n const body = await response.json() as { city?: unknown; state?: unknown };\n if (typeof body.city !== \"string\" || typeof body.state !== \"string\") {\n throw new Error(\"ZIP lookup returned an invalid response.\");\n }\n return { city: body.city, state: body.state };\n };\n\n const mutation = async (path: string, init: RequestInit, fallback: string) => {\n const headers = new Headers(init.headers);\n headers.set(\"idempotency-key\", idempotencyKey());\n const response = await request(path, { ...init, headers });\n if (!response.ok) throw await responseError(response, fallback);\n return response;\n };\n const action = async (input: Record<string, unknown>, fallback: string): Promise<BillLifecycleData> => {\n const response = await mutation(billPath(\"/actions\"), {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\" },\n body: JSON.stringify(input),\n }, fallback);\n const body = await response.json() as { data?: unknown };\n return normalizeLifecycle(body.data);\n };\n const simulateSandbox = async (input: SimulateSandboxBillInput): Promise<BillLifecycleData> => {\n await mutation(`/partner/v2/sandbox/bills/${encodeURIComponent(currentBillId)}/simulate`, {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\" },\n body: JSON.stringify(input),\n }, \"Sandbox lifecycle could not be simulated.\");\n return loadLifecycle();\n };\n return {\n getBillId() { return currentBillId; },\n clearSession() { session = null; sessionRequest = null; },\n getLifecycle: loadLifecycle,\n listMedicalProviderNetworks,\n listClaimsAdministrators,\n searchClaimsAdministrators,\n getClaimsAdministratorDirectory,\n searchDiagnosisCodes,\n searchProcedureCodes,\n quoteFee,\n quoteClaimFees,\n lookupPostalCode,\n async getDeliveryOptions() {\n const response = await request(billPath(\"/delivery-options\"));\n if (!response.ok) throw await responseError(response, \"Delivery options could not be loaded.\");\n const body = await response.json() as { data?: unknown };\n return normalizeDeliveryOptions(body.data ?? body);\n },\n async getDeliveryPreview(input) {\n const params = new URLSearchParams({ claimsAdministratorId: input.claimsAdministratorId.trim() });\n if (input.payerId?.trim()) params.set(\"payerId\", input.payerId.trim());\n if (input.injuryState?.trim()) params.set(\"injuryState\", input.injuryState.trim());\n const response = await request(`/partner/v2/delivery-preview?${params.toString()}`);\n if (!response.ok) throw await responseError(response, \"Delivery routes could not be loaded.\");\n const body = await response.json() as { data?: unknown };\n return normalizeDeliveryOptions(body.data ?? body);\n },\n async getAttachment(attachmentId) {\n const response = await request(billPath(`/documents/${encodeURIComponent(attachmentId)}`));\n if (!response.ok) throw await responseError(response, \"Document could not be opened.\");\n return response.blob();\n },\n async getEor(documentId) {\n const response = await request(billPath(`/eors/${encodeURIComponent(documentId)}`));\n if (!response.ok) throw await responseError(response, \"EOR could not be opened.\");\n return response.blob();\n },\n async getPacket() {\n const response = await request(billPath(\"/packet\"));\n if (!response.ok) throw await responseError(response, \"Submission packet could not be downloaded.\");\n return response.blob();\n },\n async getSubmissionArtifact(attemptId, artifactId) {\n const response = await request(billPath(`/submissions/${encodeURIComponent(attemptId)}/artifacts/${encodeURIComponent(artifactId)}`));\n if (!response.ok) throw await responseError(response, \"The retained submission file could not be downloaded.\");\n return response.blob();\n },\n async prepareIbrPacket() {\n const prepared = await mutation(billPath(\"/actions\"), {\n method: \"POST\", headers: { \"content-type\": \"application/json\" },\n body: JSON.stringify({ action: \"independent_bill_review\" }),\n }, \"IBR packet could not be prepared.\");\n const body = await prepared.json() as { packetUrl?: unknown };\n // Never forward the browser bearer token to an arbitrary response URL.\n if (typeof body.packetUrl !== \"string\" || !/^\\/partner\\/v2\\/(?:browser\\/)?bills\\/[A-Za-z0-9_-]+\\/ibr-packet$/.test(body.packetUrl)) throw new Error(\"The billing service returned an invalid IBR packet path.\");\n // The server may resolve a root bill to its current linked bill.\n const response = await request(body.packetUrl);\n if (!response.ok) throw await responseError(response, \"IBR packet could not be downloaded.\");\n return response.blob();\n },\n async previewCourtesyCopy(input) {\n const response = await request(billPath(\"/courtesy-forward\"), {\n method: \"POST\", headers: { \"content-type\": \"application/json\" }, body: JSON.stringify({ ...input, mode: \"preview\" }),\n });\n if (!response.ok) throw await responseError(response, \"Courtesy copy could not be previewed.\");\n return response.json() as Promise<BillCourtesyCopyPreview>;\n },\n async sendCourtesyCopy(input, key) {\n if (!key.trim() || key.length > 255) throw new Error(\"A stable idempotency key is required to send a courtesy copy.\");\n const response = await request(billPath(\"/courtesy-forward\"), {\n method: \"POST\", headers: { \"content-type\": \"application/json\", \"idempotency-key\": key },\n body: JSON.stringify({ ...input, mode: \"send\" }),\n });\n if (!response.ok) throw await responseError(response, \"Courtesy copy could not be sent. Retry with the same key to check the result safely.\");\n return response.json() as Promise<BillCourtesyCopyResult>;\n },\n addNote(input) { return action({ action: \"add_note\", ...input }, \"Note could not be added.\"); },\n closeBill(input) { return action({ action: \"close\", ...input }, \"Bill could not be closed.\"); },\n reopenBill(input) { return action({ action: \"reopen\", ...input }, \"Bill could not be reopened.\"); },\n postPayment(input) { return action({ action: \"post_payment\", penaltyAmount: 0, interestAmount: 0, ...input, checkNumber: input.checkNumber ?? \"\" }, \"Payment could not be posted.\"); },\n submitSecondReview(input) { return action({ action: \"second_review\", ...input }, \"Second Review could not be submitted.\"); },\n resubmitBill(input) { return action({ action: \"resubmit\", ...input }, \"Bill could not be resubmitted.\"); },\n submitNewBill(input) { return action({ action: \"submit_new_bill\", ...input }, \"The new bill could not be submitted.\"); },\n sendDuplicateBill(input) { return action({ action: \"send_duplicate\", ...input }, \"Duplicate bill could not be sent.\"); },\n reportBillStatus(input) { return action({ action: \"report_bill_status\", ...input }, \"Bill status could not be reported.\"); },\n simulateSandbox,\n };\n}\n\n/**\n * Browser-safe client for reference data needed before a bill exists.\n *\n * Partners can pass the same short-lived session provider used by the submitted-bill\n * lifecycle without inventing a draft bill or exposing payer directory credentials.\n */\nexport function createBillReferenceClient(\n options: BillReferenceClientOptions = {},\n): BillReferenceClient {\n const lifecycle = createBillLifecycleClient({\n ...options,\n billId: \"pre-submission-reference-data\",\n });\n return {\n listMedicalProviderNetworks: lifecycle.listMedicalProviderNetworks,\n listClaimsAdministrators: lifecycle.listClaimsAdministrators,\n searchClaimsAdministrators: lifecycle.searchClaimsAdministrators,\n getClaimsAdministratorDirectory: lifecycle.getClaimsAdministratorDirectory,\n searchDiagnosisCodes: lifecycle.searchDiagnosisCodes,\n searchProcedureCodes: lifecycle.searchProcedureCodes,\n quoteFee: lifecycle.quoteFee,\n quoteClaimFees: lifecycle.quoteClaimFees,\n lookupPostalCode: lifecycle.lookupPostalCode,\n getDeliveryPreview: lifecycle.getDeliveryPreview,\n clearSession: lifecycle.clearSession,\n };\n}\n\n// ---------------------------------------------------------------------------\n// Organization profile client (INC-1470): backs the embeddable\n// OrganizationOnboarding / BillingSettings components. Requires a browser\n// session minted with organization:manage for administrative operations.\n// Read-only saved billing profiles need only an org-wide bills:create session.\n\n/** Convert masked profile state to a write without clearing an unchanged saved SSN. */\nexport function organizationTaxIdWrite<T extends { taxId?: string; taxIdType?: \"EIN\" | \"SSN\"; taxIdLast4?: string; taxIdConfigured?: boolean }>(value: T): Omit<T, \"taxIdLast4\" | \"taxIdConfigured\"> {\n const input = { ...value };\n delete input.taxIdLast4;\n delete input.taxIdConfigured;\n if (value.taxIdType === \"SSN\" && value.taxIdConfigured && !value.taxId?.trim()) delete input.taxId;\n return input;\n}\n\nexport type OrganizationPracticeIdentity = {\n name?: string; legalName?: string; taxId?: string; npi?: string;\n taxIdType?: \"EIN\" | \"SSN\";\n /** Read-only metadata. Saved SSNs are never returned in taxId. */\n taxIdLast4?: string; taxIdConfigured?: boolean;\n phone?: string; email?: string; website?: string;\n};\n\nexport type OrganizationBillingProviderInput = {\n id?: string; externalId?: string; name: string; taxId?: string; npi: string;\n taxIdType?: \"EIN\" | \"SSN\";\n /** Read-only metadata; omit taxId on updates to preserve a saved SSN. */\n taxIdLast4?: string; taxIdConfigured?: boolean;\n billType?: \"Professional\" | \"Institutional\"; phone?: string;\n billingStreet?: string; billingCity?: string; billingState?: string; billingZip?: string;\n};\n\nexport type OrganizationLocationInput = {\n id?: string; externalId?: string; name: string; street: string; city: string;\n state: string; zip: string; nickname?: string; posCode?: string;\n isPrimary?: boolean; active?: boolean;\n};\n\nexport type OrganizationRenderingProviderInput = {\n id?: string; externalId?: string; name: string; npi: string; specialty?: string;\n taxonomy?: string; licenseNumber?: string; licenseState?: string;\n isQME?: boolean; isAME?: boolean; email?: string; active?: boolean;\n};\n\nexport type OrganizationChecklistItem = { id: string; label: string; complete: boolean };\n\nexport type OrganizationProfileData = {\n organizationId: string;\n practiceIdentity: OrganizationPracticeIdentity;\n billingProviders: Array<OrganizationBillingProviderInput & { id: string }>;\n /** Optional for compatibility with older organization-profile responses. */\n renderingProviders?: Array<OrganizationRenderingProviderInput & { id: string }>;\n locations: Array<OrganizationLocationInput & { id: string }>;\n w9: { filename: string; addDate: string; taxYear?: number } | null;\n onboarding: { status: string | null; complete: boolean; checklist: OrganizationChecklistItem[] };\n};\n\nexport type OrganizationClientOptions = {\n sessionEndpoint?: string;\n getSession?: BillLifecycleSessionProvider;\n apiBaseUrl?: string;\n fetch?: typeof globalThis.fetch;\n};\n\nexport type OrganizationTeamRole = \"admin\" | \"manager\" | \"biller\" | \"payments\" | \"viewer\";\nexport type OrganizationTeamMember = {\n id: string; email: string; name: string; role: string; active: boolean;\n createdAt: string; canManage: boolean;\n};\nexport type OrganizationTeam = {\n members: OrganizationTeamMember[];\n roles: Array<{ id: OrganizationTeamRole; label: string; permissions: string[] }>;\n capabilities: { canManage: boolean; canAdd: boolean };\n identityDomain: \"mindbill\";\n};\nexport type OrganizationClaimsAdministratorInput = {\n name: string; fax?: string; email?: string; mailingAddress?: string; notes?: string;\n};\nexport type OrganizationClaimsAdministrator = {\n id: string; name: string; fax: string | null; email: string | null;\n mailingAddress: string | null; notes: string | null; submissionMethod: string;\n active: boolean; createdAt: string;\n};\n\nexport type OrganizationClient = {\n /** Requires explicit team:manage; organization:manage alone does not grant team access. */\n getTeam: () => Promise<OrganizationTeam>;\n updateTeamMember: (id: string, input: { role?: OrganizationTeamRole; active?: boolean }) => Promise<OrganizationTeamMember>;\n getClaimsAdministrators: () => Promise<OrganizationClaimsAdministrator[]>;\n createClaimsAdministrator: (input: OrganizationClaimsAdministratorInput) => Promise<OrganizationClaimsAdministrator>;\n updateClaimsAdministrator: (id: string, input: OrganizationClaimsAdministratorInput) => Promise<OrganizationClaimsAdministrator>;\n deleteClaimsAdministrator: (id: string) => Promise<{ id: string; deleted: true }>;\n\n getOrganization: () => Promise<OrganizationProfileData>;\n /** Masked saved profiles for bill entry; requires org-wide bills:create. */\n getBillingProfile: () => Promise<OrganizationProfileData>;\n saveBillingProfile: (input: {\n practiceIdentity?: OrganizationPracticeIdentity;\n billingProviders?: OrganizationBillingProviderInput[];\n renderingProviders?: OrganizationRenderingProviderInput[];\n }) => Promise<OrganizationProfileData>;\n saveLocations: (locations: OrganizationLocationInput[]) => Promise<OrganizationProfileData>;\n saveW9: (input: { filename: string; contentBase64: string; taxYear?: number }) => Promise<OrganizationProfileData>;\n};\n\nexport function createOrganizationClient({\n sessionEndpoint = DEFAULT_SESSION_ENDPOINT,\n getSession,\n apiBaseUrl = DEFAULT_API_BASE_URL,\n fetch: fetchOverride,\n}: OrganizationClientOptions = {}): OrganizationClient {\n const fetcher = fetchOverride ?? globalThis.fetch;\n if (typeof fetcher !== \"function\") throw new Error(\"A Fetch API implementation is required.\");\n let session: BillLifecycleSession | null = null;\n\n const mintSession = async (force = false): Promise<BillLifecycleSession> => {\n if (!force && isSessionFresh(session)) return session as BillLifecycleSession;\n const pending = getSession\n ? getSession({ signal: new AbortController().signal })\n : fetcher(sessionEndpoint, {\n method: \"POST\",\n credentials: \"same-origin\",\n headers: { \"content-type\": \"application/json\" },\n body: JSON.stringify({}),\n }).then(async (response) => {\n if (!response.ok) throw await responseError(response, \"The organization session could not be created.\");\n return response.json();\n });\n session = normalizeSession(await Promise.resolve(pending));\n return session;\n };\n\n const request = async <T = OrganizationProfileData>(path: string, init: RequestInit = {}): Promise<T> => {\n let current = await mintSession();\n const perform = (active: BillLifecycleSession) => {\n const base = (active.apiBaseUrl ?? apiBaseUrl).replace(/\\/$/, \"\");\n const headers = new Headers(init.headers);\n headers.set(\"authorization\", `Bearer ${active.token}`);\n if (init.body) headers.set(\"content-type\", \"application/json\");\n return fetcher(`${base}${path}`, { ...init, headers });\n };\n let response = await perform(current);\n if (response.status === 401) {\n current = await mintSession(true);\n response = await perform(current);\n }\n if (!response.ok) throw await responseError(response, \"The organization request failed.\");\n const body = (await response.json()) as { data?: T };\n if (!body.data || typeof body.data !== \"object\") {\n throw new Error(\"The organization response was invalid.\");\n }\n return body.data;\n };\n\n return {\n getTeam: () => request<OrganizationTeam>(\"/partner/v2/organization/team\"),\n updateTeamMember: (id, input) => request<OrganizationTeamMember>(`/partner/v2/organization/team/${encodeURIComponent(id)}`, { method: \"PATCH\", body: JSON.stringify(input) }),\n getClaimsAdministrators: () => request<OrganizationClaimsAdministrator[]>(\"/partner/v2/organization/claims-administrators\"),\n createClaimsAdministrator: (input) => request<OrganizationClaimsAdministrator>(\"/partner/v2/organization/claims-administrators\", { method: \"POST\", body: JSON.stringify(input) }),\n updateClaimsAdministrator: (id, input) => request<OrganizationClaimsAdministrator>(`/partner/v2/organization/claims-administrators/${encodeURIComponent(id)}`, { method: \"PATCH\", body: JSON.stringify(input) }),\n deleteClaimsAdministrator: (id) => request<{ id: string; deleted: true }>(`/partner/v2/organization/claims-administrators/${encodeURIComponent(id)}`, { method: \"DELETE\" }),\n getOrganization: () => request(\"/partner/v2/organization\"),\n getBillingProfile: () => request(\"/partner/v2/organization/billing-profile\"),\n saveBillingProfile: (input) =>\n request(\"/partner/v2/organization/billing-profile\", { method: \"PUT\", body: JSON.stringify({\n ...input,\n ...(input.practiceIdentity ? { practiceIdentity: organizationTaxIdWrite(input.practiceIdentity) } : {}),\n ...(input.billingProviders ? { billingProviders: input.billingProviders.map(organizationTaxIdWrite) } : {}),\n }) }),\n saveLocations: (locations) =>\n request(\"/partner/v2/organization/locations\", { method: \"PUT\", body: JSON.stringify({ locations }) }),\n saveW9: (input) =>\n request(\"/partner/v2/organization/w9\", { method: \"PUT\", body: JSON.stringify(input) }),\n };\n}\n\n// ---------------------------------------------------------------------------\n// Bill Tasks dashboard: a pure, framework-neutral\n// aggregation shared by the React and Angular components. Hosts flatten their\n// own work items and get back per-section rows bucketed by age in days.\n\nexport type BillTasksAgingBucket = {\n id: string;\n label: string;\n /** Exclusive lower bound in days. The first bucket also admits day 0. */\n minDays: number;\n /** Inclusive upper bound in days; null means unbounded. */\n maxDays: number | null;\n};\n\nexport const BILL_TASKS_AGING_BUCKETS: BillTasksAgingBucket[] = [\n { id: \"1-30\", label: \"1-30 Days Ago\", minDays: 0, maxDays: 30 },\n { id: \"31-60\", label: \"31-60 Days Ago\", minDays: 30, maxDays: 60 },\n { id: \"61-90\", label: \"61-90 Days Ago\", minDays: 60, maxDays: 90 },\n { id: \"91-180\", label: \"91-180 Days Ago\", minDays: 90, maxDays: 180 },\n { id: \"181+\", label: \"181+ Days Ago\", minDays: 180, maxDays: null },\n];\n\nexport type BillTasksDashboardItem = {\n sectionId: string;\n rowId: string;\n rowLabel: string;\n ageDays: number;\n balanceDue?: number;\n /** Opaque bill reference echoed back in click-through payloads. */\n ref?: string;\n};\n\nexport type BillTasksDashboardRow = {\n id: string;\n label: string;\n /** One count per aging bucket, in bucket order. */\n counts: number[];\n total: number;\n /** Summed item balanceDue per bucket; optional for older count-only payloads. */\n balances?: number[];\n balanceTotal?: number;\n /** Collected item refs per aging bucket, in bucket order. */\n refs: string[][];\n};\n\nexport type BillTasksDashboardTone = \"violet\" | \"red\" | \"blue\" | \"green\" | \"amber\" | \"neutral\";\n\nexport type BillTasksDashboardSectionInput = {\n id: string;\n label: string;\n /** Shown under the section label as \"by {agingBasisLabel}\". */\n agingBasisLabel: string;\n tone: BillTasksDashboardTone;\n};\n\nexport type BillTasksDashboardSection = BillTasksDashboardSectionInput & {\n rows: BillTasksDashboardRow[];\n /** Per-bucket totals across the section's rows. */\n totals: number[];\n total: number;\n balanceTotals?: number[];\n balanceTotal?: number;\n empty: boolean;\n};\n\nexport type BillTasksDashboardData = {\n sections: BillTasksDashboardSection[];\n grandTotals: number[];\n grandTotal: number;\n /** Work-item sums, not deduplicated financial A/R across task categories. */\n grandBalanceTotals?: number[];\n grandBalanceTotal?: number;\n};\n\n/**\n * Bucket index for an item age: a bucket admits `minDays < ageDays <= maxDays`\n * (`maxDays: null` = unbounded) and the first bucket also admits day 0.\n * Ages beyond every bucket clamp into the last bucket.\n */\nexport function billTasksAgingBucketIndex(\n ageDays: number,\n buckets: BillTasksAgingBucket[] = BILL_TASKS_AGING_BUCKETS,\n): number {\n const days = Math.max(0, Math.floor(ageDays));\n const index = buckets.findIndex((bucket, position) =>\n (bucket.maxDays === null || days <= bucket.maxDays)\n && (days > bucket.minDays || position === 0));\n return index === -1 ? buckets.length - 1 : index;\n}\n\n/**\n * Aggregates flat work items into the Bill Tasks dashboard.\n * Sections render in the given order even when empty; rows appear in\n * first-seen item order within their section.\n */\nexport function buildBillTasksDashboard(\n items: BillTasksDashboardItem[],\n sections: BillTasksDashboardSectionInput[],\n buckets: BillTasksAgingBucket[] = BILL_TASKS_AGING_BUCKETS,\n): BillTasksDashboardData {\n const zeros = () => buckets.map(() => 0);\n const built = sections.map((section): BillTasksDashboardSection => ({\n ...section,\n rows: [],\n totals: zeros(),\n total: 0,\n balanceTotals: zeros(),\n balanceTotal: 0,\n empty: true,\n }));\n const sectionById = new Map(built.map((section) => [section.id, section]));\n const rowByKey = new Map<string, BillTasksDashboardRow>();\n const grandTotals = zeros();\n let grandTotal = 0;\n const grandBalanceTotals = zeros();\n let grandBalanceTotal = 0;\n\n for (const item of items) {\n const section = sectionById.get(item.sectionId);\n if (!section) continue;\n const key = `${item.sectionId}\\u0000${item.rowId}`;\n let row = rowByKey.get(key);\n if (!row) {\n row = {\n id: item.rowId,\n label: item.rowLabel,\n counts: zeros(),\n total: 0,\n balances: zeros(),\n balanceTotal: 0,\n refs: buckets.map(() => []),\n };\n rowByKey.set(key, row);\n section.rows.push(row);\n section.empty = false;\n }\n const bucketIndex = billTasksAgingBucketIndex(item.ageDays, buckets);\n const balance = Number.isFinite(item.balanceDue) ? item.balanceDue! : 0;\n row.counts[bucketIndex] = (row.counts[bucketIndex] ?? 0) + 1;\n row.total += 1;\n row.balances![bucketIndex] = (row.balances![bucketIndex] ?? 0) + balance;\n row.balanceTotal = (row.balanceTotal ?? 0) + balance;\n if (item.ref) row.refs[bucketIndex]?.push(item.ref);\n section.totals[bucketIndex] = (section.totals[bucketIndex] ?? 0) + 1;\n section.total += 1;\n section.balanceTotals![bucketIndex] = (section.balanceTotals![bucketIndex] ?? 0) + balance;\n section.balanceTotal = (section.balanceTotal ?? 0) + balance;\n grandTotals[bucketIndex] = (grandTotals[bucketIndex] ?? 0) + 1;\n grandTotal += 1;\n grandBalanceTotals[bucketIndex] = (grandBalanceTotals[bucketIndex] ?? 0) + balance;\n grandBalanceTotal += balance;\n }\n\n return { sections: built, grandTotals, grandTotal, grandBalanceTotals, grandBalanceTotal };\n}\n\n\n/** Contacts snapshotted on a request and included in the reviewed form. */\nexport type RfaContact = {\n name?: string; contactName?: string; address?: string; city?: string; state?: string;\n zip?: string; phone?: string; fax?: string; email?: string;\n};\nexport type RfaDeliveryPreviewInput = { documentIds: string[]; channel: \"fax\" | \"email\" | \"download\"; to?: string; recipientName?: string; message?: string };\nexport type RfaDeliveryPreview = { packetId: string; sha256: string; contentRevision: number };\nexport type RfaSubmitInput = Omit<RfaDeliveryPreview, \"contentRevision\"> & { channel: \"fax\" | \"email\"; to: string; recipientName?: string; message?: string; nonBusinessDates?: string[] };\n/** An unsigned RFA preparation draft. Signing and sending are separate operations. */\nexport type RfaCreateDraftInput = {\n claimId: string; patientId: string; renderingProviderId: string; employeeName: string; providerName: string;\n externalId?: string; claimsAdminId?: string; writtenConfirmation?: boolean;\n requestingPractice?: RfaContact | null; authorizationContact?: RfaContact | null;\n requestType?: \"new\" | \"resubmission_material_change\" | \"oral_authorization_confirmation\";\n reviewType?: \"prospective\" | \"concurrent\" | \"retrospective\"; expedited?: boolean;\n placeOfServiceCode?: string; providerNpi?: string; providerPhone?: string; providerFax?: string;\n claimNumber?: string; dateOfInjury?: string; rationale?: string; materialChange?: string;\n items: Array<{ externalId?: string; diagnosisCode: string; diagnosisDescription?: string; serviceDescription: string; procedureCode?: string;\n quantity?: number; units?: number; frequency?: string; duration?: string; requestedFrom?: string; requestedTo?: string; metadata?: Record<string, unknown> }>;\n metadata?: Record<string, unknown>;\n};\n/** Full replacement of editable request content; retained service rows keep their IDs. */\nexport type RfaUpdateDraftInput = Omit<RfaCreateDraftInput, \"externalId\" | \"claimId\" | \"patientId\" | \"renderingProviderId\" | \"items\"> & {\n expectedRevision: number;\n items: Array<Omit<RfaCreateDraftInput[\"items\"][number], \"externalId\"> & { id?: string }>;\n};\nexport type RfaRecord = {\n contentRevision: number; id: string; claimId: string; patientId: string; renderingProviderId: string; claimsAdminId: string | null;\n employeeName: string; providerName: string; claimNumber: string | null; status: string;\n /** Delivery/review lifecycle, separate from the clinical status and item outcomes. */\n lifecycleStatus?: import(\"./rfa-status\").RfaLifecycleStatus;\n requestType?: RfaCreateDraftInput[\"requestType\"]; writtenConfirmation?: boolean;\n requestingPractice?: RfaContact | null; authorizationContact?: RfaContact | null;\n placeOfServiceCode?: string | null; providerNpi?: string | null; providerPhone?: string | null; providerFax?: string | null;\n dateOfInjury?: string | null; rationale?: string | null; materialChange?: string | null; metadata?: Record<string, unknown>;\n reviewType: string; expedited: boolean; createdAt: string | null; updatedAt: string | null;\n signedAt: string | null; submittedAt: string | null; receivedAt: string | null;\n decisionDueAt: string | null; decisionDeadlineBasis: string | null;\n incompleteReason: string | null; deferredReason: string | null; closedReason: string | null;\n readiness: { ready: boolean; missing: string[] };\n items: Array<{ id: string; diagnosisCode: string; diagnosisDescription?: string; serviceDescription: string; procedureCode: string | null;\n frequency?: string | null; duration?: string | null; requestedFrom?: string | null; requestedTo?: string | null; metadata?: Record<string, unknown>;\n outcome: string; quantity: number | null; units: number | null; authorizationNumber: string | null; decisionReason: string | null;\n decisionClosure?: import(\"./rfa-lifecycle\").RfaTreatmentClosure | null;\n currentDecisionEventId?: string | null; currentResponseDocumentId?: string | null; currentImrDocumentId?: string | null;\n authorizedProcedureCode?: string | null; authorizedQuantity?: number | null; authorizedUnits?: number | null;\n effectiveFrom?: string | null; effectiveTo?: string | null; decidedAt?: string | null; reviewerName?: string | null; reviewerPhone?: string | null }>;\n documents: Array<{ id: string; documentType: string; filename: string; contentUrl: string; contentRevision: number | null; createdAt: string | null }>;\n transmissions: Array<{ id: string; purpose?: string; direction: string; channel: string; status: string; destination: string | null;\n occurredAt: string | null; receivedAt: string | null; proofDocumentId: string | null; providerMessageId: string | null }>;\n informationRequests: Array<{ id: string; requestText: string; requestedAt: string | null; dueAt: string | null; respondedAt: string | null }>;\n events: Array<{ id: string; type: string; occurredAt: string | null; text?: string }>;\n};\nexport type RfaAgingBucket = \"0_5\" | \"6_14\" | \"15_30\" | \"31_plus\";\nexport type RfaAgingSummary = { byBucket: Record<RfaAgingBucket, number>; byLifecycleStatus: Record<import(\"./rfa-status\").RfaLifecycleStatus, Record<RfaAgingBucket, number>> };\nexport type RfaListQuery = { agingBucket?: RfaAgingBucket; patientId?: string; search?: string; sortBy?: \"createdAt\" | \"employeeName\" | \"providerName\" | \"submittedAt\" | \"status\" | \"lifecycleStatus\"; sortDirection?: \"asc\" | \"desc\"; claimId?: string; renderingProviderId?: string; status?: string; lifecycleStatus?: import(\"./rfa-status\").RfaLifecycleStatus; createdFrom?: string; createdTo?: string; limit?: number; cursor?: string };\nexport type RfaListResult = { data: RfaRecord[]; nextCursor: string | null; summary: { total: number; byStatus: Record<string, number>; aging?: RfaAgingSummary; byLifecycleStatus?: Partial<Record<import(\"./rfa-status\").RfaLifecycleStatus, number>> } };\nexport type RfaSigningPreviewInput = { billingProviderId?: string; diagnosisDescriptions: Record<string, string> };\nexport type RfaSigningPreview = { id: string; contentHash: string; contentRevision: number; renderingProviderId: string; previewDocumentId: string; expiresAt: string };\nexport type RfaSignInput = { snapshotId: string; contentHash: string; renderingProviderId: string; physicianAuthorized: true; actorReference: string };\nexport type RfaFaxInput = { to: string; documentIds: string[]; nonBusinessDates?: string[] };\nexport type RfaUploadDocumentInput = { file: File; documentType: \"clinical_report\" | \"supporting_record\" | \"ur_response\" | \"imr_form\" | \"other\"; contentRevision: number };\nexport type RfaCreationClaim = { claimId: string; patientId: string; employeeName: string; claimNumber?: string; dateOfInjury?: string; claimsAdminId?: string; diagnosisCodes?: string[] };\nexport type RfaCreationProvider = { id: string; name: string; npi?: string };\nexport type RfaCreationContext = { claims: RfaCreationClaim[]; renderingProviders: RfaCreationProvider[]; nextCursor: string | null; renderingProvidersNextCursor: string | null };\nexport type RfaCreationContextQuery = { search?: string; cursor?: string; providerSearch?: string; providerCursor?: string; limit?: number; claimId?: string; renderingProviderId?: string };\nexport type RfaProvisionClaimInput = {\n patient: Omit<BrowserBillCreateInput[\"patient\"], \"id\" | \"externalId\"> & { externalId: string };\n claim: Omit<BrowserBillCreateInput[\"claim\"], \"id\" | \"externalId\"> & { externalId: string };\n};\nexport type RfaProvisionClaimResult = { patientId: string; claimId: string; patientExternalId: string; claimExternalId: string; created: { patient: boolean; claim: boolean } };\nexport type RfaClient = {\n provisionClaim?: (input: RfaProvisionClaimInput, options?: { idempotencyKey?: string }) => Promise<RfaProvisionClaimResult>;\n searchClaimsAdministrators?: (query: string, claimNumber?: string) => Promise<BillReviewPayer[]>;\n saveProviderSignature?: (providerId: string, input: { contentBase64: string; physicianAuthorized: true; actorReference: string }, options?: { idempotencyKey?: string }) => Promise<{ providerId: string; signatureConfigured: true }>;\n\n getCreationContext: (query?: RfaCreationContextQuery) => Promise<RfaCreationContext>;\n list: (query?: RfaListQuery) => Promise<RfaListResult>;\n get: (rfaId: string) => Promise<RfaRecord>;\n createDraft: (draft: RfaCreateDraftInput, idempotencyKey: string) => Promise<RfaRecord>;\n updateDraft: (rfaId: string, draft: RfaUpdateDraftInput, idempotencyKey: string) => Promise<RfaRecord>;\n getDocument: (rfaId: string, documentId: string) => Promise<Blob>;\n uploadDocument: (rfaId: string, input: RfaUploadDocumentInput, idempotencyKey: string) => Promise<RfaRecord>;\n prepareSigning: (rfaId: string, input: RfaSigningPreviewInput, idempotencyKey: string) => Promise<RfaSigningPreview>;\n sign: (rfaId: string, input: RfaSignInput, idempotencyKey: string) => Promise<RfaRecord>;\n prepareDelivery: (rfaId: string, input: RfaDeliveryPreviewInput, key?: string) => Promise<RfaDeliveryPreview>;\n getPacket: (rfaId: string, packetId: string) => Promise<Blob>;\n submit: (rfaId: string, input: RfaSubmitInput, idempotencyKey: string) => Promise<RfaRecord>;\n previewPacket: (rfaId: string, documentIds: string[]) => Promise<Blob>;\n sendFax: (rfaId: string, input: RfaFaxInput, idempotencyKey: string) => Promise<RfaRecord>;\n refreshFaxes: (rfaId: string, idempotencyKey: string) => Promise<RfaRecord>;\n};\n/** Uses short-lived browser credentials. Never pass a partner API key. */\nexport function createRfaClient({ sessionEndpoint = DEFAULT_SESSION_ENDPOINT, getSession, apiBaseUrl = DEFAULT_API_BASE_URL, fetch: fetchOverride }: OrganizationClientOptions = {}): RfaClient {\n const fetcher = fetchOverride ?? globalThis.fetch;\n let session: BillLifecycleSession | null = null;\n let pending: Promise<BillLifecycleSession> | null = null;\n const mint = (force = false): Promise<BillLifecycleSession> => {\n if (!force && isSessionFresh(session)) return Promise.resolve(session as BillLifecycleSession);\n if (pending) return pending;\n pending = (async () => {\n const value = getSession ? await getSession({ signal: new AbortController().signal }) : await (async () => {\n const response = await fetcher(sessionEndpoint, { method: \"POST\", credentials: \"same-origin\", headers: { \"content-type\": \"application/json\" }, body: \"{}\" });\n if (!response.ok) throw await responseError(response, \"The RFA session could not be created.\");\n return response.json();\n })();\n session = normalizeSession(value); return session;\n })().finally(() => { pending = null; });\n return pending;\n };\n const request = async (path: string, init: RequestInit = {}, browser = false, resource = \"rfas\") => {\n const perform = (active: BillLifecycleSession) => {\n const headers = new Headers(init.headers); headers.set(\"authorization\", `Bearer ${active.token}`);\n if (init.body && !(init.body instanceof FormData)) headers.set(\"content-type\", \"application/json\");\n return fetcher(`${(active.apiBaseUrl ?? apiBaseUrl).replace(/\\/$/, \"\")}/partner/v2/${browser ? \"browser/\" : \"\"}${resource}${path}`, { ...init, headers });\n };\n let response = await perform(await mint());\n if (response.status === 401) response = await perform(await mint(true));\n if (!response.ok) throw await responseError(response, \"The RFA request failed.\");\n return response;\n };\n const record = async (path: string, init?: RequestInit): Promise<RfaRecord> => {\n const body = await (await request(path, init)).json() as { data?: RfaRecord };\n if (!body.data?.id) throw new Error(\"The RFA response was invalid.\");\n return body.data;\n };\n const mutation = (body: unknown, key: string): RequestInit => {\n if (!key.trim()) throw new Error(\"An idempotency key is required.\");\n return { method: \"POST\", headers: { \"idempotency-key\": key }, body: JSON.stringify(body) };\n };\n const path = (id: string, suffix: string) => `/${encodeURIComponent(id)}/${suffix}`;\n return {\n provisionClaim: async (input, options) => {\n const response = await request(\"\", mutation(input, options?.idempotencyKey ?? globalThis.crypto.randomUUID()), false, \"claims\");\n const body = await response.json() as RfaProvisionClaimResult;\n if (!body.patientId || !body.claimId) throw new Error(\"The saved patient and injury response was invalid.\");\n return body;\n },\n searchClaimsAdministrators: (query, claimNumber) => createBillReferenceClient({ sessionEndpoint, ...(getSession ? { getSession } : {}), apiBaseUrl, ...(fetchOverride ? { fetch: fetchOverride } : {}) }).searchClaimsAdministrators(query, claimNumber),\n saveProviderSignature: async (providerId, input, options) => {\n const response = await request(`/providers/${encodeURIComponent(providerId)}/signature`, mutation(input, options?.idempotencyKey ?? globalThis.crypto.randomUUID()), true);\n const body = await response.json() as { data: { providerId: string; signatureConfigured: true } };\n if (body.data?.signatureConfigured !== true) throw new Error(\"The physician signature could not be confirmed.\");\n return body.data;\n },\n getCreationContext: async (query = {}) => {\n const params = new URLSearchParams();\n for (const [name, value] of Object.entries(query)) if (value !== undefined && value !== \"\") params.set(name, String(value));\n const body = await (await request(`/creation-context${params.size ? `?${params}` : \"\"}`, {}, true)).json() as { data?: RfaCreationContext };\n if (!Array.isArray(body.data?.claims) || !Array.isArray(body.data?.renderingProviders)) throw new Error(\"The RFA creation context was invalid.\");\n return body.data;\n },\n list: async (query = {}) => {\n const params = new URLSearchParams();\n for (const [key, value] of Object.entries(query)) if (value !== undefined && value !== \"\") params.set(key, String(value));\n const body = await (await request(params.size ? `?${params}` : \"\")).json() as RfaListResult;\n if (!Array.isArray(body.data) || !body.summary) throw new Error(\"The RFA list response was invalid.\");\n return body;\n },\n get: (id) => record(`/${encodeURIComponent(id)}`),\n createDraft: (draft, idempotencyKey) => {\n if (!idempotencyKey.trim()) return Promise.reject(new Error(\"An idempotency key is required.\"));\n const unsigned = { ...draft } as RfaCreateDraftInput & { signedAt?: unknown }; delete unsigned.signedAt;\n unsigned.items = draft.items.map(item => { const copy = { ...item } as typeof item & { id?: unknown }; delete copy.id; return copy; });\n return record(\"\", { method: \"POST\", headers: { \"idempotency-key\": idempotencyKey }, body: JSON.stringify(unsigned) });\n },\n updateDraft: (id, draft, key) => {\n if (!Number.isInteger(draft.expectedRevision) || draft.expectedRevision < 1) return Promise.reject(new Error(\"A positive expected content revision is required.\"));\n const body = { ...draft } as RfaUpdateDraftInput & Record<string, unknown>;\n for (const field of [\"externalId\", \"claimId\", \"patientId\", \"renderingProviderId\", \"signedAt\"]) delete body[field];\n body.items = draft.items.map(item => { const copy = { ...item } as typeof item & { externalId?: unknown }; delete copy.externalId; return copy; });\n return record(path(id, \"draft\"), { ...mutation(body, key), method: \"PATCH\" });\n },\n uploadDocument: (id, input, key) => {\n if (!key.trim()) return Promise.reject(new Error(\"An idempotency key is required.\"));\n if (input.file.size < 1 || input.file.size > 25 * 1024 * 1024) return Promise.reject(new Error(\"Choose a PDF up to 25 MB.\"));\n const body = new FormData(); body.set(\"file\", input.file); body.set(\"documentType\", input.documentType); body.set(\"contentRevision\", String(input.contentRevision));\n return record(path(id, \"documents\"), { method: \"POST\", headers: { \"idempotency-key\": key }, body });\n },\n prepareSigning: async (id, input, key) => {\n const body = await (await request(path(id, \"signing-preview\"), mutation(input, key))).json() as { data: RfaSigningPreview };\n if (!body.data?.id || !body.data.contentHash || !body.data.previewDocumentId) throw new Error(\"The signing preview was invalid.\");\n return body.data;\n },\n sign: (id, input, key) => {\n if (input.physicianAuthorized !== true || !input.actorReference.trim()) return Promise.reject(new Error(\"Physician authorization and signer identity are required.\"));\n return record(path(id, \"sign\"), mutation(input, key));\n },\n prepareDelivery: async (id, input, key) => {\n const body = await (await request(path(id, \"delivery-preview\"), mutation(input, key ?? idempotencyKey()))).json() as { data: RfaDeliveryPreview };\n if (!body.data?.packetId || !body.data.sha256 || !body.data.contentRevision) throw new Error(\"The delivery preview was invalid.\");\n return body.data;\n },\n getPacket: async (id, packetId) => (await request(path(id, `packets/${encodeURIComponent(packetId)}`))).blob(),\n submit: async (id, input, key) => {\n const body = await (await request(path(id, \"submit\"), mutation(input, key))).json() as { data: { transmissionId: string; packetId: string } };\n if (!body.data?.transmissionId || !body.data.packetId) throw new Error(\"The submission response was invalid. Refresh before trying again.\");\n return record(`/${encodeURIComponent(id)}`);\n },\n previewPacket: async (id, documentIds) => (await request(path(id, \"packet\"), { method: \"POST\", body: JSON.stringify({ documentIds }) })).blob(),\n sendFax: (id, input, key) => record(path(id, \"fax\"), mutation(input, key)),\n refreshFaxes: (id, key) => record(path(id, \"fax/refresh\"), mutation({}, key)),\n getDocument: async (id, documentId) => (await request(`/${encodeURIComponent(id)}/documents/${encodeURIComponent(documentId)}`)).blob(),\n };\n}\n\nexport * from \"./rfa-lifecycle\";\nexport { createReportAutofillClient } from \"./report-autofill\";\nexport type { ReportAutofillClient, ReportAutofillField, ReportAutofillMatch, ReportAutofillResult } from \"./report-autofill\";\n\nexport * from \"./rfa-draft-actions\";\n\nexport * from \"./rfa-packets\";\n\nexport * from \"./rfa-status\";\n"],"mappings":";AAqDA,IAAM,SAAS,CAAC,MAA6C,CAAC,CAAC,KAAK,OAAO,MAAM,YAAY,CAAC,MAAM,QAAQ,CAAC;AAC7G,IAAM,UAAU,CAAC,MAA8B,MAAM,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC,MAAM,OAAO,MAAM,QAAQ;AACvG,IAAM,QAAQ,CAAC,MAAe,OAAO,cAAc,CAAC,KAAM,KAAgB;AAC1E,IAAM,SAAS,CAAC,MAAe,CAAC,UAAU,mBAAmB,wBAAwB,EAAE,SAAS,CAAW;AAC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