@medplum/core 5.1.8 → 5.1.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/index.cjs +2 -2
- package/dist/cjs/index.cjs.map +2 -2
- package/dist/cjs/index.d.ts +4 -0
- package/dist/esm/index.d.ts +4 -0
- package/dist/esm/index.mjs +2 -2
- package/dist/esm/index.mjs.map +2 -2
- package/package.json +3 -3
package/dist/cjs/index.cjs
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
"use strict";var er=Object.defineProperty;var Ps=Object.getOwnPropertyDescriptor;var As=Object.getOwnPropertyNames;var ws=Object.prototype.hasOwnProperty;var Os=(r,e,t)=>e in r?er(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t;var Is=(r,e)=>{for(var t in e)er(r,t,{get:e[t],enumerable:!0})},ks=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of As(e))!ws.call(r,i)&&i!==t&&er(r,i,{get:()=>e[i],enumerable:!(n=Ps(e,i))||n.enumerable});return r};var Vs=r=>ks(er({},"__esModule",{value:!0}),r);var c=(r,e,t)=>Os(r,typeof e!="symbol"?e+"":e,t);var Ud={};Is(Ud,{AccessPolicyInteraction:()=>Pe,AckCode:()=>ad,AndAtom:()=>It,ArithemticOperatorAtom:()=>L,AsAtom:()=>ye,BooleanInfixOperatorAtom:()=>w,CPT:()=>Ls,ClientStorage:()=>rt,ConcatAtom:()=>Et,ContainsAtom:()=>Rt,ContentType:()=>O,DEFAULT_ACCEPT:()=>Zo,DEFAULT_MAX_SEARCH_COUNT:()=>iu,DEFAULT_SEARCH_COUNT:()=>nu,DataSampler:()=>Nr,DotAtom:()=>K,EMPTY:()=>g,EmptySetAtom:()=>bt,EqualsAtom:()=>Pt,EquivalentAtom:()=>wt,EventTarget:()=>Ir,ExternalSecretSystems:()=>yl,FHIRCAST_EVENT_NAMES:()=>kr,FHIRCAST_EVENT_RESOURCES:()=>jo,FHIRCAST_EVENT_VERSION_REQUIRED:()=>Vr,FHIRCAST_RESOURCE_TYPES:()=>Wo,FhirFilterComparison:()=>Kt,FhirFilterConnective:()=>Xt,FhirFilterNegation:()=>Yt,FhirPathAtom:()=>he,FhircastConnection:()=>Ut,FileBuilder:()=>xi,FunctionAtom:()=>ie,HTTP_HL7_ORG:()=>ct,HTTP_TERMINOLOGY_HL7_ORG:()=>Us,Hl7Context:()=>xe,Hl7Field:()=>X,Hl7Message:()=>Ti,Hl7Segment:()=>ot,ICD10:()=>Fs,ImpliesAtom:()=>Dt,InAtom:()=>Ct,IndexerAtom:()=>Ce,InfixOperatorAtom:()=>ce,IsAtom:()=>Re,LOINC:()=>Ds,LRUCache:()=>Q,LiteralAtom:()=>W,LogLevel:()=>We,LogLevelNames:()=>Ts,Logger:()=>bi,MEDPLUM_CLI_CLIENT_ID:()=>nl,MEDPLUM_RELEASES_URL:()=>Es,MEDPLUM_VERSION:()=>Fr,MedplumClient:()=>Ht,MedplumKeyValueClient:()=>Wt,MemoryStorage:()=>_r,MockAsyncClientStorage:()=>si,NDC:()=>Ns,NOOP:()=>xc,NotEqualsAtom:()=>At,NotEquivalentAtom:()=>Ot,OAuthClientAssertionType:()=>ts,OAuthGrantType:()=>Be,OAuthSigningAlgorithm:()=>dl,OAuthTokenAuthMethod:()=>ll,OAuthTokenType:()=>es,OperationOutcomeError:()=>f,Operator:()=>m,OperatorPrecedence:()=>T,OrAtom:()=>kt,PATIENT_PREFERRED_PHARMACY_URL:()=>Qr,PHARMACY_PREFERENCE_TYPE_SYSTEM:()=>Ri,PHARMACY_TYPE_PREFERRED:()=>Ci,PHARMACY_TYPE_PRIMARY:()=>Hr,Parser:()=>tr,ParserBuilder:()=>at,PrefixOperatorAtom:()=>st,PropertyType:()=>d,RXNORM:()=>_s,ReadablePromise:()=>U,ReconnectingWebSocket:()=>jt,ReturnAckCategory:()=>Mu,SNOMED:()=>Ms,SearchParameterType:()=>ae,SubscriptionEmitter:()=>it,SubscriptionManager:()=>Gt,SymbolAtom:()=>N,Tokenizer:()=>ge,TransformMapCollection:()=>jr,TypedEventTarget:()=>Y,UCUM:()=>Xr,UnaryOperatorAtom:()=>St,UnionAtom:()=>Ee,VALID_HOSTNAME_REGEX:()=>ho,XorAtom:()=>Vt,accepted:()=>Js,accessPolicySupportsInteraction:()=>Yn,addPreferredPharmacyToPatient:()=>md,addProfileToResource:()=>pc,allOk:()=>Bs,append:()=>z,applyDefaultValuesToElement:()=>Al,applyDefaultValuesToResource:()=>Pl,applyFixedOrPatternValue:()=>zt,arrayBufferToBase64:()=>Ln,arrayBufferToHex:()=>_n,arrayify:()=>Ve,assert:()=>zo,assertContextVersionOptional:()=>ti,assertOk:()=>ca,assertReleaseManifest:()=>Rs,badRequest:()=>R,booleanToTypedValue:()=>h,buildCdsRequest:()=>ju,buildElementsContext:()=>Br,buildTypeName:()=>Eo,businessRule:()=>Zs,calculateAge:()=>gt,calculateAgeString:()=>Fa,canReadResourceType:()=>Iu,canWriteResource:()=>Vu,canWriteResourceType:()=>ku,capitalize:()=>M,checkForNull:()=>Pi,checkIfValidMedplumVersion:()=>Ld,clearReleaseCache:()=>_d,codeableConceptMatchesToken:()=>Ya,codingMatchesToken:()=>so,compressElement:()=>la,concatUrls:()=>F,conceptMapTranslate:()=>mi,conflict:()=>Ks,convertContainedResourcesToBundle:()=>qu,convertToSearchableDates:()=>Gn,convertToSearchableNumbers:()=>Kc,convertToSearchableQuantities:()=>Yc,convertToSearchableReferences:()=>Qn,convertToSearchableStrings:()=>Hn,convertToSearchableTokens:()=>zn,convertToSearchableUris:()=>Xc,convertToTransactionBundle:()=>No,crawlTypedValue:()=>pr,crawlTypedValueAsync:()=>xa,createConstraintIssue:()=>ln,createFhircastMessagePayload:()=>Mr,createOperationOutcomeIssue:()=>ve,createPreferredPharmacyExtension:()=>bs,createProcessingIssue:()=>dn,createReference:()=>Te,createStructureIssue:()=>S,created:()=>qs,decodeBase64:()=>Fo,decodeBase64Url:()=>Xn,deepClone:()=>Se,deepEquals:()=>de,deepIncludes:()=>He,deriveIdentifierSearchParameter:()=>bd,encodeBase64:()=>Nt,encodeBase64Url:()=>Fu,encryptSHA256:()=>Zn,ensureNoLeadingSlash:()=>mo,ensureTrailingSlash:()=>Rr,escapeHtml:()=>yc,evalFhirPath:()=>Jc,evalFhirPathTyped:()=>P,evalSqlOnFhir:()=>Id,expandSampledData:()=>ui,expandSampledObservation:()=>Tl,extractAccountReferences:()=>br,fetchLatestVersionString:()=>Fd,fetchVersionManifest:()=>Yr,fhirPathArrayEquals:()=>An,fhirPathArrayEquivalent:()=>gr,fhirPathArrayNotEquals:()=>wn,fhirPathEquals:()=>Qe,fhirPathEquivalent:()=>Zi,fhirPathIs:()=>mt,fhirPathNot:()=>Pn,fhirTypeToJsType:()=>mr,findCodeBySystem:()=>Ka,findObservationInterval:()=>ec,findObservationReferenceRange:()=>tc,findObservationReferenceRanges:()=>uo,findResourceByCode:()=>uc,findResourceInBundle:()=>Wu,flatMapFilter:()=>hc,forbidden:()=>js,formatAddress:()=>go,formatCodeableConcept:()=>ze,formatCoding:()=>jn,formatDate:()=>bc,formatDateTime:()=>Cr,formatFamilyName:()=>Tc,formatGivenName:()=>vc,formatHl7DateTime:()=>vs,formatHumanName:()=>Ke,formatMoney:()=>Ic,formatObservationValue:()=>vo,formatPeriod:()=>Ec,formatQuantity:()=>fe,formatRange:()=>Oc,formatReferenceString:()=>yo,formatSearchQuery:()=>mu,formatTime:()=>Sc,formatTiming:()=>Ac,formatWallTime:()=>xo,generateId:()=>se,getAllDataTypes:()=>yn,getAllQuestionnaireAnswers:()=>Ua,getBuffer:()=>wr,getCodeBySystem:()=>Tr,getDataType:()=>ue,getDateProperty:()=>La,getDefaultValuesForNewSliceEntry:()=>wl,getDisplayString:()=>ro,getElementDefinition:()=>yt,getElementDefinitionFromElements:()=>Co,getElementDefinitionTypeName:()=>ar,getExpressionForResourceType:()=>wd,getExpressionsForResourceType:()=>Ii,getExtension:()=>le,getExtensionValue:()=>qa,getIdentifier:()=>oo,getImageSrc:()=>_a,getInnerDerivedIdentifierExpression:()=>Ai,getNestedProperty:()=>ke,getParsedDerivedIdentifierExpression:()=>wi,getParsedExpressionForResourceType:()=>Oi,getPathDifference:()=>pe,getPathDisplayName:()=>Fc,getPreferredPharmaciesFromPatient:()=>fd,getPropertyDisplayName:()=>Ro,getQueryString:()=>qn,getQuestionnaireAnswers:()=>Na,getRandomString:()=>Or,getReferenceString:()=>A,getResourceTypes:()=>Mc,getSearchParameter:()=>Lc,getSearchParameterDetails:()=>Sd,getSearchParameters:()=>_c,getStatus:()=>aa,getTypedPropertyValue:()=>D,getTypedPropertyValueWithPath:()=>fr,getTypedPropertyValueWithSchema:()=>Yi,getTypedPropertyValueWithoutSchema:()=>Xi,getValueSliceName:()=>di,getWebSocketUrl:()=>Bn,getWindow:()=>Lu,globalSchema:()=>q,gone:()=>$s,indexConceptMapCodings:()=>os,indexDefaultSearchParameters:()=>Tn,indexSearchParameter:()=>Pr,indexSearchParameterBundle:()=>Dc,indexStructureDefinitionBundle:()=>ur,inflateBaseSchema:()=>pn,inflateElement:()=>Bi,initFhirPathParserBuilder:()=>Xe,invalidSearchOperator:()=>xu,isAccepted:()=>ta,isAddPharmacyResponse:()=>gd,isBrowserEnvironment:()=>j,isCodeableConcept:()=>vr,isCoding:()=>xr,isCompletedSubscriptionRequest:()=>ri,isComplexTypeCode:()=>Sr,isConflict:()=>ia,isContextVersionRequired:()=>ei,isCreated:()=>ea,isDataTypeLoaded:()=>gn,isDateString:()=>On,isDateTimeString:()=>De,isDefined:()=>gc,isEmpty:()=>C,isError:()=>or,isFhirCriteriaMet:()=>Jo,isFhircastResourceType:()=>$o,isGone:()=>oa,isJwt:()=>ni,isLowerCase:()=>Xa,isMedplumAccessToken:()=>ii,isNodeEnvironment:()=>_u,isNotFound:()=>na,isObject:()=>E,isOk:()=>sr,isOperationOutcome:()=>je,isOrganizationArray:()=>yd,isPeriod:()=>In,isPopulated:()=>te,isPrimitiveType:()=>dt,isProfileLoaded:()=>xn,isProfileResource:()=>to,isQuantity:()=>I,isQuantityEquivalent:()=>kn,isRedirect:()=>ra,isReference:()=>G,isResource:()=>k,isResourceType:()=>lt,isResourceTypeSchema:()=>dr,isResourceWithId:()=>Je,isSliceDefinitionWithTypes:()=>li,isString:()=>Me,isStringArray:()=>Mn,isTextObject:()=>ao,isTypedValue:()=>Bc,isUUID:()=>Ja,isUnauthenticated:()=>sa,isValidDate:()=>Tt,isValidHostname:()=>dc,isValidMedplumSemver:()=>Cs,lazy:()=>Un,loadDataType:()=>lr,locationUtils:()=>oe,mapByIdentifier:()=>fc,matchDiscriminant:()=>hr,matchesRange:()=>Nn,matchesSearchRequest:()=>Ft,multipleMatches:()=>Qs,normalizeArrayBufferView:()=>Fn,normalizeCreateBinaryOptions:()=>ci,normalizeCreatePdfOptions:()=>rs,normalizeErrorString:()=>Oe,normalizeOperationOutcome:()=>ut,notFound:()=>sn,notModified:()=>Ws,operationOutcomeIssueToString:()=>Ui,operationOutcomeToString:()=>un,parseFhirPath:()=>Lt,parseFilterParameter:()=>sd,parseHl7DateTime:()=>ud,parseJWTPayload:()=>qt,parseLogLevel:()=>dd,parseMappingLanguage:()=>Ll,parseParameter:()=>ko,parseReference:()=>Va,parseSearchRequest:()=>Ze,parseStructureDefinition:()=>cr,parseXFhirQuery:()=>fu,pathToJSONPointer:()=>Ta,preciseEquals:()=>sc,preciseGreaterThan:()=>cc,preciseGreaterThanOrEquals:()=>fo,preciseLessThan:()=>ac,preciseLessThanOrEquals:()=>po,preciseRound:()=>oc,preconditionFailed:()=>Gs,projectAdminResourceTypes:()=>Do,protectedResourceTypes:()=>Vo,readInteractions:()=>Mo,redirect:()=>Xs,removeDuplicates:()=>ft,removePreferredPharmacyFromPatient:()=>hd,removeProfileFromResource:()=>mc,reorderBundle:()=>Uo,replaceQueryVariables:()=>qo,resolveId:()=>be,resourceMatchesSubscriptionCriteria:()=>tl,satisfiedAccessPolicy:()=>_o,serializeError:()=>Zt,serializeFhircastSubscriptionRequest:()=>Dr,serverError:()=>cn,serverTimeout:()=>Ys,setCodeBySystem:()=>Za,setIdentifier:()=>Ba,singleton:()=>J,singularize:()=>lc,sleep:()=>Er,sortStringArray:()=>vt,splitN:()=>_e,splitSearchOnComma:()=>et,streamToBuffer:()=>Od,stringify:()=>xt,stringifyTypedValue:()=>$n,structureMapTransform:()=>Fl,subsetResource:()=>fa,summarizeObservations:()=>gl,toJsBoolean:()=>B,toPeriod:()=>ht,toTypedValue:()=>b,tooManyRequests:()=>zs,trimTrailingEmptyElements:()=>$a,tryGetDataType:()=>Ge,tryGetJwtExpiration:()=>oi,tryGetProfile:()=>vn,typedValueToString:()=>Wn,unauthorized:()=>we,unauthorizedTokenAudience:()=>ir,unauthorizedTokenExpired:()=>an,unsupportedMediaType:()=>Hs,validateFhircastSubscriptionRequest:()=>Bt,validateResource:()=>Ea,validateResourceType:()=>xd,validateTypedValue:()=>Qi,validationError:()=>v,validationRegexes:()=>pt,warnIfNewerVersionAvailable:()=>Nd,wordWrap:()=>gs});module.exports=Vs(Ud);var Q=class{constructor(e=10){c(this,"max");c(this,"cache");this.max=e,this.cache=new Map}clear(){this.cache.clear()}get(e){let t=this.cache.get(e);return t&&(this.cache.delete(e),this.cache.set(e,t)),t}set(e,t){this.cache.has(e)?this.cache.delete(e):this.cache.size>=this.max&&this.cache.delete(this.first()),this.cache.set(e,t)}delete(e){this.cache.delete(e)}keys(){return this.cache.keys()}first(){return this.cache.keys().next().value}};var st=class{constructor(e,t){c(this,"operator");c(this,"child");this.operator=e,this.child=t}toString(){return`${this.operator}(${this.child.toString()})`}},ce=class{constructor(e,t,n){c(this,"operator");c(this,"left");c(this,"right");this.operator=e,this.left=t,this.right=n}toString(){return`(${this.left.toString()} ${this.operator} ${this.right.toString()})`}},at=class{constructor(){c(this,"prefixParselets",{});c(this,"infixParselets",{})}registerInfix(e,t){return this.infixParselets[e]=t,this}registerPrefix(e,t){return this.prefixParselets[e]=t,this}prefix(e,t,n){return this.registerPrefix(e,{parse(i,o){let s=i.consumeAndParse(t);return n(o,s)}})}infixLeft(e,t,n){return this.registerInfix(e,{parse(i,o,s){let a=i.consumeAndParse(t);return n(o,s,a)},precedence:t})}construct(e){return new tr(e,this.prefixParselets,this.infixParselets)}},tr=class{constructor(e,t,n){c(this,"tokens");c(this,"prefixParselets");c(this,"infixParselets");this.tokens=e,this.prefixParselets=t,this.infixParselets=n}hasMore(){return this.tokens.length>0}match(e){return this.peek()?.id!==e?!1:(this.consume(),!0)}consumeAndParse(e=1/0){let t=this.consume(),n=this.prefixParselets[t.id];if(!n)throw new Error(`Parse error at "${t.value}" (line ${t.line}, column ${t.column}). No matching prefix parselet.`);let i=n.parse(this,t);for(;e>this.getPrecedence();){let o=this.consume();i=this.getInfixParselet(o).parse(this,i,o)}return i}getPrecedence(){let e=this.peek();if(!e)return 1/0;let t=this.getInfixParselet(e);return t?t.precedence:1/0}consume(e,t){if(!this.tokens.length)throw new Error("Cant consume unknown more tokens.");if(e&&this.peek()?.id!==e){let n=this.peek();throw new Error(`Expected ${e} but got "${n.id}" (${n.value}) at line ${n.line} column ${n.column}.`)}if(t&&this.peek()?.value!==t){let n=this.peek();throw new Error(`Expected "${t}" but got "${n.value}" at line ${n.line} column ${n.column}.`)}return this.tokens.shift()}peek(){return this.tokens.length>0?this.tokens[0]:void 0}removeComments(){this.tokens=this.tokens.filter(e=>e.id!=="Comment")}getInfixParselet(e){return this.infixParselets[e.id==="Symbol"?e.value:e.id]}};var Xr="http://unitsofmeasure.org",Ds="http://loinc.org",Ms="http://snomed.info/sct",_s="http://www.nlm.nih.gov/research/umls/rxnorm",Ls="http://www.ama-assn.org/go/cpt",Fs="http://hl7.org/fhir/sid/icd-10",Ns="http://hl7.org/fhir/sid/ndc",ct="http://hl7.org",Us="http://terminology.hl7.org";var rr="created",Zr="gone",en="not-modified",tn="found",rn="not-found",nn="conflict",on="unauthorized",Vi="forbidden",Di="precondition-failed",Mi="unsupported-media-type",_i="multiple-matches",Li="too-many-requests",nr="accepted",Fi="server-timeout",Ni="business-rule",Bs={resourceType:"OperationOutcome",id:"ok",issue:[{severity:"information",code:"informational",details:{text:"All OK"}}]},qs={resourceType:"OperationOutcome",id:rr,issue:[{severity:"information",code:"informational",details:{text:"Created"}}]},Ws={resourceType:"OperationOutcome",id:en,issue:[{severity:"information",code:"informational",details:{text:"Not Modified"}}]},sn={resourceType:"OperationOutcome",id:rn,issue:[{severity:"error",code:"not-found",details:{text:"Not found"}}]},we={resourceType:"OperationOutcome",id:on,issue:[{severity:"error",code:"login",details:{text:"Unauthorized"}}]},an={...we,issue:[...we.issue,{severity:"error",code:"expired",details:{text:"Token expired"}}]},ir={...we,issue:[...we.issue,{severity:"error",code:"invalid",details:{text:"Token not issued for this audience"}}]},js={resourceType:"OperationOutcome",id:Vi,issue:[{severity:"error",code:"forbidden",details:{text:"Forbidden"}}]},$s={resourceType:"OperationOutcome",id:Zr,issue:[{severity:"error",code:"deleted",details:{text:"Gone"}}]},Gs={resourceType:"OperationOutcome",id:Di,issue:[{severity:"error",code:"processing",details:{text:"Precondition Failed"}}]},Hs={resourceType:"OperationOutcome",id:Mi,issue:[{severity:"error",code:"not-supported",details:{text:"Unsupported media type"}}]},Qs={resourceType:"OperationOutcome",id:_i,issue:[{severity:"error",code:"multiple-matches",details:{text:"Multiple resources found matching condition"}}]},zs={resourceType:"OperationOutcome",id:Li,issue:[{severity:"error",code:"throttled",details:{text:"Too Many Requests"}}]};function Js(r){return{resourceType:"OperationOutcome",id:nr,issue:[{severity:"information",code:"informational",details:{text:"Accepted"},diagnostics:r}]}}function R(r,e){return{resourceType:"OperationOutcome",issue:[{severity:"error",code:"invalid",details:{text:r},...e?{expression:[e]}:void 0}]}}function Ks(r,e){return{resourceType:"OperationOutcome",id:nn,issue:[{severity:"error",code:"conflict",details:{coding:e?[{code:e}]:void 0,text:r}}]}}function v(r,e,t,n){return{resourceType:"OperationOutcome",issue:[{severity:"error",code:t??"structure",details:{text:r},...e?{expression:e}:void 0,...n?{diagnostics:n}:void 0}]}}function cn(r){return{resourceType:"OperationOutcome",issue:[{severity:"error",code:"exception",details:{text:"Internal server error"},diagnostics:r.toString()}]}}function Ys(r){return{resourceType:"OperationOutcome",id:Fi,issue:[{severity:"error",code:"timeout",details:{text:r??"Server timeout"}}]}}function Xs(r){let e=r.toString();return{resourceType:"OperationOutcome",id:tn,issue:[{severity:"information",code:"informational",details:{coding:[{system:"urn:ietf:rfc:3986",code:e}],text:"Redirect to "+e}}]}}function Zs(r,e){return{resourceType:"OperationOutcome",id:Ni,issue:[{severity:"error",code:"business-rule",details:{id:r,text:e}}]}}function or(r){return!r||typeof r!="object"?!1:r instanceof Error||typeof DOMException<"u"&&r instanceof DOMException?!0:Object.prototype.toString.call(r)==="[object Error]"}function je(r){return typeof r=="object"&&r!==null&&r.resourceType==="OperationOutcome"}function sr(r){return r.id==="ok"||r.id===rr||r.id===en||r.id===nr}function ea(r){return r.id===rr}function ta(r){return r.id===nr}function ra(r){return r.id===tn}function na(r){return r.id===rn}function ia(r){return r.id===nn}function oa(r){return r.id===Zr}function sa(r){return r.id===on}function aa(r){switch(r.id){case"ok":return 200;case rr:return 201;case nr:return 202;case tn:return 302;case en:return 304;case on:return 401;case Vi:return 403;case rn:return 404;case nn:return 409;case Zr:return 410;case Di:case _i:return 412;case Mi:return 415;case Ni:return 422;case Li:return 429;case Fi:return 504;default:return r.issue?.[0]?.code==="exception"?500:400}}function ca(r,e){if(!sr(r)||e===void 0)throw new f(r)}var f=class extends Error{constructor(t,n){super(un(t),n);c(this,"outcome");this.name="OperationOutcomeError",this.outcome=t}};function ut(r){return r instanceof f?r.outcome:je(r)?r:R(Oe(r))}function Oe(r){return r?typeof r=="string"?r:or(r)?r.message:je(r)?un(r):typeof r=="object"&&"code"in r&&typeof r.code=="string"?r.code:JSON.stringify(r):"Unknown error"}function un(r){let e=r.issue?.map(Ui)??[];return e.length>0?e.join("; "):"Unknown error"}function Ui(r){let e;return r.details?.text?r.diagnostics?e=`${r.details.text} (${r.diagnostics})`:e=r.details.text:r.diagnostics?e=r.diagnostics:e="Unknown error",r.expression?.length&&(e+=` (${r.expression.join(", ")})`),e}function ve(r,e,t,n,i){let o={severity:r,code:e,details:{text:t},expression:[n]};return i&&(o.diagnostics=JSON.stringify(i)),o}function S(r,e){return ve("error","structure",e,r)}function ln(r,e){return ve("error","invariant",`Constraint ${e.key} not met: ${e.description}`,r,{fhirpath:e.expression})}function dn(r,e,t,n){return ve("error","processing",e,r,{...n,error:t})}var ua={"http://hl7.org/fhirpath/System.String":"string"};function la(r){let e={};return r.min!==0&&(e.min=r.min),r.max!==1&&Number.isFinite(r.max)?e.max=r.max:r.max===Number.POSITIVE_INFINITY&&(e.max=Number.MAX_SAFE_INTEGER),e.type=r.type?.map(t=>({...t,extension:void 0,code:ua[t.code]??t.code})),e}function Bi(r,e){let t=e.max&&e.max===Number.MAX_SAFE_INTEGER?Number.POSITIVE_INFINITY:e.max;return{path:r,description:"",type:e.type??[],min:e.min??0,max:t??1,isArray:!!t&&t>1,constraints:[]}}function pn(r){let e=Object.create(null);for(let[t,n]of Object.entries(r))e[t]={name:t,type:t,path:t,elements:Object.fromEntries(Object.entries(n.elements).map(([i,o])=>[i,Bi(i,o)])),constraints:[],innerTypes:[]};return e}var qi={Element:{elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]}}},BackboneElement:{elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},modifierExtension:{max:9007199254740991,type:[{code:"Extension"}]}}},Address:{elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},use:{type:[{code:"code"}]},type:{type:[{code:"code"}]},text:{type:[{code:"string"}]},line:{max:9007199254740991,type:[{code:"string"}]},city:{type:[{code:"string"}]},district:{type:[{code:"string"}]},state:{type:[{code:"string"}]},postalCode:{type:[{code:"string"}]},country:{type:[{code:"string"}]},period:{type:[{code:"Period"}]}}},Age:{elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},value:{type:[{code:"decimal"}]},comparator:{type:[{code:"code"}]},unit:{type:[{code:"string"}]},system:{type:[{code:"uri"}]},code:{type:[{code:"code"}]}}},Annotation:{elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},"author[x]":{type:[{code:"Reference",targetProfile:["http://hl7.org/fhir/StructureDefinition/Practitioner","http://hl7.org/fhir/StructureDefinition/Patient","http://hl7.org/fhir/StructureDefinition/RelatedPerson","http://hl7.org/fhir/StructureDefinition/Organization"]},{code:"string"}]},time:{type:[{code:"dateTime"}]},text:{min:1,type:[{code:"markdown"}]}}},Attachment:{elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},contentType:{type:[{code:"code"}]},language:{type:[{code:"code"}]},data:{type:[{code:"base64Binary"}]},url:{type:[{code:"url"}]},size:{type:[{code:"unsignedInt"}]},hash:{type:[{code:"base64Binary"}]},title:{type:[{code:"string"}]},creation:{type:[{code:"dateTime"}]}}},CodeableConcept:{elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},coding:{max:9007199254740991,type:[{code:"Coding"}]},text:{type:[{code:"string"}]}}},Coding:{elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},system:{type:[{code:"uri"}]},version:{type:[{code:"string"}]},code:{type:[{code:"code"}]},display:{type:[{code:"string"}]},userSelected:{type:[{code:"boolean"}]}}},ContactDetail:{elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},name:{type:[{code:"string"}]},telecom:{max:9007199254740991,type:[{code:"ContactPoint"}]}}},ContactPoint:{elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},system:{type:[{code:"code"}]},value:{type:[{code:"string"}]},use:{type:[{code:"code"}]},rank:{type:[{code:"positiveInt"}]},period:{type:[{code:"Period"}]}}},Contributor:{elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},type:{min:1,type:[{code:"code"}]},name:{min:1,type:[{code:"string"}]},contact:{max:9007199254740991,type:[{code:"ContactDetail"}]}}},Count:{elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},value:{type:[{code:"decimal"}]},comparator:{type:[{code:"code"}]},unit:{type:[{code:"string"}]},system:{type:[{code:"uri"}]},code:{type:[{code:"code"}]}}},DataRequirement:{elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},type:{min:1,type:[{code:"code"}]},profile:{max:9007199254740991,type:[{code:"canonical",targetProfile:["http://hl7.org/fhir/StructureDefinition/StructureDefinition"]}]},"subject[x]":{type:[{code:"CodeableConcept"},{code:"Reference",targetProfile:["http://hl7.org/fhir/StructureDefinition/Group"]}]},mustSupport:{max:9007199254740991,type:[{code:"string"}]},codeFilter:{max:9007199254740991,type:[{code:"DataRequirementCodeFilter"}]},dateFilter:{max:9007199254740991,type:[{code:"DataRequirementDateFilter"}]},limit:{type:[{code:"positiveInt"}]},sort:{max:9007199254740991,type:[{code:"DataRequirementSort"}]}}},DataRequirementCodeFilter:{elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},path:{type:[{code:"string"}]},searchParam:{type:[{code:"string"}]},valueSet:{type:[{code:"canonical",targetProfile:["http://hl7.org/fhir/StructureDefinition/ValueSet"]}]},code:{max:9007199254740991,type:[{code:"Coding"}]}}},DataRequirementDateFilter:{elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},path:{type:[{code:"string"}]},searchParam:{type:[{code:"string"}]},"value[x]":{type:[{code:"dateTime"},{code:"Period"},{code:"Duration"}]}}},DataRequirementSort:{elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},path:{min:1,type:[{code:"string"}]},direction:{min:1,type:[{code:"code"}]}}},Distance:{elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},value:{type:[{code:"decimal"}]},comparator:{type:[{code:"code"}]},unit:{type:[{code:"string"}]},system:{type:[{code:"uri"}]},code:{type:[{code:"code"}]}}},Dosage:{elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},modifierExtension:{max:9007199254740991,type:[{code:"Extension"}]},sequence:{type:[{code:"integer"}]},text:{type:[{code:"string"}]},additionalInstruction:{max:9007199254740991,type:[{code:"CodeableConcept"}]},patientInstruction:{type:[{code:"string"}]},timing:{type:[{code:"Timing"}]},"asNeeded[x]":{type:[{code:"boolean"},{code:"CodeableConcept"}]},site:{type:[{code:"CodeableConcept"}]},route:{type:[{code:"CodeableConcept"}]},method:{type:[{code:"CodeableConcept"}]},doseAndRate:{max:9007199254740991,type:[{code:"DosageDoseAndRate"}]},maxDosePerPeriod:{type:[{code:"Ratio"}]},maxDosePerAdministration:{type:[{code:"Quantity",profile:["http://hl7.org/fhir/StructureDefinition/SimpleQuantity"]}]},maxDosePerLifetime:{type:[{code:"Quantity",profile:["http://hl7.org/fhir/StructureDefinition/SimpleQuantity"]}]}}},DosageDoseAndRate:{elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},type:{type:[{code:"CodeableConcept"}]},"dose[x]":{type:[{code:"Range"},{code:"Quantity",profile:["http://hl7.org/fhir/StructureDefinition/SimpleQuantity"]}]},"rate[x]":{type:[{code:"Ratio"},{code:"Range"},{code:"Quantity",profile:["http://hl7.org/fhir/StructureDefinition/SimpleQuantity"]}]}}},Duration:{elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},value:{type:[{code:"decimal"}]},comparator:{type:[{code:"code"}]},unit:{type:[{code:"string"}]},system:{type:[{code:"uri"}]},code:{type:[{code:"code"}]}}},ElementDefinition:{elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},modifierExtension:{max:9007199254740991,type:[{code:"Extension"}]},path:{min:1,type:[{code:"string"}]},representation:{max:9007199254740991,type:[{code:"code"}]},sliceName:{type:[{code:"string"}]},sliceIsConstraining:{type:[{code:"boolean"}]},label:{type:[{code:"string"}]},code:{max:9007199254740991,type:[{code:"Coding"}]},slicing:{type:[{code:"ElementDefinitionSlicing"}]},short:{type:[{code:"string"}]},definition:{type:[{code:"markdown"}]},comment:{type:[{code:"markdown"}]},requirements:{type:[{code:"markdown"}]},alias:{max:9007199254740991,type:[{code:"string"}]},min:{type:[{code:"unsignedInt"}]},max:{type:[{code:"string"}]},base:{type:[{code:"ElementDefinitionBase"}]},contentReference:{type:[{code:"uri"}]},type:{max:9007199254740991,type:[{code:"ElementDefinitionType"}]},"defaultValue[x]":{type:[{code:"base64Binary"},{code:"boolean"},{code:"canonical"},{code:"code"},{code:"date"},{code:"dateTime"},{code:"decimal"},{code:"id"},{code:"instant"},{code:"integer"},{code:"markdown"},{code:"oid"},{code:"positiveInt"},{code:"string"},{code:"time"},{code:"unsignedInt"},{code:"uri"},{code:"url"},{code:"uuid"},{code:"Address"},{code:"Age"},{code:"Annotation"},{code:"Attachment"},{code:"CodeableConcept"},{code:"Coding"},{code:"ContactPoint"},{code:"Count"},{code:"Distance"},{code:"Duration"},{code:"HumanName"},{code:"Identifier"},{code:"Money"},{code:"Period"},{code:"Quantity"},{code:"Range"},{code:"Ratio"},{code:"Reference"},{code:"SampledData"},{code:"Signature"},{code:"Timing"},{code:"ContactDetail"},{code:"Contributor"},{code:"DataRequirement"},{code:"Expression"},{code:"ParameterDefinition"},{code:"RelatedArtifact"},{code:"TriggerDefinition"},{code:"UsageContext"},{code:"Dosage"},{code:"Meta"}]},meaningWhenMissing:{type:[{code:"markdown"}]},orderMeaning:{type:[{code:"string"}]},"fixed[x]":{type:[{code:"base64Binary"},{code:"boolean"},{code:"canonical"},{code:"code"},{code:"date"},{code:"dateTime"},{code:"decimal"},{code:"id"},{code:"instant"},{code:"integer"},{code:"markdown"},{code:"oid"},{code:"positiveInt"},{code:"string"},{code:"time"},{code:"unsignedInt"},{code:"uri"},{code:"url"},{code:"uuid"},{code:"Address"},{code:"Age"},{code:"Annotation"},{code:"Attachment"},{code:"CodeableConcept"},{code:"Coding"},{code:"ContactPoint"},{code:"Count"},{code:"Distance"},{code:"Duration"},{code:"HumanName"},{code:"Identifier"},{code:"Money"},{code:"Period"},{code:"Quantity"},{code:"Range"},{code:"Ratio"},{code:"Reference"},{code:"SampledData"},{code:"Signature"},{code:"Timing"},{code:"ContactDetail"},{code:"Contributor"},{code:"DataRequirement"},{code:"Expression"},{code:"ParameterDefinition"},{code:"RelatedArtifact"},{code:"TriggerDefinition"},{code:"UsageContext"},{code:"Dosage"},{code:"Meta"}]},"pattern[x]":{type:[{code:"base64Binary"},{code:"boolean"},{code:"canonical"},{code:"code"},{code:"date"},{code:"dateTime"},{code:"decimal"},{code:"id"},{code:"instant"},{code:"integer"},{code:"markdown"},{code:"oid"},{code:"positiveInt"},{code:"string"},{code:"time"},{code:"unsignedInt"},{code:"uri"},{code:"url"},{code:"uuid"},{code:"Address"},{code:"Age"},{code:"Annotation"},{code:"Attachment"},{code:"CodeableConcept"},{code:"Coding"},{code:"ContactPoint"},{code:"Count"},{code:"Distance"},{code:"Duration"},{code:"HumanName"},{code:"Identifier"},{code:"Money"},{code:"Period"},{code:"Quantity"},{code:"Range"},{code:"Ratio"},{code:"Reference"},{code:"SampledData"},{code:"Signature"},{code:"Timing"},{code:"ContactDetail"},{code:"Contributor"},{code:"DataRequirement"},{code:"Expression"},{code:"ParameterDefinition"},{code:"RelatedArtifact"},{code:"TriggerDefinition"},{code:"UsageContext"},{code:"Dosage"},{code:"Meta"}]},example:{max:9007199254740991,type:[{code:"ElementDefinitionExample"}]},"minValue[x]":{type:[{code:"date"},{code:"dateTime"},{code:"instant"},{code:"time"},{code:"decimal"},{code:"integer"},{code:"positiveInt"},{code:"unsignedInt"},{code:"Quantity"}]},"maxValue[x]":{type:[{code:"date"},{code:"dateTime"},{code:"instant"},{code:"time"},{code:"decimal"},{code:"integer"},{code:"positiveInt"},{code:"unsignedInt"},{code:"Quantity"}]},maxLength:{type:[{code:"integer"}]},condition:{max:9007199254740991,type:[{code:"id"}]},constraint:{max:9007199254740991,type:[{code:"ElementDefinitionConstraint"}]},mustSupport:{type:[{code:"boolean"}]},isModifier:{type:[{code:"boolean"}]},isModifierReason:{type:[{code:"string"}]},isSummary:{type:[{code:"boolean"}]},binding:{type:[{code:"ElementDefinitionBinding"}]},mapping:{max:9007199254740991,type:[{code:"ElementDefinitionMapping"}]}}},ElementDefinitionSlicingDiscriminator:{elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},type:{min:1,type:[{code:"code"}]},path:{min:1,type:[{code:"string"}]}}},ElementDefinitionSlicing:{elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},discriminator:{max:9007199254740991,type:[{code:"ElementDefinitionSlicingDiscriminator"}]},description:{type:[{code:"string"}]},ordered:{type:[{code:"boolean"}]},rules:{min:1,type:[{code:"code"}]}}},ElementDefinitionBase:{elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},path:{min:1,type:[{code:"string"}]},min:{min:1,type:[{code:"unsignedInt"}]},max:{min:1,type:[{code:"string"}]}}},ElementDefinitionType:{elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},code:{min:1,type:[{code:"uri"}]},profile:{max:9007199254740991,type:[{code:"canonical",targetProfile:["http://hl7.org/fhir/StructureDefinition/StructureDefinition","http://hl7.org/fhir/StructureDefinition/ImplementationGuide"]}]},targetProfile:{max:9007199254740991,type:[{code:"canonical",targetProfile:["http://hl7.org/fhir/StructureDefinition/StructureDefinition","http://hl7.org/fhir/StructureDefinition/ImplementationGuide"]}]},aggregation:{max:9007199254740991,type:[{code:"code"}]},versioning:{type:[{code:"code"}]}}},ElementDefinitionExample:{elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},label:{min:1,type:[{code:"string"}]},"value[x]":{min:1,type:[{code:"base64Binary"},{code:"boolean"},{code:"canonical"},{code:"code"},{code:"date"},{code:"dateTime"},{code:"decimal"},{code:"id"},{code:"instant"},{code:"integer"},{code:"markdown"},{code:"oid"},{code:"positiveInt"},{code:"string"},{code:"time"},{code:"unsignedInt"},{code:"uri"},{code:"url"},{code:"uuid"},{code:"Address"},{code:"Age"},{code:"Annotation"},{code:"Attachment"},{code:"CodeableConcept"},{code:"Coding"},{code:"ContactPoint"},{code:"Count"},{code:"Distance"},{code:"Duration"},{code:"HumanName"},{code:"Identifier"},{code:"Money"},{code:"Period"},{code:"Quantity"},{code:"Range"},{code:"Ratio"},{code:"Reference"},{code:"SampledData"},{code:"Signature"},{code:"Timing"},{code:"ContactDetail"},{code:"Contributor"},{code:"DataRequirement"},{code:"Expression"},{code:"ParameterDefinition"},{code:"RelatedArtifact"},{code:"TriggerDefinition"},{code:"UsageContext"},{code:"Dosage"},{code:"Meta"}]}}},ElementDefinitionConstraint:{elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},key:{min:1,type:[{code:"id"}]},requirements:{type:[{code:"string"}]},severity:{min:1,type:[{code:"code"}]},human:{min:1,type:[{code:"string"}]},expression:{type:[{code:"string"}]},xpath:{type:[{code:"string"}]},source:{type:[{code:"canonical",targetProfile:["http://hl7.org/fhir/StructureDefinition/StructureDefinition"]}]}}},ElementDefinitionBinding:{elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},strength:{min:1,type:[{code:"code"}]},description:{type:[{code:"string"}]},valueSet:{type:[{code:"canonical",targetProfile:["http://hl7.org/fhir/StructureDefinition/ValueSet"]}]}}},ElementDefinitionMapping:{elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},identity:{min:1,type:[{code:"id"}]},language:{type:[{code:"code"}]},map:{min:1,type:[{code:"string"}]},comment:{type:[{code:"string"}]}}},Expression:{elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},description:{type:[{code:"string"}]},name:{type:[{code:"id"}]},language:{min:1,type:[{code:"code"}]},expression:{type:[{code:"string"}]},reference:{type:[{code:"uri"}]}}},Extension:{elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},url:{min:1,type:[{code:"uri"}]},"value[x]":{type:[{code:"base64Binary"},{code:"boolean"},{code:"canonical"},{code:"code"},{code:"date"},{code:"dateTime"},{code:"decimal"},{code:"id"},{code:"instant"},{code:"integer"},{code:"markdown"},{code:"oid"},{code:"positiveInt"},{code:"string"},{code:"time"},{code:"unsignedInt"},{code:"uri"},{code:"url"},{code:"uuid"},{code:"Address"},{code:"Age"},{code:"Annotation"},{code:"Attachment"},{code:"CodeableConcept"},{code:"Coding"},{code:"ContactPoint"},{code:"Count"},{code:"Distance"},{code:"Duration"},{code:"HumanName"},{code:"Identifier"},{code:"Money"},{code:"Period"},{code:"Quantity"},{code:"Range"},{code:"Ratio"},{code:"Reference"},{code:"SampledData"},{code:"Signature"},{code:"Timing"},{code:"ContactDetail"},{code:"Contributor"},{code:"DataRequirement"},{code:"Expression"},{code:"ParameterDefinition"},{code:"RelatedArtifact"},{code:"TriggerDefinition"},{code:"UsageContext"},{code:"Dosage"},{code:"Meta"}]}}},HumanName:{elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},use:{type:[{code:"code"}]},text:{type:[{code:"string"}]},family:{type:[{code:"string"}]},given:{max:9007199254740991,type:[{code:"string"}]},prefix:{max:9007199254740991,type:[{code:"string"}]},suffix:{max:9007199254740991,type:[{code:"string"}]},period:{type:[{code:"Period"}]}}},Identifier:{elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},use:{type:[{code:"code"}]},type:{type:[{code:"CodeableConcept"}]},system:{type:[{code:"uri"}]},value:{type:[{code:"string"}]},period:{type:[{code:"Period"}]},assigner:{type:[{code:"Reference",targetProfile:["http://hl7.org/fhir/StructureDefinition/Organization"]}]}}},MarketingStatus:{elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},modifierExtension:{max:9007199254740991,type:[{code:"Extension"}]},country:{min:1,type:[{code:"CodeableConcept"}]},jurisdiction:{type:[{code:"CodeableConcept"}]},status:{min:1,type:[{code:"CodeableConcept"}]},dateRange:{min:1,type:[{code:"Period"}]},restoreDate:{type:[{code:"dateTime"}]}}},Meta:{elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},versionId:{type:[{code:"id"}]},lastUpdated:{type:[{code:"instant"}]},source:{type:[{code:"uri"}]},profile:{max:9007199254740991,type:[{code:"canonical",targetProfile:["http://hl7.org/fhir/StructureDefinition/StructureDefinition"]}]},security:{max:9007199254740991,type:[{code:"Coding"}]},tag:{max:9007199254740991,type:[{code:"Coding"}]},project:{type:[{code:"uri"}]},author:{type:[{code:"Reference"}]},onBehalfOf:{type:[{code:"Reference"}]},account:{type:[{code:"Reference"}]},accounts:{max:9007199254740991,type:[{code:"Reference"}]},compartment:{max:9007199254740991,type:[{code:"Reference"}]}}},Money:{elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},value:{type:[{code:"decimal"}]},currency:{type:[{code:"code"}]}}},Narrative:{elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},status:{min:1,type:[{code:"code"}]},div:{min:1,type:[{code:"xhtml"}]}}},ParameterDefinition:{elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},name:{type:[{code:"code"}]},use:{min:1,type:[{code:"code"}]},min:{type:[{code:"integer"}]},max:{type:[{code:"string"}]},documentation:{type:[{code:"string"}]},type:{min:1,type:[{code:"code"}]},profile:{type:[{code:"canonical",targetProfile:["http://hl7.org/fhir/StructureDefinition/StructureDefinition"]}]}}},Period:{elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},start:{type:[{code:"dateTime"}]},end:{type:[{code:"dateTime"}]}}},Population:{elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},modifierExtension:{max:9007199254740991,type:[{code:"Extension"}]},"age[x]":{type:[{code:"Range"},{code:"CodeableConcept"}]},gender:{type:[{code:"CodeableConcept"}]},race:{type:[{code:"CodeableConcept"}]},physiologicalCondition:{type:[{code:"CodeableConcept"}]}}},ProdCharacteristic:{elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},modifierExtension:{max:9007199254740991,type:[{code:"Extension"}]},height:{type:[{code:"Quantity"}]},width:{type:[{code:"Quantity"}]},depth:{type:[{code:"Quantity"}]},weight:{type:[{code:"Quantity"}]},nominalVolume:{type:[{code:"Quantity"}]},externalDiameter:{type:[{code:"Quantity"}]},shape:{type:[{code:"string"}]},color:{max:9007199254740991,type:[{code:"string"}]},imprint:{max:9007199254740991,type:[{code:"string"}]},image:{max:9007199254740991,type:[{code:"Attachment"}]},scoring:{type:[{code:"CodeableConcept"}]}}},ProductShelfLife:{elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},modifierExtension:{max:9007199254740991,type:[{code:"Extension"}]},identifier:{type:[{code:"Identifier"}]},type:{min:1,type:[{code:"CodeableConcept"}]},period:{min:1,type:[{code:"Quantity"}]},specialPrecautionsForStorage:{max:9007199254740991,type:[{code:"CodeableConcept"}]}}},Quantity:{elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},value:{type:[{code:"decimal"}]},comparator:{type:[{code:"code"}]},unit:{type:[{code:"string"}]},system:{type:[{code:"uri"}]},code:{type:[{code:"code"}]}}},Range:{elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},low:{type:[{code:"Quantity",profile:["http://hl7.org/fhir/StructureDefinition/SimpleQuantity"]}]},high:{type:[{code:"Quantity",profile:["http://hl7.org/fhir/StructureDefinition/SimpleQuantity"]}]}}},Ratio:{elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},numerator:{type:[{code:"Quantity"}]},denominator:{type:[{code:"Quantity"}]}}},Reference:{elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},reference:{type:[{code:"string"}]},type:{type:[{code:"uri"}]},identifier:{type:[{code:"Identifier"}]},display:{type:[{code:"string"}]}}},RelatedArtifact:{elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},type:{min:1,type:[{code:"code"}]},label:{type:[{code:"string"}]},display:{type:[{code:"string"}]},citation:{type:[{code:"markdown"}]},url:{type:[{code:"url"}]},document:{type:[{code:"Attachment"}]},resource:{type:[{code:"canonical",targetProfile:["http://hl7.org/fhir/StructureDefinition/Resource"]}]}}},SampledData:{elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},origin:{min:1,type:[{code:"Quantity",profile:["http://hl7.org/fhir/StructureDefinition/SimpleQuantity"]}]},period:{min:1,type:[{code:"decimal"}]},factor:{type:[{code:"decimal"}]},lowerLimit:{type:[{code:"decimal"}]},upperLimit:{type:[{code:"decimal"}]},dimensions:{min:1,type:[{code:"positiveInt"}]},data:{type:[{code:"string"}]}}},Signature:{elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},type:{min:1,max:9007199254740991,type:[{code:"Coding"}]},when:{min:1,type:[{code:"instant"}]},who:{min:1,type:[{code:"Reference",targetProfile:["http://hl7.org/fhir/StructureDefinition/Practitioner","http://hl7.org/fhir/StructureDefinition/PractitionerRole","http://hl7.org/fhir/StructureDefinition/RelatedPerson","http://hl7.org/fhir/StructureDefinition/Patient","http://hl7.org/fhir/StructureDefinition/Device","http://hl7.org/fhir/StructureDefinition/Organization"]}]},onBehalfOf:{type:[{code:"Reference",targetProfile:["http://hl7.org/fhir/StructureDefinition/Practitioner","http://hl7.org/fhir/StructureDefinition/PractitionerRole","http://hl7.org/fhir/StructureDefinition/RelatedPerson","http://hl7.org/fhir/StructureDefinition/Patient","http://hl7.org/fhir/StructureDefinition/Device","http://hl7.org/fhir/StructureDefinition/Organization"]}]},targetFormat:{type:[{code:"code"}]},sigFormat:{type:[{code:"code"}]},data:{type:[{code:"base64Binary"}]}}},SubstanceAmount:{elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},modifierExtension:{max:9007199254740991,type:[{code:"Extension"}]},"amount[x]":{type:[{code:"Quantity"},{code:"Range"},{code:"string"}]},amountType:{type:[{code:"CodeableConcept"}]},amountText:{type:[{code:"string"}]},referenceRange:{type:[{code:"SubstanceAmountReferenceRange"}]}}},SubstanceAmountReferenceRange:{elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},lowLimit:{type:[{code:"Quantity"}]},highLimit:{type:[{code:"Quantity"}]}}},Timing:{elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},modifierExtension:{max:9007199254740991,type:[{code:"Extension"}]},event:{max:9007199254740991,type:[{code:"dateTime"}]},repeat:{type:[{code:"TimingRepeat"}]},code:{type:[{code:"CodeableConcept"}]}}},TimingRepeat:{elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},"bounds[x]":{type:[{code:"Duration"},{code:"Range"},{code:"Period"}]},count:{type:[{code:"positiveInt"}]},countMax:{type:[{code:"positiveInt"}]},duration:{type:[{code:"decimal"}]},durationMax:{type:[{code:"decimal"}]},durationUnit:{type:[{code:"code"}]},frequency:{type:[{code:"positiveInt"}]},frequencyMax:{type:[{code:"positiveInt"}]},period:{type:[{code:"decimal"}]},periodMax:{type:[{code:"decimal"}]},periodUnit:{type:[{code:"code"}]},dayOfWeek:{max:9007199254740991,type:[{code:"code"}]},timeOfDay:{max:9007199254740991,type:[{code:"time"}]},when:{max:9007199254740991,type:[{code:"code"}]},offset:{type:[{code:"unsignedInt"}]}}},TriggerDefinition:{elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},type:{min:1,type:[{code:"code"}]},name:{type:[{code:"string"}]},"timing[x]":{type:[{code:"Timing"},{code:"Reference",targetProfile:["http://hl7.org/fhir/StructureDefinition/Schedule"]},{code:"date"},{code:"dateTime"}]},data:{max:9007199254740991,type:[{code:"DataRequirement"}]},condition:{type:[{code:"Expression"}]}}},UsageContext:{elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},code:{min:1,type:[{code:"Coding"}]},"value[x]":{min:1,type:[{code:"CodeableConcept"},{code:"Quantity"},{code:"Range"},{code:"Reference",targetProfile:["http://hl7.org/fhir/StructureDefinition/PlanDefinition","http://hl7.org/fhir/StructureDefinition/ResearchStudy","http://hl7.org/fhir/StructureDefinition/InsurancePlan","http://hl7.org/fhir/StructureDefinition/HealthcareService","http://hl7.org/fhir/StructureDefinition/Group","http://hl7.org/fhir/StructureDefinition/Location","http://hl7.org/fhir/StructureDefinition/Organization"]}]}}},MoneyQuantity:{elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},value:{type:[{code:"decimal"}]},comparator:{type:[{code:"code"}]},unit:{type:[{code:"string"}]},system:{type:[{code:"uri"}]},code:{type:[{code:"code"}]}}},SimpleQuantity:{elements:{id:{type:[{code:"string"}]},extension:{max:9007199254740991,type:[{code:"Extension"}]},value:{type:[{code:"decimal"}]},comparator:{max:0,type:[{code:"code"}]},unit:{type:[{code:"string"}]},system:{type:[{code:"uri"}]},code:{type:[{code:"code"}]}}},IdentityProvider:{elements:{authorizeUrl:{min:1,type:[{code:"string"}]},tokenUrl:{min:1,type:[{code:"string"}]},tokenAuthMethod:{type:[{code:"code"}]},userInfoUrl:{min:1,type:[{code:"string"}]},clientId:{min:1,type:[{code:"string"}]},clientSecret:{min:1,type:[{code:"string"}]},usePkce:{type:[{code:"boolean"}]},useSubject:{type:[{code:"boolean"}]}}}};function cr(r){return new mn(r).parse()}var Ie=pn(qi),hn=Object.create(null),Wi=Object.create(null),pa={"http://hl7.org/fhir/StructureDefinition/MoneyQuantity":"MoneyQuantity","http://hl7.org/fhir/StructureDefinition/SimpleQuantity":"SimpleQuantity","http://hl7.org/fhir/uv/sql-on-fhir/StructureDefinition/ViewDefinition":"ViewDefinition"};function Hi(r){let e;return e=Wi[r],e||(e=Wi[r]=Object.create(null)),e}function ur(r){let t=(Array.isArray(r)?r:r.entry?.map(n=>n.resource)??[]).filter(n=>n?.resourceType==="StructureDefinition");Tn(t);for(let n of t)lr(n)}function lr(r){if(!r?.name)throw new Error("Failed loading StructureDefinition from bundle");if(r.resourceType!=="StructureDefinition")return;let e=cr(r),t=pa[r.url],n,i;t?(n=Ie,i=t):r.url===`http://hl7.org/fhir/StructureDefinition/${r.type}`||r.url===`https://medplum.com/fhir/StructureDefinition/${r.type}`||r.type?.startsWith("http://")||r.type?.startsWith("https://")?(n=Ie,i=r.type):(n=Hi(r.url),i=r.type),n[i]=e;for(let o of e.innerTypes)o.parentType=e,n[o.name]=o;hn[r.url]=e}function yn(){return Ie}function gn(r){return!!Ie[r]}function Ge(r,e){if(e){let t=Hi(e)[r];if(t)return t}return Ie[r]}function ue(r,e){let t=Ge(r,e);if(!t)throw new f(R("Unknown data type: "+r));return t}function lt(r){let e=Ie[r];return e&&dr(e)}function xn(r){return!!hn[r]}function vn(r){return hn[r]}var mn=class{constructor(e){c(this,"root");c(this,"elements");c(this,"elementIndex");c(this,"index");c(this,"resourceSchema");c(this,"slicingContext");c(this,"innerTypes");c(this,"backboneContext");if(!e.snapshot?.element||e.snapshot.element.length===0)throw new Error(`No snapshot defined for StructureDefinition '${e.name}'`);this.root=e.snapshot.element[0],this.elements=e.snapshot.element.slice(1),this.elementIndex=Object.create(null),this.index=0,this.resourceSchema={name:e.name,path:this.root.path,title:e.title,type:e.type,url:e.url,version:e.version,kind:e.kind,description:ga(e),elements:{},constraints:this.parseElementDefinition(this.root).constraints,innerTypes:[],summaryProperties:new Set,mandatoryProperties:new Set},this.innerTypes=[]}parse(){let e=this.next();for(;e;){if(e.sliceName)this.parseSliceStart(e);else if(e.id?.includes(":")){if(this.slicingContext?.current){let t=fn(e,this.slicingContext.path);this.slicingContext.current.elements[t]=this.parseElementDefinition(e)}}else{let t=this.parseElementDefinition(e);this.checkFieldEnter(e,t);let n=this.backboneContext;for(;n;){if(e.path?.startsWith(n.path+".")){n.type.elements[fn(e,n.path)]=t;break}n=n.parent}if(!n){let i=fn(e,this.root.path);e.isSummary&&this.resourceSchema.summaryProperties?.add(i.replace("[x]","")),t.min>0&&this.resourceSchema.mandatoryProperties?.add(i.replace("[x]","")),this.resourceSchema.elements[i]=t}this.checkFieldExit(e)}e=this.next()}return this.checkFieldExit(),this.innerTypes.length>0&&(this.resourceSchema.innerTypes=this.innerTypes),this.resourceSchema}checkFieldEnter(e,t){this.isInnerType(e)&&this.enterInnerType(e),this.slicingContext&&!$e(this.slicingContext.path,e?.path)&&(this.slicingContext=void 0),e.slicing&&!this.slicingContext&&this.enterSlice(e,t)}enterInnerType(e){for(;this.backboneContext&&!$e(this.backboneContext?.path,e.path);)this.innerTypes.push(this.backboneContext.type),this.backboneContext=this.backboneContext.parent;let t=ar(e);this.backboneContext={type:{name:t,type:t,path:e.path,title:e.label,description:e.definition,elements:{},constraints:this.parseElementDefinition(e).constraints,innerTypes:[]},path:e.path,parent:$e(this.backboneContext?.path,e.path)?this.backboneContext:this.backboneContext?.parent}}enterSlice(e,t){ya(e)&&!this.peek()?.sliceName||(t.slicing={discriminator:(e.slicing?.discriminator??[]).map(n=>{if(n.type!=="value"&&n.type!=="pattern"&&n.type!=="type")throw new Error(`Unsupported slicing discriminator type: ${n.type}`);return{path:n.path,type:n.type}}),slices:[],ordered:e.slicing?.ordered??!1,rule:e.slicing?.rules},this.slicingContext={field:t.slicing,path:e.path??""})}checkFieldExit(e=void 0){if(this.backboneContext&&!$e(this.backboneContext.path,e?.path))if(this.backboneContext.parent)do this.innerTypes.push(this.backboneContext.type),this.backboneContext=this.backboneContext.parent;while(this.backboneContext&&!$e(this.backboneContext.path,e?.path));else this.innerTypes.push(this.backboneContext.type),this.backboneContext=void 0}next(){let e=this.peek();if(e)return this.index++,e}peek(){let e=this.elements[this.index];if(e){if(this.elementIndex[e.path??""]=e,e.contentReference){let t=e.contentReference.slice(e.contentReference.indexOf("#")+1),n=this.elementIndex[t];return n?{...n,id:e.id,path:e.path,min:e.min??n.min,max:e.max??n.max,base:{path:n.base?.path??t,min:e.base?.min??n.base?.min??n.min,max:e.base?.max??n.base?.max??n.max},contentReference:e.contentReference,definition:e.definition}:void 0}return e}}isInnerType(e){let t=this.peek();return!!($e(e?.path,t?.path)&&e.type?.some(n=>["BackboneElement","Element"].includes(n.code)))}parseSliceStart(e){if(!this.slicingContext)throw new Error(`Invalid slice start before discriminator: ${e.sliceName} (${e.id})`);this.slicingContext.current={...this.parseElementDefinition(e),name:e.sliceName??"",definition:e.definition,elements:{}},this.slicingContext.field.slices.push(this.slicingContext.current)}parseElementDefinitionType(e){return(e.type??[]).map(t=>{let n;return(t.code==="BackboneElement"||t.code==="Element")&&(n=ar(e)),n||(n=le(t,"http://hl7.org/fhir/StructureDefinition/structuredefinition-fhir-type")?.valueUrl),n||(n=t.code??""),{code:n,targetProfile:t.targetProfile,profile:t.profile}})}parseElementDefinition(e){let t=$i(e.max),n=e.base?.max?$i(e.base.max):t,i={type:"ElementDefinition",value:e};return{description:e.definition||"",path:e.path||e.base?.path||"",min:e.min??0,max:t,isArray:n>1,constraints:(e.constraint??[]).map(o=>({key:o.key??"",severity:o.severity??"error",expression:o.expression??"",description:o.human??""})),type:this.parseElementDefinitionType(e),fixed:Gi(D(i,"fixed[x]")),pattern:Gi(D(i,"pattern[x]")),binding:e.binding}}};function fa(r,e){if(!r)return;let t=[];for(let n of e){t.push("_"+n);let i=Ie[r.resourceType].elements[n+"[x]"];i&&t.push(...i.type.map(o=>n+M(o.code)))}for(let n of Object.getOwnPropertyNames(r))!e.includes(n)&&!t.includes(n)&&!ma.includes(n)&&Object.defineProperty(r,n,{enumerable:!1,writable:!1,value:void 0});return r.meta={...r.meta,tag:r.meta?.tag?r.meta.tag.concat(ji):[ji]},r}var ji={system:"http://hl7.org/fhir/v3/ObservationValue",code:"SUBSETTED"},ma=["resourceType","id","meta"];function $i(r){return r==="*"?Number.POSITIVE_INFINITY:Number.parseInt(r,10)}function fn(r,e=""){return ha(r.path,e)}function ha(r,e){return r?e&&r.startsWith(e)?r.substring(e.length+1):r:""}function $e(r,e){return!r||!e?!1:e.startsWith(r+".")||e===r}function Gi(r){return Array.isArray(r)&&r.length>0?r[0]:C(r)?void 0:r}function ya(r){let e=r.slicing?.discriminator;return!!(r.type?.some(t=>t.code==="Extension")&&e?.length===1&&e[0].type==="value"&&e[0].path==="url")}function ga(r){let e=r.description;return e?.startsWith(`Base StructureDefinition for ${r.name} Type: `)&&(e=e.substring(`Base StructureDefinition for ${r.name} Type: `.length)),e}function pr(r,e,t){new bn(r,e,t).crawl()}function xa(r,e,t){return new Sn(r,e,t).crawl()}var bn=class{constructor(e,t,n){c(this,"root");c(this,"visitor");c(this,"schema");c(this,"initialPath");c(this,"excludeMissingProperties");this.root=e,this.visitor=t,this.schema=n?.schema??ue(e.type),this.initialPath=n?.initialPath??this.schema.path,this.excludeMissingProperties=n?.skipMissingProperties}crawl(){this.crawlObject({...this.root,path:this.initialPath},this.schema,this.initialPath)}crawlObject(e,t,n){let i=k(e.value);if(i&&this.visitor.onEnterResource&&this.visitor.onEnterResource(n,e,t),this.visitor.onEnterObject&&this.visitor.onEnterObject(n,e,t),this.excludeMissingProperties)for(let o of Object.keys(e.value))this.crawlProperty(e,o,t,`${n}.${o}`);else for(let o of Object.keys(t.elements))this.crawlProperty(e,o,t,`${n}.${o}`);this.visitor.onExitObject&&this.visitor.onExitObject(n,e,t),i&&this.visitor.onExitResource&&this.visitor.onExitResource(n,e,t)}crawlProperty(e,t,n,i){let o=ke(e,t,{withPath:!0});this.visitor.visitProperty&&this.visitor.visitProperty(e,t,i,o,n);for(let s of o)for(let a of Ve(s))this.crawlPropertyValue(a,i,n)}crawlPropertyValue(e,t,n){if(!dt(e.type)){let i=n.innerTypes?.find(o=>o.name===e.type)??ue(e.type);this.crawlObject(e,i,t)}}},Sn=class{constructor(e,t,n){c(this,"root");c(this,"visitor");c(this,"schema");c(this,"initialPath");c(this,"excludeMissingProperties");this.root=e,this.visitor=t,this.schema=n?.schema??ue(e.type),this.initialPath=n?.initialPath??this.schema.path,this.excludeMissingProperties=n?.skipMissingProperties}async crawl(){return this.crawlObject({...this.root,path:this.initialPath},this.schema,this.initialPath)}async crawlObject(e,t,n){let i=k(e.value);if(i&&this.visitor.onEnterResource&&await this.visitor.onEnterResource(n,e,t),this.visitor.onEnterObject&&await this.visitor.onEnterObject(n,e,t),this.excludeMissingProperties&&e.value)for(let o of Object.keys(e.value))await this.crawlProperty(e,o,t,`${n}.${o}`);else for(let o of Object.keys(t.elements))await this.crawlProperty(e,o,t,`${n}.${o}`);this.visitor.onExitObject&&await this.visitor.onExitObject(n,e,t),i&&this.visitor.onExitResource&&await this.visitor.onExitResource(n,e,t)}async crawlProperty(e,t,n,i){let o=ke(e,t,{withPath:!0});if(this.visitor.visitPropertyAsync)for(let s of o)await this.visitor.visitPropertyAsync(e,t,i,s,n);for(let s of o)for(let a of Ve(s))await this.crawlPropertyValue(a,i,n)}async crawlPropertyValue(e,t,n){if(!dt(e.type)){let i=n.innerTypes?.find(o=>o.name===e.type)??ue(e.type);await this.crawlObject(e,i,t)}}};function ke(r,e,t){if(r===void 0)return[void 0];if(e==="$this")return[r];let n=t?.withPath?fr:D,[i,...o]=e.split("."),s=[n(r,i,t)];for(let a of o){let u=[];for(let l of s)if(Array.isArray(l))for(let p of l)u.push(n(p,a,t));else(t?.withPath&&l?.value!==void 0||!t?.withPath&&l!==void 0)&&u.push(n(l,a,t));s=u}return s}function fr(r,e,t){let n=r.path;return va(D(r,e,t),n,e)}function va(r,e,t){let n=e?e+".":"";return r===void 0?{type:"undefined",value:void 0,path:`${n}${t}`}:Array.isArray(r)?r.map((i,o)=>({...i,path:`${n}${t}[${o}]`})):{...r,path:`${n}${t}`}}function Ta(r){return r[0]===r[0].toUpperCase()&&(r=r.slice(r.indexOf(".")+1)),`.${r}`.replaceAll(".","/").replaceAll(/\[(\d+)]/g,(e,t)=>`/${t}`)}var mr={base64Binary:"string",boolean:"boolean",canonical:"string",code:"string",date:"string",dateTime:"string",decimal:"number",id:"string",instant:"string",integer:"number",integer64:"string",markdown:"string",oid:"string",positiveInt:"number",string:"string",time:"string",unsignedInt:"number",uri:"string",url:"string",uuid:"string",xhtml:"string","http://hl7.org/fhirpath/System.String":"string"},ba=new Q(1e3);function dt(r){return r==="undefined"||r in mr}var pt={canonical:/^\S*$/,code:/^[^\s]+( [^\s]+)*$/,date:/^(\d(\d(\d[1-9]|[1-9]0)|[1-9]00)|[1-9]000)(-(0[1-9]|1[0-2])(-(0[1-9]|[1-2]\d|3[0-1]))?)?$/,dateTime:/^(\d(\d(\d[1-9]|[1-9]0)|[1-9]00)|[1-9]000)(-(0[1-9]|1[0-2])(-(0[1-9]|[1-2]\d|3[0-1])(T([01]\d|2[0-3])(:[0-5]\d:([0-5]\d|60)(\.\d{1,9})?)?)?)?(Z|[+-]((0\d|1[0-3]):[0-5]\d|14:00)?)?)?$/,id:/^[A-Za-z0-9\-.]{1,64}$/,instant:/^(\d(\d(\d[1-9]|[1-9]0)|[1-9]00)|[1-9]000)-(0[1-9]|1[0-2])-(0[1-9]|[1-2]\d|3[0-1])T([01]\d|2[0-3]):[0-5]\d:([0-5]\d|60)(\.\d{1,9})?(Z|[+-]((0\d|1[0-3]):[0-5]\d|14:00))$/,markdown:/^[\r\n\t\u0020-\uFFFF]+$/,oid:/^urn:oid:[0-2](\.(0|[1-9]\d*))+$/,string:/^[\r\n\t\u0020-\uFFFF]+$/,time:/^([01]\d|2[0-3]):[0-5]\d:([0-5]\d|60)(\.\d{1,9})?$/,uri:/^\S*$/,url:/^\S*$/,uuid:/^urn:uuid:[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,xhtml:/.*/},Sa={"ele-1":!0,"dom-3":!0,"org-1":!0,"sdf-19":!0};function Ea(r,e){if(!lt(r.resourceType))throw new f(v("Invalid resource type"));return Qi(b(r),e)}function Qi(r,e){return new En(r,e).validate()}var En=class{constructor(e,t){c(this,"issues");c(this,"root");c(this,"resourceStack");c(this,"schema");c(this,"base64BinaryMaxBytes");c(this,"collect");this.issues=[],this.root=e,this.resourceStack=[],k(e.value)&&this.resourceStack.push(e.value),t?.profile?this.schema=cr(t.profile):this.schema=ue(e.type),this.base64BinaryMaxBytes=t?.base64BinaryMaxBytes??1*1024*1024,this.collect=t?.collect}currentResource(){return this.resourceStack.at(-1)}validate(){Rn(this.root.value,this.schema.path,this.issues),this.constraintsCheck({...this.root,path:this.schema.path},this.schema),pr(this.root,this,{schema:this.schema,initialPath:this.schema.path});for(let e of this.issues)if(e.severity==="error")throw new f({resourceType:"OperationOutcome",issue:this.issues});return this.issues}onExitObject(e,t,n){this.checkAdditionalProperties(t,n.elements,t.path)}onEnterResource(e,t){this.resourceStack.push(t.value)}onExitResource(){this.resourceStack.pop()}visitProperty(e,t,n,i,o){let s=o.elements[t];if(!s)throw new Error(`Missing element validation schema for ${t}`);for(let a of i){if(!this.checkPresence(a,s,n))return;let u;if(s.isArray){if(!Array.isArray(a)){this.issues.push(S(n,"Expected array of values for property"));return}u=a}else{if(Array.isArray(a)){this.issues.push(S(n,"Expected single value for property"));return}u=[a]}(u.length<s.min||u.length>s.max)&&this.issues.push(S(s.path,`Invalid number of values: expected ${s.min}..${Number.isFinite(s.max)?s.max:"*"}, but found ${u.length}`)),Pa(a,s)||this.issues.push(S(n,"Value did not match expected pattern"));let l=s.slicing?Object.fromEntries(s.slicing.slices.map(p=>[p.name,0])):void 0;for(let p of u){this.constraintsCheck(p,s),this.referenceTypeCheck(p,s),this.checkPropertyValue(p),this.collectValue(p,s);let y=Aa(p,s.slicing);y&&l&&(l[y]+=1)}this.validateSlices(s.slicing?.slices,l,n)}}checkPresence(e,t,n){return!Array.isArray(e)&&e.value===void 0?(t.min>0&&this.issues.push(S(e.path,"Missing required property")),!1):C(e)?(this.issues.push(S(n,"Invalid empty value")),!1):!0}checkPropertyValue(e){dt(e.type)?this.validatePrimitiveType(e):C(e.value)&&this.issues.push(S(e.path,"Invalid empty non-primitive value"))}validateSlices(e,t,n){if(!(!e||!t))for(let i of e){let o=t[i.name];(o<i.min||o>i.max)&&this.issues.push(S(n,`Incorrect number of values provided for slice '${i.name}': expected ${i.min}..${Number.isFinite(i.max)?i.max:"*"}, but found ${o}`))}}checkAdditionalProperties(e,t,n){let i=e.value;if(!i)return;let o={};for(let s of Object.keys(i)){if(s==="resourceType")continue;let a=Ca(e,s,t);if(a){let u,l;a.startsWith("_")?(u=a.slice(1),l=s.slice(1)):(u="_"+a,l="_"+s),u in o&&o[u]!==l&&this.issues.push(ve("warning","structure",`Type of primitive extension does not match the type of property "${a.startsWith("_")?a.slice(1):a}"`,a)),o[a]&&this.issues.push(ve("warning","structure",`Conflicting choice of type properties: "${s}", "${o[a]}"`,s)),o[a]=s;continue}!(s in t)&&!(s.startsWith("_")&&s.slice(1)in t)&&this.issues.push(S(`${n}.${s}`,`Invalid additional property "${s}"`))}}constraintsCheck(e,t){let n=t.constraints;for(let i of n??g)if(i.severity==="error"&&!(i.key in Sa)&&!this.isExpressionTrue(i,e)){this.issues.push(ln(e.path,i));return}}referenceTypeCheck(e,t){if(e.type!=="Reference")return;let n=e.value;if(!G(n)||n.reference.startsWith("#"))return;let i=n.reference.includes("?")?n.reference.split("?")[0]:n.reference.split("/")[0];if(!i)return;let o=t.type.find(y=>y.code==="Reference")?.targetProfile;if(!o)return;let s=ct+"/fhir/StructureDefinition/",a=s+"Resource",u=s+i,l="https://medplum.com/fhir/StructureDefinition/",p=l+i;for(let y of o)if(y===a||y===u||y===p||!y.startsWith(s)&&!y.startsWith(l))return;this.issues.push(ve("warning","structure",`Invalid reference: got "${i}", expected "${o.join('", "')}"`,e.path))}collectValue(e,t){t.binding?.valueSet&&t.binding.strength==="required"&&Oa(e.type)&&this.appendToken(t.binding.valueSet,e)}appendToken(e,t){if(!this.collect?.tokens)return;let n=this.collect.tokens[e];if(!n){let i=Object.keys(this.collect.tokens);for(let o of i)o.startsWith(e+"|")&&(n=this.collect.tokens[o])}for(let i of n??g)if(i.path===t.path)return;this.collect.tokens[e]=z(n,t)}isExpressionTrue(e,t){let n={"%context":t,"%ucum":b(Xr)},i=this.currentResource();i&&(n["%resource"]=b(i)),k(this.root.value)&&(n["%rootResource"]=this.root);try{let o=P(e.expression,[t],n,ba);return o.length===1&&o[0].value===!0}catch(o){return this.issues.push(dn(t.path,"Error evaluating invariant expression",o,{fhirpath:e.expression})),!1}}validatePrimitiveType(e){let[t,n]=wa(e),i=e.path;if(t){let{type:o,value:s}=t;if(!(o in mr)){this.issues.push(S(i,`Invalid JSON type: ${o} is not a valid FHIR type`));return}let a=mr[o];if(typeof s!==a){s!==null&&this.issues.push(S(i,`Invalid JSON type: expected ${a}, but got ${typeof s}`));return}o==="base64Binary"?this.validateBase64Binary(s,i):a==="string"?this.validateString(s,o,i):a==="number"&&this.validateNumber(s,o,i)}n&&pr(n,this,{schema:ue("Element"),initialPath:i})}validateBase64Binary(e,t){if(!Ia(e)){this.issues.push(S(t,"Invalid base64Binary format"));return}let n=0;e.endsWith("==")?n=2:e.endsWith("=")&&(n=1),Math.max(0,Math.floor(e.length*3/4)-n)>this.base64BinaryMaxBytes&&this.issues.push(S(t,`base64Binary exceeds ${this.base64BinaryMaxBytes} bytes`))}validateString(e,t,n){if(!e.trim()){this.issues.push(S(n,"String must contain non-whitespace content"));return}if(e.length>1024*1024){this.issues.push(S(n,"String cannot be larger than 1 MB"));return}let i=pt[t];i&&!i.exec(e)&&this.issues.push(S(n,"Invalid "+t+" format"))}validateNumber(e,t,n){Number.isNaN(e)||!Number.isFinite(e)?this.issues.push(S(n,"Invalid numeric value")):Ra(t)&&!Number.isInteger(e)?this.issues.push(S(n,"Expected number to be an integer")):t===d.positiveInt&&e<=0?this.issues.push(S(n,"Expected number to be positive")):t===d.unsignedInt&&e<0&&this.issues.push(S(n,"Expected number to be non-negative"))}};function Ra(r){return r===d.integer||r===d.positiveInt||r===d.unsignedInt}function Ca(r,e,t){let n="";e.startsWith("_")&&(e=e.slice(1),n="_");let i=e.split(/(?=[A-Z])/g),o="";for(let s of i){o+=s;let a=o+"[x]";if(t[a])return D(r,o)?n+a:void 0}}function Rn(r,e,t){for(let[n,i]of Object.entries(r)){let o=`${e}.${n}`,s=n.startsWith("_")?n.slice(1):`_${n}`;if(i===null)t.push(S(o,"Invalid null value"));else if(Array.isArray(i))for(let a=0;a<i.length;a++)i[a]===void 0?t.push(S(`${o}[${a}]`,"Invalid undefined value")):i[a]===null&&!r[s]?.[a]?t.push(S(`${o}[${a}]`,"Invalid null value")):i[a]&&Rn(i[a],`${o}[${a}]`,t);else typeof i=="object"&&Rn(i,o,t)}}function Pa(r,e){let t=Array.isArray(r)?r.map(n=>({type:n.type,value:n.value})):{type:r.type,value:r.value};return!(e.pattern&&!He(t,e.pattern)||e.fixed&&!de(t,e.fixed))}function hr(r,e,t,n){if(Array.isArray(r))return!1;let i;e.path==="$this"?i=t:i=(n??t.elements)[e.path];let o=t.type;switch(e.type){case"value":case"pattern":if(!r||!i)return!1;if(i.pattern)return He(r,i.pattern);if(i.fixed)return de(r,i.fixed);if(i.binding?.strength==="required"&&i.binding.valueSet)return!0;break;case"type":return!r||!o?.length?!1:o.some(s=>s.code===r.type)}return!1}function Aa(r,e){for(let t of e?.slices??g)if(e?.discriminator?.every(n=>Ve(ke(r,n.path))?.some(i=>hr(i,n,t))))return t.name}function wa(r){if(typeof r.value!="object"||!r.value)return[r,void 0];let e=r.value.valueOf();if(e===r.value)return[void 0,{type:"Element",value:r.value}];let t=new Set(Object.keys(e)),n=Object.entries(r.value).filter(([o,s])=>!t.has(o)),i=n.length>0?Object.fromEntries(n):void 0;return[{type:r.type,value:e},{type:"Element",value:i}]}function Oa(r){switch(r){case"CodeableConcept":case"Coding":case"code":case"Quantity":case"string":case"uri":return!0;default:return!1}}function Ia(r){if(r.length===0)return!1;let e=0;r.endsWith("==")?e=2:r.endsWith("=")&&(e=1);let t=r.length-e;if(t<0||(e+t)%4!==0)return!1;let n=e>0?r.slice(0,-e):r;return/^[A-Za-z\d+/]+$/.test(n)}function h(r){return[{type:d.boolean,value:r}]}function b(r){return r==null?{type:"undefined",value:void 0}:Number.isSafeInteger(r)?{type:d.integer,value:r}:typeof r=="number"?{type:d.decimal,value:r}:typeof r=="boolean"?{type:d.boolean,value:r}:typeof r=="string"?{type:d.string,value:r}:I(r)?{type:d.Quantity,value:r}:k(r)?{type:r.resourceType,value:r}:vr(r)?{type:d.CodeableConcept,value:r}:xr(r)?{type:d.Coding,value:r}:{type:d.BackboneElement,value:r}}function B(r){return r.length===0?!1:!!r[0].value}function J(r,e){if(r.length!==0){if(r.length===1&&(!e||r[0].type===e))return r[0];throw new Error(`Expected singleton of type ${e}, but found ${JSON.stringify(r)}`)}}function D(r,e,t){if(!r.value)return;let n=yt(r.type,e,t?.profileUrl);return n?Yi(r,e,n):Xi(r,e)}function Yi(r,e,t){let n=r.value,i=t.type;if(!i||i.length===0)return;let o,s="undefined",a,u=t.path.lastIndexOf("."),l=t.path.substring(u+1),p=l,y=!1;l.endsWith("[x]")&&(p=l.substring(0,l.length-3),y=!0);for(let x of i){let V=p;if(y&&(V+=M(x.code)),o=n[V],a=n["_"+V],o!==void 0||a!==void 0){s=x.code;break}}if(a)if(Array.isArray(o)){o=o.slice();for(let x=0;x<Math.max(o.length,a.length);x++)o[x]=Cn(o[x],a[x])}else if(!o&&Array.isArray(a)){o=a.slice();for(let x=0;x<a.length;x++)o[x]=Cn(void 0,a[x])}else o=Cn(o,a);if(!C(o))return(s==="Element"||s==="BackboneElement")&&(s=t.type[0].code),Array.isArray(o)?o.map(x=>zi(x,s)):zi(o,s)}function zi(r,e){return e==="Resource"&&k(r)&&(e=r.resourceType),{type:e,value:r}}function Xi(r,e){let t=r.value;if(!t||typeof t!="object")return;let n;if(e in t){let i=t[e];Array.isArray(i)?n=i.map(b):n=b(i)}else{let i=e.endsWith("[x]")?e.substring(0,e.length-3):e;for(let o of Object.values(d)){let s=i+M(o);if(s in t){let a=t[s];Array.isArray(a)?n=a.map(u=>({type:o,value:u})):n={type:o,value:a};break}}}if(Array.isArray(n)){if(n.length===0||C(n[0]))return}else if(C(n))return;return n}function ft(r){let e=[];for(let t of r){let n=!1;for(let i of e)if(B(Qe(t,i))){n=!0;break}n||e.push(t)}return e}function Pn(r){return h(!B(r))}function An(r,e){return r.length===0||e.length===0?[]:r.length!==e.length?h(!1):h(r.every((t,n)=>B(Qe(t,e[n]))))}function wn(r,e){return r.length===0||e.length===0?[]:r.length!==e.length?h(!0):h(r.some((t,n)=>!B(Qe(t,e[n]))))}function Qe(r,e){let t=r.value?.valueOf(),n=e.value?.valueOf();return typeof t=="number"&&typeof n=="number"?h(Math.abs(t-n)<1e-8):I(t)&&I(n)?h(kn(t,n)):h(typeof t=="object"&&typeof n=="object"?Vn(r,e):t===n)}function gr(r,e){return r.length===0&&e.length===0?h(!0):r.length!==e.length?h(!1):(r.sort(Ji),e.sort(Ji),h(r.every((t,n)=>B(Zi(t,e[n])))))}function Zi(r,e){let{type:t,value:n}=r,{type:i,value:o}=e,s=n?.valueOf(),a=o?.valueOf();return typeof s=="number"&&typeof a=="number"?h(Math.abs(s-a)<.01):I(s)&&I(a)?h(kn(s,a)):h(t==="Coding"&&i==="Coding"?typeof s!="object"||typeof a!="object"?!1:s.code===a.code&&s.system===a.system:typeof s=="object"&&typeof a=="object"?Vn({...s,id:void 0},{...a,id:void 0}):typeof s=="string"&&typeof a=="string"?s.toLowerCase()===a.toLowerCase():s===a)}function Ji(r,e){let t=r.value?.valueOf(),n=e.value?.valueOf();return typeof t=="number"&&typeof n=="number"?t-n:typeof t=="string"&&typeof n=="string"?t.localeCompare(n):0}function mt(r,e){let{value:t}=r;if(t==null)return!1;let n=e;switch(n.startsWith("System.")&&(n=n.substring(7)),n.startsWith("FHIR.")&&(n=n.substring(5)),n){case"Boolean":return typeof t=="boolean";case"Decimal":case"Integer":return typeof t=="number";case"Date":return On(t);case"DateTime":return De(t);case"Time":return typeof t=="string"&&!!/^T\d/.exec(t);case"Period":return In(t);case"Quantity":return I(t);default:return r.type===n||typeof t=="object"&&t?.resourceType===n}}function On(r){return typeof r=="string"&&!!pt.date.exec(r)}function De(r){return typeof r=="string"&&!!pt.dateTime.exec(r)}function In(r){return!!(r&&typeof r=="object"&&("start"in r&&De(r.start)||"end"in r&&De(r.end)))}function ht(r){if(r){if(On(r)||De(r))return{start:yr(r,"0000-01-01T00:00:00.000"),end:yr(r,"xxxx-12-31T23:59:59.999")};if(In(r))return{start:r.start?yr(r.start,"0000-01-01T00:00:00.000"):void 0,end:r.end?yr(r.end,"xxxx-12-31T23:59:59.999"):void 0}}}function yr(r,e){let t="Z",n=Math.max(r.indexOf("+",10),r.indexOf("-",10));n>-1?(t=r.substring(n),r=r.substring(0,n)):r.endsWith("Z")&&(r=r.substring(0,r.length-1));let i=r+e.substring(r.length)+t;return new Date(i).toISOString()}function I(r){return!!(r&&typeof r=="object"&&"value"in r&&typeof r.value=="number")}function kn(r,e){return Math.abs(r.value-e.value)<.01&&(r.unit===e.unit||r.code===e.code||r.unit===e.code||r.code===e.unit)}function Vn(r,e){let t=Object.keys(r),n=Object.keys(e);if(t.length!==n.length)return!1;for(let i of t){let o=r[i],s=e[i];if(Ki(o)&&Ki(s)){if(!Vn(o,s))return!1}else if(o!==s)return!1}return!0}function Ki(r){return r!==null&&typeof r=="object"}function Cn(r,e){if(e){if(typeof e!="object")throw new Error("Primitive extension must be an object");return ka(r??{},e)}return r}function ka(r,e){return delete e.__proto__,delete e.constructor,Object.assign(r,e)}function Je(r,e){return k(r,e)&&"id"in r&&typeof r.id=="string"}function Te(r){let e=A(r)??"undefined/undefined",t=ro(r);return t===e?{reference:e}:{reference:e,display:t}}function A(r){if(G(r))return r.reference;if(Je(r))return`${r.resourceType}/${r.id}`}function be(r){if(r)return G(r)?r.reference.split("/")[1]:r.id}function Va(r){if(r?.reference===void 0)throw new f(v("Reference missing reference property."));let[e,t]=r.reference.split("/");if(e===""||t===""||t===void 0)throw new f(v("Unable to parse reference string."));return[e,t]}function br(r){if(r)if(r.accounts&&r.account){let e=r.accounts;return e.some(t=>t.reference===r.account?.reference)?e:[r.account,...e]}else return Ve(r.accounts??r.account)}function to(r){return r.resourceType==="Patient"||r.resourceType==="Practitioner"||r.resourceType==="RelatedPerson"}function ro(r){if(to(r)){let e=Da(r);if(e)return e}if(r.resourceType==="Device"){let e=Ma(r);if(e)return e}if(r.resourceType==="MedicationRequest"&&r.medicationCodeableConcept)return ze(r.medicationCodeableConcept);if(r.resourceType==="Subscription"&&r.criteria)return r.criteria;if(r.resourceType==="User"&&r.email)return r.email;if("name"in r&&r.name&&typeof r.name=="string")return r.name;if("code"in r&&r.code){let e=r.code;if(Array.isArray(e)&&(e=e[0]),vr(e))return ze(e);if(ao(e))return e.text}return A(r)??""}function Da(r){let e=r.name;if(e&&e.length>0)return Ke(e[0])}function Ma(r){let e=r.deviceName;if(e&&e.length>0)return e[0].name}function _a(r){if(!("photo"in r))return;let e=r.photo;if(e)if(Array.isArray(e))for(let t of e){let n=eo(t);if(n)return n}else return eo(e)}function eo(r){if(r.url&&r.contentType?.startsWith("image/"))return r.url}function La(r){return r?new Date(r):void 0}function gt(r,e){let t=new Date(r);t.setUTCHours(0,0,0,0);let n=e?new Date(e):new Date;n.setUTCHours(0,0,0,0);let i=t.getUTCFullYear(),o=t.getUTCMonth(),s=t.getUTCDate(),a=n.getUTCFullYear(),u=n.getUTCMonth(),l=n.getUTCDate(),p=a-i;(u<o||u===o&&l<s)&&p--;let y=a*12+u-(i*12+o);l<s&&y--;let x=Math.floor((n.getTime()-t.getTime())/(1e3*60*60*24));return{years:p,months:y,days:x}}function Fa(r,e){let{years:t,months:n,days:i}=gt(r,e);return t>=2?t.toString().padStart(3,"0")+"Y":n>=1?n.toString().padStart(3,"0")+"M":i.toString().padStart(3,"0")+"D"}function Na(r){let e={};return no(r.item,e),e}function no(r,e){for(let t of r??g)t.linkId&&t.answer&&t.answer.length>0&&(e[t.linkId]=t.answer[0]),no(t.item,e)}function Ua(r){let e={};return io(r.item,e),e}function io(r,e){for(let t of r??g)t.linkId&&t.answer&&t.answer.length>0&&(e[t.linkId]?e[t.linkId]=[...e[t.linkId],...t.answer]:e[t.linkId]=t.answer),io(t.item,e)}function oo(r,e){let t=r.identifier;if(!t)return;let n=Array.isArray(t)?t:[t];for(let i of n)if(i.system===e)return i.value}function Ba(r,e,t,n){let i={system:e,value:t};n?.use&&(i.use=n.use);let o=r.identifier;if(!o){r.identifier=[i];return}for(let s of o)if(s.system===e){Object.assign(s,i);return}o.push(i)}function qa(r,...e){let t=le(r,...e);if(!t)return;let n=D({type:"Extension",value:t},"value[x]");if(n)return Array.isArray(n)?n[0].value:n.value}function le(r,...e){let t=r;for(let n=0;n<e.length&&t;n++)t=t?.extension?.find(i=>i.url===e[n]);return t}function xt(r,e){let t=Dn(r);return JSON.stringify(t,null,e?2:void 0)??""}function Dn(r){if(!(r==null||r===""))return typeof r=="object"?Array.isArray(r)?Wa(r):ja(r):r}function Wa(r){let e=r.length;if(e===0)return;let t,n=0;for(let i=0;i<e;i++){let o=r[i],s=Dn(o);s!==o&&!t&&(t=Array.from(r)),s===void 0?t&&(t[i]=null):(t&&(t[i]=s),n++)}if(n!==0)return t??r}function ja(r){let e,t=0;for(let n in r){let i=r[n],o=Dn(i);o!==i&&!e&&(e={...r}),o===void 0?e&&delete e[n]:(e&&(e[n]=o),t++)}if(t!==0)return e??r}function C(r){if(r==null)return!0;let e=typeof r;return e==="string"||e==="object"?!te(r):!1}function te(r){if(r==null)return!1;let e=typeof r;return e==="string"&&r!==""||e==="object"&&("length"in r&&r.length>0||Object.keys(r).length>0)}function $a(r){if(!r)return;let e=r.length-1;for(;e>=0&&C(r[e]);)e--;return e>=0?r.slice(0,e+1):void 0}function de(r,e,t){return r===e||C(r)&&C(e)?!0:C(r)||C(e)?!1:Array.isArray(r)&&Array.isArray(e)?Ga(r,e):Array.isArray(r)||Array.isArray(e)?!1:E(r)&&E(e)?Ha(r,e,t):(E(r)||E(e),!1)}function Ga(r,e){if(r.length!==e.length)return!1;for(let t=0;t<r.length;t++)if(!de(r[t],e[t]))return!1;return!0}function Ha(r,e,t){let n=new Set;for(let i of Object.keys(r))n.add(i);for(let i of Object.keys(e))n.add(i);t==="meta"&&(n.delete("versionId"),n.delete("lastUpdated"),n.delete("author"));for(let i of n){let o=r[i],s=e[i];if(!de(o,s,i))return!1}return!0}function He(r,e){return C(r)?!0:C(e)?!1:Array.isArray(r)&&Array.isArray(e)?Qa(r,e):Array.isArray(r)||Array.isArray(e)?!1:E(r)&&E(e)?za(r,e):E(r)||E(e)?!1:r===e}function Qa(r,e){return e.every(t=>r.some(n=>He(n,t)))}function za(r,e){return Object.entries(e).every(([t,n])=>t in r&&He(r[t],n))}function Se(r){return r===void 0?r:JSON.parse(JSON.stringify(r))}function Ja(r){return/^[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}$/i.test(r)}function E(r){return r!==null&&typeof r=="object"}function Mn(r){return r.every(Me)}function Me(r){return typeof r=="string"}function xr(r){return E(r)&&"code"in r&&typeof r.code=="string"}function vr(r){return E(r)&&"coding"in r&&Array.isArray(r.coding)&&r.coding.every(xr)}function Ka(r,e){for(let t of r??g)for(let n of t.coding??g)if(n.system===e)return n.code}function so(r,e){let[t,n]=_e(e,"|",2);return n===void 0?r.code===e:t===""?r.system===void 0&&r.code===n:n===""?r.system===t:r.system===t&&r.code===n}function Ya(r,e){return(r.coding??g).some(t=>so(t,e))}function ao(r){return E(r)&&"text"in r&&typeof r.text=="string"}var co=[];for(let r=0;r<256;r++)co.push(r.toString(16).padStart(2,"0"));function _n(r){let e=Fn(r),t=new Uint8Array(e),n=new Array(t.length);for(let i=0;i<t.length;i++)n[i]=co[t[i]];return n.join("")}function Ln(r){let e=Fn(r),t=new Uint8Array(e),n=new Array(t.length);for(let i=0;i<t.length;i++)n[i]=String.fromCodePoint(t[i]);return window.btoa(n.join(""))}function Fn(r){return ArrayBuffer.isView(r)?r.buffer:r}function M(r){return r?r.charAt(0).toUpperCase()+r.substring(1):""}function Xa(r){return r===r.toLowerCase()&&r!==r.toUpperCase()}function Sr(r){return r.length>0&&r.startsWith(r[0].toUpperCase())}function pe(r,e){let t=r+".";if(e.startsWith(t))return e.slice(t.length)}function Tr(r,e){return r.coding?.find(t=>t.system===e)?.code}function Za(r,e,t){r.coding??=[];let n=r.coding.find(i=>i.system===e);n?n.code=t:r.coding.push({system:e,code:t})}function ec(r,e,t,n){return r.qualifiedInterval?.find(i=>lo(i,e)&&ic(i,t,r.quantitativeDetails?.decimalPrecision)&&(n===void 0||i.category===n))}function tc(r,e,t){return uo(r,e,t)[0]}function uo(r,e,t){return r.qualifiedInterval?.filter(n=>lo(n,e)&&(!t||t.includes(n.condition)))??[]}function lo(r,e){return rc(r,e)&&nc(r,e)}function rc(r,e){return!r.gender||r.gender===e.gender}function nc(r,e){return!r.age||Nn(gt(e.birthDate).years,r.age)}function ic(r,e,t){return!!r.range&&Nn(e,r.range,t)}function Nn(r,e,t){return(e.low?.value===void 0||fo(r,e.low.value,t))&&(e.high?.value===void 0||po(r,e.high.value,t))}function oc(r,e){return Number.parseFloat(r.toFixed(e))}function sc(r,e,t){return ee(r,t)===ee(e,t)}function ac(r,e,t){return ee(r,t)<ee(e,t)}function cc(r,e,t){return ee(r,t)>ee(e,t)}function po(r,e,t){return ee(r,t)<=ee(e,t)}function fo(r,e,t){return ee(r,t)>=ee(e,t)}function ee(r,e){return e===void 0?r:Math.round(r*Math.pow(10,e))}function uc(r,e,t){return r.find(n=>typeof e=="string"?Tr(n.code||{},t)===e:Tr(n.code||{},t)===Tr(e,t))}function Ve(r){if(r!==void 0)return Array.isArray(r)?r:[r]}function lc(r){return Array.isArray(r)?r[0]:r}var Er=(r,e)=>new Promise((t,n)=>{e?.signal?.throwIfAborted();let i=setTimeout(t,r);e?.signal?.addEventListener("abort",()=>{clearTimeout(i),n(e.signal?.reason)},{once:!0})});function _e(r,e,t){let n=[];for(let i=0;i<t-1;i++){let o=r.indexOf(e);if(o<0)break;n.push(r.slice(0,o)),r=r.slice(o+e.length)}return n.push(r),n}function Un(r){let e,t=!1;return function(){return t||(e=r(),t=!0),e}}function z(r,e){return r?(r.push(e),r):[e]}function vt(r){return r.sort((e,t)=>e.localeCompare(t))}function Rr(r){return r.endsWith("/")?r:r+"/"}function mo(r){return r.startsWith("/")?r.slice(1):r}function F(r,e){return new URL(mo(e),Rr(r.toString())).toString()}function Bn(r,e){return F(r,e).toString().replace("http://","ws://").replace("https://","wss://")}function qn(r){return typeof r=="object"&&!Array.isArray(r)&&!(r instanceof URLSearchParams)&&(r=Object.fromEntries(Object.entries(r).filter(e=>e[1]!==void 0))),new URLSearchParams(r).toString()}var ho=/^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-_]*[a-zA-Z0-9])\.)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\-_]*[A-Za-z0-9])$/;function dc(r){return ho.test(r)}function pc(r,e){return r?.meta?.profile?.includes(e)||(r.meta=r.meta??{},r.meta.profile=r.meta.profile??[],r.meta.profile.push(e)),r}function fc(r,e){return new Map(r.entry?.filter(n=>!!n.resource).map(n=>[oo(n.resource,e),n.resource]).filter(([n])=>n!==void 0))}function mc(r,e){if(r?.meta?.profile?.includes(e)){let t=r.meta.profile.indexOf(e);r.meta.profile.splice(t,1)}return r}function hc(r,e){let t=[];if(!r)return t;for(let n=0;n<r.length;n++){let i=e(r[n],n);Array.isArray(i)?t.push(...i):i!==void 0&&t.push(i)}return t}function yc(r){return r.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',""").replaceAll("\u201C","“").replaceAll("\u201D","”").replaceAll("\u2018","‘").replaceAll("\u2019","’").replaceAll("\u2026","…")}function gc(r){return r!=null}var g=Object.freeze([]),xc=()=>{};function Wn(r){if(!r)return"";switch(r.type){case"Address":return go(r.value);case"CodeableConcept":return ze(r.value);case"Coding":return jn(r.value);case"ContactPoint":return r.value.value;case"HumanName":return Ke(r.value);case"Quantity":return fe(r.value);case"Reference":return yo(r.value);default:return r.value?.toString()??""}}function yo(r){return r?r.display??r.reference??xt(r):""}function go(r,e){if(!r)return"";let t=[];if(r.line&&t.push(...r.line),r.city||r.state||r.postalCode){let n=[];r.city&&n.push(r.city),r.state&&n.push(r.state),r.postalCode&&n.push(r.postalCode),t.push(n.join(", "))}return r.use&&(e?.all||e?.use)&&t.push("["+r.use+"]"),t.join(e?.lineSeparator??", ").trim()}function Ke(r,e){if(!r)return"";let t=[];if(r.prefix&&e?.prefix!==!1&&t.push(...r.prefix),r.given&&t.push(...r.given),r.family&&t.push(r.family),r.suffix&&e?.suffix!==!1&&t.push(...r.suffix),r.use&&(e?.all||e?.use)&&t.push("["+r.use+"]"),t.length===0){let n=Le(r.text);if(n)return n}return t.join(" ").trim()}function vc(r){let e=[];return r.given&&e.push(...r.given),e.join(" ").trim()}function Tc(r){return Le(r.family)??""}function Tt(r){return r instanceof Date&&!Number.isNaN(r.getTime())}function bc(r,e,t){if(!r)return"";let n=new Date(r);return Tt(n)?(n.setUTCHours(0,0,0,0),n.toLocaleDateString(e,{timeZone:"UTC",...t})):""}function Sc(r,e,t){if(!r)return"";let n=new Date("2000-01-01T"+r+"Z");return Tt(n)?n.toLocaleTimeString(e,t):""}function xo(r,e,t){if(!r)return"";let[n=0,i=0,o=0]=r.split(":").map(Number),s=new Date(Date.UTC(1970,0,1,n,i,o));return Tt(s)?new Intl.DateTimeFormat(e,{hour:"numeric",minute:"2-digit",second:o===0?void 0:"numeric",...t,timeZone:"UTC"}).format(s):""}function Cr(r,e,t){if(!r)return"";let n=new Date(r);return Tt(n)?n.toLocaleString(e,t):""}function Ec(r,e,t){return!r||!r.start&&!r.end?"":Cr(r.start,e,t)+" - "+Cr(r.end,e,t)}var Rc={s:"every second",min:"every minute",h:"hourly",d:"daily",wk:"weekly",mo:"monthly",a:"annually"},Cc={s:"second",min:"minute",h:"hour",d:"day",wk:"week",mo:"month",a:"year"},Pc={s:"seconds",min:"minutes",h:"hours",d:"days",wk:"weeks",mo:"months",a:"years"};function Ac(r){if(!r)return"";let e=[];return wc(e,r.repeat),r.event&&e.push(r.event.map(t=>Cr(t)).join(", ")),M(e.join(" ").trim())}function wc(r,e){if(!e?.periodUnit)return;let t=e.frequency??1,n=e.period??1,i=e.periodUnit;t===1&&n===1?r.push(Rc[i]):(t===1?r.push("once"):r.push(t+" times"),n===1?r.push("per "+Cc[i]):r.push("per "+n+" "+Pc[i])),e.dayOfWeek&&r.push("on "+e.dayOfWeek.map(M).join(", ")),e.timeOfDay&&r.push("at "+e.timeOfDay.map(o=>xo(o)).join(", "))}function Oc(r,e,t=!1){if(t&&e===void 0)throw new Error("Precision must be specified for exclusive ranges");let n=r?.low&&{...r.low,comparator:void 0},i=r?.high&&{...r.high,comparator:void 0};return n?.value===void 0&&i?.value===void 0?"":n?.value!==void 0&&i?.value===void 0?t&&e!==void 0?(n.value=Vc(n.value,e),`> ${fe(n,e)}`):`>= ${fe(n,e)}`:n?.value===void 0&&i?.value!==void 0?t&&e!==void 0?(i.value=kc(i.value,e),`< ${fe(i,e)}`):`<= ${fe(i,e)}`:(n?.unit===i?.unit&&delete n?.unit,`${fe(n,e)} - ${fe(i,e)}`)}function fe(r,e){if(!r)return"";let t=[];return r.comparator&&(t.push(r.comparator),t.push(" ")),r.value!==void 0&&(e!==void 0?t.push(r.value.toFixed(e)):t.push(r.value)),r.unit&&(r.unit!=="%"&&t.at(-1)!==" "&&t.push(" "),t.push(r.unit)),t.join("").trim()}function Ic(r){return r?.value===void 0?"":r.value.toLocaleString(void 0,{style:"currency",currency:r.currency??"USD",currencyDisplay:"narrowSymbol"})}function ze(r){if(!r)return"";let e=Le(r.text);return e||(r.coding?r.coding.map(t=>jn(t)).join(", "):"")}function jn(r,e){let t=Le(r?.display);if(t){let n=e?Le(r?.code):void 0;return`${t}${n?" ("+n+")":""}`}return Le(r?.code)??""}function vo(r){if(!r)return"";let e=[];if(r.valueQuantity)e.push(fe(r.valueQuantity));else if(r.valueCodeableConcept)e.push(ze(r.valueCodeableConcept));else{let t=Le(r.valueString);t&&e.push(t)}return"component"in r&&e.push(r.component.map(t=>vo(t)).join(" / ")),e.join(" / ").trim()}function Le(r){return typeof r=="string"?r:void 0}function kc(r,e,t=1){return(To(r,e)+t)*Math.pow(10,-e)}function Vc(r,e,t=1){return(To(r,e)-t)*Math.pow(10,-e)}function To(r,e){return e===void 0?r:Math.round(r*Math.pow(10,e))}var d={Address:"Address",Age:"Age",Annotation:"Annotation",Attachment:"Attachment",BackboneElement:"BackboneElement",CodeableConcept:"CodeableConcept",Coding:"Coding",ContactDetail:"ContactDetail",ContactPoint:"ContactPoint",Contributor:"Contributor",Count:"Count",DataRequirement:"DataRequirement",Distance:"Distance",Dosage:"Dosage",Duration:"Duration",Element:"Element",ElementDefinition:"ElementDefinition",Expression:"Expression",Extension:"Extension",HumanName:"HumanName",Identifier:"Identifier",MarketingStatus:"MarketingStatus",Meta:"Meta",Money:"Money",MoneyQuantity:"MoneyQuantity",Narrative:"Narrative",ParameterDefinition:"ParameterDefinition",Period:"Period",Population:"Population",ProdCharacteristic:"ProdCharacteristic",ProductShelfLife:"ProductShelfLife",Quantity:"Quantity",Range:"Range",Ratio:"Ratio",Reference:"Reference",RelatedArtifact:"RelatedArtifact",SampledData:"SampledData",Signature:"Signature",SimpleQuantity:"SimpleQuantity",SubstanceAmount:"SubstanceAmount",SystemString:"http://hl7.org/fhirpath/System.String",Timing:"Timing",TriggerDefinition:"TriggerDefinition",UsageContext:"UsageContext",base64Binary:"base64Binary",boolean:"boolean",canonical:"canonical",code:"code",date:"date",dateTime:"dateTime",decimal:"decimal",id:"id",instant:"instant",integer:"integer",markdown:"markdown",oid:"oid",positiveInt:"positiveInt",string:"string",time:"time",unsignedInt:"unsignedInt",uri:"uri",url:"url",uuid:"uuid",xhtml:"xhtml"};function Dc(r){for(let e of r.entry??g){let t=e.resource;t.resourceType==="SearchParameter"&&Pr(t)}}function Tn(r){let e=Array.isArray(r)?r:r.entry?.map(t=>t.resource)??[];for(let t of e)t?.resourceType==="StructureDefinition"&&t.kind==="resource"&&So(t.type)}function So(r){let e=q.types[r];return e||(e={searchParamsDetails:{}},q.types[r]=e),!e.searchParams&&r!=="Binary"&&(e.searchParams={_id:{base:[r],code:"_id",type:"token",expression:r+".id"},_lastUpdated:{base:[r],code:"_lastUpdated",type:"date",expression:r+".meta.lastUpdated"},_compartment:{base:[r],code:"_compartment",type:"reference",expression:r+".meta.compartment"},_profile:{base:[r],code:"_profile",type:"uri",expression:r+".meta.profile"},_security:{base:[r],code:"_security",type:"token",expression:r+".meta.security"},_source:{base:[r],code:"_source",type:"uri",expression:r+".meta.source"},_tag:{base:[r],code:"_tag",type:"token",expression:r+".meta.tag"}}),e}function Pr(r){for(let e of r.base??g){let t=So(e);t.searchParams||(t.searchParams={}),t.searchParams[r.code]=r}}function ar(r){let e=r.type?.[0]?.code;return e==="BackboneElement"||e==="Element"?Eo((r.base?.path??r.path)?.split(".")):e}function Eo(r){return r.length===1?r[0]:r.map(M).join("")}function dr(r){return r.kind==="resource"&&r.name!=="Resource"&&r.name!=="DomainResource"}function Mc(){return Object.values(yn()).filter(dr).map(r=>r.name)}function _c(r){return q.types[r]?.searchParams}function Lc(r,e){return q.types[r]?.searchParams?.[e]}function Fc(r){let e=r.replaceAll("[x]","").split(".").pop();return Ro(e)}function Ro(r){let e;return r.length<100?e=r.match(/[A-Z]+(?![a-z])|[A-Z]?[a-z]+|\d+/g)??[]:e=r.split(/(?=[A-Z])/),e.map(Uc).join(" ").replace("_"," ").replaceAll(/\s+/g," ")}var Nc=new Set(["CDS","ID","IP","PKCE","JWKS","URI","URL","OMB","UDI"]);function Uc(r){let e=r.toUpperCase();return r===e?r:Nc.has(e)?e:e.charAt(0)+r.slice(1)}function yt(r,e,t){let n=Ge(r,t);if(n)return Co(n.elements,e)}function Co(r,e){let t=r[e]??r[e+"[x]"];if(t)return t;for(let n=0;n<e.length;n++){let i=e[n];if(i>="A"&&i<="Z"){let o=e.slice(0,n)+"[x]",s=r[o];if(s)return s}}}function Bc(r){return!!(r&&typeof r=="object"&&"type"in r&&"value"in r)}function k(r,e){return!(!r||typeof r!="object"||!("resourceType"in r)||e&&r.resourceType!==e)}function G(r,e){return r&&typeof r=="object"&&"reference"in r&&typeof r.reference=="string"?e?r.reference.match(new RegExp(`^${e}(/|\\?)`))!==null:!0:!1}var q={types:{}};function $n(r){switch(r.type){case d.uuid:case d.uri:case d.url:case d.string:case d.oid:case d.markdown:case d.id:case d.code:case d.canonical:case d.base64Binary:case d.SystemString:case d.date:case d.dateTime:case d.instant:return r.value;case d.Identifier:return`${r.value.system??""}|${r.value.value}`;case d.Coding:return bo(r.value);case d.CodeableConcept:return r.value.coding?.map(bo).join(",")??r.value.text;case d.HumanName:return r.value.text?r.value.text:Ke(r.value);case d.unsignedInt:case d.positiveInt:case d.integer:case d.decimal:return r.value.toString();case d.boolean:return r.value?"true":"false";case d.Extension:return r.value.url;case d.ContactPoint:return r.value.value;case d.Quantity:case d.Age:case d.Count:case d.Duration:return`${r.value.value}|${r.value.system??""}|${r.value.code??r.value.unit??""}`;case d.Reference:return r.value.reference;default:return Je(r.value)?A(r.value):JSON.stringify(r)}}function bo(r){return r?`${r.system??""}|${r.code}`:""}function Ye(r){if(r.startsWith("T"))return r+"T00:00:00.000Z".substring(r.length);if(r.length<=10)return r;try{return new Date(r).toISOString()}catch{return r}}var me=()=>[],_={empty:(r,e)=>h(e.every(t=>C(t.value))),hasValue:(r,e)=>h(e.length!==0),exists:(r,e,t)=>t?h(e.some(n=>B(t.eval(r,[n])))):h(e.length>0&&e.every(n=>!C(n.value))),all:(r,e,t)=>h(e.every(n=>B(t.eval(r,[n])))),allTrue:(r,e)=>{for(let t of e)if(!t.value)return h(!1);return h(!0)},anyTrue:(r,e)=>{for(let t of e)if(t.value)return h(!0);return h(!1)},allFalse:(r,e)=>{for(let t of e)if(t.value)return h(!1);return h(!0)},anyFalse:(r,e)=>{for(let t of e)if(!t.value)return h(!0);return h(!1)},subsetOf:(r,e,t)=>{if(e.length===0)return h(!0);let n=t.eval(r,Fe(r));return n.length===0?h(!1):h(e.every(i=>n.some(o=>o.value===i.value)))},supersetOf:(r,e,t)=>{let n=t.eval(r,Fe(r));return n.length===0?h(!0):e.length===0?h(!1):h(n.every(i=>e.some(o=>o.value===i.value)))},count:(r,e)=>[{type:d.integer,value:e.length}],distinct:(r,e)=>{let t=[];for(let n of e)t.some(i=>i.value===n.value)||t.push(n);return t},isDistinct:(r,e)=>h(e.length===_.distinct(r,e).length),where:(r,e,t)=>e.filter(n=>B(t.eval(r,[n]))),select:(r,e,t)=>e.flatMap(n=>t.eval({parent:r,variables:{$this:n}},[n])),repeat:me,ofType:(r,e,t)=>e.filter(n=>n.type===t.name),single:(r,e)=>{if(e.length>1)throw new Error("Expected input length one for single()");return e.length===0?[]:e.slice(0,1)},first:(r,e)=>e.length===0?[]:e.slice(0,1),last:(r,e)=>e.length===0?[]:e.slice(-1,e.length),tail:(r,e)=>e.length===0?[]:e.slice(1,e.length),skip:(r,e,t)=>{let n=t.eval(r,e)[0]?.value;if(typeof n!="number")throw new TypeError("Expected a number for skip(num)");return n>=e.length?[]:n<=0?e:e.slice(n,e.length)},take:(r,e,t)=>{let n=t.eval(r,e)[0]?.value;if(typeof n!="number")throw new TypeError("Expected a number for take(num)");return n>=e.length?e:n<=0?[]:e.slice(0,n)},intersect:(r,e,t)=>{if(!t)return e;let n=t.eval(r,Fe(r)),i=[];for(let o of e)!i.some(s=>s.value===o.value)&&n.some(s=>s.value===o.value)&&i.push(o);return i},exclude:(r,e,t)=>{if(!t)return e;let n=t.eval(r,Fe(r)),i=[];for(let o of e)n.some(s=>s.value===o.value)||i.push(o);return i},union:(r,e,t)=>{if(!t)return e;let n=t.eval(r,Fe(r));return ft([...e,...n])},combine:(r,e,t)=>{if(!t)return e;let n=t.eval(r,Fe(r));return[...e,...n]},htmlChecks:(r,e,t)=>[b(!0)],iif:(r,e,t,n,i)=>{let o=t.eval(r,e);if(o.length>1||o.length===1&&typeof o[0].value!="boolean")throw new Error("Expected criterion to evaluate to a Boolean");return B(o)?n.eval(r,e):i?i.eval(r,e):[]},toBoolean:(r,e)=>{if(e.length===0)return[];let[{value:t}]=ne(e,1);if(typeof t=="boolean")return[{type:d.boolean,value:t}];if(typeof t=="number"&&(t===0||t===1))return h(!!t);if(typeof t=="string"){let n=t.toLowerCase();if(["true","t","yes","y","1","1.0"].includes(n))return h(!0);if(["false","f","no","n","0","0.0"].includes(n))return h(!1)}return[]},convertsToBoolean:(r,e)=>e.length===0?[]:h(_.toBoolean(r,e).length===1),toInteger:(r,e)=>{if(e.length===0)return[];let[{value:t}]=ne(e,1);return typeof t=="number"?[{type:d.integer,value:t}]:typeof t=="string"&&/^[+-]?\d+$/.exec(t)?[{type:d.integer,value:Number.parseInt(t,10)}]:typeof t=="boolean"?[{type:d.integer,value:t?1:0}]:[]},convertsToInteger:(r,e)=>e.length===0?[]:h(_.toInteger(r,e).length===1),toDate:(r,e)=>{if(e.length===0)return[];let[{value:t}]=ne(e,1);return typeof t=="string"&&/^\d{4}(-\d{2}(-\d{2})?)?/.exec(t)?[{type:d.date,value:Ye(t)}]:[]},convertsToDate:(r,e)=>e.length===0?[]:h(_.toDate(r,e).length===1),toDateTime:(r,e)=>{if(e.length===0)return[];let[{value:t}]=ne(e,1);return typeof t=="string"&&/^\d{4}(-\d{2}(-\d{2})?)?/.exec(t)?[{type:d.dateTime,value:Ye(t)}]:[]},convertsToDateTime:(r,e)=>e.length===0?[]:h(_.toDateTime(r,e).length===1),toDecimal:(r,e)=>{if(e.length===0)return[];let[{value:t}]=ne(e,1);return typeof t=="number"?[{type:d.decimal,value:t}]:typeof t=="string"&&/^-?\d{1,9}(\.\d{1,9})?$/.exec(t)?[{type:d.decimal,value:Number.parseFloat(t)}]:typeof t=="boolean"?[{type:d.decimal,value:t?1:0}]:[]},convertsToDecimal:(r,e)=>e.length===0?[]:h(_.toDecimal(r,e).length===1),toQuantity:(r,e)=>{if(e.length===0)return[];let[{value:t}]=ne(e,1);return I(t)?[{type:d.Quantity,value:t}]:typeof t=="number"?[{type:d.Quantity,value:{value:t,unit:"1"}}]:typeof t=="string"&&/^-?\d{1,9}(\.\d{1,9})?/.exec(t)?[{type:d.Quantity,value:{value:Number.parseFloat(t),unit:"1"}}]:typeof t=="boolean"?[{type:d.Quantity,value:{value:t?1:0,unit:"1"}}]:[]},convertsToQuantity:(r,e)=>e.length===0?[]:h(_.toQuantity(r,e).length===1),toString:(r,e)=>{if(e.length===0)return[];let[{value:t}]=ne(e,1);return t==null?[]:I(t)?[{type:d.string,value:`${t.value} '${t.unit}'`}]:[{type:d.string,value:t.toString()}]},convertsToString:(r,e)=>e.length===0?[]:h(_.toString(r,e).length===1),toTime:(r,e)=>{if(e.length===0)return[];let[{value:t}]=ne(e,1);if(typeof t=="string"){let n=/^T?(\d{2}(:\d{2}(:\d{2})?)?)/.exec(t);if(n)return[{type:d.time,value:Ye("T"+n[1])}]}return[]},convertsToTime:(r,e)=>e.length===0?[]:h(_.toTime(r,e).length===1),indexOf:(r,e,t)=>H((n,i)=>n.indexOf(i),r,e,t),substring:(r,e,t,n)=>H((i,o,s)=>{let a=o,u=s?a+s:i.length;return a<0||a>=i.length?void 0:i.substring(a,u)},r,e,t,n),startsWith:(r,e,t)=>H((n,i)=>n.startsWith(i),r,e,t),endsWith:(r,e,t)=>H((n,i)=>n.endsWith(i),r,e,t),contains:(r,e,t)=>H((n,i)=>n.includes(i),r,e,t),upper:(r,e)=>H(t=>t.toUpperCase(),r,e),lower:(r,e)=>H(t=>t.toLowerCase(),r,e),replace:(r,e,t,n)=>H((i,o,s)=>i.replaceAll(o,s),r,e,t,n),matches:(r,e,t)=>H((n,i)=>!!new RegExp(i).exec(n),r,e,t),replaceMatches:(r,e,t,n)=>H((i,o,s)=>i.replaceAll(new RegExp(o,"g"),s.replaceAll(/\$\{(\w+)\}/g,"$<$1>")),r,e,t,n),length:(r,e)=>H(t=>t.length,r,e),toChars:(r,e)=>H(t=>t?t.split(""):void 0,r,e),encode:me,decode:me,escape:me,unescape:me,trim:me,split:me,join:(r,e,t)=>{let n=t?.eval(r,Fe(r))[0]?.value??"";if(typeof n!="string")throw new TypeError("Separator must be a string.");return[{type:d.string,value:e.map(i=>i.value?.toString()??"").join(n)}]},abs:(r,e)=>re(Math.abs,r,e),ceiling:(r,e)=>re(Math.ceil,r,e),exp:(r,e)=>re(Math.exp,r,e),floor:(r,e)=>re(Math.floor,r,e),ln:(r,e)=>re(Math.log,r,e),log:(r,e,t)=>re((n,i)=>Math.log(n)/Math.log(i),r,e,t),power:(r,e,t)=>re(Math.pow,r,e,t),round:(r,e,...t)=>re((n,i=0)=>{if(typeof i!="number"||i<0)throw new Error("Invalid precision provided to round()");let o=Math.pow(10,i);return Math.round(n*o)/o},r,e,...t),sqrt:(r,e)=>re(Math.sqrt,r,e),truncate:(r,e)=>re(t=>Math.trunc(t),r,e),children:me,descendants:me,trace:(r,e,t)=>e,now:()=>[{type:d.dateTime,value:new Date().toISOString()}],timeOfDay:()=>[{type:d.time,value:new Date().toISOString().substring(11)}],today:()=>[{type:d.date,value:new Date().toISOString().substring(0,10)}],between:(r,e,t,n,i)=>{let o=_.toDateTime(r,t.eval(r,e));if(o.length===0)throw new Error("Invalid start date");let s=_.toDateTime(r,n.eval(r,e));if(s.length===0)throw new Error("Invalid end date");let a=i.eval(r,e)[0]?.value;if(a!=="years"&&a!=="months"&&a!=="days")throw new Error("Invalid units");let u=gt(o[0].value,s[0].value);return[{type:d.Quantity,value:{value:u[a],unit:a}}]},is:(r,e,t)=>{let n="";return t instanceof N?n=t.name:t instanceof K&&(n=t.left.name+"."+t.right.name),n?e.map(i=>({type:d.boolean,value:mt(i,n)})):[]},not:(r,e)=>_.toBoolean(r,e).map(t=>({type:d.boolean,value:!t.value})),resolve:(r,e)=>e.map(t=>{let n=t.value,i;if(typeof n=="string")i=n;else if(typeof n=="object"){let o=n;if(o.resource)return b(o.resource);o.reference?i=o.reference:o.type&&o.identifier&&(i=`${o.type}?identifier=${o.identifier.system}|${o.identifier.value}`)}if(i?.includes("?")){let[o]=i.split("?");return{type:o,value:{resourceType:o}}}if(i?.includes("/")){let[o,s]=i.split("/");return{type:o,value:{resourceType:o,id:s}}}return{type:d.BackboneElement,value:void 0}}).filter(t=>!!t.value),as:(r,e)=>e,type:(r,e)=>e.map(({value:t})=>typeof t=="boolean"?{type:d.BackboneElement,value:{namespace:"System",name:"Boolean"}}:typeof t=="number"?{type:d.BackboneElement,value:{namespace:"System",name:"Integer"}}:k(t)?{type:d.BackboneElement,value:{namespace:"FHIR",name:t.resourceType}}:{type:d.BackboneElement,value:null}),conformsTo:(r,e,t)=>{let n=t.eval(r,e)[0].value;if(!n.startsWith("http://hl7.org/fhir/StructureDefinition/"))throw new Error("Expected a StructureDefinition URL");let i=n.replace("http://hl7.org/fhir/StructureDefinition/","");return e.map(o=>({type:d.boolean,value:o.value?.resourceType===i}))},getResourceKey:(r,e)=>{let t=e[0].value;return t?.id?[{type:d.id,value:t.id}]:[]},getReferenceKey:(r,e,t)=>{let n=e[0].value;if(!n?.reference)return[];let i="";return t instanceof N&&(i=t.name),i&&!n.reference.startsWith(i+"/")?[]:[{type:d.id,value:be(n)}]},extension:(r,e,t)=>{let n=t.eval(r,e)[0].value,i=e?.[0]?.value;if(i){let o=le(i,n);if(o)return[{type:d.Extension,value:o}]}return[]}};function H(r,e,t,...n){if(t.length===0)return[];let[{value:i}]=ne(t,1);if(typeof i!="string")throw new TypeError("String function cannot be called with non-string");let o=n.map(a=>a?.eval(e,t)[0]?.value),s=r(i,...o);return s===void 0?[]:Array.isArray(s)?s.map(b):[b(s)]}function re(r,e,t,...n){if(t.length===0)return[];let[{value:i}]=ne(t,1),o=I(i),s=o?i.value:i;if(typeof s!="number")throw new TypeError("Math function cannot be called with non-number");let a=r(s,...n.map(p=>p.eval(e,t)[0]?.value)),u=o?d.Quantity:t[0].type,l=o?{...i,value:a}:a;return[{type:u,value:l}]}function ne(r,e){if(r.length!==e)throw new Error(`Expected ${e} arguments`);for(let t of r)if(t==null)throw new Error("Expected non-null argument");return r}function Fe(r){let e=r;for(;e.parent?.variables.$this;)e=e.parent;return[e.variables.$this]}var he=class{constructor(e,t){c(this,"original");c(this,"child");this.original=e,this.child=t}eval(e,t){try{if(t.length>0){let n=[];for(let i of t)n.push(this.child.eval({parent:e,variables:{$this:i}},[i]));return n.flat()}else return this.child.eval(e,[])}catch(n){throw new Error(`FhirPathError on "${this.original}": ${n}`,{cause:n})}}toString(){return this.child.toString()}},W=class{constructor(e){c(this,"value");this.value=e}eval(){return[this.value]}toString(){let e=this.value.value;return typeof e=="string"?`'${e}'`:e.toString()}},N=class{constructor(e){c(this,"name");this.name=e}eval(e,t){if(this.name==="$this")return t;let n=this.getVariable(e);if(n)return[n];if(this.name.startsWith("%"))throw new Error(`Undefined variable ${this.name}`);return t.flatMap(i=>this.evalValue(i)).filter(i=>i?.value!==void 0)}getVariable(e){let t=e.variables[this.name];if(t!==void 0)return t;if(e.parent)return this.getVariable(e.parent)}evalValue(e){let t=e.value;if(!(!t||typeof t!="object"))return k(t,this.name)?e:fr(e,this.name)}toString(){return this.name}},bt=class{eval(){return[]}toString(){return"{}"}},St=class extends st{constructor(t,n,i){super(t,n);c(this,"impl");this.impl=i}eval(t,n){return this.impl(this.child.eval(t,n))}toString(){return this.operator+this.child.toString()}},ye=class extends ce{constructor(e,t){super("as",e,t)}eval(e,t){return _.ofType(e,this.left.eval(e,t),this.right)}},w=class extends ce{},L=class extends w{constructor(t,n,i,o){super(t,n,i);c(this,"impl");this.impl=o}eval(t,n){let i=this.left.eval(t,n);if(i.length!==1)return[];let o=this.right.eval(t,n);if(o.length!==1)return[];let s=i[0].value,a=o[0].value,u=I(s)?s.value:s,l=I(a)?a.value:a,p=this.impl(u,l);return typeof p=="boolean"?h(p):I(s)?[{type:d.Quantity,value:{...s,value:p}}]:[b(p)]}},Et=class extends ce{constructor(e,t){super("&",e,t)}eval(e,t){let n=this.left.eval(e,t),i=this.right.eval(e,t),o=[...n,...i];return o.length>0&&o.every(s=>typeof s.value=="string")?[{type:d.string,value:o.map(s=>s.value).join("")}]:o}},Rt=class extends w{constructor(e,t){super("contains",e,t)}eval(e,t){let n=this.left.eval(e,t),i=this.right.eval(e,t);return h(n.some(o=>o.value===i[0].value))}},Ct=class extends w{constructor(e,t){super("in",e,t)}eval(e,t){let n=J(this.left.eval(e,t)),i=this.right.eval(e,t);return n?h(i.some(o=>Qe(n,o)[0].value)):[]}},K=class extends ce{constructor(e,t){super(".",e,t)}eval(e,t){return this.right.eval(e,this.left.eval(e,t))}toString(){return`${this.left.toString()}.${this.right.toString()}`}},Ee=class extends ce{constructor(e,t){super("|",e,t)}eval(e,t){let n=this.left.eval(e,t),i=this.right.eval(e,t);return ft([...n,...i])}},Pt=class extends w{constructor(e,t){super("=",e,t)}eval(e,t){let n=this.left.eval(e,t),i=this.right.eval(e,t);return An(n,i)}},At=class extends w{constructor(e,t){super("!=",e,t)}eval(e,t){let n=this.left.eval(e,t),i=this.right.eval(e,t);return wn(n,i)}},wt=class extends w{constructor(e,t){super("~",e,t)}eval(e,t){let n=this.left.eval(e,t),i=this.right.eval(e,t);return gr(n,i)}},Ot=class extends w{constructor(e,t){super("!~",e,t)}eval(e,t){let n=this.left.eval(e,t),i=this.right.eval(e,t);return Pn(gr(n,i))}},Re=class extends w{constructor(e,t){super("is",e,t)}eval(e,t){let n=this.left.eval(e,t);if(n.length!==1)return[];let i=this.right.name;return h(mt(n[0],i))}},It=class extends w{constructor(e,t){super("and",e,t)}eval(e,t){let n=J(this.left.eval(e,t),"boolean"),i=J(this.right.eval(e,t),"boolean");return n?.value===!0&&i?.value===!0?h(!0):n?.value===!1||i?.value===!1?h(!1):[]}},kt=class extends w{constructor(e,t){super("or",e,t)}eval(e,t){let n=J(this.left.eval(e,t),"boolean"),i=J(this.right.eval(e,t),"boolean");return n?.value===!1&&i?.value===!1?h(!1):n?.value||i?.value?h(!0):[]}},Vt=class extends w{constructor(e,t){super("xor",e,t)}eval(e,t){let n=J(this.left.eval(e,t),"boolean"),i=J(this.right.eval(e,t),"boolean");return!n||!i?[]:h(n.value!==i.value)}},Dt=class extends w{constructor(e,t){super("implies",e,t)}eval(e,t){let n=J(this.left.eval(e,t),"boolean"),i=J(this.right.eval(e,t),"boolean");return i?.value===!0||n?.value===!1?h(!0):!n||!i?[]:h(!1)}},ie=class{constructor(e,t){c(this,"name");c(this,"args");this.name=e,this.args=t}eval(e,t){let n=_[this.name];if(!n)throw new Error("Unrecognized function: "+this.name);return n(e,t,...this.args)}toString(){return`${this.name}(${this.args.map(e=>e.toString()).join(", ")})`}},Ce=class{constructor(e,t){c(this,"left");c(this,"expr");this.left=e,this.expr=t}eval(e,t){let n=this.expr.eval(e,t);if(n.length!==1)return[];let i=n[0].value;if(typeof i!="number")throw new Error("Invalid indexer expression: should return integer}");let o=this.left.eval(e,t);return i in o?[o[i]]:[]}toString(){return`${this.left.toString()}[${this.expr.toString()}]`}};var qc=["year","years","month","months","week","weeks","day","days","hour","hours","minute","minutes","second","seconds","millisecond","milliseconds"],Wc={"'":"'",'"':'"',"`":"`",r:"\r",n:`
|
|
2
2
|
`,t:" ",f:"\f","\\":"\\"},ge=class{constructor(e,t,n,i){c(this,"str");c(this,"keywords");c(this,"operators");c(this,"dateTimeLiterals");c(this,"symbolRegex");c(this,"result",[]);c(this,"pos",{index:0,line:1,column:0});c(this,"markStack",[]);this.str=e,this.keywords=t,this.operators=n,this.dateTimeLiterals=!!i?.dateTimeLiterals,this.symbolRegex=i?.symbolRegex??/[$\w%]/}tokenize(){for(;this.pos.index<this.str.length;){let e=this.consumeToken();e&&this.result.push(e)}return this.result}prevToken(){return this.result.slice(-1)[0]}peekToken(){this.mark();let e=this.consumeToken();return this.reset(),e}consumeToken(){this.consumeWhitespace();let e=this.curr();if(!e)return;this.mark();let t=this.peek();return e==="/"&&t==="*"?this.consumeMultiLineComment():e==="/"&&t==="/"?this.consumeSingleLineComment():e==="'"||e==='"'||e==="`"?this.consumeString(e):e==="@"?this.consumeDateTime():/\d/.exec(e)?this.consumeNumber():/\w/.exec(e)?this.consumeSymbol():(e==="$"||e==="%")&&/\w/.exec(t)?this.consumeSymbol():(e==="$"||e==="%")&&(t==="'"||t==='"'||t==="`")?this.consumeQuotedSymbol(t):this.consumeOperator()}consumeWhitespace(){this.consumeWhile(()=>/\s/.exec(this.curr()))}consumeMultiLineComment(){let e=this.pos.index;return this.consumeWhile(()=>this.curr()!=="*"||this.peek()!=="/"),this.advance(),this.advance(),this.buildToken("Comment",this.str.substring(e,this.pos.index))}consumeSingleLineComment(){return this.buildToken("Comment",this.consumeWhile(()=>this.curr()!==`
|
|
3
3
|
`))}consumeString(e){this.advance();let t="",n;for(;n=this.consumeChar(e);)t+=n;let i=this.buildToken(e==="`"?"Symbol":"String",t);return this.advance(),i}consumeChar(e){let t=this.curr();if(t==="\\"){this.advance();let n=this.curr(),i=Wc[n];if(i!==void 0)return this.advance(),i;if(n==="u"){this.advance();let o=/^[0-9a-fA-F]{4}$/.exec(this.str.substring(this.pos.index,this.pos.index+4))?.[0];return o?(this.advance(),this.advance(),this.advance(),this.advance(),String.fromCodePoint(Number.parseInt(o,16))):"u"}return this.consumeChar(e)}return t===e||!t?"":(this.advance(),t)}consumeQuotedSymbol(e){this.mark();let t=this.pos.index;this.advance(),this.consumeString(e);let n=this.str.substring(t,this.pos.index);return this.buildToken("Symbol",n)}consumeDateTime(){this.advance();let e=this.pos.index;this.consumeWhile(()=>/[\d-]/.exec(this.curr()));let t=!1,n=!1;if(this.curr()==="T"&&(t=!0,this.advance(),this.consumeWhile(()=>/[\d:]/.exec(this.curr())),this.curr()==="."&&/\d/.exec(this.peek())&&(this.advance(),this.consumeWhile(()=>/\d/.exec(this.curr()))),this.curr()==="Z"?(n=!0,this.advance()):(this.curr()==="+"||this.curr()==="-")&&(n=!0,this.advance(),this.consumeWhile(()=>/[\d:]/.exec(this.curr())))),this.pos.index===e)throw new Error("Invalid DateTime literal");let i=this.str.substring(e,this.pos.index);return i.endsWith("T")?i=i.substring(0,i.length-1):!i.startsWith("T")&&t&&!n&&(i+="Z"),this.buildToken("DateTime",i)}consumeNumber(){let e=this.pos.index,t="Number";this.consumeWhile(()=>/\d/.exec(this.curr())),this.curr()==="."&&/\d/.exec(this.peek())&&(this.advance(),this.consumeWhile(()=>/\d/.exec(this.curr())));let n=this.curr();if(n==="-"&&this.dateTimeLiterals)return this.pos.index=e-1,this.consumeDateTime();if(n===" ")jc(this.peekToken())&&(t="Quantity",this.consumeToken());else if(n&&/[a-zA-Z_$]/.exec(n))return this.pos.index=e-1,this.consumeString(" ");return this.buildToken(t,this.str.substring(e,this.pos.index))}consumeSymbol(){let e=this.consumeWhile(()=>this.symbolRegex.exec(this.curr()));return this.prevToken()?.value!=="."&&this.keywords.includes(e)?this.buildToken(e,e):this.buildToken("Symbol",e)}consumeOperator(){let e=this.curr(),t=this.peek(),n=e+t;return this.operators.includes(n)?(this.advance(),this.advance(),this.buildToken(n,n)):(this.advance(),this.buildToken(e,e))}consumeWhile(e){let t=this.pos.index;for(;this.pos.index<this.str.length&&e();)this.advance();return this.str.substring(t,this.pos.index)}curr(){return this.str[this.pos.index]}peek(){return this.str[this.pos.index+1]??""}mark(){this.markStack.push({...this.pos})}reset(){let e=this.markStack.pop();if(!e)throw new Error("No mark to reset to");this.pos.index=e.index,this.pos.line=e.line,this.pos.column=e.column}advance(){this.pos.index++,this.curr()===`
|
|
4
|
-
`?(this.pos.line++,this.pos.column=0):this.pos.column++}buildToken(e,t){let n=this.markStack.pop();if(!n)throw new Error("No mark for token");return{id:e,value:t,...n}}};function jc(r){return!!(r&&(r.id==="String"||r.id==="Symbol"&&qc.includes(r.value)))}var Mt=["true","false"],_t=["!=","!~","<=",">=","{}","->"];function Po(r){return new ge(r,Mt,_t).tokenize()}var T={FunctionCall:0,Dot:1,Indexer:2,UnaryAdd:3,UnarySubtract:3,Multiply:4,Divide:4,IntegerDivide:4,Modulo:4,Add:5,Subtract:5,Ampersand:5,Is:6,As:6,Union:7,GreaterThan:8,GreaterThanOrEquals:8,LessThan:8,LessThanOrEquals:8,Equals:9,Equivalent:9,NotEquals:9,NotEquivalent:9,In:10,Contains:10,And:11,Xor:12,Or:12,Implies:13,Arrow:100,Semicolon:200},$c={parse(r){let e=r.consumeAndParse();if(!r.match(")"))throw new Error("Parse error: expected `)` got `"+r.peek()?.value+"`");return e}},Gc={parse(r,e){let t=r.consumeAndParse();if(!r.match("]"))throw new Error("Parse error: expected `]`");return new Ce(e,t)},precedence:T.Indexer},Hc={parse(r,e){if(!(e instanceof N))throw new Error("Unexpected parentheses");let t=[];for(;!r.match(")");)t.push(r.consumeAndParse()),r.match(",");return new ie(e.name,t)},precedence:T.FunctionCall};function Qc(r){let e=r.split(" "),t=Number.parseFloat(e[0]),n=e[1];return n?.startsWith("'")&&n.endsWith("'")?n=n.substring(1,n.length-1):n="{"+n+"}",{value:t,unit:n}}function Xe(){return new at().registerPrefix("String",{parse:(r,e)=>new W({type:d.string,value:e.value})}).registerPrefix("DateTime",{parse:(r,e)=>new W({type:d.dateTime,value:Ye(e.value)})}).registerPrefix("Quantity",{parse:(r,e)=>new W({type:d.Quantity,value:Qc(e.value)})}).registerPrefix("Number",{parse:(r,e)=>new W({type:e.value.includes(".")?d.decimal:d.integer,value:Number.parseFloat(e.value)})}).registerPrefix("true",{parse:()=>new W({type:d.boolean,value:!0})}).registerPrefix("false",{parse:()=>new W({type:d.boolean,value:!1})}).registerPrefix("Symbol",{parse:(r,e)=>new N(e.value)}).registerPrefix("{}",{parse:()=>new bt}).registerPrefix("(",$c).registerInfix("[",Gc).registerInfix("(",Hc).prefix("+",T.UnaryAdd,(r,e)=>new St("+",e,t=>t)).prefix("-",T.UnarySubtract,(r,e)=>new L("-",e,e,(t,n)=>-n)).infixLeft(".",T.Dot,(r,e,t)=>new K(r,t)).infixLeft("/",T.Divide,(r,e,t)=>new L("/",r,t,(n,i)=>n/i)).infixLeft("*",T.Multiply,(r,e,t)=>new L("*",r,t,(n,i)=>n*i)).infixLeft("+",T.Add,(r,e,t)=>new L("+",r,t,(n,i)=>n+i)).infixLeft("-",T.Subtract,(r,e,t)=>new L("-",r,t,(n,i)=>n-i)).infixLeft("|",T.Union,(r,e,t)=>new Ee(r,t)).infixLeft("=",T.Equals,(r,e,t)=>new Pt(r,t)).infixLeft("!=",T.NotEquals,(r,e,t)=>new At(r,t)).infixLeft("~",T.Equivalent,(r,e,t)=>new wt(r,t)).infixLeft("!~",T.NotEquivalent,(r,e,t)=>new Ot(r,t)).infixLeft("<",T.LessThan,(r,e,t)=>new L("<",r,t,(n,i)=>n<i)).infixLeft("<=",T.LessThanOrEquals,(r,e,t)=>new L("<=",r,t,(n,i)=>n<=i)).infixLeft(">",T.GreaterThan,(r,e,t)=>new L(">",r,t,(n,i)=>n>i)).infixLeft(">=",T.GreaterThanOrEquals,(r,e,t)=>new L(">=",r,t,(n,i)=>n>=i)).infixLeft("&",T.Ampersand,(r,e,t)=>new Et(r,t)).infixLeft("and",T.And,(r,e,t)=>new It(r,t)).infixLeft("as",T.As,(r,e,t)=>new ye(r,t)).infixLeft("contains",T.Contains,(r,e,t)=>new Rt(r,t)).infixLeft("div",T.Divide,(r,e,t)=>new L("div",r,t,(n,i)=>Math.trunc(n/i))).infixLeft("in",T.In,(r,e,t)=>new Ct(r,t)).infixLeft("is",T.Is,(r,e,t)=>new Re(r,t)).infixLeft("mod",T.Modulo,(r,e,t)=>new L("mod",r,t,(n,i)=>n%i)).infixLeft("or",T.Or,(r,e,t)=>new kt(r,t)).infixLeft("xor",T.Xor,(r,e,t)=>new Vt(r,t)).infixLeft("implies",T.Implies,(r,e,t)=>new Dt(r,t))}var zc=Xe();function Lt(r){return new he(r,zc.construct(Po(r)).consumeAndParse())}function Jc(r,e){let t=Array.isArray(e)?e:[e];for(let n=0;n<t.length;n++){let i=t[n];typeof i=="object"&&"type"in i&&"value"in i||(t[n]=b(t[n]))}return P(r,t).map(n=>n.value)}function P(r,e,t={},n=void 0){let i;if(typeof r=="string"){let o=n?.get(r);i=o??Lt(r),n&&!o&&n.set(r,i)}else i=r;return i.eval({variables:t},e).map(o=>{let s={type:o.type,value:o.value?.valueOf()};return"path"in o&&(s.path=o.path),s})}function Kc(r){let e=[];for(let t of r)t.type===d.Range?e.push([t.value?.low?.value,t.value?.high?.value]):typeof t.value=="number"&&e.push([t.value,t.value]);return e}function Gn(r){let e=[];for(let t of r){let n=ht(t.value);n&&e.push(n)}return e}function Hn(r){let e=new Set;for(let t of r){let n=Wn(t);n&&e.add(n)}return Array.from(e)}function Qn(r){let e=new Set;for(let t of r){let{value:n}=t;n&&(Me(n)?e.add(n):G(n)?e.add(n.reference):Je(n)?e.add(A(n)):typeof n.identifier=="object"&&e.add(`identifier:${n.identifier.system}|${n.identifier.value}`))}return Array.from(e)}function Yc(r){let e=[];for(let t of r){let{value:n}=t;typeof n=="number"?e.push({value:n}):I(n)&&e.push(n)}return e}function Xc(r){let e=new Set;for(let t of r)Me(t.value)&&e.add(t.value);return Array.from(e)}function zn(r,e={}){let t=[];for(let n of r)Zc(e,t,n);return t}function Zc(r,e,t){let{type:n,value:i}=t;switch(n){case d.Identifier:eu(e,r,i);break;case d.CodeableConcept:tu(e,r,i);break;case d.Coding:Ao(e,r,i);break;case d.ContactPoint:ru(e,r,i);break;default:Ne(e,r,void 0,i?.toString())}}function eu(r,e,t){t?.type?.text&&Ne(r,e,e.textSearchSystem,t.type.text),Ne(r,e,t?.system,t?.value)}function tu(r,e,t){t?.text&&Ne(r,e,e.textSearchSystem,t.text);for(let n of t?.coding??g)Ao(r,e,n)}function Ao(r,e,t){t&&(t.display&&Ne(r,e,e.textSearchSystem,t.display),Ne(r,e,t.system,t.code))}function ru(r,e,t){t&&Ne(r,e,t.system,t.value?.toLocaleLowerCase())}function Ne(r,e,t,n){(t||n)&&!r.some(i=>i.system===t&&i.value===n)&&r.push({system:t,value:n&&e.caseInsensitive?n.toLocaleLowerCase():n})}var nu=20,iu=1e3,m={EQUALS:"eq",NOT_EQUALS:"ne",GREATER_THAN:"gt",LESS_THAN:"lt",GREATER_THAN_OR_EQUALS:"ge",LESS_THAN_OR_EQUALS:"le",STARTS_AFTER:"sa",ENDS_BEFORE:"eb",APPROXIMATELY:"ap",CONTAINS:"contains",STARTS_WITH:"sw",EXACT:"exact",TEXT:"text",NOT:"not",ABOVE:"above",BELOW:"below",IN:"in",NOT_IN:"not-in",OF_TYPE:"of-type",MISSING:"missing",PRESENT:"present",IDENTIFIER:"identifier",ITERATE:"iterate"},Jn={contains:m.CONTAINS,exact:m.EXACT,above:m.ABOVE,below:m.BELOW,text:m.TEXT,not:m.NOT,in:m.IN,"not-in":m.NOT_IN,"of-type":m.OF_TYPE,missing:m.MISSING,identifier:m.IDENTIFIER,iterate:m.ITERATE},Kn={eq:m.EQUALS,ne:m.NOT_EQUALS,lt:m.LESS_THAN,le:m.LESS_THAN_OR_EQUALS,gt:m.GREATER_THAN,ge:m.GREATER_THAN_OR_EQUALS,sa:m.STARTS_AFTER,eb:m.ENDS_BEFORE,ap:m.APPROXIMATELY,sw:m.STARTS_WITH};function Ze(r,e){if(!r)throw new Error("Invalid search URL");let t="",n;if(typeof r=="string")if(r.includes("?")){let[s,a]=r.split("?");t=s,n=new URLSearchParams(a)}else t=r;else typeof r=="object"&&(t=r.pathname,n=r.searchParams);let i;t.includes("/")?i=t.split("/").filter(Boolean).pop():i=t;let o=[];if(n&&o.push(...n.entries()),e)for(let[s,a]of Object.entries(e))if(Array.isArray(a))for(let u of a)o.push([s,u]);else o.push([s,a??""]);return ou(i,o)}function ou(r,e){let t={resourceType:r};for(let[n,i]of e)su(t,n,i);return t}function su(r,e,t){let n,i,o=e.indexOf(":");if(o>=0?(n=e.substring(0,o),i=e.substring(o+1)):(n=e,i=""),n!=="_"){if(n==="_has"||e.includes(".")){r.filters=z(r.filters,{code:e,operator:m.EQUALS,value:t});return}switch(n){case"_sort":au(r,t);break;case"_cursor":r.cursor=t;break;case"_count":r.count=Number.parseInt(t,10);break;case"_offset":r.offset=Number.parseInt(t,10);break;case"_total":r.total=t;break;case"_summary":t==="count"?(r.total="accurate",r.count=0):(t==="true"||t==="data"||t==="text")&&(r.summary=t);break;case"_include":{let s=wo(t);i==="iterate"&&(s.modifier=m.ITERATE),r.include=z(r.include,s);break}case"_revinclude":{let s=wo(t);i==="iterate"&&(s.modifier=m.ITERATE),r.revInclude=z(r.revInclude,s);break}case"_fields":case"_elements":r.fields=t.split(",");break;case"_type":r.types=t.split(",");break;case"_format":r.format=t;break;case"_pretty":r.pretty=t==="true";break;default:{let s=q.types[r.resourceType]?.searchParams?.[n];s?r.filters=z(r.filters,ko(s,m.EQUALS,i,t)):r.filters=z(r.filters,uu(n,i,t))}}}}function au(r,e){for(let t of e.split(",")){let n,i=!1;t.startsWith("-")?(n=t.substring(1),i=!0):n=t,r.sortRules||(r.sortRules=[]),r.sortRules.push({code:n,descending:i})}}var cu=[m.MISSING,m.PRESENT];function ko(r,e,t,n){if(cu.includes(t||e))return{code:r.code,operator:t||e,value:n};switch(r.type){case"number":case"date":case"quantity":{let{operator:i,value:o}=lu(n,t||m.EQUALS);if(!Oo(r,o))throw new f(R(`Invalid format for ${r.type} search parameter: ${o}`));return{code:r.code,operator:i,value:o}}case"reference":case"string":case"token":case"uri":{if(!Oo(r,n))throw new f(R(`Invalid format for ${r.type} search parameter: ${n}`));return{code:r.code,operator:du(t)??e,value:n}}default:throw new Error("Unrecognized search parameter type: "+r.type)}}function uu(r,e,t){let n=m.EQUALS;if(e)n=e;else if(t.length>=2){let i=t.substring(0,2);i in Kn&&(t.length===2||t.at(2)?.match(/\d/))&&(n=i,t=t.substring(i.length))}return{code:r,operator:n,value:t}}function lu(r,e){let t=r.substring(0,2),n=Kn[t];return n?{operator:n,value:r.substring(2)}:{operator:e,value:r}}function du(r){return Jn[r]}function wo(r){let e=r.split(":");if(e.includes("*"))throw new f(R("'*' is not supported as a value for search inclusion parameters"));if(e.length===1)throw new f(R(`Invalid include value '${r}': must be of the form ResourceType:search-parameter`));if(e.length===2)return{resourceType:e[0],searchParam:e[1]};if(e.length===3)return{resourceType:e[0],searchParam:e[1],targetType:e[2]};throw new f(R(`Invalid include value '${r}'`))}function Oo(r,e){return r.type==="date"?De(e):!0}var pu=/{{([^{}]+)}}/g;function fu(r,e,t=[]){return r=r.replaceAll(pu,(n,i)=>{let o=P(i,t,e);return o.length!==1?"":$n(o[0])}),Ze(r)}function mu(r){let e=[];r.fields&&e.push("_fields="+r.fields.join(","));for(let t of r.filters??g)e.push(hu(t));r.sortRules&&r.sortRules.length>0&&e.push(yu(r.sortRules)),r.cursor!==void 0&&e.push("_cursor="+encodeURIComponent(r.cursor)),r.offset!==void 0&&r.offset!==0&&e.push("_offset="+r.offset),r.count!==void 0&&e.push("_count="+r.count),r.total!==void 0&&e.push("_total="+r.total),r.types&&r.types.length>0&&e.push("_type="+r.types.join(","));for(let t of r.include??g)e.push(Io("_include",t));for(let t of r.revInclude??g)e.push(Io("_revinclude",t));return e.length===0?"":(vt(e),"?"+e.join("&"))}function hu(r){let e=r.operator in Jn?":"+r.operator:"",t=r.operator!==m.EQUALS&&r.operator in Kn?r.operator:"";return`${r.code}${e}=${t}${encodeURIComponent(r.value)}`}function yu(r){return"_sort="+r.map(e=>e.descending?"-"+e.code:e.code).join(",")}function Io(r,e){return r+(e.modifier?":"+e.modifier:"")+"="+e.resourceType+":"+e.searchParam+(e.targetType?":"+e.targetType:"")}function et(r){let e=[],t="",n=!1;for(let i of r)n?(t+=i,n=!1):i==="\\"?n=!0:i===","?(e.push(t),t=""):t+=i;return e.push(t),e}function gu(r,e){return R(`Invalid modifier :${r} for ${e}`)}function xu(r,e){return r in Jn?gu(r,e):R(`Invalid operator ${r} for ${e}`)}function Ft(r,e){if(e.resourceType!==r.resourceType)return!1;for(let t of e.filters??g)if(!Tu(r,e,t))return!1;return!0}var vu=new Q(1e3);function Tu(r,e,t){let n=q.types[e.resourceType]?.searchParams?.[t.code];if(!n)return!1;let i=P(n.expression,[b(r)],void 0,vu);if(t.operator===m.MISSING||t.operator===m.PRESENT)return bu(i,t);switch(n.type){case"reference":return Su(i,t);case"string":case"uri":return Cu(i,t);case"token":return Eu(i,t);case"date":return Au(i,t);default:return!1}}function bu(r,e){let t=r.length>0;return(e.operator===m.MISSING&&e.value==="false"||e.operator===m.PRESENT&&e.value==="true")===t}function Su(r,e){let t=Ar(e.operator);if(e.value===""&&r.length===0)return e.operator===m.EQUALS;let n=Qn(r);for(let i of et(e.value)){let o=n.includes(i);if(!o&&e.code==="_compartment"&&(o=n.some(s=>s?.endsWith("/"+i))),o)return!t}return t}function Eu(r,e){let t=zn(r),n=et(e.value),i=Ar(e.operator);for(let o of t)for(let s of n)if(Ru(o,s))return!i;return i}function Ru(r,e){if(e.includes("|")){let[t,n]=e.split("|").map(i=>i.toLowerCase());return!t&&!n?!1:t?r.system?.toLowerCase()===t&&(!n||r.value?.toLowerCase()===n):!r.system&&r.value?.toLowerCase()===n}return r.value?.toLowerCase()===e.toLowerCase()}function Cu(r,e){let t=Hn(r),n=et(e.value),i=Ar(e.operator);for(let o of t)for(let s of n)if(Pu(o,s))return!i;return i}function Pu(r,e){return r.toLowerCase().includes(e.toLowerCase())}function Au(r,e){let t=Gn(r),n=et(e.value),i=Ar(e.operator);for(let o of t)for(let s of n)if(wu(o,e.operator,s))return!i;return i}function wu(r,e,t){if(!r)return!1;let n=ht(t);if(!n)return!1;let i=r.start??"0000",o=r.end??"9999",s=n.start,a=n.end;switch(e){case m.APPROXIMATELY:case m.EQUALS:case m.NOT_EQUALS:return i<a&&o>s;case m.LESS_THAN:return i<s;case m.GREATER_THAN:return o>a;case m.LESS_THAN_OR_EQUALS:return i<=a;case m.GREATER_THAN_OR_EQUALS:return o>=s;case m.STARTS_AFTER:return i>a;case m.ENDS_BEFORE:return o<s;default:return!1}}function Ar(r){return r===m.NOT_EQUALS||r===m.NOT}var Ou={resourceType:"*"},Vo=["DomainConfiguration","JsonWebKey","Login"],Do=["Package","PackageRelease","PackageInstallation","Project","ProjectMembership","User","UserSecurityRequest"],Pe={READ:"read",VREAD:"vread",UPDATE:"update",DELETE:"delete",HISTORY:"history",CREATE:"create",SEARCH:"search"},Mo=[Pe.READ,Pe.VREAD,Pe.HISTORY,Pe.SEARCH];function Iu(r,e){return Yn(r,Pe.SEARCH,e)}function ku(r,e){return Vo.includes(e)?!1:Yn(r,Pe.UPDATE,e)}function Yn(r,e,t){return!!r.resource?.some(n=>Lo(n,t,e))}function Vu(r,e){return!!_o(e,Pe.UPDATE,r)}function _o(r,e,t){return t?t.resource?.find(n=>Du(r,e,n)):Ou}function Du(r,e,t){let n=r.resourceType;return Lo(t,n,e)?n==="Binary"?!0:!(t.compartment&&!r.meta?.compartment?.some(i=>i.reference===t.compartment?.reference)||t.criteria&&!Ft(r,Ze(t.criteria))):!1}function Lo(r,e,t){return r.resourceType!==e&&(r.resourceType!=="*"||Do.includes(e))?!1:r.interaction?r.interaction.includes(t):!r.readonly||Mo.includes(t)}var Mu={FIRST:"first",APPLICATION:"application"};function j(){return typeof window<"u"}function _u(){return typeof Buffer<"u"}function Lu(){return typeof window<"u"?window:void 0}function wr(){return typeof Buffer<"u"?Buffer:void 0}var oe={assign(r){j()&&globalThis.location.assign(r)},reload(){j()&&globalThis.location.reload()},getSearch(){return j()?globalThis.location.search:""},getPathname(){return j()?globalThis.location.pathname:""},getLocation(){return j()?globalThis.location.toString():""},getOrigin(){return j()?globalThis.location.protocol+"//"+globalThis.location.host+"/":""}};function Fo(r){if(j()){let t=window.atob(r),n=Uint8Array.from(t,i=>i.codePointAt(0));return new window.TextDecoder().decode(n)}let e=wr();if(e)return e.from(r,"base64").toString("utf-8");throw new Error("Unable to decode base64")}function Nt(r){if(j()){let t=new window.TextEncoder().encode(r),n=String.fromCodePoint.apply(null,t);return window.btoa(n)}let e=wr();if(e)return e.from(r,"utf8").toString("base64");throw new Error("Unable to encode base64")}function Fu(r){return Nt(r).replaceAll("+","-").replaceAll("/","_").replace(/[=]{1,2}$/,"")}function Xn(r){r=r.padEnd(r.length+(4-r.length%4)%4,"=");let e=r.replaceAll("-","+").replaceAll("_","/");return Fo(e)}function Or(){let r=new Uint32Array(28);return crypto.getRandomValues(r),_n(r.buffer)}async function Zn(r){return crypto.subtle.digest("SHA-256",new TextEncoder().encode(r))}function se(){return typeof crypto<"u"&&"randomUUID"in crypto?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replaceAll(/[xy]/g,r=>{let e=Math.trunc(Math.random()*16);return(r==="x"?e:e&3|8).toString(16)})}function No(r){let e={};r=Se(r);for(let i of r.entry??g){let o=i.resource;if(!o)continue;o.meta!==void 0&&(delete o.meta.author,delete o.meta.compartment,delete o.meta.lastUpdated,delete o.meta.project,delete o.meta.versionId,Object.keys(o.meta).length===0&&delete o.meta);let s=o?.id;s&&(e[s]=se(),i.fullUrl="urn:uuid:"+e[s],delete i.resource?.id)}let t=r.entry,n=JSON.stringify({resourceType:"Bundle",type:"transaction",entry:t?.map(i=>({fullUrl:i.fullUrl,request:{method:"POST",url:i.resource?.resourceType},resource:i.resource}))},(i,o)=>Nu(i,o,e),2);return Uo(JSON.parse(n))}function Nu(r,e,t){if(r==="reference"&&typeof e=="string"){let n;if(e.includes("/")?n=e.split("/")[1]:e.startsWith("urn:uuid:")?n=e.slice(9):e.startsWith("#")&&(n=e.slice(1)),n){let i=t[n];if(i)return"urn:uuid:"+i}}return e}function Uo(r){let e=Bu(r),{sorted:t,cycles:n}=Uu(e),i={},o=[];for(let a of r.entry??g)a.fullUrl?i[a.fullUrl]=a:o.push(a);let s=t.map(a=>i[a]);for(let a of n)for(let u of a){let l=i[u],p={...l,request:{...l.request,method:"PUT"}};s.push(p)}return s.push(...o),{...r,entry:s}}var tt={NotVisited:"NotVisited",Visiting:"Visiting",Visited:"Visited"};function Uu(r){let e=[],t={},n=[];for(let o of Object.keys(r))t[o]=tt.NotVisited;function i(o,s){if(t[o]===tt.Visited)return!0;if(t[o]===tt.Visiting){let u=s.lastIndexOf(o);return u!==-1&&n.push(s.slice(u)),!0}t[o]=tt.Visiting,s.push(o);let a=!1;for(let u of r[o])i(u,s)||(a=!0);return t[o]=tt.Visited,s.pop(),e.unshift(o),!a}for(let o in r)t[o]===tt.NotVisited&&i(o,[]);return{sorted:e,cycles:n}}function Bo(r,e){for(let t in r)if(r[t]&&typeof r[t]=="object"){let n=r[t];if(G(n)){let i=n.reference;i.startsWith("urn:uuid:")&&e(i)}else Bo(n,e)}}function Bu(r){let e={};for(let t of r.entry??g)t.fullUrl&&(e[t.fullUrl]=[]);for(let t of r.entry??g){let n=t.fullUrl;t.resource&&Bo(t.resource,i=>{e[i]&&e[i].push(n)})}return e}function qu(r){r=Se(r);let e={resourceType:"Bundle",type:"transaction",entry:[{resource:r}]};if(r.contained){for(let t of r.contained)e.entry.push({resource:t});r.contained=void 0}for(let t of e.entry)t.resource&&!t.resource.id&&(t.resource.id=se());return No(e)}function Wu(r,e,t){return r.entry?.find(({resource:n})=>n?.resourceType===e&&n?.id===t)?.resource}async function ju(r,e,t,n){return{hook:t.hook,hookInstance:se(),context:n,prefetch:await $u(r,e,t,n)}}async function $u(r,e,t,n){if(!t.prefetch)return{};let i={};for(let[o,s]of Object.entries(t.prefetch)){let a=await Gu(r,e,n,s);i[o]=a??null}return i}function Gu(r,e,t,n){if(n=qo(e,t,n),n.includes("{{"))return Promise.resolve(null);let i=/^(\w+)\/([0-9a-zA-Z-_]+)$/.exec(n);if(i){let[a,u]=i.slice(1);return r.readResource(a,u)}let[o,s]=_e(n,"?",2);return r.search(o,s)}var Hu=new Set(["userPractitionerId","userPractitionerRoleId","userPatientId","userRelatedPersonId"]);function qo(r,e,t){return t.replaceAll(/\{\{([^}]+)\}\}/g,(n,i)=>{if(i=i.trim(),Hu.has(i))return r.id;if(i.startsWith("context.")){let o=i.substring(8),s=Qu(e,o);if(Me(s))return s;if(typeof s=="number"||typeof s=="boolean")return String(s)}return n})}function Qu(r,e){let t=e.split("."),n=r;for(let i of t)if(n&&E(n)&&i in n)n=n[i];else return;return n}var O={CSS:"text/css",DICOM:"application/dicom",FAVICON:"image/vnd.microsoft.icon",FHIR_JSON:"application/fhir+json",FORM_URL_ENCODED:"application/x-www-form-urlencoded",HL7_V2:"x-application/hl7-v2+er7",HTML:"text/html",JAVASCRIPT:"text/javascript",JSON:"application/json",JSON_PATCH:"application/json-patch+json",JWT:"application/jwt",MULTIPART_FORM_DATA:"multipart/form-data",PNG:"image/png",SCIM_JSON:"application/scim+json",SVG:"image/svg+xml",TEXT:"text/plain",TYPESCRIPT:"text/typescript",PING:"x-application/ping",XML:"text/xml",CDA_XML:"application/cda+xml",OCTET_STREAM:"application/octet-stream"};var Ir=class{constructor(){c(this,"listeners");this.listeners={}}addEventListener(e,t){this.listeners[e]||(this.listeners[e]=[]),this.listeners[e].push(t)}removeEventListener(e,t){let n=this.listeners[e];if(n){for(let i=0;i<n.length;i++)if(n[i]===t){n.splice(i,1);return}}}dispatchEvent(e){let t=this.listeners[e.type];for(let n of t??g)n.call(this,e);return!e.defaultPrevented}removeAllListeners(){this.listeners={}}listenerCount(e){return this.listeners[e]?.length??0}},Y=class{constructor(){c(this,"emitter",new Ir)}dispatchEvent(e){this.emitter.dispatchEvent(e)}addEventListener(e,t){this.emitter.addEventListener(e,t)}removeEventListener(e,t){this.emitter.removeEventListener(e,t)}removeAllListeners(){this.emitter.removeAllListeners()}listenerCount(e){return this.emitter.listenerCount(e)}};var kr={"Patient-open":"Patient-open","Patient-close":"Patient-close","ImagingStudy-open":"ImagingStudy-open","ImagingStudy-close":"ImagingStudy-close","Encounter-open":"Encounter-open","Encounter-close":"Encounter-close","DiagnosticReport-open":"DiagnosticReport-open","DiagnosticReport-close":"DiagnosticReport-close","DiagnosticReport-select":"DiagnosticReport-select","DiagnosticReport-update":"DiagnosticReport-update",syncerror:"syncerror"},Wo=["Patient","Encounter","ImagingStudy","DiagnosticReport","OperationOutcome","Bundle"],Vr=["DiagnosticReport-update"];function ei(r){return Vr.includes(r)}function ti(r){if(Vr.includes(r))throw new f(v(`'context.version' is required for '${r}'.`))}var jo={"Patient-open":{patient:{resourceType:"Patient"},encounter:{resourceType:"Encounter",optional:!0}},"Patient-close":{patient:{resourceType:"Patient"},encounter:{resourceType:"Encounter",optional:!0}},"ImagingStudy-open":{study:{resourceType:"ImagingStudy"},encounter:{resourceType:"Encounter",optional:!0},patient:{resourceType:"Patient",optional:!0}},"ImagingStudy-close":{study:{resourceType:"ImagingStudy"},encounter:{resourceType:"Encounter",optional:!0},patient:{resourceType:"Patient",optional:!0}},"Encounter-open":{encounter:{resourceType:"Encounter"},patient:{resourceType:"Patient"}},"Encounter-close":{encounter:{resourceType:"Encounter"},patient:{resourceType:"Patient"}},"DiagnosticReport-open":{report:{resourceType:"DiagnosticReport"},encounter:{resourceType:"Encounter",optional:!0},study:{resourceType:"ImagingStudy",optional:!0,manyAllowed:!0},patient:{resourceType:"Patient"}},"DiagnosticReport-close":{report:{resourceType:"DiagnosticReport"},encounter:{resourceType:"Encounter",optional:!0},study:{resourceType:"ImagingStudy",optional:!0,manyAllowed:!0},patient:{resourceType:"Patient"}},"DiagnosticReport-select":{report:{resourceType:"DiagnosticReport",reference:!0},patient:{resourceType:"Patient",optional:!0,reference:!0},select:{resourceType:"*",reference:!0,manyAllowed:!0}},"DiagnosticReport-update":{report:{resourceType:"DiagnosticReport",reference:!0},patient:{resourceType:"Patient",optional:!0,reference:!0},updates:{resourceType:"Bundle"}},syncerror:{operationoutcome:{resourceType:"OperationOutcome"}}};function $o(r){return Wo.includes(r)}function ri(r){return!!r.endpoint}function Dr(r){if(!Bt(r))throw new f(v("subscriptionRequest must be an object conforming to SubscriptionRequest type."));let{channelType:e,mode:t,topic:n,events:i}=r,o={"hub.channel.type":e,"hub.mode":t,"hub.topic":n,"hub.events":i.join(",")};return ri(r)&&(o.endpoint=r.endpoint),new URLSearchParams(o).toString()}function Bt(r){if(typeof r!="object")return!1;let{channelType:e,mode:t,topic:n,events:i}=r;if(!(e&&t&&n&&i)||typeof n!="string"||typeof i!="object"||!Array.isArray(i)||i.length<1||e!=="websocket"||t!=="subscribe"&&t!=="unsubscribe")return!1;for(let o of i)if(!kr[o])return!1;return!(ri(r)&&!(typeof r.endpoint=="string"&&r.endpoint.startsWith("ws")))}function zu(r,e,t,n){if(typeof e!="object")throw new f(v(`context[${t}] is invalid. Context must contain a single valid FHIR resource! Resource is not an object.`));if(!(e.id&&typeof e.id=="string"))throw new f(v(`context[${t}] is invalid. Resource must contain a valid string ID.`));if(!e.resourceType)throw new f(v(`context[${t}] is invalid. Resource must contain a resource type. No resource type found.`));let i=n.resourceType;if(i!=="*"){if(!$o(e.resourceType))throw new f(v(`context[${t}] is invalid. Resource must contain a valid FHIRcast resource type. Resource type is not a known resource type.`));if(i&&e.resourceType!==i)throw new f(v(`context[${t}] is invalid. context[${t}] for the '${r}' event should contain resource of type ${i}.`))}}function Ju(r,e,t,n,i){if(i.set(e.key,(i.get(e.key)??0)+1),n.reference){if(!G(e.reference))throw new f(v(`context[${t}] is invalid. Expected key '${e.key}' to be a reference.`))}else zu(r,e.resource,t,n)}function Ku(r,e){let t=new Map,n=jo[r];for(let i=0;i<e.length;i++){let o=e[i].key;if(!n[o])throw new f(v(`Key '${o}' not found for event '${r}'. Make sure to add only valid keys.`));Ju(r,e[i],i,n[o],t)}for(let[i,o]of Object.entries(n)){if(!(o.optional||t.has(i)))throw new f(v(`Missing required key '${i}' on context for '${r}' event.`));if(!o.manyAllowed&&(t.get(i)??0)>1)throw new f(v(`${t.get(i)} context entries with key '${i}' found for the '${r}' event when schema only allows for 1.`))}}function Mr(r,e,t,n){if(!(r&&typeof r=="string"))throw new f(v("Must provide a topic."));if(!kr[e])throw new f(v(`Must provide a valid FHIRcast event name. Supported events: ${Object.keys(kr).join(", ")}`));if(typeof t!="object")throw new f(v("context must be a context object or array of context objects."));if(Vr.includes(e)&&!n)throw new f(v(`The '${e}' event must contain a 'context.versionId'.`));let i=Array.isArray(t)?t:[t];return Ku(e,i),{timestamp:new Date().toISOString(),id:se(),event:{"hub.topic":r,"hub.event":e,context:i,...n?{"context.versionId":n}:{}}}}var Ut=class extends Y{constructor(t){super();c(this,"subRequest");c(this,"websocket");if(this.subRequest=t,!t.endpoint)throw new f(v("Subscription request should contain an endpoint."));if(!Bt(t))throw new f(v("Subscription request failed validation."));let n=new WebSocket(t.endpoint);n.addEventListener("open",()=>{this.dispatchEvent({type:"connect"}),n.addEventListener("message",i=>{let o=JSON.parse(i.data);if(o["hub.topic"])return;let s=o;s.event["hub.event"]!=="heartbeat"&&(this.dispatchEvent({type:"message",payload:s}),n.send(JSON.stringify({id:o?.id,timestamp:new Date().toISOString()})))}),n.addEventListener("close",()=>{this.dispatchEvent({type:"disconnect"})})}),this.websocket=n}disconnect(){this.websocket.close()}};function Yu(r){return JSON.parse(Xn(r))}function ni(r){return r.split(".").length===3}function qt(r){let[e,t,n]=r.split(".");return Yu(t)}function ii(r){try{return typeof qt(r).login_id=="string"}catch{return!1}}function oi(r){try{let t=qt(r).exp;return typeof t=="number"?t*1e3:void 0}catch{return}}var Wt=class{constructor(e){c(this,"medplum");this.medplum=e}async get(e){return this.medplum.get(`keyvalue/v1/${e}`)}async set(e,t){await this.medplum.put(`keyvalue/v1/${e}`,t,O.TEXT)}async delete(e){await this.medplum.delete(`keyvalue/v1/${e}`)}};var Go;Go=Symbol.toStringTag;var U=class{constructor(e){c(this,Go,"ReadablePromise");c(this,"suspender");c(this,"status","pending");c(this,"response");c(this,"error");this.suspender=e.then(t=>(this.status="success",this.response=t,t),t=>{throw this.status="error",this.error=t,t})}isPending(){return this.status==="pending"}isOk(){return this.status==="success"}read(){switch(this.status){case"pending":throw this.suspender;case"error":throw this.error;default:return this.response}}then(e,t){return this.suspender.then(e,t)}catch(e){return this.suspender.catch(e)}finally(e){return this.suspender.finally(e)}};var rt=class{constructor(e,t=""){c(this,"storage");c(this,"prefix","");this.storage=e??globalThis.localStorage??new _r,this.prefix=t}makeKey(e){return this.prefix+e}clear(){this.storage===globalThis.localStorage&&this.prefix?Object.keys(this.storage).filter(e=>e.startsWith(this.prefix)).forEach(e=>{this.storage.removeItem(e)}):this.storage.clear()}getString(e){return this.storage.getItem(this.makeKey(e))??void 0}setString(e,t){t?this.storage.setItem(this.makeKey(e),t):this.storage.removeItem(this.makeKey(e))}getObject(e){let t=this.getString(e);return t?JSON.parse(t):void 0}setObject(e,t){this.setString(e,t?xt(t):void 0)}},_r=class{constructor(){c(this,"data");this.data=new Map}get length(){return this.data.size}clear(){this.data.clear()}getItem(e){return this.data.get(e)??null}setItem(e,t){t?this.data.set(e,t):this.data.delete(e)}removeItem(e){this.data.delete(e)}key(e){return Array.from(this.data.keys())[e]}},si=class extends rt{constructor(){super();c(this,"initialized");c(this,"initPromise");c(this,"initResolve",()=>{});this.initialized=!1,this.initPromise=new Promise(t=>{this.initResolve=t})}setInitialized(){this.initialized||(this.initResolve(),this.initialized=!0)}getInitPromise(){return this.initPromise}get isInitialized(){return this.initialized}};var nt={Event:typeof globalThis.Event<"u"?globalThis.Event:void 0,ErrorEvent:void 0,CloseEvent:void 0},Ho=!1;function Xu(){if(typeof globalThis.Event>"u")throw new Error("Unable to lazy init events for ReconnectingWebSocket. globalThis.Event is not defined yet");nt.Event=globalThis.Event,nt.ErrorEvent=class extends Event{constructor(t,n){super("error",n);c(this,"message");c(this,"error");this.message=t.message,this.error=t}},nt.CloseEvent=class extends Event{constructor(t=1e3,n="",i){super("close",i);c(this,"code");c(this,"reason");c(this,"wasClean",!0);this.code=t,this.reason=n}}}function zo(r,e){if(!r)throw new Error(e)}function Lr(r){return new r.constructor(r.type,r)}var Ue={maxReconnectionDelay:1e4,minReconnectionDelay:1e3+Math.random()*4e3,minUptime:5e3,reconnectionDelayGrowFactor:1.3,connectionTimeout:4e3,maxRetries:1/0,maxEnqueuedMessages:1/0,startClosed:!1,debug:!1},Qo=!1,jt=class r extends Y{constructor(t,n,i={}){Ho||(Xu(),Ho=!0);super();c(this,"_ws");c(this,"_retryCount",-1);c(this,"_uptimeTimeout");c(this,"_connectTimeout");c(this,"_shouldReconnect",!0);c(this,"_connectLock",!1);c(this,"_binaryType");c(this,"_closeCalled",!1);c(this,"_messageQueue",[]);c(this,"_debugLogger",console.log.bind(console));c(this,"_url");c(this,"_protocols");c(this,"_options");c(this,"onclose",null);c(this,"onerror",null);c(this,"onmessage",null);c(this,"onopen",null);c(this,"_handleOpen",t=>{this._debug("open event");let{minUptime:n=Ue.minUptime}=this._options;clearTimeout(this._connectTimeout),this._uptimeTimeout=setTimeout(()=>this._acceptOpen(),n),zo(this._ws,"WebSocket is not defined"),this._ws.binaryType=this._binaryType,this._messageQueue.forEach(i=>this._ws?.send(i)),this._messageQueue=[],this.onopen&&this.onopen(t),this.dispatchEvent(Lr(t))});c(this,"_handleMessage",t=>{this._debug("message event"),this.onmessage&&this.onmessage(t),this.dispatchEvent(Lr(t))});c(this,"_handleError",t=>{this._debug("error event",t.message),this._disconnect(void 0,t.message==="TIMEOUT"?"timeout":void 0),this.onerror&&this.onerror(t),this._debug("exec error listeners"),this.dispatchEvent(Lr(t)),this._connect()});c(this,"_handleClose",t=>{this._debug("close event"),this._clearTimeouts(),this._shouldReconnect&&this._connect(),this.onclose&&this.onclose(t),this.dispatchEvent(Lr(t))});this._url=t,this._protocols=n,this._options=i,this._options.startClosed&&(this._shouldReconnect=!1),this._options.binaryType?this._binaryType=this._options.binaryType:this._binaryType="blob",this._options.debugLogger&&(this._debugLogger=this._options.debugLogger),this._connect()}static get CONNECTING(){return 0}static get OPEN(){return 1}static get CLOSING(){return 2}static get CLOSED(){return 3}get CONNECTING(){return r.CONNECTING}get OPEN(){return r.OPEN}get CLOSING(){return r.CLOSING}get CLOSED(){return r.CLOSED}get binaryType(){return this._ws?this._ws.binaryType:this._binaryType}set binaryType(t){this._binaryType=t,this._ws&&(this._ws.binaryType=t)}get retryCount(){return Math.max(this._retryCount,0)}get bufferedAmount(){return this._messageQueue.reduce((n,i)=>(typeof i=="string"?n+=i.length:i instanceof Blob?n+=i.size:n+=i.byteLength,n),0)+(this._ws?.bufferedAmount??0)}get extensions(){return this._ws?.extensions??""}get protocol(){return this._ws?.protocol??""}get readyState(){return this._ws?this._ws.readyState:this._options.startClosed?r.CLOSED:r.CONNECTING}get url(){return this._ws?this._ws.url:""}get shouldReconnect(){return this._shouldReconnect}close(t=1e3,n){if(this._closeCalled=!0,this._shouldReconnect=!1,this._clearTimeouts(),!this._ws){this._debug("close enqueued: no ws instance");return}if(this._ws.readyState===this.CLOSED){this._debug("close: already closed");return}this._ws.close(t,n)}reconnect(t,n){this._shouldReconnect=!0,this._closeCalled=!1,this._retryCount=-1,!this._ws||this._ws.readyState===this.CLOSED?this._connect():(this._disconnect(t,n),this._connect())}send(t){if(this._ws?.readyState===this.OPEN)this._debug("send",t),this._ws.send(t);else{let{maxEnqueuedMessages:n=Ue.maxEnqueuedMessages}=this._options;this._messageQueue.length<n&&(this._debug("enqueue",t),this._messageQueue.push(t))}}_debug(...t){this._options.debug&&this._debugLogger("RWS>",...t)}_getNextDelay(){let{reconnectionDelayGrowFactor:t=Ue.reconnectionDelayGrowFactor,minReconnectionDelay:n=Ue.minReconnectionDelay,maxReconnectionDelay:i=Ue.maxReconnectionDelay}=this._options,o=0;return this._retryCount>0&&(o=n*Math.pow(t,this._retryCount-1),o>i&&(o=i)),this._debug("next delay",o),o}_wait(){return new Promise(t=>{setTimeout(t,this._getNextDelay())})}_connect(){if(this._connectLock||!this._shouldReconnect)return;this._connectLock=!0;let{maxRetries:t=Ue.maxRetries,connectionTimeout:n=Ue.connectionTimeout}=this._options;if(this._retryCount>=t){this._debug("max retries reached",this._retryCount,">=",t);return}this._retryCount++,this._debug("connect",this._retryCount),this._removeListeners(),this._wait().then(()=>{if(this._closeCalled){this._connectLock=!1;return}!this._options.WebSocket&&typeof WebSocket>"u"&&!Qo&&(console.error("\u203C\uFE0F No WebSocket implementation available. You should define options.WebSocket."),Qo=!0);let i=this._options.WebSocket||WebSocket;this._debug("connect",{url:this._url,protocols:this._protocols}),this._ws=this._protocols?new i(this._url,this._protocols):new i(this._url),this._ws.binaryType=this._binaryType,this._connectLock=!1,this._addListeners(),this._connectTimeout=setTimeout(()=>this._handleTimeout(),n)}).catch(i=>{this._connectLock=!1,this._handleError(new nt.ErrorEvent(Error(i.message),this))})}_handleTimeout(){this._debug("timeout event"),this._handleError(new nt.ErrorEvent(Error("TIMEOUT"),this))}_disconnect(t=1e3,n){if(this._clearTimeouts(),!!this._ws){this._removeListeners();try{this._ws.close(t,n),this._handleClose(new nt.CloseEvent(t,n,this))}catch{}}}_acceptOpen(){this._debug("accept open"),this._retryCount=0}_removeListeners(){this._ws&&(this._debug("removeListeners"),this._ws.removeEventListener("open",this._handleOpen),this._ws.removeEventListener("close",this._handleClose),this._ws.removeEventListener("message",this._handleMessage),this._ws.removeEventListener("error",this._handleError))}_addListeners(){this._ws&&(this._debug("addListeners"),this._ws.addEventListener("open",this._handleOpen),this._ws.addEventListener("close",this._handleClose),this._ws.addEventListener("message",this._handleMessage),this._ws.addEventListener("error",this._handleError))}_clearTimeouts(){clearTimeout(this._connectTimeout),clearTimeout(this._uptimeTimeout)}};var Zu=[WebSocket.CLOSING,WebSocket.CLOSED],it=class extends Y{constructor(...t){super();c(this,"criteria");this.criteria=new Set(t)}getCriteria(){return this.criteria}_addCriteria(t){this.criteria.add(t)}_removeCriteria(t){this.criteria.delete(t)}},ai=class{constructor(e,t){c(this,"criteria");c(this,"emitter");c(this,"refCount");c(this,"subscriptionProps");c(this,"subscriptionId");c(this,"token");c(this,"tokenExpiry");c(this,"state","idle");c(this,"generation",0);c(this,"lastUnrefTime");this.criteria=e,this.emitter=new it(e),this.refCount=1,this.subscriptionProps=t?{...t}:void 0}nextGeneration(){return++this.generation}},Gt=class{constructor(e,t,n){c(this,"medplum");c(this,"ws");c(this,"masterSubEmitter");c(this,"criteriaEntries");c(this,"criteriaEntriesBySubscriptionId");c(this,"wsClosed");c(this,"pingTimer");c(this,"tokenRefreshTimer");c(this,"pingIntervalMs");c(this,"waitingForPong",!1);c(this,"currentProfile");if(!(e instanceof Ht))throw new f(v("First arg of constructor should be a `MedplumClient`"));let i;try{i=new URL(t).toString()}catch{throw new f(v("Not a valid URL"))}let o=n?.ReconnectingWebSocket?new n.ReconnectingWebSocket(i,void 0,{debug:n?.debug,debugLogger:n?.debugLogger}):new jt(i,void 0,{debug:n?.debug,debugLogger:n?.debugLogger});this.medplum=e,this.ws=o,this.masterSubEmitter=new it,this.criteriaEntries=new Map,this.criteriaEntriesBySubscriptionId=new Map,this.wsClosed=!1,this.pingIntervalMs=n?.pingIntervalMs??5e3,this.currentProfile=e.getProfile(),this.setupListeners()}setupListeners(){let e=this.ws;e.addEventListener("message",t=>{try{let n=JSON.parse(t.data);if(n.type==="pong"){this.waitingForPong=!1;return}let i=n,o=i?.entry?.[0]?.resource;if(o.type==="heartbeat"){this.masterSubEmitter?.dispatchEvent({type:"heartbeat",payload:i});return}if(o.type==="handshake"){let a=be(o.subscription),u={type:"connect",payload:{subscriptionId:a}};this.masterSubEmitter?.dispatchEvent(u);let l=this.criteriaEntriesBySubscriptionId.get(a);if(!l){console.warn("Received handshake for criteria the SubscriptionManager is not listening for yet");return}(l.state==="connecting"||l.state==="refreshing")&&(l.state="active"),l.emitter.dispatchEvent({...u});return}this.masterSubEmitter?.dispatchEvent({type:"message",payload:i});let s=this.criteriaEntriesBySubscriptionId.get(be(o.subscription));if(!s){console.warn("Received notification for criteria the SubscriptionManager is not listening for");return}s.emitter.dispatchEvent({type:"message",payload:i})}catch(n){console.error(n);let i={type:"error",payload:n};this.masterSubEmitter?.dispatchEvent(i);for(let o of this.getAllCriteriaEmitters())o.dispatchEvent({...i})}}),e.addEventListener("error",()=>{let t={type:"error",payload:new f(cn(new Error("WebSocket error")))};this.masterSubEmitter?.dispatchEvent(t);for(let n of this.getAllCriteriaEmitters())n.dispatchEvent({...t})}),e.addEventListener("close",()=>{let t={type:"close"};this.masterSubEmitter?.dispatchEvent(t);for(let n of this.getAllCriteriaEmitters())n.dispatchEvent({...t});this.pingTimer&&(clearInterval(this.pingTimer),this.pingTimer=void 0,this.waitingForPong=!1),this.tokenRefreshTimer&&(clearInterval(this.tokenRefreshTimer),this.tokenRefreshTimer=void 0),this.wsClosed&&(this.criteriaEntries.clear(),this.criteriaEntriesBySubscriptionId.clear(),this.masterSubEmitter?.removeAllListeners())}),e.addEventListener("open",()=>{let t={type:"open"};this.masterSubEmitter?.dispatchEvent(t);for(let n of this.getAllCriteriaEmitters())n.dispatchEvent({...t});this.refreshAllSubscriptions().catch(console.error),this.pingTimer??=setInterval(()=>{this.waitingForPong?(this.waitingForPong=!1,e.reconnect()):(e.send(JSON.stringify({type:"ping"})),this.waitingForPong=!0),this.gcUnrefEntries()},this.pingIntervalMs),this.tokenRefreshTimer??=setInterval(()=>{this.checkTokenExpirations(),this.gcUnrefEntries()},6e4)}),this.medplum.addEventListener("change",()=>{let t=this.medplum.getProfile();this.currentProfile&&t===void 0?this.ws.close():t&&this.currentProfile?.id!==t.id&&this.ws.reconnect(),this.currentProfile=t})}sendBind(e){this.ws.send(JSON.stringify({type:"bind-with-token",payload:{token:e}}))}sendUnbind(e){this.ws.readyState===WebSocket.OPEN&&this.ws.send(JSON.stringify({type:"unbind-from-token",payload:{token:e}}))}emitError(e,t){let n={type:"error",payload:t};this.masterSubEmitter?.dispatchEvent(n),e.emitter.dispatchEvent({...n})}maybeEmitDisconnect(e){let{subscriptionId:t}=e;if(t){let n={type:"disconnect",payload:{subscriptionId:t}};this.masterSubEmitter?.dispatchEvent(n),e.emitter.dispatchEvent({...n})}else console.warn("Called disconnect for `CriteriaEntry` before `subscriptionId` was present.")}isStale(e,t){return this.isEntryGettingRemoved(e)||e.generation!==t}maybeGetCriteriaEntry(e,t){let n=this.criteriaEntries.get(e);if(n){if(!t)return n.bareCriteria;for(let i of n.criteriaWithProps)if(de(t,i.subscriptionProps))return i}}getAllCriteriaEmitters(){let e=[];for(let t of this.criteriaEntries.values())for(let n of $t(t))n.refCount>0&&e.push(n.emitter);return e}addCriteriaEntry(e){let{criteria:t,subscriptionProps:n}=e,i;this.criteriaEntries.has(t)?i=this.criteriaEntries.get(t):(i={criteriaWithProps:[]},this.criteriaEntries.set(t,i)),n?i.criteriaWithProps.push(e):i.bareCriteria=e}removeCriteriaEntry(e){e.state="removed",e.generation++;let{criteria:t,subscriptionProps:n,subscriptionId:i,token:o}=e;if(!this.criteriaEntries.has(t))return;let s=this.criteriaEntries.get(t);n?s.criteriaWithProps=s.criteriaWithProps.filter(a=>{let u=a.subscriptionProps;return!de(n,u)}):s.bareCriteria=void 0,!s.bareCriteria&&s.criteriaWithProps.length===0&&(this.criteriaEntries.delete(t),this.masterSubEmitter?._removeCriteria(t)),i&&this.criteriaEntriesBySubscriptionId.delete(i),o&&this.sendUnbind(o)}async subscribeToCriteria(e){this.wsClosed&&await this.reconnectIfNeeded(),this.ws.readyState===WebSocket.OPEN&&e.state==="idle"&&(e.state="connecting",await this.rebindCriteriaEntry(e))}async refreshAllSubscriptions(){this.criteriaEntriesBySubscriptionId.clear();let e=[],t=[];for(let n of this.criteriaEntries.values())for(let i of $t(n))i.refCount===0?t.push(i):e.push(i);for(let n of t)this.removeCriteriaEntry(n);for(let n of e)n.token&&this.sendUnbind(n.token),n.token=void 0,n.tokenExpiry=void 0,n.state="idle",n.generation++,await this.subscribeToCriteria(n)}async rebindCriteriaEntry(e){let t=e.nextGeneration();try{if(!e.subscriptionId){let a=await this.medplum.createResource({...e.subscriptionProps,resourceType:"Subscription",status:"active",reason:`WebSocket subscription for ${A(this.medplum.getProfile())}`,channel:{type:"websocket"},criteria:e.criteria});if(e.subscriptionId??=a.id,this.isStale(e,t))return}let{parameter:n}=await this.medplum.get(`fhir/R4/Subscription/${e.subscriptionId}/$get-ws-binding-token`,{cache:"no-cache"}),i=n?.find(a=>a.name==="token")?.valueString,o=n?.find(a=>a.name==="websocket-url")?.valueUrl,s=n?.find(a=>a.name==="expiration")?.valueDateTime;if(!i)throw new f(v("Failed to get token"));if(!o)throw new f(v("Failed to get URL from $get-ws-binding-token"));if(!s)throw new f(v("Failed to get expiration from $get-ws-binding-token"));if(this.isStale(e,t))return;e.token=i,e.tokenExpiry=new Date(s).getTime(),this.criteriaEntriesBySubscriptionId.set(e.subscriptionId,e),this.sendBind(i)}catch(n){console.error(Oe(n)),e.generation===t&&!this.isEntryGettingRemoved(e)&&(e.state=e.state==="refreshing"?"active":"idle"),this.emitError(e,n)}}checkTokenExpirations(){let e=Date.now();for(let t of this.criteriaEntries.values())for(let n of $t(t))n.refCount===0||!n.tokenExpiry||n.tokenExpiry-e<=3e5&&n.state==="active"&&this.ws.readyState===WebSocket.OPEN&&(n.state="refreshing",this.rebindCriteriaEntry(n).catch(i=>{this.masterSubEmitter?.dispatchEvent({type:"error",payload:i})}))}addCriteria(e,t){this.masterSubEmitter&&this.masterSubEmitter._addCriteria(e);let n=this.maybeGetCriteriaEntry(e,t);if(n)return n.refCount===0&&(n.lastUnrefTime=void 0,n.generation++,n.state!=="active"&&(n.state=n.token?"active":"idle")),n.refCount+=1,n.state==="idle"&&this.subscribeToCriteria(n).catch(console.error),n.emitter;let i=new ai(e,t);return this.addCriteriaEntry(i),this.subscribeToCriteria(i).catch(console.error),i.emitter}removeCriteria(e,t){let n=this.maybeGetCriteriaEntry(e,t);if(!n||this.isEntryGettingRemoved(n)){console.warn("Criteria not known to `SubscriptionManager`. Possibly called remove too many times.");return}n.refCount-=1,n.refCount===0&&(n.lastUnrefTime=Date.now(),n.generation++)}gcUnrefEntries(){let e=Date.now(),t=[];for(let n of this.criteriaEntries.values())for(let i of $t(n))i.refCount===0&&i.lastUnrefTime!==void 0&&e-i.lastUnrefTime>=1e4&&t.push(i);for(let n of t)this.maybeEmitDisconnect(n),this.removeCriteriaEntry(n);t.length>0&&this.criteriaEntries.size===0&&this.closeWebSocket()}isEntryGettingRemoved(e){return e.refCount===0||e.state==="removed"}getWebSocket(){return this.ws}closeWebSocket(){if(!this.wsClosed){if(this.ws.readyState===WebSocket.OPEN)for(let e of this.criteriaEntries.values())for(let t of $t(e))t.token&&this.sendUnbind(t.token);this.wsClosed=!0,this.ws.close()}}reconnectWebSocket(){this.ws.reconnect(),this.wsClosed=!1}getCriteriaCount(){return this.getAllCriteriaEmitters().length}getMasterEmitter(){return this.masterSubEmitter||(this.masterSubEmitter=new it(...Array.from(this.criteriaEntries.keys()))),this.masterSubEmitter}async reconnectIfNeeded(){Zu.includes(this.getWebSocket().readyState)&&await new Promise(e=>{let t=()=>{this.getWebSocket().removeEventListener("open",t),e()};this.getWebSocket().addEventListener("open",t),this.reconnectWebSocket()})}};function $t(r){return r.bareCriteria?[r.bareCriteria,...r.criteriaWithProps]:r.criteriaWithProps}var el=new Q(1e3);async function tl({resource:r,subscription:e,context:t,getPreviousResource:n,logger:i}){if(!rl(e,i))return i?.debug("Ignore subscription without recognized channel type"),!1;let o=e.criteria;if(!o)return i?.debug("Ignore rest hook missing criteria"),!1;let s=Ze(o);if(r.resourceType!==s.resourceType)return i?.debug(`Ignore rest hook for different resourceType (wanted "${s.resourceType}", received "${r.resourceType}")`),!1;if(!await Jo(e,r,n))return i?.debug("Ignore rest hook for criteria returning false"),!1;let u=le(e,"https://medplum.com/fhir/StructureDefinition/subscription-supported-interaction");if(u&&u.valueCode!==t.interaction)return i?.debug(`Ignore rest hook for different interaction (wanted "${u.valueCode}", received "${t.interaction}")`),!1;if(!Ft(r,s))return!1;let l=br(e.meta)??[],p=br(r.meta)??[];return l.length&&!l.some(y=>p.some(x=>x.reference===y.reference))?(i?.debug("Subscription suppressed due to mismatched accounts",{subscriptionId:e.id,resource:A(r)}),!1):!0}function rl(r,e){let t=r.channel?.type;return t==="rest-hook"?r.channel?.endpoint?!0:(e?.debug("Ignore rest-hook missing URL"),!1):t==="websocket"}async function Jo(r,e,t){let n=le(r,"https://medplum.com/fhir/StructureDefinition/fhir-path-criteria-expression");if(!n?.valueString)return!0;let i=await t(e),o={"%current":b(e),"%previous":b(i??{})};return P(n.valueString,[b(e)],o,el)?.[0]?.value===!0}var Fr="5.1.8-d50cd6f",nl="medplum-cli",Zo=O.FHIR_JSON+", */*; q=0.1",il="https://api.medplum.com/",ol=1e3,sl=6e4,al=0,cl=3e5,ul="Binary/",Ko={resourceType:"Device",id:"system",deviceName:[{type:"model-name",name:"System"}]},Be={ClientCredentials:"client_credentials",AuthorizationCode:"authorization_code",RefreshToken:"refresh_token",JwtBearer:"urn:ietf:params:oauth:grant-type:jwt-bearer",TokenExchange:"urn:ietf:params:oauth:grant-type:token-exchange"},es={AccessToken:"urn:ietf:params:oauth:token-type:access_token",RefreshToken:"urn:ietf:params:oauth:token-type:refresh_token",IdToken:"urn:ietf:params:oauth:token-type:id_token",Saml1Token:"urn:ietf:params:oauth:token-type:saml1",Saml2Token:"urn:ietf:params:oauth:token-type:saml2"},ll={ClientSecretBasic:"client_secret_basic",ClientSecretPost:"client_secret_post",ClientSecretJwt:"client_secret_jwt",PrivateKeyJwt:"private_key_jwt",None:"none"},ts={JwtBearer:"urn:ietf:params:oauth:client-assertion-type:jwt-bearer"},dl={ES256:"ES256",ES384:"ES384",ES512:"ES512",HS256:"HS256",RS256:"RS256",RS384:"RS384",RS512:"RS512"},Ht=class extends Y{constructor(t){super();c(this,"options");c(this,"fetch");c(this,"createPdfImpl");c(this,"storage");c(this,"requestCache");c(this,"cacheTime");c(this,"baseUrl");c(this,"fhirBaseUrl");c(this,"authorizeUrl");c(this,"tokenUrl");c(this,"logoutUrl");c(this,"fhircastHubUrl");c(this,"cdsServicesUrl");c(this,"defaultHeaders");c(this,"onUnauthenticated");c(this,"autoBatchTime");c(this,"autoBatchQueue");c(this,"maxRetries");c(this,"maxRetryTime");c(this,"refreshGracePeriod");c(this,"subscriptionManager");c(this,"medplumServer");c(this,"clientId");c(this,"clientSecret");c(this,"credentialsInHeader");c(this,"autoBatchTimerId");c(this,"accessToken");c(this,"accessTokenExpires");c(this,"refreshToken");c(this,"refreshPromise");c(this,"profilePromise");c(this,"sessionDetails");c(this,"currentRateLimits");c(this,"basicAuth");c(this,"initPromise");c(this,"initComplete",!0);c(this,"keyValueClient");c(this,"logLevel");if(t?.baseUrl&&!t.baseUrl.startsWith("http"))throw new Error("Base URL must start with http or https");this.options=t??{},this.fetch=t?.fetch??pl(),this.storage=t?.storage??new rt(void 0,t?.storagePrefix),this.createPdfImpl=t?.createPdf,this.baseUrl=Rr(t?.baseUrl??il),this.fhirBaseUrl=F(this.baseUrl,t?.fhirUrlPath??"fhir/R4"),this.authorizeUrl=F(this.baseUrl,t?.authorizeUrl??"oauth2/authorize"),this.tokenUrl=F(this.baseUrl,t?.tokenUrl??"oauth2/token"),this.logoutUrl=F(this.baseUrl,t?.logoutUrl??"oauth2/logout"),this.fhircastHubUrl=F(this.baseUrl,t?.fhircastHubUrl??"fhircast/STU3"),this.cdsServicesUrl=F(this.baseUrl,t?.cdsServicesUrl??"cds-services"),this.clientId=t?.clientId??"",this.clientSecret=t?.clientSecret??"",this.credentialsInHeader=t?.authCredentialsMethod==="header",this.defaultHeaders=t?.defaultHeaders??{},this.onUnauthenticated=t?.onUnauthenticated,this.refreshGracePeriod=t?.refreshGracePeriod??cl,this.logLevel=this.initializeLogLevel(t),this.maxRetries=t?.maxRetries??2,this.maxRetryTime=t?.maxRetryTime??2e3,this.cacheTime=t?.cacheTime??(j()?sl:al),this.cacheTime>0?this.requestCache=new Q(t?.resourceCacheSize??ol):this.requestCache=void 0,t?.autoBatchTime?(this.autoBatchTime=t.autoBatchTime,this.autoBatchQueue=[]):(this.autoBatchTime=0,this.autoBatchQueue=void 0),t?.accessToken&&this.setAccessToken(t.accessToken),this.storage.getInitPromise===void 0?(t?.accessToken||this.attemptResumeActiveLogin().catch(console.error),this.initPromise=Promise.resolve(),this.dispatchEvent({type:"storageInitialized"})):(this.initComplete=!1,this.initPromise=this.storage.getInitPromise(),this.initPromise.then(()=>{t?.accessToken||this.attemptResumeActiveLogin().catch(console.error),this.initComplete=!0,this.dispatchEvent({type:"storageInitialized"})}).catch(n=>{console.error(n),this.initComplete=!0,this.dispatchEvent({type:"storageInitFailed",payload:{error:n}})})),this.setupStorageListener()}get isInitialized(){return this.initComplete}getInitPromise(){return this.initPromise}initializeLogLevel(t){return t?.logLevel?t.logLevel:t?.verbose!==void 0&&t.verbose?"verbose":"none"}async attemptResumeActiveLogin(){let t=this.getActiveLogin();t&&(this.setAccessToken(t.accessToken,t.refreshToken),await this.refreshProfile())}getBaseUrl(){return this.baseUrl}getAuthorizeUrl(){return this.authorizeUrl}getTokenUrl(){return this.tokenUrl}getLogoutUrl(){return this.logoutUrl}getFhircastHubUrl(){return this.fhircastHubUrl}getCdsServicesUrl(){return this.cdsServicesUrl}getDefaultHeaders(){return this.defaultHeaders}clear(){this.storage.clear(),j()&&sessionStorage.clear(),this.clearActiveLogin()}clearActiveLogin(){this.storage.setString("activeLogin",void 0),this.requestCache?.clear(),this.accessToken=void 0,this.refreshToken=void 0,this.refreshPromise=void 0,this.accessTokenExpires=void 0,this.sessionDetails=void 0,this.medplumServer=void 0,this.dispatchEvent({type:"change"})}invalidateUrl(t){t=t.toString(),this.requestCache?.delete(t)}invalidateAll(){this.requestCache?.clear()}invalidateSearches(t){let n=F(this.fhirBaseUrl,t);for(let i of this.requestCache?.keys()??g)(i.endsWith(n)||i.includes(n+"?"))&&this.requestCache?.delete(i)}get(t,n={}){t=t.toString();let i=this.getCacheEntry(t,n);if(i)return i.value;let o;t.startsWith(this.fhirBaseUrl)&&this.autoBatchQueue&&!n.disableAutoBatch?o=new Promise((a,u)=>{this.autoBatchQueue.push({method:"GET",url:t.replace(this.fhirBaseUrl,""),options:n,resolve:a,reject:u}),this.autoBatchTimerId||(this.autoBatchTimerId=setTimeout(()=>this.executeAutoBatch(),this.autoBatchTime))}):o=this.request("GET",t,n);let s=new U(o);return this.setCacheEntry(t,s,n),s}post(t,n,i,o={}){return t=t.toString(),this.setRequestBody(o,n),i&&this.setRequestContentType(o,i),this.invalidateUrl(t),this.request("POST",t,o)}put(t,n,i,o={}){return t=t.toString(),this.setRequestBody(o,n),i&&this.setRequestContentType(o,i),this.invalidateUrl(t),this.request("PUT",t,o)}patch(t,n,i={}){return t=t.toString(),this.setRequestBody(i,n),this.setRequestContentType(i,O.JSON_PATCH),this.invalidateUrl(t),this.request("PATCH",t,i)}delete(t,n){return t=t.toString(),this.invalidateUrl(t),this.request("DELETE",t,n)}async startNewUser(t,n){let{codeChallengeMethod:i,codeChallenge:o}=await this.startPkce();return this.post("auth/newuser",{...t,clientId:t.clientId??this.clientId,codeChallengeMethod:i,codeChallenge:o},void 0,n)}async startNewProject(t,n){return this.post("auth/newproject",t,void 0,n)}async startNewPatient(t,n){return this.post("auth/newpatient",t,void 0,n)}async startLogin(t,n){return this.post("auth/login",{...await this.ensureCodeChallenge(t),clientId:t.clientId??this.clientId,scope:t.scope},void 0,n)}async startGoogleLogin(t,n){return this.post("auth/google",{...await this.ensureCodeChallenge(t),clientId:t.clientId??this.clientId,scope:t.scope},void 0,n)}async ensureCodeChallenge(t){return t.codeChallenge?t:{...t,...await this.startPkce()}}async signOut(){await this.post(this.logoutUrl,{}),this.clear()}async signInWithRedirect(t){let i=new URLSearchParams(oe.getSearch()).get("code");if(!i){await this.requestAuthorization(t);return}return this.processCode(i)}signOutWithRedirect(){oe.assign(this.logoutUrl)}async signInWithExternalAuth(t,n,i,o,s=!0){let a=o;s&&(a=await this.ensureCodeChallenge(o)),oe.assign(this.getExternalAuthRedirectUri(t,n,i,a,s))}async exchangeExternalAccessToken(t,n,i){if(n=n??this.clientId,!n)throw new Error("MedplumClient is missing clientId");let o={grant_type:Be.TokenExchange,subject_token_type:es.AccessToken,client_id:n,subject_token:t};return i&&(o.membership_id=i),this.fetchTokens(o)}getExternalAuthRedirectUri(t,n,i,o,s=!0){let a=new URL(t);if(a.searchParams.set("response_type","code"),a.searchParams.set("client_id",n),a.searchParams.set("redirect_uri",i),a.searchParams.set("scope",o.scope??"openid profile email"),a.searchParams.set("state",JSON.stringify(o)),s){let{codeChallenge:u,codeChallengeMethod:l}=o;if(!l)throw new Error("`LoginRequest` for external auth must include a `codeChallengeMethod`.");if(!u)throw new Error("`LoginRequest` for external auth must include a `codeChallenge`.");a.searchParams.set("code_challenge_method",l),a.searchParams.set("code_challenge",u)}return a.toString()}fhirUrl(...t){return new URL(F(this.fhirBaseUrl,t.join("/")))}fhirSearchUrl(t,n){let i=this.fhirUrl(t);return n&&(i.search=qn(n)),i}search(t,n,i){let o=this.fhirSearchUrl(t,n),s="search-"+o.toString(),a=this.getCacheEntry(s,i);if(a)return a.value;let u=this.getBundle(o,i);return this.setCacheEntry(s,u,i),u}searchOne(t,n,i){let o=this.fhirSearchUrl(t,n);o.searchParams.set("_count","1"),o.searchParams.sort();let s="searchOne-"+o.toString(),a=this.getCacheEntry(s,i);if(a)return a.value;let u=new U(this.search(t,o.searchParams,i).then(l=>l.entry?.[0]?.resource));return this.setCacheEntry(s,u,i),u}searchResources(t,n,i){let s="searchResources-"+this.fhirSearchUrl(t,n).toString(),a=this.getCacheEntry(s,i);if(a)return a.value;let u=new U(this.search(t,n,i).then(Xo));return this.setCacheEntry(s,u,i),u}async*searchResourcePages(t,n,i){let o=this.fhirSearchUrl(t,n);for(;o;){let s=new URL(o).searchParams;s.has("_count")||s.set("_count","1000");let a=await this.search(t,s,i),u=a.link?.find(l=>l.relation==="next");if(!a.entry?.length&&!u)break;yield Xo(a),o=u?.url?new URL(u.url):void 0}}valueSetExpand(t,n){let i=this.fhirUrl("ValueSet","$expand");return i.search=new URLSearchParams(t).toString(),this.get(i.toString(),n)}getCached(t,n){let i=this.requestCache?.get(this.fhirUrl(t,n).toString())?.value;return i?.isOk()?i.read():void 0}getCachedReference(t){let n=t.reference;if(!n)return;if(n==="system")return Ko;let[i,o]=n.split("/");if(!(!i||!o))return this.getCached(i,o)}readResource(t,n,i){if(!n)throw new Error('The "id" parameter cannot be null, undefined, or an empty string.');return this.get(this.fhirUrl(t,n),i)}readReference(t,n){let i=t.reference;if(!i)return new U(Promise.reject(new Error("Missing reference")));if(i==="system")return new U(Promise.resolve(Ko));let[o,s]=i.split("/");return!o||!s?new U(Promise.reject(new Error("Invalid reference"))):this.readResource(o,s,n)}readCanonical(t,n,i){return Array.isArray(t)?this.searchOne("",{_type:t.join(","),url:n},i):this.searchOne(t,"url="+n,i)}requestSchema(t,n){if(gn(t))return Promise.resolve();let i=t+"-requestSchema",o=this.getCacheEntry(i,void 0);if(o)return o.value;let s=new U((async()=>{let a=`{
|
|
4
|
+
`?(this.pos.line++,this.pos.column=0):this.pos.column++}buildToken(e,t){let n=this.markStack.pop();if(!n)throw new Error("No mark for token");return{id:e,value:t,...n}}};function jc(r){return!!(r&&(r.id==="String"||r.id==="Symbol"&&qc.includes(r.value)))}var Mt=["true","false"],_t=["!=","!~","<=",">=","{}","->"];function Po(r){return new ge(r,Mt,_t).tokenize()}var T={FunctionCall:0,Dot:1,Indexer:2,UnaryAdd:3,UnarySubtract:3,Multiply:4,Divide:4,IntegerDivide:4,Modulo:4,Add:5,Subtract:5,Ampersand:5,Is:6,As:6,Union:7,GreaterThan:8,GreaterThanOrEquals:8,LessThan:8,LessThanOrEquals:8,Equals:9,Equivalent:9,NotEquals:9,NotEquivalent:9,In:10,Contains:10,And:11,Xor:12,Or:12,Implies:13,Arrow:100,Semicolon:200},$c={parse(r){let e=r.consumeAndParse();if(!r.match(")"))throw new Error("Parse error: expected `)` got `"+r.peek()?.value+"`");return e}},Gc={parse(r,e){let t=r.consumeAndParse();if(!r.match("]"))throw new Error("Parse error: expected `]`");return new Ce(e,t)},precedence:T.Indexer},Hc={parse(r,e){if(!(e instanceof N))throw new Error("Unexpected parentheses");let t=[];for(;!r.match(")");)t.push(r.consumeAndParse()),r.match(",");return new ie(e.name,t)},precedence:T.FunctionCall};function Qc(r){let e=r.split(" "),t=Number.parseFloat(e[0]),n=e[1];return n?.startsWith("'")&&n.endsWith("'")?n=n.substring(1,n.length-1):n="{"+n+"}",{value:t,unit:n}}function Xe(){return new at().registerPrefix("String",{parse:(r,e)=>new W({type:d.string,value:e.value})}).registerPrefix("DateTime",{parse:(r,e)=>new W({type:d.dateTime,value:Ye(e.value)})}).registerPrefix("Quantity",{parse:(r,e)=>new W({type:d.Quantity,value:Qc(e.value)})}).registerPrefix("Number",{parse:(r,e)=>new W({type:e.value.includes(".")?d.decimal:d.integer,value:Number.parseFloat(e.value)})}).registerPrefix("true",{parse:()=>new W({type:d.boolean,value:!0})}).registerPrefix("false",{parse:()=>new W({type:d.boolean,value:!1})}).registerPrefix("Symbol",{parse:(r,e)=>new N(e.value)}).registerPrefix("{}",{parse:()=>new bt}).registerPrefix("(",$c).registerInfix("[",Gc).registerInfix("(",Hc).prefix("+",T.UnaryAdd,(r,e)=>new St("+",e,t=>t)).prefix("-",T.UnarySubtract,(r,e)=>new L("-",e,e,(t,n)=>-n)).infixLeft(".",T.Dot,(r,e,t)=>new K(r,t)).infixLeft("/",T.Divide,(r,e,t)=>new L("/",r,t,(n,i)=>n/i)).infixLeft("*",T.Multiply,(r,e,t)=>new L("*",r,t,(n,i)=>n*i)).infixLeft("+",T.Add,(r,e,t)=>new L("+",r,t,(n,i)=>n+i)).infixLeft("-",T.Subtract,(r,e,t)=>new L("-",r,t,(n,i)=>n-i)).infixLeft("|",T.Union,(r,e,t)=>new Ee(r,t)).infixLeft("=",T.Equals,(r,e,t)=>new Pt(r,t)).infixLeft("!=",T.NotEquals,(r,e,t)=>new At(r,t)).infixLeft("~",T.Equivalent,(r,e,t)=>new wt(r,t)).infixLeft("!~",T.NotEquivalent,(r,e,t)=>new Ot(r,t)).infixLeft("<",T.LessThan,(r,e,t)=>new L("<",r,t,(n,i)=>n<i)).infixLeft("<=",T.LessThanOrEquals,(r,e,t)=>new L("<=",r,t,(n,i)=>n<=i)).infixLeft(">",T.GreaterThan,(r,e,t)=>new L(">",r,t,(n,i)=>n>i)).infixLeft(">=",T.GreaterThanOrEquals,(r,e,t)=>new L(">=",r,t,(n,i)=>n>=i)).infixLeft("&",T.Ampersand,(r,e,t)=>new Et(r,t)).infixLeft("and",T.And,(r,e,t)=>new It(r,t)).infixLeft("as",T.As,(r,e,t)=>new ye(r,t)).infixLeft("contains",T.Contains,(r,e,t)=>new Rt(r,t)).infixLeft("div",T.Divide,(r,e,t)=>new L("div",r,t,(n,i)=>Math.trunc(n/i))).infixLeft("in",T.In,(r,e,t)=>new Ct(r,t)).infixLeft("is",T.Is,(r,e,t)=>new Re(r,t)).infixLeft("mod",T.Modulo,(r,e,t)=>new L("mod",r,t,(n,i)=>n%i)).infixLeft("or",T.Or,(r,e,t)=>new kt(r,t)).infixLeft("xor",T.Xor,(r,e,t)=>new Vt(r,t)).infixLeft("implies",T.Implies,(r,e,t)=>new Dt(r,t))}var zc=Xe();function Lt(r){return new he(r,zc.construct(Po(r)).consumeAndParse())}function Jc(r,e){let t=Array.isArray(e)?e:[e];for(let n=0;n<t.length;n++){let i=t[n];typeof i=="object"&&"type"in i&&"value"in i||(t[n]=b(t[n]))}return P(r,t).map(n=>n.value)}function P(r,e,t={},n=void 0){let i;if(typeof r=="string"){let o=n?.get(r);i=o??Lt(r),n&&!o&&n.set(r,i)}else i=r;return i.eval({variables:t},e).map(o=>{let s={type:o.type,value:o.value?.valueOf()};return"path"in o&&(s.path=o.path),s})}function Kc(r){let e=[];for(let t of r)t.type===d.Range?e.push([t.value?.low?.value,t.value?.high?.value]):typeof t.value=="number"&&e.push([t.value,t.value]);return e}function Gn(r){let e=[];for(let t of r){let n=ht(t.value);n&&e.push(n)}return e}function Hn(r){let e=new Set;for(let t of r){let n=Wn(t);n&&e.add(n)}return Array.from(e)}function Qn(r){let e=new Set;for(let t of r){let{value:n}=t;n&&(Me(n)?e.add(n):G(n)?e.add(n.reference):Je(n)?e.add(A(n)):typeof n.identifier=="object"&&e.add(`identifier:${n.identifier.system}|${n.identifier.value}`))}return Array.from(e)}function Yc(r){let e=[];for(let t of r){let{value:n}=t;typeof n=="number"?e.push({value:n}):I(n)&&e.push(n)}return e}function Xc(r){let e=new Set;for(let t of r)Me(t.value)&&e.add(t.value);return Array.from(e)}function zn(r,e={}){let t=[];for(let n of r)Zc(e,t,n);return t}function Zc(r,e,t){let{type:n,value:i}=t;switch(n){case d.Identifier:eu(e,r,i);break;case d.CodeableConcept:tu(e,r,i);break;case d.Coding:Ao(e,r,i);break;case d.ContactPoint:ru(e,r,i);break;default:Ne(e,r,void 0,i?.toString())}}function eu(r,e,t){t?.type?.text&&Ne(r,e,e.textSearchSystem,t.type.text),Ne(r,e,t?.system,t?.value)}function tu(r,e,t){t?.text&&Ne(r,e,e.textSearchSystem,t.text);for(let n of t?.coding??g)Ao(r,e,n)}function Ao(r,e,t){t&&(t.display&&Ne(r,e,e.textSearchSystem,t.display),Ne(r,e,t.system,t.code))}function ru(r,e,t){t&&Ne(r,e,t.system,t.value?.toLocaleLowerCase())}function Ne(r,e,t,n){(t||n)&&!r.some(i=>i.system===t&&i.value===n)&&r.push({system:t,value:n&&e.caseInsensitive?n.toLocaleLowerCase():n})}var nu=20,iu=1e3,m={EQUALS:"eq",NOT_EQUALS:"ne",GREATER_THAN:"gt",LESS_THAN:"lt",GREATER_THAN_OR_EQUALS:"ge",LESS_THAN_OR_EQUALS:"le",STARTS_AFTER:"sa",ENDS_BEFORE:"eb",APPROXIMATELY:"ap",CONTAINS:"contains",STARTS_WITH:"sw",EXACT:"exact",TEXT:"text",NOT:"not",ABOVE:"above",BELOW:"below",IN:"in",NOT_IN:"not-in",OF_TYPE:"of-type",MISSING:"missing",PRESENT:"present",IDENTIFIER:"identifier",ITERATE:"iterate"},Jn={contains:m.CONTAINS,exact:m.EXACT,above:m.ABOVE,below:m.BELOW,text:m.TEXT,not:m.NOT,in:m.IN,"not-in":m.NOT_IN,"of-type":m.OF_TYPE,missing:m.MISSING,identifier:m.IDENTIFIER,iterate:m.ITERATE},Kn={eq:m.EQUALS,ne:m.NOT_EQUALS,lt:m.LESS_THAN,le:m.LESS_THAN_OR_EQUALS,gt:m.GREATER_THAN,ge:m.GREATER_THAN_OR_EQUALS,sa:m.STARTS_AFTER,eb:m.ENDS_BEFORE,ap:m.APPROXIMATELY,sw:m.STARTS_WITH};function Ze(r,e){if(!r)throw new Error("Invalid search URL");let t="",n;if(typeof r=="string")if(r.includes("?")){let[s,a]=r.split("?");t=s,n=new URLSearchParams(a)}else t=r;else typeof r=="object"&&(t=r.pathname,n=r.searchParams);let i;t.includes("/")?i=t.split("/").filter(Boolean).pop():i=t;let o=[];if(n&&o.push(...n.entries()),e)for(let[s,a]of Object.entries(e))if(Array.isArray(a))for(let u of a)o.push([s,u]);else o.push([s,a??""]);return ou(i,o)}function ou(r,e){let t={resourceType:r};for(let[n,i]of e)su(t,n,i);return t}function su(r,e,t){let n,i,o=e.indexOf(":");if(o>=0?(n=e.substring(0,o),i=e.substring(o+1)):(n=e,i=""),n!=="_"){if(n==="_has"||e.includes(".")){r.filters=z(r.filters,{code:e,operator:m.EQUALS,value:t});return}switch(n){case"_sort":au(r,t);break;case"_cursor":r.cursor=t;break;case"_count":r.count=Number.parseInt(t,10);break;case"_offset":r.offset=Number.parseInt(t,10);break;case"_total":r.total=t;break;case"_summary":t==="count"?(r.total="accurate",r.count=0):(t==="true"||t==="data"||t==="text")&&(r.summary=t);break;case"_include":{let s=wo(t);i==="iterate"&&(s.modifier=m.ITERATE),r.include=z(r.include,s);break}case"_revinclude":{let s=wo(t);i==="iterate"&&(s.modifier=m.ITERATE),r.revInclude=z(r.revInclude,s);break}case"_fields":case"_elements":r.fields=t.split(",");break;case"_type":r.types=t.split(",");break;case"_format":r.format=t;break;case"_pretty":r.pretty=t==="true";break;default:{let s=q.types[r.resourceType]?.searchParams?.[n];s?r.filters=z(r.filters,ko(s,m.EQUALS,i,t)):r.filters=z(r.filters,uu(n,i,t))}}}}function au(r,e){for(let t of e.split(",")){let n,i=!1;t.startsWith("-")?(n=t.substring(1),i=!0):n=t,r.sortRules||(r.sortRules=[]),r.sortRules.push({code:n,descending:i})}}var cu=[m.MISSING,m.PRESENT];function ko(r,e,t,n){if(cu.includes(t||e))return{code:r.code,operator:t||e,value:n};switch(r.type){case"number":case"date":case"quantity":{let{operator:i,value:o}=lu(n,t||m.EQUALS);if(!Oo(r,o))throw new f(R(`Invalid format for ${r.type} search parameter: ${o}`));return{code:r.code,operator:i,value:o}}case"reference":case"string":case"token":case"uri":{if(!Oo(r,n))throw new f(R(`Invalid format for ${r.type} search parameter: ${n}`));return{code:r.code,operator:du(t)??e,value:n}}default:throw new Error("Unrecognized search parameter type: "+r.type)}}function uu(r,e,t){let n=m.EQUALS;if(e)n=e;else if(t.length>=2){let i=t.substring(0,2);i in Kn&&(t.length===2||t.at(2)?.match(/\d/))&&(n=i,t=t.substring(i.length))}return{code:r,operator:n,value:t}}function lu(r,e){let t=r.substring(0,2),n=Kn[t];return n?{operator:n,value:r.substring(2)}:{operator:e,value:r}}function du(r){return Jn[r]}function wo(r){let e=r.split(":");if(e.includes("*"))throw new f(R("'*' is not supported as a value for search inclusion parameters"));if(e.length===1)throw new f(R(`Invalid include value '${r}': must be of the form ResourceType:search-parameter`));if(e.length===2)return{resourceType:e[0],searchParam:e[1]};if(e.length===3)return{resourceType:e[0],searchParam:e[1],targetType:e[2]};throw new f(R(`Invalid include value '${r}'`))}function Oo(r,e){return r.type==="date"?De(e):!0}var pu=/{{([^{}]+)}}/g;function fu(r,e,t=[]){return r=r.replaceAll(pu,(n,i)=>{let o=P(i,t,e);return o.length!==1?"":$n(o[0])}),Ze(r)}function mu(r){let e=[];r.fields&&e.push("_fields="+r.fields.join(","));for(let t of r.filters??g)e.push(hu(t));r.sortRules&&r.sortRules.length>0&&e.push(yu(r.sortRules)),r.cursor!==void 0&&e.push("_cursor="+encodeURIComponent(r.cursor)),r.offset!==void 0&&r.offset!==0&&e.push("_offset="+r.offset),r.count!==void 0&&e.push("_count="+r.count),r.total!==void 0&&e.push("_total="+r.total),r.types&&r.types.length>0&&e.push("_type="+r.types.join(","));for(let t of r.include??g)e.push(Io("_include",t));for(let t of r.revInclude??g)e.push(Io("_revinclude",t));return e.length===0?"":(vt(e),"?"+e.join("&"))}function hu(r){let e=r.operator in Jn?":"+r.operator:"",t=r.operator!==m.EQUALS&&r.operator in Kn?r.operator:"";return`${r.code}${e}=${t}${encodeURIComponent(r.value)}`}function yu(r){return"_sort="+r.map(e=>e.descending?"-"+e.code:e.code).join(",")}function Io(r,e){return r+(e.modifier?":"+e.modifier:"")+"="+e.resourceType+":"+e.searchParam+(e.targetType?":"+e.targetType:"")}function et(r){let e=[],t="",n=!1;for(let i of r)n?(t+=i,n=!1):i==="\\"?n=!0:i===","?(e.push(t),t=""):t+=i;return e.push(t),e}function gu(r,e){return R(`Invalid modifier :${r} for ${e}`)}function xu(r,e){return r in Jn?gu(r,e):R(`Invalid operator ${r} for ${e}`)}function Ft(r,e){if(e.resourceType!==r.resourceType)return!1;for(let t of e.filters??g)if(!Tu(r,e,t))return!1;return!0}var vu=new Q(1e3);function Tu(r,e,t){let n=q.types[e.resourceType]?.searchParams?.[t.code];if(!n)return!1;let i=P(n.expression,[b(r)],void 0,vu);if(t.operator===m.MISSING||t.operator===m.PRESENT)return bu(i,t);switch(n.type){case"reference":return Su(i,t);case"string":case"uri":return Cu(i,t);case"token":return Eu(i,t);case"date":return Au(i,t);default:return!1}}function bu(r,e){let t=r.length>0;return(e.operator===m.MISSING&&e.value==="false"||e.operator===m.PRESENT&&e.value==="true")===t}function Su(r,e){let t=Ar(e.operator);if(e.value===""&&r.length===0)return e.operator===m.EQUALS;let n=Qn(r);for(let i of et(e.value)){let o=n.includes(i);if(!o&&e.code==="_compartment"&&(o=n.some(s=>s?.endsWith("/"+i))),o)return!t}return t}function Eu(r,e){let t=zn(r),n=et(e.value),i=Ar(e.operator);for(let o of t)for(let s of n)if(Ru(o,s))return!i;return i}function Ru(r,e){if(e.includes("|")){let[t,n]=e.split("|").map(i=>i.toLowerCase());return!t&&!n?!1:t?r.system?.toLowerCase()===t&&(!n||r.value?.toLowerCase()===n):!r.system&&r.value?.toLowerCase()===n}return r.value?.toLowerCase()===e.toLowerCase()}function Cu(r,e){let t=Hn(r),n=et(e.value),i=Ar(e.operator);for(let o of t)for(let s of n)if(Pu(o,s))return!i;return i}function Pu(r,e){return r.toLowerCase().includes(e.toLowerCase())}function Au(r,e){let t=Gn(r),n=et(e.value),i=Ar(e.operator);for(let o of t)for(let s of n)if(wu(o,e.operator,s))return!i;return i}function wu(r,e,t){if(!r)return!1;let n=ht(t);if(!n)return!1;let i=r.start??"0000",o=r.end??"9999",s=n.start,a=n.end;switch(e){case m.APPROXIMATELY:case m.EQUALS:case m.NOT_EQUALS:return i<a&&o>s;case m.LESS_THAN:return i<s;case m.GREATER_THAN:return o>a;case m.LESS_THAN_OR_EQUALS:return i<=a;case m.GREATER_THAN_OR_EQUALS:return o>=s;case m.STARTS_AFTER:return i>a;case m.ENDS_BEFORE:return o<s;default:return!1}}function Ar(r){return r===m.NOT_EQUALS||r===m.NOT}var Ou={resourceType:"*"},Vo=["DomainConfiguration","JsonWebKey","Login"],Do=["Package","PackageRelease","PackageInstallation","Project","ProjectMembership","User","UserSecurityRequest"],Pe={READ:"read",VREAD:"vread",UPDATE:"update",DELETE:"delete",HISTORY:"history",CREATE:"create",SEARCH:"search"},Mo=[Pe.READ,Pe.VREAD,Pe.HISTORY,Pe.SEARCH];function Iu(r,e){return Yn(r,Pe.SEARCH,e)}function ku(r,e){return Vo.includes(e)?!1:Yn(r,Pe.UPDATE,e)}function Yn(r,e,t){return!!r.resource?.some(n=>Lo(n,t,e))}function Vu(r,e){return!!_o(e,Pe.UPDATE,r)}function _o(r,e,t){return t?t.resource?.find(n=>Du(r,e,n)):Ou}function Du(r,e,t){let n=r.resourceType;return Lo(t,n,e)?n==="Binary"?!0:!(t.compartment&&!r.meta?.compartment?.some(i=>i.reference===t.compartment?.reference)||t.criteria&&!Ft(r,Ze(t.criteria))):!1}function Lo(r,e,t){return r.resourceType!==e&&(r.resourceType!=="*"||Do.includes(e))?!1:r.interaction?r.interaction.includes(t):!r.readonly||Mo.includes(t)}var Mu={FIRST:"first",APPLICATION:"application"};function j(){return typeof window<"u"}function _u(){return typeof Buffer<"u"}function Lu(){return typeof window<"u"?window:void 0}function wr(){return typeof Buffer<"u"?Buffer:void 0}var oe={assign(r){j()&&globalThis.location.assign(r)},reload(){j()&&globalThis.location.reload()},getSearch(){return j()?globalThis.location.search:""},getPathname(){return j()?globalThis.location.pathname:""},getLocation(){return j()?globalThis.location.toString():""},getOrigin(){return j()?globalThis.location.protocol+"//"+globalThis.location.host+"/":""}};function Fo(r){if(j()){let t=window.atob(r),n=Uint8Array.from(t,i=>i.codePointAt(0));return new window.TextDecoder().decode(n)}let e=wr();if(e)return e.from(r,"base64").toString("utf-8");throw new Error("Unable to decode base64")}function Nt(r){if(j()){let t=new window.TextEncoder().encode(r),n=String.fromCodePoint.apply(null,t);return window.btoa(n)}let e=wr();if(e)return e.from(r,"utf8").toString("base64");throw new Error("Unable to encode base64")}function Fu(r){return Nt(r).replaceAll("+","-").replaceAll("/","_").replace(/[=]{1,2}$/,"")}function Xn(r){r=r.padEnd(r.length+(4-r.length%4)%4,"=");let e=r.replaceAll("-","+").replaceAll("_","/");return Fo(e)}function Or(){let r=new Uint32Array(28);return crypto.getRandomValues(r),_n(r.buffer)}async function Zn(r){return crypto.subtle.digest("SHA-256",new TextEncoder().encode(r))}function se(){return typeof crypto<"u"&&"randomUUID"in crypto?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replaceAll(/[xy]/g,r=>{let e=Math.trunc(Math.random()*16);return(r==="x"?e:e&3|8).toString(16)})}function No(r){let e={};r=Se(r);for(let i of r.entry??g){let o=i.resource;if(!o)continue;o.meta!==void 0&&(delete o.meta.author,delete o.meta.compartment,delete o.meta.lastUpdated,delete o.meta.project,delete o.meta.versionId,Object.keys(o.meta).length===0&&delete o.meta);let s=o?.id;s&&(e[s]=se(),i.fullUrl="urn:uuid:"+e[s],delete i.resource?.id)}let t=r.entry,n=JSON.stringify({resourceType:"Bundle",type:"transaction",entry:t?.map(i=>({fullUrl:i.fullUrl,request:{method:"POST",url:i.resource?.resourceType},resource:i.resource}))},(i,o)=>Nu(i,o,e),2);return Uo(JSON.parse(n))}function Nu(r,e,t){if(r==="reference"&&typeof e=="string"){let n;if(e.includes("/")?n=e.split("/")[1]:e.startsWith("urn:uuid:")?n=e.slice(9):e.startsWith("#")&&(n=e.slice(1)),n){let i=t[n];if(i)return"urn:uuid:"+i}}return e}function Uo(r){let e=Bu(r),{sorted:t,cycles:n}=Uu(e),i={},o=[];for(let a of r.entry??g)a.fullUrl?i[a.fullUrl]=a:o.push(a);let s=t.map(a=>i[a]);for(let a of n)for(let u of a){let l=i[u],p={...l,request:{...l.request,method:"PUT"}};s.push(p)}return s.push(...o),{...r,entry:s}}var tt={NotVisited:"NotVisited",Visiting:"Visiting",Visited:"Visited"};function Uu(r){let e=[],t={},n=[];for(let o of Object.keys(r))t[o]=tt.NotVisited;function i(o,s){if(t[o]===tt.Visited)return!0;if(t[o]===tt.Visiting){let u=s.lastIndexOf(o);return u!==-1&&n.push(s.slice(u)),!0}t[o]=tt.Visiting,s.push(o);let a=!1;for(let u of r[o])i(u,s)||(a=!0);return t[o]=tt.Visited,s.pop(),e.unshift(o),!a}for(let o in r)t[o]===tt.NotVisited&&i(o,[]);return{sorted:e,cycles:n}}function Bo(r,e){for(let t in r)if(r[t]&&typeof r[t]=="object"){let n=r[t];if(G(n)){let i=n.reference;i.startsWith("urn:uuid:")&&e(i)}else Bo(n,e)}}function Bu(r){let e={};for(let t of r.entry??g)t.fullUrl&&(e[t.fullUrl]=[]);for(let t of r.entry??g){let n=t.fullUrl;t.resource&&Bo(t.resource,i=>{e[i]&&e[i].push(n)})}return e}function qu(r){r=Se(r);let e={resourceType:"Bundle",type:"transaction",entry:[{resource:r}]};if(r.contained){for(let t of r.contained)e.entry.push({resource:t});r.contained=void 0}for(let t of e.entry)t.resource&&!t.resource.id&&(t.resource.id=se());return No(e)}function Wu(r,e,t){return r.entry?.find(({resource:n})=>n?.resourceType===e&&n?.id===t)?.resource}async function ju(r,e,t,n){return{hook:t.hook,hookInstance:se(),context:n,prefetch:await $u(r,e,t,n)}}async function $u(r,e,t,n){if(!t.prefetch)return{};let i={};for(let[o,s]of Object.entries(t.prefetch)){let a=await Gu(r,e,n,s);i[o]=a??null}return i}function Gu(r,e,t,n){if(n=qo(e,t,n),n.includes("{{"))return Promise.resolve(null);let i=/^(\w+)\/([0-9a-zA-Z-_]+)$/.exec(n);if(i){let[a,u]=i.slice(1);return r.readResource(a,u)}let[o,s]=_e(n,"?",2);return r.search(o,s)}var Hu=new Set(["userPractitionerId","userPractitionerRoleId","userPatientId","userRelatedPersonId"]);function qo(r,e,t){return t.replaceAll(/\{\{([^}]+)\}\}/g,(n,i)=>{if(i=i.trim(),Hu.has(i))return r.id;if(i.startsWith("context.")){let o=i.substring(8),s=Qu(e,o);if(Me(s))return s;if(typeof s=="number"||typeof s=="boolean")return String(s)}return n})}function Qu(r,e){let t=e.split("."),n=r;for(let i of t)if(n&&E(n)&&i in n)n=n[i];else return;return n}var O={CSS:"text/css",DICOM:"application/dicom",FAVICON:"image/vnd.microsoft.icon",FHIR_JSON:"application/fhir+json",FORM_URL_ENCODED:"application/x-www-form-urlencoded",HL7_V2:"x-application/hl7-v2+er7",HTML:"text/html",JAVASCRIPT:"text/javascript",JSON:"application/json",JSON_PATCH:"application/json-patch+json",JWT:"application/jwt",MULTIPART_FORM_DATA:"multipart/form-data",PNG:"image/png",SCIM_JSON:"application/scim+json",SVG:"image/svg+xml",TEXT:"text/plain",TYPESCRIPT:"text/typescript",PING:"x-application/ping",XML:"text/xml",CDA_XML:"application/cda+xml",OCTET_STREAM:"application/octet-stream"};var Ir=class{constructor(){c(this,"listeners");this.listeners={}}addEventListener(e,t){this.listeners[e]||(this.listeners[e]=[]),this.listeners[e].push(t)}removeEventListener(e,t){let n=this.listeners[e];if(n){for(let i=0;i<n.length;i++)if(n[i]===t){n.splice(i,1);return}}}dispatchEvent(e){let t=this.listeners[e.type];for(let n of t??g)n.call(this,e);return!e.defaultPrevented}removeAllListeners(){this.listeners={}}listenerCount(e){return this.listeners[e]?.length??0}},Y=class{constructor(){c(this,"emitter",new Ir)}dispatchEvent(e){this.emitter.dispatchEvent(e)}addEventListener(e,t){this.emitter.addEventListener(e,t)}removeEventListener(e,t){this.emitter.removeEventListener(e,t)}removeAllListeners(){this.emitter.removeAllListeners()}listenerCount(e){return this.emitter.listenerCount(e)}};var kr={"Patient-open":"Patient-open","Patient-close":"Patient-close","ImagingStudy-open":"ImagingStudy-open","ImagingStudy-close":"ImagingStudy-close","Encounter-open":"Encounter-open","Encounter-close":"Encounter-close","DiagnosticReport-open":"DiagnosticReport-open","DiagnosticReport-close":"DiagnosticReport-close","DiagnosticReport-select":"DiagnosticReport-select","DiagnosticReport-update":"DiagnosticReport-update",syncerror:"syncerror"},Wo=["Patient","Encounter","ImagingStudy","DiagnosticReport","OperationOutcome","Bundle"],Vr=["DiagnosticReport-update"];function ei(r){return Vr.includes(r)}function ti(r){if(Vr.includes(r))throw new f(v(`'context.version' is required for '${r}'.`))}var jo={"Patient-open":{patient:{resourceType:"Patient"},encounter:{resourceType:"Encounter",optional:!0}},"Patient-close":{patient:{resourceType:"Patient"},encounter:{resourceType:"Encounter",optional:!0}},"ImagingStudy-open":{study:{resourceType:"ImagingStudy"},encounter:{resourceType:"Encounter",optional:!0},patient:{resourceType:"Patient",optional:!0}},"ImagingStudy-close":{study:{resourceType:"ImagingStudy"},encounter:{resourceType:"Encounter",optional:!0},patient:{resourceType:"Patient",optional:!0}},"Encounter-open":{encounter:{resourceType:"Encounter"},patient:{resourceType:"Patient"}},"Encounter-close":{encounter:{resourceType:"Encounter"},patient:{resourceType:"Patient"}},"DiagnosticReport-open":{report:{resourceType:"DiagnosticReport"},encounter:{resourceType:"Encounter",optional:!0},study:{resourceType:"ImagingStudy",optional:!0,manyAllowed:!0},patient:{resourceType:"Patient"}},"DiagnosticReport-close":{report:{resourceType:"DiagnosticReport"},encounter:{resourceType:"Encounter",optional:!0},study:{resourceType:"ImagingStudy",optional:!0,manyAllowed:!0},patient:{resourceType:"Patient"}},"DiagnosticReport-select":{report:{resourceType:"DiagnosticReport",reference:!0},patient:{resourceType:"Patient",optional:!0,reference:!0},select:{resourceType:"*",reference:!0,manyAllowed:!0}},"DiagnosticReport-update":{report:{resourceType:"DiagnosticReport",reference:!0},patient:{resourceType:"Patient",optional:!0,reference:!0},updates:{resourceType:"Bundle"}},syncerror:{operationoutcome:{resourceType:"OperationOutcome"}}};function $o(r){return Wo.includes(r)}function ri(r){return!!r.endpoint}function Dr(r){if(!Bt(r))throw new f(v("subscriptionRequest must be an object conforming to SubscriptionRequest type."));let{channelType:e,mode:t,topic:n,events:i}=r,o={"hub.channel.type":e,"hub.mode":t,"hub.topic":n,"hub.events":i.join(",")};return ri(r)&&(o.endpoint=r.endpoint),new URLSearchParams(o).toString()}function Bt(r){if(typeof r!="object")return!1;let{channelType:e,mode:t,topic:n,events:i}=r;if(!(e&&t&&n&&i)||typeof n!="string"||typeof i!="object"||!Array.isArray(i)||i.length<1||e!=="websocket"||t!=="subscribe"&&t!=="unsubscribe")return!1;for(let o of i)if(!kr[o])return!1;return!(ri(r)&&!(typeof r.endpoint=="string"&&r.endpoint.startsWith("ws")))}function zu(r,e,t,n){if(typeof e!="object")throw new f(v(`context[${t}] is invalid. Context must contain a single valid FHIR resource! Resource is not an object.`));if(!(e.id&&typeof e.id=="string"))throw new f(v(`context[${t}] is invalid. Resource must contain a valid string ID.`));if(!e.resourceType)throw new f(v(`context[${t}] is invalid. Resource must contain a resource type. No resource type found.`));let i=n.resourceType;if(i!=="*"){if(!$o(e.resourceType))throw new f(v(`context[${t}] is invalid. Resource must contain a valid FHIRcast resource type. Resource type is not a known resource type.`));if(i&&e.resourceType!==i)throw new f(v(`context[${t}] is invalid. context[${t}] for the '${r}' event should contain resource of type ${i}.`))}}function Ju(r,e,t,n,i){if(i.set(e.key,(i.get(e.key)??0)+1),n.reference){if(!G(e.reference))throw new f(v(`context[${t}] is invalid. Expected key '${e.key}' to be a reference.`))}else zu(r,e.resource,t,n)}function Ku(r,e){let t=new Map,n=jo[r];for(let i=0;i<e.length;i++){let o=e[i].key;if(!n[o])throw new f(v(`Key '${o}' not found for event '${r}'. Make sure to add only valid keys.`));Ju(r,e[i],i,n[o],t)}for(let[i,o]of Object.entries(n)){if(!(o.optional||t.has(i)))throw new f(v(`Missing required key '${i}' on context for '${r}' event.`));if(!o.manyAllowed&&(t.get(i)??0)>1)throw new f(v(`${t.get(i)} context entries with key '${i}' found for the '${r}' event when schema only allows for 1.`))}}function Mr(r,e,t,n){if(!(r&&typeof r=="string"))throw new f(v("Must provide a topic."));if(!kr[e])throw new f(v(`Must provide a valid FHIRcast event name. Supported events: ${Object.keys(kr).join(", ")}`));if(typeof t!="object")throw new f(v("context must be a context object or array of context objects."));if(Vr.includes(e)&&!n)throw new f(v(`The '${e}' event must contain a 'context.versionId'.`));let i=Array.isArray(t)?t:[t];return Ku(e,i),{timestamp:new Date().toISOString(),id:se(),event:{"hub.topic":r,"hub.event":e,context:i,...n?{"context.versionId":n}:{}}}}var Ut=class extends Y{constructor(t){super();c(this,"subRequest");c(this,"websocket");if(this.subRequest=t,!t.endpoint)throw new f(v("Subscription request should contain an endpoint."));if(!Bt(t))throw new f(v("Subscription request failed validation."));let n=new WebSocket(t.endpoint);n.addEventListener("open",()=>{this.dispatchEvent({type:"connect"}),n.addEventListener("message",i=>{let o=JSON.parse(i.data);if(o["hub.topic"])return;let s=o;s.event["hub.event"]!=="heartbeat"&&(this.dispatchEvent({type:"message",payload:s}),n.send(JSON.stringify({id:o?.id,timestamp:new Date().toISOString()})))}),n.addEventListener("close",()=>{this.dispatchEvent({type:"disconnect"})})}),this.websocket=n}disconnect(){this.websocket.close()}};function Yu(r){return JSON.parse(Xn(r))}function ni(r){return r.split(".").length===3}function qt(r){let[e,t,n]=r.split(".");return Yu(t)}function ii(r){try{return typeof qt(r).login_id=="string"}catch{return!1}}function oi(r){try{let t=qt(r).exp;return typeof t=="number"?t*1e3:void 0}catch{return}}var Wt=class{constructor(e){c(this,"medplum");this.medplum=e}async get(e){return this.medplum.get(`keyvalue/v1/${e}`)}async set(e,t){await this.medplum.put(`keyvalue/v1/${e}`,t,O.TEXT)}async delete(e){await this.medplum.delete(`keyvalue/v1/${e}`)}};var Go;Go=Symbol.toStringTag;var U=class{constructor(e){c(this,Go,"ReadablePromise");c(this,"suspender");c(this,"status","pending");c(this,"response");c(this,"error");this.suspender=e.then(t=>(this.status="success",this.response=t,t),t=>{throw this.status="error",this.error=t,t})}isPending(){return this.status==="pending"}isOk(){return this.status==="success"}read(){switch(this.status){case"pending":throw this.suspender;case"error":throw this.error;default:return this.response}}then(e,t){return this.suspender.then(e,t)}catch(e){return this.suspender.catch(e)}finally(e){return this.suspender.finally(e)}};var rt=class{constructor(e,t=""){c(this,"storage");c(this,"prefix","");this.storage=e??globalThis.localStorage??new _r,this.prefix=t}makeKey(e){return this.prefix+e}clear(){this.storage===globalThis.localStorage&&this.prefix?Object.keys(this.storage).filter(e=>e.startsWith(this.prefix)).forEach(e=>{this.storage.removeItem(e)}):this.storage.clear()}getString(e){return this.storage.getItem(this.makeKey(e))??void 0}setString(e,t){t?this.storage.setItem(this.makeKey(e),t):this.storage.removeItem(this.makeKey(e))}getObject(e){let t=this.getString(e);return t?JSON.parse(t):void 0}setObject(e,t){this.setString(e,t?xt(t):void 0)}},_r=class{constructor(){c(this,"data");this.data=new Map}get length(){return this.data.size}clear(){this.data.clear()}getItem(e){return this.data.get(e)??null}setItem(e,t){t?this.data.set(e,t):this.data.delete(e)}removeItem(e){this.data.delete(e)}key(e){return Array.from(this.data.keys())[e]}},si=class extends rt{constructor(){super();c(this,"initialized");c(this,"initPromise");c(this,"initResolve",()=>{});this.initialized=!1,this.initPromise=new Promise(t=>{this.initResolve=t})}setInitialized(){this.initialized||(this.initResolve(),this.initialized=!0)}getInitPromise(){return this.initPromise}get isInitialized(){return this.initialized}};var nt={Event:typeof globalThis.Event<"u"?globalThis.Event:void 0,ErrorEvent:void 0,CloseEvent:void 0},Ho=!1;function Xu(){if(typeof globalThis.Event>"u")throw new Error("Unable to lazy init events for ReconnectingWebSocket. globalThis.Event is not defined yet");nt.Event=globalThis.Event,nt.ErrorEvent=class extends Event{constructor(t,n){super("error",n);c(this,"message");c(this,"error");this.message=t.message,this.error=t}},nt.CloseEvent=class extends Event{constructor(t=1e3,n="",i){super("close",i);c(this,"code");c(this,"reason");c(this,"wasClean",!0);this.code=t,this.reason=n}}}function zo(r,e){if(!r)throw new Error(e)}function Lr(r){return new r.constructor(r.type,r)}var Ue={maxReconnectionDelay:1e4,minReconnectionDelay:1e3+Math.random()*4e3,minUptime:5e3,reconnectionDelayGrowFactor:1.3,connectionTimeout:4e3,maxRetries:1/0,maxEnqueuedMessages:1/0,startClosed:!1,debug:!1},Qo=!1,jt=class r extends Y{constructor(t,n,i={}){Ho||(Xu(),Ho=!0);super();c(this,"_ws");c(this,"_retryCount",-1);c(this,"_uptimeTimeout");c(this,"_connectTimeout");c(this,"_shouldReconnect",!0);c(this,"_connectLock",!1);c(this,"_binaryType");c(this,"_closeCalled",!1);c(this,"_messageQueue",[]);c(this,"_debugLogger",console.log.bind(console));c(this,"_url");c(this,"_protocols");c(this,"_options");c(this,"onclose",null);c(this,"onerror",null);c(this,"onmessage",null);c(this,"onopen",null);c(this,"_handleOpen",t=>{this._debug("open event");let{minUptime:n=Ue.minUptime}=this._options;clearTimeout(this._connectTimeout),this._uptimeTimeout=setTimeout(()=>this._acceptOpen(),n),zo(this._ws,"WebSocket is not defined"),this._ws.binaryType=this._binaryType,this._messageQueue.forEach(i=>this._ws?.send(i)),this._messageQueue=[],this.onopen&&this.onopen(t),this.dispatchEvent(Lr(t))});c(this,"_handleMessage",t=>{this._debug("message event"),this.onmessage&&this.onmessage(t),this.dispatchEvent(Lr(t))});c(this,"_handleError",t=>{this._debug("error event",t.message),this._disconnect(void 0,t.message==="TIMEOUT"?"timeout":void 0),this.onerror&&this.onerror(t),this._debug("exec error listeners"),this.dispatchEvent(Lr(t)),this._connect()});c(this,"_handleClose",t=>{this._debug("close event"),this._clearTimeouts(),this._shouldReconnect&&this._connect(),this.onclose&&this.onclose(t),this.dispatchEvent(Lr(t))});this._url=t,this._protocols=n,this._options=i,this._options.startClosed&&(this._shouldReconnect=!1),this._options.binaryType?this._binaryType=this._options.binaryType:this._binaryType="blob",this._options.debugLogger&&(this._debugLogger=this._options.debugLogger),this._connect()}static get CONNECTING(){return 0}static get OPEN(){return 1}static get CLOSING(){return 2}static get CLOSED(){return 3}get CONNECTING(){return r.CONNECTING}get OPEN(){return r.OPEN}get CLOSING(){return r.CLOSING}get CLOSED(){return r.CLOSED}get binaryType(){return this._ws?this._ws.binaryType:this._binaryType}set binaryType(t){this._binaryType=t,this._ws&&(this._ws.binaryType=t)}get retryCount(){return Math.max(this._retryCount,0)}get bufferedAmount(){return this._messageQueue.reduce((n,i)=>(typeof i=="string"?n+=i.length:i instanceof Blob?n+=i.size:n+=i.byteLength,n),0)+(this._ws?.bufferedAmount??0)}get extensions(){return this._ws?.extensions??""}get protocol(){return this._ws?.protocol??""}get readyState(){return this._ws?this._ws.readyState:this._options.startClosed?r.CLOSED:r.CONNECTING}get url(){return this._ws?this._ws.url:""}get shouldReconnect(){return this._shouldReconnect}close(t=1e3,n){if(this._closeCalled=!0,this._shouldReconnect=!1,this._clearTimeouts(),!this._ws){this._debug("close enqueued: no ws instance");return}if(this._ws.readyState===this.CLOSED){this._debug("close: already closed");return}this._ws.close(t,n)}reconnect(t,n){this._shouldReconnect=!0,this._closeCalled=!1,this._retryCount=-1,!this._ws||this._ws.readyState===this.CLOSED?this._connect():(this._disconnect(t,n),this._connect())}send(t){if(this._ws?.readyState===this.OPEN)this._debug("send",t),this._ws.send(t);else{let{maxEnqueuedMessages:n=Ue.maxEnqueuedMessages}=this._options;this._messageQueue.length<n&&(this._debug("enqueue",t),this._messageQueue.push(t))}}_debug(...t){this._options.debug&&this._debugLogger("RWS>",...t)}_getNextDelay(){let{reconnectionDelayGrowFactor:t=Ue.reconnectionDelayGrowFactor,minReconnectionDelay:n=Ue.minReconnectionDelay,maxReconnectionDelay:i=Ue.maxReconnectionDelay}=this._options,o=0;return this._retryCount>0&&(o=n*Math.pow(t,this._retryCount-1),o>i&&(o=i)),this._debug("next delay",o),o}_wait(){return new Promise(t=>{setTimeout(t,this._getNextDelay())})}_connect(){if(this._connectLock||!this._shouldReconnect)return;this._connectLock=!0;let{maxRetries:t=Ue.maxRetries,connectionTimeout:n=Ue.connectionTimeout}=this._options;if(this._retryCount>=t){this._debug("max retries reached",this._retryCount,">=",t);return}this._retryCount++,this._debug("connect",this._retryCount),this._removeListeners(),this._wait().then(()=>{if(this._closeCalled){this._connectLock=!1;return}!this._options.WebSocket&&typeof WebSocket>"u"&&!Qo&&(console.error("\u203C\uFE0F No WebSocket implementation available. You should define options.WebSocket."),Qo=!0);let i=this._options.WebSocket||WebSocket;this._debug("connect",{url:this._url,protocols:this._protocols}),this._ws=this._protocols?new i(this._url,this._protocols):new i(this._url),this._ws.binaryType=this._binaryType,this._connectLock=!1,this._addListeners(),this._connectTimeout=setTimeout(()=>this._handleTimeout(),n)}).catch(i=>{this._connectLock=!1,this._handleError(new nt.ErrorEvent(Error(i.message),this))})}_handleTimeout(){this._debug("timeout event"),this._handleError(new nt.ErrorEvent(Error("TIMEOUT"),this))}_disconnect(t=1e3,n){if(this._clearTimeouts(),!!this._ws){this._removeListeners();try{this._ws.close(t,n),this._handleClose(new nt.CloseEvent(t,n,this))}catch{}}}_acceptOpen(){this._debug("accept open"),this._retryCount=0}_removeListeners(){this._ws&&(this._debug("removeListeners"),this._ws.removeEventListener("open",this._handleOpen),this._ws.removeEventListener("close",this._handleClose),this._ws.removeEventListener("message",this._handleMessage),this._ws.removeEventListener("error",this._handleError))}_addListeners(){this._ws&&(this._debug("addListeners"),this._ws.addEventListener("open",this._handleOpen),this._ws.addEventListener("close",this._handleClose),this._ws.addEventListener("message",this._handleMessage),this._ws.addEventListener("error",this._handleError))}_clearTimeouts(){clearTimeout(this._connectTimeout),clearTimeout(this._uptimeTimeout)}};var Zu=[WebSocket.CLOSING,WebSocket.CLOSED],it=class extends Y{constructor(...t){super();c(this,"criteria");this.criteria=new Set(t)}getCriteria(){return this.criteria}_addCriteria(t){this.criteria.add(t)}_removeCriteria(t){this.criteria.delete(t)}},ai=class{constructor(e,t){c(this,"criteria");c(this,"emitter");c(this,"refCount");c(this,"subscriptionProps");c(this,"subscriptionId");c(this,"token");c(this,"tokenExpiry");c(this,"state","idle");c(this,"generation",0);c(this,"lastUnrefTime");this.criteria=e,this.emitter=new it(e),this.refCount=1,this.subscriptionProps=t?{...t}:void 0}nextGeneration(){return++this.generation}},Gt=class{constructor(e,t,n){c(this,"medplum");c(this,"ws");c(this,"masterSubEmitter");c(this,"criteriaEntries");c(this,"criteriaEntriesBySubscriptionId");c(this,"wsClosed");c(this,"pingTimer");c(this,"tokenRefreshTimer");c(this,"pingIntervalMs");c(this,"waitingForPong",!1);c(this,"currentProfile");if(!(e instanceof Ht))throw new f(v("First arg of constructor should be a `MedplumClient`"));let i;try{i=new URL(t).toString()}catch{throw new f(v("Not a valid URL"))}let o=n?.ReconnectingWebSocket?new n.ReconnectingWebSocket(i,void 0,{debug:n?.debug,debugLogger:n?.debugLogger}):new jt(i,void 0,{debug:n?.debug,debugLogger:n?.debugLogger});this.medplum=e,this.ws=o,this.masterSubEmitter=new it,this.criteriaEntries=new Map,this.criteriaEntriesBySubscriptionId=new Map,this.wsClosed=!1,this.pingIntervalMs=n?.pingIntervalMs??5e3,this.currentProfile=e.getProfile(),this.setupListeners()}setupListeners(){let e=this.ws;e.addEventListener("message",t=>{try{let n=JSON.parse(t.data);if(n.type==="pong"){this.waitingForPong=!1;return}let i=n,o=i?.entry?.[0]?.resource;if(o.type==="heartbeat"){this.masterSubEmitter?.dispatchEvent({type:"heartbeat",payload:i});return}if(o.type==="handshake"){let a=be(o.subscription),u={type:"connect",payload:{subscriptionId:a}};this.masterSubEmitter?.dispatchEvent(u);let l=this.criteriaEntriesBySubscriptionId.get(a);if(!l){console.warn("Received handshake for criteria the SubscriptionManager is not listening for yet");return}(l.state==="connecting"||l.state==="refreshing")&&(l.state="active"),l.emitter.dispatchEvent({...u});return}this.masterSubEmitter?.dispatchEvent({type:"message",payload:i});let s=this.criteriaEntriesBySubscriptionId.get(be(o.subscription));if(!s){console.warn("Received notification for criteria the SubscriptionManager is not listening for");return}s.emitter.dispatchEvent({type:"message",payload:i})}catch(n){console.error(n);let i={type:"error",payload:n};this.masterSubEmitter?.dispatchEvent(i);for(let o of this.getAllCriteriaEmitters())o.dispatchEvent({...i})}}),e.addEventListener("error",()=>{let t={type:"error",payload:new f(cn(new Error("WebSocket error")))};this.masterSubEmitter?.dispatchEvent(t);for(let n of this.getAllCriteriaEmitters())n.dispatchEvent({...t})}),e.addEventListener("close",()=>{let t={type:"close"};this.masterSubEmitter?.dispatchEvent(t);for(let n of this.getAllCriteriaEmitters())n.dispatchEvent({...t});this.pingTimer&&(clearInterval(this.pingTimer),this.pingTimer=void 0,this.waitingForPong=!1),this.tokenRefreshTimer&&(clearInterval(this.tokenRefreshTimer),this.tokenRefreshTimer=void 0),this.wsClosed&&(this.criteriaEntries.clear(),this.criteriaEntriesBySubscriptionId.clear(),this.masterSubEmitter?.removeAllListeners())}),e.addEventListener("open",()=>{let t={type:"open"};this.masterSubEmitter?.dispatchEvent(t);for(let n of this.getAllCriteriaEmitters())n.dispatchEvent({...t});this.refreshAllSubscriptions().catch(console.error),this.pingTimer??=setInterval(()=>{this.waitingForPong?(this.waitingForPong=!1,e.reconnect()):(e.send(JSON.stringify({type:"ping"})),this.waitingForPong=!0),this.gcUnrefEntries()},this.pingIntervalMs),this.tokenRefreshTimer??=setInterval(()=>{this.checkTokenExpirations(),this.gcUnrefEntries()},6e4)}),this.medplum.addEventListener("change",()=>{let t=this.medplum.getProfile();this.currentProfile&&t===void 0?this.ws.close():t&&this.currentProfile?.id!==t.id&&this.ws.reconnect(),this.currentProfile=t})}sendBind(e){this.ws.send(JSON.stringify({type:"bind-with-token",payload:{token:e}}))}sendUnbind(e){this.ws.readyState===WebSocket.OPEN&&this.ws.send(JSON.stringify({type:"unbind-from-token",payload:{token:e}}))}emitError(e,t){let n={type:"error",payload:t};this.masterSubEmitter?.dispatchEvent(n),e.emitter.dispatchEvent({...n})}maybeEmitDisconnect(e){let{subscriptionId:t}=e;if(t){let n={type:"disconnect",payload:{subscriptionId:t}};this.masterSubEmitter?.dispatchEvent(n),e.emitter.dispatchEvent({...n})}else console.warn("Called disconnect for `CriteriaEntry` before `subscriptionId` was present.")}isStale(e,t){return this.isEntryGettingRemoved(e)||e.generation!==t}maybeGetCriteriaEntry(e,t){let n=this.criteriaEntries.get(e);if(n){if(!t)return n.bareCriteria;for(let i of n.criteriaWithProps)if(de(t,i.subscriptionProps))return i}}getAllCriteriaEmitters(){let e=[];for(let t of this.criteriaEntries.values())for(let n of $t(t))n.refCount>0&&e.push(n.emitter);return e}addCriteriaEntry(e){let{criteria:t,subscriptionProps:n}=e,i;this.criteriaEntries.has(t)?i=this.criteriaEntries.get(t):(i={criteriaWithProps:[]},this.criteriaEntries.set(t,i)),n?i.criteriaWithProps.push(e):i.bareCriteria=e}removeCriteriaEntry(e){e.state="removed",e.generation++;let{criteria:t,subscriptionProps:n,subscriptionId:i,token:o}=e;if(!this.criteriaEntries.has(t))return;let s=this.criteriaEntries.get(t);n?s.criteriaWithProps=s.criteriaWithProps.filter(a=>{let u=a.subscriptionProps;return!de(n,u)}):s.bareCriteria=void 0,!s.bareCriteria&&s.criteriaWithProps.length===0&&(this.criteriaEntries.delete(t),this.masterSubEmitter?._removeCriteria(t)),i&&this.criteriaEntriesBySubscriptionId.delete(i),o&&this.sendUnbind(o)}async subscribeToCriteria(e){this.wsClosed&&await this.reconnectIfNeeded(),this.ws.readyState===WebSocket.OPEN&&e.state==="idle"&&(e.state="connecting",await this.rebindCriteriaEntry(e))}async refreshAllSubscriptions(){this.criteriaEntriesBySubscriptionId.clear();let e=[],t=[];for(let n of this.criteriaEntries.values())for(let i of $t(n))i.refCount===0?t.push(i):e.push(i);for(let n of t)this.removeCriteriaEntry(n);for(let n of e)n.token&&this.sendUnbind(n.token),n.token=void 0,n.tokenExpiry=void 0,n.state="idle",n.generation++,await this.subscribeToCriteria(n)}async rebindCriteriaEntry(e){let t=e.nextGeneration();try{if(!e.subscriptionId){let a=await this.medplum.createResource({...e.subscriptionProps,resourceType:"Subscription",status:"active",reason:`WebSocket subscription for ${A(this.medplum.getProfile())}`,channel:{type:"websocket"},criteria:e.criteria});if(e.subscriptionId??=a.id,this.isStale(e,t))return}let{parameter:n}=await this.medplum.get(`fhir/R4/Subscription/${e.subscriptionId}/$get-ws-binding-token`,{cache:"no-cache"}),i=n?.find(a=>a.name==="token")?.valueString,o=n?.find(a=>a.name==="websocket-url")?.valueUrl,s=n?.find(a=>a.name==="expiration")?.valueDateTime;if(!i)throw new f(v("Failed to get token"));if(!o)throw new f(v("Failed to get URL from $get-ws-binding-token"));if(!s)throw new f(v("Failed to get expiration from $get-ws-binding-token"));if(this.isStale(e,t))return;e.token=i,e.tokenExpiry=new Date(s).getTime(),this.criteriaEntriesBySubscriptionId.set(e.subscriptionId,e),this.sendBind(i)}catch(n){console.error(Oe(n)),e.generation===t&&!this.isEntryGettingRemoved(e)&&(e.state=e.state==="refreshing"?"active":"idle"),this.emitError(e,n)}}checkTokenExpirations(){let e=Date.now();for(let t of this.criteriaEntries.values())for(let n of $t(t))n.refCount===0||!n.tokenExpiry||n.tokenExpiry-e<=3e5&&n.state==="active"&&this.ws.readyState===WebSocket.OPEN&&(n.state="refreshing",this.rebindCriteriaEntry(n).catch(i=>{this.masterSubEmitter?.dispatchEvent({type:"error",payload:i})}))}addCriteria(e,t){this.masterSubEmitter&&this.masterSubEmitter._addCriteria(e);let n=this.maybeGetCriteriaEntry(e,t);if(n)return n.refCount===0&&(n.lastUnrefTime=void 0,n.generation++,n.state!=="active"&&(n.state=n.token?"active":"idle")),n.refCount+=1,n.state==="idle"&&this.subscribeToCriteria(n).catch(console.error),n.emitter;let i=new ai(e,t);return this.addCriteriaEntry(i),this.subscribeToCriteria(i).catch(console.error),i.emitter}removeCriteria(e,t){let n=this.maybeGetCriteriaEntry(e,t);if(!n||this.isEntryGettingRemoved(n)){console.warn("Criteria not known to `SubscriptionManager`. Possibly called remove too many times.");return}n.refCount-=1,n.refCount===0&&(n.lastUnrefTime=Date.now(),n.generation++)}gcUnrefEntries(){let e=Date.now(),t=[];for(let n of this.criteriaEntries.values())for(let i of $t(n))i.refCount===0&&i.lastUnrefTime!==void 0&&e-i.lastUnrefTime>=1e4&&t.push(i);for(let n of t)this.maybeEmitDisconnect(n),this.removeCriteriaEntry(n);t.length>0&&this.criteriaEntries.size===0&&this.closeWebSocket()}isEntryGettingRemoved(e){return e.refCount===0||e.state==="removed"}getWebSocket(){return this.ws}closeWebSocket(){if(!this.wsClosed){if(this.ws.readyState===WebSocket.OPEN)for(let e of this.criteriaEntries.values())for(let t of $t(e))t.token&&this.sendUnbind(t.token);this.wsClosed=!0,this.ws.close()}}reconnectWebSocket(){this.ws.reconnect(),this.wsClosed=!1}getCriteriaCount(){return this.getAllCriteriaEmitters().length}getMasterEmitter(){return this.masterSubEmitter||(this.masterSubEmitter=new it(...Array.from(this.criteriaEntries.keys()))),this.masterSubEmitter}async reconnectIfNeeded(){Zu.includes(this.getWebSocket().readyState)&&await new Promise(e=>{let t=()=>{this.getWebSocket().removeEventListener("open",t),e()};this.getWebSocket().addEventListener("open",t),this.reconnectWebSocket()})}};function $t(r){return r.bareCriteria?[r.bareCriteria,...r.criteriaWithProps]:r.criteriaWithProps}var el=new Q(1e3);async function tl({resource:r,subscription:e,context:t,getPreviousResource:n,logger:i}){if(!rl(e,i))return i?.debug("Ignore subscription without recognized channel type"),!1;let o=e.criteria;if(!o)return i?.debug("Ignore rest hook missing criteria"),!1;let s=Ze(o);if(r.resourceType!==s.resourceType)return i?.debug(`Ignore rest hook for different resourceType (wanted "${s.resourceType}", received "${r.resourceType}")`),!1;if(!await Jo(e,r,n))return i?.debug("Ignore rest hook for criteria returning false"),!1;let u=le(e,"https://medplum.com/fhir/StructureDefinition/subscription-supported-interaction");if(u&&u.valueCode!==t.interaction)return i?.debug(`Ignore rest hook for different interaction (wanted "${u.valueCode}", received "${t.interaction}")`),!1;if(!Ft(r,s))return!1;let l=br(e.meta)??[],p=br(r.meta)??[];return l.length&&!l.some(y=>p.some(x=>x.reference===y.reference))?(i?.debug("Subscription suppressed due to mismatched accounts",{subscriptionId:e.id,resource:A(r)}),!1):!0}function rl(r,e){let t=r.channel?.type;return t==="rest-hook"?r.channel?.endpoint?!0:(e?.debug("Ignore rest-hook missing URL"),!1):t==="websocket"}async function Jo(r,e,t){let n=le(r,"https://medplum.com/fhir/StructureDefinition/fhir-path-criteria-expression");if(!n?.valueString)return!0;let i=await t(e),o={"%current":b(e),"%previous":b(i??{})};return P(n.valueString,[b(e)],o,el)?.[0]?.value===!0}var Fr="5.1.9-0b9a26b",nl="medplum-cli",Zo=O.FHIR_JSON+", */*; q=0.1",il="https://api.medplum.com/",ol=1e3,sl=6e4,al=0,cl=3e5,ul="Binary/",Ko={resourceType:"Device",id:"system",deviceName:[{type:"model-name",name:"System"}]},Be={ClientCredentials:"client_credentials",AuthorizationCode:"authorization_code",RefreshToken:"refresh_token",JwtBearer:"urn:ietf:params:oauth:grant-type:jwt-bearer",TokenExchange:"urn:ietf:params:oauth:grant-type:token-exchange"},es={AccessToken:"urn:ietf:params:oauth:token-type:access_token",RefreshToken:"urn:ietf:params:oauth:token-type:refresh_token",IdToken:"urn:ietf:params:oauth:token-type:id_token",Saml1Token:"urn:ietf:params:oauth:token-type:saml1",Saml2Token:"urn:ietf:params:oauth:token-type:saml2"},ll={ClientSecretBasic:"client_secret_basic",ClientSecretPost:"client_secret_post",ClientSecretJwt:"client_secret_jwt",PrivateKeyJwt:"private_key_jwt",None:"none"},ts={JwtBearer:"urn:ietf:params:oauth:client-assertion-type:jwt-bearer"},dl={ES256:"ES256",ES384:"ES384",ES512:"ES512",HS256:"HS256",RS256:"RS256",RS384:"RS384",RS512:"RS512"},Ht=class extends Y{constructor(t){super();c(this,"options");c(this,"fetch");c(this,"createPdfImpl");c(this,"storage");c(this,"requestCache");c(this,"cacheTime");c(this,"baseUrl");c(this,"fhirBaseUrl");c(this,"authorizeUrl");c(this,"tokenUrl");c(this,"logoutUrl");c(this,"fhircastHubUrl");c(this,"cdsServicesUrl");c(this,"defaultHeaders");c(this,"onUnauthenticated");c(this,"autoBatchTime");c(this,"autoBatchQueue");c(this,"maxRetries");c(this,"maxRetryTime");c(this,"refreshGracePeriod");c(this,"subscriptionManager");c(this,"medplumServer");c(this,"clientId");c(this,"clientSecret");c(this,"credentialsInHeader");c(this,"autoBatchTimerId");c(this,"accessToken");c(this,"accessTokenExpires");c(this,"refreshToken");c(this,"refreshPromise");c(this,"profilePromise");c(this,"sessionDetails");c(this,"currentRateLimits");c(this,"basicAuth");c(this,"initPromise");c(this,"initComplete",!0);c(this,"keyValueClient");c(this,"logLevel");if(t?.baseUrl&&!t.baseUrl.startsWith("http"))throw new Error("Base URL must start with http or https");this.options=t??{},this.fetch=t?.fetch??pl(),this.storage=t?.storage??new rt(void 0,t?.storagePrefix),this.createPdfImpl=t?.createPdf,this.baseUrl=Rr(t?.baseUrl??il),this.fhirBaseUrl=F(this.baseUrl,t?.fhirUrlPath??"fhir/R4"),this.authorizeUrl=F(this.baseUrl,t?.authorizeUrl??"oauth2/authorize"),this.tokenUrl=F(this.baseUrl,t?.tokenUrl??"oauth2/token"),this.logoutUrl=F(this.baseUrl,t?.logoutUrl??"oauth2/logout"),this.fhircastHubUrl=F(this.baseUrl,t?.fhircastHubUrl??"fhircast/STU3"),this.cdsServicesUrl=F(this.baseUrl,t?.cdsServicesUrl??"cds-services"),this.clientId=t?.clientId??"",this.clientSecret=t?.clientSecret??"",this.credentialsInHeader=t?.authCredentialsMethod==="header",this.defaultHeaders=t?.defaultHeaders??{},this.onUnauthenticated=t?.onUnauthenticated,this.refreshGracePeriod=t?.refreshGracePeriod??cl,this.logLevel=this.initializeLogLevel(t),this.maxRetries=t?.maxRetries??2,this.maxRetryTime=t?.maxRetryTime??2e3,this.cacheTime=t?.cacheTime??(j()?sl:al),this.cacheTime>0?this.requestCache=new Q(t?.resourceCacheSize??ol):this.requestCache=void 0,t?.autoBatchTime?(this.autoBatchTime=t.autoBatchTime,this.autoBatchQueue=[]):(this.autoBatchTime=0,this.autoBatchQueue=void 0),t?.accessToken&&this.setAccessToken(t.accessToken),this.storage.getInitPromise===void 0?(t?.accessToken||this.attemptResumeActiveLogin().catch(console.error),this.initPromise=Promise.resolve(),this.dispatchEvent({type:"storageInitialized"})):(this.initComplete=!1,this.initPromise=this.storage.getInitPromise(),this.initPromise.then(()=>{t?.accessToken||this.attemptResumeActiveLogin().catch(console.error),this.initComplete=!0,this.dispatchEvent({type:"storageInitialized"})}).catch(n=>{console.error(n),this.initComplete=!0,this.dispatchEvent({type:"storageInitFailed",payload:{error:n}})})),this.setupStorageListener()}get isInitialized(){return this.initComplete}getInitPromise(){return this.initPromise}initializeLogLevel(t){return t?.logLevel?t.logLevel:t?.verbose!==void 0&&t.verbose?"verbose":"none"}async attemptResumeActiveLogin(){let t=this.getActiveLogin();t&&(this.setAccessToken(t.accessToken,t.refreshToken),await this.refreshProfile())}getBaseUrl(){return this.baseUrl}getAuthorizeUrl(){return this.authorizeUrl}getTokenUrl(){return this.tokenUrl}getLogoutUrl(){return this.logoutUrl}getFhircastHubUrl(){return this.fhircastHubUrl}getCdsServicesUrl(){return this.cdsServicesUrl}getDefaultHeaders(){return this.defaultHeaders}clear(){this.storage.clear(),j()&&sessionStorage.clear(),this.clearActiveLogin()}clearActiveLogin(){this.storage.setString("activeLogin",void 0),this.requestCache?.clear(),this.accessToken=void 0,this.refreshToken=void 0,this.refreshPromise=void 0,this.accessTokenExpires=void 0,this.sessionDetails=void 0,this.medplumServer=void 0,this.dispatchEvent({type:"change"})}invalidateUrl(t){t=t.toString(),this.requestCache?.delete(t)}invalidateAll(){this.requestCache?.clear()}invalidateSearches(t){let n=F(this.fhirBaseUrl,t);for(let i of this.requestCache?.keys()??g)(i.endsWith(n)||i.includes(n+"?"))&&this.requestCache?.delete(i)}get(t,n={}){t=t.toString();let i=this.getCacheEntry(t,n);if(i)return i.value;let o;t.startsWith(this.fhirBaseUrl)&&this.autoBatchQueue&&!n.disableAutoBatch?o=new Promise((a,u)=>{this.autoBatchQueue.push({method:"GET",url:t.replace(this.fhirBaseUrl,""),options:n,resolve:a,reject:u}),this.autoBatchTimerId||(this.autoBatchTimerId=setTimeout(()=>this.executeAutoBatch(),this.autoBatchTime))}):o=this.request("GET",t,n);let s=new U(o);return this.setCacheEntry(t,s,n),s}post(t,n,i,o={}){return t=t.toString(),this.setRequestBody(o,n),i&&this.setRequestContentType(o,i),this.invalidateUrl(t),this.request("POST",t,o)}put(t,n,i,o={}){return t=t.toString(),this.setRequestBody(o,n),i&&this.setRequestContentType(o,i),this.invalidateUrl(t),this.request("PUT",t,o)}patch(t,n,i={}){return t=t.toString(),this.setRequestBody(i,n),this.setRequestContentType(i,O.JSON_PATCH),this.invalidateUrl(t),this.request("PATCH",t,i)}delete(t,n){return t=t.toString(),this.invalidateUrl(t),this.request("DELETE",t,n)}async startNewUser(t,n){let{codeChallengeMethod:i,codeChallenge:o}=await this.startPkce();return this.post("auth/newuser",{...t,clientId:t.clientId??this.clientId,codeChallengeMethod:i,codeChallenge:o},void 0,n)}async startNewProject(t,n){return this.post("auth/newproject",t,void 0,n)}async startNewPatient(t,n){return this.post("auth/newpatient",t,void 0,n)}async startLogin(t,n){return this.post("auth/login",{...await this.ensureCodeChallenge(t),clientId:t.clientId??this.clientId,scope:t.scope},void 0,n)}async startGoogleLogin(t,n){return this.post("auth/google",{...await this.ensureCodeChallenge(t),clientId:t.clientId??this.clientId,scope:t.scope},void 0,n)}async ensureCodeChallenge(t){return t.codeChallenge?t:{...t,...await this.startPkce()}}async signOut(){await this.post(this.logoutUrl,{}),this.clear()}async signInWithRedirect(t){let i=new URLSearchParams(oe.getSearch()).get("code");if(!i){await this.requestAuthorization(t);return}return this.processCode(i)}signOutWithRedirect(){oe.assign(this.logoutUrl)}async signInWithExternalAuth(t,n,i,o,s=!0){let a=o;s&&(a=await this.ensureCodeChallenge(o)),oe.assign(this.getExternalAuthRedirectUri(t,n,i,a,s))}async exchangeExternalAccessToken(t,n,i){if(n=n??this.clientId,!n)throw new Error("MedplumClient is missing clientId");let o={grant_type:Be.TokenExchange,subject_token_type:es.AccessToken,client_id:n,subject_token:t};return i&&(o.membership_id=i),this.fetchTokens(o)}getExternalAuthRedirectUri(t,n,i,o,s=!0){let a=new URL(t);if(a.searchParams.set("response_type","code"),a.searchParams.set("client_id",n),a.searchParams.set("redirect_uri",i),a.searchParams.set("scope",o.scope??"openid profile email"),a.searchParams.set("state",JSON.stringify(o)),s){let{codeChallenge:u,codeChallengeMethod:l}=o;if(!l)throw new Error("`LoginRequest` for external auth must include a `codeChallengeMethod`.");if(!u)throw new Error("`LoginRequest` for external auth must include a `codeChallenge`.");a.searchParams.set("code_challenge_method",l),a.searchParams.set("code_challenge",u)}return a.toString()}fhirUrl(...t){return new URL(F(this.fhirBaseUrl,t.join("/")))}fhirSearchUrl(t,n){let i=this.fhirUrl(t);return n&&(i.search=qn(n)),i}search(t,n,i){let o=this.fhirSearchUrl(t,n),s="search-"+o.toString(),a=this.getCacheEntry(s,i);if(a)return a.value;let u=this.getBundle(o,i);return this.setCacheEntry(s,u,i),u}searchOne(t,n,i){let o=this.fhirSearchUrl(t,n);o.searchParams.set("_count","1"),o.searchParams.sort();let s="searchOne-"+o.toString(),a=this.getCacheEntry(s,i);if(a)return a.value;let u=new U(this.search(t,o.searchParams,i).then(l=>l.entry?.[0]?.resource));return this.setCacheEntry(s,u,i),u}searchResources(t,n,i){let s="searchResources-"+this.fhirSearchUrl(t,n).toString(),a=this.getCacheEntry(s,i);if(a)return a.value;let u=new U(this.search(t,n,i).then(Xo));return this.setCacheEntry(s,u,i),u}async*searchResourcePages(t,n,i){let o=this.fhirSearchUrl(t,n);for(;o;){let s=new URL(o).searchParams;s.has("_count")||s.set("_count","1000");let a=await this.search(t,s,i),u=a.link?.find(l=>l.relation==="next");if(!a.entry?.length&&!u)break;yield Xo(a),o=u?.url?new URL(u.url):void 0}}valueSetExpand(t,n){let i=this.fhirUrl("ValueSet","$expand");return i.search=new URLSearchParams(t).toString(),this.get(i.toString(),n)}getCached(t,n){let i=this.requestCache?.get(this.fhirUrl(t,n).toString())?.value;return i?.isOk()?i.read():void 0}getCachedReference(t){let n=t.reference;if(!n)return;if(n==="system")return Ko;let[i,o]=n.split("/");if(!(!i||!o))return this.getCached(i,o)}readResource(t,n,i){if(!n)throw new Error('The "id" parameter cannot be null, undefined, or an empty string.');return this.get(this.fhirUrl(t,n),i)}readReference(t,n){let i=t.reference;if(!i)return new U(Promise.reject(new Error("Missing reference")));if(i==="system")return new U(Promise.resolve(Ko));let[o,s]=i.split("/");return!o||!s?new U(Promise.reject(new Error("Invalid reference"))):this.readResource(o,s,n)}readCanonical(t,n,i){return Array.isArray(t)?this.searchOne("",{_type:t.join(","),url:n},i):this.searchOne(t,"url="+n,i)}requestSchema(t,n){if(gn(t))return Promise.resolve();let i=t+"-requestSchema",o=this.getCacheEntry(i,void 0);if(o)return o.value;let s=new U((async()=>{let a=`{
|
|
5
5
|
StructureDefinitionList(_filter: "name eq ${t}") {
|
|
6
6
|
resourceType,
|
|
7
7
|
name,
|
|
@@ -41,7 +41,7 @@
|
|
|
41
41
|
expression,
|
|
42
42
|
target
|
|
43
43
|
}
|
|
44
|
-
}`.replaceAll(/\s+/g," "),u=await this.graphql(a);ur(u.data.StructureDefinitionList);for(let l of u.data.SearchParameterList)Pr(l)})());return this.setCacheEntry(i,s,n),s}requestProfileSchema(t,n){if(!n?.expandProfile&&xn(t))return Promise.resolve();let i=t+"-requestSchema"+(n?.expandProfile?"-nested":""),o=this.getCacheEntry(i,void 0);if(o)return o.value;let s=new U((async()=>{if(n?.expandProfile){let a=this.fhirUrl("StructureDefinition","$expand-profile");a.search=new URLSearchParams({url:t}).toString();let u=await this.post(a.toString(),{});ur(u)}else{let a=await this.searchOne("StructureDefinition",{url:t,_sort:"-_lastUpdated"});if(!a){console.warn(`No StructureDefinition found for ${t}!`);return}lr(a)}})());return this.setCacheEntry(i,s,n),s}readHistory(t,n,i,o){let s=this.fhirUrl(t,n,"_history");return i?.count&&s.searchParams.set("_count",i.count.toString()),i?.offset&&s.searchParams.set("_offset",i.offset.toString()),this.get(s.toString(),o)}readVersion(t,n,i,o){return this.get(this.fhirUrl(t,n,"_history",i),o)}readPatientEverything(t,n){return this.getBundle(this.fhirUrl("Patient",t,"$everything"),n)}readPatientSummary(t,n){return this.getBundle(this.fhirUrl("Patient",t,"$summary"),n)}createResource(t,n){if(!t.resourceType)throw new Error("Missing resourceType");return this.invalidateSearches(t.resourceType),this.post(this.fhirUrl(t.resourceType),t,void 0,n)}async createResourceIfNoneExist(t,n,i={}){let o=this.fhirUrl(t.resourceType);this.setRequestHeader(i,"If-None-Exist",n);let s=await this.post(o,t,void 0,i);return this.cacheResource(s,i),this.invalidateUrl(this.fhirUrl(t.resourceType,t.id,"_history")),this.invalidateSearches(t.resourceType),s}async upsertResource(t,n,i){let o=this.fhirSearchUrl(t.resourceType,n),s=await this.put(o,t,void 0,i);return s||(s=t),this.cacheResource(s,i),this.invalidateUrl(this.fhirUrl(t.resourceType,t.id,"_history")),this.invalidateSearches(t.resourceType),s}async createAttachment(t,n,i,o,s){let a=ci(t,n,i,o);if(a.contentType===O.XML){let p=a.data,y;p instanceof Blob?y=await new Promise((x,V)=>{let Z=new FileReader;Z.onload=()=>{if(!Z.result){V(new Error("Failed to load file"));return}x(Z.result)},Z.readAsText(p,"utf-8")}):ArrayBuffer.isView(p)?y=new TextDecoder().decode(p):y=p,y.includes("<ClinicalDocument")&&y.includes("urn:hl7-org:v3")&&(a={...a,contentType:O.CDA_XML})}let u=s??(typeof n=="object"?n:{}),l=await this.createBinary(a,u);return{contentType:a.contentType,url:l.url,title:a.filename}}createBinary(t,n,i,o,s){let a=ci(t,n,i,o),u=s??(typeof n=="object"?n:{}),{data:l,contentType:p,filename:y,securityContext:x,onProgress:V}=a,Z=this.fhirUrl("Binary");return y&&Z.searchParams.set("_filename",y),x?.reference&&this.setRequestHeader(u,"X-Security-Context",x.reference),V?this.uploadwithProgress(Z,l,p,V,u):this.post(Z,l,p,u)}uploadwithProgress(t,n,i,o,s){return new Promise((a,u)=>{let l=new XMLHttpRequest,p=()=>l.abort();s?.signal?.addEventListener("abort",p);let y=x=>{s?.signal?.removeEventListener("abort",p),x instanceof Error?u(x):a(x)};if(l.responseType="json",l.onabort=()=>y(new DOMException("Request aborted","AbortError")),l.onerror=()=>y(new Error("Request error")),o&&(l.upload.onprogress=x=>o(x),l.upload.onload=x=>o(x)),l.onload=()=>{l.status>=200&&l.status<300?y(l.response):y(new f(ut(l.response||l.statusText)))},l.open("POST",t),l.withCredentials=!0,l.setRequestHeader("Authorization","Bearer "+this.accessToken),l.setRequestHeader("Cache-Control","no-cache, no-store, max-age=0"),l.setRequestHeader("Content-Type",i),this.options.extendedMode!==!1&&l.setRequestHeader("X-Medplum","extended"),s?.headers){let x=s.headers;for(let[V,Z]of Object.entries(x))l.setRequestHeader(V,Z)}l.send(n)})}async createPdf(t,n,i,o){if(!this.createPdfImpl)throw new Error("PDF creation not enabled");let s=rs(t,n,i,o),a=typeof n=="object"?n:{},{docDefinition:u,tableLayouts:l,fonts:p,...y}=s,x=await this.createPdfImpl(u,l,p),V={...y,data:x,contentType:"application/pdf"};return this.createBinary(V,a)}createComment(t,n,i){let o=this.getProfile(),s,a;return t.resourceType==="Encounter"&&(s=Te(t),a=t.subject),t.resourceType==="ServiceRequest"&&(s=t.encounter,a=t.subject),t.resourceType==="Patient"&&(a=Te(t)),this.createResource({resourceType:"Communication",status:"completed",basedOn:[Te(t)],encounter:s,subject:a,sender:o?Te(o):void 0,sent:new Date().toISOString(),payload:[{contentString:n}]},i)}async updateResource(t,n){if(!t.resourceType)throw new Error("Missing resourceType");if(!t.id)throw new Error("Missing id");let i=await this.put(this.fhirUrl(t.resourceType,t.id),t,void 0,n);return i||(i=t),this.cacheResource(i,n),this.invalidateUrl(this.fhirUrl(t.resourceType,t.id,"_history")),this.invalidateSearches(t.resourceType),i}async patchResource(t,n,i,o){let s=await this.patch(this.fhirUrl(t,n),i,o);return this.cacheResource(s,o),this.invalidateUrl(this.fhirUrl(t,n,"_history")),this.invalidateSearches(t),s}deleteResource(t,n,i){return this.deleteCacheEntry(this.fhirUrl(t,n).toString()),this.invalidateSearches(t),this.delete(this.fhirUrl(t,n),i)}validateResource(t,n){return this.post(this.fhirUrl(t.resourceType,"$validate"),t,void 0,n)}executeBot(t,n,i,o){let s;if(typeof t=="string"){let a=t;s=this.fhirUrl("Bot",a,"$execute")}else{let a=t;s=this.fhirUrl("Bot","$execute"),s.searchParams.set("identifier",a.system+"|"+a.value)}return this.post(s,n,i,o)}executeBatch(t,n){return this.post(this.fhirBaseUrl,t,void 0,n)}sendEmail(t,n){return this.post("email/v1/send",t,O.JSON,n)}graphql(t,n,i,o){return this.post(this.fhirUrl("$graphql"),{query:t,operationName:n,variables:i},O.JSON,o)}readResourceGraph(t,n,i,o){return this.get(`${this.fhirUrl(t,n)}/$graph?graph=${i}`,o)}pushToAgent(t,n,i,o,s,a){let{waitTimeout:u,returnAck:l,...p}=a??{};return this.post(this.fhirUrl("Agent",be(t),"$push"),{destination:typeof n=="string"?n:A(n),body:i,contentType:o,waitForResponse:s,...u!==void 0?{waitTimeout:u}:void 0,...l!==void 0?{returnAck:l}:void 0},O.FHIR_JSON,p)}getCdsServices(t){return this.get(this.cdsServicesUrl,t)}callCdsService(t,n,i){return this.post(F(this.cdsServicesUrl,t),n,O.JSON,i)}getActiveLogin(){return this.storage.getObject("activeLogin")}async setActiveLogin(t){(!this.sessionDetails?.profile||A(this.sessionDetails.profile)!==t.profile?.reference)&&this.clearActiveLogin(),this.setAccessToken(t.accessToken,t.refreshToken),this.storage.setObject("activeLogin",t),this.addLogin(t),this.refreshPromise=void 0,await this.refreshProfile()}getAccessToken(){return this.accessToken}isAuthenticated(t){return this.accessTokenExpires!==void 0&&Date.now()<this.accessTokenExpires-(t??this.refreshGracePeriod)}setAccessToken(t,n){this.accessToken=t,this.refreshToken=n,this.accessTokenExpires=oi(t),this.medplumServer=ii(t)}getLogins(){return this.storage.getObject("logins")??[]}addLogin(t){let n=this.getLogins().filter(i=>i.profile?.reference!==t.profile?.reference);n.push(t),this.storage.setObject("logins",n)}async refreshProfile(){if(this.medplumServer)return this.profilePromise=new Promise((t,n)=>{this.get("auth/me",{cache:"no-cache"}).then(i=>{this.profilePromise=void 0;let o=this.sessionDetails?.profile?.id!==i.profile.id;this.sessionDetails=i,o&&this.dispatchEvent({type:"change"}),t(i.profile),this.dispatchEvent({type:"profileRefreshed"})}).catch(n)}),this.dispatchEvent({type:"profileRefreshing"}),this.profilePromise}isLoading(){return!this.isInitialized||!!this.profilePromise&&!this.sessionDetails?.profile}isSuperAdmin(){return!!this.sessionDetails?.project.superAdmin}isProjectAdmin(){return!!this.sessionDetails?.membership.admin}getProject(){return this.sessionDetails?.project}getProjectMembership(){return this.sessionDetails?.membership}getProfile(){return this.sessionDetails?.profile}async getProfileAsync(){return this.profilePromise?this.profilePromise:this.sessionDetails?this.sessionDetails.profile:this.refreshProfile()}getUserConfiguration(){return this.sessionDetails?.config}getAccessPolicy(){return this.sessionDetails?.accessPolicy}async download(t,n={}){return(await this.downloadResponse(t,n)).blob()}async downloadResponse(t,n={}){this.refreshPromise&&await this.refreshPromise;let i=t.toString();i.startsWith(ul)&&(t=this.fhirUrl(i));let o=n.headers;return o||(o={},n.headers=o),o.Accept||(o.Accept="*/*"),this.addFetchOptionsDefaults(n),this.fetchWithRetry(t.toString(),n)}async createMedia(t,n){let{additionalFields:i,...o}=t,s=await this.createResource({resourceType:"Media",status:"preparation",content:{contentType:t.contentType},...i});o.securityContext||(o.securityContext=Te(s));let a=await this.createAttachment(o,n);return this.updateResource({...s,status:"completed",content:a})}async uploadMedia(t,n,i,o,s){return this.createMedia({data:t,contentType:n,filename:i,additionalFields:o},s)}async createDocumentReference(t,n){let{additionalFields:i,...o}=t,s=await this.createResource({resourceType:"DocumentReference",status:"current",content:[{attachment:{contentType:t.contentType}}],...i});o.securityContext||(o.securityContext=Te(s));let a=await this.createAttachment(o,n);return this.updateResource({...s,content:[{attachment:a}]})}async bulkExport(t="",n,i,o){let s=t&&`${t}/`,a=this.fhirUrl(`${s}$export`);return n&&a.searchParams.set("_type",n),i&&a.searchParams.set("_since",i),this.startAsyncRequest(a.toString(),o)}async startAsyncRequest(t,n={}){this.addFetchOptionsDefaults(n);let i=n.headers;return i.Prefer="respond-async",this.request("POST",t,n)}get keyValue(){return this.keyValueClient||(this.keyValueClient=new Wt(this)),this.keyValueClient}getBundle(t,n){return new U((async()=>{let i=await this.get(t,n);for(let o of i.entry??g)this.cacheResource(o.resource,n);return i})())}isCacheEnabled(t){return!!this.requestCache&&!this.getRequestHeader(t,"x-medplum-on-behalf-of")}getCacheEntry(t,n){if(!this.isCacheEnabled(n)||n?.cache==="no-cache"||n?.cache==="reload")return;let i=this.requestCache.get(t);if(!(!i||i.requestTime+this.cacheTime<Date.now()))return i}setCacheEntry(t,n,i){this.isCacheEnabled(i)&&(this.requestCache.set(t,{requestTime:Date.now(),value:n}),i?.signal&&i.signal.addEventListener("abort",()=>{this.requestCache.delete(t)}))}cacheResource(t,n){t?.id&&!t.meta?.tag?.some(i=>i.code==="SUBSETTED")&&this.setCacheEntry(this.fhirUrl(t.resourceType,t.id).toString(),new U(Promise.resolve(t)),n)}deleteCacheEntry(t){this.requestCache&&this.requestCache.delete(t)}async request(t,n,i={},o={}){await this.refreshIfExpired(),i.method=t,this.addFetchOptionsDefaults(i);let s=await this.fetchWithRetry(n,i);if(s.status===401)return this.handleUnauthenticated(t,n,i);if(s.status===204||s.status===304)return;let u=s.headers.get("content-type")?.includes("json");if(s.status===404&&!u)throw new f(sn);let l=await this.parseBody(s,u);if(s.status===200&&i.followRedirectOnOk||s.status===201&&i.followRedirectOnCreated){let p=await Yo(s,l);if(p)return this.request("GET",p,{...i,body:void 0})}if(s.status===202&&i.pollStatusOnAccepted){let y=await Yo(s,l)??o.statusUrl;if(y)return this.pollStatus(y,i,o)}if(s.status>=400)throw new f(ut(l));return l}async parseBody(t,n){let i;if(t.headers.get("content-length")!=="0"){if(n)try{i=await t.json()}catch(o){throw console.error("Error parsing response",t.status,o),o}else i=await t.text();return i}}async fetchWithRetry(t,n){t.startsWith("http")||(t=F(this.baseUrl,t));let i=n?.maxRetries??this.maxRetries;for(let o=0;o<=i;o++)try{this.logLevel!=="none"&&this.logRequest(t,n);let s=await this.fetch(t,n);if(this.logLevel!=="none"&&this.logResponse(s),this.setCurrentRateLimit(s),o>=i||!hl(s))return s;let a=this.getRetryDelay(o),u=n.maxRetryTime??this.maxRetryTime;if(a>u)return s;await Er(a,{signal:n.signal})}catch(s){if(s.message==="Failed to fetch"&&o===0&&this.dispatchEvent({type:"offline"}),s.name==="AbortError"||o===i)throw s}throw new Error("Unreachable")}logRequest(t,n){if(console.log(`> ${n.method} ${t}`),this.logLevel==="verbose"&&n.headers){let i=n.headers;for(let o of vt(Object.keys(i)))console.log(`> ${o}: ${i[o]}`)}}logResponse(t){console.log(`< ${t.status} ${t.statusText}`),this.logLevel==="verbose"&&t.headers&&t.headers.forEach((n,i)=>console.log(`< ${i}: ${n}`))}setCurrentRateLimit(t){if(!t?.headers||typeof t.headers.get!="function")return;let n=t.headers.get("ratelimit");n&&(this.currentRateLimits=n)}rateLimitStatus(){if(!this.currentRateLimits)return[];let t=this.currentRateLimits;return t.split(",").map(n=>{let i=n.split(";").map(p=>p.trim());if(i.length!==3)throw new Error("Could not parse RateLimit header: "+t);let o=i[0].substring(1,i[0].length-1),s=i.find(p=>p.startsWith("r="))?.substring(2),a=s?Number.parseInt(s,10):Number.NaN,u=i.find(p=>p.startsWith("t="))?.substring(2),l=u?Number.parseInt(u,10):Number.NaN;if(!o||Number.isNaN(a)||Number.isNaN(l))throw new Error("Could not parse RateLimit header: "+t);return{name:o,remainingUnits:a,secondsUntilReset:l,resetsAfter:Math.ceil((Date.now()+1e3*l)/1e3)}})}getRetryDelay(t){let n=this.rateLimitStatus(),i=500*Math.pow(1.5,t);for(let o of n)o.remainingUnits||(i=Math.max(i,o.secondsUntilReset*1e3));return i}async pollStatus(t,n,i){let o={...n,method:"GET",body:void 0,redirect:"follow"};if(i.pollCount===void 0)n.headers&&typeof n.headers=="object"&&"Prefer"in n.headers&&(o.headers={...n.headers},delete o.headers.Prefer),i.statusUrl=t,i.pollCount=1;else{let s=n.pollStatusPeriod??1e3;await Er(s,{signal:n.signal}),i.pollCount++}return this.request("GET",t,o,i)}async executeAutoBatch(){if(this.autoBatchQueue===void 0)return;let t=[...this.autoBatchQueue];if(this.autoBatchQueue.length=0,this.autoBatchTimerId=void 0,t.length===1){let o=t[0];try{o.resolve(await this.request(o.method,F(this.fhirBaseUrl,o.url),o.options))}catch(s){o.reject(new f(ut(s)))}return}let n={resourceType:"Bundle",type:"batch",entry:t.map(o=>({request:{method:o.method,url:o.url},resource:o.options.body?JSON.parse(o.options.body):void 0}))},i=await this.post(this.fhirBaseUrl,n);for(let o=0;o<t.length;o++){let s=t[o],a=i.entry?.[o];a?.response?.outcome&&!sr(a.response.outcome)?s.reject(new f(a.response.outcome)):s.resolve(a?.resource)}}addFetchOptionsDefaults(t){Object.entries(this.defaultHeaders).forEach(([n,i])=>{this.setRequestHeader(t,n,i)}),this.setRequestHeader(t,"Accept",Zo,!0),this.options.extendedMode!==!1&&this.setRequestHeader(t,"X-Medplum","extended"),t.body&&this.setRequestHeader(t,"Content-Type",O.FHIR_JSON,!0),this.accessToken?this.setRequestHeader(t,"Authorization","Bearer "+this.accessToken):this.basicAuth&&this.setRequestHeader(t,"Authorization","Basic "+this.basicAuth),t.cache||(t.cache="no-cache"),t.credentials||(t.credentials="include")}setRequestContentType(t,n){this.setRequestHeader(t,"Content-Type",n)}getRequestHeader(t,n){let i=t?.headers;if(i)if(Array.isArray(i)){let o=i.find(([s])=>s.toLowerCase()===n.toLowerCase());return o?o[1]:void 0}else{if(i instanceof Headers)return i.get(n)??void 0;if(E(i))return i[n]??void 0}else return}setRequestHeader(t,n,i,o=!1){let s=t.headers;s?Array.isArray(s)?(!o||!s.some(([a])=>a.toLowerCase()===n.toLowerCase()))&&s.push([n,i]):s instanceof Headers?(!o||!s.has(n))&&s.set(n,i):E(s)&&(!o||!s[n])&&(s[n]=i):t.headers={[n]:i}}setRequestBody(t,n){typeof n=="string"||typeof Blob<"u"&&(n instanceof Blob||n?.constructor.name==="Blob")||typeof File<"u"&&(n instanceof File||n?.constructor.name==="File")||typeof Uint8Array<"u"&&(n instanceof Uint8Array||n?.constructor.name==="Uint8Array")?t.body=n:n&&(t.body=JSON.stringify(n))}async handleUnauthenticated(t,n,i){if(this.refresh())return this.request(t,n,i);throw this.clear(),this.onUnauthenticated?.(),new f(we)}async startPkce(){let t=Or();sessionStorage.setItem("pkceState",t);let n=Or().slice(0,128);sessionStorage.setItem("codeVerifier",n);try{let i=await Zn(n);return{codeChallengeMethod:"S256",codeChallenge:Ln(i).replaceAll("+","-").replaceAll("/","_").replaceAll("=","")}}catch(i){return console.warn("Failed to hash code verifier. Falling back to 'plain' code challenge method",i),{codeChallengeMethod:"plain",codeChallenge:n}}}async requestAuthorization(t){let n=await this.ensureCodeChallenge(t??{}),i=new URL(this.authorizeUrl);i.searchParams.set("response_type","code"),i.searchParams.set("state",sessionStorage.getItem("pkceState")),i.searchParams.set("client_id",n.clientId??this.clientId),i.searchParams.set("redirect_uri",n.redirectUri??oe.getOrigin()),i.searchParams.set("code_challenge_method",n.codeChallengeMethod),i.searchParams.set("code_challenge",n.codeChallenge),i.searchParams.set("scope",n.scope??"openid profile"),oe.assign(i.toString())}processCode(t,n){let i={grant_type:Be.AuthorizationCode,code:t,client_id:n?.clientId??this.clientId??"",redirect_uri:n?.redirectUri??oe.getOrigin()};if(typeof sessionStorage<"u"){let o=sessionStorage.getItem("codeVerifier");o&&(i.code_verifier=o)}return this.fetchTokens(i)}refreshIfExpired(t){return!this.refreshPromise&&this.accessTokenExpires!==void 0&&!this.isAuthenticated(t)&&this.refresh(),this.refreshPromise??Promise.resolve()}refresh(){if(this.refreshPromise)return this.refreshPromise;if(this.refreshToken)return this.refreshPromise=this.fetchTokens({grant_type:Be.RefreshToken,client_id:this.clientId??"",refresh_token:this.refreshToken}),this.refreshPromise;if(this.clientId&&this.clientSecret)return this.refreshPromise=this.startClientLogin(this.clientId,this.clientSecret),this.refreshPromise}async startClientLogin(t,n){return this.clientId=t,this.clientSecret=n,this.fetchTokens({grant_type:Be.ClientCredentials,client_id:t,client_secret:n})}async startJwtBearerLogin(t,n,i){return this.clientId=t,this.fetchTokens({grant_type:Be.JwtBearer,client_id:t,assertion:n,scope:i})}async startJwtAssertionLogin(t){return this.fetchTokens({grant_type:Be.ClientCredentials,client_assertion_type:ts.JwtBearer,client_assertion:t})}setBasicAuth(t,n){this.clientId=t,this.clientSecret=n,this.basicAuth=Nt(t+":"+n)}setLogLevel(t){this.logLevel=t,this.options.verbose=t==="verbose"}getLogLevel(){return this.logLevel}setVerbose(t){this.logLevel=t?"verbose":"none",this.options.verbose=t}async fhircastSubscribe(t,n){if(!(typeof t=="string"&&t!==""))throw new f(v("Invalid topic provided. Topic must be a valid string."));if(!(typeof n=="object"&&Array.isArray(n)&&n.length>0))throw new f(v("Invalid events provided. Events must be an array of event names containing at least one event."));let i={channelType:"websocket",mode:"subscribe",topic:t,events:n},s=(await this.post(this.fhircastHubUrl,Dr(i),O.FORM_URL_ENCODED))["hub.channel.endpoint"];if(!s)throw new Error("Invalid response!");return i.endpoint=s,i}async fhircastUnsubscribe(t){if(!Bt(t))throw new f(v("Invalid topic or subscriptionRequest. SubscriptionRequest must be an object."));if(!(t.endpoint&&typeof t.endpoint=="string"&&t.endpoint.startsWith("ws")))throw new f(v("Provided subscription request must have an endpoint in order to unsubscribe."));t.mode="unsubscribe",await this.post(this.fhircastHubUrl,Dr(t),O.FORM_URL_ENCODED)}fhircastConnect(t){return new Ut(t)}async fhircastPublish(t,n,i,o){return ei(n)?this.post(this.fhircastHubUrl,Mr(t,n,i,o),O.JSON):(ti(n),this.post(this.fhircastHubUrl,Mr(t,n,i),O.JSON))}async fhircastGetContext(t){return this.get(`${this.fhircastHubUrl}/${t}`,{cache:"no-cache"})}async invite(t,n){return this.post("admin/projects/"+t+"/invite",n)}async handleTokenError(t){try{let n=await t.json();throw je(n)?new f(n):n.error_description?new f(R(n.error_description)):new Error(JSON.stringify(n))}catch(n){throw n instanceof f?(n.message=`Failed to fetch tokens: ${n.message}`,n):new f(R("Failed to fetch tokens"),{cause:n})}}async fetchTokens(t){let n=new URLSearchParams(t),i={...this.defaultHeaders,"Content-Type":O.FORM_URL_ENCODED};this.basicAuth&&(i.Authorization=`Basic ${this.basicAuth}`),this.credentialsInHeader&&(n.delete("client_id"),n.delete("client_secret"),!this.basicAuth&&t.client_id&&t.client_secret&&(i.Authorization=`Basic ${Nt(t.client_id+":"+t.client_secret)}`));let o={method:"POST",headers:i,body:n.toString(),credentials:"include"},s;try{s=await this.fetchWithRetry(this.tokenUrl,o)}catch(u){throw this.refreshPromise=void 0,u}s.ok||(this.clearActiveLogin(),this.onUnauthenticated?.(),await this.handleTokenError(s));let a=await s.json();return await this.verifyTokens(a),this.getProfile()}async verifyTokens(t){let n=t.access_token;if(ni(n)){let i=qt(n);if(Date.now()>=i.exp*1e3)throw this.clearActiveLogin(),new f(an);if(i.cid){if(i.cid!==this.clientId)throw this.clearActiveLogin(),new f(ir)}else if(this.clientId&&i.client_id!==this.clientId)throw this.clearActiveLogin(),new f(ir)}return this.setActiveLogin({accessToken:n,refreshToken:t.refresh_token,project:t.project,profile:t.profile})}checkSessionDetailsMatchLogin(t){return this.sessionDetails&&t?t.profile?.reference?.endsWith(this.sessionDetails.profile.id)??!1:!0}setupStorageListener(){try{window.addEventListener("storage",t=>{if(t.key===null)oe.reload();else if(t.key===this.storage.makeKey("activeLogin")){let n=t.oldValue?JSON.parse(t.oldValue):void 0,i=t.newValue?JSON.parse(t.newValue):void 0;n?.profile.reference!==i?.profile.reference||!this.checkSessionDetailsMatchLogin(i)?oe.reload():i?this.setAccessToken(i.accessToken,i.refreshToken):this.clear()}})}catch{}}getSubscriptionManager(){return this.subscriptionManager||(this.subscriptionManager=new Gt(this,Bn(this.baseUrl,"/ws/subscriptions-r4"))),this.subscriptionManager}subscribeToCriteria(t,n){return this.getSubscriptionManager().addCriteria(t,n)}unsubscribeFromCriteria(t,n){this.subscriptionManager&&this.subscriptionManager.removeCriteria(t,n)}getMasterSubscriptionEmitter(){return this.getSubscriptionManager().getMasterEmitter()}};function pl(){if(!globalThis.fetch)throw new Error("Fetch not available in this environment");return globalThis.fetch.bind(globalThis)}async function Yo(r,e){let t=r.headers.get("content-location");if(t)return t;let n=r.headers.get("location");if(n)return n;if(je(e)&&e.issue?.[0]?.diagnostics)return e.issue[0].diagnostics}function Xo(r){let e=r.entry?.map(t=>t.resource)??[];return Object.assign(e,{bundle:r})}function fl(r){return E(r)&&"data"in r&&"contentType"in r}function ci(r,e,t,n){return fl(r)?r:{data:r,filename:e,contentType:t,onProgress:n}}function ml(r){return E(r)&&"docDefinition"in r}function rs(r,e,t,n){return ml(r)?r:{docDefinition:r,filename:e,tableLayouts:t,fonts:n}}function hl(r){return r.status===429||r.status>=500}var yl={aws_ssm_parameter_store:"aws_ssm_parameter_store"};function gl(r,e,t){let n=new Nr;Array.isArray(r)||(r=r.entry?.map(i=>i.resource)??[]);for(let i of r)n.addObservation(i);return n.summarize(e,t)}var Nr=class{constructor(e){c(this,"code");c(this,"unit");c(this,"sampling");c(this,"dataPoints");this.dataPoints=[],this.code=e?.code,this.unit=e?.unit,this.sampling=e?.sampling}addObservation(e){if(!this.code)this.code=e.code;else if(!xl(this.code,e.code))throw new Error("Observation does not match code of sampled data");e.valueQuantity?.value!==void 0?(this.checkUnit(e.valueQuantity),this.addData(e.valueQuantity.value)):e.valueInteger!==void 0?this.addData(e.valueInteger):e.valueSampledData?.data&&(this.checkUnit(e.valueSampledData.origin),this.addData(...ui(e.valueSampledData)))}addData(...e){this.dataPoints.push(...e)}checkUnit(e){if(!this.unit)this.unit=e;else if(e.code&&e.system){if(this.unit.system!==e.system||this.unit.code!==e.code)throw new Error("Incorrect unit for Observation")}else if(e.unit&&this.unit.unit!==e.unit)throw new Error("Incorrect unit for Observation")}summarize(e,t){if(!this.code)throw new Error("Code is required for data points");let n=t(this.dataPoints);return{resourceType:"Observation",status:"final",code:e,valueQuantity:typeof n=="number"?{...this.unit,value:n}:n,component:[{code:this.code,valueSampledData:{origin:{...this.unit,value:0},dimensions:1,period:0,...this.sampling,data:vl(this.dataPoints,this.sampling)}}]}}};function xl(r,e){return!!r.coding?.some(t=>e.coding?.some(n=>t.system===n.system&&t.code===n.code))}function ui(r){return r.data?.split(" ").map(e=>Number.parseFloat(e)*(r.factor??1)+(r.origin.value??0))??[]}function vl(r,e){if(r.length)return r.map(t=>(t-(e?.origin.value??0))/(e?.factor??1)).join(" ")}function Tl(r){let e=[],t=r.effectiveInstant??r.effectiveDateTime??r.effectivePeriod?.start,n=t?Date.parse(t).valueOf():0;r.valueSampledData&&e.push(...ns(r.valueSampledData,n,r));for(let i of r.component??g)i.valueSampledData&&e.push(...ns(i.valueSampledData,n,{...r,...i}));return e}function ns(r,e,t){let n=[],i=ui(r),o=A(t);for(let s=0;s<i.length;s++){let a=i[s],u=e+Math.floor(s/r.dimensions)*r.period;n.push({...t,id:void 0,effectiveInstant:void 0,effectivePeriod:void 0,effectiveTiming:void 0,effectiveDateTime:u?new Date(u).toISOString():void 0,valueQuantity:{...r.origin,value:a},valueSampledData:void 0,component:void 0,derivedFrom:o?[...t.derivedFrom??[],{reference:o}]:t.derivedFrom})}return n}function Br({parentContext:r,path:e,elements:t,profileUrl:n,debugMode:i,accessPolicyResource:o}){if(e===r?.path)return;i??=r?.debugMode??!1,o??=r?.accessPolicyResource;let s=bl(e,t,r,!!i),a=_e(e,".",2)[1];s=Sl(s,o,a),s=El(s,o,a);let u=Object.create(null);for(let[p,y]of Object.entries(s))u[e+"."+p]=y;let l;if(r&&!r.isDefaultContext)l=r.getExtendedProps;else{let p=Object.create(null);l=y=>{let x=_e(y,".",2)[1];if(x){if(!p[x]){let V=Ur(x,o?.hiddenFields);p[x]={hidden:V,readonly:V||Ur(x,o?.readonlyFields)}}return p[x]}}}return{path:e,elements:s,elementsByPath:u,profileUrl:n??r?.profileUrl,debugMode:i,getExtendedProps:l,accessPolicyResource:o}}function bl(r,e,t,n){let i=Object.create(null);if(t)for(let[s,a]of Object.entries(t.elementsByPath)){let u=pe(r,s);u!==void 0&&(i[u]=a)}let o=!1;if(e)for(let[s,a]of Object.entries(e))s in i||(i[s]=a,o=!0);return n&&console.assert(o,"Unnecessary ElementsContext; not using any newly provided elements"),i}function Sl(r,e,t){if(!e?.hiddenFields?.length)return r;let n=t?t+".":"";return Object.fromEntries(Object.entries(r).filter(([i])=>!Ur(n+i,e.hiddenFields)))}function El(r,e,t){if(!e?.readonlyFields?.length)return r;let n=Object.create(null),i=t?t+".":"";for(let[o,s]of Object.entries(r))Ur(i+o,e.readonlyFields)?n[o]={...s,readonly:!0}:n[o]=s;return n}function Ur(r,e){if(!e?.length)return!1;let t=r.split(".");for(let n=1;n<=t.length;n++){let i=t.slice(0,n).join(".");if(e.includes(i))return!0}return!1}function li(r){return r.type!==void 0&&r.type.length>0}function Rl(r,e,t,n){let i=ke(r,e.path,{profileUrl:n});if(i){let o=t.typeSchema?.elements??t.elements;return i.some(s=>hr(s,e,t,o))??!1}return console.assert(!1,"getNestedProperty[%s] in isDiscriminatorComponentMatch missed",e.path),!1}function di(r,e,t,n){if(r)for(let i of e){let o={value:r,type:i.typeSchema?.type??i.type?.[0].code};if(t.every(s=>Rl(o,s,i,i.typeSchema?.url??n)))return i.name}}var Qt=class{constructor(e,t,n){c(this,"rootSchema");c(this,"visitor");c(this,"elementsContextStack");c(this,"sliceAllowList");if(e.type===void 0)throw new Error("schema must include a type");this.rootSchema=e;let i=Br({parentContext:void 0,path:this.rootSchema.type,elements:n??this.rootSchema.elements,profileUrl:this.rootSchema.name===this.rootSchema.type?void 0:this.rootSchema.url});if(i===void 0)throw new Error("Could not create root elements context");this.elementsContextStack=[i],this.visitor=t}get elementsContext(){return this.elementsContextStack.at(-1)}crawlElement(e,t,n){this.visitor.onEnterSchema&&this.visitor.onEnterSchema(this.rootSchema);let i=Object.fromEntries(Object.entries(this.elementsContext.elements).filter(([o])=>o.startsWith(t)));this.crawlElementsImpl(i,n),this.visitor.onExitSchema&&this.visitor.onExitSchema(this.rootSchema)}crawlSlice(e,t,n){let i=this.prepareSlices(n.slices,n);if(!te(i.slices))throw new Error(`cannot crawl slice ${t.name} since it has no type information`);this.visitor.onEnterSchema&&this.visitor.onEnterSchema(this.rootSchema),this.sliceAllowList=[t],this.crawlSliceImpl(i.slices[0],t.path,i),this.sliceAllowList=void 0,this.visitor.onExitSchema&&this.visitor.onExitSchema(this.rootSchema)}crawlResource(){this.visitor.onEnterSchema&&this.visitor.onEnterSchema(this.rootSchema),this.crawlElementsImpl(this.rootSchema.elements,this.rootSchema.type),this.visitor.onExitSchema&&this.visitor.onExitSchema(this.rootSchema)}crawlElementsImpl(e,t){let n=Cl(e);for(let i of n)this.crawlElementNode(i,t)}crawlElementNode(e,t){let n=t+"."+e.key;this.visitor.onEnterElement&&this.visitor.onEnterElement(n,e.element,this.elementsContext);for(let i of e.children)this.crawlElementNode(i,t);te(e.element?.slicing?.slices)&&this.crawlSlicingImpl(e.element.slicing,n),this.visitor.onExitElement&&this.visitor.onExitElement(n,e.element,this.elementsContext)}prepareSlices(e,t){let n=[];for(let o of e){if(!li(o))continue;let s=o.type.find(a=>te(a.profile))?.profile?.[0];if(te(s)){let a=vn(s);a&&(o.typeSchema=a)}n.push(o)}return{...t,slices:n}}crawlSlicingImpl(e,t){let n=this.prepareSlices(e.slices,e);for(let i of n.slices)(this.sliceAllowList===void 0||this.sliceAllowList.includes(i))&&this.crawlSliceImpl(i,t,n)}crawlSliceImpl(e,t,n){let i=e.typeSchema;i&&this.visitor.onEnterSchema&&this.visitor.onEnterSchema(i),this.visitor.onEnterSlice&&this.visitor.onEnterSlice(t,e,n);let o,s=i?.elements??e.elements;te(s)&&(o=Br({path:t,parentContext:this.elementsContext,elements:s})),o&&this.elementsContextStack.push(o),this.crawlElementsImpl(s,t),o&&this.elementsContextStack.pop(),this.visitor.onExitSlice&&this.visitor.onExitSlice(t,e,n),i&&this.visitor.onExitSchema&&this.visitor.onExitSchema(i)}};function Cl(r){let e=[];function t(o,s){return s.startsWith(o+".")}function n(o,s){for(let a of o.children)if(t(a.key,s.key)){n(a,s);return}o.children.push(s)}let i=Object.entries(r);i.sort((o,s)=>o[0].localeCompare(s[0]));for(let[o,s]of i){let a={key:o,element:s,children:[]},u=!1;for(let l of e)if(t(l.key,o)){n(l,a),u=!0;break}u||e.push(a)}return e}var qr="__sliceName";function Pl(r,e){let t=new Wr(r,r.resourceType,"resource");return new Qt(e,t).crawlResource(),t.getDefaultValue()}function Al(r,e,t){for(let[n,i]of Object.entries(e)){if(t===void 0||t===n){zt(r,n,i,e);continue}let o=pe(t,n);o!==void 0&&zt(r,o,i,e)}return r}function wl(r,e,t,n){let i=new Wr([{[qr]:e.name}],e.path,"element");return new Qt(n,i).crawlSlice(r,e,t),i.getDefaultValue()[0]}var Wr=class{constructor(e,t,n){c(this,"rootValue");c(this,"schemaStack");c(this,"valueStack");this.schemaStack=[],this.valueStack=[],this.rootValue=Se(e),this.valueStack.splice(0,this.valueStack.length,{type:n,path:t,values:[this.rootValue]})}get schema(){return this.schemaStack.at(-1)}get value(){return this.valueStack.at(-1)}onEnterSchema(e){this.schemaStack.push(e)}onExitSchema(){this.schemaStack.pop()}onEnterElement(e,t,n){let i=this.value.values,o=this.value.path,s=pe(o,e);if(s===void 0)throw new Error(`Expected ${e} to be prefixed by ${o}`);let a=[];for(let u of i){if(u===void 0)continue;let l=pe(n.path,o),p=Array.isArray(u)?u:[u];for(let y of p){Ol(y,s,t,n.elements,l),zt(y,s,t,n.elements);let x=fi(y,s,n.elements,l);x!==void 0&&a.push(x)}}this.valueStack.push({type:"element",path:e,values:a})}onExitElement(e,t,n){if(!this.valueStack.pop())throw new Error("Expected value context to exist when exiting element");let o=pe(this.value.path,e);if(o===void 0)throw new Error(`Expected ${e} to be prefixed by ${this.value.path}`);let s=pe(n.path,this.value.path);for(let a of this.value.values){let u=fi(a,o,n.elements,s);if(Array.isArray(u))for(let l=u.length-1;l>=0;l--){let p=u[l];te(p)||u.splice(l,1)}C(u)&&pi(a,void 0,o,t)}}onEnterSlice(e,t,n){let i=this.value.values,o=[];for(let s of i)if(s!==void 0){let a=Array.isArray(s)?s:[s],u=this.getMatchingSliceValues(a,t,n);o.push(u)}this.valueStack.push({type:"slice",path:e,values:o})}getMatchingSliceValues(e,t,n){let i=[];for(let o of e)(o[qr]??di(o,[t],n.discriminator,this.schema.url))===t.name&&i.push(o);for(let o=i.length;o<t.min;o++)if(Sr(t.type[0].code)){let s=Object.create(null);i.push(s),e.push(s)}return i}onExitSlice(){let e=this.valueStack.pop();if(!e)throw new Error("Expected value context to exist in onExitSlice");for(let t of e.values)for(let n=t.length-1;n>=0;n--){let i=t[n];qr in i&&delete i[qr]}}getDefaultValue(){return this.rootValue}};function Ol(r,e,t,n,i){let o=fi(r,e,n,i);t.min>0&&o===void 0&&Sr(t.type[0].code)&&(t.isArray?pi(r,[Object.create(null)],e,t):pi(r,Object.create(null),e,t))}function pi(r,e,t,n){if(t.includes("."))throw new Error("key cannot be nested");let i=t;if(t.includes("[x]")){let o=n.type[0].code;i=t.replace("[x]",M(o))}e===void 0?delete r[i]:r[i]=e}function fi(r,e,t,n){let i=e.split("."),o=r,s;for(let a=0;a<i.length;a++){let u=i[a];if(u.includes("[x]")){let l=(n?n+".":"")+i.slice(0,a+1).join("."),y=t[l].type[0].code;u=u.replace("[x]",M(y))}if(a===i.length-1){Array.isArray(o)?s=o.map(l=>l[u]):s=o[u];continue}if(Array.isArray(o))o=o.map(l=>l[u]);else if(E(o)){if(o[u]===void 0)return;o=o[u]}else return}return s}function zt(r,e,t,n){if(!(t.fixed||t.pattern))return r;if(Array.isArray(r))return r.map(a=>zt(a,e,t,n));r==null&&(r=Object.create(null));let i=r,o=e.split("."),s=i;for(let a=0;a<o.length;a++){let u=o[a];if(u.includes("[x]")){let p=n[o.slice(0,a+1).join(".")].type[0].code;u=u.replace("[x]",M(p))}if(a===o.length-1){let l=Array.isArray(s)?s:[s];for(let p of l)t.fixed?p[u]??=t.fixed.value:t.pattern&&(p[u]=is(p[u],t.pattern.value))}else{if(!(u in s)){let l=o.slice(0,a+1).join(".");s[u]=n[l].isArray?[Object.create(null)]:Object.create(null)}s=s[u]}}return i}function is(r,e){if(Array.isArray(e)&&(Array.isArray(r)||r===void 0))return(r?.length??0)>0?r:Se(e);if(E(e)&&(E(r)&&!Array.isArray(r)||r===void 0)){let t=Se(r)??Object.create(null);for(let n of Object.keys(e))t[n]=is(t[n],e[n]);return t}return r}function mi(r,e){if(!r.group)throw new f(R("ConceptMap does not specify a mapping group","ConceptMap.group"));let t=os(e),n=Il(t,e.targetsystem?r.group.filter(o=>o.target===e.targetsystem):r.group),i=n.length>0;return{result:i,match:i?n:void 0}}function os(r){let e=Object.create(null);if(r.code&&!r.coding&&!r.codeableConcept){if(!r.system)throw new f(R("System parameter must be provided with code"));e[r.system]=[r.code]}else if(r.coding&&!r.code&&!r.codeableConcept)r.coding.code&&(e[r.coding.system??""]=[r.coding.code]);else if(r.codeableConcept&&!r.code&&!r.coding)for(let{system:t,code:n}of r.codeableConcept.coding??g)n&&(e[t??""]=z(e[t??""],n));else throw r.code||r.coding||r.codeableConcept?new f(R("Ambiguous input: multiple source codings provided")):new f(R("Source Coding (system + code) must be specified"));return e}function Il(r,e){let t=[];for(let[n,i]of Object.entries(r))for(let o of e.filter(s=>(s.source??"")===n)){let s=o.element?.filter(a=>i.includes(a.code)).flatMap(a=>a.target?.map(u=>({equivalence:u.equivalence,concept:{system:o.target,code:u.code,display:u.display}}))??[]);s?.length||(s=kl(i,o)),s&&t.push(...s)}return t}function kl(r,e){switch(e.unmapped?.mode){case"provided":return r.map(t=>({equivalence:"equal",concept:{system:e.target,code:t}}));case"fixed":return[{equivalence:"equivalent",concept:{system:e.target,code:e.unmapped.code,display:e.unmapped.display}}];default:return}}var Vl=[..._t,"->","<<",">>","=="];function ss(r){return new ge(r,Mt,Vl).tokenize()}var Dl={"-":"disjoint","==":"equal"},hi=class{constructor(e){c(this,"parser");c(this,"structureMap",{resourceType:"StructureMap",status:"active"});this.parser=e}parse(){for(;this.parser.hasMore();){let e=this.parser.peek()?.value;switch(e){case"map":this.parseMap();break;case"uses":this.parseUses();break;case"imports":this.parseImport();break;case"group":this.parseGroup();break;case"conceptmap":this.parseConceptMap();break;default:throw new Error(`Unexpected token: ${e}`)}}return this.structureMap}parseMap(){this.parser.consume("Symbol","map"),this.structureMap.url=this.parser.consume("String").value,this.parser.consume("="),this.structureMap.name=this.parser.consume().value}parseUses(){this.parser.consume("Symbol","uses");let e={};e.url=this.parser.consume("String").value,this.parser.peek()?.value==="alias"&&(this.parser.consume("Symbol","alias"),e.alias=this.parser.consume("Symbol").value),this.parser.consume("Symbol","as"),e.mode=this.parser.consume().value,this.structureMap.structure||(this.structureMap.structure=[]),this.structureMap.structure.push(e)}parseImport(){this.parser.consume("Symbol","imports"),this.structureMap.import||(this.structureMap.import=[]),this.structureMap.import.push(this.parser.consume("String").value)}parseGroup(){let e={};this.parser.consume("Symbol","group"),e.name=this.parser.consume("Symbol").value,e.input=this.parseParameters(),this.parser.peek()?.value==="extends"&&(this.parser.consume("Symbol","extends"),e.extends=this.parser.consume("Symbol").value),this.parser.peek()?.value==="<<"?(this.parser.consume("<<"),e.typeMode=this.parser.consume().value,this.parser.peek()?.value==="+"&&(this.parser.consume("+"),e.typeMode="type-and-types"),this.parser.consume(">>")):e.typeMode="none",e.rule=this.parseRules(),this.structureMap.group||(this.structureMap.group=[]),this.structureMap.group.push(e)}parseParameters(){let e=[];for(this.parser.consume("(");this.parser.hasMore()&&this.parser.peek()?.value!==")";)e.push(this.parseParameter()),this.parser.peek()?.value===","&&this.parser.consume(",");return this.parser.consume(")"),e}parseParameter(){let e={};return e.mode=this.parser.consume().value,e.name=this.parser.consume("Symbol").value,this.parser.peek()?.value===":"&&(this.parser.consume(":"),e.type=this.parser.consume("Symbol").value),e}parseRules(){let e=[];for(this.parser.consume("{");this.parser.hasMore()&&this.parser.peek()?.value!=="}";)e.push(this.parseRule());return this.parser.consume("}"),e}parseRule(){let e={source:this.parseRuleSources()};return this.parser.peek()?.value==="->"&&(this.parser.consume("->"),e.target=this.parseRuleTargets()),this.parser.peek()?.value==="then"&&(this.parser.consume("Symbol","then"),this.parser.peek()?.id==="{"?e.rule=this.parseRules():e.dependent=this.parseRuleDependents()),this.parser.peek()?.id==="String"?e.name=this.parser.consume().value:e.name=e.source?.[0]?.element,this.parser.consume(";"),e}parseRuleSources(){this.parser.hasMore()&&this.parser.peek()?.value==="for"&&this.parser.consume("Symbol","for");let e=[this.parseRuleSource()];for(;this.parser.hasMore()&&this.parser.peek()?.value===",";)this.parser.consume(","),e.push(this.parseRuleSource());return e}parseRuleSource(){let e={},n=this.parseRuleContext().split(".");if(e.context=n[0],e.element=n[1],this.parser.hasMore()&&this.parser.peek()?.value===":"&&(this.parser.consume(":"),e.type=this.parser.consume().value),this.parser.hasMore()&&this.parser.peek()?.value==="default"&&(this.parser.consume("Symbol","default"),e.defaultValueString=this.parser.consume("String").value),(this.parser.peek()?.value==="first"||this.parser.peek()?.value==="not_first"||this.parser.peek()?.value==="last"||this.parser.peek()?.value==="not_last"||this.parser.peek()?.value==="only_one")&&(e.listMode=this.parser.consume().value),this.parser.peek()?.value==="as"&&(this.parser.consume("Symbol","as"),e.variable=this.parser.consume().value),this.parser.peek()?.value==="log"&&(this.parser.consume("Symbol","log"),e.logMessage=this.parser.consume().value),this.parser.peek()?.value==="where"){this.parser.consume("Symbol","where");let i=this.parser.consumeAndParse(T.Arrow);e.condition=i.toString()}if(this.parser.peek()?.value==="check"){this.parser.consume("Symbol","check");let i=this.parser.consumeAndParse(T.Arrow);e.check=i.toString()}return e}parseRuleTargets(){let e=[this.parseRuleTarget()];for(;this.parser.hasMore()&&this.parser.peek()?.value===",";)this.parser.consume(","),e.push(this.parseRuleTarget());return e}parseRuleTarget(){let e={},n=this.parseRuleContext().split(".");return e.contextType="variable",e.context=n[0],e.element=n[1],this.parser.peek()?.value==="="&&(this.parser.consume("="),this.parseRuleTargetTransform(e)),this.parser.peek()?.value==="as"&&(this.parser.consume("Symbol","as"),e.variable=this.parser.consume().value),this.parser.peek()?.value==="share"&&(this.parser.consume("Symbol","share"),e.listMode=["share"],this.parser.consume("Symbol")),(this.parser.peek()?.value==="first"||this.parser.peek()?.value==="last"||this.parser.peek()?.value==="collate")&&(e.listMode=[this.parser.consume().value]),e}parseRuleTargetTransform(e){let t=this.parser.consumeAndParse(T.As);t instanceof ie?(e.transform=t.name,e.parameter=t.args?.map(as)):t instanceof W||t instanceof N?(e.transform="copy",e.parameter=[as(t)]):(e.transform="evaluate",e.parameter=[{valueString:t.toString()}])}parseRuleContext(){let e=this.parser.consume().value;for(;this.parser.peek()?.value===".";)this.parser.consume("."),e+="."+this.parser.consume().value;return e}parseRuleDependents(){let e=this.parser.consumeAndParse(T.Arrow);return[{name:e.name,variable:e.args.map(t=>t.name)}]}parseConceptMap(){this.parser.consume("Symbol","conceptmap");let e={resourceType:"ConceptMap",status:"active",url:"#"+this.parser.consume("String").value};this.parser.consume("{");let t={},n=this.parser.peek()?.value;for(;n!=="}";)n==="prefix"?this.parseConceptMapPrefix(t):this.parseConceptMapRule(e,t),n=this.parser.peek()?.value;this.parser.consume("}"),this.structureMap.contained||(this.structureMap.contained=[]),this.structureMap.contained.push(e)}parseConceptMapPrefix(e){this.parser.consume("Symbol","prefix");let t=this.parser.consume().value;this.parser.consume("=");let n=this.parser.consume().value;e[t]=n}parseConceptMapRule(e,t){let n=this.parser.consume().value,i=t[n];this.parser.consume(":");let o=this.parser.consume().value,s=Dl[this.parser.consume().value],a=this.parser.consume().value,u=t[a];this.parser.consume(":");let l=this.parser.consume().value,p=e?.group?.find(y=>y.source===i&&y.target===u);p||(p={source:i,target:u,element:[]},e.group||(e.group=[]),e.group.push(p)),p.element||(p.element=[]),p.element.push({code:o,target:[{code:l,equivalence:s}]})}};function as(r){if(r instanceof N)return{valueId:r.name};if(r instanceof W)return Ml(r);throw new Error(`Unknown parameter atom type: ${r.constructor.name} (${r.toString()})`)}function Ml(r){switch(r.value.type){case"boolean":return{valueBoolean:r.value.value};case"decimal":return{valueDecimal:r.value.value};case"integer":return{valueInteger:r.value.value};case"dateTime":case"string":return{valueString:r.value.value};default:throw new Error("Unknown target literal type: "+r.value.type)}}var _l=Xe().registerInfix("->",{precedence:T.Arrow}).registerInfix(";",{precedence:T.Semicolon});function Ll(r){let e=_l.construct(ss(r));return e.removeComments(),new hi(e).parse()}var jr=class{constructor(e=[]){c(this,"resources");this.resources=e}get(e,t){let n=[];for(let i of this.resources)i.resourceType===e&&i.url&&this.matchesUrl(i.url,t)&&n.push(i);return n}matchesUrl(e,t){if(t.includes("*")){let n=t.split("*");return e.startsWith(n[0])&&e.endsWith(n[1])}else return e===t}};function Fl(r,e,t=new jr){return Nl({root:r,transformMaps:t},r,e)}function Nl(r,e,t){return Ul(r,e),us(r,e),gi(r,e.group[0],t)}function Ul(r,e){let t=Gr(r);if(t&&e.import)for(let n of e.import){let i=t.get("StructureMap",n);for(let o of i)us(r,o)}}function us(r,e){let t=Gr(r);if(t&&e.contained)for(let n of e.contained)(n.resourceType==="StructureMap"||n.resourceType==="ConceptMap")&&t.resources.push(n);for(let n of e.group??g)$r(r,n.name,{type:"StructureMapGroup",value:n})}function gi(r,e,t){let n=[],i=[];for(let l of e.input)l.mode==="source"&&n.push(l),l.mode==="target"&&i.push(l);if(n.length===0)throw new Error("Missing source definitions");if(i.length===0)throw new Error("Missing target definitions");if(t.length<n.length)throw new Error(`Not enough arguments (got ${t.length}, min ${n.length})`);if(t.length>n.length+i.length)throw new Error(`Too many arguments (got ${t.length}, max ${n.length+i.length})`);let o={},s=[],a=0;for(let l of n)Jt(o,l.name,t[a++]);for(let l of i){let p=t[a++]??{type:l.type??"BackboneElement",value:{}};Jt(o,l.name,p),s.push(p)}let u={root:r.root,parent:r,variables:o};for(let l of e.rule??g)ls(u,l);return s}function ls(r,e){e.source&&ds(r,e,0)}function ds(r,e,t){let n=e.source[t];for(let i of jl(r,n))$r(r,"_",i),n.variable&&$r(r,n.variable,i),t<e.source.length-1?ds(r,e,t+1):Bl(r,e)}function Bl(r,e){if(!ql(r,e)){for(let t of e.target??g)ps(r,t);for(let t of e.rule??g)ls(r,t);for(let t of e.dependent??g)Zl(r,t)}}function ql(r,e){if(e.target?.length!==1||e.target[0].transform||e.rule||e.dependent)return!1;let t=Ae(r,"_");if(Array.isArray(t)&&(t=t[0]),!t)return!1;let n=Wl(r,t);if(!n)return ps(r,{...e.target[0],transform:"copy",parameter:[{valueId:"_"}]}),!0;let i=e.target[0],o=Ae(r,i.context),s=o.value[i.element],a=ms(o,i.element)||Array.isArray(s),u={root:r.root,parent:r,variables:{}},l=gi(u,n,[t]);return fs(r,i,o,l,a,s),!0}function Wl(r,e){let t=r;for(;t;){if(t.variables){for(let n of Object.values(t.variables))for(let i of yi(n))if(i.type==="StructureMapGroup"){let o=i.value;if((o.typeMode==="types"||o.typeMode==="type-and-types")&&o.input.length===2&&o.input[0].mode==="source"&&o.input[0].type===e.type&&o.input[1].mode==="target")return o}}t=t.parent}}function jl(r,e){let t=Ae(r,e.context);if(!t)return[];let n=e.element;if(!n)return[t];let i=P(n,[t]);if(!i||i.length===0)return[];if(e.condition&&!cs(t,{[e.variable]:i[0]},e.condition))return[];if(e.check&&!cs(t,{[e.variable]:i[0]},e.check))throw new Error("Check failed: "+e.check);return e.listMode&&(i=$l(e,i)),i}function cs(r,e,t){return B(P(t,[r],e))}function $l(r,e){switch(r.listMode){case"first":return[e[0]];case"not_first":return e.slice(1);case"last":return[e.at(-1)];case"not_last":return e.slice(0,e.length-1);case"only_one":if(e.length!==1)throw new Error("Expected only one value");break}return e}function ps(r,e){let t=Ae(r,e.context);if(!t)throw new Error("Target not found: "+e.context);let n=t.value[e.element],i,o=ms(t,e.element)||Array.isArray(n);if(e.transform)switch(e.transform){case"append":i=Gl(r,e);break;case"cast":i=Hl(r,e);break;case"cc":i=Ql(r,e);break;case"copy":i=zl(r,e);break;case"create":i=Jl(r,e);break;case"evaluate":i=Kl(r,e);break;case"translate":i=Yl(r,e);break;case"truncate":i=Xl(r,e);break;case"uuid":i=[{type:"string",value:se()}];break;default:throw new Error(`Unsupported transform: ${e.transform}`)}else{let s=hs(t,e.element)?.type,a=s?.length===1?s[0].code:void 0;o||n===void 0?i=[a?{type:a,value:{}}:b({})]:i=[a?{type:a,value:n}:b(n)]}fs(r,e,t,i,o,n)}function fs(r,e,t,n,i,o){if(n.length!==0){if(i){o||(o=[],Jt(t.value,e.element,o));for(let s of n)o.push(s.value)}else Jt(t.value,e.element,n[0].value);e.variable&&$r(r,e.variable,ed(n))}}function ms(r,e){return hs(r,e)?.isArray}function hs(r,e){return Ge(r.type)?.elements?.[e]}function Gl(r,e){let t=$(r,e.parameter?.[0])?.[0]?.value,n=$(r,e.parameter?.[1])?.[0]?.value;return[{type:"string",value:(t??"").toString()+(n??"").toString()}]}function Hl(r,e){let t=$(r,e.parameter?.[0])?.[0];return $(r,e.parameter?.[1])?.[0]?.value==="string"?[{type:"string",value:t?.value?.toString()}]:[t]}function Ql(r,e){let t=e.parameter;if(t.length===2){let n=$(r,t[0])?.[0]?.value,i=$(r,t[1])?.[0]?.value;return[{type:"CodeableConcept",value:{coding:[{system:n,code:i}]}}]}else return[{type:"CodeableConcept",value:{text:$(r,t[0])?.[0]?.value}}]}function zl(r,e){return e.parameter.flatMap(t=>$(r,t))}function Jl(r,e){let t={};return e.parameter&&e.parameter.length>0&&(t.resourceType=$(r,e.parameter?.[0])?.[0]?.value),[b(t)]}function Kl(r,e){let n=$(r,e.parameter?.[0])[0].value;return P(n,[],ys(r))}function Yl(r,e){let t=e.parameter.flatMap(u=>$(r,u)),n=t[0].value,i=t[1].value,s=Gr(r)?.get("ConceptMap",i)[0];if(!s)throw new Error("ConceptMap not found: "+i);let a=mi(s,{system:s.group?.[0]?.source,code:n});return[b(a.match?.[0]?.concept?.code)]}function Xl(r,e){let t=$(r,e.parameter?.[0])?.[0],n=$(r,e.parameter?.[1])?.[0]?.value;return t.type==="string"?[{type:"string",value:t.value.substring(0,n)}]:[t]}function Zl(r,e){let t=Ae(r,e.name);if(!t)throw new Error("Dependent group not found: "+e.name);let n=e.variable,i=[];for(let s of n){let a=Ae(r,s);if(!a)throw new Error("Dependent variable not found: "+s);i.push(a)}let o={root:r.root,parent:r,variables:{}};gi(o,t.value,i)}function Gr(r){if(r.transformMaps)return r.transformMaps;if(r.parent)return Gr(r.parent)}function $(r,e){let n=D({type:"StructureMapGroupRuleTargetParameter",value:e},"value");if(!n)throw new Error("Missing target parameter: "+JSON.stringify(e));if(n=yi(n),n.length===1&&n[0].type==="id"){let i=Ae(r,n[0].value);if(!i)throw new Error("Variable not found: "+n[0].value);return yi(i)}return n}function Ae(r,e){let t=r.variables?.[e];if(t)return t;if(r.parent)return Ae(r.parent,e)}function ys(r,e={}){if(r.parent&&ys(r.parent,e),r.variables)for(let[t,n]of Object.entries(r.variables))e[t]=n,e["%"+t]=n;return e}function $r(r,e,t){r.variables||(r.variables={}),Jt(r.variables,e,t)}function Jt(r,e,t){if(e==="__proto__"||e==="constructor"||e==="prototype")throw new Error("Invalid key: "+e);r[e]=t}function yi(r){return Array.isArray(r)?r:[r]}function ed(r){return r.length===1?r[0]:r}var td=" ".repeat(2),xi=class{constructor(e=td,t=!0){c(this,"indent");c(this,"b");c(this,"indentCount");this.indent=e,this.b=[],this.indentCount=0,t&&(this.appendNoWrap("// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors"),this.appendNoWrap("// SPDX-License-Identifier: Apache-2.0"),this.appendNoWrap("/*"),this.appendNoWrap(" * This is a generated file"),this.appendNoWrap(" * Do not edit manually."),this.appendNoWrap(" */"),this.newLine())}newLine(){this.b.push(`
|
|
44
|
+
}`.replaceAll(/\s+/g," "),u=await this.graphql(a);ur(u.data.StructureDefinitionList);for(let l of u.data.SearchParameterList)Pr(l)})());return this.setCacheEntry(i,s,n),s}requestProfileSchema(t,n){if(!n?.expandProfile&&xn(t))return Promise.resolve();let i=t+"-requestSchema"+(n?.expandProfile?"-nested":""),o=this.getCacheEntry(i,void 0);if(o)return o.value;let s=new U((async()=>{if(n?.expandProfile){let a=this.fhirUrl("StructureDefinition","$expand-profile");a.search=new URLSearchParams({url:t}).toString();let u=await this.post(a.toString(),{});ur(u)}else{let a=await this.searchOne("StructureDefinition",{url:t,_sort:"-_lastUpdated"});if(!a){console.warn(`No StructureDefinition found for ${t}!`);return}lr(a)}})());return this.setCacheEntry(i,s,n),s}readHistory(t,n,i,o){let s=this.fhirUrl(t,n,"_history");return i?.count&&s.searchParams.set("_count",i.count.toString()),i?.offset&&s.searchParams.set("_offset",i.offset.toString()),this.get(s.toString(),o)}readVersion(t,n,i,o){return this.get(this.fhirUrl(t,n,"_history",i),o)}readPatientEverything(t,n){return this.getBundle(this.fhirUrl("Patient",t,"$everything"),n)}readPatientSummary(t,n){return this.getBundle(this.fhirUrl("Patient",t,"$summary"),n)}createResource(t,n){if(!t.resourceType)throw new Error("Missing resourceType");return this.invalidateSearches(t.resourceType),this.post(this.fhirUrl(t.resourceType),t,void 0,n)}async createResourceIfNoneExist(t,n,i={}){let o=this.fhirUrl(t.resourceType);this.setRequestHeader(i,"If-None-Exist",n);let s=await this.post(o,t,void 0,i);return this.cacheResource(s,i),this.invalidateUrl(this.fhirUrl(t.resourceType,t.id,"_history")),this.invalidateSearches(t.resourceType),s}async upsertResource(t,n,i){let o=this.fhirSearchUrl(t.resourceType,n),s=await this.put(o,t,void 0,i);return s||(s=t),this.cacheResource(s,i),this.invalidateUrl(this.fhirUrl(t.resourceType,t.id,"_history")),this.invalidateSearches(t.resourceType),s}async createAttachment(t,n,i,o,s){let a=ci(t,n,i,o);if(a.contentType===O.XML){let p=a.data,y;p instanceof Blob?y=await new Promise((x,V)=>{let Z=new FileReader;Z.onload=()=>{if(!Z.result){V(new Error("Failed to load file"));return}x(Z.result)},Z.readAsText(p,"utf-8")}):ArrayBuffer.isView(p)?y=new TextDecoder().decode(p):y=p,y.includes("<ClinicalDocument")&&y.includes("urn:hl7-org:v3")&&(a={...a,contentType:O.CDA_XML})}let u=s??(typeof n=="object"?n:{}),l=await this.createBinary(a,u);return{contentType:a.contentType,url:l.url,title:a.filename}}createBinary(t,n,i,o,s){let a=ci(t,n,i,o),u=s??(typeof n=="object"?n:{}),{data:l,contentType:p,filename:y,securityContext:x,onProgress:V}=a,Z=this.fhirUrl("Binary");return y&&Z.searchParams.set("_filename",y),x?.reference&&this.setRequestHeader(u,"X-Security-Context",x.reference),V?this.uploadwithProgress(Z,l,p,V,u):this.post(Z,l,p,u)}uploadwithProgress(t,n,i,o,s){return new Promise((a,u)=>{let l=new XMLHttpRequest,p=()=>l.abort();s?.signal?.addEventListener("abort",p);let y=x=>{s?.signal?.removeEventListener("abort",p),x instanceof Error?u(x):a(x)};if(l.responseType="json",l.onabort=()=>y(new DOMException("Request aborted","AbortError")),l.onerror=()=>y(new Error("Request error")),o&&(l.upload.onprogress=x=>o(x),l.upload.onload=x=>o(x)),l.onload=()=>{l.status>=200&&l.status<300?y(l.response):y(new f(ut(l.response||l.statusText)))},l.open("POST",t),l.withCredentials=!0,l.setRequestHeader("Authorization","Bearer "+this.accessToken),l.setRequestHeader("Cache-Control","no-cache, no-store, max-age=0"),l.setRequestHeader("Content-Type",i),this.options.extendedMode!==!1&&l.setRequestHeader("X-Medplum","extended"),s?.headers){let x=s.headers;for(let[V,Z]of Object.entries(x))l.setRequestHeader(V,Z)}l.send(n)})}async createPdf(t,n,i,o){if(!this.createPdfImpl)throw new Error("PDF creation not enabled");let s=rs(t,n,i,o),a=typeof n=="object"?n:{},{docDefinition:u,tableLayouts:l,fonts:p,...y}=s,x=await this.createPdfImpl(u,l,p),V={...y,data:x,contentType:"application/pdf"};return this.createBinary(V,a)}createComment(t,n,i){let o=this.getProfile(),s,a;return t.resourceType==="Encounter"&&(s=Te(t),a=t.subject),t.resourceType==="ServiceRequest"&&(s=t.encounter,a=t.subject),t.resourceType==="Patient"&&(a=Te(t)),this.createResource({resourceType:"Communication",status:"completed",basedOn:[Te(t)],encounter:s,subject:a,sender:o?Te(o):void 0,sent:new Date().toISOString(),payload:[{contentString:n}]},i)}async updateResource(t,n){if(!t.resourceType)throw new Error("Missing resourceType");if(!t.id)throw new Error("Missing id");let i=await this.put(this.fhirUrl(t.resourceType,t.id),t,void 0,n);return i||(i=t),this.cacheResource(i,n),this.invalidateUrl(this.fhirUrl(t.resourceType,t.id,"_history")),this.invalidateSearches(t.resourceType),i}async patchResource(t,n,i,o){let s=await this.patch(this.fhirUrl(t,n),i,o);return this.cacheResource(s,o),this.invalidateUrl(this.fhirUrl(t,n,"_history")),this.invalidateSearches(t),s}deleteResource(t,n,i){return this.deleteCacheEntry(this.fhirUrl(t,n).toString()),this.invalidateSearches(t),this.delete(this.fhirUrl(t,n),i)}validateResource(t,n){return this.post(this.fhirUrl(t.resourceType,"$validate"),t,void 0,n)}executeBot(t,n,i,o){let s;if(typeof t=="string"){let a=t;s=this.fhirUrl("Bot",a,"$execute")}else{let a=t;s=this.fhirUrl("Bot","$execute"),s.searchParams.set("identifier",a.system+"|"+a.value)}return this.post(s,n,i,o)}executeBatch(t,n){return this.post(this.fhirBaseUrl,t,void 0,n)}sendEmail(t,n){return this.post("email/v1/send",t,O.JSON,n)}graphql(t,n,i,o){return this.post(this.fhirUrl("$graphql"),{query:t,operationName:n,variables:i},O.JSON,o)}readResourceGraph(t,n,i,o){return this.get(`${this.fhirUrl(t,n)}/$graph?graph=${i}`,o)}pushToAgent(t,n,i,o,s,a){let{waitTimeout:u,returnAck:l,...p}=a??{};return this.post(this.fhirUrl("Agent",be(t),"$push"),{destination:typeof n=="string"?n:A(n),body:i,contentType:o,waitForResponse:s,...u!==void 0?{waitTimeout:u}:void 0,...l!==void 0?{returnAck:l}:void 0},O.FHIR_JSON,p)}getCdsServices(t){return this.get(this.cdsServicesUrl,t)}callCdsService(t,n,i){return this.post(F(this.cdsServicesUrl,t),n,O.JSON,i)}getActiveLogin(){return this.storage.getObject("activeLogin")}async setActiveLogin(t){(!this.sessionDetails?.profile||A(this.sessionDetails.profile)!==t.profile?.reference)&&this.clearActiveLogin(),this.setAccessToken(t.accessToken,t.refreshToken),this.storage.setObject("activeLogin",t),this.addLogin(t),this.refreshPromise=void 0,await this.refreshProfile()}getAccessToken(){return this.accessToken}isAuthenticated(t){return this.accessTokenExpires!==void 0&&Date.now()<this.accessTokenExpires-(t??this.refreshGracePeriod)}setAccessToken(t,n){this.accessToken=t,this.refreshToken=n,this.accessTokenExpires=oi(t),this.medplumServer=ii(t)}getLogins(){return this.storage.getObject("logins")??[]}addLogin(t){let n=this.getLogins().filter(i=>i.profile?.reference!==t.profile?.reference);n.push(t),this.storage.setObject("logins",n)}async refreshProfile(){if(this.medplumServer)return this.profilePromise=new Promise((t,n)=>{this.get("auth/me",{cache:"no-cache"}).then(i=>{this.profilePromise=void 0;let o=this.sessionDetails?.profile?.id!==i.profile.id;this.sessionDetails=i,o&&this.dispatchEvent({type:"change"}),t(i.profile),this.dispatchEvent({type:"profileRefreshed"})}).catch(n)}),this.dispatchEvent({type:"profileRefreshing"}),this.profilePromise}isLoading(){return!this.isInitialized||!!this.profilePromise&&!this.sessionDetails?.profile}isSuperAdmin(){return!!this.sessionDetails?.project.superAdmin}isProjectAdmin(){return!!this.sessionDetails?.membership.admin}getProject(){return this.sessionDetails?.project}getProjectMembership(){return this.sessionDetails?.membership}getProfile(){return this.sessionDetails?.profile}async getProfileAsync(){return this.profilePromise?this.profilePromise:this.sessionDetails?this.sessionDetails.profile:this.refreshProfile()}getUserConfiguration(){return this.sessionDetails?.config}getAccessPolicy(){return this.sessionDetails?.accessPolicy}async download(t,n={}){return(await this.downloadResponse(t,n)).blob()}async downloadResponse(t,n={}){this.refreshPromise&&await this.refreshPromise;let i=t.toString();i.startsWith(ul)&&(t=this.fhirUrl(i));let o=n.headers;return o||(o={},n.headers=o),o.Accept||(o.Accept="*/*"),this.addFetchOptionsDefaults(n),this.fetchWithRetry(t.toString(),n)}async createMedia(t,n){let{additionalFields:i,...o}=t,s=await this.createResource({resourceType:"Media",status:"preparation",content:{contentType:t.contentType},...i});o.securityContext||(o.securityContext=Te(s));let a=await this.createAttachment(o,n);return this.updateResource({...s,status:"completed",content:a})}async uploadMedia(t,n,i,o,s){return this.createMedia({data:t,contentType:n,filename:i,additionalFields:o},s)}async createDocumentReference(t,n){let{additionalFields:i,...o}=t,s=await this.createResource({resourceType:"DocumentReference",status:"current",content:[{attachment:{contentType:t.contentType}}],...i});o.securityContext||(o.securityContext=Te(s));let a=await this.createAttachment(o,n);return this.updateResource({...s,content:[{attachment:a}]})}async bulkExport(t="",n,i,o){let s=t&&`${t}/`,a=this.fhirUrl(`${s}$export`);return n&&a.searchParams.set("_type",n),i&&a.searchParams.set("_since",i),this.startAsyncRequest(a.toString(),o)}async startAsyncRequest(t,n={}){this.addFetchOptionsDefaults(n);let i=n.headers;return i.Prefer="respond-async",this.request("POST",t,n)}get keyValue(){return this.keyValueClient||(this.keyValueClient=new Wt(this)),this.keyValueClient}getBundle(t,n){return new U((async()=>{let i=await this.get(t,n);for(let o of i.entry??g)this.cacheResource(o.resource,n);return i})())}isCacheEnabled(t){return!!this.requestCache&&!this.getRequestHeader(t,"x-medplum-on-behalf-of")}getCacheEntry(t,n){if(!this.isCacheEnabled(n)||n?.cache==="no-cache"||n?.cache==="reload")return;let i=this.requestCache.get(t);if(!(!i||i.requestTime+this.cacheTime<Date.now()))return i}setCacheEntry(t,n,i){this.isCacheEnabled(i)&&(this.requestCache.set(t,{requestTime:Date.now(),value:n}),i?.signal&&i.signal.addEventListener("abort",()=>{this.requestCache.delete(t)}))}cacheResource(t,n){t?.id&&!t.meta?.tag?.some(i=>i.code==="SUBSETTED")&&this.setCacheEntry(this.fhirUrl(t.resourceType,t.id).toString(),new U(Promise.resolve(t)),n)}deleteCacheEntry(t){this.requestCache&&this.requestCache.delete(t)}async request(t,n,i={},o={}){await this.refreshIfExpired(),i.method=t,this.addFetchOptionsDefaults(i);let s=await this.fetchWithRetry(n,i);if(s.status===401)return this.handleUnauthenticated(t,n,i);if(s.status===204||s.status===304)return;let u=s.headers.get("content-type")?.includes("json");if(s.status===404&&!u)throw new f(sn);let l=await this.parseBody(s,u);if(s.status===200&&i.followRedirectOnOk||s.status===201&&i.followRedirectOnCreated){let p=await Yo(s,l);if(p)return this.request("GET",p,{...i,body:void 0})}if(s.status===202&&i.pollStatusOnAccepted){let y=await Yo(s,l)??o.statusUrl;if(y)return this.pollStatus(y,i,o)}if(s.status>=400)throw new f(ut(l));return l}async parseBody(t,n){let i;if(t.headers.get("content-length")!=="0"){if(n)try{i=await t.json()}catch(o){throw console.error("Error parsing response",t.status,o),o}else i=await t.text();return i}}async fetchWithRetry(t,n){t.startsWith("http")||(t=F(this.baseUrl,t));let i=n?.maxRetries??this.maxRetries;for(let o=0;o<=i;o++)try{this.logLevel!=="none"&&this.logRequest(t,n);let s=await this.fetch(t,n);if(this.logLevel!=="none"&&this.logResponse(s),this.setCurrentRateLimit(s),o>=i||!hl(s))return s;let a=this.getRetryDelay(o),u=n.maxRetryTime??this.maxRetryTime;if(a>u)return s;await Er(a,{signal:n.signal})}catch(s){if(s.message==="Failed to fetch"&&o===0&&this.dispatchEvent({type:"offline"}),s.name==="AbortError"||o===i)throw s}throw new Error("Unreachable")}logRequest(t,n){if(console.log(`> ${n.method} ${t}`),this.logLevel==="verbose"&&n.headers){let i=n.headers;for(let o of vt(Object.keys(i)))console.log(`> ${o}: ${i[o]}`)}}logResponse(t){console.log(`< ${t.status} ${t.statusText}`),this.logLevel==="verbose"&&t.headers&&t.headers.forEach((n,i)=>console.log(`< ${i}: ${n}`))}setCurrentRateLimit(t){if(!t?.headers||typeof t.headers.get!="function")return;let n=t.headers.get("ratelimit");n&&(this.currentRateLimits=n)}rateLimitStatus(){if(!this.currentRateLimits)return[];let t=this.currentRateLimits;return t.split(",").map(n=>{let i=n.split(";").map(p=>p.trim());if(i.length!==3)throw new Error("Could not parse RateLimit header: "+t);let o=i[0].substring(1,i[0].length-1),s=i.find(p=>p.startsWith("r="))?.substring(2),a=s?Number.parseInt(s,10):Number.NaN,u=i.find(p=>p.startsWith("t="))?.substring(2),l=u?Number.parseInt(u,10):Number.NaN;if(!o||Number.isNaN(a)||Number.isNaN(l))throw new Error("Could not parse RateLimit header: "+t);return{name:o,remainingUnits:a,secondsUntilReset:l,resetsAfter:Math.ceil((Date.now()+1e3*l)/1e3)}})}getRetryDelay(t){let n=this.rateLimitStatus(),i=500*Math.pow(1.5,t);for(let o of n)o.remainingUnits||(i=Math.max(i,o.secondsUntilReset*1e3));return i}async pollStatus(t,n,i){let o={...n,method:"GET",body:void 0,redirect:"follow"};if(i.pollCount===void 0)n.headers&&typeof n.headers=="object"&&"Prefer"in n.headers&&(o.headers={...n.headers},delete o.headers.Prefer),i.statusUrl=t,i.pollCount=1;else{let s=n.pollStatusPeriod??1e3;await Er(s,{signal:n.signal}),i.pollCount++}return this.request("GET",t,o,i)}async executeAutoBatch(){if(this.autoBatchQueue===void 0)return;let t=[...this.autoBatchQueue];if(this.autoBatchQueue.length=0,this.autoBatchTimerId=void 0,t.length===1){let o=t[0];try{o.resolve(await this.request(o.method,F(this.fhirBaseUrl,o.url),o.options))}catch(s){o.reject(new f(ut(s)))}return}let n={resourceType:"Bundle",type:"batch",entry:t.map(o=>({request:{method:o.method,url:o.url},resource:o.options.body?JSON.parse(o.options.body):void 0}))},i=await this.post(this.fhirBaseUrl,n);for(let o=0;o<t.length;o++){let s=t[o],a=i.entry?.[o];a?.response?.outcome&&!sr(a.response.outcome)?s.reject(new f(a.response.outcome)):s.resolve(a?.resource)}}addFetchOptionsDefaults(t){Object.entries(this.defaultHeaders).forEach(([n,i])=>{this.setRequestHeader(t,n,i)}),this.setRequestHeader(t,"Accept",Zo,!0),this.options.extendedMode!==!1&&this.setRequestHeader(t,"X-Medplum","extended"),t.body&&this.setRequestHeader(t,"Content-Type",O.FHIR_JSON,!0),this.accessToken?this.setRequestHeader(t,"Authorization","Bearer "+this.accessToken):this.basicAuth&&this.setRequestHeader(t,"Authorization","Basic "+this.basicAuth),t.cache||(t.cache="no-cache"),t.credentials||(t.credentials="include")}setRequestContentType(t,n){this.setRequestHeader(t,"Content-Type",n)}getRequestHeader(t,n){let i=t?.headers;if(i)if(Array.isArray(i)){let o=i.find(([s])=>s.toLowerCase()===n.toLowerCase());return o?o[1]:void 0}else{if(i instanceof Headers)return i.get(n)??void 0;if(E(i))return i[n]??void 0}else return}setRequestHeader(t,n,i,o=!1){let s=t.headers;s?Array.isArray(s)?(!o||!s.some(([a])=>a.toLowerCase()===n.toLowerCase()))&&s.push([n,i]):s instanceof Headers?(!o||!s.has(n))&&s.set(n,i):E(s)&&(!o||!s[n])&&(s[n]=i):t.headers={[n]:i}}setRequestBody(t,n){typeof n=="string"||typeof Blob<"u"&&(n instanceof Blob||n?.constructor.name==="Blob")||typeof File<"u"&&(n instanceof File||n?.constructor.name==="File")||typeof Uint8Array<"u"&&(n instanceof Uint8Array||n?.constructor.name==="Uint8Array")?t.body=n:typeof n=="object"&&n!==null&&(typeof n.getReader=="function"||typeof n.pipe=="function"&&typeof n.on=="function")?(t.body=n,t.duplex="half"):n&&(t.body=JSON.stringify(n))}async handleUnauthenticated(t,n,i){if(this.refresh())return this.request(t,n,i);throw this.clear(),this.onUnauthenticated?.(),new f(we)}async startPkce(){let t=Or();sessionStorage.setItem("pkceState",t);let n=Or().slice(0,128);sessionStorage.setItem("codeVerifier",n);try{let i=await Zn(n);return{codeChallengeMethod:"S256",codeChallenge:Ln(i).replaceAll("+","-").replaceAll("/","_").replaceAll("=","")}}catch(i){return console.warn("Failed to hash code verifier. Falling back to 'plain' code challenge method",i),{codeChallengeMethod:"plain",codeChallenge:n}}}async requestAuthorization(t){let n=await this.ensureCodeChallenge(t??{}),i=new URL(this.authorizeUrl);i.searchParams.set("response_type","code"),i.searchParams.set("state",sessionStorage.getItem("pkceState")),i.searchParams.set("client_id",n.clientId??this.clientId),i.searchParams.set("redirect_uri",n.redirectUri??oe.getOrigin()),i.searchParams.set("code_challenge_method",n.codeChallengeMethod),i.searchParams.set("code_challenge",n.codeChallenge),i.searchParams.set("scope",n.scope??"openid profile"),oe.assign(i.toString())}processCode(t,n){let i={grant_type:Be.AuthorizationCode,code:t,client_id:n?.clientId??this.clientId??"",redirect_uri:n?.redirectUri??oe.getOrigin()};if(typeof sessionStorage<"u"){let o=sessionStorage.getItem("codeVerifier");o&&(i.code_verifier=o)}return this.fetchTokens(i)}refreshIfExpired(t){return!this.refreshPromise&&this.accessTokenExpires!==void 0&&!this.isAuthenticated(t)&&this.refresh(),this.refreshPromise??Promise.resolve()}refresh(){if(this.refreshPromise)return this.refreshPromise;if(this.refreshToken)return this.refreshPromise=this.fetchTokens({grant_type:Be.RefreshToken,client_id:this.clientId??"",refresh_token:this.refreshToken}),this.refreshPromise;if(this.clientId&&this.clientSecret)return this.refreshPromise=this.startClientLogin(this.clientId,this.clientSecret),this.refreshPromise}async startClientLogin(t,n){return this.clientId=t,this.clientSecret=n,this.fetchTokens({grant_type:Be.ClientCredentials,client_id:t,client_secret:n})}async startJwtBearerLogin(t,n,i){return this.clientId=t,this.fetchTokens({grant_type:Be.JwtBearer,client_id:t,assertion:n,scope:i})}async startJwtAssertionLogin(t){return this.fetchTokens({grant_type:Be.ClientCredentials,client_assertion_type:ts.JwtBearer,client_assertion:t})}setBasicAuth(t,n){this.clientId=t,this.clientSecret=n,this.basicAuth=Nt(t+":"+n)}setLogLevel(t){this.logLevel=t,this.options.verbose=t==="verbose"}getLogLevel(){return this.logLevel}setVerbose(t){this.logLevel=t?"verbose":"none",this.options.verbose=t}async fhircastSubscribe(t,n){if(!(typeof t=="string"&&t!==""))throw new f(v("Invalid topic provided. Topic must be a valid string."));if(!(typeof n=="object"&&Array.isArray(n)&&n.length>0))throw new f(v("Invalid events provided. Events must be an array of event names containing at least one event."));let i={channelType:"websocket",mode:"subscribe",topic:t,events:n},s=(await this.post(this.fhircastHubUrl,Dr(i),O.FORM_URL_ENCODED))["hub.channel.endpoint"];if(!s)throw new Error("Invalid response!");return i.endpoint=s,i}async fhircastUnsubscribe(t){if(!Bt(t))throw new f(v("Invalid topic or subscriptionRequest. SubscriptionRequest must be an object."));if(!(t.endpoint&&typeof t.endpoint=="string"&&t.endpoint.startsWith("ws")))throw new f(v("Provided subscription request must have an endpoint in order to unsubscribe."));t.mode="unsubscribe",await this.post(this.fhircastHubUrl,Dr(t),O.FORM_URL_ENCODED)}fhircastConnect(t){return new Ut(t)}async fhircastPublish(t,n,i,o){return ei(n)?this.post(this.fhircastHubUrl,Mr(t,n,i,o),O.JSON):(ti(n),this.post(this.fhircastHubUrl,Mr(t,n,i),O.JSON))}async fhircastGetContext(t){return this.get(`${this.fhircastHubUrl}/${t}`,{cache:"no-cache"})}async invite(t,n){return this.post("admin/projects/"+t+"/invite",n)}async handleTokenError(t){try{let n=await t.json();throw je(n)?new f(n):n.error_description?new f(R(n.error_description)):new Error(JSON.stringify(n))}catch(n){throw n instanceof f?(n.message=`Failed to fetch tokens: ${n.message}`,n):new f(R("Failed to fetch tokens"),{cause:n})}}async fetchTokens(t){let n=new URLSearchParams(t),i={...this.defaultHeaders,"Content-Type":O.FORM_URL_ENCODED};this.basicAuth&&(i.Authorization=`Basic ${this.basicAuth}`),this.credentialsInHeader&&(n.delete("client_id"),n.delete("client_secret"),!this.basicAuth&&t.client_id&&t.client_secret&&(i.Authorization=`Basic ${Nt(t.client_id+":"+t.client_secret)}`));let o={method:"POST",headers:i,body:n.toString(),credentials:"include"},s;try{s=await this.fetchWithRetry(this.tokenUrl,o)}catch(u){throw this.refreshPromise=void 0,u}s.ok||(this.clearActiveLogin(),this.onUnauthenticated?.(),await this.handleTokenError(s));let a=await s.json();return await this.verifyTokens(a),this.getProfile()}async verifyTokens(t){let n=t.access_token;if(ni(n)){let i=qt(n);if(Date.now()>=i.exp*1e3)throw this.clearActiveLogin(),new f(an);if(i.cid){if(i.cid!==this.clientId)throw this.clearActiveLogin(),new f(ir)}else if(this.clientId&&i.client_id!==this.clientId)throw this.clearActiveLogin(),new f(ir)}return this.setActiveLogin({accessToken:n,refreshToken:t.refresh_token,project:t.project,profile:t.profile})}checkSessionDetailsMatchLogin(t){return this.sessionDetails&&t?t.profile?.reference?.endsWith(this.sessionDetails.profile.id)??!1:!0}setupStorageListener(){try{window.addEventListener("storage",t=>{if(t.key===null)oe.reload();else if(t.key===this.storage.makeKey("activeLogin")){let n=t.oldValue?JSON.parse(t.oldValue):void 0,i=t.newValue?JSON.parse(t.newValue):void 0;n?.profile.reference!==i?.profile.reference||!this.checkSessionDetailsMatchLogin(i)?oe.reload():i?this.setAccessToken(i.accessToken,i.refreshToken):this.clear()}})}catch{}}getSubscriptionManager(){return this.subscriptionManager||(this.subscriptionManager=new Gt(this,Bn(this.baseUrl,"/ws/subscriptions-r4"))),this.subscriptionManager}subscribeToCriteria(t,n){return this.getSubscriptionManager().addCriteria(t,n)}unsubscribeFromCriteria(t,n){this.subscriptionManager&&this.subscriptionManager.removeCriteria(t,n)}getMasterSubscriptionEmitter(){return this.getSubscriptionManager().getMasterEmitter()}};function pl(){if(!globalThis.fetch)throw new Error("Fetch not available in this environment");return globalThis.fetch.bind(globalThis)}async function Yo(r,e){let t=r.headers.get("content-location");if(t)return t;let n=r.headers.get("location");if(n)return n;if(je(e)&&e.issue?.[0]?.diagnostics)return e.issue[0].diagnostics}function Xo(r){let e=r.entry?.map(t=>t.resource)??[];return Object.assign(e,{bundle:r})}function fl(r){return E(r)&&"data"in r&&"contentType"in r}function ci(r,e,t,n){return fl(r)?r:{data:r,filename:e,contentType:t,onProgress:n}}function ml(r){return E(r)&&"docDefinition"in r}function rs(r,e,t,n){return ml(r)?r:{docDefinition:r,filename:e,tableLayouts:t,fonts:n}}function hl(r){return r.status===429||r.status>=500}var yl={aws_ssm_parameter_store:"aws_ssm_parameter_store"};function gl(r,e,t){let n=new Nr;Array.isArray(r)||(r=r.entry?.map(i=>i.resource)??[]);for(let i of r)n.addObservation(i);return n.summarize(e,t)}var Nr=class{constructor(e){c(this,"code");c(this,"unit");c(this,"sampling");c(this,"dataPoints");this.dataPoints=[],this.code=e?.code,this.unit=e?.unit,this.sampling=e?.sampling}addObservation(e){if(!this.code)this.code=e.code;else if(!xl(this.code,e.code))throw new Error("Observation does not match code of sampled data");e.valueQuantity?.value!==void 0?(this.checkUnit(e.valueQuantity),this.addData(e.valueQuantity.value)):e.valueInteger!==void 0?this.addData(e.valueInteger):e.valueSampledData?.data&&(this.checkUnit(e.valueSampledData.origin),this.addData(...ui(e.valueSampledData)))}addData(...e){this.dataPoints.push(...e)}checkUnit(e){if(!this.unit)this.unit=e;else if(e.code&&e.system){if(this.unit.system!==e.system||this.unit.code!==e.code)throw new Error("Incorrect unit for Observation")}else if(e.unit&&this.unit.unit!==e.unit)throw new Error("Incorrect unit for Observation")}summarize(e,t){if(!this.code)throw new Error("Code is required for data points");let n=t(this.dataPoints);return{resourceType:"Observation",status:"final",code:e,valueQuantity:typeof n=="number"?{...this.unit,value:n}:n,component:[{code:this.code,valueSampledData:{origin:{...this.unit,value:0},dimensions:1,period:0,...this.sampling,data:vl(this.dataPoints,this.sampling)}}]}}};function xl(r,e){return!!r.coding?.some(t=>e.coding?.some(n=>t.system===n.system&&t.code===n.code))}function ui(r){return r.data?.split(" ").map(e=>Number.parseFloat(e)*(r.factor??1)+(r.origin.value??0))??[]}function vl(r,e){if(r.length)return r.map(t=>(t-(e?.origin.value??0))/(e?.factor??1)).join(" ")}function Tl(r){let e=[],t=r.effectiveInstant??r.effectiveDateTime??r.effectivePeriod?.start,n=t?Date.parse(t).valueOf():0;r.valueSampledData&&e.push(...ns(r.valueSampledData,n,r));for(let i of r.component??g)i.valueSampledData&&e.push(...ns(i.valueSampledData,n,{...r,...i}));return e}function ns(r,e,t){let n=[],i=ui(r),o=A(t);for(let s=0;s<i.length;s++){let a=i[s],u=e+Math.floor(s/r.dimensions)*r.period;n.push({...t,id:void 0,effectiveInstant:void 0,effectivePeriod:void 0,effectiveTiming:void 0,effectiveDateTime:u?new Date(u).toISOString():void 0,valueQuantity:{...r.origin,value:a},valueSampledData:void 0,component:void 0,derivedFrom:o?[...t.derivedFrom??[],{reference:o}]:t.derivedFrom})}return n}function Br({parentContext:r,path:e,elements:t,profileUrl:n,debugMode:i,accessPolicyResource:o}){if(e===r?.path)return;i??=r?.debugMode??!1,o??=r?.accessPolicyResource;let s=bl(e,t,r,!!i),a=_e(e,".",2)[1];s=Sl(s,o,a),s=El(s,o,a);let u=Object.create(null);for(let[p,y]of Object.entries(s))u[e+"."+p]=y;let l;if(r&&!r.isDefaultContext)l=r.getExtendedProps;else{let p=Object.create(null);l=y=>{let x=_e(y,".",2)[1];if(x){if(!p[x]){let V=Ur(x,o?.hiddenFields);p[x]={hidden:V,readonly:V||Ur(x,o?.readonlyFields)}}return p[x]}}}return{path:e,elements:s,elementsByPath:u,profileUrl:n??r?.profileUrl,debugMode:i,getExtendedProps:l,accessPolicyResource:o}}function bl(r,e,t,n){let i=Object.create(null);if(t)for(let[s,a]of Object.entries(t.elementsByPath)){let u=pe(r,s);u!==void 0&&(i[u]=a)}let o=!1;if(e)for(let[s,a]of Object.entries(e))s in i||(i[s]=a,o=!0);return n&&console.assert(o,"Unnecessary ElementsContext; not using any newly provided elements"),i}function Sl(r,e,t){if(!e?.hiddenFields?.length)return r;let n=t?t+".":"";return Object.fromEntries(Object.entries(r).filter(([i])=>!Ur(n+i,e.hiddenFields)))}function El(r,e,t){if(!e?.readonlyFields?.length)return r;let n=Object.create(null),i=t?t+".":"";for(let[o,s]of Object.entries(r))Ur(i+o,e.readonlyFields)?n[o]={...s,readonly:!0}:n[o]=s;return n}function Ur(r,e){if(!e?.length)return!1;let t=r.split(".");for(let n=1;n<=t.length;n++){let i=t.slice(0,n).join(".");if(e.includes(i))return!0}return!1}function li(r){return r.type!==void 0&&r.type.length>0}function Rl(r,e,t,n){let i=ke(r,e.path,{profileUrl:n});if(i){let o=t.typeSchema?.elements??t.elements;return i.some(s=>hr(s,e,t,o))??!1}return console.assert(!1,"getNestedProperty[%s] in isDiscriminatorComponentMatch missed",e.path),!1}function di(r,e,t,n){if(r)for(let i of e){let o={value:r,type:i.typeSchema?.type??i.type?.[0].code};if(t.every(s=>Rl(o,s,i,i.typeSchema?.url??n)))return i.name}}var Qt=class{constructor(e,t,n){c(this,"rootSchema");c(this,"visitor");c(this,"elementsContextStack");c(this,"sliceAllowList");if(e.type===void 0)throw new Error("schema must include a type");this.rootSchema=e;let i=Br({parentContext:void 0,path:this.rootSchema.type,elements:n??this.rootSchema.elements,profileUrl:this.rootSchema.name===this.rootSchema.type?void 0:this.rootSchema.url});if(i===void 0)throw new Error("Could not create root elements context");this.elementsContextStack=[i],this.visitor=t}get elementsContext(){return this.elementsContextStack.at(-1)}crawlElement(e,t,n){this.visitor.onEnterSchema&&this.visitor.onEnterSchema(this.rootSchema);let i=Object.fromEntries(Object.entries(this.elementsContext.elements).filter(([o])=>o.startsWith(t)));this.crawlElementsImpl(i,n),this.visitor.onExitSchema&&this.visitor.onExitSchema(this.rootSchema)}crawlSlice(e,t,n){let i=this.prepareSlices(n.slices,n);if(!te(i.slices))throw new Error(`cannot crawl slice ${t.name} since it has no type information`);this.visitor.onEnterSchema&&this.visitor.onEnterSchema(this.rootSchema),this.sliceAllowList=[t],this.crawlSliceImpl(i.slices[0],t.path,i),this.sliceAllowList=void 0,this.visitor.onExitSchema&&this.visitor.onExitSchema(this.rootSchema)}crawlResource(){this.visitor.onEnterSchema&&this.visitor.onEnterSchema(this.rootSchema),this.crawlElementsImpl(this.rootSchema.elements,this.rootSchema.type),this.visitor.onExitSchema&&this.visitor.onExitSchema(this.rootSchema)}crawlElementsImpl(e,t){let n=Cl(e);for(let i of n)this.crawlElementNode(i,t)}crawlElementNode(e,t){let n=t+"."+e.key;this.visitor.onEnterElement&&this.visitor.onEnterElement(n,e.element,this.elementsContext);for(let i of e.children)this.crawlElementNode(i,t);te(e.element?.slicing?.slices)&&this.crawlSlicingImpl(e.element.slicing,n),this.visitor.onExitElement&&this.visitor.onExitElement(n,e.element,this.elementsContext)}prepareSlices(e,t){let n=[];for(let o of e){if(!li(o))continue;let s=o.type.find(a=>te(a.profile))?.profile?.[0];if(te(s)){let a=vn(s);a&&(o.typeSchema=a)}n.push(o)}return{...t,slices:n}}crawlSlicingImpl(e,t){let n=this.prepareSlices(e.slices,e);for(let i of n.slices)(this.sliceAllowList===void 0||this.sliceAllowList.includes(i))&&this.crawlSliceImpl(i,t,n)}crawlSliceImpl(e,t,n){let i=e.typeSchema;i&&this.visitor.onEnterSchema&&this.visitor.onEnterSchema(i),this.visitor.onEnterSlice&&this.visitor.onEnterSlice(t,e,n);let o,s=i?.elements??e.elements;te(s)&&(o=Br({path:t,parentContext:this.elementsContext,elements:s})),o&&this.elementsContextStack.push(o),this.crawlElementsImpl(s,t),o&&this.elementsContextStack.pop(),this.visitor.onExitSlice&&this.visitor.onExitSlice(t,e,n),i&&this.visitor.onExitSchema&&this.visitor.onExitSchema(i)}};function Cl(r){let e=[];function t(o,s){return s.startsWith(o+".")}function n(o,s){for(let a of o.children)if(t(a.key,s.key)){n(a,s);return}o.children.push(s)}let i=Object.entries(r);i.sort((o,s)=>o[0].localeCompare(s[0]));for(let[o,s]of i){let a={key:o,element:s,children:[]},u=!1;for(let l of e)if(t(l.key,o)){n(l,a),u=!0;break}u||e.push(a)}return e}var qr="__sliceName";function Pl(r,e){let t=new Wr(r,r.resourceType,"resource");return new Qt(e,t).crawlResource(),t.getDefaultValue()}function Al(r,e,t){for(let[n,i]of Object.entries(e)){if(t===void 0||t===n){zt(r,n,i,e);continue}let o=pe(t,n);o!==void 0&&zt(r,o,i,e)}return r}function wl(r,e,t,n){let i=new Wr([{[qr]:e.name}],e.path,"element");return new Qt(n,i).crawlSlice(r,e,t),i.getDefaultValue()[0]}var Wr=class{constructor(e,t,n){c(this,"rootValue");c(this,"schemaStack");c(this,"valueStack");this.schemaStack=[],this.valueStack=[],this.rootValue=Se(e),this.valueStack.splice(0,this.valueStack.length,{type:n,path:t,values:[this.rootValue]})}get schema(){return this.schemaStack.at(-1)}get value(){return this.valueStack.at(-1)}onEnterSchema(e){this.schemaStack.push(e)}onExitSchema(){this.schemaStack.pop()}onEnterElement(e,t,n){let i=this.value.values,o=this.value.path,s=pe(o,e);if(s===void 0)throw new Error(`Expected ${e} to be prefixed by ${o}`);let a=[];for(let u of i){if(u===void 0)continue;let l=pe(n.path,o),p=Array.isArray(u)?u:[u];for(let y of p){Ol(y,s,t,n.elements,l),zt(y,s,t,n.elements);let x=fi(y,s,n.elements,l);x!==void 0&&a.push(x)}}this.valueStack.push({type:"element",path:e,values:a})}onExitElement(e,t,n){if(!this.valueStack.pop())throw new Error("Expected value context to exist when exiting element");let o=pe(this.value.path,e);if(o===void 0)throw new Error(`Expected ${e} to be prefixed by ${this.value.path}`);let s=pe(n.path,this.value.path);for(let a of this.value.values){let u=fi(a,o,n.elements,s);if(Array.isArray(u))for(let l=u.length-1;l>=0;l--){let p=u[l];te(p)||u.splice(l,1)}C(u)&&pi(a,void 0,o,t)}}onEnterSlice(e,t,n){let i=this.value.values,o=[];for(let s of i)if(s!==void 0){let a=Array.isArray(s)?s:[s],u=this.getMatchingSliceValues(a,t,n);o.push(u)}this.valueStack.push({type:"slice",path:e,values:o})}getMatchingSliceValues(e,t,n){let i=[];for(let o of e)(o[qr]??di(o,[t],n.discriminator,this.schema.url))===t.name&&i.push(o);for(let o=i.length;o<t.min;o++)if(Sr(t.type[0].code)){let s=Object.create(null);i.push(s),e.push(s)}return i}onExitSlice(){let e=this.valueStack.pop();if(!e)throw new Error("Expected value context to exist in onExitSlice");for(let t of e.values)for(let n=t.length-1;n>=0;n--){let i=t[n];qr in i&&delete i[qr]}}getDefaultValue(){return this.rootValue}};function Ol(r,e,t,n,i){let o=fi(r,e,n,i);t.min>0&&o===void 0&&Sr(t.type[0].code)&&(t.isArray?pi(r,[Object.create(null)],e,t):pi(r,Object.create(null),e,t))}function pi(r,e,t,n){if(t.includes("."))throw new Error("key cannot be nested");let i=t;if(t.includes("[x]")){let o=n.type[0].code;i=t.replace("[x]",M(o))}e===void 0?delete r[i]:r[i]=e}function fi(r,e,t,n){let i=e.split("."),o=r,s;for(let a=0;a<i.length;a++){let u=i[a];if(u.includes("[x]")){let l=(n?n+".":"")+i.slice(0,a+1).join("."),y=t[l].type[0].code;u=u.replace("[x]",M(y))}if(a===i.length-1){Array.isArray(o)?s=o.map(l=>l[u]):s=o[u];continue}if(Array.isArray(o))o=o.map(l=>l[u]);else if(E(o)){if(o[u]===void 0)return;o=o[u]}else return}return s}function zt(r,e,t,n){if(!(t.fixed||t.pattern))return r;if(Array.isArray(r))return r.map(a=>zt(a,e,t,n));r==null&&(r=Object.create(null));let i=r,o=e.split("."),s=i;for(let a=0;a<o.length;a++){let u=o[a];if(u.includes("[x]")){let p=n[o.slice(0,a+1).join(".")].type[0].code;u=u.replace("[x]",M(p))}if(a===o.length-1){let l=Array.isArray(s)?s:[s];for(let p of l)t.fixed?p[u]??=t.fixed.value:t.pattern&&(p[u]=is(p[u],t.pattern.value))}else{if(!(u in s)){let l=o.slice(0,a+1).join(".");s[u]=n[l].isArray?[Object.create(null)]:Object.create(null)}s=s[u]}}return i}function is(r,e){if(Array.isArray(e)&&(Array.isArray(r)||r===void 0))return(r?.length??0)>0?r:Se(e);if(E(e)&&(E(r)&&!Array.isArray(r)||r===void 0)){let t=Se(r)??Object.create(null);for(let n of Object.keys(e))t[n]=is(t[n],e[n]);return t}return r}function mi(r,e){if(!r.group)throw new f(R("ConceptMap does not specify a mapping group","ConceptMap.group"));let t=os(e),n=Il(t,e.targetsystem?r.group.filter(o=>o.target===e.targetsystem):r.group),i=n.length>0;return{result:i,match:i?n:void 0}}function os(r){let e=Object.create(null);if(r.code&&!r.coding&&!r.codeableConcept){if(!r.system)throw new f(R("System parameter must be provided with code"));e[r.system]=[r.code]}else if(r.coding&&!r.code&&!r.codeableConcept)r.coding.code&&(e[r.coding.system??""]=[r.coding.code]);else if(r.codeableConcept&&!r.code&&!r.coding)for(let{system:t,code:n}of r.codeableConcept.coding??g)n&&(e[t??""]=z(e[t??""],n));else throw r.code||r.coding||r.codeableConcept?new f(R("Ambiguous input: multiple source codings provided")):new f(R("Source Coding (system + code) must be specified"));return e}function Il(r,e){let t=[];for(let[n,i]of Object.entries(r))for(let o of e.filter(s=>(s.source??"")===n)){let s=o.element?.filter(a=>i.includes(a.code)).flatMap(a=>a.target?.map(u=>({equivalence:u.equivalence,concept:{system:o.target,code:u.code,display:u.display}}))??[]);s?.length||(s=kl(i,o)),s&&t.push(...s)}return t}function kl(r,e){switch(e.unmapped?.mode){case"provided":return r.map(t=>({equivalence:"equal",concept:{system:e.target,code:t}}));case"fixed":return[{equivalence:"equivalent",concept:{system:e.target,code:e.unmapped.code,display:e.unmapped.display}}];default:return}}var Vl=[..._t,"->","<<",">>","=="];function ss(r){return new ge(r,Mt,Vl).tokenize()}var Dl={"-":"disjoint","==":"equal"},hi=class{constructor(e){c(this,"parser");c(this,"structureMap",{resourceType:"StructureMap",status:"active"});this.parser=e}parse(){for(;this.parser.hasMore();){let e=this.parser.peek()?.value;switch(e){case"map":this.parseMap();break;case"uses":this.parseUses();break;case"imports":this.parseImport();break;case"group":this.parseGroup();break;case"conceptmap":this.parseConceptMap();break;default:throw new Error(`Unexpected token: ${e}`)}}return this.structureMap}parseMap(){this.parser.consume("Symbol","map"),this.structureMap.url=this.parser.consume("String").value,this.parser.consume("="),this.structureMap.name=this.parser.consume().value}parseUses(){this.parser.consume("Symbol","uses");let e={};e.url=this.parser.consume("String").value,this.parser.peek()?.value==="alias"&&(this.parser.consume("Symbol","alias"),e.alias=this.parser.consume("Symbol").value),this.parser.consume("Symbol","as"),e.mode=this.parser.consume().value,this.structureMap.structure||(this.structureMap.structure=[]),this.structureMap.structure.push(e)}parseImport(){this.parser.consume("Symbol","imports"),this.structureMap.import||(this.structureMap.import=[]),this.structureMap.import.push(this.parser.consume("String").value)}parseGroup(){let e={};this.parser.consume("Symbol","group"),e.name=this.parser.consume("Symbol").value,e.input=this.parseParameters(),this.parser.peek()?.value==="extends"&&(this.parser.consume("Symbol","extends"),e.extends=this.parser.consume("Symbol").value),this.parser.peek()?.value==="<<"?(this.parser.consume("<<"),e.typeMode=this.parser.consume().value,this.parser.peek()?.value==="+"&&(this.parser.consume("+"),e.typeMode="type-and-types"),this.parser.consume(">>")):e.typeMode="none",e.rule=this.parseRules(),this.structureMap.group||(this.structureMap.group=[]),this.structureMap.group.push(e)}parseParameters(){let e=[];for(this.parser.consume("(");this.parser.hasMore()&&this.parser.peek()?.value!==")";)e.push(this.parseParameter()),this.parser.peek()?.value===","&&this.parser.consume(",");return this.parser.consume(")"),e}parseParameter(){let e={};return e.mode=this.parser.consume().value,e.name=this.parser.consume("Symbol").value,this.parser.peek()?.value===":"&&(this.parser.consume(":"),e.type=this.parser.consume("Symbol").value),e}parseRules(){let e=[];for(this.parser.consume("{");this.parser.hasMore()&&this.parser.peek()?.value!=="}";)e.push(this.parseRule());return this.parser.consume("}"),e}parseRule(){let e={source:this.parseRuleSources()};return this.parser.peek()?.value==="->"&&(this.parser.consume("->"),e.target=this.parseRuleTargets()),this.parser.peek()?.value==="then"&&(this.parser.consume("Symbol","then"),this.parser.peek()?.id==="{"?e.rule=this.parseRules():e.dependent=this.parseRuleDependents()),this.parser.peek()?.id==="String"?e.name=this.parser.consume().value:e.name=e.source?.[0]?.element,this.parser.consume(";"),e}parseRuleSources(){this.parser.hasMore()&&this.parser.peek()?.value==="for"&&this.parser.consume("Symbol","for");let e=[this.parseRuleSource()];for(;this.parser.hasMore()&&this.parser.peek()?.value===",";)this.parser.consume(","),e.push(this.parseRuleSource());return e}parseRuleSource(){let e={},n=this.parseRuleContext().split(".");if(e.context=n[0],e.element=n[1],this.parser.hasMore()&&this.parser.peek()?.value===":"&&(this.parser.consume(":"),e.type=this.parser.consume().value),this.parser.hasMore()&&this.parser.peek()?.value==="default"&&(this.parser.consume("Symbol","default"),e.defaultValueString=this.parser.consume("String").value),(this.parser.peek()?.value==="first"||this.parser.peek()?.value==="not_first"||this.parser.peek()?.value==="last"||this.parser.peek()?.value==="not_last"||this.parser.peek()?.value==="only_one")&&(e.listMode=this.parser.consume().value),this.parser.peek()?.value==="as"&&(this.parser.consume("Symbol","as"),e.variable=this.parser.consume().value),this.parser.peek()?.value==="log"&&(this.parser.consume("Symbol","log"),e.logMessage=this.parser.consume().value),this.parser.peek()?.value==="where"){this.parser.consume("Symbol","where");let i=this.parser.consumeAndParse(T.Arrow);e.condition=i.toString()}if(this.parser.peek()?.value==="check"){this.parser.consume("Symbol","check");let i=this.parser.consumeAndParse(T.Arrow);e.check=i.toString()}return e}parseRuleTargets(){let e=[this.parseRuleTarget()];for(;this.parser.hasMore()&&this.parser.peek()?.value===",";)this.parser.consume(","),e.push(this.parseRuleTarget());return e}parseRuleTarget(){let e={},n=this.parseRuleContext().split(".");return e.contextType="variable",e.context=n[0],e.element=n[1],this.parser.peek()?.value==="="&&(this.parser.consume("="),this.parseRuleTargetTransform(e)),this.parser.peek()?.value==="as"&&(this.parser.consume("Symbol","as"),e.variable=this.parser.consume().value),this.parser.peek()?.value==="share"&&(this.parser.consume("Symbol","share"),e.listMode=["share"],this.parser.consume("Symbol")),(this.parser.peek()?.value==="first"||this.parser.peek()?.value==="last"||this.parser.peek()?.value==="collate")&&(e.listMode=[this.parser.consume().value]),e}parseRuleTargetTransform(e){let t=this.parser.consumeAndParse(T.As);t instanceof ie?(e.transform=t.name,e.parameter=t.args?.map(as)):t instanceof W||t instanceof N?(e.transform="copy",e.parameter=[as(t)]):(e.transform="evaluate",e.parameter=[{valueString:t.toString()}])}parseRuleContext(){let e=this.parser.consume().value;for(;this.parser.peek()?.value===".";)this.parser.consume("."),e+="."+this.parser.consume().value;return e}parseRuleDependents(){let e=this.parser.consumeAndParse(T.Arrow);return[{name:e.name,variable:e.args.map(t=>t.name)}]}parseConceptMap(){this.parser.consume("Symbol","conceptmap");let e={resourceType:"ConceptMap",status:"active",url:"#"+this.parser.consume("String").value};this.parser.consume("{");let t={},n=this.parser.peek()?.value;for(;n!=="}";)n==="prefix"?this.parseConceptMapPrefix(t):this.parseConceptMapRule(e,t),n=this.parser.peek()?.value;this.parser.consume("}"),this.structureMap.contained||(this.structureMap.contained=[]),this.structureMap.contained.push(e)}parseConceptMapPrefix(e){this.parser.consume("Symbol","prefix");let t=this.parser.consume().value;this.parser.consume("=");let n=this.parser.consume().value;e[t]=n}parseConceptMapRule(e,t){let n=this.parser.consume().value,i=t[n];this.parser.consume(":");let o=this.parser.consume().value,s=Dl[this.parser.consume().value],a=this.parser.consume().value,u=t[a];this.parser.consume(":");let l=this.parser.consume().value,p=e?.group?.find(y=>y.source===i&&y.target===u);p||(p={source:i,target:u,element:[]},e.group||(e.group=[]),e.group.push(p)),p.element||(p.element=[]),p.element.push({code:o,target:[{code:l,equivalence:s}]})}};function as(r){if(r instanceof N)return{valueId:r.name};if(r instanceof W)return Ml(r);throw new Error(`Unknown parameter atom type: ${r.constructor.name} (${r.toString()})`)}function Ml(r){switch(r.value.type){case"boolean":return{valueBoolean:r.value.value};case"decimal":return{valueDecimal:r.value.value};case"integer":return{valueInteger:r.value.value};case"dateTime":case"string":return{valueString:r.value.value};default:throw new Error("Unknown target literal type: "+r.value.type)}}var _l=Xe().registerInfix("->",{precedence:T.Arrow}).registerInfix(";",{precedence:T.Semicolon});function Ll(r){let e=_l.construct(ss(r));return e.removeComments(),new hi(e).parse()}var jr=class{constructor(e=[]){c(this,"resources");this.resources=e}get(e,t){let n=[];for(let i of this.resources)i.resourceType===e&&i.url&&this.matchesUrl(i.url,t)&&n.push(i);return n}matchesUrl(e,t){if(t.includes("*")){let n=t.split("*");return e.startsWith(n[0])&&e.endsWith(n[1])}else return e===t}};function Fl(r,e,t=new jr){return Nl({root:r,transformMaps:t},r,e)}function Nl(r,e,t){return Ul(r,e),us(r,e),gi(r,e.group[0],t)}function Ul(r,e){let t=Gr(r);if(t&&e.import)for(let n of e.import){let i=t.get("StructureMap",n);for(let o of i)us(r,o)}}function us(r,e){let t=Gr(r);if(t&&e.contained)for(let n of e.contained)(n.resourceType==="StructureMap"||n.resourceType==="ConceptMap")&&t.resources.push(n);for(let n of e.group??g)$r(r,n.name,{type:"StructureMapGroup",value:n})}function gi(r,e,t){let n=[],i=[];for(let l of e.input)l.mode==="source"&&n.push(l),l.mode==="target"&&i.push(l);if(n.length===0)throw new Error("Missing source definitions");if(i.length===0)throw new Error("Missing target definitions");if(t.length<n.length)throw new Error(`Not enough arguments (got ${t.length}, min ${n.length})`);if(t.length>n.length+i.length)throw new Error(`Too many arguments (got ${t.length}, max ${n.length+i.length})`);let o={},s=[],a=0;for(let l of n)Jt(o,l.name,t[a++]);for(let l of i){let p=t[a++]??{type:l.type??"BackboneElement",value:{}};Jt(o,l.name,p),s.push(p)}let u={root:r.root,parent:r,variables:o};for(let l of e.rule??g)ls(u,l);return s}function ls(r,e){e.source&&ds(r,e,0)}function ds(r,e,t){let n=e.source[t];for(let i of jl(r,n))$r(r,"_",i),n.variable&&$r(r,n.variable,i),t<e.source.length-1?ds(r,e,t+1):Bl(r,e)}function Bl(r,e){if(!ql(r,e)){for(let t of e.target??g)ps(r,t);for(let t of e.rule??g)ls(r,t);for(let t of e.dependent??g)Zl(r,t)}}function ql(r,e){if(e.target?.length!==1||e.target[0].transform||e.rule||e.dependent)return!1;let t=Ae(r,"_");if(Array.isArray(t)&&(t=t[0]),!t)return!1;let n=Wl(r,t);if(!n)return ps(r,{...e.target[0],transform:"copy",parameter:[{valueId:"_"}]}),!0;let i=e.target[0],o=Ae(r,i.context),s=o.value[i.element],a=ms(o,i.element)||Array.isArray(s),u={root:r.root,parent:r,variables:{}},l=gi(u,n,[t]);return fs(r,i,o,l,a,s),!0}function Wl(r,e){let t=r;for(;t;){if(t.variables){for(let n of Object.values(t.variables))for(let i of yi(n))if(i.type==="StructureMapGroup"){let o=i.value;if((o.typeMode==="types"||o.typeMode==="type-and-types")&&o.input.length===2&&o.input[0].mode==="source"&&o.input[0].type===e.type&&o.input[1].mode==="target")return o}}t=t.parent}}function jl(r,e){let t=Ae(r,e.context);if(!t)return[];let n=e.element;if(!n)return[t];let i=P(n,[t]);if(!i||i.length===0)return[];if(e.condition&&!cs(t,{[e.variable]:i[0]},e.condition))return[];if(e.check&&!cs(t,{[e.variable]:i[0]},e.check))throw new Error("Check failed: "+e.check);return e.listMode&&(i=$l(e,i)),i}function cs(r,e,t){return B(P(t,[r],e))}function $l(r,e){switch(r.listMode){case"first":return[e[0]];case"not_first":return e.slice(1);case"last":return[e.at(-1)];case"not_last":return e.slice(0,e.length-1);case"only_one":if(e.length!==1)throw new Error("Expected only one value");break}return e}function ps(r,e){let t=Ae(r,e.context);if(!t)throw new Error("Target not found: "+e.context);let n=t.value[e.element],i,o=ms(t,e.element)||Array.isArray(n);if(e.transform)switch(e.transform){case"append":i=Gl(r,e);break;case"cast":i=Hl(r,e);break;case"cc":i=Ql(r,e);break;case"copy":i=zl(r,e);break;case"create":i=Jl(r,e);break;case"evaluate":i=Kl(r,e);break;case"translate":i=Yl(r,e);break;case"truncate":i=Xl(r,e);break;case"uuid":i=[{type:"string",value:se()}];break;default:throw new Error(`Unsupported transform: ${e.transform}`)}else{let s=hs(t,e.element)?.type,a=s?.length===1?s[0].code:void 0;o||n===void 0?i=[a?{type:a,value:{}}:b({})]:i=[a?{type:a,value:n}:b(n)]}fs(r,e,t,i,o,n)}function fs(r,e,t,n,i,o){if(n.length!==0){if(i){o||(o=[],Jt(t.value,e.element,o));for(let s of n)o.push(s.value)}else Jt(t.value,e.element,n[0].value);e.variable&&$r(r,e.variable,ed(n))}}function ms(r,e){return hs(r,e)?.isArray}function hs(r,e){return Ge(r.type)?.elements?.[e]}function Gl(r,e){let t=$(r,e.parameter?.[0])?.[0]?.value,n=$(r,e.parameter?.[1])?.[0]?.value;return[{type:"string",value:(t??"").toString()+(n??"").toString()}]}function Hl(r,e){let t=$(r,e.parameter?.[0])?.[0];return $(r,e.parameter?.[1])?.[0]?.value==="string"?[{type:"string",value:t?.value?.toString()}]:[t]}function Ql(r,e){let t=e.parameter;if(t.length===2){let n=$(r,t[0])?.[0]?.value,i=$(r,t[1])?.[0]?.value;return[{type:"CodeableConcept",value:{coding:[{system:n,code:i}]}}]}else return[{type:"CodeableConcept",value:{text:$(r,t[0])?.[0]?.value}}]}function zl(r,e){return e.parameter.flatMap(t=>$(r,t))}function Jl(r,e){let t={};return e.parameter&&e.parameter.length>0&&(t.resourceType=$(r,e.parameter?.[0])?.[0]?.value),[b(t)]}function Kl(r,e){let n=$(r,e.parameter?.[0])[0].value;return P(n,[],ys(r))}function Yl(r,e){let t=e.parameter.flatMap(u=>$(r,u)),n=t[0].value,i=t[1].value,s=Gr(r)?.get("ConceptMap",i)[0];if(!s)throw new Error("ConceptMap not found: "+i);let a=mi(s,{system:s.group?.[0]?.source,code:n});return[b(a.match?.[0]?.concept?.code)]}function Xl(r,e){let t=$(r,e.parameter?.[0])?.[0],n=$(r,e.parameter?.[1])?.[0]?.value;return t.type==="string"?[{type:"string",value:t.value.substring(0,n)}]:[t]}function Zl(r,e){let t=Ae(r,e.name);if(!t)throw new Error("Dependent group not found: "+e.name);let n=e.variable,i=[];for(let s of n){let a=Ae(r,s);if(!a)throw new Error("Dependent variable not found: "+s);i.push(a)}let o={root:r.root,parent:r,variables:{}};gi(o,t.value,i)}function Gr(r){if(r.transformMaps)return r.transformMaps;if(r.parent)return Gr(r.parent)}function $(r,e){let n=D({type:"StructureMapGroupRuleTargetParameter",value:e},"value");if(!n)throw new Error("Missing target parameter: "+JSON.stringify(e));if(n=yi(n),n.length===1&&n[0].type==="id"){let i=Ae(r,n[0].value);if(!i)throw new Error("Variable not found: "+n[0].value);return yi(i)}return n}function Ae(r,e){let t=r.variables?.[e];if(t)return t;if(r.parent)return Ae(r.parent,e)}function ys(r,e={}){if(r.parent&&ys(r.parent,e),r.variables)for(let[t,n]of Object.entries(r.variables))e[t]=n,e["%"+t]=n;return e}function $r(r,e,t){r.variables||(r.variables={}),Jt(r.variables,e,t)}function Jt(r,e,t){if(e==="__proto__"||e==="constructor"||e==="prototype")throw new Error("Invalid key: "+e);r[e]=t}function yi(r){return Array.isArray(r)?r:[r]}function ed(r){return r.length===1?r[0]:r}var td=" ".repeat(2),xi=class{constructor(e=td,t=!0){c(this,"indent");c(this,"b");c(this,"indentCount");this.indent=e,this.b=[],this.indentCount=0,t&&(this.appendNoWrap("// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors"),this.appendNoWrap("// SPDX-License-Identifier: Apache-2.0"),this.appendNoWrap("/*"),this.appendNoWrap(" * This is a generated file"),this.appendNoWrap(" * Do not edit manually."),this.appendNoWrap(" */"),this.newLine())}newLine(){this.b.push(`
|
|
45
45
|
`)}appendNoWrap(e){this.b.push(this.indent.repeat(this.indentCount)),this.b.push(e),this.b.push(`
|
|
46
46
|
`)}append(e){let t=this.indent.repeat(this.indentCount)+e;if(t.length<160)this.b.push(t),this.b.push(`
|
|
47
47
|
`);else{let n=!0;for(let i of gs(t,120-this.indent.length*this.indentCount))n?this.b.push(this.indent.repeat(this.indentCount)):this.b.push(this.indent.repeat(this.indentCount+2)),this.b.push(i.trim()),this.b.push(`
|