import { AccessPolicy } from '@medplum/fhirtypes';
import { AccessPolicyResource } from '@medplum/fhirtypes';
import { Address } from '@medplum/fhirtypes';
import { Agent } from '@medplum/fhirtypes';
import { Attachment } from '@medplum/fhirtypes';
import { Binary } from '@medplum/fhirtypes';
import { Bot } from '@medplum/fhirtypes';
import { BulkDataExport } from '@medplum/fhirtypes';
import { Bundle } from '@medplum/fhirtypes';
import { CodeableConcept } from '@medplum/fhirtypes';
import { Coding } from '@medplum/fhirtypes';
import { Communication } from '@medplum/fhirtypes';
import { ConceptMap } from '@medplum/fhirtypes';
import type { CustomTableLayout } from 'pdfmake/interfaces';
import { Device } from '@medplum/fhirtypes';
import { DiagnosticReport } from '@medplum/fhirtypes';
import { ElementDefinition } from '@medplum/fhirtypes';
import { ElementDefinitionBinding } from '@medplum/fhirtypes';
import { Encounter } from '@medplum/fhirtypes';
import { Extension } from '@medplum/fhirtypes';
import { ExtensionValue } from '@medplum/fhirtypes';
import { ExtractResource } from '@medplum/fhirtypes';
import { HumanName } from '@medplum/fhirtypes';
import { Identifier } from '@medplum/fhirtypes';
import { ImagingStudy } from '@medplum/fhirtypes';
import { Media } from '@medplum/fhirtypes';
import { Money } from '@medplum/fhirtypes';
import { Observation } from '@medplum/fhirtypes';
import { ObservationComponent } from '@medplum/fhirtypes';
import { ObservationDefinition } from '@medplum/fhirtypes';
import { ObservationDefinitionQualifiedInterval } from '@medplum/fhirtypes';
import { OperationOutcome } from '@medplum/fhirtypes';
import { OperationOutcomeIssue } from '@medplum/fhirtypes';
import { Patient } from '@medplum/fhirtypes';
import { Period } from '@medplum/fhirtypes';
import { Practitioner } from '@medplum/fhirtypes';
import { Project } from '@medplum/fhirtypes';
import { ProjectMembership } from '@medplum/fhirtypes';
import { ProjectMembershipAccess } from '@medplum/fhirtypes';
import { ProjectSetting } from '@medplum/fhirtypes';
import { Quantity } from '@medplum/fhirtypes';
import { QuestionnaireResponse } from '@medplum/fhirtypes';
import { QuestionnaireResponseItemAnswer } from '@medplum/fhirtypes';
import { Range as Range_2 } from '@medplum/fhirtypes';
import { Readable } from 'stream';
import { Reference } from '@medplum/fhirtypes';
import { RelatedPerson } from '@medplum/fhirtypes';
import { Resource } from '@medplum/fhirtypes';
import { ResourceType } from '@medplum/fhirtypes';
import { SearchParameter } from '@medplum/fhirtypes';
import { StructureDefinition } from '@medplum/fhirtypes';
import { StructureMap } from '@medplum/fhirtypes';
import { Subscription } from '@medplum/fhirtypes';
import type { TDocumentDefinitions } from 'pdfmake/interfaces';
import type { TFontDictionary } from 'pdfmake/interfaces';
import { Timing } from '@medplum/fhirtypes';
import { UserConfiguration } from '@medplum/fhirtypes';
import { ValueSet } from '@medplum/fhirtypes';
import { ViewDefinition } from '@medplum/fhirtypes';
import { ViewDefinitionSelect } from '@medplum/fhirtypes';

export declare function accepted(location: string): OperationOutcome;

/**
 * Interactions with a resource that can be controlled via an access policy.
 *
 * Codes taken from http://hl7.org/fhir/codesystem-restful-interaction.html
 */
export declare const AccessPolicyInteraction: {
    readonly READ: "read";
    readonly VREAD: "vread";
    readonly UPDATE: "update";
    readonly PATCH: "patch";
    readonly DELETE: "delete";
    readonly HISTORY: "history";
    readonly HISTORY_INSTANCE: "history-instance";
    readonly HISTORY_TYPE: "history-type";
    readonly HISTORY_SYSTEM: "history-system";
    readonly CREATE: "create";
    readonly SEARCH: "search";
    readonly SEARCH_TYPE: "search-type";
    readonly SEARCH_SYSTEM: "search-system";
    readonly SEARCH_COMPARTMENT: "search-compartment";
    readonly CAPABILITIES: "capabilities";
    readonly TRANSACTION: "transaction";
    readonly BATCH: "batch";
    readonly OPERATION: "operation";
};

export declare type AccessPolicyInteraction = (typeof AccessPolicyInteraction)[keyof typeof AccessPolicyInteraction];

/**
 * Adds the supplied profileUrl to the resource.meta.profile if it is not already
 * specified
 * @param resource - A FHIR resource
 * @param profileUrl - The profile URL to add
 * @returns The resource
 */
export declare function addProfileToResource<T extends Resource = Resource>(resource: T, profileUrl: string): T;

export declare interface AddressFormatOptions {
    all?: boolean;
    use?: boolean;
    lineSeparator?: string;
}

export declare interface AgentConnectRequest extends BaseAgentRequestMessage {
    type: 'agent:connect:request';
    agentId: string;
}

export declare interface AgentConnectResponse extends BaseAgentMessage {
    type: 'agent:connect:response';
}

export declare interface AgentError extends BaseAgentMessage {
    type: 'agent:error';
    body: string;
}

export declare interface AgentHeartbeatRequest extends BaseAgentRequestMessage {
    type: 'agent:heartbeat:request';
}

export declare interface AgentHeartbeatResponse extends BaseAgentMessage {
    type: 'agent:heartbeat:response';
    version: string;
}

export declare type AgentMessage = AgentRequestMessage | AgentResponseMessage;

export declare interface AgentReloadConfigRequest extends BaseAgentRequestMessage {
    type: 'agent:reloadconfig:request';
}

export declare interface AgentReloadConfigResponse extends BaseAgentMessage {
    type: 'agent:reloadconfig:response';
    statusCode: number;
}

export declare type AgentRequestMessage = AgentConnectRequest | AgentHeartbeatRequest | AgentTransmitRequest | AgentReloadConfigRequest | AgentUpgradeRequest;

export declare type AgentResponseMessage = AgentConnectResponse | AgentHeartbeatResponse | AgentTransmitResponse | AgentReloadConfigResponse | AgentUpgradeResponse | AgentError;

export declare interface AgentTransmitRequest extends BaseAgentRequestMessage {
    type: 'agent:transmit:request';
    channel?: string;
    remote: string;
    contentType: string;
    body: string;
}

export declare interface AgentTransmitResponse extends BaseAgentMessage {
    type: 'agent:transmit:response';
    channel?: string;
    remote: string;
    contentType: string;
    statusCode?: number;
    body: string;
}

export declare interface AgentUpgradeRequest extends BaseAgentRequestMessage {
    type: 'agent:upgrade:request';
    version?: string;
}

export declare interface AgentUpgradeResponse extends BaseAgentMessage {
    type: 'agent:upgrade:response';
    statusCode: number;
}

export declare const allOk: OperationOutcome;

export declare type AnchorResourceOpenEvent<T extends FhircastAnchorResourceType> = T extends FhircastAnchorResourceType ? `${T}-open` : never;

/**
 * 6.5.1. and
 * Returns true if both operands evaluate to true,
 * false if either operand evaluates to false,
 * and the empty collection otherwise.
 */
export declare class AndAtom extends BooleanInfixOperatorAtom {
    constructor(left: Atom, right: Atom);
    eval(context: AtomContext, input: TypedValue[]): TypedValue[];
}

export declare function append<T>(array: T[] | undefined, value: T): T[];

/**
 * Adds default values to `existingValue` for the given `key` and its children. If `key` is undefined,
 * default values are added to all elements in `elements`. Default values consist of all fixed and pattern
 * values defined in the relevant elements.
 * @param existingValue - The
 * @param elements - The elements to which default values should be added.
 * @param key - (optional) The key of the element(s) for which default values should be added. Elements with nested
 * keys are also included. If undefined, default values for all elements are added.
 * @returns `existingValue` with default values added
 */
export declare function applyDefaultValuesToElement(existingValue: object, elements: Record<string, InternalSchemaElement>, key?: string): object;

/**
 * Adds default values to `resource` based on the supplied `schema`. Default values includes all required fixed and pattern
 * values specified on elements in the schema. If an element has a fixed/pattern value but is optional, i.e.
 * `element.min === 0`, the default value is not added.
 *
 * @param resource - The resource to which default values should be added.
 * @param schema - The schema to use for adding default values.
 * @returns A clone of `resource` with default values added.
 */
export declare function applyDefaultValuesToResource(resource: Resource, schema: InternalTypeSchema): Resource;

export declare function applyFixedOrPatternValue(inputValue: any, key: string, element: InternalSchemaElement, elements: Record<string, InternalSchemaElement>): any;

export declare class ArithemticOperatorAtom extends BooleanInfixOperatorAtom {
    readonly impl: (x: number, y: number) => number | boolean;
    constructor(operator: string, left: Atom, right: Atom, impl: (x: number, y: number) => number | boolean);
    eval(context: AtomContext, input: TypedValue[]): TypedValue[];
}

/**
 * Converts an ArrayBuffer to a base-64 encoded string.
 * @param arrayBuffer - The input array buffer.
 * @returns The base-64 encoded string.
 */
export declare function arrayBufferToBase64(arrayBuffer: ArrayBufferLike | ArrayBufferView): string;

/**
 * Converts an ArrayBuffer to hex string.
 * See: https://stackoverflow.com/a/55200387
 * @param arrayBuffer - The input array buffer.
 * @returns The resulting hex string.
 */
export declare function arrayBufferToHex(arrayBuffer: ArrayBufferLike | ArrayBufferView): string;

export declare function arrayify<T>(value: T | T[] | undefined): T[] | undefined;

export declare class AsAtom extends InfixOperatorAtom {
    constructor(left: Atom, right: Atom);
    eval(context: AtomContext, input: TypedValue[]): TypedValue[];
}

export declare function assert(condition: unknown, msg?: string): asserts condition;

export declare function assertContextVersionOptional(event: string): asserts event is FhircastEventVersionOptional;

/**
 * Asserts that the operation completed successfully and that the resource is defined.
 * @param outcome - The operation outcome.
 * @param resource - The resource that may or may not have been returned.
 */
export declare function assertOk<T>(outcome: OperationOutcome, resource: T | undefined): asserts resource is T;

/**
 * Asserts that a given candidate is a `ReleaseManifest`.
 * @param candidate - An object assumed to be a `ReleaseManifest`.
 */
export declare function assertReleaseManifest(candidate: unknown): asserts candidate is ReleaseManifest;

export declare interface AsyncCrawlerVisitor {
    onEnterObject?: (path: string, value: TypedValueWithPath, schema: InternalTypeSchema) => Promise<void>;
    onExitObject?: (path: string, value: TypedValueWithPath, schema: InternalTypeSchema) => Promise<void>;
    onEnterResource?: (path: string, value: TypedValueWithPath, schema: InternalTypeSchema) => Promise<void>;
    onExitResource?: (path: string, value: TypedValueWithPath, schema: InternalTypeSchema) => Promise<void>;
    visitPropertyAsync: (parent: TypedValueWithPath, key: string, path: string, value: TypedValueWithPath | TypedValueWithPath[], schema: InternalTypeSchema) => Promise<void>;
}

export declare interface Atom {
    eval(context: AtomContext, input: TypedValue[]): TypedValue[];
    toString(): string;
}

export declare interface AtomContext {
    parent?: AtomContext;
    variables: Record<string, TypedValue>;
}

export declare interface BackgroundJobContext {
    interaction: BackgroundJobInteraction;
}

export declare type BackgroundJobInteraction = 'create' | 'update' | 'delete';

export declare function badRequest(details: string, expression?: string): OperationOutcome;

export declare interface BaseAgentMessage {
    type: string;
    callback?: string;
}

export declare interface BaseAgentRequestMessage extends BaseAgentMessage {
    accessToken?: string;
}

export declare interface BaseLoginRequest {
    readonly projectId?: string;
    readonly clientId?: string;
    readonly resourceType?: string;
    readonly scope?: string;
    readonly nonce?: string;
    readonly codeChallenge?: string;
    readonly codeChallengeMethod?: CodeChallengeMethod;
    readonly googleClientId?: string;
    readonly launch?: string;
    readonly redirectUri?: string;
}

export declare type BaseSchema = Record<string, {
    elements: Record<string, Partial<InternalSchemaElement>>;
}>;

/**
 * Source for a FHIR Binary.
 */
export declare type BinarySource = string | File | Blob | Uint8Array;

export declare abstract class BooleanInfixOperatorAtom extends InfixOperatorAtom {
    abstract eval(context: AtomContext, input: TypedValue[]): TypedValue[];
}

/**
 * Returns a single element array with a typed boolean value.
 * @param value - The primitive boolean value.
 * @returns Single element array with a typed boolean value.
 */
export declare function booleanToTypedValue(value: boolean): [TypedValue];

export declare interface BotEvent<T = Resource | Hl7Message | string | Record<string, any>> {
    readonly bot: Reference<Bot>;
    readonly contentType: string;
    readonly input: T;
    readonly secrets: Record<string, ProjectSetting>;
    readonly traceId?: string;
}

export declare function buildElementsContext({ parentContext, path, elements, profileUrl, debugMode, accessPolicyResource, }: {
    /** The most recent `ElementsContextType` in which this context is being built. */
    parentContext: ElementsContextType | undefined;
    /** The FHIR path from the root resource to which the keys of `elements` are relative. */
    path: string;
    /**
     * The mapping of keys to `InternalSchemaElement` at the current `path` relative to the
     * root resource. This should be either `InternalTypeSchema.elements` or `SliceDefinition.elements`.
     */
    elements: Record<string, InternalSchemaElement>;
    /** The URL, if any, of the resource profile or extension from which the `elements` collection originated. */
    profileUrl?: string;
    /** Whether debug logging is enabled */
    debugMode?: boolean;
    accessPolicyResource?: AccessPolicyResource;
}): ElementsContextType | undefined;

export declare function buildTypeName(components: string[]): string;

/**
 * Calculates the age in years from the birth date.
 * @param birthDateStr - The birth date or start date in ISO-8601 format YYYY-MM-DD.
 * @param endDateStr - Optional end date in ISO-8601 format YYYY-MM-DD. Default value is today.
 * @returns The age in years, months, and days.
 */
export declare function calculateAge(birthDateStr: string, endDateStr?: string): {
    years: number;
    months: number;
    days: number;
};

/**
 * Calculates the age string for display using the age appropriate units.
 * If the age is greater than or equal to 2 years, then the age is displayed in years.
 * If the age is greater than or equal to 1 month, then the age is displayed in months.
 * Otherwise, the age is displayed in days.
 * @param birthDateStr - The birth date or start date in ISO-8601 format YYYY-MM-DD.
 * @param endDateStr - Optional end date in ISO-8601 format YYYY-MM-DD. Default value is today.
 * @returns The age string.
 */
export declare function calculateAgeString(birthDateStr: string, endDateStr?: string): string | undefined;

export declare type CanBePopulated = {
    length: number;
} | object;

/**
 * Determines if the current user can read the specified resource type.
 * @param accessPolicy - The access policy.
 * @param resourceType - The resource type.
 * @returns True if the current user can read the specified resource type.
 */
export declare function canReadResourceType(accessPolicy: AccessPolicy, resourceType: ResourceType): boolean;

/**
 * Determines if the current user can write the specified resource.
 * This is a more in-depth check after building the candidate result of a write operation.
 * @param accessPolicy - The access policy.
 * @param resource - The resource.
 * @returns True if the current user can write the specified resource type.
 */
export declare function canWriteResource(accessPolicy: AccessPolicy, resource: Resource): boolean;

/**
 * Determines if the current user can write the specified resource type.
 * This is a preliminary check before evaluating a write operation in depth.
 * If a user cannot write a resource type at all, then don't bother looking up previous versions.
 * @param accessPolicy - The access policy.
 * @param resourceType - The resource type.
 * @returns True if the current user can write the specified resource type.
 */
export declare function canWriteResourceType(accessPolicy: AccessPolicy, resourceType: ResourceType): boolean;

export declare function capitalize(word: string): string;

/**
 * Recursively checks for null values in an object.
 *
 * Note that "null" is a special value in JSON that is not allowed in FHIR.
 * @param value - Input value of any type.
 * @param path - Path string to the value for OperationOutcome.
 * @param issues - Output list of issues.
 */
export declare function checkForNull(value: unknown, path: string, issues: OperationOutcomeIssue[]): void;

/**
 * Tests that a given version string is a valid existing Medplum release version.
 * @param appName - The name of the app to check the version for.
 * @param version - A version to be checked against the existing Medplum repo releases.
 * @returns `true` if `version` is a valid semver version that corresponds to an existing release, otherwise `false`.
 */
export declare function checkIfValidMedplumVersion(appName: string, version: string): Promise<boolean>;

/**
 * Clears the locally-cached `ReleaseManifest`s for all versions.
 */
export declare function clearReleaseCache(): void;

/**
 * The ClientStorage class is a utility class for storing strings and objects.
 *
 * When using MedplumClient in the browser, it will be backed by browser localStorage.
 *
 * When Using MedplumClient in the server, it will be backed by the MemoryStorage class.  For example, the Medplum CLI uses `FileSystemStorage`.
 */
export declare class ClientStorage implements IClientStorage {
    private readonly storage;
    constructor(storage?: Storage);
    clear(): void;
    getString(key: string): string | undefined;
    setString(key: string, value: string | undefined): void;
    getObject<T>(key: string): T | undefined;
    setObject<T>(key: string, value: T): void;
}

declare interface CloseEvent_2 extends globalThis.Event {
    code: number;
    reason: string;
    wasClean: boolean;
}
export { CloseEvent_2 as CloseEvent }

export declare interface Code {
    code?: CodeableConcept;
}

/**
 * Allowed values for `code_challenge_method` in a PKCE exchange.
 */
export declare type CodeChallengeMethod = 'plain' | 'S256';

export declare function compressElement(element: InternalSchemaElement): Partial<InternalSchemaElement>;

export declare class ConcatAtom extends InfixOperatorAtom {
    constructor(left: Atom, right: Atom);
    eval(context: AtomContext, input: TypedValue[]): TypedValue[];
}

/**
 * Concatenates the given base URL and URL.
 *
 * If the URL is absolute, it is returned as-is.
 *
 * @param baseUrl - The base URL.
 * @param path - The URL to concat. Can be relative or absolute.
 * @returns The concatenated URL.
 */
export declare function concatUrls(baseUrl: string | URL, path: string): string;

export declare function conceptMapTranslate(map: ConceptMap, params: ConceptMapTranslateParameters): ConceptMapTranslateOutput;

export declare interface ConceptMapTranslateMatch {
    equivalence?: string;
    concept?: Coding;
}

export declare interface ConceptMapTranslateOutput {
    result: boolean;
    message?: string;
    match?: ConceptMapTranslateMatch[];
}

export declare interface ConceptMapTranslateParameters {
    url?: string;
    source?: string;
    code?: string;
    system?: string;
    coding?: Coding;
    codeableConcept?: CodeableConcept;
    targetsystem?: string;
}

export declare function conflict(details: string, code?: string): OperationOutcome;

export declare interface Constraint {
    key: string;
    severity: 'error' | 'warning';
    expression: string;
    description: string;
}

export declare class ContainsAtom extends BooleanInfixOperatorAtom {
    constructor(left: Atom, right: Atom);
    eval(context: AtomContext, input: TypedValue[]): TypedValue[];
}

/**
 * Content type constants.
 */
export declare const ContentType: {
    readonly CSS: "text/css";
    readonly DICOM: "application/dicom";
    readonly FAVICON: "image/vnd.microsoft.icon";
    readonly FHIR_JSON: "application/fhir+json";
    readonly FORM_URL_ENCODED: "application/x-www-form-urlencoded";
    readonly HL7_V2: "x-application/hl7-v2+er7";
    readonly HTML: "text/html";
    readonly JAVASCRIPT: "text/javascript";
    readonly JSON: "application/json";
    readonly JSON_PATCH: "application/json-patch+json";
    readonly PNG: "image/png";
    readonly SCIM_JSON: "application/scim+json";
    readonly SVG: "image/svg+xml";
    readonly TEXT: "text/plain";
    readonly TYPESCRIPT: "text/typescript";
    readonly PING: "x-application/ping";
    readonly XML: "text/xml";
    readonly CDA_XML: "application/cda+xml";
};

/**
 * Converts a resource with contained resources to a transaction bundle.
 * This function is useful when creating a resource that contains other resources.
 * Handles local references and topological sorting.
 * @param resource - The input resource which may or may not include contained resources.
 * @returns A bundle with the input resource and all contained resources.
 */
export declare function convertContainedResourcesToBundle(resource: Resource & {
    contained?: Resource[];
}): Bundle;

/**
 * More on Bundles can be found here
 * http://hl7.org/fhir/R4/bundle.html
 */
/**
 * Takes a bundle and creates a Transaction Type bundle
 * @param bundle - The Bundle object that we'll receive from the search query
 * @returns transaction type bundle
 */
export declare function convertToTransactionBundle(bundle: Bundle): Bundle;

export declare const CPT = "http://www.ama-assn.org/go/cpt";

export declare interface CrawlerOptions {
    skipMissingProperties?: boolean;
    schema?: InternalTypeSchema;
    initialPath?: string;
}

export declare interface CrawlerVisitor {
    onEnterObject?: (path: string, value: TypedValueWithPath, schema: InternalTypeSchema) => void;
    onExitObject?: (path: string, value: TypedValueWithPath, schema: InternalTypeSchema) => void;
    onEnterResource?: (path: string, value: TypedValueWithPath, schema: InternalTypeSchema) => void;
    onExitResource?: (path: string, value: TypedValueWithPath, schema: InternalTypeSchema) => void;
    visitProperty: (parent: TypedValueWithPath, key: string, path: string, propertyValues: (TypedValueWithPath | TypedValueWithPath[])[], schema: InternalTypeSchema) => void;
}

/**
 * Crawls the typed value synchronously.
 * @param typedValue - The typed value to crawl.
 * @param visitor - The visitor functions to apply while crawling.
 * @param options - Options for how to crawl the typed value.
 */
export declare function crawlTypedValue(typedValue: TypedValue, visitor: CrawlerVisitor, options?: CrawlerOptions): void;

/**
 * Crawls the typed value asynchronously.
 * @param typedValue - The typed value to crawl.
 * @param visitor - The visitor functions to apply while crawling.
 * @param options - Options for how to crawl the typed value.
 * @returns Promise to crawl the typed value.
 */
export declare function crawlTypedValueAsync(typedValue: TypedValue, visitor: AsyncCrawlerVisitor, options?: CrawlerOptions): Promise<void>;

/**
 * Binary upload options.
 */
export declare interface CreateBinaryOptions {
    /**
     * The binary data to upload.
     */
    readonly data: BinarySource;
    /**
     * Content type for the binary.
     */
    readonly contentType: string;
    /**
     * Optional filename for the binary.
     */
    readonly filename?: string;
    /**
     * Optional security context for the binary.
     */
    readonly securityContext?: Reference;
    /**
     * Optional fetch options. **NOTE:** only `requestOptions.signal` is respected when `onProgress` is also provided.
     */
    readonly onProgress?: (e: ProgressEvent) => void;
}

export declare function createConstraintIssue(expression: string, constraint: Constraint): OperationOutcomeIssue;

export declare const created: OperationOutcome;

/**
 * Creates a serializable JSON payload for the `FHIRcast` protocol
 *
 * @param topic - The topic that this message will be published on. Usually a UUID.
 * @param event - The event name, ie. "Patient-open" or "Patient-close".
 * @param context - The updated context, containing new versions of resources related to this event.
 * @param versionId - The current `versionId` of the anchor context. For example, in `DiagnosticReport-update`, it's the `versionId` of the `DiagnosticReport`.
 * @returns A serializable `FhircastMessagePayload`.
 */
export declare function createFhircastMessagePayload<EventName extends FhircastEventVersionOptional>(topic: string, event: EventName, context: FhircastEventContext<EventName> | FhircastEventContext<EventName>[], versionId?: never): FhircastMessagePayload<EventName>;

export declare function createFhircastMessagePayload<EventName extends FhircastEventVersionRequired>(topic: string, event: EventName, context: FhircastEventContext<EventName> | FhircastEventContext<EventName>[], versionId: string): FhircastMessagePayload<EventName>;

export declare interface CreateMediaOptions extends CreateBinaryOptions {
    /**
     * Optional additional fields for the Media resource.
     */
    readonly additionalFields?: Partial<Media>;
}

export declare function createOperationOutcomeIssue(severity: IssueSeverity, code: IssueType, message: string, path: string, data?: Record<string, any>): OperationOutcomeIssue;

export declare interface CreatePdfFunction {
    (docDefinition: TDocumentDefinitions, tableLayouts?: Record<string, CustomTableLayout>, fonts?: TFontDictionary): Promise<any>;
}

/**
 * PDF upload options.
 */
export declare interface CreatePdfOptions extends Omit<CreateBinaryOptions, 'data' | 'contentType'> {
    /**
     * The PDF document definition. See https://pdfmake.github.io/docs/0.1/document-definition-object/
     */
    readonly docDefinition: TDocumentDefinitions;
    /**
     * Optional pdfmake custom table layout.
     */
    readonly tableLayouts?: Record<string, CustomTableLayout>;
    /**
     * Optional pdfmake custom font dictionary.
     */
    readonly fonts?: TFontDictionary;
}

export declare function createProcessingIssue(expression: string, message: string, err: Error, data?: Record<string, any>): OperationOutcomeIssue;

/**
 * Creates a reference resource.
 * @param resource - The FHIR resource.
 * @returns A reference resource.
 */
export declare function createReference<T extends Resource>(resource: T): Reference<T> & {
    reference: string;
};

export declare function createStructureIssue(expression: string, details: string): OperationOutcomeIssue;

export declare type CurrentContext<T extends FhircastAnchorResourceType | '' = FhircastAnchorResourceType | ''> = T extends '' ? {
    'context.type': '';
    context: never[];
} : T extends 'DiagnosticReport' ? {
    'context.type': 'DiagnosticReport';
    'context.versionId': string;
    context: (FhircastEventContext<'DiagnosticReport-open'> | FhircastHubContentContext)[];
} : T extends 'Patient' | 'Encounter' | 'ImagingStudy' ? {
    'context.type': T;
    'context.versionId': string;
    context: FhircastEventContext<AnchorResourceOpenEvent<T>>;
} : never;

export declare type DataTypesMap = {
    [type: string]: InternalTypeSchema;
};

/**
 * Decodes a base64 string.
 * Handles both browser and Node environments.
 * Supports Unicode characters.
 * @param data - The base-64 encoded input string.
 * @returns The decoded string.
 */
export declare function decodeBase64(data: string): string;

/**
 * Creates a deep clone of the input value.
 *
 * Limitations:
 *  - Only supports JSON primitives and arrays.
 *  - Does not support Functions, lambdas, etc.
 *  - Does not support circular references.
 *
 * See: https://web.dev/structured-clone/
 * See: https://stackoverflow.com/questions/40488190/how-is-structured-clone-algorithm-different-from-deep-copy
 * @param input - The input to clone.
 * @returns A deep clone of the input.
 */
export declare function deepClone<T>(input: T): T;

/**
 * Resource equality.
 * Ignores meta.versionId and meta.lastUpdated.
 * @param object1 - The first object.
 * @param object2 - The second object.
 * @param path - Optional path string.
 * @returns True if the objects are equal.
 */
export declare function deepEquals(object1: unknown, object2: unknown, path?: string): boolean;

/**
 * Checks if value includes all fields and values of pattern.
 * It doesn't matter if value has extra fields, values, etc.
 * @param value - The object being tested against pattern.
 * @param pattern - The object pattern/shape checked to exist within value.
 * @returns True if value includes all fields and values of pattern.
 */
export declare function deepIncludes(value: any, pattern: any): boolean;

export declare const DEFAULT_ACCEPT: string;

export declare const DEFAULT_MAX_SEARCH_COUNT = 1000;

export declare const DEFAULT_SEARCH_COUNT = 20;

export declare class DotAtom extends InfixOperatorAtom {
    constructor(left: Atom, right: Atom);
    eval(context: AtomContext, input: TypedValue[]): TypedValue[];
    toString(): string;
}

/**
 * Information for the set of elements at a given path within in a resource. This mostly exists to
 * normalize access to elements regardless of whether they are from a profile, extension, or slice.
 */
export declare type ElementsContextType = {
    /** The FHIR path from the root resource to which the keys of `elements` are relative. */
    path: string;
    /**
     * The mapping of keys to `ExtendedInternalSchemaElement` at the current `path` relative to the
     * root resource. `elements` originate from either `InternalTypeSchema.elements` or
     * `SliceDefinition.elements` when the elements context is created within a slice.
     */
    elements: Record<string, ExtendedInternalSchemaElement>;
    /**
     * Similar mapping as `elements`, but with keys being the full path from the root resource rather
     * than relative to `path`, in other words, the keys of the Record are `${path}.${key}`.
     */
    elementsByPath: Record<string, ExtendedInternalSchemaElement>;
    /** The URL, if any, of the resource profile or extension from which the `elements` collection originated. */
    profileUrl: string | undefined;
    /** Whether debug logging is enabled */
    debugMode: boolean;
    /** The `AccessPolicyResource` provided, if any, used to determine hidden and readonly elements. */
    accessPolicyResource?: AccessPolicyResource;
    /**
     * Used to get an `ExtendedElementProperties` object for an element at a given path. This
     * is primarily useful when working with elements not included in `InternalTypeSchema.elements`
     * as is the case for nested elements that have not been modified by a profile or extension,
     * e.g. Patient.name.family.
     *
     * This function does not attempt to determine if the input `path` is actually an element in the
     * resource. When a syntactically correct path to a nonexistent element, e.g. Patient.foobar, is provided,
     * a `ExtendedElementProperties` object with default values is returned.
     *
     * @param path - The full path to an element in the resource, e.g. Patient.name.family
     * @returns An `ExtendedElementProperties` object with `readonly` and `hidden` properties for the
     * element at `path`, or `undefined` if the input path is malformed.
     */
    getExtendedProps(path: string): ExtendedElementProperties | undefined;
    /** `true` if this is a default/placeholder `ElementsContextType` */
    isDefaultContext?: boolean;
};

export declare interface ElementType {
    code: string;
    targetProfile?: string[];
    profile?: string[];
}

export declare interface EmailPasswordLoginRequest extends BaseLoginRequest {
    readonly email: string;
    readonly password: string;
    /** @deprecated Use scope of "offline" or "offline_access" instead. */
    readonly remember?: boolean;
}

export declare class EmptySetAtom implements Atom {
    eval(): [];
    toString(): string;
}

/**
 * Encodes a base64 string.
 * Handles both browser and Node environments.
 * Supports Unicode characters.
 * @param data - The unencoded input string.
 * @returns The base-64 encoded string.
 */
export declare function encodeBase64(data: string): string;

/**
 * Encrypts a string with SHA256 encryption.
 * @param str - The unencrypted input string.
 * @returns The encrypted value in an ArrayBuffer.
 */
export declare function encryptSHA256(str: string): Promise<ArrayBuffer>;

/**
 * Ensures the given URL has no leading slash.
 * @param url - The URL to ensure has no leading slash.
 * @returns The URL string with no slash.
 */
export declare function ensureNoLeadingSlash(url: string): string;

/**
 * Ensures the given URL has a trailing slash.
 * @param url - The URL to ensure has a trailing slash.
 * @returns The URL with a trailing slash.
 */
export declare function ensureTrailingSlash(url: string): string;

export declare class EqualsAtom extends BooleanInfixOperatorAtom {
    constructor(left: Atom, right: Atom);
    eval(context: AtomContext, input: TypedValue[]): TypedValue[];
}

export declare class EquivalentAtom extends BooleanInfixOperatorAtom {
    constructor(left: Atom, right: Atom);
    eval(context: AtomContext, input: TypedValue[]): TypedValue[];
}

declare interface ErrorEvent_2 extends globalThis.Event {
    message: string;
    error: Error;
}
export { ErrorEvent_2 as ErrorEvent }

/**
 * Returns the escaped HTML string of the input string.
 * @param unsafe - The unsafe HTML string to escape.
 * @returns The escaped HTML string.
 */
export declare function escapeHtml(unsafe: string): string;

/**
 * Evaluates a FHIRPath expression against a resource or other object.
 * @param expression - The FHIRPath expression to parse.
 * @param input - The resource or object to evaluate the expression against.
 * @returns The result of the FHIRPath expression against the resource or object.
 */
export declare function evalFhirPath(expression: string, input: unknown): unknown[];

/**
 * Evaluates a FHIRPath expression against a resource or other object.
 * @param expression - The FHIRPath expression to parse.
 * @param input - The resource or object to evaluate the expression against.
 * @param variables - A map of variables for eval input.
 * @returns The result of the FHIRPath expression against the resource or object.
 */
export declare function evalFhirPathTyped(expression: string, input: TypedValue[], variables?: Record<string, TypedValue>): TypedValue[];

/**
 * Evaluates a SQL-on-FHIR view on a set of FHIR resources.
 * @param view - The view definition.
 * @param resources - The array of FHIR resources.
 * @returns The output rows.
 */
export declare function evalSqlOnFhir(view: ViewDefinition, resources: Resource[]): OutputRow[];

declare interface Event_2 {
    readonly type: string;
    readonly defaultPrevented?: boolean;
}
export { Event_2 as Event }

declare type EventListener_2 = (e: Event_2) => void;
export { EventListener_2 as EventListener }

declare class EventTarget_2 {
    private readonly listeners;
    constructor();
    addEventListener(type: string, callback: EventListener_2): void;
    removeEventListener(type: string, callback: EventListener_2): void;
    dispatchEvent(event: Event_2): boolean;
    removeAllListeners(): void;
}
export { EventTarget_2 as EventTarget }

export declare type ExtendedElementProperties = {
    readonly: boolean;
    hidden: boolean;
};

export declare interface ExtendedInternalSchemaElement extends InternalSchemaElement {
    readonly?: boolean;
}

export declare type ExternalSecret<T extends ExternalSecretPrimitive = ExternalSecretPrimitive> = {
    system: ExternalSecretSystem;
    key: string;
    type: TypeName<T>;
};

export declare type ExternalSecretPrimitive = string | boolean | number;

export declare type ExternalSecretPrimitiveType = 'string' | 'boolean' | 'number';

export declare type ExternalSecretSystem = keyof typeof ExternalSecretSystems;

export declare const ExternalSecretSystems: {
    readonly aws_ssm_parameter_store: "aws_ssm_parameter_store";
};

/**
 * Fetches the latest Medplum release version string.
 * @param appName - The name of the app to fetch the latest version for.
 * @returns A version string corresponding to the latest Medplum release version.
 */
export declare function fetchLatestVersionString(appName: string): Promise<string>;

export declare type FetchLike = (url: string, options?: any) => Promise<any>;

/**
 * Fetches the manifest for a given Medplum release version.
 * @param appName - The name of the app to fetch the manifest for.
 * @param version - The version to fetch. If no `version` is provided, defaults to the `latest` version.
 * @param params - An optional list of key-value pairs to be appended to the URL query string.
 * @returns - The manifest for the specified or latest version.
 */
export declare function fetchVersionManifest(appName: string, version?: string, params?: Record<string, string>): Promise<ReleaseManifest>;

export declare const FHIRCAST_EVENT_NAMES: {
    readonly 'Patient-open': "Patient-open";
    readonly 'Patient-close': "Patient-close";
    readonly 'ImagingStudy-open': "ImagingStudy-open";
    readonly 'ImagingStudy-close': "ImagingStudy-close";
    readonly 'Encounter-open': "Encounter-open";
    readonly 'Encounter-close': "Encounter-close";
    readonly 'DiagnosticReport-open': "DiagnosticReport-open";
    readonly 'DiagnosticReport-close': "DiagnosticReport-close";
    readonly 'DiagnosticReport-select': "DiagnosticReport-select";
    readonly 'DiagnosticReport-update': "DiagnosticReport-update";
    readonly syncerror: "syncerror";
};

export declare const FHIRCAST_EVENT_RESOURCES: {
    readonly 'Patient-open': {
        readonly patient: {
            readonly resourceType: "Patient";
        };
        readonly encounter: {
            readonly resourceType: "Encounter";
            readonly optional: true;
        };
    };
    readonly 'Patient-close': {
        readonly patient: {
            readonly resourceType: "Patient";
        };
        readonly encounter: {
            readonly resourceType: "Encounter";
            readonly optional: true;
        };
    };
    readonly 'ImagingStudy-open': {
        readonly study: {
            readonly resourceType: "ImagingStudy";
        };
        readonly encounter: {
            readonly resourceType: "Encounter";
            readonly optional: true;
        };
        readonly patient: {
            readonly resourceType: "Patient";
            readonly optional: true;
        };
    };
    readonly 'ImagingStudy-close': {
        readonly study: {
            readonly resourceType: "ImagingStudy";
        };
        readonly encounter: {
            readonly resourceType: "Encounter";
            readonly optional: true;
        };
        readonly patient: {
            readonly resourceType: "Patient";
            readonly optional: true;
        };
    };
    readonly 'Encounter-open': {
        readonly encounter: {
            readonly resourceType: "Encounter";
        };
        readonly patient: {
            readonly resourceType: "Patient";
        };
    };
    readonly 'Encounter-close': {
        readonly encounter: {
            readonly resourceType: "Encounter";
        };
        readonly patient: {
            readonly resourceType: "Patient";
        };
    };
    readonly 'DiagnosticReport-open': {
        readonly report: {
            readonly resourceType: "DiagnosticReport";
        };
        readonly encounter: {
            readonly resourceType: "Encounter";
            readonly optional: true;
        };
        readonly study: {
            readonly resourceType: "ImagingStudy";
            readonly optional: true;
            readonly manyAllowed: true;
        };
        readonly patient: {
            readonly resourceType: "Patient";
        };
    };
    readonly 'DiagnosticReport-close': {
        readonly report: {
            readonly resourceType: "DiagnosticReport";
        };
        readonly encounter: {
            readonly resourceType: "Encounter";
            readonly optional: true;
        };
        readonly study: {
            readonly resourceType: "ImagingStudy";
            readonly optional: true;
            readonly manyAllowed: true;
        };
        readonly patient: {
            readonly resourceType: "Patient";
        };
    };
    readonly 'DiagnosticReport-select': {
        readonly report: {
            readonly resourceType: "DiagnosticReport";
            readonly reference: true;
        };
        readonly patient: {
            readonly resourceType: "Patient";
            readonly optional: true;
            readonly reference: true;
        };
        readonly select: {
            readonly resourceType: "*";
            readonly reference: true;
            readonly manyAllowed: true;
        };
    };
    readonly 'DiagnosticReport-update': {
        readonly report: {
            readonly resourceType: "DiagnosticReport";
            readonly reference: true;
        };
        readonly patient: {
            readonly resourceType: "Patient";
            readonly optional: true;
            readonly reference: true;
        };
        readonly updates: {
            readonly resourceType: "Bundle";
        };
    };
    readonly syncerror: {
        readonly operationoutcome: {
            readonly resourceType: "OperationOutcome";
        };
    };
};

export declare const FHIRCAST_EVENT_VERSION_REQUIRED: readonly ["DiagnosticReport-update"];

export declare const FHIRCAST_RESOURCE_TYPES: readonly ["Patient", "Encounter", "ImagingStudy", "DiagnosticReport", "OperationOutcome", "Bundle"];

export declare type FhircastAnchorResourceType = 'Patient' | 'ImagingStudy' | 'Encounter' | 'DiagnosticReport';

export declare type FhircastConnectEvent = {
    type: 'connect';
};

/**
 * A class representing a `FHIRcast` connection.
 *
 * `FhircastConnection` extends `EventTarget` and emits 3 lifecycle events:
 * 1. `connect` - An event to signal when a WebSocket connection has been opened. Fired as soon as a WebSocket emits `open`.
 * 2. `message` - Contains a `payload` field containing a `FHIRcast` message payload exactly as it comes in over WebSockets.
 * 3. `disconnect` - An event to signal when a WebSocket connection has been closed. Fired as soon as a WebSocket emits `close`.
 *
 * To close the connection, call `connection.disconnect()` and listen to the `disconnect` event to know when the connection has been disconnected.
 */
export declare class FhircastConnection extends TypedEventTarget<FhircastSubscriptionEventMap> {
    readonly subRequest: SubscriptionRequest;
    private readonly websocket;
    /**
     * Creates a new `FhircastConnection`.
     * @param subRequest - The subscription request to initialize the connection from.
     */
    constructor(subRequest: SubscriptionRequest);
    disconnect(): void;
}

export declare type FhircastContextResourceType<EventName extends FhircastEventName, K extends FhircastEventKeys<EventName>> = (typeof FHIRCAST_EVENT_RESOURCES)[EventName][K] extends {
    resourceType: infer R;
} ? R : never;

export declare type FhircastDiagnosticReportCloseContext = FhircastDiagnosticReportOpenContext;

export declare type FhircastDiagnosticReportOpenContext = FhircastReportContext | FhircastEncounterContext | FhircastStudyContext | FhircastPatientContext;

export declare type FhircastDiagnosticReportSelectContext = FhircastReportReferenceContext | FhircastPatientReferenceContext | FhircastSelectContext;

export declare type FhircastDiagnosticReportUpdateContext = FhircastReportReferenceContext | FhircastPatientReferenceContext | FhircastUpdatesContext;

export declare type FhircastDisconnectEvent = {
    type: 'disconnect';
};

export declare type FhircastEncounterCloseContext = FhircastEncounterOpenContext;

export declare type FhircastEncounterContext = {
    key: 'encounter';
    resource: Encounter;
};

export declare type FhircastEncounterOpenContext = FhircastEncounterContext | FhircastPatientContext;

export declare type FhircastEventContext<EventName extends FhircastEventName = FhircastResourceEventName> = EventName extends 'Patient-open' ? FhircastPatientOpenContext : EventName extends 'Patient-close' ? FhircastPatientCloseContext : EventName extends 'ImagingStudy-open' ? FhircastImagingStudyOpenContext : EventName extends 'ImagingStudy-close' ? FhircastImagingStudyCloseContext : EventName extends 'Encounter-open' ? FhircastEncounterOpenContext : EventName extends 'Encounter-close' ? FhircastEncounterCloseContext : EventName extends 'DiagnosticReport-open' ? FhircastDiagnosticReportOpenContext : EventName extends 'DiagnosticReport-close' ? FhircastDiagnosticReportCloseContext : EventName extends 'DiagnosticReport-update' ? FhircastDiagnosticReportUpdateContext : EventName extends 'DiagnosticReport-select' ? FhircastDiagnosticReportSelectContext : EventName extends 'syncerror' ? FhircastSyncErrorContext : never;

export declare type FhircastEventContextDetails = {
    resourceType: FhircastResourceType | '*';
    optional?: boolean;
    manyAllowed?: boolean;
    array?: boolean;
    reference?: boolean;
};

export declare type FhircastEventKeys<EventName extends FhircastEventName> = keyof (typeof FHIRCAST_EVENT_RESOURCES)[EventName];

export declare type FhircastEventName = keyof typeof FHIRCAST_EVENT_NAMES;

export declare type FhircastEventPayload<EventName extends FhircastEventName = FhircastEventName> = {
    'hub.topic': string;
    'hub.event': EventName;
    context: FhircastEventContext<EventName>[];
    'context.versionId'?: string;
    'context.priorVersionId'?: string;
};

export declare type FhircastEventVersionOptional = Exclude<FhircastEventName, FhircastEventVersionRequired>;

export declare type FhircastEventVersionRequired = (typeof FHIRCAST_EVENT_VERSION_REQUIRED)[number];

export declare type FhircastHubContentContext = {
    key: 'content';
    resource: Bundle;
};

export declare type FhircastImagingStudyCloseContext = FhircastImagingStudyOpenContext;

export declare type FhircastImagingStudyOpenContext = FhircastStudyContext | FhircastEncounterContext | FhircastPatientContext;

export declare type FhircastMessageEvent = {
    type: 'message';
    payload: FhircastMessagePayload;
};

export declare type FhircastMessagePayload<EventName extends FhircastEventName = FhircastEventName> = {
    timestamp: string;
    id: string;
    event: FhircastEventPayload<EventName>;
};

export declare type FhircastOperationOutcomeContext = {
    key: 'operationoutcome';
    resource: OperationOutcome;
};

export declare type FhircastPatientCloseContext = FhircastPatientOpenContext;

export declare type FhircastPatientContext = {
    key: 'patient';
    resource: Patient;
};

export declare type FhircastPatientOpenContext = FhircastPatientContext | FhircastEncounterContext;

export declare type FhircastPatientReferenceContext = {
    key: 'patient';
    reference: Reference<Patient>;
};

export declare type FhircastReferenceContext = FhircastReportReferenceContext | FhircastPatientReferenceContext | FhircastSelectContext;

export declare type FhircastReportContext = {
    key: 'report';
    resource: DiagnosticReport;
};

export declare type FhircastReportReferenceContext = {
    key: 'report';
    reference: Reference<DiagnosticReport>;
};

export declare type FhircastResourceContext = FhircastPatientContext | FhircastEncounterContext | FhircastStudyContext | FhircastReportContext | FhircastUpdatesContext | FhircastOperationOutcomeContext;

export declare type FhircastResourceEventName = Exclude<FhircastEventName, 'syncerror'>;

export declare type FhircastResourceType = (typeof FHIRCAST_RESOURCE_TYPES)[number];

export declare type FhircastSelectContext = {
    key: 'select';
    reference: Reference;
};

export declare type FhircastStudyContext = {
    key: 'study';
    resource: ImagingStudy;
};

export declare type FhircastSubscriptionEventMap = {
    connect: FhircastConnectEvent;
    message: FhircastMessageEvent;
    disconnect: FhircastDisconnectEvent;
};

export declare type FhircastSyncErrorContext = FhircastOperationOutcomeContext;

export declare type FhircastUpdatesContext = {
    key: 'updates';
    resource: Bundle;
};

/**
 * The FhirFilterComparison class represents a comparison expression.
 */
export declare class FhirFilterComparison {
    readonly path: string;
    readonly operator: Operator;
    readonly value: string;
    constructor(path: string, operator: Operator, value: string);
}

/**
 * The FhirFilterConnective class represents a connective expression.
 * It contains a list of child expressions.
 */
export declare class FhirFilterConnective {
    readonly keyword: 'and' | 'or';
    readonly left: FhirFilterExpression;
    readonly right: FhirFilterExpression;
    constructor(keyword: 'and' | 'or', left: FhirFilterExpression, right: FhirFilterExpression);
}

/**
 * The FhirFilterExpression type is the base type of all filter expressions.
 */
export declare type FhirFilterExpression = FhirFilterComparison | FhirFilterNegation | FhirFilterConnective;

/**
 * The FhirFilterNegation class represents a negation expression.
 * It contains a single child expression.
 */
export declare class FhirFilterNegation {
    readonly child: FhirFilterExpression;
    constructor(child: FhirFilterExpression);
}

/**
 * Determines if two arrays are equal according to FHIRPath equality rules.
 * @param x - The first array.
 * @param y - The second array.
 * @returns FHIRPath true if the arrays are equal.
 */
export declare function fhirPathArrayEquals(x: TypedValue[], y: TypedValue[]): TypedValue[];

/**
 * Determines if two arrays are equivalent according to FHIRPath equality rules.
 * @param x - The first array.
 * @param y - The second array.
 * @returns FHIRPath true if the arrays are equivalent.
 */
export declare function fhirPathArrayEquivalent(x: TypedValue[], y: TypedValue[]): TypedValue[];

/**
 * Determines if two arrays are not equal according to FHIRPath equality rules.
 * @param x - The first array.
 * @param y - The second array.
 * @returns FHIRPath true if the arrays are not equal.
 */
export declare function fhirPathArrayNotEquals(x: TypedValue[], y: TypedValue[]): TypedValue[];

export declare class FhirPathAtom implements Atom {
    readonly original: string;
    readonly child: Atom;
    constructor(original: string, child: Atom);
    eval(context: AtomContext, input: TypedValue[]): TypedValue[];
    toString(): string;
}

/**
 * Determines if two values are equal according to FHIRPath equality rules.
 * @param x - The first value.
 * @param y - The second value.
 * @returns True if equal.
 */
export declare function fhirPathEquals(x: TypedValue, y: TypedValue): TypedValue[];

/**
 * Determines if two values are equivalent according to FHIRPath equality rules.
 * @param x - The first value.
 * @param y - The second value.
 * @returns True if equivalent.
 */
export declare function fhirPathEquivalent(x: TypedValue, y: TypedValue): TypedValue[];

/**
 * Determines if the typed value is the desired type.
 * @param typedValue - The typed value to check.
 * @param desiredType - The desired type name.
 * @returns True if the typed value is of the desired type.
 */
export declare function fhirPathIs(typedValue: TypedValue, desiredType: string): boolean;

/**
 * Returns a negated FHIRPath boolean expression.
 * @param input - The input array.
 * @returns The negated type value array.
 */
export declare function fhirPathNot(input: TypedValue[]): TypedValue[];

export declare const fhirTypeToJsType: {
    readonly base64Binary: "string";
    readonly boolean: "boolean";
    readonly canonical: "string";
    readonly code: "string";
    readonly date: "string";
    readonly dateTime: "string";
    readonly decimal: "number";
    readonly id: "string";
    readonly instant: "string";
    readonly integer: "number";
    readonly integer64: "string";
    readonly markdown: "string";
    readonly oid: "string";
    readonly positiveInt: "number";
    readonly string: "string";
    readonly time: "string";
    readonly unsignedInt: "number";
    readonly uri: "string";
    readonly url: "string";
    readonly uuid: "string";
    readonly xhtml: "string";
    readonly 'http://hl7.org/fhirpath/System.String': "string";
};

export declare class FileBuilder {
    private readonly indent;
    private readonly b;
    indentCount: number;
    constructor(indent?: string, header?: boolean);
    newLine(): void;
    appendNoWrap(line: string): void;
    append(line: string): void;
    toString(): string;
}

export declare interface Filter {
    code: string;
    operator: Operator;
    value: string;
}

/**
 * Tries to find an observation interval for the given patient and value.
 * @param definition - The observation definition.
 * @param patient - The patient.
 * @param value - The observation value.
 * @param category - Optional interval category restriction.
 * @returns The observation interval if found; otherwise undefined.
 */
export declare function findObservationInterval(definition: ObservationDefinition, patient: Patient, value: number, category?: 'reference' | 'critical' | 'absolute'): ObservationDefinitionQualifiedInterval | undefined;

/**
 * Tries to find an observation reference range for the given patient and condition names.
 * @param definition - The observation definition.
 * @param patient - The patient.
 * @param names - Optional condition names.
 * @returns The observation interval if found; otherwise undefined.
 */
export declare function findObservationReferenceRange(definition: ObservationDefinition, patient: Patient, names?: string[]): ObservationDefinitionQualifiedInterval | undefined;

/**
 * Returns all matching observation reference range for the given patient and condition names.
 * @param definition - The observation definition.
 * @param patient - The patient.
 * @param names - Optional condition names.
 * @returns The observation intervals if found; otherwise an empty array.
 */
export declare function findObservationReferenceRanges(definition: ObservationDefinition, patient: Patient, names?: string[]): ObservationDefinitionQualifiedInterval[];

/**
 * Finds the first resource in the input array that matches the specified code and system.
 * @param resources - The array of resources to search.
 * @param code - The code to search for.
 * @param system - The system to search for.
 * @returns The first resource in the input array that matches the specified code and system, or undefined if no such resource is found.
 */
export declare function findResourceByCode(resources: ResourceWithCode[], code: CodeableConcept | string, system: string): ResourceWithCode | undefined;

export declare function flatMapFilter<T, U>(arr: T[] | undefined, fn: (value: T, idx: number) => U | undefined): U[];

export declare const forbidden: OperationOutcome;

/**
 * Formats a FHIR Address as a string.
 * @param address - The address to format.
 * @param options - Optional address format options.
 * @returns The formatted address string.
 */
export declare function formatAddress(address: Address, options?: AddressFormatOptions): string;

/**
 * Formats a CodeableConcept element as a string.
 * @param codeableConcept - A FHIR CodeableConcept element
 * @returns The codeable concept as a string.
 */
export declare function formatCodeableConcept(codeableConcept: CodeableConcept | undefined): string;

/**
 * Formats a Coding element as a string.
 * @param coding - A FHIR Coding element
 * @param includeCode - If true, includes both the code and display if available
 * @returns The coding as a string.
 */
export declare function formatCoding(coding: Coding | undefined, includeCode?: boolean): string;

/**
 * Formats a FHIR date string as a human readable string.
 * Handles missing values and invalid dates.
 * @param date - The date to format.
 * @param locales - Optional locales.
 * @param options - Optional date format options.
 * @returns The formatted date string.
 */
export declare function formatDate(date: string | undefined, locales?: Intl.LocalesArgument, options?: Intl.DateTimeFormatOptions): string;

/**
 * Formats a FHIR dateTime string as a human readable string.
 * Handles missing values and invalid dates.
 * @param dateTime - The dateTime to format.
 * @param locales - Optional locales.
 * @param options - Optional dateTime format options.
 * @returns The formatted dateTime string.
 */
export declare function formatDateTime(dateTime: string | undefined, locales?: Intl.LocalesArgument, options?: Intl.DateTimeFormatOptions): string;

/**
 * Formats the family name portion of a FHIR HumanName element.
 * @param name - The name to format.
 * @returns The formatted family name string.
 */
export declare function formatFamilyName(name: HumanName): string;

/**
 * Formats the given name portion of a FHIR HumanName element.
 * @param name - The name to format.
 * @returns The formatted given name string.
 */
export declare function formatGivenName(name: HumanName): string;

/**
 * Formats an ISO date/time string into an HL7 date/time string.
 * @param isoDate - The ISO date/time string.
 * @returns The HL7 date/time string.
 */
export declare function formatHl7DateTime(isoDate: Date | string): string;

/**
 * Formats a FHIR HumanName as a string.
 * @param name - The name to format.
 * @param options - Optional name format options.
 * @returns The formatted name string.
 */
export declare function formatHumanName(name: HumanName, options?: HumanNameFormatOptions): string;

export declare function formatMoney(money: Money | undefined): string;

/**
 * Formats a FHIR Observation resource value as a string.
 * @param obs - A FHIR Observation resource.
 * @returns A human-readable string representation of the Observation.
 */
export declare function formatObservationValue(obs: Observation | ObservationComponent | undefined): string;

/**
 * Formats a FHIR Period as a human readable string.
 * @param period - The period to format.
 * @param locales - Optional locales.
 * @param options - Optional period format options.
 * @returns The formatted period string.
 */
export declare function formatPeriod(period: Period | undefined, locales?: Intl.LocalesArgument, options?: Intl.DateTimeFormatOptions): string;

/**
 * Returns a human-readable string for a FHIR Quantity datatype, taking into account units and comparators
 * @param quantity - A FHIR Quantity element
 * @param precision - Number of decimal places to display in the rendered quantity values
 * @returns A human-readable string representation of the Quantity
 */
export declare function formatQuantity(quantity: Quantity | undefined, precision?: number): string;

/**
 * Returns a human-readable string for a FHIR Range datatype, taking into account one-sided ranges
 * @param range - A FHIR Range element
 * @param precision - Number of decimal places to display in the rendered quantity values
 * @param exclusive - If true, one-sided ranges will be rendered with the `>` or `<` bounds rather than `>=` or `<=`
 * @returns A human-readable string representation of the Range
 */
export declare function formatRange(range: Range_2 | undefined, precision?: number, exclusive?: boolean): string;

/**
 * Formats a FHIR Reference as a string.
 * @param value - The reference to format.
 * @returns The formatted reference string.
 */
export declare function formatReferenceString(value: Reference | undefined): string;

/**
 * Formats a search definition object into a query string.
 * Note: The return value does not include the resource type.
 * @param definition - The search definition.
 * @returns Formatted URL.
 */
export declare function formatSearchQuery(definition: SearchRequest): string;

/**
 * Formats a FHIR time string as a human readable string.
 * Handles missing values and invalid dates.
 * @param time - The date to format.
 * @param locales - Optional locales.
 * @param options - Optional time format options.
 * @returns The formatted time string.
 */
export declare function formatTime(time: string | undefined, locales?: Intl.LocalesArgument, options?: Intl.DateTimeFormatOptions): string;

/**
 * Formats a FHIR Timing as a human readable string.
 * @param timing - The timing to format.
 * @returns The formatted timing string.
 */
export declare function formatTiming(timing: Timing | undefined): string;

export declare class FunctionAtom implements Atom {
    readonly name: string;
    readonly args: Atom[];
    constructor(name: string, args: Atom[]);
    eval(context: AtomContext, input: TypedValue[]): TypedValue[];
    toString(): string;
}

/**
 * Cross platform random UUID generator
 * Note that this is not intended for production use, but rather for testing
 * This should be replaced when crypto.randomUUID is fully supported
 * See: https://stackoverflow.com/revisions/2117523/28
 * @returns A random UUID.
 */
export declare function generateId(): string;

export declare function getAllDataTypes(): DataTypesMap;

/**
 * Returns an array of  questionnaire answers as a map by link ID.
 * @param response - The questionnaire response resource.
 * @returns Questionnaire answer arrays mapped by link ID.
 */
export declare function getAllQuestionnaireAnswers(response: QuestionnaireResponse): Record<string, QuestionnaireResponseItemAnswer[]>;

/**
 * Tries to find a code string for a given system within a given codeable concept.
 * @param concept - The codeable concept.
 * @param system - The system string.
 * @returns The code if found; otherwise undefined.
 */
export declare function getCodeBySystem(concept: CodeableConcept, system: string): string | undefined;

export declare function getDataType(type: string, profileUrl?: string): InternalTypeSchema;

/**
 * Returns a Date property as a Date.
 * When working with JSON objects, Dates are often serialized as ISO-8601 strings.
 * When that happens, we need to safely convert to a proper Date object.
 * @param date - The date property value, which could be a string or a Date object.
 * @returns A Date object.
 */
export declare function getDateProperty(date: string | undefined): Date | undefined;

export declare function getDefaultValuesForNewSliceEntry(key: string, slice: SliceDefinition, slicing: SlicingRules, schema: InternalTypeSchema): Resource;

/**
 * Returns a display string for the resource.
 * @param resource - The input resource.
 * @returns Human friendly display string.
 */
export declare function getDisplayString(resource: Resource): string;

/**
 * Returns an element definition by type and property name.
 * @param typeName - The type name.
 * @param propertyName - The property name.
 * @param profileUrl - (optional) The URL of the current resource profile
 * @returns The element definition if found.
 */
export declare function getElementDefinition(typeName: string, propertyName: string, profileUrl?: string): InternalSchemaElement | undefined;

/**
 * Returns an element definition from mapping of elements by property name.
 * @param elements  - A mapping of property names to element definitions
 * @param propertyName - The property name of interest
 * @returns The element definition if found.
 */
export declare function getElementDefinitionFromElements(elements: InternalTypeSchema['elements'], propertyName: string): InternalSchemaElement | undefined;

/**
 * Returns the type name for an ElementDefinition.
 * @param elementDefinition - The element definition.
 * @returns The Medplum type name.
 */
export declare function getElementDefinitionTypeName(elementDefinition: ElementDefinition): string;

export declare function getExpressionForResourceType(resourceType: string, expression: string): string | undefined;

export declare function getExpressionsForResourceType(resourceType: string, expression: string): Atom[];

/**
 * Returns an extension by extension URLs.
 * @param resource - The base resource.
 * @param urls - Array of extension URLs. Each entry represents a nested extension.
 * @returns The extension object if found; undefined otherwise.
 */
export declare function getExtension(resource: any, ...urls: string[]): Extension | undefined;

/**
 * Returns an extension value by extension URLs.
 * @param resource - The base resource.
 * @param urls - Array of extension URLs.  Each entry represents a nested extension.
 * @returns The extension value if found; undefined otherwise.
 */
export declare function getExtensionValue(resource: any, ...urls: string[]): ExtensionValue | undefined;

/**
 * Returns the resource identifier for the given system.
 *
 * If multiple identifiers exist with the same system, the first one is returned.
 *
 * If the system is not found, then returns undefined.
 * @param resource - The resource to check.
 * @param system - The identifier system.
 * @returns The identifier value if found; otherwise undefined.
 */
export declare function getIdentifier(resource: Resource, system: string): string | undefined;

/**
 * Returns an image URL for the resource, if one is available.
 * @param resource - The input resource.
 * @returns The image URL for the resource or undefined.
 */
export declare function getImageSrc(resource: Resource): string | undefined;

export declare function getNestedProperty(value: TypedValueWithPath | undefined, key: string, options: {
    profileUrl?: string;
    withPath: true;
}): (TypedValueWithPath | TypedValueWithPath[])[];

export declare function getNestedProperty(value: TypedValue | undefined, key: string, options?: {
    profileUrl?: string;
    withPath?: false;
}): (TypedValue | TypedValue[] | undefined)[];

/**
 * Returns the difference between two paths which is often suitable to use as a key in a `Record<string, InternalSchemaElement>`
 * @param parentPath - The parent path that will be removed from `path`.
 * @param path - The element path that should be a child of `parentPath`.
 * @returns - The difference between `path` and `parentPath` or `undefined` if `path` is not a child of `parentPath`.
 */
export declare function getPathDifference(parentPath: string, path: string): string | undefined;

/**
 * Returns a human friendly display name for a FHIR element definition path.
 * @param path - The FHIR element definition path.
 * @returns The best guess of the display name.
 */
export declare function getPathDisplayName(path: string): string;

/**
 * Returns a human friendly display name for a FHIR element property or slice name
 * @param propertyName - The FHIR element property or slice name
 * @returns The best guess of the display name.
 */
export declare function getPropertyDisplayName(propertyName: string): string;

/**
 * Converts the given `query` to a string.
 *
 * @param query - The query to convert. The type can be any member of `QueryTypes`.
 * @returns The query as a string.
 */
export declare function getQueryString(query: QueryTypes): string;

/**
 * Returns all questionnaire answers as a map by link ID.
 * @param response - The questionnaire response resource.
 * @returns Questionnaire answers mapped by link ID.
 */
export declare function getQuestionnaireAnswers(response: QuestionnaireResponse): Record<string, QuestionnaireResponseItemAnswer>;

/**
 * Returns a cryptographically secure random string.
 * @returns A cryptographically secure random string.
 */
export declare function getRandomString(): string;

/**
 * Returns a reference string for a resource.
 * @param input - The FHIR resource or reference.
 * @returns A reference string of the form resourceType/id.
 */
export declare function getReferenceString(input: (Reference & {
    reference: string;
}) | WithId<Resource>): string;

export declare function getReferenceString(input: Reference | Resource): string | undefined;

/**
 * Returns an array of all resource types.
 * Note that this is based on globalSchema, and will only return resource types that are currently in memory.
 * @returns An array of all resource types.
 */
export declare function getResourceTypes(): ResourceType[];

/**
 * Returns a search parameter for a resource type by search code.
 * @param resourceType - The FHIR resource type.
 * @param code - The search parameter code.
 * @returns The search parameter if found, otherwise undefined.
 */
export declare function getSearchParameter(resourceType: string, code: string): SearchParameter | undefined;

/**
 * Returns the type details of a SearchParameter.
 *
 * The SearchParameter resource has a "type" parameter, but that is missing some critical information.
 *
 * For example:
 *   1) The "date" type includes "date", "datetime", and "period".
 *   2) The "token" type includes enums and booleans.
 *   3) Arrays/multiple values are not reflected at all.
 * @param resourceType - The root resource type.
 * @param searchParam - The search parameter.
 * @returns The search parameter type details.
 */
export declare function getSearchParameterDetails(resourceType: string, searchParam: SearchParameter): SearchParameterDetails;

/**
 * Returns the search parameters for the resource type indexed by search code.
 * @param resourceType - The resource type.
 * @returns The search parameters for the resource type indexed by search code.
 */
export declare function getSearchParameters(resourceType: string): Record<string, SearchParameter> | undefined;

export declare function getStatus(outcome: OperationOutcome): number;

/**
 * Returns the value of the property and the property type.
 * Some property definitions support multiple types.
 * For example, "Observation.value[x]" can be "valueString", "valueInteger", "valueQuantity", etc.
 * According to the spec, there can only be one property for a given element definition.
 * This function returns the value and the type.
 * @param input - The base context (FHIR resource or backbone element).
 * @param path - The property path.
 * @param options - (optional) Additional options
 * @returns The value of the property and the property type.
 */
export declare function getTypedPropertyValue(input: TypedValue, path: string, options?: GetTypedPropertyValueOptions): TypedValue[] | TypedValue | undefined;

export declare interface GetTypedPropertyValueOptions {
    /** (optional) URL of a resource profile for type resolution */
    profileUrl?: string;
}

/**
 * Returns the value of the property and the property type using a type schema.
 * Note that because the type schema is not available, this function may be inaccurate.
 * In some cases, that is the desired behavior.
 * @param typedValue - The base context (FHIR resource or backbone element).
 * @param path - The property path.
 * @returns The value of the property and the property type.
 */
export declare function getTypedPropertyValueWithoutSchema(typedValue: TypedValue, path: string): TypedValue[] | TypedValue | undefined;

export declare function getTypedPropertyValueWithPath(input: TypedValue | TypedValueWithPath, path: string, options?: GetTypedPropertyValueOptions): TypedValueWithPath[] | TypedValueWithPath;

/**
 * Returns the value of the property and the property type using a type schema.
 * @param typedValue - The base context (FHIR resource or backbone element).
 * @param path - The property path.
 * @param element - The property element definition.
 * @returns The value of the property and the property type.
 */
export declare function getTypedPropertyValueWithSchema(typedValue: TypedValue, path: string, element: InternalSchemaElement): TypedValue[] | TypedValue | undefined;

export declare function getValueSliceName(value: any, slices: SliceDefinitionWithTypes[], discriminators: SliceDiscriminator[], profileUrl: string | undefined): string | undefined;

/**
 * Concatenates a given base URL and path, ensuring the URL has the appropriate `ws://` or `wss://` protocol instead of `http://` or `https://`.
 *
 * @param baseUrl - The base URL.
 * @param path - The URL to concat. Can be relative or absolute.
 * @returns The concatenated WebSocket URL.
 */
export declare function getWebSocketUrl(baseUrl: URL | string, path: string): string;

/**
 * Global schema singleton.
 */
export declare const globalSchema: IndexedStructureDefinition;

export declare const gone: OperationOutcome;

export declare interface GoogleCredentialResponse {
    readonly clientId: string;
    readonly credential: string;
}

export declare interface GoogleLoginRequest extends BaseLoginRequest {
    readonly googleClientId: string;
    readonly googleCredential: string;
    readonly createUser?: boolean;
}

/**
 * The Hl7Context class represents the parsing context for an HL7 message.
 *
 * @see MSH-1: https://hl7-definition.caristix.com/v2/HL7v2.6/Fields/MSH.1
 * @see MSH-2: https://hl7-definition.caristix.com/v2/HL7v2.6/Fields/MSH.2
 * @see See this tutorial on MSH, and why it's a bad idea to use anything other than the default values: https://www.hl7soup.com/HL7TutorialMSH.html
 */
export declare class Hl7Context {
    readonly segmentSeparator: string;
    readonly fieldSeparator: string;
    readonly componentSeparator: string;
    readonly repetitionSeparator: string;
    readonly escapeCharacter: string;
    readonly subcomponentSeparator: string;
    constructor(segmentSeparator?: string, fieldSeparator?: string, componentSeparator?: string, repetitionSeparator?: string, escapeCharacter?: string, subcomponentSeparator?: string);
    /**
     * Returns the MSH-1 field value based on the configured separators.
     * @returns The HL7 MSH-1 field value.
     */
    getMsh1(): string;
    /**
     * Returns the MSH-2 field value based on the configured separators.
     * @returns The HL7 MSH-2 field value.
     */
    getMsh2(): string;
}

export declare interface Hl7DateParseOptions {
    /**
     * Default timezone offset.
     * Example: "-0500"
     */
    tzOffset?: string;
}

/**
 * The Hl7Field class represents one HL7 field.
 * A field is a collection of components.
 */
export declare class Hl7Field {
    readonly context: Hl7Context;
    readonly components: string[][];
    /**
     * Creates a new HL7 field.
     * @param components - The HL7 components.
     * @param context - Optional HL7 parsing context.
     */
    constructor(components: string[][], context?: Hl7Context);
    /**
     * Returns an HL7 component by index.
     * @param component - The component index.
     * @param subcomponent - Optional subcomponent index.
     * @param repetition - Optional repetition index.
     * @returns The string value of the specified component.
     * @deprecated Use getComponent() instead. This method will be removed in a future release.
     */
    get(component: number, subcomponent?: number, repetition?: number): string;
    /**
     * Returns an HL7 component by index.
     *
     * Note that the index is 1-based, not 0-based.
     *
     * For example, to get the first component, use `getComponent(1)`.
     *
     * This aligns with HL7 component names such as MSH.9.2.
     *
     * @param component - The component index.
     * @param subcomponent - Optional subcomponent index.
     * @param repetition - Optional repetition index.
     * @returns The string value of the specified component.
     */
    getComponent(component: number, subcomponent?: number, repetition?: number): string;
    /**
     * Returns the HL7 field as a string.
     * @returns The HL7 field as a string.
     */
    toString(): string;
    /**
     * Parses an HL7 field string into an Hl7Field object.
     * @param text - The HL7 field text.
     * @param context - Optional HL7 parsing context.
     * @returns The parsed HL7 field.
     */
    static parse(text: string, context?: Hl7Context): Hl7Field;
}

/**
 * The Hl7Message class represents one HL7 message.
 * A message is a collection of segments.
 */
export declare class Hl7Message {
    readonly context: Hl7Context;
    readonly segments: Hl7Segment[];
    /**
     * Creates a new HL7 message.
     * @param segments - The HL7 segments.
     * @param context - Optional HL7 parsing context.
     */
    constructor(segments: Hl7Segment[], context?: Hl7Context);
    /**
     * Returns the HL7 message header.
     * @returns The HL7 message header.
     */
    get header(): Hl7Segment;
    /**
     * Returns an HL7 segment by index or by name.
     * @param index - The HL7 segment index or name.
     * @returns The HL7 segment if found; otherwise, undefined.
     * @deprecated Use getSegment() instead. This method will be removed in a future release.
     */
    get(index: number | string): Hl7Segment | undefined;
    /**
     * Returns all HL7 segments of a given name.
     * @param name - The HL7 segment name.
     * @returns An array of HL7 segments with the specified name.
     * @deprecated Use getAllSegments() instead. This method will be removed in a future release.
     */
    getAll(name: string): Hl7Segment[];
    /**
     * Returns an HL7 segment by index or by name.
     *
     * When using a numeric index, the first segment (usually the MSH header segment) is at index 0.
     *
     * When using a string index, this method returns the first segment with the specified name.
     *
     * @param index - The HL7 segment index or name.
     * @returns The HL7 segment if found; otherwise, undefined.
     */
    getSegment(index: number | string): Hl7Segment | undefined;
    /**
     * Returns all HL7 segments of a given name.
     * @param name - The HL7 segment name.
     * @returns An array of HL7 segments with the specified name.
     */
    getAllSegments(name: string): Hl7Segment[];
    /**
     * Returns the HL7 message as a string.
     * @returns The HL7 message as a string.
     */
    toString(): string;
    /**
     * Returns an HL7 "ACK" (acknowledgement) message for this message.
     * @returns The HL7 "ACK" message.
     */
    buildAck(): Hl7Message;
    private buildAckMessageType;
    /**
     * Parses an HL7 message string into an Hl7Message object.
     * @param text - The HL7 message text.
     * @returns The parsed HL7 message.
     */
    static parse(text: string): Hl7Message;
}

/**
 * The Hl7Segment class represents one HL7 segment.
 * A segment is a collection of fields.
 * The name field is the first field.
 */
export declare class Hl7Segment {
    readonly context: Hl7Context;
    readonly name: string;
    readonly fields: Hl7Field[];
    /**
     * Creates a new HL7 segment.
     * @param fields - The HL7 fields. The first field is the segment name.
     * @param context - Optional HL7 parsing context.
     */
    constructor(fields: Hl7Field[] | string[], context?: Hl7Context);
    /**
     * Returns an HL7 field by index.
     * @param index - The HL7 field index.
     * @returns The HL7 field.
     * @deprecated Use getSegment() instead. This method includes the segment name in the index, which leads to confusing behavior. This method will be removed in a future release.
     */
    get(index: number): Hl7Field;
    /**
     * Returns an HL7 field by index.
     *
     * Note that the index is 1-based, not 0-based.
     *
     * For example, to get the first field, use `getField(1)`.
     *
     * This aligns with HL7 field names such as PID.1, PID.2, etc.
     *
     * Field zero is the segment name.
     *
     * @param index - The HL7 field index.
     * @returns The HL7 field.
     */
    getField(index: number): Hl7Field;
    /**
     * Returns an HL7 component by field index and component index.
     *
     * This is a shortcut for `getField(field).getComponent(component)`.
     *
     * Note that both indexex are 1-based, not 0-based.
     *
     * For example, to get the first component, use `getComponent(1, 1)`.
     *
     * This aligns with HL7 component names such as MSH.9.2.
     *
     * @param fieldIndex - The HL7 field index.
     * @param component - The component index.
     * @param subcomponent - Optional subcomponent index.
     * @param repetition - Optional repetition index.
     * @returns The string value of the specified component.
     */
    getComponent(fieldIndex: number, component: number, subcomponent?: number, repetition?: number): string;
    /**
     * Returns the HL7 segment as a string.
     * @returns The HL7 segment as a string.
     */
    toString(): string;
    /**
     * Parses an HL7 segment string into an Hl7Segment object.
     * @param text - The HL7 segment text.
     * @param context - Optional HL7 parsing context.
     * @returns The parsed HL7 segment.
     */
    static parse(text: string, context?: Hl7Context): Hl7Segment;
}

export declare const HTTP_HL7_ORG = "http://hl7.org";

export declare const HTTP_TERMINOLOGY_HL7_ORG = "http://terminology.hl7.org";

export declare interface HumanNameFormatOptions {
    all?: boolean;
    prefix?: boolean;
    suffix?: boolean;
    use?: boolean;
}

export declare const ICD10 = "http://hl7.org/fhir/sid/icd-10";

export declare interface IClientStorage {
    getInitPromise?(): Promise<void>;
    clear(): void;
    getString(key: string): string | undefined;
    setString(key: string, value: string | undefined): void;
    getObject<T>(key: string): T | undefined;
    setObject<T>(key: string, value: T): void;
}

/**
 * 6.5.5. implies
 * Returns true if left is true and right is true,
 * true left is false and right true, false or empty
 * true left is empty
 */
export declare class ImpliesAtom extends BooleanInfixOperatorAtom {
    constructor(left: Atom, right: Atom);
    eval(context: AtomContext, input: TypedValue[]): TypedValue[];
}

export declare class InAtom extends BooleanInfixOperatorAtom {
    constructor(left: Atom, right: Atom);
    eval(context: AtomContext, input: TypedValue[]): TypedValue[];
}

export declare interface IncludeTarget {
    resourceType: string;
    searchParam: string;
    targetType?: string;
    modifier?: 'iterate';
}

export declare function indexDefaultSearchParameters(bundle: StructureDefinition[] | Bundle): void;

/**
 * An IndexedStructureDefinition is a lookup-optimized version of a StructureDefinition.
 *
 * StructureDefinition resources contain schema information for other resource types.
 * These schemas can be used to automatically generate user interface elements for
 * resources.
 *
 * However, a StructureDefinition resource is not optimized for realtime lookups.  All
 * resource types, sub types, and property definitions are stored in a flat array of
 * ElementDefinition objects.  Therefore, to lookup the schema for a property (i.e., "Patient.name")
 * requires a linear scan of all ElementDefinition objects
 *
 * A StructureDefinition resource contains information about one or more types.
 * For example, the "Patient" StructureDefinition includes "Patient", "Patient_Contact",
 * "Patient_Communication", and "Patient_Link".  This is inefficient.
 *
 * Instead, we create an indexed version of the StructureDefinition, called IndexedStructureDefinition.
 * In an IndexedStructureDefinition, retrieving a property definition is a hashtable lookup.
 *
 * The hierarchy is:
 *   IndexedStructureDefinition - top level for one resource type
 *   TypeSchema - one per resource type and all contained BackboneElements
 *   PropertySchema - one per property/field
 */
export declare interface IndexedStructureDefinition {
    types: Record<string, TypeInfo>;
}

export declare class IndexerAtom implements Atom {
    readonly left: Atom;
    readonly expr: Atom;
    constructor(left: Atom, expr: Atom);
    eval(context: AtomContext, input: TypedValue[]): TypedValue[];
    toString(): string;
}

/**
 * Indexes a SearchParameter resource for fast lookup.
 * Indexes by SearchParameter.code, which is the query string parameter name.
 * @param searchParam - The SearchParameter resource.
 * @see {@link IndexedStructureDefinition} for more details on indexed StructureDefinitions.
 */
export declare function indexSearchParameter(searchParam: SearchParameter): void;

/**
 * Indexes a bundle of SearchParameter resources for faster lookup.
 * @param bundle - A FHIR bundle SearchParameter resources.
 * @see {@link IndexedStructureDefinition} for more details on indexed StructureDefinitions.
 */
export declare function indexSearchParameterBundle(bundle: Bundle<SearchParameter>): void;

/**
 * Parses and indexes structure definitions
 * @param bundle - Bundle or array of structure definitions to be parsed and indexed
 */
export declare function indexStructureDefinitionBundle(bundle: StructureDefinition[] | Bundle): void;

export declare abstract class InfixOperatorAtom implements Atom {
    readonly operator: string;
    readonly left: Atom;
    readonly right: Atom;
    constructor(operator: string, left: Atom, right: Atom);
    abstract eval(context: AtomContext, input: TypedValue[]): TypedValue[];
    toString(): string;
}

export declare interface InfixParselet {
    precedence: number;
    parse?(parser: Parser, left: Atom, token: Token): Atom;
}

export declare function inflateBaseSchema(base: BaseSchema): DataTypesMap;

export declare function inflateElement(path: string, partial: Partial<InternalSchemaElement>): InternalSchemaElement;

export declare function initFhirPathParserBuilder(): ParserBuilder;

export declare interface InternalSchemaElement {
    description: string;
    path: string;
    min: number;
    max: number;
    isArray?: boolean;
    constraints?: Constraint[];
    type: ElementType[];
    slicing?: SlicingRules;
    fixed?: TypedValue;
    pattern?: TypedValue;
    binding?: ElementDefinitionBinding;
}

/**
 * Internal representation of a non-primitive FHIR type, suitable for use in resource validation
 */
export declare interface InternalTypeSchema {
    name: string;
    type: string;
    path: string;
    title?: string;
    url?: string;
    version?: string;
    kind?: string;
    description?: string;
    elements: Record<string, InternalSchemaElement>;
    constraints?: Constraint[];
    parentType?: InternalTypeSchema;
    innerTypes: InternalTypeSchema[];
    summaryProperties?: Set<string>;
    mandatoryProperties?: Set<string>;
}

export declare interface InviteRequest {
    resourceType: 'Patient' | 'Practitioner' | 'RelatedPerson';
    firstName: string;
    lastName: string;
    email?: string;
    externalId?: string;
    password?: string;
    sendEmail?: boolean;
    membership?: Partial<ProjectMembership>;
    upsert?: boolean;
    /** @deprecated Use membership.accessPolicy instead. */
    accessPolicy?: Reference<AccessPolicy>;
    /** @deprecated Use membership.access instead. */
    access?: ProjectMembershipAccess[];
    /** @deprecated Use membership.admin instead. */
    admin?: boolean;
}

export declare interface IReconnectingWebSocket extends TypedEventTarget<WebSocketEventMap_2> {
    readyState: number;
    close(code?: number, reason?: string): void;
    send(message: string): void;
    reconnect(code?: number, reason?: string): void;
}

export declare interface IReconnectingWebSocketCtor {
    new (url: string, protocols?: ProtocolsProvider, options?: Options): IReconnectingWebSocket;
}

export declare function isAccepted(outcome: OperationOutcome): boolean;

export declare class IsAtom extends BooleanInfixOperatorAtom {
    constructor(left: Atom, right: Atom);
    eval(context: AtomContext, input: TypedValue[]): TypedValue[];
}

/**
 * Returns true if the input value is a CodeableConcept object.
 * This is a heuristic check based on the presence of the "coding" property.
 * @param value - The candidate value.
 * @returns True if the input value is a CodeableConcept.
 */
export declare function isCodeableConcept(value: unknown): value is CodeableConcept & {
    coding: Coding[];
};

/**
 * Returns true if the input value is a Coding object.
 * This is a heuristic check based on the presence of the "code" property.
 * @param value - The candidate value.
 * @returns True if the input value is a Coding.
 */
export declare function isCoding(value: unknown): value is Coding & {
    code: string;
};

export declare function isCompletedSubscriptionRequest(subscriptionRequest: SubscriptionRequest | PendingSubscriptionRequest): subscriptionRequest is SubscriptionRequest;

export declare function isComplexTypeCode(code: string): boolean;

export declare function isConflict(outcome: OperationOutcome): boolean;

export declare function isContextVersionRequired(event: string): event is FhircastEventVersionRequired;

export declare function isCreated(outcome: OperationOutcome): boolean;

export declare function isDataTypeLoaded(type: string): boolean;

/**
 * Returns true if the input value is a YYYY-MM-DD date string.
 * @param input - Unknown input value.
 * @returns True if the input is a date string.
 */
export declare function isDateString(input: unknown): input is string;

/**
 * Returns true if the input value is a YYYY-MM-DDThh:mm:ss.sssZ date/time string.
 * @param input - Unknown input value.
 * @returns True if the input is a date/time string.
 */
export declare function isDateTimeString(input: unknown): input is string;

/**
 * Returns true if the value is empty (null, undefined, empty string, or empty object).
 * @param v - Any value.
 * @returns True if the value is an empty string or an empty object.
 */
export declare function isEmpty(v: unknown): boolean;

/**
 * Checks if a `ResourceType` can be used in a `FHIRcast` context.
 *
 * @param resourceType - A `ResourceType` to test.
 * @returns `true` if this is a resource type associated with `FHIRcast` contexts, otherwise returns `false`.
 */
export declare function isFhircastResourceType(resourceType: FhircastResourceType): boolean;

export declare function isFhirCriteriaMet(subscription: Subscription, currentResource: Resource, getPreviousResource: (currentResource: Resource) => Promise<Resource | undefined>): Promise<boolean>;

export declare function isGone(outcome: OperationOutcome): boolean;

/**
 * Returns true if the token is a JWT.
 * @param token - The potential JWT token.
 * @returns True if the token is a JWT.
 */
export declare function isJwt(token: string): boolean;

export declare function isLowerCase(c: string): boolean;

/**
 * Returns true if the access token was issued by a Medplum server.
 * @param accessToken - An access token of unknown origin.
 * @returns True if the access token was issued by a Medplum server.
 */
export declare function isMedplumAccessToken(accessToken: string): boolean;

export declare function isNotFound(outcome: OperationOutcome): boolean;

/**
 * Returns true if the input is an object.
 * @param obj - The candidate object.
 * @returns True if the input is a non-null non-undefined object.
 */
export declare function isObject(obj: unknown): obj is Record<string, unknown>;

export declare function isOk(outcome: OperationOutcome): boolean;

export declare function isOperationOutcome(value: unknown): value is OperationOutcome;

/**
 * Determines if the input is a Period object.
 * This is heuristic based, as we do not have strong typing at runtime.
 * @param input - The input value.
 * @returns True if the input is a period.
 */
export declare function isPeriod(input: unknown): input is Period;

/**
 * Returns true if the value is a non-empty string, an object with a length property greater than zero, or a non-empty object
 * @param arg - Any value
 * @returns True if the value is a non-empty string, an object with a length property greater than zero, or a non-empty object
 */
export declare function isPopulated<T extends {
    length: number;
} | object>(arg: CanBePopulated | undefined | null): arg is T;

/**
 * Returns true if the type code is a primitive type.
 * @param code - The type code to check.
 * @returns True if the type code is a primitive type.
 */
export declare function isPrimitiveType(code: string): boolean;

export declare function isProfileLoaded(profileUrl: string): boolean;

/**
 * Returns true if the resource is a "ProfileResource".
 * @param resource - The FHIR resource.
 * @returns True if the resource is a "ProfileResource".
 */
export declare function isProfileResource(resource: Resource): resource is ProfileResource;

/**
 * Determines if the input is a Quantity object.
 * This is heuristic based, as we do not have strong typing at runtime.
 * @param input - The input value.
 * @returns True if the input is a quantity.
 */
export declare function isQuantity(input: unknown): input is Quantity;

export declare function isQuantityEquivalent(x: Quantity, y: Quantity): boolean;

export declare function isRedirect(outcome: OperationOutcome): boolean;

/**
 * Type guard to validate that an object is a FHIR reference
 * @param value - The object to check
 * @returns True if the input is of type 'object' and contains property 'reference'
 */
export declare function isReference(value: unknown): value is Reference & {
    reference: string;
};

/**
 * Type guard to validate that an object is a FHIR resource
 * @param value - The object to check
 * @param resourceType - Checks that the resource is of the given type
 * @returns True if the input is of type 'object' and contains property 'resourceType'
 */
export declare function isResource<T extends Resource>(value: unknown, resourceType?: T['resourceType']): value is T;

/**
 * Returns true if the given string is a valid FHIR resource type.
 *
 * @example
 * ```ts
 * isResourceType('Patient'); // true
 * isResourceType('XYZ'); // false
 * ```
 *
 * @param resourceType - The candidate resource type string.
 * @returns True if the resource type is a valid FHIR resource type.
 */
export declare function isResourceType(resourceType: string): boolean;

/**
 * Returns true if the type schema is a non-abstract FHIR resource.
 * @param typeSchema - The type schema to check.
 * @returns True if the type schema is a non-abstract FHIR resource.
 */
export declare function isResourceTypeSchema(typeSchema: InternalTypeSchema): boolean;

export declare function isResourceWithId<T extends Resource>(resource: unknown, resourceType?: T['resourceType']): resource is WithId<T>;

export declare function isSliceDefinitionWithTypes(slice: SliceDefinition): slice is SliceDefinitionWithTypes;

/**
 * Returns true if the input value is a string.
 * @param value - The candidate value.
 * @returns True if the input value is a string.
 */
export declare function isString(value: unknown): value is string;

/**
 * Returns true if the input array is an array of strings.
 * @param arr - Input array.
 * @returns True if the input array is an array of strings.
 */
export declare function isStringArray(arr: any[]): arr is string[];

export declare type IssueSeverity = 'error' | 'fatal' | 'warning' | 'information';

export declare type IssueType = 'structure' | 'invariant' | 'processing';

/**
 * Returns true if the input value is an object with a string text property.
 * This is a heuristic check based on the presence of the "text" property.
 * @param value - The candidate value.
 * @returns True if the input value is a text object.
 */
export declare function isTextObject(value: unknown): value is {
    text: string;
};

/**
 * Returns true if the value is a TypedValue.
 * @param value - The unknown value to check.
 * @returns True if the value is a TypedValue.
 */
export declare function isTypedValue(value: unknown): value is TypedValue;

export declare function isUnauthenticated(outcome: OperationOutcome): boolean;

/**
 * Returns true if the input string is a UUID.
 * @param input - The input string.
 * @returns True if the input string matches the UUID format.
 */
export declare function isUUID(input: string): input is string;

/**
 * Returns true if the given date object is a valid date.
 * Dates can be invalid if created by parsing an invalid string.
 * @param date - A date object.
 * @returns Returns true if the date is a valid date.
 */
export declare function isValidDate(date: Date): boolean;

/**
 * Tests whether a given input is a valid hostname.
 *
 * __NOTE: Does not validate that the input is a valid domain name, only a valid hostname.__
 *
 * @param input - The input to test.
 * @returns True if `input` is a valid hostname, otherwise returns false.
 *
 * ### Valid matches:
 * - foo
 * - foo.com
 * - foo.bar.com
 * - foo.org
 * - foo.bar.co.uk
 * - localhost
 * - LOCALHOST
 * - foo-bar-baz
 * - foo_bar
 * - foobar123
 *
 * ### Invalid matches:
 * - foo.com/bar
 * - https://foo.com
 * - foo_-bar_-
 * - foo | rm -rf /
 */
export declare function isValidHostname(input: string): boolean;

/**
 * Tests that a given version string follows the basic semver pattern of `<int>.<int>.<int>`, which is used for Medplum versions.
 *
 * @param version - A version string that should be tested for valid semver semantics.
 * @returns `true` if `version` is a valid semver version that conforms to the Medplum versioning system, otherwise `false`.
 */
export declare function isValidMedplumSemver(version: string): boolean;

/**
 * Generic interface that an implementation of `WebSocket` must satisfy to be used with `ReconnectingWebSocket`.
 * This is a slightly modified fork of the `WebSocket` global type used in Node.
 *
 * The main key difference is making all the `onclose`, `onerror`, etc. functions have `any[]` args, making `data` in `send()` of type `any`, and making `binaryType` of type string,
 * though the particular implementation should narrow each of these implementation-specific types.
 */
export declare interface IWebSocket {
    binaryType: string;
    readonly bufferedAmount: number;
    readonly extensions: string;
    onclose: ((...args: any[]) => any) | null;
    onerror: ((...args: any[]) => any) | null;
    onmessage: ((...args: any[]) => any) | null;
    onopen: ((...args: any[]) => any) | null;
    readonly protocol: string;
    readonly readyState: number;
    readonly url: string;
    close(code?: number, reason?: string): void;
    send(data: any): void;
    readonly CLOSED: number;
    readonly CLOSING: number;
    readonly CONNECTING: number;
    readonly OPEN: number;
    addEventListener<K extends keyof WebSocketEventMap_2>(type: K, listener: (ev: WebSocketEventMap_2[K]) => any, options?: boolean | AddEventListenerOptions): void;
    addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;
    removeEventListener<K extends keyof WebSocketEventMap_2>(type: K, listener: (ev: WebSocketEventMap_2[K]) => any, options?: boolean | EventListenerOptions): void;
    removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;
}

/**
 * This map exists separately from `WebSocketEventMap`, which is the actual event map used for the `ReconnectingWebSocket` class itself,
 * due to slight difference in the type between the events as we use them, and the events as they exist as global interfaces. We need the global interfaces
 * to be generic enough to satisfy conformant implementations that don't exactly match the events we export and use in `ReconnectingWebSocket` itself.
 */
export declare type IWebSocketEventMap = {
    close: globalThis.CloseEvent;
    error: globalThis.ErrorEvent;
    message: globalThis.MessageEvent;
    open: Event;
};

/**
 * Recognized JWT Claims Set members, any other members may also be present.
 * @see {@link https://github.com/panva/jose/blob/main/src/types.d.ts#L532}
 */
export declare interface JWTPayload {
    /**
     * JWT Issuer
     * @see {@link https://www.rfc-editor.org/rfc/rfc7519#section-4.1.1|RFC7519#section-4.1.1}
     */
    iss?: string;
    /**
     * JWT Subject
     * @see {@link https://www.rfc-editor.org/rfc/rfc7519#section-4.1.2|RFC7519#section-4.1.2}
     */
    sub?: string;
    /**
     * JWT Audience
     * @see {@link https://www.rfc-editor.org/rfc/rfc7519#section-4.1.3|RFC7519#section-4.1.3}
     */
    aud?: string | string[];
    /**
     * JWT ID
     * @see {@link https://www.rfc-editor.org/rfc/rfc7519#section-4.1.7|RFC7519#section-4.1.7}
     */
    jti?: string;
    /**
     * JWT Not Before
     * @see {@link https://www.rfc-editor.org/rfc/rfc7519#section-4.1.5|RFC7519#section-4.1.5}
     */
    nbf?: number;
    /**
     * JWT Expiration Time
     * @see {@link https://www.rfc-editor.org/rfc/rfc7519#section-4.1.4|RFC7519#section-4.1.4}
     */
    exp?: number;
    /**
     * JWT Issued At
     * @see {@link https://www.rfc-editor.org/rfc/rfc7519#section-4.1.6|RFC7519#section-4.1.6}
     */
    iat?: number;
    /** Any other JWT Claim Set member. */
    [propName: string]: unknown;
}

/**
 * Memoizes the result of a parameterless function
 * @param fn - The function to be wrapped
 * @returns The result of the first invocation of the wrapped function
 */
export declare function lazy<T>(fn: () => T): () => T;

export declare class LiteralAtom implements Atom {
    readonly value: TypedValue;
    constructor(value: TypedValue);
    eval(): TypedValue[];
    toString(): string;
}

export declare function loadDataType(sd: StructureDefinition): void;

export declare class Logger {
    readonly write: (msg: string) => void;
    readonly metadata: Record<string, any>;
    readonly options?: LoggerOptions;
    readonly prefix?: string;
    level: LogLevel;
    constructor(write: (msg: string) => void, metadata?: Record<string, any>, level?: LogLevel, options?: LoggerOptions);
    clone(override?: LoggerConfigOverride): Logger;
    private getLoggerConfig;
    error(msg: string, data?: Record<string, any> | Error): void;
    warn(msg: string, data?: Record<string, any> | Error): void;
    info(msg: string, data?: Record<string, any> | Error): void;
    debug(msg: string, data?: Record<string, any> | Error): void;
    log(level: LogLevel, msg: string, data?: Record<string, any> | Error): void;
}

export declare interface LoggerConfig {
    write: (msg: string) => void;
    metadata: Record<string, any>;
    level: LogLevel;
    options?: LoggerOptions;
}

export declare type LoggerConfigOverride = Partial<LoggerConfig>;

export declare interface LoggerOptions {
    prefix?: string;
}

export declare interface LoginAuthenticationResponse {
    readonly login: string;
    readonly mfaRequired?: boolean;
    readonly code?: string;
    readonly memberships?: ProjectMembership[];
}

export declare interface LoginProfileResponse {
    readonly login: string;
    readonly scope: string;
}

export declare interface LoginScopeResponse {
    readonly login: string;
    readonly code: string;
}

export declare interface LoginState {
    readonly project: Reference<Project>;
    readonly profile: Reference<ProfileResource>;
    readonly accessToken: string;
    readonly refreshToken: string;
}

/**
 * Logging level, with greater values representing more detailed logs emitted.
 *
 * The zero value means no server logs will be emitted.
 */
export declare const LogLevel: {
    NONE: number;
    ERROR: number;
    WARN: number;
    INFO: number;
    DEBUG: number;
};

export declare type LogLevel = (typeof LogLevel)[keyof typeof LogLevel];

export declare const LogLevelNames: string[];

export declare const LOINC = "http://loinc.org";

/**
 * LRU cache (least recently used)
 * Source: https://stackoverflow.com/a/46432113
 */
export declare class LRUCache<T> {
    private readonly max;
    private readonly cache;
    constructor(max?: number);
    /**
     * Deletes all values from the cache.
     */
    clear(): void;
    /**
     * Returns the value for the given key.
     * @param key - The key to retrieve.
     * @returns The value if found; undefined otherwise.
     */
    get(key: string): T | undefined;
    /**
     * Sets the value for the given key.
     * @param key - The key to set.
     * @param val - The value to set.
     */
    set(key: string, val: T): void;
    /**
     * Deletes the value for the given key.
     * @param key - The key to delete.
     */
    delete(key: string): void;
    /**
     * Returns the list of all keys in the cache.
     * @returns The array of keys in the cache.
     */
    keys(): IterableIterator<string>;
    private first;
}

/**
 * Email address definition.
 * Compatible with nodemailer Mail.Address.
 */
export declare interface MailAddress {
    readonly name: string;
    readonly address: string;
}

/**
 * Email attachment definition.
 * Compatible with nodemailer Mail.Options.
 */
export declare interface MailAttachment {
    /** String, Buffer or a Stream contents for the attachment */
    readonly content?: string;
    /** path to a file or an URL (data uris are allowed as well) if you want to stream the file instead of including it (better for larger attachments) */
    readonly path?: string;
    /** filename to be reported as the name of the attached file, use of unicode is allowed. If you do not want to use a filename, set this value as false, otherwise a filename is generated automatically */
    readonly filename?: string | false;
    /** optional content type for the attachment, if not set will be derived from the filename property */
    readonly contentType?: string;
}

/**
 * Email destination definition.
 */
export declare type MailDestination = string | MailAddress | string[] | MailAddress[];

/**
 * Email message definition.
 * Compatible with nodemailer Mail.Options.
 */
export declare interface MailOptions {
    /** The e-mail address of the sender. All e-mail addresses can be plain `sender@server.com` or formatted `Sender Name <sender@server.com>` */
    readonly from?: string | MailAddress;
    /** An e-mail address that will appear on the Sender: field */
    readonly sender?: string | MailAddress;
    /** Comma separated list or an array of recipients e-mail addresses that will appear on the To: field */
    readonly to?: MailDestination;
    /** Comma separated list or an array of recipients e-mail addresses that will appear on the Cc: field */
    readonly cc?: MailDestination;
    /** Comma separated list or an array of recipients e-mail addresses that will appear on the Bcc: field */
    readonly bcc?: MailDestination;
    /** An e-mail address that will appear on the Reply-To: field */
    readonly replyTo?: string | MailAddress;
    /** The subject of the e-mail */
    readonly subject?: string;
    /** The plaintext version of the message */
    readonly text?: string;
    /** The HTML version of the message */
    readonly html?: string;
    /** An array of attachment objects */
    readonly attachments?: MailAttachment[];
}

/**
 * Returns a Map of resources from a bundle, using the specified identifier system as the key.
 * @param resourceBundle - The bundle of resources.
 * @param identifierSystem - The identifier system to use for keys.
 * @returns Map of resources keyed by identifier value for the specified system.
 */
export declare function mapByIdentifier<T extends Resource = Resource>(resourceBundle: Bundle<T>, identifierSystem: string): Map<string, T>;

export declare interface Marker {
    index: number;
    line: number;
    column: number;
}

export declare function matchDiscriminant(value: TypedValue | TypedValue[] | undefined, discriminator: SliceDiscriminator, slice: SliceDefinition, elements?: Record<string, InternalSchemaElement>): boolean;

/**
 * Returns true if the value is in the range accounting for precision.
 * @param value - The numeric value.
 * @param range - The numeric range.
 * @param precision - Optional precision in number of digits.
 * @returns True if the value is within the range.
 */
export declare function matchesRange(value: number, range: Range_2, precision?: number): boolean;

/**
 * Determines if the resource matches the search request.
 * @param resource - The resource that was created or updated.
 * @param searchRequest - The subscription criteria as a search request.
 * @returns True if the resource satisfies the search request.
 */
export declare function matchesSearchRequest(resource: Resource, searchRequest: SearchRequest): boolean;

export declare const MEDPLUM_CLI_CLIENT_ID = "medplum-cli";

export declare const MEDPLUM_RELEASES_URL = "https://meta.medplum.com/releases";

export declare const MEDPLUM_VERSION: string;

/**
 * The MedplumClient class provides a client for the Medplum FHIR server.
 *
 * The client can be used in the browser, in a Node.js application, or in a Medplum Bot.
 *
 * The client provides helpful methods for common operations such as:
 *   1. Authenticating
 *   2. Creating resources
 *   3. Reading resources
 *   4. Updating resources
 *   5. Deleting resources
 *   6. Searching
 *   7. Making GraphQL queries
 *
 * The client can also be used to integrate with other FHIR servers. For an example, see the Epic Connection Demo Bot [here](https://github.com/medplum/medplum/tree/main/examples/medplum-demo-bots/src/epic).
 *
 * @example
 * Here is a quick example of how to use the client:
 *
 * ```typescript
 * import { MedplumClient } from '@medplum/core';
 * const medplum = new MedplumClient();
 * ```
 *
 * @example
 * Create a `Patient`:
 *
 * ```typescript
 * const patient = await medplum.createResource({
 *   resourceType: 'Patient',
 *   name: [{
 *     given: ['Alice'],
 *     family: 'Smith'
 *   }]
 * });
 * ```
 *
 * @example
 * Read a `Patient` by ID:
 *
 * ```typescript
 * const patient = await medplum.readResource('Patient', '123');
 * console.log(patient.name[0].given[0]);
 * ```
 *
 * @example
 * Search for a `Patient` by name:
 *
 * ```typescript
 * const bundle = await medplum.search('Patient', 'name=Alice');
 * console.log(bundle.total);
 * ```
 *
 *  <head>
 *    <meta name="algolia:pageRank" content="100" />
 *  </head>
 */
export declare class MedplumClient extends TypedEventTarget<MedplumClientEventMap> {
    private readonly options;
    private readonly fetch;
    private readonly createPdfImpl?;
    private readonly storage;
    private readonly requestCache;
    private readonly cacheTime;
    private readonly baseUrl;
    private readonly fhirBaseUrl;
    private readonly authorizeUrl;
    private readonly tokenUrl;
    private readonly logoutUrl;
    private readonly fhircastHubUrl;
    private readonly defaultHeaders;
    private readonly onUnauthenticated?;
    private readonly autoBatchTime;
    private readonly autoBatchQueue;
    private readonly refreshGracePeriod;
    private subscriptionManager?;
    private medplumServer?;
    private clientId?;
    private clientSecret?;
    private credentialsInHeader;
    private autoBatchTimerId?;
    private accessToken?;
    private accessTokenExpires?;
    private refreshToken?;
    private refreshPromise?;
    private profilePromise?;
    private sessionDetails?;
    private basicAuth?;
    private initPromise;
    private initComplete;
    private keyValueClient?;
    constructor(options?: MedplumClientOptions);
    /**
     * @returns Whether the client has been fully initialized or not. Should always be true unless a custom asynchronous `ClientStorage` was passed into the constructor.
     */
    get isInitialized(): boolean;
    /**
     * Gets a Promise that resolves when async initialization is complete. This is particularly useful for waiting for an async `ClientStorage` and/or authentication to finish.
     * @returns A Promise that resolves when any async initialization of the client is finished.
     */
    getInitPromise(): Promise<void>;
    private attemptResumeActiveLogin;
    /**
     * Returns the current base URL for all API requests.
     * By default, this is set to `https://api.medplum.com/`.
     * This can be overridden by setting the `baseUrl` option when creating the client.
     * @category HTTP
     * @returns The current base URL for all API requests.
     */
    getBaseUrl(): string;
    /**
     * Returns the current authorize URL.
     * By default, this is set to `https://api.medplum.com/oauth2/authorize`.
     * This can be overridden by setting the `authorizeUrl` option when creating the client.
     * @category HTTP
     * @returns The current authorize URL.
     */
    getAuthorizeUrl(): string;
    /**
     * Returns the current token URL.
     * By default, this is set to `https://api.medplum.com/oauth2/token`.
     * This can be overridden by setting the `tokenUrl` option when creating the client.
     * @category HTTP
     * @returns The current token URL.
     */
    getTokenUrl(): string;
    /**
     * Returns the current logout URL.
     * By default, this is set to `https://api.medplum.com/oauth2/logout`.
     * This can be overridden by setting the `logoutUrl` option when creating the client.
     * @category HTTP
     * @returns The current logout URL.
     */
    getLogoutUrl(): string;
    /**
     * Returns the current FHIRcast Hub URL.
     * By default, this is set to `https://api.medplum.com/fhircast/STU3`.
     * This can be overridden by setting the `logoutUrl` option when creating the client.
     * @category HTTP
     * @returns The current FHIRcast Hub URL.
     */
    getFhircastHubUrl(): string;
    /**
     * Returns default headers to include in all requests.
     * This can be used to set custom headers such as Cookies or Authorization headers.
     * @category HTTP
     * @returns Default headers to include in all requests.
     */
    getDefaultHeaders(): Record<string, string>;
    /**
     * Clears all auth state including local storage and session storage.
     * @category Authentication
     */
    clear(): void;
    /**
     * Clears the active login from local storage.
     * Does not clear all local storage (such as other logins).
     * @category Authentication
     */
    clearActiveLogin(): void;
    /**
     * Invalidates any cached values or cached requests for the given URL.
     * @category Caching
     * @param url - The URL to invalidate.
     */
    invalidateUrl(url: URL | string): void;
    /**
     * Invalidates all cached values and flushes the cache.
     * @category Caching
     */
    invalidateAll(): void;
    /**
     * Invalidates all cached search results or cached requests for the given resourceType.
     * @category Caching
     * @param resourceType - The resource type to invalidate.
     */
    invalidateSearches(resourceType: ResourceType): void;
    /**
     * Makes an HTTP GET request to the specified URL.
     *
     * This is a lower level method for custom requests.
     * For common operations, we recommend using higher level methods
     * such as `readResource()`, `search()`, etc.
     * @category HTTP
     * @param url - The target URL.
     * @param options - Optional fetch options.
     * @returns Promise to the response content.
     */
    get<T = any>(url: URL | string, options?: MedplumRequestOptions): ReadablePromise<T>;
    /**
     * Makes an HTTP POST request to the specified URL.
     *
     * This is a lower level method for custom requests.
     * For common operations, we recommend using higher level methods
     * such as `createResource()`.
     * @category HTTP
     * @param url - The target URL.
     * @param body - The content body. Strings and `File` objects are passed directly. Other objects are converted to JSON.
     * @param contentType - The content type to be included in the "Content-Type" header.
     * @param options - Optional fetch options.
     * @returns Promise to the response content.
     */
    post(url: URL | string, body?: any, contentType?: string, options?: MedplumRequestOptions): Promise<any>;
    /**
     * Makes an HTTP PUT request to the specified URL.
     *
     * This is a lower level method for custom requests.
     * For common operations, we recommend using higher level methods
     * such as `updateResource()`.
     * @category HTTP
     * @param url - The target URL.
     * @param body - The content body. Strings and `File` objects are passed directly. Other objects are converted to JSON.
     * @param contentType - The content type to be included in the "Content-Type" header.
     * @param options - Optional fetch options.
     * @returns Promise to the response content.
     */
    put(url: URL | string, body: any, contentType?: string, options?: MedplumRequestOptions): Promise<any>;
    /**
     * Makes an HTTP PATCH request to the specified URL.
     *
     * This is a lower level method for custom requests.
     * For common operations, we recommend using higher level methods
     * such as `patchResource()`.
     * @category HTTP
     * @param url - The target URL.
     * @param operations - Array of JSONPatch operations.
     * @param options - Optional fetch options.
     * @returns Promise to the response content.
     */
    patch(url: URL | string, operations: PatchOperation[], options?: MedplumRequestOptions): Promise<any>;
    /**
     * Makes an HTTP DELETE request to the specified URL.
     *
     *
     * This is a lower level method for custom requests.
     * For common operations, we recommend using higher level methods
     * such as `deleteResource()`.
     * @category HTTP
     * @param url - The target URL.
     * @param options - Optional fetch options.
     * @returns Promise to the response content.
     */
    delete(url: URL | string, options?: MedplumRequestOptions): Promise<any>;
    /**
     * Initiates a new user flow.
     *
     * This method is part of the two different user registration flows:
     * 1) New Practitioner and new Project
     * 2) New Patient registration
     * @category Authentication
     * @param newUserRequest - Register request including email and password.
     * @param options - Optional fetch options.
     * @returns Promise to the authentication response.
     */
    startNewUser(newUserRequest: NewUserRequest, options?: MedplumRequestOptions): Promise<LoginAuthenticationResponse>;
    /**
     * Initiates a new project flow.
     *
     * This requires a partial login from `startNewUser` or `startNewGoogleUser`.
     * @param newProjectRequest - Register request including email and password.
     * @param options - Optional fetch options.
     * @returns Promise to the authentication response.
     */
    startNewProject(newProjectRequest: NewProjectRequest, options?: MedplumRequestOptions): Promise<LoginAuthenticationResponse>;
    /**
     * Initiates a new patient flow.
     *
     * This requires a partial login from `startNewUser` or `startNewGoogleUser`.
     * @param newPatientRequest - Register request including email and password.
     * @param options - Optional fetch options.
     * @returns Promise to the authentication response.
     */
    startNewPatient(newPatientRequest: NewPatientRequest, options?: MedplumRequestOptions): Promise<LoginAuthenticationResponse>;
    /**
     * Initiates a user login flow.
     * @category Authentication
     * @param loginRequest - Login request including email and password.
     * @param options - Optional fetch options.
     * @returns Promise to the authentication response.
     */
    startLogin(loginRequest: EmailPasswordLoginRequest, options?: MedplumRequestOptions): Promise<LoginAuthenticationResponse>;
    /**
     * Tries to sign in with Google authentication.
     * The response parameter is the result of a Google authentication.
     * See: https://developers.google.com/identity/gsi/web/guides/handle-credential-responses-js-functions
     * @category Authentication
     * @param loginRequest - Login request including Google credential response.
     * @param options - Optional fetch options.
     * @returns Promise to the authentication response.
     */
    startGoogleLogin(loginRequest: GoogleLoginRequest, options?: MedplumRequestOptions): Promise<LoginAuthenticationResponse>;
    /**
     * Returns the PKCE code challenge and method.
     * If the login request already includes a code challenge, it is returned.
     * Otherwise, a new PKCE code challenge is generated.
     * @category Authentication
     * @param loginRequest - The original login request.
     * @returns The PKCE code challenge and method.
     */
    ensureCodeChallenge<T extends BaseLoginRequest>(loginRequest: T): Promise<T>;
    /**
     * Signs out the client.
     * This revokes the current token and clears token from the local cache.
     * @category Authentication
     */
    signOut(): Promise<void>;
    /**
     * Tries to sign in the user.
     * Returns true if the user is signed in.
     * This may result in navigating away to the sign in page.
     * @category Authentication
     * @param loginParams - Optional login parameters.
     * @returns The user profile resource if available.
     */
    signInWithRedirect(loginParams?: Partial<BaseLoginRequest>): Promise<ProfileResource | undefined>;
    /**
     * Tries to sign out the user.
     * See: https://docs.aws.amazon.com/cognito/latest/developerguide/logout-endpoint.html
     * @category Authentication
     */
    signOutWithRedirect(): void;
    /**
     * Initiates sign in with an external identity provider.
     * @param authorizeUrl - The external authorization URL.
     * @param clientId - The external client ID.
     * @param redirectUri - The external identity provider redirect URI.
     * @param baseLogin - The Medplum login request.
     * @param pkceEnabled - Whether `PKCE` should be enabled for this external auth request. Defaults to `true`.
     * @category Authentication
     */
    signInWithExternalAuth(authorizeUrl: string, clientId: string, redirectUri: string, baseLogin: BaseLoginRequest, pkceEnabled?: boolean): Promise<void>;
    /**
     * Exchange an external access token for a Medplum access token.
     * @param token - The access token that was generated by the external identity provider.
     * @param clientId - The ID of the `ClientApplication` in your Medplum project that will be making the exchange request.
     * @returns The user profile resource.
     * @category Authentication
     */
    exchangeExternalAccessToken(token: string, clientId?: string): Promise<ProfileResource>;
    /**
     * Builds the external identity provider redirect URI.
     * @param authorizeUrl - The external authorization URL.
     * @param clientId - The external client ID.
     * @param redirectUri - The external identity provider redirect URI.
     * @param loginRequest - The Medplum login request.
     * @param pkceEnabled - Whether `PKCE` should be enabled for this external auth request. Defaults to `true`.
     * @returns The external identity provider redirect URI.
     * @category Authentication
     */
    getExternalAuthRedirectUri(authorizeUrl: string, clientId: string, redirectUri: string, loginRequest: BaseLoginRequest, pkceEnabled?: boolean): string;
    /**
     * Builds a FHIR URL from a collection of URL path components.
     * For example, `fhirUrl('Patient', '123')` returns `fhir/R4/Patient/123`.
     * @category HTTP
     * @param path - The path component of the URL.
     * @returns The well-formed FHIR URL.
     */
    fhirUrl(...path: string[]): URL;
    /**
     * Builds a FHIR search URL from a search query or structured query object.
     * @category HTTP
     * @category Search
     * @param resourceType - The FHIR resource type.
     * @param query - The FHIR search query or structured query object. Can be any valid input to the URLSearchParams() constructor.
     * @returns The well-formed FHIR URL.
     */
    fhirSearchUrl(resourceType: ResourceType, query: QueryTypes): URL;
    /**
     * Sends a FHIR search request.
     *
     * @example
     * Example using a FHIR search string:
     *
     * ```typescript
     * const bundle = await client.search('Patient', 'name=Alice');
     * console.log(bundle);
     * ```
     *
     * @example
     * The return value is a FHIR bundle:
     *
     * ```json
     * {
     *    "resourceType": "Bundle",
     *    "type": "searchset",
     *    "entry": [
     *       {
     *          "resource": {
     *             "resourceType": "Patient",
     *             "name": [
     *                {
     *                   "given": [
     *                      "George"
     *                   ],
     *                   "family": "Washington"
     *                }
     *             ],
     *          }
     *       }
     *    ]
     * }
     * ```
     *
     * @example
     * To query the count of a search, use the summary feature like so:
     *
     * ```typescript
     * const patients = medplum.search('Patient', '_summary=count');
     * ```
     *
     * See FHIR search for full details: https://www.hl7.org/fhir/search.html
     * @category Search
     * @param resourceType - The FHIR resource type.
     * @param query - Optional FHIR search query or structured query object. Can be any valid input to the URLSearchParams() constructor.
     * @param options - Optional fetch options.
     * @returns Promise to the search result bundle.
     */
    search<RT extends ResourceType>(resourceType: RT, query?: QueryTypes, options?: MedplumRequestOptions): ReadablePromise<Bundle<WithId<ExtractResource<RT>>>>;
    /**
     * Sends a FHIR search request for a single resource.
     *
     * This is a convenience method for `search()` that returns the first resource rather than a `Bundle`.
     *
     * @example
     * Example using a FHIR search string:
     *
     * ```typescript
     * const patient = await client.searchOne('Patient', 'identifier=123');
     * console.log(patient);
     * ```
     *
     * The return value is the resource, if available; otherwise, undefined.
     *
     * See FHIR search for full details: https://www.hl7.org/fhir/search.html
     * @category Search
     * @param resourceType - The FHIR resource type.
     * @param query - Optional FHIR search query or structured query object. Can be any valid input to the URLSearchParams() constructor.
     * @param options - Optional fetch options.
     * @returns Promise to the first search result.
     */
    searchOne<RT extends ResourceType>(resourceType: RT, query?: QueryTypes, options?: MedplumRequestOptions): ReadablePromise<WithId<ExtractResource<RT>> | undefined>;
    /**
     * Sends a FHIR search request for an array of resources.
     *
     * This is a convenience method for `search()` that returns the resources as an array rather than a `Bundle`.
     *
     * @example
     * Example using a FHIR search string:
     *
     * ```typescript
     * const patients = await client.searchResources('Patient', 'name=Alice');
     * console.log(patients);
     * ```
     *
     * The return value is an array of resources.
     *
     * See FHIR search for full details: https://www.hl7.org/fhir/search.html
     * @category Search
     * @param resourceType - The FHIR resource type.
     * @param query - Optional FHIR search query or structured query object. Can be any valid input to the URLSearchParams() constructor.
     * @param options - Optional fetch options.
     * @returns Promise to the array of search results.
     */
    searchResources<RT extends ResourceType>(resourceType: RT, query?: QueryTypes, options?: MedplumRequestOptions): ReadablePromise<ResourceArray<WithId<ExtractResource<RT>>>>;
    /**
     * Creates an
     * [async generator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/AsyncGenerator)
     * over a series of FHIR search requests for paginated search results. Each iteration of the generator yields
     * the array of resources on each page. Searches using _offset based pagination are limited to 10,000 records.
     * For larger result sets, _cursor based pagination should be used instead.
     * See: https://www.medplum.com/docs/search/paginated-search#cursor-based-pagination
     *
     * @example
     *
     * ```typescript
     * for await (const page of medplum.searchResourcePages('Patient', { _count: 10 })) {
     *  for (const patient of page) {
     *    console.log(`Processing Patient resource with ID: ${patient.id}`);
     *  }
     * }
     * ```
     *
     * @category Search
     * @param resourceType - The FHIR resource type.
     * @param query - Optional FHIR search query or structured query object. Can be any valid input to the URLSearchParams() constructor.
     * @param options - Optional fetch options.
     * @yields An async generator, where each result is an array of resources for each page.
     */
    searchResourcePages<RT extends ResourceType>(resourceType: RT, query?: QueryTypes, options?: MedplumRequestOptions): AsyncGenerator<ResourceArray<WithId<ExtractResource<RT>>>>;
    /**
     * Searches a ValueSet resource using the "expand" operation.
     * See: https://www.hl7.org/fhir/operation-valueset-expand.html
     * @category Search
     * @param params - The ValueSet expand parameters.
     * @param options - Optional fetch options.
     * @returns Promise to expanded ValueSet.
     */
    valueSetExpand(params: ValueSetExpandParams, options?: MedplumRequestOptions): ReadablePromise<ValueSet>;
    /**
     * Returns a cached resource if it is available.
     * @category Caching
     * @param resourceType - The FHIR resource type.
     * @param id - The FHIR resource ID.
     * @returns The resource if it is available in the cache; undefined otherwise.
     */
    getCached<RT extends ResourceType>(resourceType: RT, id: string): WithId<ExtractResource<RT>> | undefined;
    /**
     * Returns a cached resource if it is available.
     * @category Caching
     * @param reference - The FHIR reference.
     * @returns The resource if it is available in the cache; undefined otherwise.
     */
    getCachedReference<T extends Resource>(reference: Reference<T>): T | undefined;
    /**
     * Reads a resource by resource type and ID.
     *
     * @example
     * Example:
     *
     * ```typescript
     * const patient = await medplum.readResource('Patient', '123');
     * console.log(patient);
     * ```
     *
     * See the FHIR "read" operation for full details: https://www.hl7.org/fhir/http.html#read
     * @category Read
     * @param resourceType - The FHIR resource type.
     * @param id - The resource ID.
     * @param options - Optional fetch options.
     * @returns The resource if available.
     */
    readResource<RT extends ResourceType>(resourceType: RT, id: string, options?: MedplumRequestOptions): ReadablePromise<WithId<ExtractResource<RT>>>;
    /**
     * Reads a resource by `Reference`.
     *
     * This is a convenience method for `readResource()` that accepts a `Reference` object.
     *
     * @example
     * Example:
     *
     * ```typescript
     * const serviceRequest = await medplum.readResource('ServiceRequest', '123');
     * const patient = await medplum.readReference(serviceRequest.subject);
     * console.log(patient);
     * ```
     *
     * See the FHIR "read" operation for full details: https://www.hl7.org/fhir/http.html#read
     * @category Read
     * @param reference - The FHIR reference object.
     * @param options - Optional fetch options.
     * @returns The resource if available.
     */
    readReference<T extends Resource>(reference: Reference<T>, options?: MedplumRequestOptions): ReadablePromise<WithId<T>>;
    /**
     * Requests the schema for a resource type.
     * If the schema is already cached, the promise is resolved immediately.
     * @category Schema
     * @param resourceType - The FHIR resource type.
     * @returns Promise to a schema with the requested resource type.
     */
    requestSchema(resourceType: string): Promise<void>;
    /**
     * Requests the schema for a profile.
     * If the schema is already cached, the promise is resolved immediately.
     * @category Schema
     * @param profileUrl - The FHIR URL of the profile
     * @param options - (optional) Additional options
     * @returns Promise for schema request.
     */
    requestProfileSchema(profileUrl: string, options?: RequestProfileSchemaOptions): Promise<void>;
    /**
     * Reads resource history by resource type and ID.
     *
     * The return value is a bundle of all versions of the resource.
     *
     * @example
     * Example:
     *
     * ```typescript
     * const history = await medplum.readHistory('Patient', '123');
     * console.log(history);
     * ```
     *
     * See the FHIR "history" operation for full details: https://www.hl7.org/fhir/http.html#history
     * @category Read
     * @param resourceType - The FHIR resource type.
     * @param id - The resource ID.
     * @param options - Optional fetch options.
     * @returns Promise to the resource history.
     */
    readHistory<RT extends ResourceType>(resourceType: RT, id: string, options?: MedplumRequestOptions): ReadablePromise<Bundle<WithId<ExtractResource<RT>>>>;
    /**
     * Reads a specific version of a resource by resource type, ID, and version ID.
     *
     * @example
     * Example:
     *
     * ```typescript
     * const version = await medplum.readVersion('Patient', '123', '456');
     * console.log(version);
     * ```
     *
     * See the FHIR "vread" operation for full details: https://www.hl7.org/fhir/http.html#vread
     * @category Read
     * @param resourceType - The FHIR resource type.
     * @param id - The resource ID.
     * @param vid - The version ID.
     * @param options - Optional fetch options.
     * @returns The resource if available.
     */
    readVersion<RT extends ResourceType>(resourceType: RT, id: string, vid: string, options?: MedplumRequestOptions): ReadablePromise<WithId<ExtractResource<RT>>>;
    /**
     * Executes the Patient "everything" operation for a patient.
     *
     * @example
     * Example:
     *
     * ```typescript
     * const bundle = await medplum.readPatientEverything('123');
     * console.log(bundle);
     * ```
     *
     * See the FHIR "patient-everything" operation for full details: https://hl7.org/fhir/operation-patient-everything.html
     * @category Read
     * @param id - The Patient Id
     * @param options - Optional fetch options.
     * @returns A Bundle of all Resources related to the Patient
     */
    readPatientEverything(id: string, options?: MedplumRequestOptions): ReadablePromise<Bundle>;
    /**
     * Executes the Patient "summary" operation for a patient.
     *
     * @example
     * Example:
     *
     * ```typescript
     * const bundle = await medplum.readPatientSummary('123');
     * console.log(bundle);
     * ```
     *
     * See International Patient Summary Implementation Guide: https://build.fhir.org/ig/HL7/fhir-ips/index.html
     *
     * See Patient summary operation: https://build.fhir.org/ig/HL7/fhir-ips/OperationDefinition-summary.html
     *
     * @param id - The Patient ID.
     * @param options - Optional fetch options.
     * @returns A patient summary bundle, organized into the patient summary sections.
     */
    readPatientSummary(id: string, options?: MedplumRequestOptions): ReadablePromise<Bundle>;
    /**
     * Creates a new FHIR resource.
     *
     * The return value is the newly created resource, including the ID and meta.
     *
     * @example
     * Example:
     *
     * ```typescript
     * const result = await medplum.createResource({
     *   resourceType: 'Patient',
     *   name: [{
     *    family: 'Smith',
     *    given: ['John']
     *   }]
     * });
     * console.log(result.id);
     * ```
     *
     * See the FHIR "create" operation for full details: https://www.hl7.org/fhir/http.html#create
     * @category Create
     * @param resource - The FHIR resource to create.
     * @param options - Optional fetch options.
     * @returns The result of the create operation.
     */
    createResource<T extends Resource>(resource: T, options?: MedplumRequestOptions): Promise<WithId<T>>;
    /**
     * Conditionally create a new FHIR resource only if some equivalent resource does not already exist on the server.
     *
     * The return value is the existing resource or the newly created resource, including the ID and meta.
     *
     * @example
     * Example:
     *
     * ```typescript
     * const result = await medplum.createResourceIfNoneExist(
     *   {
     *     resourceType: 'Patient',
     *     identifier: [{
     *      system: 'http://example.com/mrn',
     *      value: '123'
     *     }]
     *     name: [{
     *      family: 'Smith',
     *      given: ['John']
     *     }]
     *   },
     *   'identifier=123'
     * );
     * console.log(result.id);
     * ```
     *
     * This method is syntactic sugar for:
     *
     * ```typescript
     * return searchOne(resourceType, query) ?? createResource(resource);
     * ```
     *
     * The query parameter only contains the search parameters (what would be in the URL following the "?").
     *
     * See the FHIR "conditional create" operation for full details: https://www.hl7.org/fhir/http.html#ccreate
     * @category Create
     * @param resource - The FHIR resource to create.
     * @param query - The search query for an equivalent resource (should not include resource type or "?").
     * @param options - Optional fetch options.
     * @returns The result of the create operation.
     */
    createResourceIfNoneExist<T extends Resource>(resource: T, query: string, options?: MedplumRequestOptions): Promise<WithId<T>>;
    /**
     * Upsert a resource: update it in place if it exists, otherwise create it.  This is done in a single, transactional
     * request to guarantee data consistency.
     * @param resource - The resource to update or create.
     * @param query - A FHIR search query to uniquely identify the resource if it already exists.
     * @param options  - Optional fetch options.
     * @returns The updated/created resource.
     */
    upsertResource<T extends Resource>(resource: T, query: QueryTypes, options?: MedplumRequestOptions): Promise<WithId<T>>;
    /**
     * Creates a FHIR `Attachment` with the provided data content.
     *
     * This is a convenience method for creating a `Binary` resource and then creating an `Attachment` element.
     *
     * The `data` parameter can be a string or a `File` object.
     *
     * A `File` object often comes from a `<input type="file">` element.
     *
     * @example
     * Example:
     *
     * ```typescript
     * const result = await medplum.createAttachment(myFile, 'test.jpg', 'image/jpeg');
     * console.log(result);
     * ```
     *
     * See the FHIR "create" operation for full details: https://www.hl7.org/fhir/http.html#create
     * @category Create
     * @param createBinaryOptions -The binary options. See `CreateBinaryOptions` for full details.
     * @param requestOptions - Optional fetch options. **NOTE:** only `options.signal` is respected when `onProgress` is also provided.
     * @returns The result of the create operation.
     */
    createAttachment(createBinaryOptions: CreateBinaryOptions, requestOptions?: MedplumRequestOptions): Promise<Attachment>;
    /**
     * @category Create
     * @param data - The binary data to upload.
     * @param filename - Optional filename for the binary.
     * @param contentType - Content type for the binary.
     * @param onProgress - Optional callback for progress events. **NOTE:** only `options.signal` is respected when `onProgress` is also provided.
     * @param options - Optional fetch options. **NOTE:** only `options.signal` is respected when `onProgress` is also provided.
     * @returns The result of the create operation.
     * @deprecated Use `createAttachment` with `CreateBinaryOptions` instead. To be removed in a future version.
     */
    createAttachment(data: BinarySource, filename: string | undefined, contentType: string, onProgress?: (e: ProgressEvent) => void, options?: MedplumRequestOptions): Promise<Attachment>;
    /**
     * Creates a FHIR `Binary` resource with the provided data content.
     *
     * The return value is the newly created resource, including the ID and meta.
     *
     * The `data` parameter can be a string or a `File` object.
     *
     * A `File` object often comes from a `<input type="file">` element.
     *
     * @example
     * Example:
     *
     * ```typescript
     * const result = await medplum.createBinary(myFile, 'test.jpg', 'image/jpeg');
     * console.log(result.id);
     * ```
     *
     * See the FHIR "create" operation for full details: https://www.hl7.org/fhir/http.html#create
     *
     * @category Create
     * @param createBinaryOptions -The binary options. See `CreateBinaryOptions` for full details.
     * @param requestOptions - Optional fetch options. **NOTE:** only `options.signal` is respected when `onProgress` is also provided.
     * @returns The result of the create operation.
     */
    createBinary(createBinaryOptions: CreateBinaryOptions, requestOptions?: MedplumRequestOptions): Promise<WithId<Binary>>;
    /**
     * @category Create
     * @param data - The binary data to upload.
     * @param filename - Optional filename for the binary.
     * @param contentType - Content type for the binary.
     * @param onProgress - Optional callback for progress events. **NOTE:** only `options.signal` is respected when `onProgress` is also provided.
     * @param options - Optional fetch options. **NOTE:** only `options.signal` is respected when `onProgress` is also provided.
     * @returns The result of the create operation.
     * @deprecated Use `createBinary` with `CreateBinaryOptions` instead. To be removed in a future version.
     */
    createBinary(data: BinarySource, filename: string | undefined, contentType: string, onProgress?: (e: ProgressEvent) => void, options?: MedplumRequestOptions): Promise<WithId<Binary>>;
    uploadwithProgress(url: URL, data: BinarySource, contentType: string, onProgress: (e: ProgressEvent) => void, options?: MedplumRequestOptions): Promise<any>;
    /**
     * Creates a PDF as a FHIR `Binary` resource based on pdfmake document definition.
     *
     * The return value is the newly created resource, including the ID and meta.
     *
     * The `docDefinition` parameter is a pdfmake document definition.
     *
     * @example
     * Example:
     *
     * ```typescript
     * const result = await medplum.createPdf({
     *   content: ['Hello world']
     * });
     * console.log(result.id);
     * ```
     *
     * See the pdfmake document definition for full details: https://pdfmake.github.io/docs/0.1/document-definition-object/
     * @category Media
     * @param createPdfOptions - The PDF creation options. See `CreatePdfOptions` for full details.
     * @param requestOptions - Optional fetch options.
     * @returns The result of the create operation.
     */
    createPdf(createPdfOptions: CreatePdfOptions, requestOptions?: MedplumRequestOptions): Promise<WithId<Binary>>;
    /**
     * @category Media
     * @param docDefinition - The PDF document definition.
     * @param filename - Optional filename for the PDF binary resource.
     * @param tableLayouts - Optional pdfmake custom table layout.
     * @param fonts - Optional pdfmake custom font dictionary.
     * @returns The result of the create operation.
     * @deprecated Use `createPdf` with `CreatePdfOptions` instead. To be removed in a future version.
     */
    createPdf(docDefinition: TDocumentDefinitions, filename: string | undefined, tableLayouts?: Record<string, CustomTableLayout>, fonts?: TFontDictionary): Promise<WithId<Binary>>;
    /**
     * Creates a FHIR `Communication` resource with the provided data content.
     *
     * This is a convenience method to handle common cases where a `Communication` resource is created with a `payload`.
     * @category Create
     * @param resource - The FHIR resource to comment on.
     * @param text - The text of the comment.
     * @param options - Optional fetch options.
     * @returns The result of the create operation.
     */
    createComment(resource: Resource, text: string, options?: MedplumRequestOptions): Promise<WithId<Communication>>;
    /**
     * Updates a FHIR resource.
     *
     * The return value is the updated resource, including the ID and meta.
     *
     * @example
     * Example:
     *
     * ```typescript
     * const result = await medplum.updateResource({
     *   resourceType: 'Patient',
     *   id: '123',
     *   name: [{
     *    family: 'Smith',
     *    given: ['John']
     *   }]
     * });
     * console.log(result.meta.versionId);
     * ```
     *
     * See the FHIR "update" operation for full details: https://www.hl7.org/fhir/http.html#update
     * @category Write
     * @param resource - The FHIR resource to update.
     * @param options - Optional fetch options.
     * @returns The result of the update operation.
     */
    updateResource<T extends Resource>(resource: T, options?: MedplumRequestOptions): Promise<WithId<T>>;
    /**
     * Updates a FHIR resource using JSONPatch operations.
     *
     * The return value is the updated resource, including the ID and meta.
     *
     * @example
     * Example:
     *
     * ```typescript
     * const result = await medplum.patchResource('Patient', '123', [
     *   {op: 'replace', path: '/name/0/family', value: 'Smith'},
     * ]);
     * console.log(result.meta.versionId);
     * ```
     *
     * See the FHIR "update" operation for full details: https://www.hl7.org/fhir/http.html#patch
     *
     * See the JSONPatch specification for full details: https://tools.ietf.org/html/rfc6902
     * @category Write
     * @param resourceType - The FHIR resource type.
     * @param id - The resource ID.
     * @param operations - The JSONPatch operations.
     * @param options - Optional fetch options.
     * @returns The result of the patch operations.
     */
    patchResource<RT extends ResourceType>(resourceType: RT, id: string, operations: PatchOperation[], options?: MedplumRequestOptions): Promise<WithId<ExtractResource<RT>>>;
    /**
     * Deletes a FHIR resource by resource type and ID.
     *
     * @example
     * Example:
     *
     * ```typescript
     * await medplum.deleteResource('Patient', '123');
     * ```
     *
     * See the FHIR "delete" operation for full details: https://www.hl7.org/fhir/http.html#delete
     * @category Delete
     * @param resourceType - The FHIR resource type.
     * @param id - The resource ID.
     * @param options - Optional fetch options.
     * @returns The result of the delete operation.
     */
    deleteResource(resourceType: ResourceType, id: string, options?: MedplumRequestOptions): Promise<any>;
    /**
     * Executes the validate operation with the provided resource.
     *
     * @example
     * Example:
     *
     * ```typescript
     * const result = await medplum.validateResource({
     *   resourceType: 'Patient',
     *   name: [{ given: ['Alice'], family: 'Smith' }],
     * });
     * ```
     *
     * See the FHIR "$validate" operation for full details: https://www.hl7.org/fhir/resource-operation-validate.html
     * @param resource - The FHIR resource.
     * @param options - Optional fetch options.
     * @returns The validate operation outcome.
     */
    validateResource<T extends Resource>(resource: T, options?: MedplumRequestOptions): Promise<OperationOutcome>;
    /**
     * Executes a bot by ID or Identifier.
     * @param idOrIdentifier - The Bot ID or Identifier.
     * @param body - The content body. Strings and `File` objects are passed directly. Other objects are converted to JSON.
     * @param contentType - The content type to be included in the "Content-Type" header.
     * @param options - Optional fetch options.
     * @returns The Bot return value.
     */
    executeBot(idOrIdentifier: string | Identifier, body: any, contentType?: string, options?: MedplumRequestOptions): Promise<any>;
    /**
     * Executes a batch or transaction of FHIR operations.
     *
     * @example
     * Example:
     *
     * ```typescript
     * await medplum.executeBatch({
     *   "resourceType": "Bundle",
     *   "type": "transaction",
     *   "entry": [
     *     {
     *       "fullUrl": "urn:uuid:61ebe359-bfdc-4613-8bf2-c5e300945f0a",
     *       "resource": {
     *         "resourceType": "Patient",
     *         "name": [{ "use": "official", "given": ["Alice"], "family": "Smith" }],
     *         "gender": "female",
     *         "birthDate": "1974-12-25"
     *       },
     *       "request": {
     *         "method": "POST",
     *         "url": "Patient"
     *       }
     *     },
     *     {
     *       "fullUrl": "urn:uuid:88f151c0-a954-468a-88bd-5ae15c08e059",
     *       "resource": {
     *         "resourceType": "Patient",
     *         "identifier": [{ "system": "http:/example.org/fhir/ids", "value": "234234" }],
     *         "name": [{ "use": "official", "given": ["Bob"], "family": "Jones" }],
     *         "gender": "male",
     *         "birthDate": "1974-12-25"
     *       },
     *       "request": {
     *         "method": "POST",
     *         "url": "Patient",
     *         "ifNoneExist": "identifier=http:/example.org/fhir/ids|234234"
     *       }
     *     }
     *   ]
     * });
     * ```
     *
     * See The FHIR "batch/transaction" section for full details: https://hl7.org/fhir/http.html#transaction
     * @category Batch
     * @param bundle - The FHIR batch/transaction bundle.
     * @param options - Optional fetch options.
     * @returns The FHIR batch/transaction response bundle.
     */
    executeBatch(bundle: Bundle, options?: MedplumRequestOptions): Promise<Bundle>;
    /**
     * Sends an email using the Medplum Email API.
     *
     * Builds the email using nodemailer MailComposer.
     *
     * Examples:
     *
     * @example
     * Send a simple text email:
     *
     * ```typescript
     * await medplum.sendEmail({
     *   to: 'alice@example.com',
     *   cc: 'bob@example.com',
     *   subject: 'Hello',
     *   text: 'Hello Alice',
     * });
     * ```
     *
     * @example
     * Send an email with a `Binary` attachment:
     *
     * ```typescript
     * await medplum.sendEmail({
     *   to: 'alice@example.com',
     *   subject: 'Email with attachment',
     *   text: 'See the attached report',
     *   attachments: [{
     *     filename: 'report.pdf',
     *     path: "Binary/" + binary.id
     *   }]
     * });
     * ```
     *
     * See options here: https://nodemailer.com/extras/mailcomposer/
     * @category Media
     * @param email - The MailComposer options.
     * @param options - Optional fetch options.
     * @returns Promise to the operation outcome.
     */
    sendEmail(email: MailOptions, options?: MedplumRequestOptions): Promise<OperationOutcome>;
    /**
     * Executes a GraphQL query.
     *
     * @example
     * Example:
     *
     * ```typescript
     * const result = await medplum.graphql(`{
     *   Patient(id: "123") {
     *     resourceType
     *     id
     *     name {
     *       given
     *       family
     *     }
     *   }
     * }`);
     * ```
     *
     * @example
     * Advanced queries such as named operations and variable substitution are supported:
     *
     * ```typescript
     * const result = await medplum.graphql(
     *   `query GetPatientById($patientId: ID!) {
     *     Patient(id: $patientId) {
     *       resourceType
     *       id
     *       name {
     *         given
     *         family
     *       }
     *     }
     *   }`,
     *   'GetPatientById',
     *   { patientId: '123' }
     * );
     * ```
     *
     * See the GraphQL documentation for more details: https://graphql.org/learn/
     *
     * See the FHIR GraphQL documentation for FHIR specific details: https://www.hl7.org/fhir/graphql.html
     * @category Read
     * @param query - The GraphQL query.
     * @param operationName - Optional GraphQL operation name.
     * @param variables - Optional GraphQL variables.
     * @param options - Optional fetch options.
     * @returns The GraphQL result.
     */
    graphql(query: string, operationName?: string | null, variables?: any, options?: MedplumRequestOptions): Promise<any>;
    /**
     * Executes the $graph operation on this resource to fetch a Bundle of resources linked to the target resource
     * according to a graph definition
     * @category Read
     * @param resourceType - The FHIR resource type.
     * @param id - The resource ID.
     * @param graphName - `name` parameter of the GraphDefinition
     * @param options - Optional fetch options.
     * @returns A Bundle
     */
    readResourceGraph(resourceType: ResourceType, id: string, graphName: string, options?: MedplumRequestOptions): ReadablePromise<Bundle>;
    /**
     * Pushes a message to an agent.
     *
     * @param agent - The agent to push to.
     * @param destination - The destination device.
     * @param body - The message body.
     * @param contentType - Optional message content type.
     * @param waitForResponse - Optional wait for response flag.
     * @param options - Optional fetch options.
     * @returns Promise to the result. If waiting for response, the result is the response body. Otherwise, it is an operation outcome.
     */
    pushToAgent(agent: Agent | Reference<Agent>, destination: Device | Reference<Device> | string, body: any, contentType?: string, waitForResponse?: boolean, options?: MedplumRequestOptions): Promise<any>;
    /**
     * @category Authentication
     * @returns The Login State
     */
    getActiveLogin(): LoginState | undefined;
    /**
     * Sets the active login.
     * @param login - The new active login state.
     * @category Authentication
     */
    setActiveLogin(login: LoginState): Promise<void>;
    /**
     * Returns the current access token.
     * @returns The current access token.
     * @category Authentication
     */
    getAccessToken(): string | undefined;
    /**
     * Returns whether the client has a valid access token or not.
     * @param gracePeriod - Optional grace period in milliseconds. If not specified, uses the client configured grace period (default 5 minutes).
     * @returns Boolean indicating whether or not the client is authenticated.
     *
     * **NOTE: Does not check whether the auth token has been revoked server-side.**
     */
    isAuthenticated(gracePeriod?: number): boolean;
    /**
     * Sets the current access token.
     * @param accessToken - The new access token.
     * @param refreshToken - Optional refresh token.
     * @category Authentication
     */
    setAccessToken(accessToken: string, refreshToken?: string): void;
    /**
     * Returns the list of available logins.
     * @returns The list of available logins.
     * @category Authentication
     */
    getLogins(): LoginState[];
    private addLogin;
    private refreshProfile;
    /**
     * Returns true if the client is waiting for initial authentication.
     * @returns True if the client is waiting for initial authentication.
     * @category Authentication
     */
    isLoading(): boolean;
    /**
     * Returns true if the current user is authenticated as a super admin.
     * @returns True if the current user is authenticated as a super admin.
     * @category Authentication
     */
    isSuperAdmin(): boolean;
    /**
     * Returns true if the current user is authenticated as a project admin.
     * @returns True if the current user is authenticated as a project admin.
     * @category Authentication
     */
    isProjectAdmin(): boolean;
    /**
     * Returns the current project if available.
     * @returns The current project if available.
     * @category User Profile
     */
    getProject(): Project | undefined;
    /**
     * Returns the current project membership if available.
     * @returns The current project membership if available.
     * @category User Profile
     */
    getProjectMembership(): ProjectMembership | undefined;
    /**
     * Returns the current user profile resource if available.
     * This method does not wait for loading promises.
     * @returns The current user profile resource if available.
     * @category User Profile
     */
    getProfile(): ProfileResource | undefined;
    /**
     * Returns the current user profile resource, retrieving form the server if necessary.
     * This method waits for loading promises.
     * @returns The current user profile resource.
     * @category User Profile
     */
    getProfileAsync(): Promise<WithId<ProfileResource> | undefined>;
    /**
     * Returns the current user configuration if available.
     * @returns The current user configuration if available.
     * @category User Profile
     */
    getUserConfiguration(): WithId<UserConfiguration> | undefined;
    /**
     * Returns the current user access policy if available.
     * @returns The current user access policy if available.
     * @category User Profile
     */
    getAccessPolicy(): AccessPolicy | undefined;
    /**
     * Downloads the URL as a blob. Can accept binary URLs in the form of `Binary/{id}` as well.
     * @category Read
     * @param url - The URL to request. Can be a standard URL or one in the form of `Binary/{id}`.
     * @param options - Optional fetch request init options.
     * @returns Promise to the response body as a blob.
     */
    download(url: URL | string, options?: MedplumRequestOptions): Promise<Blob>;
    /**
     * Creates a FHIR Media resource with the provided data content.
     *
     * @category Create
     * @param createMediaOptions - The media creation options. See `CreateMediaOptions` for full details.
     * @param requestOptions - Optional fetch options.
     * @returns The new media resource.
     */
    createMedia(createMediaOptions: CreateMediaOptions, requestOptions?: MedplumRequestOptions): Promise<Media>;
    /**
     * Upload media to the server and create a Media instance for the uploaded content.
     * @param contents - The contents of the media file, as a string, Uint8Array, File, or Blob.
     * @param contentType - The media type of the content.
     * @param filename - Optional filename for the binary, or extended upload options (see `BinaryUploadOptions`).
     * @param additionalFields - Additional fields for Media.
     * @param options - Optional fetch options.
     * @returns Promise that resolves to the created Media
     * @deprecated Use `createMedia` with `CreateMediaOptions` instead. To be removed in a future version.
     */
    uploadMedia(contents: string | Uint8Array | File | Blob, contentType: string, filename: string | undefined, additionalFields?: Partial<Media>, options?: MedplumRequestOptions): Promise<Media>;
    /**
     * Performs Bulk Data Export operation request flow. See The FHIR "Bulk Data Export" for full details: https://build.fhir.org/ig/HL7/bulk-data/export.html#bulk-data-export
     * @param exportLevel - Optional export level. Defaults to system level export. 'Group/:id' - Group of Patients, 'Patient' - All Patients.
     * @param resourceTypes - A string of comma-delimited FHIR resource types.
     * @param since - Resources will be included in the response if their state has changed after the supplied time (e.g. if Resource.meta.lastUpdated is later than the supplied _since time).
     * @param options - Optional fetch options.
     * @returns Bulk Data Response containing links to Bulk Data files. See "Response - Complete Status" for full details: https://build.fhir.org/ig/HL7/bulk-data/export.html#response---complete-status
     */
    bulkExport(exportLevel?: string, resourceTypes?: string, since?: string, options?: MedplumRequestOptions): Promise<Partial<BulkDataExport>>;
    /**
     * Starts an async request following the FHIR "Asynchronous Request Pattern".
     * See: https://hl7.org/fhir/r4/async.html
     * @param url - The URL to request.
     * @param options - Optional fetch options.
     * @returns The response body.
     */
    startAsyncRequest<T>(url: string, options?: MedplumRequestOptions): Promise<T>;
    /**
     * Returns the key value client.
     * @returns The key value client.
     */
    get keyValue(): MedplumKeyValueClient;
    /**
     * Internal helper method to get a bundle from a URL.
     * In addition to returning the bundle, it also caches all of the resources in the bundle.
     * This should be used by any method that returns a bundle of resources to be cached.
     * @param url - The bundle URL.
     * @param options - Optional fetch options.
     * @returns Promise to the bundle.
     */
    private getBundle;
    /**
     * Returns the cache entry if available and not expired.
     * @param key - The cache key to retrieve.
     * @param options - Optional fetch options for cache settings.
     * @returns The cached entry if found.
     */
    private getCacheEntry;
    /**
     * Adds a readable promise to the cache.
     * @param key - The cache key to store.
     * @param value - The readable promise to store.
     */
    private setCacheEntry;
    /**
     * Adds a concrete value as the cache entry for the given resource.
     * This is used in cases where the resource is loaded indirectly.
     * For example, when a resource is loaded as part of a Bundle.
     * @param resource - The resource to cache.
     */
    private cacheResource;
    /**
     * Deletes a cache entry.
     * @param key - The cache key to delete.
     */
    private deleteCacheEntry;
    /**
     * Makes an HTTP request.
     * @param method - The HTTP method (GET, POST, etc).
     * @param url - The target URL.
     * @param options - Optional fetch request init options.
     * @param state - Optional request state.
     * @returns The JSON content body if available.
     */
    private request;
    private parseBody;
    private fetchWithRetry;
    private logRequest;
    private logResponse;
    private pollStatus;
    /**
     * Executes a batch of requests that were automatically batched together.
     */
    private executeAutoBatch;
    /**
     * Adds default options to the fetch options.
     * @param options - The options to add defaults to.
     */
    private addFetchOptionsDefaults;
    /**
     * Sets the "Content-Type" header on fetch options.
     * @param options - The fetch options.
     * @param contentType - The new content type to set.
     */
    private setRequestContentType;
    /**
     * Sets a header on fetch options.
     * @param options - The fetch options.
     * @param key - The header key.
     * @param value - The header value.
     * @param ifNoneExist - Optional flag to only set the header if it doesn't already exist.
     */
    private setRequestHeader;
    /**
     * Sets the body on fetch options.
     * @param options - The fetch options.
     * @param data - The new content body.
     */
    private setRequestBody;
    /**
     * Handles an unauthenticated response from the server.
     * First, tries to refresh the access token and retry the request.
     * Otherwise, calls unauthenticated callbacks and rejects.
     * @param method - The HTTP method of the original request.
     * @param url - The URL of the original request.
     * @param options - Optional fetch request init options.
     * @returns The result of the retry.
     */
    private handleUnauthenticated;
    /**
     * Starts a new PKCE flow.
     * These PKCE values are stateful, and must survive redirects and page refreshes.
     * @category Authentication
     * @returns The PKCE code challenge details.
     */
    startPkce(): Promise<{
        codeChallengeMethod: CodeChallengeMethod;
        codeChallenge: string;
    }>;
    /**
     * Redirects the user to the login screen for authorization.
     * Clears all auth state including local storage and session storage.
     * @param loginParams - The authorization login parameters.
     * @see https://openid.net/specs/openid-connect-core-1_0.html#AuthorizationEndpoint
     */
    private requestAuthorization;
    /**
     * Processes an OAuth authorization code.
     * See: https://openid.net/specs/openid-connect-core-1_0.html#TokenRequest
     * @param code - The authorization code received by URL parameter.
     * @param loginParams - Optional login parameters.
     * @returns The user profile resource.
     * @category Authentication
     */
    processCode(code: string, loginParams?: Partial<BaseLoginRequest>): Promise<ProfileResource>;
    /**
     * Refreshes the access token using the refresh token if available.
     * @param gracePeriod - Optional grace period in milliseconds. If not specified, uses the client configured grace period (default 5 minutes).
     * @returns Promise to refresh the access token.
     */
    refreshIfExpired(gracePeriod?: number): Promise<void>;
    /**
     * Tries to refresh the auth tokens.
     * @returns The refresh promise if available; otherwise undefined.
     * @see https://openid.net/specs/openid-connect-core-1_0.html#RefreshTokens
     */
    private refresh;
    /**
     * Starts a new OAuth2 client credentials flow.
     *
     * @example
     * ```typescript
     * await medplum.startClientLogin(import.meta.env.MEDPLUM_CLIENT_ID, import.meta.env.MEDPLUM_CLIENT_SECRET)
     * // Example Search
     * await medplum.searchResources('Patient')
     * ```
     *
     * See: https://datatracker.ietf.org/doc/html/rfc6749#section-4.4
     *
     * @category Authentication
     * @param clientId - The client ID.
     * @param clientSecret - The client secret.
     * @returns Promise that resolves to the client profile.
     */
    startClientLogin(clientId: string, clientSecret: string): Promise<ProfileResource>;
    /**
     * Starts a new OAuth2 JWT bearer flow.
     *
     * @example
     * ```typescript
     * await medplum.startJwtBearerLogin(import.meta.env.MEDPLUM_CLIENT_ID, import.meta.env.MEDPLUM_JWT_BEARER_ASSERTION, 'openid profile');
     * // Example Search
     * await medplum.searchResources('Patient')
     * ```
     *
     * See: https://datatracker.ietf.org/doc/html/rfc7523#section-2.1
     *
     * @category Authentication
     * @param clientId - The client ID.
     * @param assertion - The JWT assertion.
     * @param scope - The OAuth scope.
     * @returns Promise that resolves to the client profile.
     */
    startJwtBearerLogin(clientId: string, assertion: string, scope: string): Promise<ProfileResource>;
    /**
     * Starts a new OAuth2 JWT assertion flow.
     *
     * See: https://datatracker.ietf.org/doc/html/rfc7523#section-2.2
     *
     * @category Authentication
     * @param jwt - The JWT assertion.
     * @returns Promise that resolves to the client profile.
     */
    startJwtAssertionLogin(jwt: string): Promise<ProfileResource>;
    /**
     * Sets the client ID and secret for basic auth.
     *
     * @example
     * ```typescript
     * medplum.setBasicAuth(import.meta.env.MEDPLUM_CLIENT_ID, import.meta.env.MEDPLUM_CLIENT_SECRET);
     * // Example Search
     * await medplum.searchResources('Patient');
     * ```
     *
     * @category Authentication
     * @param clientId - The client ID.
     * @param clientSecret - The client secret.
     */
    setBasicAuth(clientId: string, clientSecret: string): void;
    /**
     * Subscribes to a specified topic, listening for a list of specified events.
     *
     * Once you have the `SubscriptionRequest` returned from this method, you can call `fhircastConnect(subscriptionRequest)` to connect to the subscription stream.
     *
     * @category FHIRcast
     * @param topic - The topic to publish to. Usually a UUID.
     * @param events - An array of event names to listen for.
     * @returns A `Promise` that resolves once the request completes, or rejects if it fails.
     */
    fhircastSubscribe(topic: string, events: FhircastEventName[]): Promise<SubscriptionRequest>;
    /**
     * Unsubscribes from the specified topic.
     *
     * @category FHIRcast
     * @param subRequest - A `SubscriptionRequest` representing a subscription to cancel. Mode will be set to `unsubscribe` automatically.
     * @returns A `Promise` that resolves when request to unsubscribe is completed.
     */
    fhircastUnsubscribe(subRequest: SubscriptionRequest): Promise<void>;
    /**
     * Connects to a `FHIRcast` session.
     *
     * @category FHIRcast
     * @param subRequest - The `SubscriptionRequest` to use for connecting.
     * @returns A `FhircastConnection` which emits lifecycle events for the `FHIRcast` WebSocket connection.
     */
    fhircastConnect(subRequest: SubscriptionRequest): FhircastConnection;
    /**
     * Publishes a new context to a given topic for a specified event type.
     *
     * @category FHIRcast
     * @param topic - The topic to publish to. Usually a UUID.
     * @param event - The name of the event to publish an updated context for, ie. `Patient-open`.
     * @param context - The updated context containing resources relevant to this event.
     * @param versionId - The `versionId` of the `anchor context` of the given event. Used for `DiagnosticReport-update` event.
     * @returns A `Promise` that resolves once the request completes, or rejects if it fails.
     */
    fhircastPublish<EventName extends FhircastEventVersionOptional>(topic: string, event: EventName, context: FhircastEventContext<EventName> | FhircastEventContext<EventName>[], versionId?: never): Promise<Record<string, any>>;
    fhircastPublish<RequiredVersionEvent extends FhircastEventVersionRequired>(topic: string, event: RequiredVersionEvent, context: FhircastEventContext<RequiredVersionEvent> | FhircastEventContext<RequiredVersionEvent>[], versionId: string): Promise<Record<string, any>>;
    /**
     * Gets the current context of the given FHIRcast `topic`.
     *
     * @category FHIRcast
     * @param topic - The topic to get the current context for. Usually a UUID.
     * @returns A Promise which resolves to the `CurrentContext` for the given topic.
     */
    fhircastGetContext(topic: string): Promise<CurrentContext>;
    /**
     * Invite a user to a project.
     * @param projectId - The project ID.
     * @param body - The InviteRequest.
     * @returns Promise that returns a project membership or an operation outcome.
     */
    invite(projectId: string, body: InviteRequest): Promise<ProjectMembership | OperationOutcome>;
    /**
     * Makes a POST request to the tokens endpoint.
     * See: https://openid.net/specs/openid-connect-core-1_0.html#TokenEndpoint
     * @param params - Token parameters.
     * @returns The user profile resource.
     */
    private fetchTokens;
    /**
     * Verifies the tokens received from the auth server.
     * Validates the JWT against the JWKS.
     * See: https://openid.net/specs/openid-connect-core-1_0.html#TokenEndpoint
     * @param tokens - The token response.
     * @returns Promise to complete.
     */
    private verifyTokens;
    private checkSessionDetailsMatchLogin;
    /**
     * Sets up a listener for window storage events.
     * This synchronizes state across browser windows and browser tabs.
     */
    private setupStorageListener;
    /**
     * Gets the `SubscriptionManager` for WebSocket subscriptions.
     *
     * @category Subscriptions
     * @returns the `SubscriptionManager` for this client.
     */
    getSubscriptionManager(): SubscriptionManager;
    /**
     * Subscribes to a given criteria, listening to notifications over WebSockets.
     *
     * This uses Medplum's `WebSocket Subscriptions` under the hood.
     *
     * A `SubscriptionEmitter` is returned from this function, which can be used to listen for updates to resources described by the given criteria.
     *
     * When subscribing to the same criteria multiple times, the same `SubscriptionEmitter` will be returned, and a reference count will be incremented.
     *
     * -----
     * @example
     * ```ts
     * const emitter = medplum.subscribeToCriteria('Communication');
     *
     * emitter.addEventListener('message', (bundle: Bundle) => {
     *   // Called when a `Communication` resource is created or modified
     *   console.log(bundle?.entry?.[1]?.resource); // Logs the `Communication` resource that was updated
     * });
     * ```
     *
     * @category Subscriptions
     * @param criteria - The criteria to subscribe to.
     * @param subscriptionProps - Optional properties to add to the created `Subscription` resource.
     * @returns a `SubscriptionEmitter` that emits `Bundle` resources containing changes to resources based on the given criteria.
     */
    subscribeToCriteria(criteria: string, subscriptionProps?: Partial<Subscription>): SubscriptionEmitter;
    /**
     * Unsubscribes from the given criteria.
     *
     * When called the same amount of times as proceeding calls to `subscribeToCriteria` on a given `criteria`,
     * the criteria is fully removed from the `SubscriptionManager`.
     *
     * @category Subscriptions
     * @param criteria - The criteria to unsubscribe from.
     * @param subscriptionProps - The optional properties that `subscribeToCriteria` was called with.
     */
    unsubscribeFromCriteria(criteria: string, subscriptionProps?: Partial<Subscription>): void;
    /**
     * Get the master `SubscriptionEmitter` for the `SubscriptionManager`.
     *
     * The master `SubscriptionEmitter` gets messages for all subscribed `criteria` as well as WebSocket errors, `connect` and `disconnect` events, and the `close` event.
     *
     * It can also be used to listen for `heartbeat` messages.
     *
     *------
     * @example
     * ### Listening for `heartbeat`:
     * ```ts
     * const masterEmitter = medplum.getMasterSubscriptionEmitter();
     *
     * masterEmitter.addEventListener('heartbeat', (bundle: Bundle<SubscriptionStatus>) => {
     *   console.log(bundle?.entry?.[0]?.resource); // A `SubscriptionStatus` of type `heartbeat`
     * });
     *
     * ```
     * @category Subscriptions
     * @returns the master `SubscriptionEmitter` from the `SubscriptionManager`.
     */
    getMasterSubscriptionEmitter(): SubscriptionEmitter;
}

/**
 * This map enumerates all the lifecycle events that `MedplumClient` emits and what the shape of the `Event` is.
 */
export declare type MedplumClientEventMap = {
    change: {
        type: 'change';
    };
    offline: {
        type: 'offline';
    };
    profileRefreshing: {
        type: 'profileRefreshing';
    };
    profileRefreshed: {
        type: 'profileRefreshed';
    };
    storageInitialized: {
        type: 'storageInitialized';
    };
    storageInitFailed: {
        type: 'storageInitFailed';
        payload: {
            error: Error;
        };
    };
};

/**
 * The MedplumClientOptions interface defines configuration options for MedplumClient.
 *
 * All configuration settings are optional.
 */
export declare interface MedplumClientOptions {
    /**
     * Base server URL.
     *
     * Default value is https://api.medplum.com/
     *
     * Use this to point to a custom Medplum deployment.
     */
    baseUrl?: string;
    /**
     * OAuth2 authorize URL.
     *
     * Default value is baseUrl + "/oauth2/authorize".
     *
     * Can be specified as absolute URL or relative to baseUrl.
     *
     * Use this if you want to use a separate OAuth server.
     */
    authorizeUrl?: string;
    /**
     * FHIR URL path.
     *
     * Default value is "fhir/R4/".
     *
     * Can be specified as absolute URL or relative to baseUrl.
     *
     * Use this if you want to use a different path when connecting to a FHIR server.
     */
    fhirUrlPath?: string;
    /**
     * OAuth2 token URL.
     *
     * Default value is baseUrl + "/oauth2/token".
     *
     * Can be specified as absolute URL or relative to baseUrl.
     *
     * Use this if you want to use a separate OAuth server.
     */
    tokenUrl?: string;
    /**
     * OAuth2 logout URL.
     *
     * Default value is baseUrl + "/oauth2/logout".
     *
     * Can be specified as absolute URL or relative to baseUrl.
     *
     * Use this if you want to use a separate OAuth server.
     */
    logoutUrl?: string;
    /**
     * FHIRcast Hub URL.
     *
     * Default value is `fhircast/STU3`.
     *
     * Can be specified as absolute URL or relative to `baseUrl`.
     *
     * Use this if you want to use a different path when connecting to a FHIRcast hub.
     */
    fhircastHubUrl?: string;
    /**
     * The client ID.
     *
     * Client ID can be used for SMART-on-FHIR customization.
     */
    clientId?: string;
    /**
     * The client secret.
     *
     * Client secret can be used for FHIR Oauth Client Credential flows
     */
    clientSecret?: string;
    /**
     * The OAuth Access Token.
     *
     * Access Token used to connect to make request to FHIR servers
     */
    accessToken?: string;
    /**
     * Specifies through which part of the HTTP request the client credentials should be sent.
     *
     * Body is the default for backwards compatibility, but header may be more desirable for applications.
     */
    authCredentialsMethod?: 'body' | 'header';
    /**
     * Number of resources to store in the cache.
     *
     * Default value is 1000.
     *
     * Consider using this for performance of displaying Patient or Practitioner resources.
     */
    resourceCacheSize?: number;
    /**
     * The length of time in milliseconds to cache resources.
     *
     * Default value is 60000 (60 seconds).
     *
     * Cache time of zero disables all caching.
     *
     * For any individual request, the cache behavior can be overridden by setting the cache property on request options.
     *
     * See: https://developer.mozilla.org/en-US/docs/Web/API/Request/cache
     */
    cacheTime?: number;
    /**
     * The length of time in milliseconds to delay requests for auto batching.
     *
     * Auto batching attempts to group multiple requests together into a single batch request.
     *
     * Default value is 0, which disables auto batching.
     */
    autoBatchTime?: number;
    /**
     * The refresh grace period in milliseconds.
     *
     * This is the amount of time before the access token expires that the client will attempt to refresh the token.
     *
     * Default value is 300000 (5 minutes).
     */
    refreshGracePeriod?: number;
    /**
     * Fetch implementation.
     *
     * Default is window.fetch (if available).
     *
     * For Node.js applications, consider the 'node-fetch' package.
     */
    fetch?: FetchLike;
    /**
     * Storage implementation.
     *
     * Default is window.localStorage (if available), this is the common implementation for use in the browser, or an in-memory storage implementation.  If using Medplum on a server it may be useful to provide a custom storage implementation, for example using redis, a database or a file based storage.  Medplum CLI is an an example of `FileSystemStorage`, for reference.
     */
    storage?: IClientStorage;
    /**
     * Create PDF implementation.
     *
     * Default is none, and PDF generation is disabled.
     *
     * @example
     * In browser environments, import the client-side pdfmake library.
     *
     * ```html
     * <script src="pdfmake.min.js"></script>
     * <script>
     * async function createPdf(docDefinition, tableLayouts, fonts) {
     *   return new Promise((resolve) => {
     *     pdfMake.createPdf(docDefinition, tableLayouts, fonts).getBlob(resolve);
     *   });
     * }
     * </script>
     * ```
     *
     * @example
     * In Node.js applications:
     *
     * ```ts
     * import type { CustomTableLayout, TDocumentDefinitions, TFontDictionary } from 'pdfmake/interfaces';
     * function createPdf(
     *   docDefinition: TDocumentDefinitions,
     *   tableLayouts?: { [name: string]: CustomTableLayout },
     *   fonts?: TFontDictionary
     * ): Promise<Buffer> {
     *   return new Promise((resolve, reject) => {
     *     const printer = new PdfPrinter(fonts ?? {});
     *     const pdfDoc = printer.createPdfKitDocument(docDefinition, { tableLayouts });
     *     const chunks: Uint8Array[] = [];
     *     pdfDoc.on('data', (chunk: Uint8Array) => chunks.push(chunk));
     *     pdfDoc.on('end', () => resolve(Buffer.concat(chunks)));
     *     pdfDoc.on('error', reject);
     *     pdfDoc.end();
     *   });
     * }
     * ```
     */
    createPdf?: CreatePdfFunction;
    /**
     * Callback for when the client is unauthenticated.
     *
     * Default is do nothing.
     *
     * For client side applications, consider redirecting to a sign in page.
     */
    onUnauthenticated?: () => void;
    /**
     * The default redirect behavior.
     *
     * The default behavior is to not follow redirects.
     *
     * Use "follow" to automatically follow redirects.
     */
    redirect?: RequestRedirect;
    /**
     * When the verbose flag is set, the client will log all requests and responses to the console.
     */
    verbose?: boolean;
    /**
     * Optional flag to enable or disable Medplum extended mode.
     *
     * Medplum extended mode includes a few non-standard FHIR properties such as meta.author and meta.project.
     *
     * Default is true.
     */
    extendedMode?: boolean;
    /**
     * Default headers to include in all requests.
     * This can be used to set custom headers such as Cookies or Authorization headers.
     */
    defaultHeaders?: Record<string, string>;
}

export declare interface MedplumInfraConfig {
    name: string;
    stackName: string;
    accountNumber: string;
    region: string;
    domainName: string;
    vpcId: string;
    apiPort: number;
    apiDomainName: string;
    apiSslCertArn: string;
    apiInternetFacing?: boolean;
    apiWafIpSetArn?: string;
    appDomainName: string;
    appSslCertArn: string;
    appApiProxy?: boolean;
    appWafIpSetArn?: string;
    appLoggingBucket?: string;
    appLoggingPrefix?: string;
    storageBucketName: string;
    storageDomainName: string;
    storageSslCertArn: string;
    signingKeyId: string;
    storagePublicKey: string;
    storageWafIpSetArn?: string;
    storageLoggingBucket?: string;
    storageLoggingPrefix?: string;
    baseUrl: string;
    maxAzs: number;
    rdsInstances: number;
    rdsInstanceType: string;
    rdsInstanceVersion?: string;
    rdsClusterParameters?: StringMap;
    rdsSecretsArn?: string;
    rdsReaderInstanceType?: string;
    rdsProxyEnabled?: boolean;
    cacheNodeType?: string;
    cacheSecurityGroupId?: string;
    desiredServerCount: number;
    serverImage: string;
    serverMemory: number;
    serverCpu: number;
    loadBalancerSecurityGroupId?: string;
    loadBalancerLoggingBucket?: string;
    loadBalancerLoggingPrefix?: string;
    clamscanEnabled: boolean;
    clamscanLoggingBucket: string;
    clamscanLoggingPrefix: string;
    skipDns?: boolean;
    hostedZoneName?: string;
    additionalContainers?: {
        name: string;
        image: string;
        cpu?: number;
        memory?: number;
        essential?: boolean;
        command?: string[];
        environment?: {
            [key: string]: string;
        };
    }[];
    containerInsights?: boolean;
    cloudTrailAlarms?: {
        logGroupName: string;
        logGroupCreate?: boolean;
        snsTopicArn?: string;
        snsTopicName?: string;
    };
    fargateAutoScaling?: {
        minCapacity: number;
        maxCapacity: number;
        targetUtilizationPercent: number;
        scaleInCooldown: number;
        scaleOutCooldown: number;
    };
    environment?: StringMap;
    rdsIdsMajorVersionSuffix?: boolean;
    rdsPersistentParameterGroups?: boolean;
}

export declare class MedplumKeyValueClient {
    readonly medplum: MedplumClient;
    constructor(medplum: MedplumClient);
    /**
     * Gets the value for the given key from the keyvalue store.
     * @param key - The key to get the value for.
     * @returns The value for the given key.
     */
    get(key: string): Promise<string | undefined>;
    /**
     * Sets the value for the given key in the keyvalue store.
     * @param key - The key to set the value for.
     * @param value - The value to set.
     */
    set(key: string, value: string): Promise<void>;
    /**
     * Deletes the value for the given key from the keyvalue store.
     * @param key - The key to delete the value for.
     */
    delete(key: string): Promise<void>;
}

export declare interface MedplumRequestOptions extends RequestInit {
    /**
     * Optional flag to follow "Location" or "Content-Location" URL on successful HTTP 200 "OK" responses.
     */
    followRedirectOnOk?: boolean;
    /**
     * Optional flag to follow "Location" or "Content-Location" URL on successful HTTP 201 "Created" responses.
     */
    followRedirectOnCreated?: boolean;
    /**
     * Optional flag to poll the status URL on successful HTTP 202 "Accepted" responses.
     */
    pollStatusOnAccepted?: boolean;
    /**
     * Optional polling time interval in milliseconds.
     * Default value is 1000 (1 second).
     */
    pollStatusPeriod?: number;
    /**
     * Optional max number of retries that should be made in the case of a failed request. Default is `2`.
     */
    maxRetries?: number;
    /**
     * Optional flag to disable auto-batching for this specific request.
     * Only applies when the client is configured with auto-batching enabled.
     */
    disableAutoBatch?: boolean;
}

export declare interface MedplumSourceInfraConfig {
    name: ValueOrExternalSecret<string>;
    stackName: ValueOrExternalSecret<string>;
    accountNumber: ValueOrExternalSecret<string>;
    region: string;
    domainName: ValueOrExternalSecret<string>;
    vpcId: ValueOrExternalSecret<string>;
    apiPort: ValueOrExternalSecret<number>;
    apiDomainName: ValueOrExternalSecret<string>;
    apiSslCertArn: ValueOrExternalSecret<string>;
    apiInternetFacing?: ValueOrExternalSecret<boolean>;
    apiWafIpSetArn: ValueOrExternalSecret<string>;
    appDomainName: ValueOrExternalSecret<string>;
    appSslCertArn: ValueOrExternalSecret<string>;
    appApiProxy?: ValueOrExternalSecret<boolean>;
    appWafIpSetArn: ValueOrExternalSecret<string>;
    appLoggingBucket?: ValueOrExternalSecret<string>;
    appLoggingPrefix?: ValueOrExternalSecret<string>;
    storageBucketName: ValueOrExternalSecret<string>;
    storageDomainName: ValueOrExternalSecret<string>;
    storageSslCertArn: ValueOrExternalSecret<string>;
    signingKeyId: ValueOrExternalSecret<string>;
    storagePublicKey: ValueOrExternalSecret<string>;
    storageWafIpSetArn: ValueOrExternalSecret<string>;
    storageLoggingBucket?: ValueOrExternalSecret<string>;
    storageLoggingPrefix?: ValueOrExternalSecret<string>;
    baseUrl: ValueOrExternalSecret<string>;
    maxAzs: ValueOrExternalSecret<number>;
    rdsInstances: ValueOrExternalSecret<number>;
    rdsInstanceType: ValueOrExternalSecret<string>;
    rdsInstanceVersion?: ValueOrExternalSecret<string>;
    rdsSecretsArn?: ValueOrExternalSecret<string>;
    rdsReaderInstanceType?: ValueOrExternalSecret<string>;
    rdsProxyEnabled?: ValueOrExternalSecret<boolean>;
    rdsClusterParameters?: StringMap;
    cacheNodeType?: ValueOrExternalSecret<string>;
    cacheSecurityGroupId?: ValueOrExternalSecret<string>;
    desiredServerCount: ValueOrExternalSecret<number>;
    serverImage: ValueOrExternalSecret<string>;
    serverMemory: ValueOrExternalSecret<number>;
    serverCpu: ValueOrExternalSecret<number>;
    loadBalancerSecurityGroupId?: ValueOrExternalSecret<string>;
    loadBalancerLoggingBucket?: ValueOrExternalSecret<string>;
    loadBalancerLoggingPrefix?: ValueOrExternalSecret<string>;
    clamscanEnabled: ValueOrExternalSecret<boolean>;
    clamscanLoggingBucket: ValueOrExternalSecret<string>;
    clamscanLoggingPrefix: ValueOrExternalSecret<string>;
    skipDns?: ValueOrExternalSecret<boolean>;
    hostedZoneName?: ValueOrExternalSecret<string>;
    additionalContainers?: {
        name: ValueOrExternalSecret<string>;
        image: ValueOrExternalSecret<string>;
        cpu?: ValueOrExternalSecret<number>;
        memory?: ValueOrExternalSecret<number>;
        essential?: ValueOrExternalSecret<boolean>;
        command?: ValueOrExternalSecret<string>[];
        environment?: {
            [key: string]: ValueOrExternalSecret<string>;
        };
    }[];
    containerInsights?: ValueOrExternalSecret<boolean>;
    cloudTrailAlarms?: {
        logGroupName: ValueOrExternalSecret<string>;
        logGroupCreate?: ValueOrExternalSecret<boolean>;
        snsTopicArn?: ValueOrExternalSecret<string>;
        snsTopicName?: ValueOrExternalSecret<string>;
    };
    fargateAutoScaling?: {
        minCapacity: ValueOrExternalSecret<number>;
        maxCapacity: ValueOrExternalSecret<number>;
        targetUtilizationPercent: ValueOrExternalSecret<number>;
        scaleInCooldown: ValueOrExternalSecret<number>;
        scaleOutCooldown: ValueOrExternalSecret<number>;
    };
    environment?: StringMap;
    rdsIdsMajorVersionSuffix?: boolean;
    rdsPersistentParameterGroups?: boolean;
}

/**
 * The MemoryStorage class is a minimal in-memory implementation of the Storage interface.
 */
export declare class MemoryStorage implements Storage {
    private readonly data;
    constructor();
    /**
     * Returns the number of key/value pairs.
     * @returns The number of key/value pairs.
     */
    get length(): number;
    /**
     * Removes all key/value pairs, if there are any.
     */
    clear(): void;
    /**
     * Returns the current value associated with the given key, or null if the given key does not exist.
     * @param key - The specified storage key.
     * @returns The current value associated with the given key, or null if the given key does not exist.
     */
    getItem(key: string): string | null;
    /**
     * Sets the value of the pair identified by key to value, creating a new key/value pair if none existed for key previously.
     * @param key - The storage key.
     * @param value - The new value.
     */
    setItem(key: string, value: string | null): void;
    /**
     * Removes the key/value pair with the given key, if a key/value pair with the given key exists.
     * @param key - The storage key.
     */
    removeItem(key: string): void;
    /**
     * Returns the name of the nth key, or null if n is greater than or equal to the number of key/value pairs.
     * @param index - The numeric index.
     * @returns The nth key.
     */
    key(index: number): string | null;
}

export declare type Message = string | ArrayBuffer | Blob | ArrayBufferView;

/**
 * The MockAsyncClientStorage class is a mock implementation of the ClientStorage class.
 * This can be used for testing async initialization of the MedplumClient.
 */
export declare class MockAsyncClientStorage extends ClientStorage implements IClientStorage {
    private initialized;
    private readonly initPromise;
    private initResolve;
    constructor();
    setInitialized(): void;
    getInitPromise(): Promise<void>;
    get isInitialized(): boolean;
}

export declare const multipleMatches: OperationOutcome;

export declare const NDC = "http://hl7.org/fhir/sid/ndc";

export declare interface NewPatientRequest {
    readonly login: string;
    readonly projectId: string;
}

export declare interface NewProjectRequest {
    readonly login: string;
    readonly projectName: string;
}

export declare interface NewUserRequest {
    readonly firstName: string;
    readonly lastName: string;
    readonly email: string;
    readonly password: string;
    readonly recaptchaToken: string;
    readonly recaptchaSiteKey?: string;
    readonly remember?: boolean;
    readonly projectId?: string;
    readonly clientId?: string;
}

/**
 * Normalizes an `ArrayBufferLike` (eg. an `ArrayBuffer`) to a raw `ArrayBufferLike` (without a view). If the passed buffer is a view, it gives the raw `ArrayBufferLike`.
 *
 * This is useful in cases where you need to operate on the raw bytes of an `ArrayBuffer` where a `TypedArray` (eg. `Uint32Array`) might be passed in.
 * This ensures that you will always operate on the raw bytes rather than accidentally truncating the input by operating on the elements of the view.
 *
 * @param typedArrayOrBuffer - The `ArrayBufferLike` (either `TypedArray` or raw `ArrayBuffer`) to normalize to raw `ArrayBuffer`.
 * @returns The raw `ArrayBuffer` without a view.
 */
export declare function normalizeArrayBufferView(typedArrayOrBuffer: ArrayBufferLike | ArrayBufferView): ArrayBufferLike;

export declare function normalizeCreateBinaryOptions(arg1: BinarySource | CreateBinaryOptions, arg2: string | undefined | MedplumRequestOptions, arg3?: string, arg4?: (e: ProgressEvent) => void): CreateBinaryOptions;

export declare function normalizeCreatePdfOptions(arg1: TDocumentDefinitions | CreatePdfOptions, arg2: string | undefined | MedplumRequestOptions, arg3: Record<string, CustomTableLayout> | undefined, arg4: TFontDictionary | undefined): CreatePdfOptions;

/**
 * Normalizes an error object into a displayable error string.
 * @param error - The error value which could be a string, Error, OperationOutcome, or other unknown type.
 * @returns A display string for the error.
 */
export declare function normalizeErrorString(error: unknown): string;

/**
 * Normalizes an error object into an OperationOutcome.
 * @param error - The error value which could be a string, Error, OperationOutcome, or other unknown type.
 * @returns The normalized OperationOutcome.
 */
export declare function normalizeOperationOutcome(error: unknown): OperationOutcome;

export declare class NotEqualsAtom extends BooleanInfixOperatorAtom {
    constructor(left: Atom, right: Atom);
    eval(context: AtomContext, input: TypedValue[]): TypedValue[];
}

export declare class NotEquivalentAtom extends BooleanInfixOperatorAtom {
    constructor(left: Atom, right: Atom);
    eval(context: AtomContext, input: TypedValue[]): TypedValue[];
}

export declare const notFound: OperationOutcome;

export declare const notModified: OperationOutcome;

/**
 * OAuth 2.0 Client Authentication Methods
 * See: https://datatracker.ietf.org/doc/html/rfc7523#section-2.2
 */
export declare const OAuthClientAssertionType: {
    /** Using JWTs for Client Authentication */
    readonly JwtBearer: "urn:ietf:params:oauth:client-assertion-type:jwt-bearer";
};

export declare type OAuthClientAssertionType = (typeof OAuthClientAssertionType)[keyof typeof OAuthClientAssertionType];

/**
 * OAuth 2.0 Grant Type Identifiers
 * Standard identifiers: https://datatracker.ietf.org/doc/html/draft-ietf-oauth-v2-1-07#name-grant-types
 * JWT bearer extension: https://datatracker.ietf.org/doc/html/rfc7523
 * Token exchange extension: https://datatracker.ietf.org/doc/html/rfc8693
 */
export declare const OAuthGrantType: {
    readonly ClientCredentials: "client_credentials";
    readonly AuthorizationCode: "authorization_code";
    readonly RefreshToken: "refresh_token";
    readonly JwtBearer: "urn:ietf:params:oauth:grant-type:jwt-bearer";
    readonly TokenExchange: "urn:ietf:params:oauth:grant-type:token-exchange";
};

export declare type OAuthGrantType = (typeof OAuthGrantType)[keyof typeof OAuthGrantType];

/**
 * OAuth 2.0 Client Authentication Methods
 * See: https://openid.net/specs/openid-connect-core-1_0.html#ClientAuthentication
 */
export declare const OAuthTokenAuthMethod: {
    readonly ClientSecretBasic: "client_secret_basic";
    readonly ClientSecretPost: "client_secret_post";
    readonly ClientSecretJwt: "client_secret_jwt";
    readonly PrivateKeyJwt: "private_key_jwt";
    readonly None: "none";
};

export declare type OAuthTokenAuthMethod = (typeof OAuthTokenAuthMethod)[keyof typeof OAuthTokenAuthMethod];

/**
 * OAuth 2.0 Token Type Identifiers
 * See: https://datatracker.ietf.org/doc/html/rfc8693#name-token-type-identifiers
 */
export declare const OAuthTokenType: {
    /** Indicates that the token is an OAuth 2.0 access token issued by the given authorization server. */
    readonly AccessToken: "urn:ietf:params:oauth:token-type:access_token";
    /** Indicates that the token is an OAuth 2.0 refresh token issued by the given authorization server. */
    readonly RefreshToken: "urn:ietf:params:oauth:token-type:refresh_token";
    /** Indicates that the token is an ID Token as defined in Section 2 of [OpenID.Core]. */
    readonly IdToken: "urn:ietf:params:oauth:token-type:id_token";
    /** Indicates that the token is a base64url-encoded SAML 1.1 [OASIS.saml-core-1.1] assertion. */
    readonly Saml1Token: "urn:ietf:params:oauth:token-type:saml1";
    /** Indicates that the token is a base64url-encoded SAML 2.0 [OASIS.saml-core-2.0-os] assertion. */
    readonly Saml2Token: "urn:ietf:params:oauth:token-type:saml2";
};

export declare type OAuthTokenType = (typeof OAuthTokenType)[keyof typeof OAuthTokenType];

export declare class OperationOutcomeError extends Error {
    readonly outcome: OperationOutcome;
    constructor(outcome: OperationOutcome, cause?: unknown);
}

/**
 * Returns a string represenation of the operation outcome issue.
 * @param issue - The operation outcome issue.
 * @returns The string representation of the operation outcome issue.
 */
export declare function operationOutcomeIssueToString(issue: OperationOutcomeIssue): string;

/**
 * Returns a string represenation of the operation outcome.
 * @param outcome - The operation outcome.
 * @returns The string representation of the operation outcome.
 */
export declare function operationOutcomeToString(outcome: OperationOutcome): string;

/**
 * Search operators.
 * These operators represent "modifiers" and "prefixes" in FHIR search.
 * See: https://www.hl7.org/fhir/search.html
 */
export declare const Operator: {
    readonly EQUALS: "eq";
    readonly NOT_EQUALS: "ne";
    readonly GREATER_THAN: "gt";
    readonly LESS_THAN: "lt";
    readonly GREATER_THAN_OR_EQUALS: "ge";
    readonly LESS_THAN_OR_EQUALS: "le";
    readonly STARTS_AFTER: "sa";
    readonly ENDS_BEFORE: "eb";
    readonly APPROXIMATELY: "ap";
    readonly CONTAINS: "contains";
    readonly STARTS_WITH: "sw";
    readonly EXACT: "exact";
    readonly TEXT: "text";
    readonly NOT: "not";
    readonly ABOVE: "above";
    readonly BELOW: "below";
    readonly IN: "in";
    readonly NOT_IN: "not-in";
    readonly OF_TYPE: "of-type";
    readonly MISSING: "missing";
    readonly PRESENT: "present";
    readonly IDENTIFIER: "identifier";
    readonly ITERATE: "iterate";
};

export declare type Operator = (typeof Operator)[keyof typeof Operator];

/**
 * Operator precedence
 * See: https://hl7.org/fhirpath/#operator-precedence
 */
export declare const OperatorPrecedence: {
    FunctionCall: number;
    Dot: number;
    Indexer: number;
    UnaryAdd: number;
    UnarySubtract: number;
    Multiply: number;
    Divide: number;
    IntegerDivide: number;
    Modulo: number;
    Add: number;
    Subtract: number;
    Ampersand: number;
    Is: number;
    As: number;
    Union: number;
    GreaterThan: number;
    GreaterThanOrEquals: number;
    LessThan: number;
    LessThanOrEquals: number;
    Equals: number;
    Equivalent: number;
    NotEquals: number;
    NotEquivalent: number;
    In: number;
    Contains: number;
    And: number;
    Xor: number;
    Or: number;
    Implies: number;
    Arrow: number;
    Semicolon: number;
};

export declare type Options<WS extends IWebSocket = WebSocket> = {
    WebSocket?: any;
    binaryType?: WS['binaryType'];
    maxReconnectionDelay?: number;
    minReconnectionDelay?: number;
    reconnectionDelayGrowFactor?: number;
    minUptime?: number;
    connectionTimeout?: number;
    maxRetries?: number;
    maxEnqueuedMessages?: number;
    startClosed?: boolean;
    debug?: boolean;
    debugLogger?: (...args: any[]) => void;
};

/**
 * 6.5.2. or
 * Returns false if both operands evaluate to false,
 * true if either operand evaluates to true,
 * and empty (`{ }`) otherwise:
 */
export declare class OrAtom extends BooleanInfixOperatorAtom {
    constructor(left: Atom, right: Atom);
    eval(context: AtomContext, input: TypedValue[]): TypedValue[];
}

/**
 * SQL on FHIR output row.
 */
export declare type OutputRow = Record<string, any>;

/**
 * Parses a FHIRPath expression into an AST.
 * The result can be used to evaluate the expression against a resource or other object.
 * This method is useful if you know that you will evaluate the same expression many times
 * against different resources.
 * @param input - The FHIRPath expression to parse.
 * @returns The AST representing the expression.
 */
export declare function parseFhirPath(input: string): FhirPathAtom;

/**
 * Parses a FHIR _filter parameter expression into an AST.
 * @param input - The FHIR _filter parameter expression.
 * @returns The AST representing the filters.
 */
export declare function parseFilterParameter(input: string): FhirFilterExpression;

/**
 * Returns a formatted string representing the date in ISO-8601 format.
 *
 * HL7-Definition V2
 * Specifies a point in time using a 24-hour clock notation.
 *
 * Format: YYYY[MM[DD[HH[MM[SS[. S[S[S[S]]]]]]]]][+/-ZZZZ].
 *
 * @param hl7DateTime - Date/time string.
 * @param options - Optional parsing options.
 * @returns The date in ISO-8601 format.
 */
export declare function parseHl7DateTime(hl7DateTime: string | undefined, options?: Hl7DateParseOptions): string | undefined;

/**
 * Parses the JWT payload.
 * @param token - JWT token.
 * @returns Collection of key value claims in the JWT payload.
 */
export declare function parseJWTPayload(token: string): JWTPayload;

export declare function parseLogLevel(level: string): LogLevel;

/**
 * Parses a FHIR Mapping Language document into an AST.
 * @param input - The FHIR Mapping Language document to parse.
 * @returns The AST representing the document.
 */
export declare function parseMappingLanguage(input: string): StructureMap;

export declare function parseParameter(searchParam: SearchParameter, modifier: string, value: string): Filter;

export declare class Parser {
    private tokens;
    private readonly prefixParselets;
    private readonly infixParselets;
    constructor(tokens: Token[], prefixParselets: Record<string, PrefixParselet>, infixParselets: Record<string, InfixParselet>);
    hasMore(): boolean;
    match(expected: string): boolean;
    consumeAndParse(precedence?: number): Atom;
    getPrecedence(): number;
    consume(expectedId?: string, expectedValue?: string): Token;
    peek(): Token | undefined;
    removeComments(): void;
    getInfixParselet(token: Token): InfixParselet | undefined;
}

export declare class ParserBuilder {
    private readonly prefixParselets;
    private readonly infixParselets;
    registerInfix(tokenType: string, parselet: InfixParselet): this;
    registerPrefix(tokenType: string, parselet: PrefixParselet): this;
    prefix(tokenType: string, precedence: number, builder: (token: Token, right: Atom) => Atom): this;
    infixLeft(tokenType: string, precedence: number, builder: (left: Atom, token: Token, right: Atom) => Atom): this;
    construct(input: Token[]): Parser;
}

/**
 * Parses a reference and returns a tuple of [ResourceType, ID].
 * @param reference - A reference to a FHIR resource.
 * @returns A tuple containing the `ResourceType` and the ID of the resource or `undefined` when `undefined` or an invalid reference is passed.
 */
export declare function parseReference<T extends Resource>(reference: Reference<T> | undefined): [T['resourceType'], string];

/**
 * Parses a search URL into a search request.
 * @param url - The original search URL or the FHIR resource type.
 * @param query - Optional collection of additional query string parameters.
 * @returns A parsed SearchRequest.
 */
export declare function parseSearchRequest<T extends Resource = Resource>(url: T['resourceType'] | URL | string, query?: Record<string, string[] | string | undefined>): SearchRequest<T>;

/**
 * Parses a StructureDefinition resource into an internal schema better suited for
 * programmatic validation and usage in internal systems
 * @param sd - The StructureDefinition resource to parse
 * @returns The parsed schema for the given resource type
 * @experimental
 */
export declare function parseStructureDefinition(sd: StructureDefinition): InternalTypeSchema;

/**
 * Parses an extended FHIR search criteria string (i.e. application/x-fhir-query).
 *
 * @example Evaluating a FHIRPath subexpression
 *
 * ```typescript
 * const query = 'Patient?name={{ %patient.name }}';
 * const variables = { patient: { name: 'John Doe' } };
 * const request = parseXFhirQuery(query, variables);
 * console.log(request.filters[0].value); // "John Doe"
 * ```
 *
 * @see https://hl7.org/fhir/fhir-xquery.html
 * @param query - The X-Fhir-Query string to parse
 * @param variables - Values to pass into embedded FHIRPath expressions
 * @returns The parsed search request
 */
export declare function parseXFhirQuery(query: string, variables: Record<string, TypedValue>): SearchRequest;

/**
 * JSONPatch patch operation.
 * Compatible with fast-json-patch and rfc6902 Operation.
 */
export declare interface PatchOperation {
    readonly op: 'add' | 'remove' | 'replace' | 'copy' | 'move' | 'test';
    readonly path: string;
    readonly value?: any;
}

export declare type PendingSubscriptionRequest = Omit<SubscriptionRequest, 'endpoint'>;

/**
 * Returns true if the two numbers are equal to the given precision.
 * @param a - The first number.
 * @param b - The second number.
 * @param precision - Optional precision in number of digits.
 * @returns True if the two numbers are equal to the given precision.
 */
export declare function preciseEquals(a: number, b: number, precision?: number): boolean;

/**
 * Returns true if the first number is greater than the second number to the given precision.
 * @param a - The first number.
 * @param b - The second number.
 * @param precision - Optional precision in number of digits.
 * @returns True if the first number is greater than the second number to the given precision.
 */
export declare function preciseGreaterThan(a: number, b: number, precision?: number): boolean;

/**
 * Returns true if the first number is greater than or equal to the second number to the given precision.
 * @param a - The first number.
 * @param b - The second number.
 * @param precision - Optional precision in number of digits.
 * @returns True if the first number is greater than or equal to the second number to the given precision.
 */
export declare function preciseGreaterThanOrEquals(a: number, b: number, precision?: number): boolean;

/**
 * Returns true if the first number is less than the second number to the given precision.
 * @param a - The first number.
 * @param b - The second number.
 * @param precision - Optional precision in number of digits.
 * @returns True if the first number is less than the second number to the given precision.
 */
export declare function preciseLessThan(a: number, b: number, precision?: number): boolean;

/**
 * Returns true if the first number is less than or equal to the second number to the given precision.
 * @param a - The first number.
 * @param b - The second number.
 * @param precision - Optional precision in number of digits.
 * @returns True if the first number is less than or equal to the second number to the given precision.
 */
export declare function preciseLessThanOrEquals(a: number, b: number, precision?: number): boolean;

/**
 * Returns the input number rounded to the specified number of digits.
 * @param a - The input number.
 * @param precision - The precision in number of digits.
 * @returns The number rounded to the specified number of digits.
 */
export declare function preciseRound(a: number, precision: number): number;

export declare const preconditionFailed: OperationOutcome;

export declare abstract class PrefixOperatorAtom implements Atom {
    readonly operator: string;
    readonly child: Atom;
    constructor(operator: string, child: Atom);
    abstract eval(context: AtomContext, input: TypedValue[]): TypedValue[];
    toString(): string;
}

export declare interface PrefixParselet {
    parse(parser: Parser, token: Token): Atom;
}

export declare type ProfileResource = Patient | Practitioner | RelatedPerson;

/**
 * Project admin resource types are special resources that are only
 * accessible to project administrators.
 */
export declare const projectAdminResourceTypes: string[];

/**
 * List of property types.
 * http://www.hl7.org/fhir/valueset-defined-types.html
 * The list here includes additions found from StructureDefinition resources.
 */
export declare const PropertyType: {
    readonly Address: "Address";
    readonly Age: "Age";
    readonly Annotation: "Annotation";
    readonly Attachment: "Attachment";
    readonly BackboneElement: "BackboneElement";
    readonly CodeableConcept: "CodeableConcept";
    readonly Coding: "Coding";
    readonly ContactDetail: "ContactDetail";
    readonly ContactPoint: "ContactPoint";
    readonly Contributor: "Contributor";
    readonly Count: "Count";
    readonly DataRequirement: "DataRequirement";
    readonly Distance: "Distance";
    readonly Dosage: "Dosage";
    readonly Duration: "Duration";
    readonly Expression: "Expression";
    readonly Extension: "Extension";
    readonly HumanName: "HumanName";
    readonly Identifier: "Identifier";
    readonly MarketingStatus: "MarketingStatus";
    readonly Meta: "Meta";
    readonly Money: "Money";
    readonly Narrative: "Narrative";
    readonly ParameterDefinition: "ParameterDefinition";
    readonly Period: "Period";
    readonly Population: "Population";
    readonly ProdCharacteristic: "ProdCharacteristic";
    readonly ProductShelfLife: "ProductShelfLife";
    readonly Quantity: "Quantity";
    readonly Range: "Range";
    readonly Ratio: "Ratio";
    readonly Reference: "Reference";
    readonly RelatedArtifact: "RelatedArtifact";
    readonly SampledData: "SampledData";
    readonly Signature: "Signature";
    readonly SubstanceAmount: "SubstanceAmount";
    readonly SystemString: "http://hl7.org/fhirpath/System.String";
    readonly Timing: "Timing";
    readonly TriggerDefinition: "TriggerDefinition";
    readonly UsageContext: "UsageContext";
    readonly base64Binary: "base64Binary";
    readonly boolean: "boolean";
    readonly canonical: "canonical";
    readonly code: "code";
    readonly date: "date";
    readonly dateTime: "dateTime";
    readonly decimal: "decimal";
    readonly id: "id";
    readonly instant: "instant";
    readonly integer: "integer";
    readonly markdown: "markdown";
    readonly oid: "oid";
    readonly positiveInt: "positiveInt";
    readonly string: "string";
    readonly time: "time";
    readonly unsignedInt: "unsignedInt";
    readonly uri: "uri";
    readonly url: "url";
    readonly uuid: "uuid";
};

/**
 * Protected resource types are in the "medplum" project.
 * Reading and writing is limited to the system account.
 */
export declare const protectedResourceTypes: string[];

export declare type ProtocolsProvider = null | string | string[];

/**
 * QueryTypes defines the different ways to specify FHIR search parameters.
 *
 * Can be any valid input to the URLSearchParams() constructor.
 *
 * TypeScript definitions for URLSearchParams do not match runtime behavior.
 * The official spec only accepts string values.
 * Web browsers and Node.js automatically coerce values to strings.
 * See: https://github.com/microsoft/TypeScript/issues/32951
 */
export declare type QueryTypes = URLSearchParams | string[][] | Record<string, string | number | boolean | undefined> | string | undefined;

/**
 * The ReadablePromise class wraps a request promise suitable for React Suspense.
 * See: https://blog.logrocket.com/react-suspense-data-fetching/#wrappromise-js
 * See: https://github.com/ovieokeh/suspense-data-fetching/blob/master/lib/api/wrapPromise.js
 */
export declare class ReadablePromise<T> implements Promise<T> {
    readonly [Symbol.toStringTag]: string;
    private readonly suspender;
    private status;
    private response;
    private error;
    constructor(requestPromise: Promise<T>);
    /**
     * Returns true if the promise is pending.
     * @returns True if the Promise is pending.
     */
    isPending(): boolean;
    /**
     * Returns true if the promise resolved successfully.
     * @returns True if the Promise resolved successfully.
     */
    isOk(): boolean;
    /**
     * Attempts to read the value of the promise.
     * If the promise is pending, this method will throw a promise.
     * If the promise rejected, this method will throw the rejection reason.
     * If the promise resolved, this method will return the resolved value.
     * @returns The resolved value of the Promise.
     */
    read(): T;
    /**
     * Attaches callbacks for the resolution and/or rejection of the Promise.
     * @param onfulfilled - The callback to execute when the Promise is resolved.
     * @param onrejected - The callback to execute when the Promise is rejected.
     * @returns A Promise for the completion of which ever callback is executed.
     */
    then<TResult1 = T, TResult2 = never>(onfulfilled?: ((value: T) => TResult1 | PromiseLike<TResult1>) | null, onrejected?: ((reason: any) => TResult2 | PromiseLike<TResult2>) | null): Promise<TResult1 | TResult2>;
    /**
     * Attaches a callback for only the rejection of the Promise.
     * @param onrejected - The callback to execute when the Promise is rejected.
     * @returns A Promise for the completion of the callback.
     */
    catch<TResult = never>(onrejected?: ((reason: any) => TResult | PromiseLike<TResult>) | null): Promise<T | TResult>;
    /**
     * Attaches a callback that is invoked when the Promise is settled (fulfilled or rejected). The
     * resolved value cannot be modified from the callback.
     * @param onfinally - The callback to execute when the Promise is settled (fulfilled or rejected).
     * @returns A Promise for the completion of the callback.
     */
    finally(onfinally?: (() => void) | null): Promise<T>;
}

export declare class ReconnectingWebSocket<WS extends IWebSocket = WebSocket> extends TypedEventTarget<WebSocketEventMap_2> implements IReconnectingWebSocket {
    private _ws;
    private _retryCount;
    private _uptimeTimeout;
    private _connectTimeout;
    private _shouldReconnect;
    private _connectLock;
    private _binaryType;
    private _closeCalled;
    private _messageQueue;
    private readonly _debugLogger;
    protected _url: string;
    protected _protocols?: ProtocolsProvider;
    protected _options: Options<WS>;
    constructor(url: string, protocols?: ProtocolsProvider, options?: Options<WS>);
    static get CONNECTING(): number;
    static get OPEN(): number;
    static get CLOSING(): number;
    static get CLOSED(): number;
    get CONNECTING(): number;
    get OPEN(): number;
    get CLOSING(): number;
    get CLOSED(): number;
    get binaryType(): WS['binaryType'];
    set binaryType(value: WS['binaryType']);
    /**
     * @returns The number or connection retries.
     */
    get retryCount(): number;
    /**
     * @returns The number of bytes of data that have been queued using calls to send() but not yet
     * transmitted to the network. This value resets to zero once all queued data has been sent.
     * This value does not reset to zero when the connection is closed; if you keep calling send(),
     * this will continue to climb. Read only
     *
     */
    get bufferedAmount(): number;
    /**
     * @returns The extensions selected by the server. This is currently only the empty string or a list of
     * extensions as negotiated by the connection
     */
    get extensions(): string;
    /**
     * @returns A string indicating the name of the sub-protocol the server selected;
     * this will be one of the strings specified in the protocols parameter when creating the
     * WebSocket object.
     */
    get protocol(): string;
    /**
     * @returns The current state of the connection; this is one of the Ready state constants.
     */
    get readyState(): number;
    /**
     * @returns The URL as resolved by the constructor.
     */
    get url(): string;
    /**
     * @returns Whether the websocket object is now in reconnectable state.
     */
    get shouldReconnect(): boolean;
    /**
     * An event listener to be called when the WebSocket connection's readyState changes to CLOSED
     */
    onclose: ((event: CloseEvent_2) => void) | null;
    /**
     * An event listener to be called when an error occurs
     */
    onerror: ((event: ErrorEvent_2) => void) | null;
    /**
     * An event listener to be called when a message is received from the server
     */
    onmessage: ((event: MessageEvent) => void) | null;
    /**
     * An event listener to be called when the WebSocket connection's readyState changes to OPEN;
     * this indicates that the connection is ready to send and receive data
     */
    onopen: ((event: Event) => void) | null;
    /**
     * Closes the WebSocket connection or connection attempt, if any. If the connection is already
     * CLOSED, this method does nothing
     * @param code - The code to close with. Default is 1000.
     * @param reason - An optional reason for closing the connection.
     */
    close(code?: number, reason?: string): void;
    /**
     * Closes the WebSocket connection or connection attempt and connects again.
     * Resets retry counter;
     * @param code - The code to disconnect with. Default is 1000.
     * @param reason - An optional reason for disconnecting the connection.
     */
    reconnect(code?: number, reason?: string): void;
    /**
     * Enqueue specified data to be transmitted to the server over the WebSocket connection
     * @param data - The data to enqueue.
     */
    send(data: Message): void;
    private _debug;
    private _getNextDelay;
    private _wait;
    private _connect;
    private _handleTimeout;
    private _disconnect;
    private _acceptOpen;
    private readonly _handleOpen;
    private readonly _handleMessage;
    private readonly _handleError;
    private readonly _handleClose;
    private _removeListeners;
    private _addListeners;
    private _clearTimeouts;
}

export declare function redirect(url: URL): OperationOutcome;

export declare type ReleaseManifest = {
    tag_name: string;
    assets: {
        name: string;
        browser_download_url: string;
    }[];
};

/**
 * Removes duplicates in array using FHIRPath equality rules.
 * @param arr - The input array.
 * @returns The result array with duplicates removed.
 */
export declare function removeDuplicates(arr: TypedValue[]): TypedValue[];

/**
 * Removes the supplied profileUrl from the resource.meta.profile if it is present
 * @param resource - A FHIR resource
 * @param profileUrl - The profile URL to remove
 * @returns The resource
 */
export declare function removeProfileFromResource<T extends Resource = Resource>(resource: T, profileUrl: string): T;

/**
 * Topologically sorts a `batch` or `transaction` bundle to improve reference resolution.
 * The bundle is sorted such that a resource is created _before_ references to that resource appear in the bundle.
 *
 * In the event of cycles, this function will first create a POST request for each resource in the cycle, and then will
 * append a PUT request to the bundle. This ensures that each resources in the cycle is visited twice, and all
 * references can be resolved
 * @param bundle - Input bundle with type `batch` or `transaction`
 * @returns Bundle of the same type, with Bundle.entry reordered
 */
export declare function reorderBundle(bundle: Bundle): Bundle;

export declare interface RequestProfileSchemaOptions {
    /** (optional) Whether to include nested profiles, e.g. from extensions. Defaults to false. */
    expandProfile?: boolean;
}

/**
 * Returns the ID portion of a reference.
 * @param input - A FHIR reference or resource.
 * @returns The ID portion of a reference.
 */
export declare function resolveId(input: Reference | Resource | undefined): string | undefined;

/**
 * ResourceArray is an array of resources with a bundle property.
 * The bundle property is a FHIR Bundle containing the search results.
 * This is useful for retrieving bundle metadata such as total, offset, and next link.
 */
export declare type ResourceArray<T extends Resource = Resource> = T[] & {
    bundle: Bundle<T>;
};

export declare type ResourceMatchesSubscriptionCriteria = {
    resource: Resource;
    subscription: Subscription;
    context: BackgroundJobContext;
    logger?: Logger;
    getPreviousResource: (currentResource: Resource) => Promise<Resource | undefined>;
};

export declare function resourceMatchesSubscriptionCriteria({ resource, subscription, context, getPreviousResource, logger, }: ResourceMatchesSubscriptionCriteria): Promise<boolean>;

export declare type ResourceWithCode = Resource & Code;

export declare const RXNORM = "http://www.nlm.nih.gov/research/umls/rxnorm";

/**
 * Checks that there is an access policy permitting the given resource interaction, returning the matching policy object.
 * @param resource - The resource being acted upon.
 * @param interaction - The interaction being performed on the resource.
 * @param accessPolicy - The relevant access policy for the current user.
 * @returns The satisfied access policy, or undefined if the access policy does not permit the given interaction.
 */
export declare function satisfiedAccessPolicy(resource: Resource, interaction: AccessPolicyInteraction, accessPolicy: AccessPolicy | undefined): AccessPolicyResource | undefined;

export declare interface SearchParameterDetails {
    readonly type: SearchParameterType;
    readonly elementDefinitions?: InternalSchemaElement[];
    readonly array?: boolean;
}

export declare const SearchParameterType: {
    readonly BOOLEAN: "BOOLEAN";
    readonly NUMBER: "NUMBER";
    readonly QUANTITY: "QUANTITY";
    readonly TEXT: "TEXT";
    readonly REFERENCE: "REFERENCE";
    readonly CANONICAL: "CANONICAL";
    readonly DATE: "DATE";
    readonly DATETIME: "DATETIME";
    readonly PERIOD: "PERIOD";
    readonly UUID: "UUID";
};

export declare type SearchParameterType = (typeof SearchParameterType)[keyof typeof SearchParameterType];

export declare interface SearchRequest<T extends Resource = Resource> {
    readonly resourceType: T['resourceType'];
    filters?: Filter[];
    sortRules?: SortRule[];
    cursor?: string;
    offset?: number;
    count?: number;
    fields?: string[];
    name?: string;
    total?: 'none' | 'estimate' | 'accurate';
    include?: IncludeTarget[];
    revInclude?: IncludeTarget[];
    summary?: 'true' | 'text' | 'data';
    format?: string;
    pretty?: boolean;
    types?: T['resourceType'][];
}

/**
 * Represents a "selection structure" in the SQL-on-FHIR specification.
 *
 * In practice, this can be a ViewDefinition or ViewDefinitionSelect.
 *
 * TypeScript does not like checks for properties that are not part of the type, so we use this interface instead.
 */
export declare interface SelectionStructure {
    forEach?: string;
    forEachOrNull?: string;
    column?: ViewDefinitionSelect['column'];
    select?: SelectionStructure[];
    unionAll?: SelectionStructure[];
}

/**
 * Creates a serialized url-encoded payload for a `FHIRcast` subscription from a `SubscriptionRequest` object that can be directly used in an HTTP request to the Hub.
 *
 * @param subscriptionRequest - An object representing a subscription request.
 * @returns A serialized subscription in url-encoded form.
 */
export declare function serializeFhircastSubscriptionRequest(subscriptionRequest: SubscriptionRequest | PendingSubscriptionRequest): string;

export declare function serverError(err: Error): OperationOutcome;

export declare function serverTimeout(msg?: string): OperationOutcome;

/**
 * Sets a code for a given system within a given codeable concept.
 * @param concept - The codeable concept.
 * @param system - The system string.
 * @param code - The code value.
 */
export declare function setCodeBySystem(concept: CodeableConcept, system: string, code: string): void;

/**
 * Sets a resource identifier for the given system.
 *
 * Note that this method is only available on resources that have an "identifier" property,
 * and that property must be an array of Identifier objects,
 * which is not true for all FHIR resources.
 *
 * If the identifier already exists, then the value is updated.
 *
 * Otherwise a new identifier is added.
 *
 * @param resource - The resource to add the identifier to.
 * @param system - The identifier system.
 * @param value - The identifier value.
 */
export declare function setIdentifier(resource: Resource & {
    identifier?: Identifier[];
}, system: string, value: string): void;

export declare function singleton(collection: TypedValue[], type?: string): TypedValue | undefined;

export declare function singularize<T>(value: T | T[] | undefined): T | undefined;

/**
 * Sleeps for the specified number of milliseconds.
 * @param ms - Time delay in milliseconds
 * @returns A promise that resolves after the specified number of milliseconds.
 */
export declare const sleep: (ms: number) => Promise<void>;

export declare interface SliceDefinition extends Omit<InternalSchemaElement, 'slicing'> {
    name: string;
    definition?: string;
    elements: Record<string, InternalSchemaElement>;
}

export declare type SliceDefinitionWithTypes = SliceDefinition & {
    type: NonNullable<SliceDefinition['type']>;
    typeSchema?: InternalTypeSchema;
};

export declare interface SliceDiscriminator {
    path: string;
    type: string;
}

export declare interface SlicingRules {
    discriminator: SliceDiscriminator[];
    ordered: boolean;
    rule?: 'open' | 'closed' | 'openAtEnd';
    slices: SliceDefinition[];
}

export declare const SNOMED = "http://snomed.info/sct";

export declare interface SortRule {
    code: string;
    descending?: boolean;
}

/**
 * Sorts an array of strings in place using the localeCompare method.
 *
 * This method will mutate the input array.
 *
 * @param array - The array of strings to sort.
 * @returns The sorted array of strings.
 */
export declare function sortStringArray(array: string[]): string[];

/**
 * Splits a string into an array of strings using the specified delimiter.
 * Unlike the built-in split function, this function will split the string into a maximum of exactly n parts.
 * Trailing empty strings are included in the result.
 * @param str - The string to split.
 * @param delim - The delimiter.
 * @param n - The maximum number of parts to split the string into.
 * @returns The resulting array of strings.
 */
export declare function splitN(str: string, delim: string, n: number): string[];

/**
 * Splits a FHIR search value on commas.
 * Respects backslash escape.
 *
 * See: https://hl7.org/fhir/r4/search.html#escaping
 *
 * @param input - The FHIR search value to split.
 * @returns The individual search values.
 */
export declare function splitSearchOnComma(input: string): string[];

/**
 * Reads data from a Readable stream and returns a Promise that resolves with a Buffer containing all the data.
 * @param stream - The Readable stream to read from.
 * @returns A Promise that resolves with a Buffer containing all the data from the Readable stream.
 */
export declare function streamToBuffer(stream: Readable): Promise<Buffer>;

/**
 * Returns the FHIR JSON string representation of the input value.
 *
 * Removes properties with empty string values.
 * Removes objects with zero properties.
 *
 * Does not modify the input value.
 * If the input value does not contain any empty properties, then the original value is returned.
 * Otherwise, a new value is returned with the empty properties removed.
 *
 * See: https://www.hl7.org/fhir/json.html
 *
 * @param value - The input value.
 * @param pretty - Optional flag to pretty-print the JSON.
 * @returns The resulting JSON string.
 */
export declare function stringify(value: any, pretty?: boolean): string;

/**
 * Output the string representation of a value, suitable for use as part of a search query.
 * @param v - The value to format as a string
 * @returns The stringified value
 */
export declare function stringifyTypedValue(v: TypedValue): string;

export declare type StringMap = {
    [key: string]: string;
};

/**
 * Transforms input values using a FHIR StructureMap.
 *
 * See: https://www.hl7.org/fhir/mapping-language.html
 *
 * @param structureMap - The StructureMap to transform.
 * @param input - The input values.
 * @param transformMaps - Optional collection of imported StructureMaps and ConceptMaps.
 * @returns The transformed values.
 */
export declare function structureMapTransform(structureMap: StructureMap, input: TypedValue[], transformMaps?: TransformMapCollection): TypedValue[];

export declare interface SubManagerOptions {
    ReconnectingWebSocket?: IReconnectingWebSocketCtor;
    pingIntervalMs?: number;
    debug?: boolean;
    debugLogger?: (...args: any[]) => void;
}

/**
 * An `EventTarget` that emits events when new subscription notifications come in over WebSockets.
 *
 * -----
 *
 * ### Events emitted:
 *
 * - `connect` - A new subscription is connected to the `SubscriptionManager` and `message` events for this subscription can be expected.
 * - `disconnect` - The specified subscription is no longer being monitored by the `SubscriptionManager`.
 * - `error` - An error has occurred.
 * - `message` - A message containing a notification `Bundle` has been received.
 * - `open` - The WebSocket has been opened.
 * - `close` - The WebSocket has been closed.
 * - `heartbeat` - A `heartbeat` message has been received.
 */
export declare class SubscriptionEmitter extends TypedEventTarget<SubscriptionEventMap> {
    private readonly criteria;
    constructor(...criteria: string[]);
    getCriteria(): Set<string>;
    /**
     * @internal
     * @param criteria - The criteria to add to this `SubscriptionEmitter`.
     */
    _addCriteria(criteria: string): void;
    /**
     * @internal
     * @param criteria - The criteria to remove from this `SubscriptionEmitter`.
     */
    _removeCriteria(criteria: string): void;
}

export declare type SubscriptionEventMap = {
    connect: {
        type: 'connect';
        payload: {
            subscriptionId: string;
        };
    };
    disconnect: {
        type: 'disconnect';
        payload: {
            subscriptionId: string;
        };
    };
    error: {
        type: 'error';
        payload: Error;
    };
    message: {
        type: 'message';
        payload: Bundle;
    };
    open: {
        type: 'open';
    };
    close: {
        type: 'close';
    };
    heartbeat: {
        type: 'heartbeat';
        payload: Bundle;
    };
};

export declare class SubscriptionManager {
    private readonly medplum;
    private readonly ws;
    private masterSubEmitter?;
    private readonly criteriaEntries;
    private readonly criteriaEntriesBySubscriptionId;
    private wsClosed;
    private pingTimer;
    private readonly pingIntervalMs;
    private waitingForPong;
    private currentProfile;
    constructor(medplum: MedplumClient, wsUrl: URL | string, options?: SubManagerOptions);
    private setupListeners;
    private emitError;
    private maybeEmitDisconnect;
    private getTokenForCriteria;
    private maybeGetCriteriaEntry;
    private getAllCriteriaEmitters;
    private addCriteriaEntry;
    private removeCriteriaEntry;
    private subscribeToCriteria;
    private refreshAllSubscriptions;
    addCriteria(criteria: string, subscriptionProps?: Partial<Subscription>): SubscriptionEmitter;
    removeCriteria(criteria: string, subscriptionProps?: Partial<Subscription>): void;
    getWebSocket(): IReconnectingWebSocket;
    closeWebSocket(): void;
    reconnectWebSocket(): void;
    getCriteriaCount(): number;
    getMasterEmitter(): SubscriptionEmitter;
}

/**
 * A `FHIRcast` subscription request.
 *
 * Can be passed to `MedplumClient.fhircastConnect` or `MedplumClient.fhircastUnsubscribe` to either open a `FHIRcast` connection, or unsubscribe from the subscription.
 */
export declare type SubscriptionRequest = {
    channelType: 'websocket';
    mode: 'subscribe' | 'unsubscribe';
    events: FhircastEventName[];
    topic: string;
    endpoint: string;
};

/**
 * Construct the subset of a resource containing a minimum set of fields.  The returned resource is not guaranteed
 * to contain only the provided properties, and may contain others (e.g. `resourceType` and `id`)
 *
 * @param resource - The resource to subset
 * @param properties - The minimum properties to include in the subset
 * @returns The modified resource, containing the listed properties and possibly other mandatory ones
 */
export declare function subsetResource<T extends Resource>(resource: T | undefined, properties: string[]): T | undefined;

export declare class SymbolAtom implements Atom {
    readonly name: string;
    constructor(name: string);
    eval(context: AtomContext, input: TypedValue[]): TypedValue[];
    private getVariable;
    private evalValue;
    toString(): string;
}

/**
 * Converts unknown object into a JavaScript boolean.
 * Note that this is different than the FHIRPath "toBoolean",
 * which has particular semantics around arrays, empty arrays, and type conversions.
 * @param obj - Any value or array of values.
 * @returns The converted boolean value according to FHIRPath rules.
 */
export declare function toJsBoolean(obj: TypedValue[]): boolean;

export declare interface Token extends Marker {
    id: string;
    value: string;
}

export declare class Tokenizer {
    private readonly str;
    private readonly keywords;
    private readonly operators;
    private readonly dateTimeLiterals;
    private readonly symbolRegex;
    private readonly result;
    private readonly pos;
    private readonly markStack;
    constructor(str: string, keywords: string[], operators: string[], options?: TokenizerOptions);
    tokenize(): Token[];
    private prevToken;
    private peekToken;
    private consumeToken;
    private consumeWhitespace;
    private consumeMultiLineComment;
    private consumeSingleLineComment;
    private consumeString;
    private consumeQuotedSymbol;
    private consumeDateTime;
    private consumeNumber;
    private consumeSymbol;
    private consumeOperator;
    private consumeWhile;
    private curr;
    private prev;
    private peek;
    private mark;
    private reset;
    private advance;
    private buildToken;
}

export declare interface TokenizerOptions {
    dateTimeLiterals?: boolean;
    symbolRegex?: RegExp;
}

export declare interface TokenResponse {
    readonly token_type: string;
    readonly id_token: string;
    readonly access_token: string;
    readonly refresh_token: string;
    readonly expires_in: number;
    readonly project: Reference<Project>;
    readonly profile: Reference<ProfileResource>;
}

export declare const tooManyRequests: OperationOutcome;

/**
 * Tries to convert an unknown input value to a Period object.
 * @param input - Unknown input value.
 * @returns A Period object or undefined.
 */
export declare function toPeriod(input: unknown): Period | undefined;

/**
 * Returns a "best guess" TypedValue for a given value.
 * @param value - The unknown value to check.
 * @returns A "best guess" TypedValue for the given value.
 */
export declare function toTypedValue(value: unknown): TypedValue;

/**
 * The TransformMapCollection class is a collection of StructureMap and ConceptMap resources.
 * It is used to store and retrieve imported StructureMaps and ConceptMaps by URL.
 */
export declare class TransformMapCollection {
    readonly resources: (StructureMap | ConceptMap)[];
    constructor(resources?: (StructureMap | ConceptMap)[]);
    get<K extends ResourceType>(resourceType: K, url: string): ExtractResource<K>[];
    private matchesUrl;
}

export declare function tryGetDataType(type: string, profileUrl?: string): InternalTypeSchema | undefined;

/**
 * Returns the JWT expiration time in number of milliseconds elapsed since the epoch.
 * @param token - The JWT token.
 * @returns The JWT expiration time in number of milliseconds elapsed since the epoch if available, undefined if unknown.
 */
export declare function tryGetJwtExpiration(token: string): number | undefined;

export declare function tryGetProfile(profileUrl: string): InternalTypeSchema | undefined;

export declare class TypedEventTarget<TEvents extends Record<string, Event_2>> {
    private readonly emitter;
    dispatchEvent<TEventType extends keyof TEvents & string>(event: TEvents[TEventType]): void;
    addEventListener<TEventType extends keyof TEvents & string>(type: TEventType, handler: (event: TEvents[TEventType]) => void): void;
    removeEventListener<TEventType extends keyof TEvents & string>(type: TEventType, handler: (event: TEvents[TEventType]) => void): void;
    removeAllListeners(): void;
}

export declare interface TypedValue {
    readonly type: string;
    readonly value: any;
}

/**
 * Converts a typed value to a string.
 * @param typedValue - The typed value to convert to a string.
 * @returns The string representation of the typed value.
 */
export declare function typedValueToString(typedValue: TypedValue | undefined): string;

export declare type TypedValueWithPath = TypedValue & {
    path: string;
};

/**
 * An indexed TypeSchema.
 *
 * Example:  The IndexedStructureDefinition for "Patient" would include the following TypeSchemas:
 *   1) Patient
 *   2) Patient_Contact
 *   3) Patient_Communication
 *   4) Patient_Link
 */
export declare interface TypeInfo {
    searchParams?: Record<string, SearchParameter>;
    searchParamsDetails?: Record<string, SearchParameterDetails>;
}

export declare type TypeName<T> = T extends string ? 'string' : T extends number ? 'number' : T extends boolean ? 'boolean' : T extends undefined ? 'undefined' : 'object';

export declare const UCUM = "http://unitsofmeasure.org";

export declare class UnaryOperatorAtom extends PrefixOperatorAtom {
    readonly impl: (x: TypedValue[]) => TypedValue[];
    constructor(operator: string, child: Atom, impl: (x: TypedValue[]) => TypedValue[]);
    eval(context: AtomContext, input: TypedValue[]): TypedValue[];
    toString(): string;
}

export declare const unauthorized: OperationOutcome;

export declare const unauthorizedTokenAudience: OperationOutcome;

export declare const unauthorizedTokenExpired: OperationOutcome;

export declare class UnionAtom extends InfixOperatorAtom {
    constructor(left: Atom, right: Atom);
    eval(context: AtomContext, input: TypedValue[]): TypedValue[];
}

export declare const VALID_HOSTNAME_REGEX: RegExp;

/**
 * Validates that a `SubscriptionRequest`.
 *
 * @param subscriptionRequest - The `SubscriptionRequest` to validate.
 * @returns A `boolean` indicating whether or not the `SubscriptionRequest` is valid.
 */
export declare function validateFhircastSubscriptionRequest(subscriptionRequest: SubscriptionRequest | PendingSubscriptionRequest): boolean;

export declare function validateResource(resource: Resource, options?: ValidatorOptions): OperationOutcomeIssue[];

/**
 * Validates that the given string is a valid FHIR resource type.
 *
 * On success, silently returns void.
 * On failure, throws an OperationOutcomeError.
 *
 * @example
 * ```ts
 * validateResourceType('Patient'); // nothing
 * validateResourceType('XYZ'); // throws OperationOutcomeError
 * ```
 *
 * Note that this depends on globalSchema, which is populated by the StructureDefinition loader.
 *
 * @example
 * In a server context, you can load all schema definitions:
 *
 * ```ts
 * import { indexStructureDefinitionBundle } from '@medplum/core';
 * import { readJson } from '@medplum/definitions';
 * import { Bundle } from '@medplum/fhirtypes';
 *
 * indexStructureDefinitionBundle(readJson('fhir/r4/profiles-resources.json') as Bundle);
 * ```
 *
 * @example
 * In a client context, you can load the schema definitions using MedplumClient:
 *
 * ```ts
 * import { MedplumClient } from '@medplum/core';
 *
 * const medplum = new MedplumClient();
 * await medplum.requestSchema('Patient');
 * ```
 *
 * @param resourceType - The candidate resource type string.
 */
export declare function validateResourceType(resourceType: string): void;

export declare function validateTypedValue(typedValue: TypedValue, options?: ValidatorOptions): OperationOutcomeIssue[];

export declare function validationError(details: string): OperationOutcome;

export declare const validationRegexes: Record<string, RegExp>;

export declare interface ValidatorOptions {
    profile?: StructureDefinition;
}

export declare type ValueOrExternalSecret<T extends ExternalSecretPrimitive> = T | ExternalSecret<T>;

/**
 * ValueSet $expand operation parameters.
 * See: https://hl7.org/fhir/r4/valueset-operation-expand.html
 */
export declare interface ValueSetExpandParams {
    url?: string;
    filter?: string;
    date?: string;
    offset?: number;
    count?: number;
}

/**
 * Checks if a newer version of Medplum is available and logs a warning if so.
 * @param appName - The name of the app to check the version for.
 * @param params - An optional list of key-value pairs to be appended to the URL query string.
 */
export declare function warnIfNewerVersionAvailable(appName: string, params?: Record<string, string>): Promise<void>;

declare type WebSocketEventMap_2 = {
    close: CloseEvent_2;
    error: ErrorEvent_2;
    message: MessageEvent;
    open: Event;
};
export { WebSocketEventMap_2 as WebSocketEventMap }

export declare type WithId<T> = T & {
    id: string;
};

/**
 * Returns a word-wrapped string.
 * Based on: https://stackoverflow.com/a/38709683
 * @param text - Original input string.
 * @param maxLength - Width in number of characters.
 * @returns Array of lines.
 */
export declare function wordWrap(text: string, maxLength: number): string[];

/**
 * 6.5.4. xor
 * Returns true if exactly one of the operands evaluates to true,
 * false if either both operands evaluate to true or both operands evaluate to false,
 * and the empty collection otherwise.
 */
export declare class XorAtom extends BooleanInfixOperatorAtom {
    constructor(left: Atom, right: Atom);
    eval(context: AtomContext, input: TypedValue[]): TypedValue[];
}

export { }
