@medplum/core 2.0.22 → 2.0.24
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 +14080 -13218
- package/dist/cjs/index.cjs.map +1 -1
- package/dist/cjs/index.min.cjs +1 -1
- package/dist/esm/access.mjs +142 -0
- package/dist/esm/access.mjs.map +1 -0
- package/dist/esm/bundle.mjs +3 -3
- package/dist/esm/bundle.mjs.map +1 -1
- package/dist/esm/client.mjs +111 -34
- package/dist/esm/client.mjs.map +1 -1
- package/dist/esm/fhirlexer/parse.mjs.map +1 -1
- package/dist/esm/fhirlexer/tokenize.mjs +2 -2
- package/dist/esm/fhirlexer/tokenize.mjs.map +1 -1
- package/dist/esm/fhirmapper/parse.mjs +1 -1
- package/dist/esm/fhirmapper/parse.mjs.map +1 -1
- package/dist/esm/fhirpath/atoms.mjs +63 -56
- package/dist/esm/fhirpath/atoms.mjs.map +1 -1
- package/dist/esm/fhirpath/functions.mjs +196 -128
- package/dist/esm/fhirpath/functions.mjs.map +1 -1
- package/dist/esm/fhirpath/parse.mjs +6 -3
- package/dist/esm/fhirpath/parse.mjs.map +1 -1
- package/dist/esm/fhirpath/utils.mjs +4 -5
- package/dist/esm/fhirpath/utils.mjs.map +1 -1
- package/dist/esm/format.mjs +1 -1
- package/dist/esm/format.mjs.map +1 -1
- package/dist/esm/hl7.mjs +6 -6
- package/dist/esm/hl7.mjs.map +1 -1
- package/dist/esm/index.min.mjs +1 -1
- package/dist/esm/index.mjs +5 -2
- package/dist/esm/index.mjs.map +1 -1
- package/dist/esm/outcomes.mjs +51 -24
- package/dist/esm/outcomes.mjs.map +1 -1
- package/dist/esm/readablepromise.mjs +1 -1
- package/dist/esm/readablepromise.mjs.map +1 -1
- package/dist/esm/schema.mjs +1 -1
- package/dist/esm/schema.mjs.map +1 -1
- package/dist/esm/search/details.mjs +18 -20
- package/dist/esm/search/details.mjs.map +1 -1
- package/dist/esm/search/match.mjs +7 -5
- package/dist/esm/search/match.mjs.map +1 -1
- package/dist/esm/search/search.mjs +14 -5
- package/dist/esm/search/search.mjs.map +1 -1
- package/dist/esm/types.mjs +1 -1
- package/dist/esm/types.mjs.map +1 -1
- package/dist/esm/typeschema/types.mjs +278 -0
- package/dist/esm/typeschema/types.mjs.map +1 -0
- package/dist/esm/typeschema/validation.mjs +262 -0
- package/dist/esm/typeschema/validation.mjs.map +1 -0
- package/dist/esm/utils.mjs +3 -3
- package/dist/esm/utils.mjs.map +1 -1
- package/dist/types/access.d.ts +48 -0
- package/dist/types/client.d.ts +69 -25
- package/dist/types/fhirlexer/parse.d.ts +12 -7
- package/dist/types/fhirpath/atoms.d.ts +21 -21
- package/dist/types/fhirpath/functions.d.ts +2 -4
- package/dist/types/fhirpath/parse.d.ts +2 -1
- package/dist/types/index.d.ts +3 -0
- package/dist/types/outcomes.d.ts +10 -2
- package/dist/types/search/search.d.ts +7 -0
- package/dist/types/typeschema/types.d.ts +5 -2
- package/dist/types/typeschema/validation.d.ts +2 -0
- package/dist/types/utils.d.ts +1 -8
- package/package.json +1 -1
package/dist/esm/index.min.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
function e(e){if("undefined"!=typeof window)return window.atob(e);if("undefined"!=typeof Buffer)return Buffer.from(e,"base64").toString("binary");throw new Error("Unable to decode base64")}function t(e){if("undefined"!=typeof window)return window.btoa(e);if("undefined"!=typeof Buffer)return Buffer.from(e,"binary").toString("base64");throw new Error("Unable to encode base64")}function r(e){for(const t of e.entry||[])delete t?.resource?.meta,t.fullUrl="urn:uuid:"+t?.resource?.id,delete t?.resource?.id;const t=e.entry,r=JSON.stringify({resourceType:"Bundle",type:"transaction",entry:t?.map((e=>({fullUrl:e.fullUrl,request:{method:"POST",url:e.resource.resourceType},resource:e.resource})))},n,2);return JSON.parse(r)}function n(e,t){return"reference"===e&&"string"==typeof t&&t.includes("/")?"urn:uuid:"+t.split("/")[1]:t}class i{constructor(e=10){this.max=e,this.cache=new Map}clear(){this.cache.clear()}get(e){const 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}}function o(e,t){const r=[];if(e.line&&r.push(...e.line),e.city||e.state||e.postalCode){const t=[];e.city&&t.push(e.city),e.state&&t.push(e.state),e.postalCode&&t.push(e.postalCode),r.push(t.join(", "))}return e.use&&(t?.all||t?.use)&&r.push("["+e.use+"]"),r.join(t?.lineSeparator||", ").trim()}function s(e,t){const r=[];return e.prefix&&!1!==t?.prefix&&r.push(...e.prefix),e.given&&r.push(...e.given),e.family&&r.push(e.family),e.suffix&&!1!==t?.suffix&&r.push(...e.suffix),e.use&&(t?.all||t?.use)&&r.push("["+e.use+"]"),r.join(" ").trim()}function a(e){const t=[];return e.given&&t.push(...e.given),t.join(" ").trim()}function c(e){return e.family||""}function u(e){return e instanceof Date&&!isNaN(e.getTime())}function d(e,t,r){if(!e)return"";const n=new Date(e);return u(n)?(n.setUTCHours(0,0,0,0),n.toLocaleDateString(t,{timeZone:"UTC",...r})):""}function p(e,t,r){if(!e)return"";const n=new Date("2000-01-01T"+e+"Z");return u(n)?n.toLocaleTimeString(t,r):""}function l(e,t,r){if(!e)return"";const n=new Date(e);return u(n)?n.toLocaleString(t,r):""}function h(e,t,r){return e&&(e.start||e.end)?l(e.start,t,r)+" - "+l(e.end,t,r):""}const f={s:"every second",min:"every minute",h:"hourly",d:"daily",wk:"weekly",mo:"monthly",a:"annually"},m={s:"second",min:"minute",h:"hour",d:"day",wk:"week",mo:"month",a:"year"},y={s:"seconds",min:"minutes",h:"hours",d:"days",wk:"weeks",mo:"months",a:"years"};function g(e){if(!e)return"";const t=[];if(e.repeat?.periodUnit){const r=e.repeat.frequency||1,n=e.repeat.period||1,i=e.repeat.periodUnit;1===r&&1===n?t.push(f[i]):(1===r?t.push("once"):t.push(r+" times"),1===n?t.push("per "+m[i]):t.push("per "+n+" "+y[i])),e.repeat.dayOfWeek&&t.push("on "+e.repeat.dayOfWeek.map(Y).join(", ")),e.repeat.timeOfDay&&t.push("at "+e.repeat.timeOfDay.map((e=>p(e))).join(", "))}return e.event&&t.push(e.event.map((e=>l(e))).join(", ")),Y(t.join(" ").trim())}function v(e,t,r=!1){if(r&&void 0===t)throw new Error("Precision must be specified for exclusive ranges");const n=e?.low&&{...e.low,comparator:void 0},i=e?.high&&{...e.high,comparator:void 0};return void 0===n?.value&&void 0===i?.value?"":void 0!==n?.value&&void 0===i?.value?r&&void 0!==t?(n.value=function(e,t,r=1){return(E(e,t)-r)*Math.pow(10,-t)}(n.value,t),`> ${x(n,t)}`):`>= ${x(n,t)}`:void 0===n?.value&&void 0!==i?.value?r&&void 0!==t?(i.value=function(e,t,r=1){return(E(e,t)+r)*Math.pow(10,-t)}(i.value,t),`< ${x(i,t)}`):`<= ${x(i,t)}`:(n?.unit===i?.unit&&delete n?.unit,`${x(n,t)} - ${x(i,t)}`)}function x(e,t){if(!e)return"";const r=[];return e.comparator&&(r.push(e.comparator),r.push(" ")),void 0!==e.value&&(void 0!==t?r.push(e.value.toFixed(t)):r.push(e.value)),e.unit&&("%"!==e.unit&&" "!==r[r.length-1]&&r.push(" "),r.push(e.unit)),r.join("").trim()}function S(e){return void 0===e?.value?"":e.value.toLocaleString(void 0,{style:"currency",currency:e.currency||"USD",currencyDisplay:"narrowSymbol"})}function b(e){return e?e.text?e.text:e.coding?e.coding.map((e=>w(e))).join(", "):"":""}function w(e){return e?.display||e?.code||""}function T(e){return e?"component"in e?e.component.map((e=>T(e))).join(" / "):e?.valueQuantity?x(e.valueQuantity):e.valueCodeableConcept?b(e.valueCodeableConcept):e.valueString?e.valueString:"":""}function E(e,t){return void 0===t?e:Math.round(e*Math.pow(10,t))}function k(e){const t=C(e),r=D(e);return r===t?{reference:t}:{reference:t,display:r}}function C(e){return e.resourceType+"/"+e.id}function P(e){return e?.reference?.split("/")[1]}function R(e){return"Patient"===e.resourceType||"Practitioner"===e.resourceType||"RelatedPerson"===e.resourceType}function D(e){if(R(e)){const t=function(e){const t=e.name;if(t&&t.length>0)return s(t[0]);return}(e);if(t)return t}if("Device"===e.resourceType){const t=function(e){const t=e.deviceName;if(t&&t.length>0)return t[0].name;return}(e);if(t)return t}return"Observation"===e.resourceType&&"code"in e&&e.code?.text?e.code.text:"User"===e.resourceType&&e.email?e.email:"name"in e&&e.name&&"string"==typeof e.name?e.name:C(e)}function A(e){if(!("photo"in e))return;const t=e.photo;if(t){if(!Array.isArray(t))return I(t);for(const e of t){const t=I(e);if(t)return t}}}function I(e){if(e.url&&e.contentType&&e.contentType.startsWith("image/"))return e.url}function U(e){return e?new Date(e):void 0}function O(e,t){const r=new Date(e);r.setUTCHours(0,0,0,0);const n=t?new Date(t):new Date;n.setUTCHours(0,0,0,0);const i=r.getUTCFullYear(),o=r.getUTCMonth(),s=r.getUTCDate(),a=n.getUTCFullYear(),c=n.getUTCMonth(),u=n.getUTCDate();let d=a-i;(c<o||c===o&&u<s)&&d--;let p=12*a+c-(12*i+o);u<s&&p--;return{years:d,months:p,days:Math.floor((n.getTime()-r.getTime())/864e5)}}function L(e,t){const{years:r,months:n,days:i}=O(e,t);return r>=2?r.toString().padStart(3,"0")+"Y":n>=1?n.toString().padStart(3,"0")+"M":i.toString().padStart(3,"0")+"D"}function N(e){const t={};return M(e.item,t),t}function M(e,t){if(e)for(const r of e)r.linkId&&r.answer&&r.answer.length>0&&(t[r.linkId]=r.answer[0]),M(r.item,t)}function _(e,t){const r=e.identifier;if(!r)return;const n=Array.isArray(r)?r:[r];for(const e of n)if(e.system===t)return e.value}function B(e,...t){let r=e;for(let e=0;e<t.length&&r;e++)r=r?.extension?.find((r=>r.url===t[e]));return r?.valueString}function j(e,...t){let r=e;for(let e=0;e<t.length&&r;e++)r=r?.extension?.find((r=>r.url===t[e]));return r}function $(e,t){return JSON.stringify(e,q,t?2:void 0)}function q(e,t){return!function(e){return!!e.match(/\d+$/)}(e)&&Q(t)?void 0:t}function Q(e){if(null==e)return!0;const t=typeof e;return"string"===t&&""===e||"object"===t&&0===Object.keys(e).length}function F(e,t,r){return e===t||(!(!Q(e)||!Q(t))||!Q(e)&&!Q(t)&&(Array.isArray(e)&&Array.isArray(t)?function(e,t){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(!F(e[r],t[r]))return!1;return!0}(e,t):!Array.isArray(e)&&!Array.isArray(t)&&(z(e)&&z(t)?function(e,t,r){const n=new Set;Object.keys(e).forEach((e=>n.add(e))),Object.keys(t).forEach((e=>n.add(e))),"meta"===r&&(n.delete("versionId"),n.delete("lastUpdated"),n.delete("author"));for(const r of n){if(!F(e[r],t[r],r))return!1}return!0}(e,t,r):(z(e)||z(t),!1))))}function W(e){return JSON.parse(JSON.stringify(e))}function H(e){return!!e.match(/^\w{8}-\w{4}-\w{4}-\w{4}-\w{12}$/i)}function z(e){return null!==e&&"object"==typeof e}function G(e){return e.every((e=>"string"==typeof e))}const V=[];for(let e=0;e<256;e++)V.push(e.toString(16).padStart(2,"0"));function X(e){const t=new Uint8Array(e),r=new Array(t.length);for(let e=0;e<t.length;e++)r[e]=V[t[e]];return r.join("")}function J(e){const t=new Uint8Array(e),r=[];for(let e=0;e<t.length;e++)r[e]=String.fromCharCode(t[e]);return window.btoa(r.join(""))}function Y(e){return e.charAt(0).toUpperCase()+e.substring(1)}function Z(e){return e===e.toLowerCase()&&e!==e.toUpperCase()}function K(e,t){return e?.coding?.find((e=>e.system===t))?.code}function ee(e,t,r){e.coding||(e.coding=[]);const n=e.coding?.find((e=>e.system===t));n?n.code=r:e.coding?.push({system:t,code:r})}function te(e,t,r,n){return e.qualifiedInterval?.find((i=>ne(i,t)&&function(e,t,r){return!!e.range&&ie(t,e.range,r)}(i,r,e.quantitativeDetails?.decimalPrecision)&&(void 0===n||i.category===n)))}function re(e,t,r){return e.qualifiedInterval?.find((e=>ne(e,t)&&r.includes(e.condition)))}function ne(e,t){return function(e,t){return!e.gender||e.gender===t.gender}(e,t)&&function(e,t){return!e.age||ie(O(t.birthDate).years,e.age)}(e,t)}function ie(e,t,r){return(void 0===t.low?.value||de(e,t.low.value,r))&&(void 0===t.high?.value||ue(e,t.high.value,r))}function oe(e,t){return parseFloat(e.toFixed(t))}function se(e,t,r){return pe(e,r)===pe(t,r)}function ae(e,t,r){return pe(e,r)<pe(t,r)}function ce(e,t,r){return pe(e,r)>pe(t,r)}function ue(e,t,r){return pe(e,r)<=pe(t,r)}function de(e,t,r){return pe(e,r)>=pe(t,r)}function pe(e,t){return void 0===t?e:Math.round(e*Math.pow(10,t))}function le(e,t,r){return e.find((e=>"string"==typeof t?K(e.code||{},r)===t:K(e.code||{},r)===K(t,r)))}function he(){const e=new Uint32Array(28);return crypto.getRandomValues(e),X(e.buffer)}class fe{constructor(){this.listeners={}}addEventListener(e,t){this.listeners[e]||(this.listeners[e]=[]),this.listeners[e].push(t)}removeEventListeneer(e,t){const r=this.listeners[e];if(r)for(let e=0;e<r.length;e++)if(r[e]===t)return void r.splice(e,1)}dispatchEvent(e){const t=this.listeners[e.type];return t&&t.forEach((t=>t.call(this,e))),!e.defaultPrevented}}function me(t){const[r,n,i]=t.split(".");return function(t){const r=e(t.replace(/-/g,"+").replace(/_/g,"/")),n=Array.from(r).reduce(((e,t)=>`${e}%${("00"+t.charCodeAt(0).toString(16)).slice(-2)}`),""),i=decodeURIComponent(n);return JSON.parse(i)}(n)}const ye="ok",ge="created",ve="gone",xe="not-modified",Se="not-found",be="unauthorized",we="forbidden",Te="too-many-requests",Ee={resourceType:"OperationOutcome",id:ye,issue:[{severity:"information",code:"informational",details:{text:"All OK"}}]},ke={resourceType:"OperationOutcome",id:ge,issue:[{severity:"information",code:"informational",details:{text:"Created"}}]},Ce={resourceType:"OperationOutcome",id:xe,issue:[{severity:"information",code:"informational",details:{text:"Not Modified"}}]},Pe={resourceType:"OperationOutcome",id:Se,issue:[{severity:"error",code:"not-found",details:{text:"Not found"}}]},Re={resourceType:"OperationOutcome",id:be,issue:[{severity:"error",code:"login",details:{text:"Unauthorized"}}]},De={resourceType:"OperationOutcome",id:we,issue:[{severity:"error",code:"forbidden",details:{text:"Forbidden"}}]},Ae={resourceType:"OperationOutcome",id:ve,issue:[{severity:"error",code:"deleted",details:{text:"Gone"}}]},Ie={resourceType:"OperationOutcome",id:Te,issue:[{severity:"error",code:"throttled",details:{text:"Too Many Requests"}}]},Ue={resourceType:"OperationOutcome",id:"accepted",issue:[{severity:"information",code:"informational",details:{text:"Accepted"}}]};function Oe(e,t){return{resourceType:"OperationOutcome",issue:[{severity:"error",code:"invalid",details:{text:e},expression:t?[t]:void 0}]}}function Le(e){return{resourceType:"OperationOutcome",issue:[{severity:"error",code:"structure",details:{text:e}}]}}function Ne(e){return"object"==typeof e&&null!==e&&"OperationOutcome"===e.resourceType}function Me(e){return e.id===ye||e.id===ge||e.id===xe}function _e(e){return e.id===Se}function Be(e){return e.id===ve}function je(e){return e.id===ye?200:e.id===ge?201:e.id===xe?304:e.id===be?401:e.id===we?403:e.id===Se?404:e.id===ve?410:e.id===Te?429:400}function $e(e,t){if(!Me(e)||void 0===t)throw new qe(e)}class qe extends Error{constructor(e,t){super(We(e)),this.outcome=e,this.cause=t}}function Qe(e){return e instanceof qe?e.outcome:Ne(e)?e:Oe(Fe(e))}function Fe(e){return e?"string"==typeof e?e:e instanceof Error?e.message:Ne(e)?We(e):JSON.stringify(e):"Unknown error"}function We(e){const t=[];if(e.issue)for(const r of e.issue){let e=r.details?.text||"Unknown error";r.expression?.length&&(e+=` (${r.expression.join(", ")})`),t.push(e)}return t.length>0?t.join("; "):"Unknown error"}var He;class ze{constructor(e){this[He]="ReadablePromise",this.status="pending",this.suspender=e.then((e=>(this.status="success",this.response=e,e)),(e=>{throw this.status="error",this.error=e,e}))}isPending(){return"pending"===this.status}isOk(){return"success"===this.status}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)}}He=Symbol.toStringTag;class Ge{constructor(){this.storage="undefined"!=typeof localStorage?localStorage:new Ve}clear(){this.storage.clear()}getString(e){return this.storage.getItem(e)||void 0}setString(e,t){t?this.storage.setItem(e,t):this.storage.removeItem(e)}getObject(e){const t=this.getString(e);return t?JSON.parse(t):void 0}setObject(e,t){this.setString(e,t?$(t):void 0)}}class Ve{constructor(){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]}}var Xe,Je={types:{Element:{display:"Element",properties:{id:{type:[{code:"string"}]},extension:{max:"*",type:[{code:"Extension"}]}}},BackboneElement:{display:"BackboneElement",properties:{id:{type:[{code:"string"}]},extension:{max:"*",type:[{code:"Extension"}]},modifierExtension:{max:"*",type:[{code:"Extension"}]}}},Address:{display:"Address",properties:{id:{type:[{code:"string"}]},extension:{max:"*",type:[{code:"Extension"}]},use:{type:[{code:"code"}]},type:{type:[{code:"code"}]},text:{type:[{code:"string"}]},line:{max:"*",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:{display:"Age",properties:{id:{type:[{code:"string"}]},extension:{max:"*",type:[{code:"Extension"}]},value:{type:[{code:"decimal"}]},comparator:{type:[{code:"code"}]},unit:{type:[{code:"string"}]},system:{type:[{code:"uri"}]},code:{type:[{code:"code"}]}}},Annotation:{display:"Annotation",properties:{id:{type:[{code:"string"}]},extension:{max:"*",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:{display:"Attachment",properties:{id:{type:[{code:"string"}]},extension:{max:"*",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:{display:"CodeableConcept",properties:{id:{type:[{code:"string"}]},extension:{max:"*",type:[{code:"Extension"}]},coding:{max:"*",type:[{code:"Coding"}]},text:{type:[{code:"string"}]}}},Coding:{display:"Coding",properties:{id:{type:[{code:"string"}]},extension:{max:"*",type:[{code:"Extension"}]},system:{type:[{code:"uri"}]},version:{type:[{code:"string"}]},code:{type:[{code:"code"}]},display:{type:[{code:"string"}]},userSelected:{type:[{code:"boolean"}]}}},ContactDetail:{display:"ContactDetail",properties:{id:{type:[{code:"string"}]},extension:{max:"*",type:[{code:"Extension"}]},name:{type:[{code:"string"}]},telecom:{max:"*",type:[{code:"ContactPoint"}]}}},ContactPoint:{display:"ContactPoint",properties:{id:{type:[{code:"string"}]},extension:{max:"*",type:[{code:"Extension"}]},system:{type:[{code:"code"}]},value:{type:[{code:"string"}]},use:{type:[{code:"code"}]},rank:{type:[{code:"positiveInt"}]},period:{type:[{code:"Period"}]}}},Contributor:{display:"Contributor",properties:{id:{type:[{code:"string"}]},extension:{max:"*",type:[{code:"Extension"}]},type:{min:1,type:[{code:"code"}]},name:{min:1,type:[{code:"string"}]},contact:{max:"*",type:[{code:"ContactDetail"}]}}},Count:{display:"Count",properties:{id:{type:[{code:"string"}]},extension:{max:"*",type:[{code:"Extension"}]},value:{type:[{code:"decimal"}]},comparator:{type:[{code:"code"}]},unit:{type:[{code:"string"}]},system:{type:[{code:"uri"}]},code:{type:[{code:"code"}]}}},DataRequirement:{display:"DataRequirement",properties:{id:{type:[{code:"string"}]},extension:{max:"*",type:[{code:"Extension"}]},type:{min:1,type:[{code:"code"}]},profile:{max:"*",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:"*",type:[{code:"string"}]},codeFilter:{max:"*",type:[{code:"Element"}]},dateFilter:{max:"*",type:[{code:"Element"}]},limit:{type:[{code:"positiveInt"}]},sort:{max:"*",type:[{code:"Element"}]}}},DataRequirementCodeFilter:{display:"DataRequirementCodeFilter",properties:{id:{type:[{code:"string"}]},extension:{max:"*",type:[{code:"Extension"}]},path:{type:[{code:"string"}]},searchParam:{type:[{code:"string"}]},valueSet:{type:[{code:"canonical",targetProfile:["http://hl7.org/fhir/StructureDefinition/ValueSet"]}]},code:{max:"*",type:[{code:"Coding"}]}}},DataRequirementDateFilter:{display:"DataRequirementDateFilter",properties:{id:{type:[{code:"string"}]},extension:{max:"*",type:[{code:"Extension"}]},path:{type:[{code:"string"}]},searchParam:{type:[{code:"string"}]},"value[x]":{type:[{code:"dateTime"},{code:"Period"},{code:"Duration"}]}}},DataRequirementSort:{display:"DataRequirementSort",properties:{id:{type:[{code:"string"}]},extension:{max:"*",type:[{code:"Extension"}]},path:{min:1,type:[{code:"string"}]},direction:{min:1,type:[{code:"code"}]}}},Distance:{display:"Distance",properties:{id:{type:[{code:"string"}]},extension:{max:"*",type:[{code:"Extension"}]},value:{type:[{code:"decimal"}]},comparator:{type:[{code:"code"}]},unit:{type:[{code:"string"}]},system:{type:[{code:"uri"}]},code:{type:[{code:"code"}]}}},Dosage:{display:"Dosage",properties:{id:{type:[{code:"string"}]},extension:{max:"*",type:[{code:"Extension"}]},modifierExtension:{max:"*",type:[{code:"Extension"}]},sequence:{type:[{code:"integer"}]},text:{type:[{code:"string"}]},additionalInstruction:{max:"*",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:"*",type:[{code:"Element"}]},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:{display:"DosageDoseAndRate",properties:{id:{type:[{code:"string"}]},extension:{max:"*",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:{display:"Duration",properties:{id:{type:[{code:"string"}]},extension:{max:"*",type:[{code:"Extension"}]},value:{type:[{code:"decimal"}]},comparator:{type:[{code:"code"}]},unit:{type:[{code:"string"}]},system:{type:[{code:"uri"}]},code:{type:[{code:"code"}]}}},ElementDefinition:{display:"ElementDefinition",properties:{id:{type:[{code:"string"}]},extension:{max:"*",type:[{code:"Extension"}]},modifierExtension:{max:"*",type:[{code:"Extension"}]},path:{min:1,type:[{code:"string"}]},representation:{max:"*",type:[{code:"code"}]},sliceName:{type:[{code:"string"}]},sliceIsConstraining:{type:[{code:"boolean"}]},label:{type:[{code:"string"}]},code:{max:"*",type:[{code:"Coding"}]},slicing:{type:[{code:"Element"}]},short:{type:[{code:"string"}]},definition:{type:[{code:"markdown"}]},comment:{type:[{code:"markdown"}]},requirements:{type:[{code:"markdown"}]},alias:{max:"*",type:[{code:"string"}]},min:{type:[{code:"unsignedInt"}]},max:{type:[{code:"string"}]},base:{type:[{code:"Element"}]},contentReference:{type:[{code:"uri"}]},type:{max:"*",type:[{code:"Element"}]},"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:"*",type:[{code:"Element"}]},"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:"*",type:[{code:"id"}]},constraint:{max:"*",type:[{code:"Element"}]},mustSupport:{type:[{code:"boolean"}]},isModifier:{type:[{code:"boolean"}]},isModifierReason:{type:[{code:"string"}]},isSummary:{type:[{code:"boolean"}]},binding:{type:[{code:"Element"}]},mapping:{max:"*",type:[{code:"Element"}]}}},ElementDefinitionSlicing:{display:"ElementDefinitionSlicing",properties:{id:{type:[{code:"string"}]},extension:{max:"*",type:[{code:"Extension"}]},discriminator:{max:"*",type:[{code:"Element"}]},description:{type:[{code:"string"}]},ordered:{type:[{code:"boolean"}]},rules:{min:1,type:[{code:"code"}]}}},ElementDefinitionSlicingDiscriminator:{display:"ElementDefinitionSlicingDiscriminator",properties:{id:{type:[{code:"string"}]},extension:{max:"*",type:[{code:"Extension"}]},type:{min:1,type:[{code:"code"}]},path:{min:1,type:[{code:"string"}]}}},ElementDefinitionBase:{display:"ElementDefinitionBase",properties:{id:{type:[{code:"string"}]},extension:{max:"*",type:[{code:"Extension"}]},path:{min:1,type:[{code:"string"}]},min:{min:1,type:[{code:"unsignedInt"}]},max:{min:1,type:[{code:"string"}]}}},ElementDefinitionType:{display:"ElementDefinitionType",properties:{id:{type:[{code:"string"}]},extension:{max:"*",type:[{code:"Extension"}]},code:{min:1,type:[{code:"uri"}]},profile:{max:"*",type:[{code:"canonical",targetProfile:["http://hl7.org/fhir/StructureDefinition/StructureDefinition","http://hl7.org/fhir/StructureDefinition/ImplementationGuide"]}]},targetProfile:{max:"*",type:[{code:"canonical",targetProfile:["http://hl7.org/fhir/StructureDefinition/StructureDefinition","http://hl7.org/fhir/StructureDefinition/ImplementationGuide"]}]},aggregation:{max:"*",type:[{code:"code"}]},versioning:{type:[{code:"code"}]}}},ElementDefinitionExample:{display:"ElementDefinitionExample",properties:{id:{type:[{code:"string"}]},extension:{max:"*",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:{display:"ElementDefinitionConstraint",properties:{id:{type:[{code:"string"}]},extension:{max:"*",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:{display:"ElementDefinitionBinding",properties:{id:{type:[{code:"string"}]},extension:{max:"*",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:{display:"ElementDefinitionMapping",properties:{id:{type:[{code:"string"}]},extension:{max:"*",type:[{code:"Extension"}]},identity:{min:1,type:[{code:"id"}]},language:{type:[{code:"code"}]},map:{min:1,type:[{code:"string"}]},comment:{type:[{code:"string"}]}}},Expression:{display:"Expression",properties:{id:{type:[{code:"string"}]},extension:{max:"*",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:{display:"Extension",properties:{id:{type:[{code:"string"}]},extension:{max:"*",type:[{code:"Extension"}]},url:{min:1,type:[{code:"string"}]},"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:{display:"HumanName",properties:{id:{type:[{code:"string"}]},extension:{max:"*",type:[{code:"Extension"}]},use:{type:[{code:"code"}]},text:{type:[{code:"string"}]},family:{type:[{code:"string"}]},given:{max:"*",type:[{code:"string"}]},prefix:{max:"*",type:[{code:"string"}]},suffix:{max:"*",type:[{code:"string"}]},period:{type:[{code:"Period"}]}}},Identifier:{display:"Identifier",properties:{id:{type:[{code:"string"}]},extension:{max:"*",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:{display:"MarketingStatus",properties:{id:{type:[{code:"string"}]},extension:{max:"*",type:[{code:"Extension"}]},modifierExtension:{max:"*",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:{display:"Meta",properties:{id:{type:[{code:"string"}]},extension:{max:"*",type:[{code:"Extension"}]},versionId:{type:[{code:"id"}]},lastUpdated:{type:[{code:"instant"}]},source:{type:[{code:"uri"}]},profile:{max:"*",type:[{code:"canonical",targetProfile:["http://hl7.org/fhir/StructureDefinition/StructureDefinition"]}]},security:{max:"*",type:[{code:"Coding"}]},tag:{max:"*",type:[{code:"Coding"}]},project:{type:[{code:"uri"}]},author:{type:[{code:"Reference"}]},account:{type:[{code:"Reference"}]},compartment:{max:"*",type:[{code:"Reference"}]}}},Money:{display:"Money",properties:{id:{type:[{code:"string"}]},extension:{max:"*",type:[{code:"Extension"}]},value:{type:[{code:"decimal"}]},currency:{type:[{code:"code"}]}}},Narrative:{display:"Narrative",properties:{id:{type:[{code:"string"}]},extension:{max:"*",type:[{code:"Extension"}]},status:{min:1,type:[{code:"code"}]},div:{min:1,type:[{code:"xhtml"}]}}},ParameterDefinition:{display:"ParameterDefinition",properties:{id:{type:[{code:"string"}]},extension:{max:"*",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:{display:"Period",properties:{id:{type:[{code:"string"}]},extension:{max:"*",type:[{code:"Extension"}]},start:{type:[{code:"dateTime"}]},end:{type:[{code:"dateTime"}]}}},Population:{display:"Population",properties:{id:{type:[{code:"string"}]},extension:{max:"*",type:[{code:"Extension"}]},modifierExtension:{max:"*",type:[{code:"Extension"}]},"age[x]":{type:[{code:"Range"},{code:"CodeableConcept"}]},gender:{type:[{code:"CodeableConcept"}]},race:{type:[{code:"CodeableConcept"}]},physiologicalCondition:{type:[{code:"CodeableConcept"}]}}},ProdCharacteristic:{display:"ProdCharacteristic",properties:{id:{type:[{code:"string"}]},extension:{max:"*",type:[{code:"Extension"}]},modifierExtension:{max:"*",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:"*",type:[{code:"string"}]},imprint:{max:"*",type:[{code:"string"}]},image:{max:"*",type:[{code:"Attachment"}]},scoring:{type:[{code:"CodeableConcept"}]}}},ProductShelfLife:{display:"ProductShelfLife",properties:{id:{type:[{code:"string"}]},extension:{max:"*",type:[{code:"Extension"}]},modifierExtension:{max:"*",type:[{code:"Extension"}]},identifier:{type:[{code:"Identifier"}]},type:{min:1,type:[{code:"CodeableConcept"}]},period:{min:1,type:[{code:"Quantity"}]},specialPrecautionsForStorage:{max:"*",type:[{code:"CodeableConcept"}]}}},Quantity:{display:"Quantity",properties:{id:{type:[{code:"string"}]},extension:{max:"*",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"}]}}},Range:{display:"Range",properties:{id:{type:[{code:"string"}]},extension:{max:"*",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:{display:"Ratio",properties:{id:{type:[{code:"string"}]},extension:{max:"*",type:[{code:"Extension"}]},numerator:{type:[{code:"Quantity"}]},denominator:{type:[{code:"Quantity"}]}}},Reference:{display:"Reference",properties:{id:{type:[{code:"string"}]},extension:{max:"*",type:[{code:"Extension"}]},reference:{type:[{code:"string"}]},type:{type:[{code:"uri"}]},identifier:{type:[{code:"Identifier"}]},display:{type:[{code:"string"}]}}},RelatedArtifact:{display:"RelatedArtifact",properties:{id:{type:[{code:"string"}]},extension:{max:"*",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:{display:"SampledData",properties:{id:{type:[{code:"string"}]},extension:{max:"*",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:{display:"Signature",properties:{id:{type:[{code:"string"}]},extension:{max:"*",type:[{code:"Extension"}]},type:{min:1,max:"*",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:{display:"SubstanceAmount",properties:{id:{type:[{code:"string"}]},extension:{max:"*",type:[{code:"Extension"}]},modifierExtension:{max:"*",type:[{code:"Extension"}]},"amount[x]":{type:[{code:"Quantity"},{code:"Range"},{code:"string"}]},amountType:{type:[{code:"CodeableConcept"}]},amountText:{type:[{code:"string"}]},referenceRange:{type:[{code:"Element"}]}}},SubstanceAmountReferenceRange:{display:"SubstanceAmountReferenceRange",properties:{id:{type:[{code:"string"}]},extension:{max:"*",type:[{code:"Extension"}]},lowLimit:{type:[{code:"Quantity"}]},highLimit:{type:[{code:"Quantity"}]}}},Timing:{display:"Timing",properties:{id:{type:[{code:"string"}]},extension:{max:"*",type:[{code:"Extension"}]},modifierExtension:{max:"*",type:[{code:"Extension"}]},event:{max:"*",type:[{code:"dateTime"}]},repeat:{type:[{code:"Element"}]},code:{type:[{code:"CodeableConcept"}]}}},TimingRepeat:{display:"TimingRepeat",properties:{id:{type:[{code:"string"}]},extension:{max:"*",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:"*",type:[{code:"code"}]},timeOfDay:{max:"*",type:[{code:"time"}]},when:{max:"*",type:[{code:"code"}]},offset:{type:[{code:"unsignedInt"}]}}},TriggerDefinition:{display:"TriggerDefinition",properties:{id:{type:[{code:"string"}]},extension:{max:"*",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:"*",type:[{code:"DataRequirement"}]},condition:{type:[{code:"Expression"}]}}},UsageContext:{display:"UsageContext",properties:{id:{type:[{code:"string"}]},extension:{max:"*",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"]}]}}},MetadataResource:{display:"MetadataResource",properties:{id:{type:[{code:"string"}]},meta:{type:[{code:"Meta"}]},implicitRules:{type:[{code:"uri"}]},language:{type:[{code:"code"}]},text:{type:[{code:"Narrative"}]},contained:{max:"*",type:[{code:"Resource"}]},extension:{max:"*",type:[{code:"Extension"}]},modifierExtension:{max:"*",type:[{code:"Extension"}]},url:{type:[{code:"uri"}]},version:{type:[{code:"string"}]},name:{type:[{code:"string"}]},title:{type:[{code:"string"}]},status:{min:1,type:[{code:"code"}]},experimental:{type:[{code:"boolean"}]},date:{type:[{code:"dateTime"}]},publisher:{type:[{code:"string"}]},contact:{max:"*",type:[{code:"ContactDetail"}]},description:{type:[{code:"markdown"}]},useContext:{max:"*",type:[{code:"UsageContext"}]},jurisdiction:{max:"*",type:[{code:"CodeableConcept"}]}}},IdentityProvider:{display:"IdentityProvider",properties:{authorizeUrl:{min:1,type:[{code:"string"}]},tokenUrl:{min:1,type:[{code:"string"}]},userInfoUrl:{min:1,type:[{code:"string"}]},clientId:{min:1,type:[{code:"string"}]},clientSecret:{min:1,type:[{code:"string"}]},useSubject:{type:[{code:"boolean"}]}}}}};function Ye(e){for(const t of e.entry){const e=t.resource;"StructureDefinition"===e.resourceType&&Ze(e)}}function Ze(e){if(!e.name)return;const t=e.snapshot?.element;t&&(t.forEach((t=>function(e,t){const r=t.path,n=t.type?.[0]?.code;if(void 0!==n&&"Element"!==n&&"BackboneElement"!==n)return;const i=r.split(".");i[0]=e.name;const o=rt(i);let s=ht.types[o];s||(ht.types[o]=s={});s.parentType=s.parentType||rt(i.slice(0,i.length-1)),s.display=s.display||o,s.structureDefinition=s.structureDefinition||e,s.elementDefinition=s.elementDefinition||t,s.description=s.description||t.definition,s.properties=s.properties||{}}(e,t))),t.forEach((t=>function(e,t){const r=t.path,n=r.split(".");if(1===n.length)return;n[0]=e.name;const i=rt(n.slice(0,n.length-1)),o=ht.types[i];if(!o)return;const s=n[n.length-1];o.properties[s]=t}(e,t))))}function Ke(e){for(const t of e.entry){const e=t.resource;"SearchParameter"===e.resourceType&&et(e)}}function et(e){if(e.base)for(const t of e.base){const r=ht.types[t];r&&(r.searchParams||(r.searchParams={_id:{base:[t],code:"_id",type:"token",expression:t+".id"},_lastUpdated:{base:[t],code:"_lastUpdated",type:"date",expression:t+".meta.lastUpdated"},_compartment:{base:[t],code:"_compartment",type:"reference",expression:t+".meta.compartment"},_profile:{base:[t],code:"_profile",type:"uri",expression:t+".meta.profile"},_security:{base:[t],code:"_security",type:"token",expression:t+".meta.security"},_source:{base:[t],code:"_source",type:"uri",expression:t+".meta.source"},_tag:{base:[t],code:"_tag",type:"token",expression:t+".meta.tag"}}),r.searchParams[e.code]=e)}}function tt(e){const t=e.type?.[0]?.code;return"BackboneElement"===t||"Element"===t?rt(e.path?.split(".")):t}function rt(e){return 1===e.length?e[0]:e.map(Y).join("")}function nt(e){const t=e.structureDefinition;return t&&t.name===e.elementDefinition?.path&&"resource"===t.kind&&!t.abstract}function it(){const e=[];for(const[t,r]of Object.entries(ht.types))nt(r)&&e.push(t);return e}function ot(e){return ht.types[e]}function st(e){return ht.types[e].searchParams}function at(e){return e.replaceAll("[x]","").split(".").pop().split(/(?=[A-Z])/).map(ut).join(" ").replace("_"," ").replace(/\s+/g," ")}!function(e){e.Address="Address",e.Age="Age",e.Annotation="Annotation",e.Attachment="Attachment",e.BackboneElement="BackboneElement",e.CodeableConcept="CodeableConcept",e.Coding="Coding",e.ContactDetail="ContactDetail",e.ContactPoint="ContactPoint",e.Contributor="Contributor",e.Count="Count",e.DataRequirement="DataRequirement",e.Distance="Distance",e.Dosage="Dosage",e.Duration="Duration",e.Expression="Expression",e.Extension="Extension",e.HumanName="HumanName",e.Identifier="Identifier",e.MarketingStatus="MarketingStatus",e.Meta="Meta",e.Money="Money",e.Narrative="Narrative",e.ParameterDefinition="ParameterDefinition",e.Period="Period",e.Population="Population",e.ProdCharacteristic="ProdCharacteristic",e.ProductShelfLife="ProductShelfLife",e.Quantity="Quantity",e.Range="Range",e.Ratio="Ratio",e.Reference="Reference",e.RelatedArtifact="RelatedArtifact",e.SampledData="SampledData",e.Signature="Signature",e.SubstanceAmount="SubstanceAmount",e.SystemString="http://hl7.org/fhirpath/System.String",e.Timing="Timing",e.TriggerDefinition="TriggerDefinition",e.UsageContext="UsageContext",e.base64Binary="base64Binary",e.boolean="boolean",e.canonical="canonical",e.code="code",e.date="date",e.dateTime="dateTime",e.decimal="decimal",e.id="id",e.instant="instant",e.integer="integer",e.markdown="markdown",e.oid="oid",e.positiveInt="positiveInt",e.string="string",e.time="time",e.unsignedInt="unsignedInt",e.uri="uri",e.url="url",e.uuid="uuid"}(Xe||(Xe={}));const ct=new Set(["ID","IP","PKCE","JWKS","URI","URL"]);function ut(e){const t=e.toUpperCase();return ct.has(t)?t:t.charAt(0)+e.slice(1)}function dt(e,t){const r=ht.types[e];if(!r)return;const n=r.properties[t]??r.properties[t+"[x]"];if(n){if(n.contentReference){const e=n.contentReference.substring(1).split("."),t=e.pop();return dt(rt(e),t)}return n}}function pt(e){return!(!e||"object"!=typeof e||!("resourceType"in e))}function lt(e){return!(!e||"object"!=typeof e||!("reference"in e))}const ht=Je,ft="2.0.22-f51ac45a",mt="application/fhir+json",yt={resourceType:"Device",id:"system",deviceName:[{name:"System"}]};var gt,vt;!function(e){e.ClientCredentials="client_credentials",e.AuthorizationCode="authorization_code",e.RefreshToken="refresh_token",e.TokenExchange="urn:ietf:params:oauth:grant-type:token-exchange"}(gt||(gt={})),function(e){e.AccessToken="urn:ietf:params:oauth:token-type:access_token",e.RefreshToken="urn:ietf:params:oauth:token-type:refresh_token",e.IdToken="urn:ietf:params:oauth:token-type:id_token",e.Saml1Token="urn:ietf:params:oauth:token-type:saml1",e.Saml2Token="urn:ietf:params:oauth:token-type:saml2"}(vt||(vt={}));class xt extends fe{constructor(e){if(super(),e?.baseUrl&&!e.baseUrl.startsWith("http"))throw new Error("Base URL must start with http or https");this.fetch=e?.fetch||function(){if(!globalThis.fetch)throw new Error("Fetch not available in this environment");return globalThis.fetch.bind(globalThis)}(),this.storage=e?.storage||new Ge,this.createPdfImpl=e?.createPdf,this.baseUrl=bt(e?.baseUrl)||"https://api.medplum.com/",this.fhirBaseUrl=this.baseUrl+(bt(e?.fhirUrlPath)||"fhir/R4/"),this.clientId=e?.clientId||"",this.authorizeUrl=e?.authorizeUrl||this.baseUrl+"oauth2/authorize",this.tokenUrl=e?.tokenUrl||this.baseUrl+"oauth2/token",this.logoutUrl=e?.logoutUrl||this.baseUrl+"oauth2/logout",this.onUnauthenticated=e?.onUnauthenticated,this.cacheTime=e?.cacheTime??6e4,this.cacheTime>0?this.requestCache=new i(e?.resourceCacheSize??1e3):this.requestCache=void 0,e?.autoBatchTime?(this.autoBatchTime=e?.autoBatchTime??0,this.autoBatchQueue=[]):(this.autoBatchTime=0,this.autoBatchQueue=void 0);const t=this.getActiveLogin();t&&(this.accessToken=t.accessToken,this.refreshToken=t.refreshToken,this.refreshProfile().catch(console.log)),this.setupStorageListener()}getBaseUrl(){return this.baseUrl}clear(){this.storage.clear(),this.clearActiveLogin()}clearActiveLogin(){this.basicAuth||(this.storage.setString("activeLogin",void 0),this.requestCache?.clear(),this.accessToken=void 0,this.refreshToken=void 0,this.profile=void 0,this.config=void 0,this.dispatchEvent({type:"change"}))}invalidateUrl(e){e=e.toString(),this.requestCache?.delete(e)}invalidateAll(){this.requestCache?.clear()}invalidateSearches(e){const t=this.fhirBaseUrl+e;if(this.requestCache)for(const e of this.requestCache.keys())(e.endsWith(t)||e.includes(t+"?"))&&this.requestCache.delete(e)}get(e,t={}){e=e.toString();const r=this.getCacheEntry(e,t);if(r)return r.value;let n;n=e.startsWith(this.fhirBaseUrl)&&this.autoBatchQueue?new Promise(((r,n)=>{this.autoBatchQueue.push({method:"GET",url:e.replace(this.fhirBaseUrl,""),options:t,resolve:r,reject:n}),this.autoBatchTimerId||(this.autoBatchTimerId=setTimeout((()=>this.executeAutoBatch()),this.autoBatchTime))})):this.request("GET",e,t);const i=new ze(n);return this.setCacheEntry(e,i),i}post(e,t,r,n={}){return e=e.toString(),t&&this.setRequestBody(n,t),r&&this.setRequestContentType(n,r),this.invalidateUrl(e),this.request("POST",e,n)}put(e,t,r,n={}){return e=e.toString(),t&&this.setRequestBody(n,t),r&&this.setRequestContentType(n,r),this.invalidateUrl(e),this.request("PUT",e,n)}patch(e,t,r={}){return e=e.toString(),this.setRequestBody(r,t),this.setRequestContentType(r,"application/json-patch+json"),this.invalidateUrl(e),this.request("PATCH",e,r)}delete(e,t){return e=e.toString(),this.invalidateUrl(e),this.request("DELETE",e,t)}async startNewUser(e,t){const{codeChallengeMethod:r,codeChallenge:n}=await this.startPkce();return this.post("auth/newuser",{...e,codeChallengeMethod:r,codeChallenge:n},void 0,t)}async startNewProject(e,t){return this.post("auth/newproject",e,void 0,t)}async startNewPatient(e,t){return this.post("auth/newpatient",e,void 0,t)}async startLogin(e,t){return this.post("auth/login",{...await this.ensureCodeChallenge(e),clientId:e.clientId??this.clientId,scope:e.scope},void 0,t)}async startGoogleLogin(e,t){return this.post("auth/google",{...await this.ensureCodeChallenge(e),clientId:e.clientId??this.clientId,scope:e.scope},void 0,t)}async ensureCodeChallenge(e){return e.codeChallenge?e:{...e,...await this.startPkce()}}async signOut(){await this.post(this.logoutUrl,{}),this.clear()}async signInWithRedirect(e){const t=new URLSearchParams(window.location.search).get("code");return t?this.processCode(t):void await this.requestAuthorization(e)}signOutWithRedirect(){window.location.assign(this.logoutUrl)}async signInWithExternalAuth(e,t,r,n){const i=await this.ensureCodeChallenge(n);window.location.assign(this.getExternalAuthRedirectUri(e,t,r,i))}async exchangeExternalAccessToken(e,t){if(!(t=t||this.clientId))throw new Error("MedplumClient is missing clientId");const r=new URLSearchParams;return r.set("grant_type",gt.TokenExchange),r.set("subject_token_type",vt.AccessToken),r.set("client_id",t),r.set("subject_token",e),this.fetchTokens(r)}getExternalAuthRedirectUri(e,t,r,n){const i=new URL(e);return i.searchParams.set("response_type","code"),i.searchParams.set("client_id",t),i.searchParams.set("redirect_uri",r),i.searchParams.set("scope","openid profile email"),i.searchParams.set("state",JSON.stringify(n)),i.toString()}fhirUrl(...e){return new URL(this.fhirBaseUrl+e.join("/"))}fhirSearchUrl(e,t){const r=this.fhirUrl(e);return t&&(r.search=new URLSearchParams(t).toString()),r}search(e,t,r){const n=this.fhirSearchUrl(e,t),i=n.toString()+"-search",o=this.getCacheEntry(i,r);if(o)return o.value;const s=new ze((async()=>{const e=await this.get(n,r);if(e.entry)for(const t of e.entry)this.cacheResource(t.resource);return e})());return this.setCacheEntry(i,s),s}searchOne(e,t,r){const n=this.fhirSearchUrl(e,t);n.searchParams.set("_count","1"),n.searchParams.sort();const i=n.toString()+"-searchOne",o=this.getCacheEntry(i,r);if(o)return o.value;const s=new ze(this.search(e,n.searchParams,r).then((e=>e.entry?.[0]?.resource)));return this.setCacheEntry(i,s),s}searchResources(e,t,r){const n=this.fhirSearchUrl(e,t).toString()+"-searchResources",i=this.getCacheEntry(n,r);if(i)return i.value;const o=new ze(this.search(e,t,r).then((e=>e.entry?.map((e=>e.resource))??[])));return this.setCacheEntry(n,o),o}async*searchResourcePages(e,t,r){let n=this.fhirSearchUrl(e,t);for(;n;){const t=new URL(n).searchParams,i=await this.search(e,t,r),o=i?.link?.find((e=>"next"===e.relation));if(!i?.entry?.length&&!o)break;yield i?.entry?.map((e=>e.resource))??[],n=o?.url?new URL(o?.url):void 0}}searchValueSet(e,t,r){const n=this.fhirUrl("ValueSet","$expand");return n.searchParams.set("url",e),n.searchParams.set("filter",t),this.get(n.toString(),r)}getCached(e,t){const r=this.requestCache?.get(this.fhirUrl(e,t).toString())?.value;return r&&r.isOk()?r.read():void 0}getCachedReference(e){const t=e.reference;if(!t)return;if("system"===t)return yt;const[r,n]=t.split("/");return r&&n?this.getCached(r,n):void 0}readResource(e,t,r){return this.get(this.fhirUrl(e,t),r)}readReference(e,t){const r=e?.reference;if(!r)return new ze(Promise.reject(new Error("Missing reference")));if("system"===r)return new ze(Promise.resolve(yt));const[n,i]=r.split("/");return n&&i?this.readResource(n,i,t):new ze(Promise.reject(new Error("Invalid reference")))}getSchema(){return ht}requestSchema(e){if(e in ht.types)return Promise.resolve(ht);const t=e+"-requestSchema",r=this.getCacheEntry(t,void 0);if(r)return r.value;const n=new ze((async()=>{const t=`{\n StructureDefinitionList(name: "${e}") {\n name,\n description,\n snapshot {\n element {\n id,\n path,\n min,\n max,\n type {\n code,\n targetProfile\n },\n binding {\n valueSet\n },\n definition\n }\n }\n }\n SearchParameterList(base: "${e}", _count: 100) {\n base,\n code,\n type,\n expression,\n target\n }\n }`.replace(/\s+/g," "),r=await this.graphql(t);for(const e of r.data.StructureDefinitionList)Ze(e);for(const e of r.data.SearchParameterList)et(e);return ht})());return this.setCacheEntry(t,n),n}readHistory(e,t,r){return this.get(this.fhirUrl(e,t,"_history"),r)}readVersion(e,t,r,n){return this.get(this.fhirUrl(e,t,"_history",r),n)}readPatientEverything(e,t){return this.get(this.fhirUrl("Patient",e,"$everything"),t)}createResource(e,t){if(!e.resourceType)throw new Error("Missing resourceType");return this.invalidateSearches(e.resourceType),this.post(this.fhirUrl(e.resourceType),e,void 0,t)}async createResourceIfNoneExist(e,t,r){return await this.searchOne(e.resourceType,t,r)??this.createResource(e,r)}createBinary(e,t,r,n){const i=this.fhirUrl("Binary");return t&&i.searchParams.set("_filename",t),n?this.uploadwithProgress(i,e,r,n):this.post(i,e,r)}uploadwithProgress(e,t,r,n){return new Promise(((i,o)=>{const s=new XMLHttpRequest;s.responseType="json",s.onabort=()=>o(new Error("Request aborted")),s.onerror=()=>o(new Error("Request error")),n&&(s.upload.onprogress=e=>n(e),s.upload.onload=e=>n(e)),s.onload=()=>{s.status>=200&&s.status<300?i(s.response):o(new Error(s.statusText))},s.open("POST",e),s.withCredentials=!0,s.setRequestHeader("Authorization","Bearer "+this.accessToken),s.setRequestHeader("Cache-Control","no-cache, no-store, max-age=0"),s.setRequestHeader("Content-Type",r),s.setRequestHeader("X-Medplum","extended"),s.send(t)}))}async createPdf(e,t,r,n){if(!this.createPdfImpl)throw new Error("PDF creation not enabled");const i=await this.createPdfImpl(e,r,n);return this.createBinary(i,t,"application/pdf")}createComment(e,t,r){const n=this.getProfile();let i,o;return"Encounter"===e.resourceType&&(i=k(e),o=e.subject),"ServiceRequest"===e.resourceType&&(i=e.encounter,o=e.subject),"Patient"===e.resourceType&&(o=k(e)),this.createResource({resourceType:"Communication",basedOn:[k(e)],encounter:i,subject:o,sender:n?k(n):void 0,sent:(new Date).toISOString(),payload:[{contentString:t}]},r)}async updateResource(e,t){if(!e.resourceType)throw new Error("Missing resourceType");if(!e.id)throw new Error("Missing id");this.invalidateSearches(e.resourceType);let r=await this.put(this.fhirUrl(e.resourceType,e.id),e,void 0,t);return r||(r=e),this.cacheResource(r),r}patchResource(e,t,r,n){return this.invalidateSearches(e),this.patch(this.fhirUrl(e,t),r,n)}deleteResource(e,t,r){return this.deleteCacheEntry(this.fhirUrl(e,t).toString()),this.invalidateSearches(e),this.delete(this.fhirUrl(e,t),r)}validateResource(e,t){return this.post(this.fhirUrl(e.resourceType,"$validate"),e,void 0,t)}executeBot(e,t,r,n){let i;if("string"==typeof e){const t=e;i=this.fhirUrl("Bot",t,"$execute")}else{const t=e;i=this.fhirUrl("Bot","$execute")+`?identifier=${t.system}|${t.value}`}return this.post(i,t,r,n)}executeBatch(e,t){return this.post(this.fhirBaseUrl.slice(0,-1),e,void 0,t)}sendEmail(e,t){return this.post("email/v1/send",e,"application/json",t)}graphql(e,t,r,n){return this.post(this.fhirUrl("$graphql"),{query:e,operationName:t,variables:r},"application/json",n)}readResourceGraph(e,t,r,n){return this.get(`${this.fhirUrl(e,t)}/$graph?graph=${r}`,n)}getActiveLogin(){return this.storage.getObject("activeLogin")}async setActiveLogin(e){this.clearActiveLogin(),this.accessToken=e.accessToken,this.basicAuth||(this.refreshToken=e.refreshToken,this.storage.setObject("activeLogin",e),this.addLogin(e),this.refreshPromise=void 0,await this.refreshProfile())}getAccessToken(){return this.accessToken}setAccessToken(e){this.accessToken=e,this.refreshToken=void 0,this.profile=void 0,this.config=void 0}getLogins(){return this.storage.getObject("logins")??[]}addLogin(e){const t=this.getLogins().filter((t=>t.profile?.reference!==e.profile?.reference));t.push(e),this.storage.setObject("logins",t)}async refreshProfile(){return this.profilePromise=new Promise(((e,t)=>{this.basicAuth||this.get("auth/me").then((t=>{this.profilePromise=void 0,this.profile=t.profile,this.config=t.config,this.dispatchEvent({type:"change"}),e(this.profile)})).catch(t)})),this.profilePromise}isLoading(){return!!this.profilePromise}getProfile(){return this.profile}async getProfileAsync(){return this.profilePromise&&await this.profilePromise,this.getProfile()}getUserConfiguration(){return this.config}async download(e,t={}){this.refreshPromise&&await this.refreshPromise,this.addFetchOptionsDefaults(t);return(await this.fetch(e.toString(),t)).blob()}async uploadMedia(e,t,r,n,i){const o=await this.createBinary(e,r,t);return this.createResource({...n,resourceType:"Media",content:{contentType:t,url:"Binary/"+o.id,title:r}},i)}async bulkExport(e="",t,r,n={}){const i=e?`${e}/`:e,o=this.fhirUrl(`${i}$export`);t&&o.searchParams.set("_type",t),r&&o.searchParams.set("_since",r),this.addFetchOptionsDefaults(n);n.headers.Prefer="respond-async";const s=await this.fetchWithRetry(o.toString(),n);if(202===s.status){const e=s.headers.get("content-location");if(e)return await this.pollStatus(e)}return await this.parseResponse(s,"POST",o.toString())}getCacheEntry(e,t){if(!this.requestCache||"no-cache"===t?.cache||"reload"===t?.cache)return;const r=this.requestCache.get(e);return!r||r.requestTime+this.cacheTime<Date.now()?void 0:r}setCacheEntry(e,t){this.requestCache&&this.requestCache.set(e,{requestTime:Date.now(),value:t})}cacheResource(e){e?.id&&this.setCacheEntry(this.fhirUrl(e.resourceType,e.id).toString(),new ze(Promise.resolve(e)))}deleteCacheEntry(e){this.requestCache&&this.requestCache.delete(e)}async request(e,t,r={}){this.refreshPromise&&await this.refreshPromise,t.startsWith("http")||(t=this.baseUrl+t),r.method=e,this.addFetchOptionsDefaults(r);const n=await this.fetchWithRetry(t,r);return await this.parseResponse(n,e,t,r)}async parseResponse(e,t,r,n={}){if(401===e.status)return this.handleUnauthenticated(t,r,n);if(204===e.status||304===e.status)return;if(404===e.status){const t=e.headers.get("content-type");if(!t?.includes("application/fhir+json"))throw new qe(Pe)}let i;try{i=await e.json()}catch(t){throw console.error("Error parsing response",e.status,t),t}if(e.status>=400)throw new qe(Qe(i));return i}async fetchWithRetry(e,t){let r;for(let n=0;n<3;n++){try{if(r=await this.fetch(e,t),r.status<500)return r}catch(e){this.retryCatch(n,3,e)}await new Promise((e=>setTimeout(e,200)))}return r}async pollStatus(e){let t,r=!0;for(;r;){const n={};this.addFetchOptionsDefaults(n);const i=await this.fetchWithRetry(e,n);202!==i.status&&(r=!1,t=i),await new Promise((e=>setTimeout(e,200)))}return await this.parseResponse(t,"POST",e)}async executeAutoBatch(){const e=[...this.autoBatchQueue];if(this.autoBatchQueue.length=0,this.autoBatchTimerId=void 0,1===e.length){const t=e[0];try{t.resolve(await this.request(t.method,this.fhirBaseUrl+t.url,t.options))}catch(e){t.reject(new qe(Qe(e)))}return}const t={resourceType:"Bundle",type:"batch",entry:e.map((e=>({request:{method:e.method,url:e.url},resource:e.options.body?JSON.parse(e.options.body):void 0})))},r=await this.post(this.fhirBaseUrl.slice(0,-1),t);for(let t=0;t<e.length;t++){const n=e[t],i=r.entry?.[t];i?.response?.outcome&&!Me(i.response.outcome)?n.reject(new qe(i.response.outcome)):n.resolve(i?.resource)}}addFetchOptionsDefaults(e){let t=e.headers;t||(t={},e.headers=t),t.Accept=mt,t["X-Medplum"]="extended",e.body&&!t["Content-Type"]&&(t["Content-Type"]=mt),this.accessToken?t.Authorization="Bearer "+this.accessToken:this.basicAuth&&(t.Authorization="Basic "+this.basicAuth),e.cache||(e.cache="no-cache"),e.credentials||(e.credentials="include")}setRequestContentType(e,t){e.headers||(e.headers={});e.headers["Content-Type"]=t}setRequestBody(e,t){"string"==typeof t||"undefined"!=typeof Blob&&t instanceof Blob||"undefined"!=typeof File&&t instanceof File||"undefined"!=typeof Uint8Array&&t instanceof Uint8Array?e.body=t:t&&(e.body=JSON.stringify(t))}handleUnauthenticated(e,t,r){return this.refresh()?this.request(e,t,r):(this.clearActiveLogin(),this.onUnauthenticated&&this.onUnauthenticated(),Promise.reject(new Error("Unauthenticated")))}async startPkce(){const e=he();sessionStorage.setItem("pkceState",e);const t=he();sessionStorage.setItem("codeVerifier",t);const r=J(await async function(e){return crypto.subtle.digest("SHA-256",(new TextEncoder).encode(e))}(t)).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"");return sessionStorage.setItem("codeChallenge",r),{codeChallengeMethod:"S256",codeChallenge:r}}async requestAuthorization(e){const t=await this.ensureCodeChallenge(e||{}),r=new URL(this.authorizeUrl);r.searchParams.set("response_type","code"),r.searchParams.set("state",sessionStorage.getItem("pkceState")),r.searchParams.set("client_id",t.clientId||this.clientId),r.searchParams.set("redirect_uri",t.redirectUri||St()),r.searchParams.set("code_challenge_method",t.codeChallengeMethod),r.searchParams.set("code_challenge",t.codeChallenge),r.searchParams.set("scope",t.scope||"openid profile"),window.location.assign(r.toString())}processCode(e,t){const r=new URLSearchParams;if(r.set("grant_type",gt.AuthorizationCode),r.set("code",e),r.set("client_id",t?.clientId||this.clientId),r.set("redirect_uri",t?.redirectUri||St()),"undefined"!=typeof sessionStorage){const e=sessionStorage.getItem("codeVerifier");e&&r.set("code_verifier",e)}return this.fetchTokens(r)}refresh(){if(this.refreshPromise)return this.refreshPromise;if(this.refreshToken){const e=new URLSearchParams;return e.set("grant_type",gt.RefreshToken),e.set("client_id",this.clientId),e.set("refresh_token",this.refreshToken),this.refreshPromise=this.fetchTokens(e),this.refreshPromise}return this.clientId&&this.clientSecret?(this.refreshPromise=this.startClientLogin(this.clientId,this.clientSecret),this.refreshPromise):void 0}async startClientLogin(e,t){this.clientId=e,this.clientSecret=t;const r=new URLSearchParams;return r.set("grant_type",gt.ClientCredentials),r.set("client_id",e),r.set("client_secret",t),this.fetchTokens(r)}setBasicAuth(e,r){this.clientId=e,this.clientSecret=r,this.basicAuth=t(e+":"+r)}async invite(e,t){return this.post("admin/projects/"+e+"/invite",t)}async fetchTokens(e){const t={method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:e,credentials:"include"},r=t.headers;this.basicAuth&&(r.Authorization=`Basic ${this.basicAuth}`);const n=await this.fetch(this.tokenUrl,t);if(!n.ok)throw this.clearActiveLogin(),new Error("Failed to fetch tokens");const i=await n.json();return await this.verifyTokens(i),this.getProfile()}async verifyTokens(e){const t=e.access_token,r=me(t);if(Date.now()>=1e3*r.exp)throw this.clearActiveLogin(),new Error("Token expired");if(r.cid){if(r.cid!==this.clientId)throw this.clearActiveLogin(),new Error("Token was not issued for this audience")}else if(this.clientId&&r.client_id!==this.clientId)throw this.clearActiveLogin(),new Error("Token was not issued for this audience");return this.setActiveLogin({accessToken:t,refreshToken:e.refresh_token,project:e.project,profile:e.profile})}setupStorageListener(){try{window.addEventListener("storage",(e=>{null!==e.key&&"activeLogin"!==e.key||window.location.reload()}))}catch(e){}}retryCatch(e,t,r){if("Failed to fetch"===r.message&&1===e&&this.dispatchEvent({type:"offline"}),e>=t-1)throw r}}function St(){return"undefined"==typeof window?"":window.location.protocol+"//"+window.location.host+"/"}function bt(e){return e?e.endsWith("/")?e:e+"/":e}class wt{constructor(e,t){this.operator=e,this.child=t}toString(){return`${this.operator}(${this.child.toString()})`}}class Tt{constructor(e,t,r){this.operator=e,this.left=t,this.right=r}toString(){return`${this.left.toString()} ${this.operator} ${this.right.toString()}`}}class Et{constructor(){this.prefixParselets={},this.infixParselets={}}registerInfix(e,t){return this.infixParselets[e]=t,this}registerPrefix(e,t){return this.prefixParselets[e]=t,this}prefix(e,t,r){return this.registerPrefix(e,{parse(e,n){const i=e.consumeAndParse(t);return r(n,i)}})}infixLeft(e,t,r){return this.registerInfix(e,{parse(e,n,i){const o=e.consumeAndParse(t);return r(n,i,o)},precedence:t})}construct(e){return new kt(e,this.prefixParselets,this.infixParselets)}}class kt{constructor(e,t,r){this.tokens=e,this.prefixParselets=t,this.infixParselets=r}hasMore(){return this.tokens.length>0}match(e){const t=this.peek();return t?.id===e&&(this.consume(),!0)}consumeAndParse(e=1/0){const t=this.consume(),r=this.prefixParselets[t.id];if(!r)throw Error(`Parse error at "${t.value}" (line ${t.line}, column ${t.column}). No matching prefix parselet.`);let n=r.parse(this,t);for(;e>this.getPrecedence();){const e=this.consume();n=this.getInfixParselet(e).parse(this,n,e)}return n}getPrecedence(){const e=this.peek();if(!e)return 1/0;const t=this.getInfixParselet(e);return t?t.precedence:1/0}consume(e,t){if(!this.tokens.length)throw Error("Cant consume unknown more tokens.");if(e&&this.peek()?.id!==e){const t=this.peek();throw Error(`Expected ${e} but got "${t.id}" at line ${t.line} column ${t.column}.`)}if(t&&this.peek()?.value!==t){const e=this.peek();throw Error(`Expected "${t}" but got "${e.value}" at line ${e.line} column ${e.column}.`)}return this.tokens.shift()}peek(){return this.tokens.length>0?this.tokens[0]:void 0}removeComments(){this.tokens=this.tokens.filter((e=>"Comment"!==e.id))}getInfixParselet(e){return this.infixParselets["Symbol"===e.id?e.value:e.id]}}const Ct=["year","years","month","months","week","weeks","day","days","hour","hours","minute","minutes","second","seconds","millisecond","milliseconds"];class Pt{constructor(e,t,r,n){this.result=[],this.pos={index:0,line:1,column:0},this.markStack=[],this.str=e,this.keywords=t,this.operators=r,this.dateTimeLiterals=!!n?.dateTimeLiterals,this.symbolRegex=n?.symbolRegex??/[$\w]/}tokenize(){for(;this.pos.index<this.str.length;){const e=this.consumeToken();e&&this.result.push(e)}return this.result}prevToken(){return this.result.slice(-1)[0]}peekToken(){this.mark();const e=this.consumeToken();return this.reset(),e}consumeToken(){this.consumeWhitespace();const e=this.curr();if(!e)return;this.mark();const t=this.peek();return"/"===e&&"*"===t?this.consumeMultiLineComment():"/"===e&&"/"===t?this.consumeSingleLineComment():"'"===e||'"'===e?this.consumeString(e):"`"===e?this.consumeBacktickSymbol():"@"===e?this.consumeDateTime():e.match(/\d/)?this.consumeNumber():e.match(/\w/)||"$"===e&&t.match(/\w/)?this.consumeSymbol():this.consumeOperator()}consumeWhitespace(){this.consumeWhile((()=>this.curr().match(/\s/)))}consumeMultiLineComment(){const 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((()=>"\n"!==this.curr())))}consumeString(e){this.advance();const t=this.buildToken("String",this.consumeWhile((()=>"\\"===this.prev()||this.curr()!==e)));return this.advance(),t}consumeBacktickSymbol(){this.advance();const e=this.buildToken("Symbol",this.consumeWhile((()=>"`"!==this.curr())));return this.advance(),e}consumeDateTime(){this.advance();const e=this.pos.index;return this.consumeWhile((()=>this.curr().match(/[\d-]/))),"T"===this.curr()&&(this.advance(),this.consumeWhile((()=>this.curr().match(/[\d:]/))),"."===this.curr()&&this.peek().match(/\d/)&&(this.advance(),this.consumeWhile((()=>this.curr().match(/\d/)))),"Z"===this.curr()?this.advance():"+"!==this.curr()&&"-"!==this.curr()||(this.advance(),this.consumeWhile((()=>this.curr().match(/[\d:]/))))),this.buildToken("DateTime",this.str.substring(e,this.pos.index))}consumeNumber(){const e=this.pos.index;let t="Number";return this.consumeWhile((()=>this.curr().match(/\d/))),"."===this.curr()&&this.peek().match(/\d/)&&(this.advance(),this.consumeWhile((()=>this.curr().match(/\d/)))),"-"===this.curr()&&this.dateTimeLiterals?(this.pos.index=e-1,this.consumeDateTime()):(" "===this.curr()&&function(e){if(e){if("String"===e.id)return!0;if("Symbol"===e.id&&Ct.includes(e.value))return!0}return!1}(this.peekToken())&&(t="Quantity",this.consumeToken()),this.buildToken(t,this.str.substring(e,this.pos.index)))}consumeSymbol(){const e=this.consumeWhile((()=>this.curr().match(this.symbolRegex)));return"."!==this.prevToken()?.value&&this.keywords.includes(e)?this.buildToken(e,e):this.buildToken("Symbol",e)}consumeOperator(){const e=this.curr(),t=e+this.peek();return this.operators.includes(t)?(this.advance(),this.advance(),this.buildToken(t,t)):(this.advance(),this.buildToken(e,e))}consumeWhile(e){const 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]}prev(){return this.str[this.pos.index-1]??""}peek(){return this.str[this.pos.index+1]??""}mark(){this.markStack.push({...this.pos})}reset(){const 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++,"\n"===this.curr()?(this.pos.line++,this.pos.column=0):this.pos.column++}buildToken(e,t){const r=this.markStack.pop();if(!r)throw new Error("No mark for token");return{id:e,value:t,...r}}}function Rt(e){if(e.startsWith("T"))return e+"T00:00:00.000Z".substring(e.length);if(e.length<=10)return e;try{return new Date(e).toISOString()}catch(t){return e}}function Dt(e){return[{type:Xe.boolean,value:e}]}function At(e){return null==e?{type:"undefined",value:void 0}:Number.isSafeInteger(e)?{type:Xe.integer,value:e}:"number"==typeof e?{type:Xe.decimal,value:e}:"boolean"==typeof e?{type:Xe.boolean,value:e}:"string"==typeof e?{type:Xe.string,value:e}:Ft(e)?{type:Xe.Quantity,value:e}:pt(e)?{type:e.resourceType,value:e}:{type:Xe.BackboneElement,value:e}}function It(e){return 0!==e.length&&!!e[0].value}function Ut(e,t){if(!e?.value)return;const r=dt(e.type,t);if(r){const n=function(e,t,r){const n=r.type;if(!n||0===n.length)return;let i,o="undefined";if(1===n.length)i=e.value[t],o=n[0].code;else for(const r of n){const n=t.replace("[x]","")+Y(r.code);if(n in e.value){i=e.value[n],o=r.code;break}}if(Q(i))return;"Element"!==o&&"BackboneElement"!==o||(o=rt(r.path?.split(".")));return Array.isArray(i)?i.map((e=>Ot(e,o))):Ot(i,o)}(e,t,r);if(n)return n}return function(e,t){const r=e.value;if(!r||"object"!=typeof r)return;let n;if(t in r)n=r[t];else for(const e in Xe){const i=t+Y(e);if(i in r){n=r[i];break}}if(Q(n))return;return Array.isArray(n)?n.map(At):At(n)}(e,t)}function Ot(e,t){return"Resource"===t&&pt(e)&&(t=e.resourceType),{type:t,value:e}}function Lt(e){const t=[];for(const r of e){let e=!1;for(const n of t)if(It(_t(r,n))){e=!0;break}e||t.push(r)}return t}function Nt(e){return Dt(!It(e))}function Mt(e,t){return 0===e.length||0===t.length?[]:e.length!==t.length?Dt(!1):Dt(e.every(((e,r)=>It(_t(e,t[r])))))}function _t(e,t){const r=e.value,n=t.value;return"number"==typeof r&&"number"==typeof n?Dt(Math.abs(r-n)<1e-8):Ft(r)&&Ft(n)?Dt(Wt(r,n)):Dt("object"==typeof r&&"object"==typeof n?Ht(e,t):r===n)}function Bt(e,t){return 0===e.length&&0===t.length?Dt(!0):e.length!==t.length?Dt(!1):(e.sort($t),t.sort($t),Dt(e.every(((e,r)=>It(jt(e,t[r]))))))}function jt(e,t){const r=e.value,n=t.value;return"number"==typeof r&&"number"==typeof n?Dt(Math.abs(r-n)<.01):Ft(r)&&Ft(n)?Dt(Wt(r,n)):Dt("object"==typeof r&&"object"==typeof n?Ht(r,n):"string"==typeof r&&"string"==typeof n?r.toLowerCase()===n.toLowerCase():r===n)}function $t(e,t){const r=e.value,n=t.value;return"number"==typeof r&&"number"==typeof n?r-n:"string"==typeof r&&"string"==typeof n?r.localeCompare(n):0}function qt(e,t){const{value:r}=e;if(null==r)return!1;switch(t){case"Boolean":return"boolean"==typeof r;case"Decimal":case"Integer":return"number"==typeof r;case"Date":return"string"==typeof r&&!!r.match(/^\d{4}(-\d{2}(-\d{2})?)?/);case"DateTime":return"string"==typeof r&&!!r.match(/^\d{4}(-\d{2}(-\d{2})?)?T/);case"Time":return"string"==typeof r&&!!r.match(/^T\d/);case"Period":return Qt(r);case"Quantity":return Ft(r);default:return"object"==typeof r&&r?.resourceType===t}}function Qt(e){return!(!e||"object"!=typeof e||!("start"in e))}function Ft(e){return!(!e||"object"!=typeof e||!("value"in e)||"number"!=typeof e.value)}function Wt(e,t){return Math.abs(e.value-t.value)<.01&&(e.unit===t.unit||e.code===t.code||e.unit===t.code||e.code===t.unit)}function Ht(e,t){const r=Object.keys(e),n=Object.keys(t);if(r.length!==n.length)return!1;for(const n of r){const r=e[n],i=t[n];if(zt(r)&&zt(i)){if(!Ht(r,i))return!1}else if(r!==i)return!1}return!0}function zt(e){return null!==e&&"object"==typeof e}const Gt=()=>[],Vt={empty:e=>Dt(0===e.length),exists:(e,t)=>Dt(t?e.filter((e=>It(t.eval([e])))).length>0:e.length>0),all:(e,t)=>Dt(e.every((e=>It(t.eval([e]))))),allTrue:e=>{for(const t of e)if(!t.value)return Dt(!1);return Dt(!0)},anyTrue:e=>{for(const t of e)if(t.value)return Dt(!0);return Dt(!1)},allFalse:e=>{for(const t of e)if(t.value)return Dt(!1);return Dt(!0)},anyFalse:e=>{for(const t of e)if(!t.value)return Dt(!0);return Dt(!1)},subsetOf:Gt,supersetOf:Gt,count:e=>[{type:Xe.integer,value:e.length}],distinct:e=>{const t=[];for(const r of e)t.some((e=>e.value===r.value))||t.push(r);return t},isDistinct:e=>Dt(e.length===Vt.distinct(e).length),where:(e,t)=>e.filter((e=>It(t.eval([e])))),select:(e,t)=>e.map((e=>t.eval([e]))).flat(),repeat:Gt,ofType:(e,t)=>e.filter((e=>e.type===t.name)),single:e=>{if(e.length>1)throw new Error("Expected input length one for single()");return 0===e.length?[]:e.slice(0,1)},first:e=>0===e.length?[]:e.slice(0,1),last:e=>0===e.length?[]:e.slice(e.length-1,e.length),tail:e=>0===e.length?[]:e.slice(1,e.length),skip:(e,t)=>{const r=t.eval(e)[0]?.value;if("number"!=typeof r)throw new Error("Expected a number for skip(num)");return r>=e.length?[]:r<=0?e:e.slice(r,e.length)},take:(e,t)=>{const r=t.eval(e)[0]?.value;if("number"!=typeof r)throw new Error("Expected a number for take(num)");return r>=e.length?e:r<=0?[]:e.slice(0,r)},intersect:(e,t)=>{if(!t)return e;const r=t.eval(e),n=[];for(const t of e)!n.some((e=>e.value===t.value))&&r.some((e=>e.value===t.value))&&n.push(t);return n},exclude:(e,t)=>{if(!t)return e;const r=t.eval(e),n=[];for(const t of e)r.some((e=>e.value===t.value))||n.push(t);return n},union:(e,t)=>{if(!t)return e;const r=t.eval(e);return Lt([...e,...r])},combine:(e,t)=>{if(!t)return e;const r=t.eval(e);return[...e,...r]},iif:(e,t,r,n)=>{const i=t.eval(e);if(i.length>1||1===i.length&&"boolean"!=typeof i[0].value)throw new Error("Expected criterion to evaluate to a Boolean");return It(i)?r.eval(e):n?n.eval(e):[]},toBoolean:e=>{if(0===e.length)return[];const[{value:t}]=Yt(e,1);if("boolean"==typeof t)return[{type:Xe.boolean,value:t}];if("number"==typeof t&&(0===t||1===t))return Dt(!!t);if("string"==typeof t){const e=t.toLowerCase();if(["true","t","yes","y","1","1.0"].includes(e))return Dt(!0);if(["false","f","no","n","0","0.0"].includes(e))return Dt(!1)}return[]},convertsToBoolean:e=>0===e.length?[]:Dt(1===Vt.toBoolean(e).length),toInteger:e=>{if(0===e.length)return[];const[{value:t}]=Yt(e,1);return"number"==typeof t?[{type:Xe.integer,value:t}]:"string"==typeof t&&t.match(/^[+-]?\d+$/)?[{type:Xe.integer,value:parseInt(t,10)}]:"boolean"==typeof t?[{type:Xe.integer,value:t?1:0}]:[]},convertsToInteger:e=>0===e.length?[]:Dt(1===Vt.toInteger(e).length),toDate:e=>{if(0===e.length)return[];const[{value:t}]=Yt(e,1);return"string"==typeof t&&t.match(/^\d{4}(-\d{2}(-\d{2})?)?/)?[{type:Xe.date,value:Rt(t)}]:[]},convertsToDate:e=>0===e.length?[]:Dt(1===Vt.toDate(e).length),toDateTime:e=>{if(0===e.length)return[];const[{value:t}]=Yt(e,1);return"string"==typeof t&&t.match(/^\d{4}(-\d{2}(-\d{2})?)?/)?[{type:Xe.dateTime,value:Rt(t)}]:[]},convertsToDateTime:e=>0===e.length?[]:Dt(1===Vt.toDateTime(e).length),toDecimal:e=>{if(0===e.length)return[];const[{value:t}]=Yt(e,1);return"number"==typeof t?[{type:Xe.decimal,value:t}]:"string"==typeof t&&t.match(/^-?\d{1,9}(\.\d{1,9})?$/)?[{type:Xe.decimal,value:parseFloat(t)}]:"boolean"==typeof t?[{type:Xe.decimal,value:t?1:0}]:[]},convertsToDecimal:e=>0===e.length?[]:Dt(1===Vt.toDecimal(e).length),toQuantity:e=>{if(0===e.length)return[];const[{value:t}]=Yt(e,1);return Ft(t)?[{type:Xe.Quantity,value:t}]:"number"==typeof t?[{type:Xe.Quantity,value:{value:t,unit:"1"}}]:"string"==typeof t&&t.match(/^-?\d{1,9}(\.\d{1,9})?/)?[{type:Xe.Quantity,value:{value:parseFloat(t),unit:"1"}}]:"boolean"==typeof t?[{type:Xe.Quantity,value:{value:t?1:0,unit:"1"}}]:[]},convertsToQuantity:e=>0===e.length?[]:Dt(1===Vt.toQuantity(e).length),toString:e=>{if(0===e.length)return[];const[{value:t}]=Yt(e,1);return null==t?[]:Ft(t)?[{type:Xe.string,value:`${t.value} '${t.unit}'`}]:[{type:Xe.string,value:t.toString()}]},convertsToString:e=>0===e.length?[]:Dt(1===Vt.toString(e).length),toTime:e=>{if(0===e.length)return[];const[{value:t}]=Yt(e,1);if("string"==typeof t){const e=t.match(/^T?(\d{2}(:\d{2}(:\d{2})?)?)/);if(e)return[{type:Xe.time,value:Rt("T"+e[1])}]}return[]},convertsToTime:e=>0===e.length?[]:Dt(1===Vt.toTime(e).length),indexOf:(e,t)=>Xt(((e,t)=>e.indexOf(t)),e,t),substring:(e,t,r)=>Xt(((e,t,r)=>{const n=t,i=r?n+r:e.length;return n<0||n>=e.length?void 0:e.substring(n,i)}),e,t,r),startsWith:(e,t)=>Xt(((e,t)=>e.startsWith(t)),e,t),endsWith:(e,t)=>Xt(((e,t)=>e.endsWith(t)),e,t),contains:(e,t)=>Xt(((e,t)=>e.includes(t)),e,t),upper:e=>Xt((e=>e.toUpperCase()),e),lower:e=>Xt((e=>e.toLowerCase()),e),replace:(e,t,r)=>Xt(((e,t,r)=>e.replaceAll(t,r)),e,t,r),matches:(e,t)=>Xt(((e,t)=>!!e.match(t)),e,t),replaceMatches:(e,t,r)=>Xt(((e,t,r)=>e.replaceAll(t,r)),e,t,r),length:e=>Xt((e=>e.length),e),toChars:e=>Xt((e=>e?e.split(""):void 0),e),abs:e=>Jt(Math.abs,e),ceiling:e=>Jt(Math.ceil,e),exp:e=>Jt(Math.exp,e),floor:e=>Jt(Math.floor,e),ln:e=>Jt(Math.log,e),log:(e,t)=>Jt(((e,t)=>Math.log(e)/Math.log(t)),e,t),power:(e,t)=>Jt(Math.pow,e,t),round:e=>Jt(Math.round,e),sqrt:e=>Jt(Math.sqrt,e),truncate:e=>Jt((e=>0|e),e),children:Gt,descendants:Gt,trace:(e,t)=>(console.log("trace",e,t),e),now:()=>[{type:Xe.dateTime,value:(new Date).toISOString()}],timeOfDay:()=>[{type:Xe.time,value:(new Date).toISOString().substring(11)}],today:()=>[{type:Xe.date,value:(new Date).toISOString().substring(0,10)}],between:(e,t,r,n)=>{const i=Vt.toDateTime(t.eval(e));if(0===i.length)throw new Error("Invalid start date");const o=Vt.toDateTime(r.eval(e));if(0===o.length)throw new Error("Invalid end date");const s=n.eval(e)[0]?.value;if("years"!==s&&"months"!==s&&"days"!==s)throw new Error("Invalid units");const a=O(i[0].value,o[0].value);return[{type:Xe.Quantity,value:{value:a[s],unit:s}}]},is:(e,t)=>{let r="";return t instanceof er?r=t.name:t instanceof cr&&(r=t.left.name+"."+t.right.name),r?e.map((e=>({type:Xe.boolean,value:qt(e,r)}))):[]},not:e=>Vt.toBoolean(e).map((e=>({type:Xe.boolean,value:!e.value}))),resolve:e=>e.map((e=>{const t=e.value;let r;if("string"==typeof t)r=t;else if("object"==typeof t){const e=t;if(e.resource)return At(e.resource);e.reference?r=e.reference:e.type&&e.identifier&&(r=`${e.type}?identifier=${e.identifier.system}|${e.identifier.value}`)}if(r?.includes("?")){const[e]=r.split("?");return{type:e,value:{resourceType:e}}}if(r?.includes("/")){const[e,t]=r.split("/");return{type:e,value:{resourceType:e,id:t}}}return{type:Xe.BackboneElement,value:void 0}})).filter((e=>!!e.value)),as:e=>e,type:e=>e.map((({value:e})=>"boolean"==typeof e?{type:Xe.BackboneElement,value:{namespace:"System",name:"Boolean"}}:"number"==typeof e?{type:Xe.BackboneElement,value:{namespace:"System",name:"Integer"}}:pt(e)?{type:Xe.BackboneElement,value:{namespace:"FHIR",name:e.resourceType}}:{type:Xe.BackboneElement,value:null})),conformsTo:(e,t)=>{const r=t.eval(e)[0].value;if(!r.startsWith("http://hl7.org/fhir/StructureDefinition/"))throw new Error("Expected a StructureDefinition URL");const n=r.replace("http://hl7.org/fhir/StructureDefinition/","");return e.map((e=>({type:Xe.boolean,value:e.value?.resourceType===n})))}};function Xt(e,t,...r){if(0===t.length)return[];const[{value:n}]=Yt(t,1);if("string"!=typeof n)throw new Error("String function cannot be called with non-string");const i=e(n,...r.map((e=>e&&e.eval(t)?.[0]?.value)));return void 0===i?[]:Array.isArray(i)?i.map(At):[At(i)]}function Jt(e,t,...r){if(0===t.length)return[];const[{value:n}]=Yt(t,1),i=Ft(n),o=i?n.value:n;if("number"!=typeof o)throw new Error("Math function cannot be called with non-number");const s=e(o,...r.map((e=>e.eval(t)?.[0]?.value)));return[{type:i?Xe.Quantity:t[0].type,value:i?{...n,value:s}:s}]}function Yt(e,t){if(e.length!==t)throw new Error(`Expected ${t} arguments`);for(const t of e)if(null==t)throw new Error("Expected non-null argument");return e}class Zt{constructor(e,t){this.original=e,this.child=t}eval(e){try{return e.length>0?e.map((e=>this.child.eval([e]))).flat():this.child.eval([])}catch(e){throw new Error(`FhirPathError on "${this.original}": ${e}`)}}toString(){return this.child.toString()}}class Kt{constructor(e){this.value=e}eval(){return[this.value]}toString(){const e=this.value.value;return"string"==typeof e?`'${e}'`:e.toString()}}class er{constructor(e){this.name=e}eval(e){return"$this"===this.name?e:e.flatMap((e=>this.evalValue(e))).filter((e=>void 0!==e?.value))}evalValue(e){const t=e.value;if(t&&"object"==typeof t)return pt(t)&&t.resourceType===this.name?e:Ut(e,this.name)}toString(){return this.name}}class tr{eval(){return[]}toString(){return"{}"}}class rr extends wt{constructor(e,t,r){super(e,t),this.impl=r}eval(e){return this.impl(this.child.eval(e))}toString(){return this.child.toString()}}class nr extends Tt{constructor(e,t){super("as",e,t)}eval(e){return Vt.ofType(this.left.eval(e),this.right)}}class ir extends Tt{constructor(e,t,r,n){super(e,t,r),this.impl=n}eval(e){const t=this.left.eval(e);if(1!==t.length)return[];const r=this.right.eval(e);if(1!==r.length)return[];const n=t[0].value,i=r[0].value,o=Ft(n)?n.value:n,s=Ft(i)?i.value:i,a=this.impl(o,s);return"boolean"==typeof a?Dt(a):Ft(n)?[{type:Xe.Quantity,value:{...n,value:a}}]:[At(a)]}}class or extends Tt{constructor(e,t){super("&",e,t)}eval(e){const t=[...this.left.eval(e),...this.right.eval(e)];return t.length>0&&t.every((e=>"string"==typeof e.value))?[{type:Xe.string,value:t.map((e=>e.value)).join("")}]:t}}class sr extends Tt{constructor(e,t){super("contains",e,t)}eval(e){const t=this.left.eval(e),r=this.right.eval(e);return Dt(t.some((e=>e.value===r[0].value)))}}class ar extends Tt{constructor(e,t){super("in",e,t)}eval(e){const t=this.left.eval(e);return Dt(this.right.eval(e).some((e=>e.value===t[0].value)))}}class cr extends Tt{constructor(e,t){super(".",e,t)}eval(e){return this.right.eval(this.left.eval(e))}toString(){return`${this.left.toString()}.${this.right.toString()}`}}class ur extends Tt{constructor(e,t){super("|",e,t)}eval(e){return Lt([...this.left.eval(e),...this.right.eval(e)])}}class dr extends Tt{constructor(e,t){super("=",e,t)}eval(e){return Mt(this.left.eval(e),this.right.eval(e))}}class pr extends Tt{constructor(e,t){super("!=",e,t)}eval(e){return Nt(Mt(this.left.eval(e),this.right.eval(e)))}}class lr extends Tt{constructor(e,t){super("~",e,t)}eval(e){return Bt(this.left.eval(e),this.right.eval(e))}}class hr extends Tt{constructor(e,t){super("!~",e,t)}eval(e){return Nt(Bt(this.left.eval(e),this.right.eval(e)))}}class fr extends Tt{constructor(e,t){super("is",e,t)}eval(e){const t=this.left.eval(e);if(1!==t.length)return[];const r=this.right.name;return Dt(qt(t[0],r))}}class mr extends Tt{constructor(e,t){super("and",e,t)}eval(e){const t=this.left.eval(e),r=this.right.eval(e);return!0===t[0]?.value&&!0===r[0]?.value?Dt(!0):!1===t[0]?.value||!1===r[0]?.value?Dt(!1):[]}}class yr extends Tt{constructor(e,t){super("or",e,t)}eval(e){const t=this.left.eval(e);if(It(t))return t;const r=this.right.eval(e);return It(r)?r:[]}}class gr extends Tt{constructor(e,t){super("xor",e,t)}eval(e){const t=this.left.eval(e),r=this.right.eval(e);if(0===t.length&&0===r.length)return[];const n=0===t.length?null:t[0].value,i=0===r.length?null:r[0].value;return!0===n&&!0!==i||!0!==n&&!0===i?Dt(!0):!0===n&&!0===i||!1===n&&!1===i?Dt(!1):[]}}class vr{constructor(e,t){this.name=e,this.args=t}eval(e){const t=Vt[this.name];if(!t)throw new Error("Unrecognized function: "+this.name);return t(e,...this.args)}toString(){return`${this.name}(${this.args.map((e=>e.toString())).join(", ")})`}}class xr{constructor(e,t){this.left=e,this.expr=t}eval(e){const t=this.expr.eval(e);if(1!==t.length)return[];const r=t[0].value;if("number"!=typeof r)throw new Error("Invalid indexer expression: should return integer}");const n=this.left.eval(e);return r in n?[n[r]]:[]}toString(){return`${this.left.toString()}[${this.expr.toString()}]`}}const Sr=["true","false"],br=["!=","!~","<=",">=","{}","->"];function wr(e){return new Pt(e,Sr,br).tokenize()}const Tr={parse(e){const t=e.consumeAndParse();if(!e.match(")"))throw new Error("Parse error: expected `)` got `"+e.peek()?.value+"`");return t}},Er={parse(e,t){const r=e.consumeAndParse();if(!e.match("]"))throw new Error("Parse error: expected `]`");return new xr(t,r)},precedence:2},kr={parse(e,t){if(!(t instanceof er))throw new Error("Unexpected parentheses");const r=[];for(;!e.match(")");)r.push(e.consumeAndParse()),e.match(",");return new vr(t.name,r)},precedence:0};function Cr(e){const t=e.split(" "),r=parseFloat(t[0]);let n=t[1];return n=n&&n.startsWith("'")&&n.endsWith("'")?n.substring(1,n.length-1):"{"+n+"}",{value:r,unit:n}}function Pr(){return(new Et).registerPrefix("String",{parse:(e,t)=>new Kt({type:Xe.string,value:t.value})}).registerPrefix("DateTime",{parse:(e,t)=>new Kt({type:Xe.dateTime,value:Rt(t.value)})}).registerPrefix("Quantity",{parse:(e,t)=>new Kt({type:Xe.Quantity,value:Cr(t.value)})}).registerPrefix("Number",{parse:(e,t)=>new Kt({type:Xe.decimal,value:parseFloat(t.value)})}).registerPrefix("true",{parse:()=>new Kt({type:Xe.boolean,value:!0})}).registerPrefix("false",{parse:()=>new Kt({type:Xe.boolean,value:!1})}).registerPrefix("Symbol",{parse:(e,t)=>new er(t.value)}).registerPrefix("{}",{parse:()=>new tr}).registerPrefix("(",Tr).registerInfix("[",Er).registerInfix("(",kr).prefix("+",3,((e,t)=>new rr("+",t,(e=>e)))).prefix("-",3,((e,t)=>new ir("-",t,t,((e,t)=>-t)))).infixLeft(".",1,((e,t,r)=>new cr(e,r))).infixLeft("/",4,((e,t,r)=>new ir("/",e,r,((e,t)=>e/t)))).infixLeft("*",4,((e,t,r)=>new ir("*",e,r,((e,t)=>e*t)))).infixLeft("+",5,((e,t,r)=>new ir("+",e,r,((e,t)=>e+t)))).infixLeft("-",5,((e,t,r)=>new ir("-",e,r,((e,t)=>e-t)))).infixLeft("|",7,((e,t,r)=>new ur(e,r))).infixLeft("=",9,((e,t,r)=>new dr(e,r))).infixLeft("!=",9,((e,t,r)=>new pr(e,r))).infixLeft("~",9,((e,t,r)=>new lr(e,r))).infixLeft("!~",9,((e,t,r)=>new hr(e,r))).infixLeft("<",8,((e,t,r)=>new ir("<",e,r,((e,t)=>e<t)))).infixLeft("<=",8,((e,t,r)=>new ir("<=",e,r,((e,t)=>e<=t)))).infixLeft(">",8,((e,t,r)=>new ir(">",e,r,((e,t)=>e>t)))).infixLeft(">=",8,((e,t,r)=>new ir(">=",e,r,((e,t)=>e>=t)))).infixLeft("&",5,((e,t,r)=>new or(e,r))).infixLeft("and",6,((e,t,r)=>new mr(e,r))).infixLeft("as",6,((e,t,r)=>new nr(e,r))).infixLeft("contains",6,((e,t,r)=>new sr(e,r))).infixLeft("div",6,((e,t,r)=>new ir("div",e,r,((e,t)=>e/t|0)))).infixLeft("in",6,((e,t,r)=>new ar(e,r))).infixLeft("is",6,((e,t,r)=>new fr(e,r))).infixLeft("mod",6,((e,t,r)=>new ir("mod",e,r,((e,t)=>e%t)))).infixLeft("or",6,((e,t,r)=>new yr(e,r))).infixLeft("xor",6,((e,t,r)=>new gr(e,r)))}const Rr=Pr();function Dr(e){return new Zt(e,Rr.construct(wr(e)).consumeAndParse())}function Ar(e,t){const r=Array.isArray(t)?t:[t];for(let e=0;e<r.length;e++){const t=r[e];"object"==typeof t&&"type"in t&&"value"in t||(r[e]=At(r[e]))}return Ir(e,r).map((e=>e.value))}function Ir(e,t){return Dr(e).eval(t)}const Ur=[...br,"->","<<",">>"];class Or{constructor(e){this.parser=e,this.structureMap={resourceType:"StructureMap"}}parse(){for(this.parser.consume("Symbol","map"),this.structureMap.url=this.parser.consume("String").value,this.parser.consume("="),this.structureMap.name=this.parser.consume().value;this.parser.hasMore();){const e=this.parser.peek()?.value;switch(e){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}parseUses(){this.parser.consume("Symbol","uses");const e={};e.url=this.parser.consume("String").value,"alias"===this.parser.peek()?.value&&(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(){const e={};this.parser.consume("Symbol","group"),e.name=this.parser.consume("Symbol").value,e.input=this.parseParameters(),"extends"===this.parser.peek()?.value&&(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(){const 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(){const 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(){const e=[];for(this.parser.consume("{");this.parser.hasMore()&&"}"!==this.parser.peek()?.value;)e.push(this.parseRule());return this.parser.consume("}"),e}parseRule(){const e={source:this.parseRuleSources()};return"->"===this.parser.peek()?.value&&(this.parser.consume("->"),e.target=this.parseRuleTargets()),"then"===this.parser.peek()?.value&&(this.parser.consume("Symbol","then"),"{"===this.parser.peek()?.id?e.rule=this.parseRules():e.dependent=this.parseRuleDependents()),"String"===this.parser.peek()?.id?e.name=this.parser.consume().value:e.name=e.source?.[0]?.element,this.parser.consume(";"),e}parseRuleSources(){const e=[this.parseRuleSource()];for(;this.parser.hasMore()&&","===this.parser.peek()?.value;)this.parser.consume(","),e.push(this.parseRuleSource());return e}parseRuleSource(){const e={},t=this.parseRuleContext();if(t.includes(".")){const r=t.split(".");e.context=r[0],e.element=r[1]}else e.context=t;if(this.parser.hasMore()&&":"===this.parser.peek()?.value&&(this.parser.consume(":"),e.type=this.parser.consume().value),this.parser.hasMore()&&"default"===this.parser.peek()?.value&&(this.parser.consume("default"),this.parser.consumeAndParse()),"first"!==this.parser.peek()?.value&&"not_first"!==this.parser.peek()?.value&&"last"!==this.parser.peek()?.value&&"not_last"!==this.parser.peek()?.value&&"only_one"!==this.parser.peek()?.value||(e.listMode=this.parser.consume().value),"as"===this.parser.peek()?.value&&(this.parser.consume("Symbol","as"),e.variable=this.parser.consume().value),"where"===this.parser.peek()?.value){this.parser.consume("Symbol","where");const t=this.parser.consumeAndParse(100);e.condition=t.toString()}if("check"===this.parser.peek()?.value){this.parser.consume("Symbol","check");const t=this.parser.consumeAndParse(100);e.check=t.toString()}return e}parseRuleTargets(){const e=[this.parseRuleTarget()];for(;this.parser.hasMore()&&","===this.parser.peek()?.value;)this.parser.consume(","),e.push(this.parseRuleTarget());return e}parseRuleTarget(){const e={},t=this.parseRuleContext();if(t.includes(".")){const r=t.split(".");e.contextType="variable",e.context=r[0],e.element=r[1]}else e.context=t;return"="===this.parser.peek()?.value&&(this.parser.consume("="),this.parseRuleTargetTransform(e)),"as"===this.parser.peek()?.value&&(this.parser.consume("Symbol","as"),e.variable=this.parser.consume().value),"first"!==this.parser.peek()?.value&&"share"!==this.parser.peek()?.value&&"last"!==this.parser.peek()?.value&&"collate"!==this.parser.peek()?.value||(e.listMode=[this.parser.consume().value]),e}parseRuleTargetTransform(e){e.transform="copy";const t=this.parser.consumeAndParse(6);if(t instanceof er)this.parseRuleTargetSymbol(e,t);else if(t instanceof vr)this.parseRuleTargetFunction(e,t);else{if(!(t instanceof Kt))throw new Error(`Unexpected FHIRPath: ${t}`);this.parseRuleTargetLiteral(e,t)}}parseRuleTargetSymbol(e,t){e.parameter=[{valueId:t.name}]}parseRuleTargetFunction(e,t){const r=t.name;switch(r){case"create":e.parameter=[{valueString:(t.args?.[0]).value.value}];break;case"translate":e.parameter=[{}];break;default:throw new Error("Unknown target function: "+r)}}parseRuleTargetLiteral(e,t){switch(t.value.type){case"boolean":e.parameter=[{valueBoolean:t.value.value}];break;case"decimal":e.parameter=[{valueDecimal:t.value.value}];break;case"string":e.parameter=[{valueString:t.value.value}];break;default:throw new Error("Unknown target literal type: "+t.value.type)}}parseRuleContext(){let e=this.parser.consume().value;for(;"."===this.parser.peek()?.value;)this.parser.consume("."),e+="."+this.parser.consume().value;return e}parseRuleDependents(){const e=this.parser.consumeAndParse(100);return[{name:e.name,variable:e.args.map((e=>e.name))}]}parseConceptMap(){for(;"}"!==this.parser.peek()?.value;)this.parser.consume();this.parser.consume("}")}}const Lr=Pr().registerInfix("->",{precedence:100}).registerInfix(";",{precedence:200});function Nr(e){const t=Lr.construct(new Pt(e,Sr,Ur).tokenize());return t.removeComments(),new Or(t).parse()}const Mr=20;var _r;!function(e){e.EQUALS="eq",e.NOT_EQUALS="ne",e.GREATER_THAN="gt",e.LESS_THAN="lt",e.GREATER_THAN_OR_EQUALS="ge",e.LESS_THAN_OR_EQUALS="le",e.STARTS_AFTER="sa",e.ENDS_BEFORE="eb",e.APPROXIMATELY="ap",e.CONTAINS="contains",e.EXACT="exact",e.TEXT="text",e.NOT="not",e.ABOVE="above",e.BELOW="below",e.IN="in",e.NOT_IN="not-in",e.OF_TYPE="of-type",e.MISSING="missing",e.IDENTIFIER="identifier",e.ITERATE="iterate"}(_r||(_r={}));const Br={contains:_r.CONTAINS,exact:_r.EXACT,above:_r.ABOVE,below:_r.BELOW,text:_r.TEXT,not:_r.NOT,in:_r.IN,"not-in":_r.NOT_IN,"of-type":_r.OF_TYPE,missing:_r.MISSING,identifier:_r.IDENTIFIER,iterate:_r.ITERATE},jr={eq:_r.EQUALS,ne:_r.NOT_EQUALS,lt:_r.LESS_THAN,le:_r.LESS_THAN_OR_EQUALS,gt:_r.GREATER_THAN,ge:_r.GREATER_THAN_OR_EQUALS,sa:_r.STARTS_AFTER,eb:_r.ENDS_BEFORE,ap:_r.APPROXIMATELY};function $r(e,t){const r=[];for(const[e,n]of Object.entries(t))if(Array.isArray(n))for(let t=0;t<n.length;t++)r.push([e,n[t]]);else r.push([e,n||""]);return Fr(e,r)}function qr(e){return Fr(e.pathname.split("/").filter(Boolean).pop(),e.searchParams.entries())}function Qr(e){return qr(new URL(e,"https://example.com/"))}function Fr(e,t){const r={resourceType:e};for(const[e,n]of t)Wr(r,e,n);return r}function Wr(e,t,r){let n,i;const o=t.indexOf(":");switch(o>=0?(n=t.substring(0,o),i=t.substring(o+1)):(n=t,i=""),n){case"_sort":!function(e,t){for(const r of t.split(",")){let t,n=!1;r.startsWith("-")?(t=r.substring(1),n=!0):t=r,e.sortRules||(e.sortRules=[]),e.sortRules.push({code:t,descending:n})}}(e,r);break;case"_count":e.count=parseInt(r);break;case"_offset":e.offset=parseInt(r);break;case"_total":e.total=r;break;case"_summary":e.total="accurate",e.count=0;break;case"_include":{const t=Gr(r);"iterate"===i&&(t.modifier=_r.ITERATE),e.include?e.include.push(t):e.include=[t];break}case"_revinclude":{const t=Gr(r);"iterate"===i&&(t.modifier=_r.ITERATE),e.revInclude?e.revInclude.push(t):e.revInclude=[t];break}case"_fields":e.fields=r.split(",");break;default:{const t=ht.types[e.resourceType]?.searchParams?.[n];t?function(e,t,r,n){if("missing"===r)return void Vr(e,{code:t.code,operator:_r.MISSING,value:n});switch(t.type){case"number":case"date":!function(e,t,r){const{operator:n,value:i}=Hr(r);Vr(e,{code:t.code,operator:n,value:i})}(e,t,n);break;case"reference":case"string":case"token":case"uri":!function(e,t,r,n){Vr(e,{code:t.code,operator:zr(r),value:n})}(e,t,r,n);break;case"quantity":!function(e,t,r){const[n,i,o]=r.split("|"),{operator:s,value:a}=Hr(n);Vr(e,{code:t.code,operator:s,value:a,unitSystem:i,unitCode:o})}(e,t,n)}}(e,t,i,r):function(e,t,r,n){let i=_r.EQUALS;if(r)i=r;else if(n.length>=2){const e=n.substring(0,2);e in jr&&(2===n.length||n.at(2)?.match(/\d/))&&(i=e,n=n.substring(e.length))}Vr(e,{code:t,operator:i,value:n})}(e,n,i,r)}}}function Hr(e){const t=e.substring(0,2),r=jr[t];return r?{operator:r,value:e.substring(2)}:{operator:_r.EQUALS,value:e}}function zr(e){return Br[e]||_r.EQUALS}function Gr(e){const t=e.split(":");if(t.forEach((e=>{if("*"===e)throw new qe(Oe("'*' is not supported as a value for search inclusion parameters"))})),1===t.length)throw new qe(Oe(`Invalid include value '${e}': must be of the form ResourceType:search-parameter`));if(2===t.length)return{resourceType:t[0],searchParam:t[1]};if(3===t.length)return{resourceType:t[0],searchParam:t[1],targetType:t[2]};throw new qe(Oe(`Invalid include value '${e}'`))}function Vr(e,t){e.filters?e.filters.push(t):e.filters=[t]}function Xr(e){const t=[];return e.fields&&t.push("_fields="+e.fields.join(",")),e.filters&&e.filters.forEach((e=>t.push(function(e){const t=e.operator in Br?":"+e.operator:"",r=e.operator!==_r.EQUALS&&e.operator in jr?e.operator:"";return`${e.code}${t}=${r}${encodeURIComponent(e.value)}`}(e)))),e.sortRules&&e.sortRules.length>0&&t.push("_sort="+e.sortRules.map((e=>e.descending?"-"+e.code:e.code)).join(",")),void 0!==e.offset&&t.push("_offset="+e.offset),void 0!==e.count&&t.push("_count="+e.count),void 0!==e.total&&t.push("_total="+e.total),0===t.length?"":(t.sort(),"?"+t.join("&"))}const Jr=[...br,"eq","ne","co"];class Yr{constructor(e,t,r){this.path=e,this.operator=t,this.value=r}}class Zr{constructor(e){this.child=e}}class Kr{constructor(e,t,r){this.keyword=e,this.left=t,this.right=r}}const en={eq:_r.EQUALS,ne:_r.NOT_EQUALS,co:_r.CONTAINS,sw:void 0,ew:void 0,gt:_r.GREATER_THAN,lt:_r.LESS_THAN,ge:_r.GREATER_THAN_OR_EQUALS,le:_r.LESS_THAN_OR_EQUALS,ap:_r.APPROXIMATELY,sa:_r.STARTS_AFTER,eb:_r.ENDS_BEFORE,pr:_r.MISSING,po:void 0,ss:void 0,sb:void 0,in:_r.IN,ni:_r.NOT_IN,re:void 0,identifier:_r.IDENTIFIER};class tn{constructor(e){this.parser=e}parse(){let e;"("===this.parser.peek()?.value?(this.parser.consume("("),e=this.parse(),this.parser.consume(")")):"not"===this.parser.peek()?.value?(this.parser.consume("Symbol","not"),this.parser.consume("("),e=new Zr(this.parse()),this.parser.consume(")")):e=new Yr(this.parser.consume("Symbol").value,function(e){const t=en[e];if(!t)throw new qe(Oe("Invalid operator: "+e));return t}(this.parser.consume("Symbol").value),this.parser.consume().value);const t=this.parser.peek()?.value;return"and"===t||"or"===t?(this.parser.consume("Symbol",t),new Kr(t,e,this.parse())):e}}const rn=Pr();function nn(e){const t=rn.construct(new Pt(e,Sr,Jr,{dateTimeLiterals:!0,symbolRegex:/[^\s\])]/}).tokenize());return t.removeComments(),new tn(t).parse()}class on{constructor(e="\r",t="|",r="^",n="~",i="\\",o="&"){this.segmentSeparator=e,this.fieldSeparator=t,this.componentSeparator=r,this.repetitionSeparator=n,this.escapeCharacter=i,this.subcomponentSeparator=o}getMsh2(){return this.fieldSeparator+this.componentSeparator+this.repetitionSeparator+this.escapeCharacter+this.subcomponentSeparator}}class sn{constructor(e,t=new on){this.context=t,this.segments=e}get(e){return"number"==typeof e?this.segments[e]:this.segments.find((t=>t.name===e))}getAll(e){return this.segments.filter((t=>t.name===e))}toString(){return this.segments.map((e=>e.toString())).join(this.context.segmentSeparator)}buildAck(){const e=new Date,t=this.get("MSH"),r=t?.get(2)?.toString()||"",n=t?.get(3)?.toString()||"",i=t?.get(4)?.toString()||"",o=t?.get(5)?.toString()||"",s=t?.get(9)?.toString()||"",a=t?.get(12)?.toString()||"2.5.1";return new sn([new an(["MSH",this.context.getMsh2(),i,o,r,n,e.toISOString(),"","ACK",e.getTime().toString(),"P",a],this.context),new an(["MSA","AA",s,"OK"],this.context)])}static parse(e){if(!e.startsWith("MSH")){const e=new Error("Invalid HL7 message");throw e.type="entity.parse.failed",e}const t=new on("\r",e.charAt(3),e.charAt(4),e.charAt(5),e.charAt(6),e.charAt(7));return new sn(e.split(/[\r\n]+/).map((e=>an.parse(e,t))),t)}}class an{constructor(e,t=new on){this.context=t,G(e)?this.fields=e.map((e=>cn.parse(e))):this.fields=e,this.name=this.fields[0].components[0][0]}get(e){return this.fields[e]}toString(){return this.fields.map((e=>e.toString())).join(this.context.fieldSeparator)}static parse(e,t=new on){return new an(e.split(t.fieldSeparator).map((e=>cn.parse(e,t))),t)}}class cn{constructor(e,t=new on){this.context=t,this.components=e}get(e,t,r=0){let n=this.components[r][e]||"";return void 0!==t&&(n=n.split(this.context.subcomponentSeparator)[t]||""),n}toString(){return this.components.map((e=>e.join(this.context.componentSeparator))).join(this.context.repetitionSeparator)}static parse(e,t=new on){return new cn(e.split(t.repetitionSeparator).map((e=>e.split(t.componentSeparator))),t)}}function un(e,t){if(!e)return;t={seconds:!0,tzOffset:"Z",...t};const r=Number.parseInt(e.substring(0,4)),n=Number.parseInt(e.substring(4,6)),i=Number.parseInt(e.substring(6,8)),o=Number.parseInt(e.substring(8,10)),s=Number.parseInt(e.substring(10,12)),a=t.seconds?Number.parseInt(e.substring(12,14)):0;return`${dn(r)}-${dn(n)}-${dn(i)}T${dn(o)}:${dn(s)}:${dn(a)}.000${t.tzOffset}`}function dn(e){return e.toString().padStart(2,"0")}const pn={base64Binary:"string",boolean:"boolean",canonical:"string",code:"string",date:"string",dateTime:"string",decimal:"number",id:"string",instant:"string",integer:"number",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"},ln=new Set(["resourceType","id","meta","implicitRules","language","text","contained","extension","modifierExtension"]);function hn(e){const t=ht.types[e];return t&&t.structureDefinition.id===e&&"resource"===t.structureDefinition.kind}function fn(e){if(!e)throw new qe(Le("Resource type is null"));if(!hn(e))throw new qe(Le("Unknown resource type"))}function mn(e){new yn(e).validate()}class yn{constructor(e){this.issues=[],this.root=e}validate(){const e=this.root;if(!e)throw new qe(Le("Resource is null"));const t=e.resourceType;if(!t)throw new qe(Le("Missing resource type"));if(gn(e,"",this.issues),this.validateObject(At(e),t),this.issues.length>0)throw new qe({resourceType:"OperationOutcome",issue:this.issues})}validateObject(e,t){const r=ht.types[e.type];if(!r)throw new qe(Le("Unknown type: "+e.type));const n=r.properties;this.checkProperties(t,n,e),this.checkAdditionalProperties(t,e,n)}checkProperties(e,t,r){for(const[n,i]of Object.entries(t))this.checkProperty(e+"."+n,i,r)}checkProperty(e,t,r){const n=Ut(r,e.split(".").pop());if(Q(n))void 0!==t.min&&t.min>0&&this.issues.push(vn(e,"Missing required property"));else if("*"===t.max){if(!Array.isArray(n))return void this.issues.push(vn(e,"Expected array for property"));for(const r of n)this.checkPropertyValue(e,t,r)}else{if(Array.isArray(n))return void this.issues.push(vn(e,"Expected single value for property"));this.checkPropertyValue(e,t,n)}}checkPropertyValue(e,t,r){null!==r.value&&(Z(r.type.charAt(0))?this.validatePrimitiveType(t,r):this.validateObject(r,e))}validatePrimitiveType(e,t){const{type:r,value:n}=t;if(null===n)return;const i=pn[t.type];typeof n===i?"string"===i?this.validateString(e,r,n):"number"===i&&this.validateNumber(e,r,n):this.createIssue(e,"Invalid type for "+r)}validateString(e,t,r){if(!r.trim())return void this.createIssue(e,"Invalid empty string");const n=ht.types[t]?.properties?.value;if(n?.type){const i=B(n.type[0],"http://hl7.org/fhir/StructureDefinition/regex");i&&(r.match(new RegExp(i))||this.createIssue(e,"Invalid "+t+" format"))}}validateNumber(e,t,r){var n;!isNaN(r)&&isFinite(r)?((n=t)!==Xe.integer&&n!==Xe.positiveInt&&n!==Xe.unsignedInt||Number.isInteger(r)||this.createIssue(e,"Number is not an integer"),t===Xe.positiveInt&&r<=0&&this.createIssue(e,"Number is less than or equal to zero"),t===Xe.unsignedInt&&r<0&&this.createIssue(e,"Number is negative")):this.createIssue(e,"Invalid "+t+" value")}checkAdditionalProperties(e,t,r){const n=t.value;for(const i of Object.keys(n))this.checkAdditionalProperty(e,i,t,r)}checkAdditionalProperty(e,t,r,n){if(!(ln.has(t)||t in n||function(e,t,r){for(const n of Object.keys(r)){if(!n.endsWith("[x]"))continue;const r=n.replace("[x]","");if(!e.startsWith(r))continue;let i=Ut(t,n);if(i&&(Array.isArray(i)&&(i=i[0]),i&&e===r+Y(i.type)))return!0}return!1}(t,r,n)||this.checkPrimitiveElement(e,t,r))){const r=`${e}.${t}`;this.issues.push(vn(r,`Invalid additional property "${r}"`))}}checkPrimitiveElement(e,t,r){if(!t.startsWith("_"))return!1;return t.slice(1)in r.value&&(this.validateObject({type:"Element",value:r.value[t]},e),!0)}createIssue(e,t){this.issues.push(vn(e.path,t))}}function gn(e,t,r){null===e?r.push(vn(t,"Invalid null value")):Array.isArray(e)?function(e,t,r){for(let n=0;n<e.length;n++)void 0===e[n]?r.push(vn(`${t}[${n}]`,"Invalid undefined value")):gn(e[n],`${t}[${n}]`,r)}(e,t,r):"object"==typeof e&&function(e,t,r){for(const[n,i]of Object.entries(e))gn(i,`${t}${t?".":""}${n}`,r)}(e,t,r)}function vn(e,t){return{severity:"error",code:"structure",details:{text:t},expression:[e]}}var xn;function Sn(e,t){let r=ht.types[e]?.searchParamsDetails?.[t.code];return r||(r=function(e,t){const r=t.code,n=function(e){return e.split("-").reduce(((e,t,r)=>e+(r?Y(t):t)),"")}(r),i=wn(e,t.expression)?.split(".");if(!i)return{columnName:n,type:xn.TEXT};let o,s,a=e,c=!1;for(let r=1;r<i.length;r++){let n=i[r],u=!1;const d=/\[\d+\]$/.exec(n);if(d&&(n=n.substring(0,n.length-d[0].length),u=!0),o=dt(a,n),!o)throw new Error(`Element definition not found for ${e} ${t.code}`);"0"===o.max||"1"===o.max||u||(c=!0),s=o.type?.[0].code,r<i.length-1&&(a=bn(s)?rt(o.path?.split(".")):s)}const u=function(e,t){let r=xn.TEXT;switch(e.type){case"date":r=t===Xe.date?xn.DATE:xn.DATETIME;break;case"number":r=xn.NUMBER;break;case"quantity":r=xn.QUANTITY;break;case"reference":r=t===Xe.canonical?xn.CANONICAL:xn.REFERENCE;break;case"token":"boolean"===t&&(r=xn.BOOLEAN)}return r}(t,s),d={columnName:n,type:u,elementDefinition:o,array:c};return function(e,t,r){const n=ht.types[e];n.searchParamsDetails||(n.searchParamsDetails={});n.searchParamsDetails[t]=r}(e,r,d),d}(e,t)),r}function bn(e){return"Element"===e||"BackboneElement"===e}function wn(e,t){const r=t.split(" | ");for(const t of r){if((n=t).includes(" as Period")||n.includes(" as SampledDate"))continue;const r=Tn(t);if(r.startsWith(e+"."))return r}var n}function Tn(e){let t=e.trim();t.startsWith("(")&&t.endsWith(")")&&(t=t.substring(1,t.length-1));const r=[" != "," as ",".as(",".exists(",".resolve(",".where("];for(const e of r)t.includes(e)&&(t=t.substring(0,t.indexOf(e)));return t}function En(e,t){if(t.resourceType!==e.resourceType)return!1;if(t.filters)for(const r of t.filters)if(!kn(e,t,r))return!1;return!0}function kn(e,t,r){const n=ht.types[t.resourceType]?.searchParams?.[r.code];switch(n?.type){case"reference":return function(e,t,r){const n=Ar(r.expression,e),i=Dn(t.operator);if(""===t.value&&0===n.length)return t.operator===_r.EQUALS;const o=n.map((e=>"string"==typeof e?e:e.reference));for(const e of t.value.split(",")){let r=o.includes(e);if(r||"_compartment"!==t.code||(r=o.some((t=>t?.endsWith("/"+e)))),r)return!i}return i}(e,r,n);case"string":case"uri":return Cn(e,r,n);case"token":return function(e,t,r){const n=Sn(e.resourceType,r);return n.type===xn.BOOLEAN?function(e,t,r){const n=Ar(r.expression,e),i="true"===t.value,o=n.includes(i);return Dn(t.operator)?!o:o}(e,t,r):Cn(e,t,r,!0)}(e,r,n);case"date":return function(e,t,r){const n=Ar(r.expression,e),i=t.value.split(","),o=Dn(t.operator);for(const e of n)for(const r of i){if(Rn(e,t.operator,r))return!o}return o}(e,r,n)}return!1}function Cn(e,t,r,n){const i=Ar(r.expression,e),o=t.value.split(","),s=Dn(t.operator);for(const e of i)for(const r of o){if(Pn(e,t.operator,r,n))return!s}return s}function Pn(e,t,r,n){if(n&&r.includes("|")){const[n,i]=r.split("|");return Pn(e,t,n,!1)&&(!i||Pn(e,t,i,!1))}let i="";return e&&("string"==typeof e?i=e:"object"==typeof e&&(i=JSON.stringify(e))),i.toLowerCase().includes(r.toLowerCase())}function Rn(e,t,r){switch(t){case _r.STARTS_AFTER:case _r.GREATER_THAN:return e>r;case _r.GREATER_THAN_OR_EQUALS:return e>=r;case _r.ENDS_BEFORE:case _r.LESS_THAN:return e<r;case _r.LESS_THAN_OR_EQUALS:return e<=r;case _r.EQUALS:case _r.NOT_EQUALS:return e===r}return!1}function Dn(e){return e===_r.NOT_EQUALS||e===_r.NOT}function An(e){const t=[];return new Promise(((r,n)=>{e.on("data",(e=>t.push(Buffer.from(e)))),e.on("error",(t=>{e.destroy(),n(t)})),e.on("end",(()=>{r(Buffer.concat(t))})),e.on("close",(()=>{e.destroy()}))}))}!function(e){e.BOOLEAN="BOOLEAN",e.NUMBER="NUMBER",e.QUANTITY="QUANTITY",e.TEXT="TEXT",e.REFERENCE="REFERENCE",e.CANONICAL="CANONICAL",e.DATE="DATE",e.DATETIME="DATETIME",e.PERIOD="PERIOD",e.UUID="UUID"}(xn||(xn={}));export{mr as AndAtom,ir as ArithemticOperatorAtom,nr as AsAtom,Ge as ClientStorage,or as ConcatAtom,sr as ContainsAtom,Mr as DEFAULT_SEARCH_COUNT,cr as DotAtom,tr as EmptySetAtom,dr as EqualsAtom,lr as EquivalentAtom,Sr as FHIRPATH_KEYWORDS,br as FHIRPATH_OPERATORS,Yr as FhirFilterComparison,Kr as FhirFilterConnective,Zr as FhirFilterNegation,Zt as FhirPathAtom,yn as FhirSchemaValidator,vr as FunctionAtom,on as Hl7Context,cn as Hl7Field,sn as Hl7Message,an as Hl7Segment,ar as InAtom,xr as IndexerAtom,Tt as InfixOperatorAtom,fr as IsAtom,i as LRUCache,Kt as LiteralAtom,ft as MEDPLUM_VERSION,xt as MedplumClient,Ve as MemoryStorage,pr as NotEqualsAtom,hr as NotEquivalentAtom,gt as OAuthGrantType,vt as OAuthTokenType,qe as OperationOutcomeError,_r as Operator,yr as OrAtom,kt as Parser,Et as ParserBuilder,wt as PrefixOperatorAtom,Xe as PropertyType,ze as ReadablePromise,xn as SearchParameterType,er as SymbolAtom,Pt as Tokenizer,rr as UnaryOperatorAtom,ur as UnionAtom,gr as XorAtom,Ue as accepted,Ee as allOk,J as arrayBufferToBase64,X as arrayBufferToHex,$e as assertOk,Oe as badRequest,Dt as booleanToTypedValue,rt as buildTypeName,O as calculateAge,L as calculateAgeString,Y as capitalize,gn as checkForNull,r as convertToTransactionBundle,k as createReference,vn as createStructureIssue,ke as created,e as decodeBase64,W as deepClone,F as deepEquals,t as encodeBase64,Ar as evalFhirPath,Ir as evalFhirPathTyped,Mt as fhirPathArrayEquals,Bt as fhirPathArrayEquivalent,_t as fhirPathEquals,jt as fhirPathEquivalent,qt as fhirPathIs,Nt as fhirPathNot,te as findObservationInterval,re as findObservationReferenceRange,le as findResourceByCode,De as forbidden,o as formatAddress,b as formatCodeableConcept,w as formatCoding,d as formatDate,l as formatDateTime,c as formatFamilyName,a as formatGivenName,s as formatHumanName,S as formatMoney,T as formatObservationValue,h as formatPeriod,x as formatQuantity,v as formatRange,Xr as formatSearchQuery,p as formatTime,g as formatTiming,K as getCodeBySystem,U as getDateProperty,D as getDisplayString,dt as getElementDefinition,tt as getElementDefinitionTypeName,wn as getExpressionForResourceType,j as getExtension,B as getExtensionValue,_ as getIdentifier,A as getImageSrc,at as getPropertyDisplayName,N as getQuestionnaireAnswers,C as getReferenceString,ot as getResourceTypeSchema,it as getResourceTypes,Sn as getSearchParameterDetails,st as getSearchParameters,je as getStatus,Ut as getTypedPropertyValue,ht as globalSchema,Ae as gone,et as indexSearchParameter,Ke as indexSearchParameterBundle,Ze as indexStructureDefinition,Ye as indexStructureDefinitionBundle,Pr as initFhirPathParserBuilder,Q as isEmpty,Be as isGone,Z as isLowerCase,_e as isNotFound,z as isObject,Me as isOk,Ne as isOperationOutcome,Qt as isPeriod,R as isProfileResource,Ft as isQuantity,Wt as isQuantityEquivalent,lt as isReference,pt as isResource,hn as isResourceType,nt as isResourceTypeSchema,G as isStringArray,H as isUUID,u as isValidDate,ie as matchesRange,En as matchesSearchRequest,Fe as normalizeErrorString,Qe as normalizeOperationOutcome,Pe as notFound,Ce as notModified,We as operationOutcomeToString,Dr as parseFhirPath,nn as parseFilterParameter,un as parseHl7Date,me as parseJWTPayload,Nr as parseMappingLanguage,Qr as parseSearchDefinition,$r as parseSearchRequest,qr as parseSearchUrl,se as preciseEquals,ce as preciseGreaterThan,de as preciseGreaterThanOrEquals,ae as preciseLessThan,ue as preciseLessThanOrEquals,oe as preciseRound,Lt as removeDuplicates,P as resolveId,ee as setCodeBySystem,An as streamToBuffer,$ as stringify,It as toJsBoolean,At as toTypedValue,wr as tokenize,Ie as tooManyRequests,Re as unauthorized,mn as validateResource,fn as validateResourceType,Le as validationError};
|
|
1
|
+
var e={types:{Element:{display:"Element",properties:{id:{type:[{code:"string"}]},extension:{max:"*",type:[{code:"Extension"}]}}},BackboneElement:{display:"BackboneElement",properties:{id:{type:[{code:"string"}]},extension:{max:"*",type:[{code:"Extension"}]},modifierExtension:{max:"*",type:[{code:"Extension"}]}}},Address:{display:"Address",properties:{id:{type:[{code:"string"}]},extension:{max:"*",type:[{code:"Extension"}]},use:{type:[{code:"code"}]},type:{type:[{code:"code"}]},text:{type:[{code:"string"}]},line:{max:"*",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:{display:"Age",properties:{id:{type:[{code:"string"}]},extension:{max:"*",type:[{code:"Extension"}]},value:{type:[{code:"decimal"}]},comparator:{type:[{code:"code"}]},unit:{type:[{code:"string"}]},system:{type:[{code:"uri"}]},code:{type:[{code:"code"}]}}},Annotation:{display:"Annotation",properties:{id:{type:[{code:"string"}]},extension:{max:"*",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:{display:"Attachment",properties:{id:{type:[{code:"string"}]},extension:{max:"*",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:{display:"CodeableConcept",properties:{id:{type:[{code:"string"}]},extension:{max:"*",type:[{code:"Extension"}]},coding:{max:"*",type:[{code:"Coding"}]},text:{type:[{code:"string"}]}}},Coding:{display:"Coding",properties:{id:{type:[{code:"string"}]},extension:{max:"*",type:[{code:"Extension"}]},system:{type:[{code:"uri"}]},version:{type:[{code:"string"}]},code:{type:[{code:"code"}]},display:{type:[{code:"string"}]},userSelected:{type:[{code:"boolean"}]}}},ContactDetail:{display:"ContactDetail",properties:{id:{type:[{code:"string"}]},extension:{max:"*",type:[{code:"Extension"}]},name:{type:[{code:"string"}]},telecom:{max:"*",type:[{code:"ContactPoint"}]}}},ContactPoint:{display:"ContactPoint",properties:{id:{type:[{code:"string"}]},extension:{max:"*",type:[{code:"Extension"}]},system:{type:[{code:"code"}]},value:{type:[{code:"string"}]},use:{type:[{code:"code"}]},rank:{type:[{code:"positiveInt"}]},period:{type:[{code:"Period"}]}}},Contributor:{display:"Contributor",properties:{id:{type:[{code:"string"}]},extension:{max:"*",type:[{code:"Extension"}]},type:{min:1,type:[{code:"code"}]},name:{min:1,type:[{code:"string"}]},contact:{max:"*",type:[{code:"ContactDetail"}]}}},Count:{display:"Count",properties:{id:{type:[{code:"string"}]},extension:{max:"*",type:[{code:"Extension"}]},value:{type:[{code:"decimal"}]},comparator:{type:[{code:"code"}]},unit:{type:[{code:"string"}]},system:{type:[{code:"uri"}]},code:{type:[{code:"code"}]}}},DataRequirement:{display:"DataRequirement",properties:{id:{type:[{code:"string"}]},extension:{max:"*",type:[{code:"Extension"}]},type:{min:1,type:[{code:"code"}]},profile:{max:"*",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:"*",type:[{code:"string"}]},codeFilter:{max:"*",type:[{code:"Element"}]},dateFilter:{max:"*",type:[{code:"Element"}]},limit:{type:[{code:"positiveInt"}]},sort:{max:"*",type:[{code:"Element"}]}}},DataRequirementCodeFilter:{display:"DataRequirementCodeFilter",properties:{id:{type:[{code:"string"}]},extension:{max:"*",type:[{code:"Extension"}]},path:{type:[{code:"string"}]},searchParam:{type:[{code:"string"}]},valueSet:{type:[{code:"canonical",targetProfile:["http://hl7.org/fhir/StructureDefinition/ValueSet"]}]},code:{max:"*",type:[{code:"Coding"}]}}},DataRequirementDateFilter:{display:"DataRequirementDateFilter",properties:{id:{type:[{code:"string"}]},extension:{max:"*",type:[{code:"Extension"}]},path:{type:[{code:"string"}]},searchParam:{type:[{code:"string"}]},"value[x]":{type:[{code:"dateTime"},{code:"Period"},{code:"Duration"}]}}},DataRequirementSort:{display:"DataRequirementSort",properties:{id:{type:[{code:"string"}]},extension:{max:"*",type:[{code:"Extension"}]},path:{min:1,type:[{code:"string"}]},direction:{min:1,type:[{code:"code"}]}}},Distance:{display:"Distance",properties:{id:{type:[{code:"string"}]},extension:{max:"*",type:[{code:"Extension"}]},value:{type:[{code:"decimal"}]},comparator:{type:[{code:"code"}]},unit:{type:[{code:"string"}]},system:{type:[{code:"uri"}]},code:{type:[{code:"code"}]}}},Dosage:{display:"Dosage",properties:{id:{type:[{code:"string"}]},extension:{max:"*",type:[{code:"Extension"}]},modifierExtension:{max:"*",type:[{code:"Extension"}]},sequence:{type:[{code:"integer"}]},text:{type:[{code:"string"}]},additionalInstruction:{max:"*",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:"*",type:[{code:"Element"}]},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:{display:"DosageDoseAndRate",properties:{id:{type:[{code:"string"}]},extension:{max:"*",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:{display:"Duration",properties:{id:{type:[{code:"string"}]},extension:{max:"*",type:[{code:"Extension"}]},value:{type:[{code:"decimal"}]},comparator:{type:[{code:"code"}]},unit:{type:[{code:"string"}]},system:{type:[{code:"uri"}]},code:{type:[{code:"code"}]}}},ElementDefinition:{display:"ElementDefinition",properties:{id:{type:[{code:"string"}]},extension:{max:"*",type:[{code:"Extension"}]},modifierExtension:{max:"*",type:[{code:"Extension"}]},path:{min:1,type:[{code:"string"}]},representation:{max:"*",type:[{code:"code"}]},sliceName:{type:[{code:"string"}]},sliceIsConstraining:{type:[{code:"boolean"}]},label:{type:[{code:"string"}]},code:{max:"*",type:[{code:"Coding"}]},slicing:{type:[{code:"Element"}]},short:{type:[{code:"string"}]},definition:{type:[{code:"markdown"}]},comment:{type:[{code:"markdown"}]},requirements:{type:[{code:"markdown"}]},alias:{max:"*",type:[{code:"string"}]},min:{type:[{code:"unsignedInt"}]},max:{type:[{code:"string"}]},base:{type:[{code:"Element"}]},contentReference:{type:[{code:"uri"}]},type:{max:"*",type:[{code:"Element"}]},"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:"*",type:[{code:"Element"}]},"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:"*",type:[{code:"id"}]},constraint:{max:"*",type:[{code:"Element"}]},mustSupport:{type:[{code:"boolean"}]},isModifier:{type:[{code:"boolean"}]},isModifierReason:{type:[{code:"string"}]},isSummary:{type:[{code:"boolean"}]},binding:{type:[{code:"Element"}]},mapping:{max:"*",type:[{code:"Element"}]}}},ElementDefinitionSlicing:{display:"ElementDefinitionSlicing",properties:{id:{type:[{code:"string"}]},extension:{max:"*",type:[{code:"Extension"}]},discriminator:{max:"*",type:[{code:"Element"}]},description:{type:[{code:"string"}]},ordered:{type:[{code:"boolean"}]},rules:{min:1,type:[{code:"code"}]}}},ElementDefinitionSlicingDiscriminator:{display:"ElementDefinitionSlicingDiscriminator",properties:{id:{type:[{code:"string"}]},extension:{max:"*",type:[{code:"Extension"}]},type:{min:1,type:[{code:"code"}]},path:{min:1,type:[{code:"string"}]}}},ElementDefinitionBase:{display:"ElementDefinitionBase",properties:{id:{type:[{code:"string"}]},extension:{max:"*",type:[{code:"Extension"}]},path:{min:1,type:[{code:"string"}]},min:{min:1,type:[{code:"unsignedInt"}]},max:{min:1,type:[{code:"string"}]}}},ElementDefinitionType:{display:"ElementDefinitionType",properties:{id:{type:[{code:"string"}]},extension:{max:"*",type:[{code:"Extension"}]},code:{min:1,type:[{code:"uri"}]},profile:{max:"*",type:[{code:"canonical",targetProfile:["http://hl7.org/fhir/StructureDefinition/StructureDefinition","http://hl7.org/fhir/StructureDefinition/ImplementationGuide"]}]},targetProfile:{max:"*",type:[{code:"canonical",targetProfile:["http://hl7.org/fhir/StructureDefinition/StructureDefinition","http://hl7.org/fhir/StructureDefinition/ImplementationGuide"]}]},aggregation:{max:"*",type:[{code:"code"}]},versioning:{type:[{code:"code"}]}}},ElementDefinitionExample:{display:"ElementDefinitionExample",properties:{id:{type:[{code:"string"}]},extension:{max:"*",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:{display:"ElementDefinitionConstraint",properties:{id:{type:[{code:"string"}]},extension:{max:"*",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:{display:"ElementDefinitionBinding",properties:{id:{type:[{code:"string"}]},extension:{max:"*",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:{display:"ElementDefinitionMapping",properties:{id:{type:[{code:"string"}]},extension:{max:"*",type:[{code:"Extension"}]},identity:{min:1,type:[{code:"id"}]},language:{type:[{code:"code"}]},map:{min:1,type:[{code:"string"}]},comment:{type:[{code:"string"}]}}},Expression:{display:"Expression",properties:{id:{type:[{code:"string"}]},extension:{max:"*",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:{display:"Extension",properties:{id:{type:[{code:"string"}]},extension:{max:"*",type:[{code:"Extension"}]},url:{min:1,type:[{code:"string"}]},"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:{display:"HumanName",properties:{id:{type:[{code:"string"}]},extension:{max:"*",type:[{code:"Extension"}]},use:{type:[{code:"code"}]},text:{type:[{code:"string"}]},family:{type:[{code:"string"}]},given:{max:"*",type:[{code:"string"}]},prefix:{max:"*",type:[{code:"string"}]},suffix:{max:"*",type:[{code:"string"}]},period:{type:[{code:"Period"}]}}},Identifier:{display:"Identifier",properties:{id:{type:[{code:"string"}]},extension:{max:"*",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:{display:"MarketingStatus",properties:{id:{type:[{code:"string"}]},extension:{max:"*",type:[{code:"Extension"}]},modifierExtension:{max:"*",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:{display:"Meta",properties:{id:{type:[{code:"string"}]},extension:{max:"*",type:[{code:"Extension"}]},versionId:{type:[{code:"id"}]},lastUpdated:{type:[{code:"instant"}]},source:{type:[{code:"uri"}]},profile:{max:"*",type:[{code:"canonical",targetProfile:["http://hl7.org/fhir/StructureDefinition/StructureDefinition"]}]},security:{max:"*",type:[{code:"Coding"}]},tag:{max:"*",type:[{code:"Coding"}]},project:{type:[{code:"uri"}]},author:{type:[{code:"Reference"}]},account:{type:[{code:"Reference"}]},compartment:{max:"*",type:[{code:"Reference"}]}}},Money:{display:"Money",properties:{id:{type:[{code:"string"}]},extension:{max:"*",type:[{code:"Extension"}]},value:{type:[{code:"decimal"}]},currency:{type:[{code:"code"}]}}},Narrative:{display:"Narrative",properties:{id:{type:[{code:"string"}]},extension:{max:"*",type:[{code:"Extension"}]},status:{min:1,type:[{code:"code"}]},div:{min:1,type:[{code:"xhtml"}]}}},ParameterDefinition:{display:"ParameterDefinition",properties:{id:{type:[{code:"string"}]},extension:{max:"*",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:{display:"Period",properties:{id:{type:[{code:"string"}]},extension:{max:"*",type:[{code:"Extension"}]},start:{type:[{code:"dateTime"}]},end:{type:[{code:"dateTime"}]}}},Population:{display:"Population",properties:{id:{type:[{code:"string"}]},extension:{max:"*",type:[{code:"Extension"}]},modifierExtension:{max:"*",type:[{code:"Extension"}]},"age[x]":{type:[{code:"Range"},{code:"CodeableConcept"}]},gender:{type:[{code:"CodeableConcept"}]},race:{type:[{code:"CodeableConcept"}]},physiologicalCondition:{type:[{code:"CodeableConcept"}]}}},ProdCharacteristic:{display:"ProdCharacteristic",properties:{id:{type:[{code:"string"}]},extension:{max:"*",type:[{code:"Extension"}]},modifierExtension:{max:"*",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:"*",type:[{code:"string"}]},imprint:{max:"*",type:[{code:"string"}]},image:{max:"*",type:[{code:"Attachment"}]},scoring:{type:[{code:"CodeableConcept"}]}}},ProductShelfLife:{display:"ProductShelfLife",properties:{id:{type:[{code:"string"}]},extension:{max:"*",type:[{code:"Extension"}]},modifierExtension:{max:"*",type:[{code:"Extension"}]},identifier:{type:[{code:"Identifier"}]},type:{min:1,type:[{code:"CodeableConcept"}]},period:{min:1,type:[{code:"Quantity"}]},specialPrecautionsForStorage:{max:"*",type:[{code:"CodeableConcept"}]}}},Quantity:{display:"Quantity",properties:{id:{type:[{code:"string"}]},extension:{max:"*",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"}]}}},Range:{display:"Range",properties:{id:{type:[{code:"string"}]},extension:{max:"*",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:{display:"Ratio",properties:{id:{type:[{code:"string"}]},extension:{max:"*",type:[{code:"Extension"}]},numerator:{type:[{code:"Quantity"}]},denominator:{type:[{code:"Quantity"}]}}},Reference:{display:"Reference",properties:{id:{type:[{code:"string"}]},extension:{max:"*",type:[{code:"Extension"}]},reference:{type:[{code:"string"}]},type:{type:[{code:"uri"}]},identifier:{type:[{code:"Identifier"}]},display:{type:[{code:"string"}]}}},RelatedArtifact:{display:"RelatedArtifact",properties:{id:{type:[{code:"string"}]},extension:{max:"*",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:{display:"SampledData",properties:{id:{type:[{code:"string"}]},extension:{max:"*",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:{display:"Signature",properties:{id:{type:[{code:"string"}]},extension:{max:"*",type:[{code:"Extension"}]},type:{min:1,max:"*",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:{display:"SubstanceAmount",properties:{id:{type:[{code:"string"}]},extension:{max:"*",type:[{code:"Extension"}]},modifierExtension:{max:"*",type:[{code:"Extension"}]},"amount[x]":{type:[{code:"Quantity"},{code:"Range"},{code:"string"}]},amountType:{type:[{code:"CodeableConcept"}]},amountText:{type:[{code:"string"}]},referenceRange:{type:[{code:"Element"}]}}},SubstanceAmountReferenceRange:{display:"SubstanceAmountReferenceRange",properties:{id:{type:[{code:"string"}]},extension:{max:"*",type:[{code:"Extension"}]},lowLimit:{type:[{code:"Quantity"}]},highLimit:{type:[{code:"Quantity"}]}}},Timing:{display:"Timing",properties:{id:{type:[{code:"string"}]},extension:{max:"*",type:[{code:"Extension"}]},modifierExtension:{max:"*",type:[{code:"Extension"}]},event:{max:"*",type:[{code:"dateTime"}]},repeat:{type:[{code:"Element"}]},code:{type:[{code:"CodeableConcept"}]}}},TimingRepeat:{display:"TimingRepeat",properties:{id:{type:[{code:"string"}]},extension:{max:"*",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:"*",type:[{code:"code"}]},timeOfDay:{max:"*",type:[{code:"time"}]},when:{max:"*",type:[{code:"code"}]},offset:{type:[{code:"unsignedInt"}]}}},TriggerDefinition:{display:"TriggerDefinition",properties:{id:{type:[{code:"string"}]},extension:{max:"*",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:"*",type:[{code:"DataRequirement"}]},condition:{type:[{code:"Expression"}]}}},UsageContext:{display:"UsageContext",properties:{id:{type:[{code:"string"}]},extension:{max:"*",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"]}]}}},MetadataResource:{display:"MetadataResource",properties:{id:{type:[{code:"string"}]},meta:{type:[{code:"Meta"}]},implicitRules:{type:[{code:"uri"}]},language:{type:[{code:"code"}]},text:{type:[{code:"Narrative"}]},contained:{max:"*",type:[{code:"Resource"}]},extension:{max:"*",type:[{code:"Extension"}]},modifierExtension:{max:"*",type:[{code:"Extension"}]},url:{type:[{code:"uri"}]},version:{type:[{code:"string"}]},name:{type:[{code:"string"}]},title:{type:[{code:"string"}]},status:{min:1,type:[{code:"code"}]},experimental:{type:[{code:"boolean"}]},date:{type:[{code:"dateTime"}]},publisher:{type:[{code:"string"}]},contact:{max:"*",type:[{code:"ContactDetail"}]},description:{type:[{code:"markdown"}]},useContext:{max:"*",type:[{code:"UsageContext"}]},jurisdiction:{max:"*",type:[{code:"CodeableConcept"}]}}},IdentityProvider:{display:"IdentityProvider",properties:{authorizeUrl:{min:1,type:[{code:"string"}]},tokenUrl:{min:1,type:[{code:"string"}]},userInfoUrl:{min:1,type:[{code:"string"}]},clientId:{min:1,type:[{code:"string"}]},clientSecret:{min:1,type:[{code:"string"}]},useSubject:{type:[{code:"boolean"}]}}}}};function t(e,t){const n=[];if(e.line&&n.push(...e.line),e.city||e.state||e.postalCode){const t=[];e.city&&t.push(e.city),e.state&&t.push(e.state),e.postalCode&&t.push(e.postalCode),n.push(t.join(", "))}return e.use&&(t?.all||t?.use)&&n.push("["+e.use+"]"),n.join(t?.lineSeparator||", ").trim()}function n(e,t){const n=[];return e.prefix&&!1!==t?.prefix&&n.push(...e.prefix),e.given&&n.push(...e.given),e.family&&n.push(e.family),e.suffix&&!1!==t?.suffix&&n.push(...e.suffix),e.use&&(t?.all||t?.use)&&n.push("["+e.use+"]"),n.join(" ").trim()}function r(e){const t=[];return e.given&&t.push(...e.given),t.join(" ").trim()}function i(e){return e.family||""}function o(e){return e instanceof Date&&!isNaN(e.getTime())}function s(e,t,n){if(!e)return"";const r=new Date(e);return o(r)?(r.setUTCHours(0,0,0,0),r.toLocaleDateString(t,{timeZone:"UTC",...n})):""}function a(e,t,n){if(!e)return"";const r=new Date("2000-01-01T"+e+"Z");return o(r)?r.toLocaleTimeString(t,n):""}function c(e,t,n){if(!e)return"";const r=new Date(e);return o(r)?r.toLocaleString(t,n):""}function u(e,t,n){return e&&(e.start||e.end)?c(e.start,t,n)+" - "+c(e.end,t,n):""}const d={s:"every second",min:"every minute",h:"hourly",d:"daily",wk:"weekly",mo:"monthly",a:"annually"},p={s:"second",min:"minute",h:"hour",d:"day",wk:"week",mo:"month",a:"year"},l={s:"seconds",min:"minutes",h:"hours",d:"days",wk:"weeks",mo:"months",a:"years"};function h(e){if(!e)return"";const t=[];if(e.repeat?.periodUnit){const n=e.repeat.frequency||1,r=e.repeat.period||1,i=e.repeat.periodUnit;1===n&&1===r?t.push(d[i]):(1===n?t.push("once"):t.push(n+" times"),1===r?t.push("per "+p[i]):t.push("per "+r+" "+l[i])),e.repeat.dayOfWeek&&t.push("on "+e.repeat.dayOfWeek.map(G).join(", ")),e.repeat.timeOfDay&&t.push("at "+e.repeat.timeOfDay.map((e=>a(e))).join(", "))}return e.event&&t.push(e.event.map((e=>c(e))).join(", ")),G(t.join(" ").trim())}function f(e,t,n=!1){if(n&&void 0===t)throw new Error("Precision must be specified for exclusive ranges");const r=e?.low&&{...e.low,comparator:void 0},i=e?.high&&{...e.high,comparator:void 0};return void 0===r?.value&&void 0===i?.value?"":void 0!==r?.value&&void 0===i?.value?n&&void 0!==t?(r.value=function(e,t,n=1){return(b(e,t)-n)*Math.pow(10,-t)}(r.value,t),`> ${m(r,t)}`):`>= ${m(r,t)}`:void 0===r?.value&&void 0!==i?.value?n&&void 0!==t?(i.value=function(e,t,n=1){return(b(e,t)+n)*Math.pow(10,-t)}(i.value,t),`< ${m(i,t)}`):`<= ${m(i,t)}`:(r?.unit===i?.unit&&delete r?.unit,`${m(r,t)} - ${m(i,t)}`)}function m(e,t){if(!e)return"";const n=[];return e.comparator&&(n.push(e.comparator),n.push(" ")),void 0!==e.value&&(void 0!==t?n.push(e.value.toFixed(t)):n.push(e.value)),e.unit&&("%"!==e.unit&&" "!==n[n.length-1]&&n.push(" "),n.push(e.unit)),n.join("").trim()}function y(e){return void 0===e?.value?"":e.value.toLocaleString(void 0,{style:"currency",currency:e.currency||"USD",currencyDisplay:"narrowSymbol"})}function g(e){return e?e.text?e.text:e.coding?e.coding.map((e=>v(e))).join(", "):"":""}function v(e){return e?.display||e?.code||""}function x(e){return e?"component"in e?e.component.map((e=>x(e))).join(" / "):e.valueQuantity?m(e.valueQuantity):e.valueCodeableConcept?g(e.valueCodeableConcept):e.valueString?e.valueString:"":""}function b(e,t){return void 0===t?e:Math.round(e*Math.pow(10,t))}function S(e){const t=w(e),n=k(e);return n===t?{reference:t}:{reference:t,display:n}}function w(e){return e.resourceType+"/"+e.id}function T(e){return e?.reference?.split("/")[1]}function E(e){return"Patient"===e.resourceType||"Practitioner"===e.resourceType||"RelatedPerson"===e.resourceType}function k(e){if(E(e)){const t=function(e){const t=e.name;if(t&&t.length>0)return n(t[0]);return}(e);if(t)return t}if("Device"===e.resourceType){const t=function(e){const t=e.deviceName;if(t&&t.length>0)return t[0].name;return}(e);if(t)return t}return"Observation"===e.resourceType&&"code"in e&&e.code?.text?e.code.text:"User"===e.resourceType&&e.email?e.email:"name"in e&&e.name&&"string"==typeof e.name?e.name:w(e)}function C(e){if(!("photo"in e))return;const t=e.photo;if(t){if(!Array.isArray(t))return P(t);for(const e of t){const t=P(e);if(t)return t}}}function P(e){if(e.url&&e.contentType&&e.contentType.startsWith("image/"))return e.url}function A(e){return e?new Date(e):void 0}function D(e,t){const n=new Date(e);n.setUTCHours(0,0,0,0);const r=t?new Date(t):new Date;r.setUTCHours(0,0,0,0);const i=n.getUTCFullYear(),o=n.getUTCMonth(),s=n.getUTCDate(),a=r.getUTCFullYear(),c=r.getUTCMonth(),u=r.getUTCDate();let d=a-i;(c<o||c===o&&u<s)&&d--;let p=12*a+c-(12*i+o);u<s&&p--;return{years:d,months:p,days:Math.floor((r.getTime()-n.getTime())/864e5)}}function R(e,t){const{years:n,months:r,days:i}=D(e,t);return n>=2?n.toString().padStart(3,"0")+"Y":r>=1?r.toString().padStart(3,"0")+"M":i.toString().padStart(3,"0")+"D"}function I(e){const t={};return U(e.item,t),t}function U(e,t){if(e)for(const n of e)n.linkId&&n.answer&&n.answer.length>0&&(t[n.linkId]=n.answer[0]),U(n.item,t)}function O(e,t){const n=e.identifier;if(!n)return;const r=Array.isArray(n)?n:[n];for(const e of r)if(e.system===t)return e.value}function L(e,...t){let n=e;for(let e=0;e<t.length&&n;e++)n=n?.extension?.find((n=>n.url===t[e]));return n?.valueString}function N(e,...t){let n=e;for(let e=0;e<t.length&&n;e++)n=n?.extension?.find((n=>n.url===t[e]));return n}function M(e,t){return JSON.stringify(e,_,t?2:void 0)}function _(e,t){return!function(e){return!!e.match(/\d+$/)}(e)&&j(t)?void 0:t}function j(e){if(null==e)return!0;const t=typeof e;return"string"===t&&""===e||"object"===t&&0===Object.keys(e).length}function $(e,t,n){return e===t||(!(!j(e)||!j(t))||!j(e)&&!j(t)&&(Array.isArray(e)&&Array.isArray(t)?function(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(!$(e[n],t[n]))return!1;return!0}(e,t):!Array.isArray(e)&&!Array.isArray(t)&&(Q(e)&&Q(t)?function(e,t,n){const r=new Set;Object.keys(e).forEach((e=>r.add(e))),Object.keys(t).forEach((e=>r.add(e))),"meta"===n&&(r.delete("versionId"),r.delete("lastUpdated"),r.delete("author"));for(const n of r){if(!$(e[n],t[n],n))return!1}return!0}(e,t,n):(Q(e)||Q(t),!1))))}function B(e){return JSON.parse(JSON.stringify(e))}function q(e){return!!e.match(/^\w{8}-\w{4}-\w{4}-\w{4}-\w{12}$/i)}function Q(e){return null!==e&&"object"==typeof e}function F(e){return e.every((e=>"string"==typeof e))}const W=[];for(let e=0;e<256;e++)W.push(e.toString(16).padStart(2,"0"));function H(e){const t=new Uint8Array(e),n=new Array(t.length);for(let e=0;e<t.length;e++)n[e]=W[t[e]];return n.join("")}function z(e){const t=new Uint8Array(e),n=[];for(let e=0;e<t.length;e++)n[e]=String.fromCharCode(t[e]);return window.btoa(n.join(""))}function G(e){return e.charAt(0).toUpperCase()+e.substring(1)}function V(e){return e===e.toLowerCase()&&e!==e.toUpperCase()}function J(e,t){return e.coding?.find((e=>e.system===t))?.code}function X(e,t,n){e.coding||(e.coding=[]);const r=e.coding.find((e=>e.system===t));r?r.code=n:e.coding.push({system:t,code:n})}function Y(e,t,n,r){return e.qualifiedInterval?.find((i=>K(i,t)&&function(e,t,n){return!!e.range&&ee(t,e.range,n)}(i,n,e.quantitativeDetails?.decimalPrecision)&&(void 0===r||i.category===r)))}function Z(e,t,n){return e.qualifiedInterval?.find((e=>K(e,t)&&n.includes(e.condition)))}function K(e,t){return function(e,t){return!e.gender||e.gender===t.gender}(e,t)&&function(e,t){return!e.age||ee(D(t.birthDate).years,e.age)}(e,t)}function ee(e,t,n){return(void 0===t.low?.value||se(e,t.low.value,n))&&(void 0===t.high?.value||oe(e,t.high.value,n))}function te(e,t){return parseFloat(e.toFixed(t))}function ne(e,t,n){return ae(e,n)===ae(t,n)}function re(e,t,n){return ae(e,n)<ae(t,n)}function ie(e,t,n){return ae(e,n)>ae(t,n)}function oe(e,t,n){return ae(e,n)<=ae(t,n)}function se(e,t,n){return ae(e,n)>=ae(t,n)}function ae(e,t){return void 0===t?e:Math.round(e*Math.pow(10,t))}function ce(e,t,n){return e.find((e=>"string"==typeof t?J(e.code||{},n)===t:J(e.code||{},n)===J(t,n)))}var ue;function de(e){for(const t of e.entry){const e=t.resource;"StructureDefinition"===e.resourceType&&pe(e)}}function pe(e){if(!e.name)return;const t=e.snapshot?.element;t&&(t.forEach((t=>function(e,t){const n=t.path,r=t.type?.[0]?.code;if(void 0!==r&&"Element"!==r&&"BackboneElement"!==r)return;const i=n.split(".");i[0]=e.name;const o=me(i);let s=Ce.types[o];s||(Ce.types[o]=s={});s.parentType=s.parentType||me(i.slice(0,i.length-1)),s.display=s.display||o,s.structureDefinition=s.structureDefinition||e,s.elementDefinition=s.elementDefinition||t,s.description=s.description||t.definition,s.properties=s.properties||{}}(e,t))),t.forEach((t=>function(e,t){const n=t.path,r=n.split(".");if(1===r.length)return;r[0]=e.name;const i=me(r.slice(0,r.length-1)),o=Ce.types[i];if(!o)return;const s=r[r.length-1];o.properties[s]=t}(e,t))))}function le(e){for(const t of e.entry){const e=t.resource;"SearchParameter"===e.resourceType&&he(e)}}function he(e){if(e.base)for(const t of e.base){const n=Ce.types[t];n&&(n.searchParams||(n.searchParams={_id:{base:[t],code:"_id",type:"token",expression:t+".id"},_lastUpdated:{base:[t],code:"_lastUpdated",type:"date",expression:t+".meta.lastUpdated"},_compartment:{base:[t],code:"_compartment",type:"reference",expression:t+".meta.compartment"},_profile:{base:[t],code:"_profile",type:"uri",expression:t+".meta.profile"},_security:{base:[t],code:"_security",type:"token",expression:t+".meta.security"},_source:{base:[t],code:"_source",type:"uri",expression:t+".meta.source"},_tag:{base:[t],code:"_tag",type:"token",expression:t+".meta.tag"}}),n.searchParams[e.code]=e)}}function fe(e){const t=e.type?.[0]?.code;return"BackboneElement"===t||"Element"===t?me(e.path?.split(".")):t}function me(e){return 1===e.length?e[0]:e.map(G).join("")}function ye(e){const t=e.structureDefinition;return t&&t.name===e.elementDefinition.path&&"resource"===t.kind&&!t.abstract}function ge(){const e=[];for(const[t,n]of Object.entries(Ce.types))ye(n)&&e.push(t);return e}function ve(e){return Ce.types[e]}function xe(e){return Ce.types[e].searchParams}function be(e){return e.replaceAll("[x]","").split(".").pop().split(/(?=[A-Z])/).map(we).join(" ").replace("_"," ").replace(/\s+/g," ")}!function(e){e.Address="Address",e.Age="Age",e.Annotation="Annotation",e.Attachment="Attachment",e.BackboneElement="BackboneElement",e.CodeableConcept="CodeableConcept",e.Coding="Coding",e.ContactDetail="ContactDetail",e.ContactPoint="ContactPoint",e.Contributor="Contributor",e.Count="Count",e.DataRequirement="DataRequirement",e.Distance="Distance",e.Dosage="Dosage",e.Duration="Duration",e.Expression="Expression",e.Extension="Extension",e.HumanName="HumanName",e.Identifier="Identifier",e.MarketingStatus="MarketingStatus",e.Meta="Meta",e.Money="Money",e.Narrative="Narrative",e.ParameterDefinition="ParameterDefinition",e.Period="Period",e.Population="Population",e.ProdCharacteristic="ProdCharacteristic",e.ProductShelfLife="ProductShelfLife",e.Quantity="Quantity",e.Range="Range",e.Ratio="Ratio",e.Reference="Reference",e.RelatedArtifact="RelatedArtifact",e.SampledData="SampledData",e.Signature="Signature",e.SubstanceAmount="SubstanceAmount",e.SystemString="http://hl7.org/fhirpath/System.String",e.Timing="Timing",e.TriggerDefinition="TriggerDefinition",e.UsageContext="UsageContext",e.base64Binary="base64Binary",e.boolean="boolean",e.canonical="canonical",e.code="code",e.date="date",e.dateTime="dateTime",e.decimal="decimal",e.id="id",e.instant="instant",e.integer="integer",e.markdown="markdown",e.oid="oid",e.positiveInt="positiveInt",e.string="string",e.time="time",e.unsignedInt="unsignedInt",e.uri="uri",e.url="url",e.uuid="uuid"}(ue||(ue={}));const Se=new Set(["ID","IP","PKCE","JWKS","URI","URL"]);function we(e){const t=e.toUpperCase();return Se.has(t)?t:t.charAt(0)+e.slice(1)}function Te(e,t){const n=Ce.types[e];if(!n)return;const r=n.properties[t]??n.properties[t+"[x]"];if(r){if(r.contentReference){const e=r.contentReference.substring(1).split("."),t=e.pop();return Te(me(e),t)}return r}}function Ee(e){return!(!e||"object"!=typeof e||!("resourceType"in e))}function ke(e){return!(!e||"object"!=typeof e||!("reference"in e))}const Ce=e,Pe="ok",Ae="created",De="gone",Re="not-modified",Ie="not-found",Ue="unauthorized",Oe="forbidden",Le="too-many-requests",Ne="accepted",Me={resourceType:"OperationOutcome",id:Pe,issue:[{severity:"information",code:"informational",details:{text:"All OK"}}]},_e={resourceType:"OperationOutcome",id:Ae,issue:[{severity:"information",code:"informational",details:{text:"Created"}}]},je={resourceType:"OperationOutcome",id:Re,issue:[{severity:"information",code:"informational",details:{text:"Not Modified"}}]},$e={resourceType:"OperationOutcome",id:Ie,issue:[{severity:"error",code:"not-found",details:{text:"Not found"}}]},Be={resourceType:"OperationOutcome",id:Ue,issue:[{severity:"error",code:"login",details:{text:"Unauthorized"}}]},qe={resourceType:"OperationOutcome",id:Oe,issue:[{severity:"error",code:"forbidden",details:{text:"Forbidden"}}]},Qe={resourceType:"OperationOutcome",id:De,issue:[{severity:"error",code:"deleted",details:{text:"Gone"}}]},Fe={resourceType:"OperationOutcome",id:Le,issue:[{severity:"error",code:"throttled",details:{text:"Too Many Requests"}}]};function We(e){return{resourceType:"OperationOutcome",id:Ne,issue:[{severity:"information",code:"informational",details:{text:"Accepted"},diagnostics:e}]}}function He(e,t){return{resourceType:"OperationOutcome",issue:[{severity:"error",code:"invalid",details:{text:e},expression:t?[t]:void 0}]}}function ze(e){return{resourceType:"OperationOutcome",issue:[{severity:"error",code:"structure",details:{text:e}}]}}function Ge(e){return{resourceType:"OperationOutcome",issue:[{severity:"error",code:"exception",details:{text:"Internal server error"},diagnostics:e.toString()}]}}function Ve(e){return"object"==typeof e&&null!==e&&"OperationOutcome"===e.resourceType}function Je(e){return e.id===Pe||e.id===Ae||e.id===Re||e.id===Ne}function Xe(e){return e.id===Ne}function Ye(e){return e.id===Ie}function Ze(e){return e.id===De}function Ke(e){return e.id===Pe?200:e.id===Ae?201:e.id===Ne?202:e.id===Re?304:e.id===Ue?401:e.id===Oe?403:e.id===Ie?404:e.id===De?410:e.id===Le?429:400}function et(e,t){if(!Je(e)||void 0===t)throw new tt(e)}class tt extends Error{constructor(e,t){super(it(e)),this.outcome=e,this.cause=t}}function nt(e){return e instanceof tt?e.outcome:Ve(e)?e:He(rt(e))}function rt(e){return e?"string"==typeof e?e:e instanceof Error?e.message:Ve(e)?it(e):JSON.stringify(e):"Unknown error"}function it(e){const t=e.issue?.map(ot)??[];return t.length>0?t.join("; "):"Unknown error"}function ot(e){let t=e.details?.text??e.diagnostics??"Unknown error";return e.expression?.length&&(t+=` (${e.expression.join(", ")})`),t}const st=20;var at;!function(e){e.EQUALS="eq",e.NOT_EQUALS="ne",e.GREATER_THAN="gt",e.LESS_THAN="lt",e.GREATER_THAN_OR_EQUALS="ge",e.LESS_THAN_OR_EQUALS="le",e.STARTS_AFTER="sa",e.ENDS_BEFORE="eb",e.APPROXIMATELY="ap",e.CONTAINS="contains",e.EXACT="exact",e.TEXT="text",e.NOT="not",e.ABOVE="above",e.BELOW="below",e.IN="in",e.NOT_IN="not-in",e.OF_TYPE="of-type",e.MISSING="missing",e.IDENTIFIER="identifier",e.ITERATE="iterate"}(at||(at={}));const ct={contains:at.CONTAINS,exact:at.EXACT,above:at.ABOVE,below:at.BELOW,text:at.TEXT,not:at.NOT,in:at.IN,"not-in":at.NOT_IN,"of-type":at.OF_TYPE,missing:at.MISSING,identifier:at.IDENTIFIER,iterate:at.ITERATE},ut={eq:at.EQUALS,ne:at.NOT_EQUALS,lt:at.LESS_THAN,le:at.LESS_THAN_OR_EQUALS,gt:at.GREATER_THAN,ge:at.GREATER_THAN_OR_EQUALS,sa:at.STARTS_AFTER,eb:at.ENDS_BEFORE,ap:at.APPROXIMATELY};function dt(e,t){const n=[];for(const[e,r]of Object.entries(t))if(Array.isArray(r))for(const t of r)n.push([e,t]);else n.push([e,r||""]);return ft(e,n)}function pt(e){return ft(e.pathname.split("/").filter(Boolean).pop(),e.searchParams.entries())}function lt(e){return pt(new URL(e,"https://example.com/"))}function ht(e){return pt(new URL(e,"https://api.medplum.com/"))}function ft(e,t){const n={resourceType:e};for(const[e,r]of t)mt(n,e,r);return n}function mt(e,t,n){let r,i;const o=t.indexOf(":");switch(o>=0?(r=t.substring(0,o),i=t.substring(o+1)):(r=t,i=""),r){case"_sort":!function(e,t){for(const n of t.split(",")){let t,r=!1;n.startsWith("-")?(t=n.substring(1),r=!0):t=n,e.sortRules||(e.sortRules=[]),e.sortRules.push({code:t,descending:r})}}(e,n);break;case"_count":e.count=parseInt(n,10);break;case"_offset":e.offset=parseInt(n,10);break;case"_total":e.total=n;break;case"_summary":e.total="accurate",e.count=0;break;case"_include":{const t=vt(n);"iterate"===i&&(t.modifier=at.ITERATE),e.include?e.include.push(t):e.include=[t];break}case"_revinclude":{const t=vt(n);"iterate"===i&&(t.modifier=at.ITERATE),e.revInclude?e.revInclude.push(t):e.revInclude=[t];break}case"_fields":e.fields=n.split(",");break;default:{const t=Ce.types[e.resourceType]?.searchParams?.[r];t?function(e,t,n,r){if("missing"===n)return void xt(e,{code:t.code,operator:at.MISSING,value:r});switch(t.type){case"number":case"date":!function(e,t,n){const{operator:r,value:i}=yt(n);xt(e,{code:t.code,operator:r,value:i})}(e,t,r);break;case"reference":case"string":case"token":case"uri":!function(e,t,n,r){xt(e,{code:t.code,operator:gt(n),value:r})}(e,t,n,r);break;case"quantity":!function(e,t,n){const[r,i,o]=n.split("|"),{operator:s,value:a}=yt(r);xt(e,{code:t.code,operator:s,value:a,unitSystem:i,unitCode:o})}(e,t,r)}}(e,t,i,n):function(e,t,n,r){let i=at.EQUALS;if(n)i=n;else if(r.length>=2){const e=r.substring(0,2);e in ut&&(2===r.length||r.at(2)?.match(/\d/))&&(i=e,r=r.substring(e.length))}xt(e,{code:t,operator:i,value:r})}(e,r,i,n)}}}function yt(e){const t=e.substring(0,2),n=ut[t];return n?{operator:n,value:e.substring(2)}:{operator:at.EQUALS,value:e}}function gt(e){return ct[e]||at.EQUALS}function vt(e){const t=e.split(":");if(t.forEach((e=>{if("*"===e)throw new tt(He("'*' is not supported as a value for search inclusion parameters"))})),1===t.length)throw new tt(He(`Invalid include value '${e}': must be of the form ResourceType:search-parameter`));if(2===t.length)return{resourceType:t[0],searchParam:t[1]};if(3===t.length)return{resourceType:t[0],searchParam:t[1],targetType:t[2]};throw new tt(He(`Invalid include value '${e}'`))}function xt(e,t){e.filters?e.filters.push(t):e.filters=[t]}function bt(e){const t=[];return e.fields&&t.push("_fields="+e.fields.join(",")),e.filters&&e.filters.forEach((e=>t.push(function(e){const t=e.operator in ct?":"+e.operator:"",n=e.operator!==at.EQUALS&&e.operator in ut?e.operator:"";return`${e.code}${t}=${n}${encodeURIComponent(e.value)}`}(e)))),e.sortRules&&e.sortRules.length>0&&t.push("_sort="+e.sortRules.map((e=>e.descending?"-"+e.code:e.code)).join(",")),void 0!==e.offset&&t.push("_offset="+e.offset),void 0!==e.count&&t.push("_count="+e.count),void 0!==e.total&&t.push("_total="+e.total),0===t.length?"":(t.sort(),"?"+t.join("&"))}class St{constructor(e,t){this.operator=e,this.child=t}toString(){return`${this.operator}(${this.child.toString()})`}}class wt{constructor(e,t,n){this.operator=e,this.left=t,this.right=n}toString(){return`${this.left.toString()} ${this.operator} ${this.right.toString()}`}}class Tt{constructor(){this.prefixParselets={},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(e,r){const i=e.consumeAndParse(t);return n(r,i)}})}infixLeft(e,t,n){return this.registerInfix(e,{parse(e,r,i){const o=e.consumeAndParse(t);return n(r,i,o)},precedence:t})}construct(e){return new Et(e,this.prefixParselets,this.infixParselets)}}class Et{constructor(e,t,n){this.tokens=e,this.prefixParselets=t,this.infixParselets=n}hasMore(){return this.tokens.length>0}match(e){const t=this.peek();return t?.id===e&&(this.consume(),!0)}consumeAndParse(e=1/0){const t=this.consume(),n=this.prefixParselets[t.id];if(!n)throw Error(`Parse error at "${t.value}" (line ${t.line}, column ${t.column}). No matching prefix parselet.`);let r=n.parse(this,t);for(;e>this.getPrecedence();){const e=this.consume();r=this.getInfixParselet(e).parse(this,r,e)}return r}getPrecedence(){const e=this.peek();if(!e)return 1/0;const t=this.getInfixParselet(e);return t?t.precedence:1/0}consume(e,t){if(!this.tokens.length)throw Error("Cant consume unknown more tokens.");if(e&&this.peek()?.id!==e){const t=this.peek();throw Error(`Expected ${e} but got "${t.id}" at line ${t.line} column ${t.column}.`)}if(t&&this.peek()?.value!==t){const e=this.peek();throw Error(`Expected "${t}" but got "${e.value}" at line ${e.line} column ${e.column}.`)}return this.tokens.shift()}peek(){return this.tokens.length>0?this.tokens[0]:void 0}removeComments(){this.tokens=this.tokens.filter((e=>"Comment"!==e.id))}getInfixParselet(e){return this.infixParselets["Symbol"===e.id?e.value:e.id]}}const kt=["year","years","month","months","week","weeks","day","days","hour","hours","minute","minutes","second","seconds","millisecond","milliseconds"];class Ct{constructor(e,t,n,r){this.result=[],this.pos={index:0,line:1,column:0},this.markStack=[],this.str=e,this.keywords=t,this.operators=n,this.dateTimeLiterals=!!r?.dateTimeLiterals,this.symbolRegex=r?.symbolRegex??/[$\w%]/}tokenize(){for(;this.pos.index<this.str.length;){const e=this.consumeToken();e&&this.result.push(e)}return this.result}prevToken(){return this.result.slice(-1)[0]}peekToken(){this.mark();const e=this.consumeToken();return this.reset(),e}consumeToken(){this.consumeWhitespace();const e=this.curr();if(!e)return;this.mark();const t=this.peek();return"/"===e&&"*"===t?this.consumeMultiLineComment():"/"===e&&"/"===t?this.consumeSingleLineComment():"'"===e||'"'===e?this.consumeString(e):"`"===e?this.consumeBacktickSymbol():"@"===e?this.consumeDateTime():e.match(/\d/)?this.consumeNumber():e.match(/\w/)?this.consumeSymbol():"$"!==e&&"%"!==e||!t.match(/\w/)?this.consumeOperator():this.consumeSymbol()}consumeWhitespace(){this.consumeWhile((()=>this.curr().match(/\s/)))}consumeMultiLineComment(){const 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((()=>"\n"!==this.curr())))}consumeString(e){this.advance();const t=this.buildToken("String",this.consumeWhile((()=>"\\"===this.prev()||this.curr()!==e)));return this.advance(),t}consumeBacktickSymbol(){this.advance();const e=this.buildToken("Symbol",this.consumeWhile((()=>"`"!==this.curr())));return this.advance(),e}consumeDateTime(){this.advance();const e=this.pos.index;return this.consumeWhile((()=>this.curr().match(/[\d-]/))),"T"===this.curr()&&(this.advance(),this.consumeWhile((()=>this.curr().match(/[\d:]/))),"."===this.curr()&&this.peek().match(/\d/)&&(this.advance(),this.consumeWhile((()=>this.curr().match(/\d/)))),"Z"===this.curr()?this.advance():"+"!==this.curr()&&"-"!==this.curr()||(this.advance(),this.consumeWhile((()=>this.curr().match(/[\d:]/))))),this.buildToken("DateTime",this.str.substring(e,this.pos.index))}consumeNumber(){const e=this.pos.index;let t="Number";return this.consumeWhile((()=>this.curr().match(/\d/))),"."===this.curr()&&this.peek().match(/\d/)&&(this.advance(),this.consumeWhile((()=>this.curr().match(/\d/)))),"-"===this.curr()&&this.dateTimeLiterals?(this.pos.index=e-1,this.consumeDateTime()):(" "===this.curr()&&function(e){if(e){if("String"===e.id)return!0;if("Symbol"===e.id&&kt.includes(e.value))return!0}return!1}(this.peekToken())&&(t="Quantity",this.consumeToken()),this.buildToken(t,this.str.substring(e,this.pos.index)))}consumeSymbol(){const e=this.consumeWhile((()=>this.curr().match(this.symbolRegex)));return"."!==this.prevToken()?.value&&this.keywords.includes(e)?this.buildToken(e,e):this.buildToken("Symbol",e)}consumeOperator(){const e=this.curr(),t=e+this.peek();return this.operators.includes(t)?(this.advance(),this.advance(),this.buildToken(t,t)):(this.advance(),this.buildToken(e,e))}consumeWhile(e){const 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]}prev(){return this.str[this.pos.index-1]??""}peek(){return this.str[this.pos.index+1]??""}mark(){this.markStack.push({...this.pos})}reset(){const 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++,"\n"===this.curr()?(this.pos.line++,this.pos.column=0):this.pos.column++}buildToken(e,t){const n=this.markStack.pop();if(!n)throw new Error("No mark for token");return{id:e,value:t,...n}}}function Pt(e){if(e.startsWith("T"))return e+"T00:00:00.000Z".substring(e.length);if(e.length<=10)return e;try{return new Date(e).toISOString()}catch(t){return e}}function At(e){return[{type:ue.boolean,value:e}]}function Dt(e){return null==e?{type:"undefined",value:void 0}:Number.isSafeInteger(e)?{type:ue.integer,value:e}:"number"==typeof e?{type:ue.decimal,value:e}:"boolean"==typeof e?{type:ue.boolean,value:e}:"string"==typeof e?{type:ue.string,value:e}:Qt(e)?{type:ue.Quantity,value:e}:Ee(e)?{type:e.resourceType,value:e}:{type:ue.BackboneElement,value:e}}function Rt(e){return 0!==e.length&&!!e[0].value}function It(e,t){if(!e.value)return;const n=Te(e.type,t);if(n){const r=function(e,t,n){const r=n.type;if(!r||0===r.length)return;let i,o="undefined";if(1===r.length)i=e.value[t],o=r[0].code;else for(const n of r){const r=t.replace("[x]","")+G(n.code);if(r in e.value){i=e.value[r],o=n.code;break}}if(j(i))return;"Element"!==o&&"BackboneElement"!==o||(o=me(n.path?.split(".")));return Array.isArray(i)?i.map((e=>Ut(e,o))):Ut(i,o)}(e,t,n);if(r)return r}return function(e,t){const n=e.value;if(!n||"object"!=typeof n)return;let r;if(t in n)r=n[t];else for(const e in ue){const i=t+G(e);if(i in n){r=n[i];break}}if(j(r))return;return Array.isArray(r)?r.map(Dt):Dt(r)}(e,t)}function Ut(e,t){return"Resource"===t&&Ee(e)&&(t=e.resourceType),{type:t,value:e}}function Ot(e){const t=[];for(const n of e){let e=!1;for(const r of t)if(Rt(Mt(n,r))){e=!0;break}e||t.push(n)}return t}function Lt(e){return At(!Rt(e))}function Nt(e,t){return 0===e.length||0===t.length?[]:e.length!==t.length?At(!1):At(e.every(((e,n)=>Rt(Mt(e,t[n])))))}function Mt(e,t){const n=e.value,r=t.value;return"number"==typeof n&&"number"==typeof r?At(Math.abs(n-r)<1e-8):Qt(n)&&Qt(r)?At(Ft(n,r)):At("object"==typeof n&&"object"==typeof r?Wt(e,t):n===r)}function _t(e,t){return 0===e.length&&0===t.length?At(!0):e.length!==t.length?At(!1):(e.sort($t),t.sort($t),At(e.every(((e,n)=>Rt(jt(e,t[n]))))))}function jt(e,t){const n=e.value,r=t.value;return"number"==typeof n&&"number"==typeof r?At(Math.abs(n-r)<.01):Qt(n)&&Qt(r)?At(Ft(n,r)):At("object"==typeof n&&"object"==typeof r?Wt(n,r):"string"==typeof n&&"string"==typeof r?n.toLowerCase()===r.toLowerCase():n===r)}function $t(e,t){const n=e.value,r=t.value;return"number"==typeof n&&"number"==typeof r?n-r:"string"==typeof n&&"string"==typeof r?n.localeCompare(r):0}function Bt(e,t){const{value:n}=e;if(null==n)return!1;switch(t){case"Boolean":return"boolean"==typeof n;case"Decimal":case"Integer":return"number"==typeof n;case"Date":return"string"==typeof n&&!!n.match(/^\d{4}(-\d{2}(-\d{2})?)?/);case"DateTime":return"string"==typeof n&&!!n.match(/^\d{4}(-\d{2}(-\d{2})?)?T/);case"Time":return"string"==typeof n&&!!n.match(/^T\d/);case"Period":return qt(n);case"Quantity":return Qt(n);default:return"object"==typeof n&&n?.resourceType===t}}function qt(e){return!(!e||"object"!=typeof e||!("start"in e))}function Qt(e){return!(!e||"object"!=typeof e||!("value"in e)||"number"!=typeof e.value)}function Ft(e,t){return Math.abs(e.value-t.value)<.01&&(e.unit===t.unit||e.code===t.code||e.unit===t.code||e.code===t.unit)}function Wt(e,t){const n=Object.keys(e),r=Object.keys(t);if(n.length!==r.length)return!1;for(const r of n){const n=e[r],i=t[r];if(Ht(n)&&Ht(i)){if(!Wt(n,i))return!1}else if(n!==i)return!1}return!0}function Ht(e){return null!==e&&"object"==typeof e}const zt=()=>[],Gt={empty:(e,t)=>At(0===t.length),exists:(e,t,n)=>At(n?t.filter((t=>Rt(n.eval(e,[t])))).length>0:t.length>0),all:(e,t,n)=>At(t.every((t=>Rt(n.eval(e,[t]))))),allTrue:(e,t)=>{for(const e of t)if(!e.value)return At(!1);return At(!0)},anyTrue:(e,t)=>{for(const e of t)if(e.value)return At(!0);return At(!1)},allFalse:(e,t)=>{for(const e of t)if(e.value)return At(!1);return At(!0)},anyFalse:(e,t)=>{for(const e of t)if(!e.value)return At(!0);return At(!1)},subsetOf:zt,supersetOf:zt,count:(e,t)=>[{type:ue.integer,value:t.length}],distinct:(e,t)=>{const n=[];for(const e of t)n.some((t=>t.value===e.value))||n.push(e);return n},isDistinct:(e,t)=>At(t.length===Gt.distinct(e,t).length),where:(e,t,n)=>t.filter((t=>Rt(n.eval(e,[t])))),select:(e,t,n)=>t.map((t=>n.eval(e,[t]))).flat(),repeat:zt,ofType:(e,t,n)=>t.filter((e=>e.type===n.name)),single:(e,t)=>{if(t.length>1)throw new Error("Expected input length one for single()");return 0===t.length?[]:t.slice(0,1)},first:(e,t)=>0===t.length?[]:t.slice(0,1),last:(e,t)=>0===t.length?[]:t.slice(t.length-1,t.length),tail:(e,t)=>0===t.length?[]:t.slice(1,t.length),skip:(e,t,n)=>{const r=n.eval(e,t)[0]?.value;if("number"!=typeof r)throw new Error("Expected a number for skip(num)");return r>=t.length?[]:r<=0?t:t.slice(r,t.length)},take:(e,t,n)=>{const r=n.eval(e,t)[0]?.value;if("number"!=typeof r)throw new Error("Expected a number for take(num)");return r>=t.length?t:r<=0?[]:t.slice(0,r)},intersect:(e,t,n)=>{if(!n)return t;const r=n.eval(e,t),i=[];for(const e of t)!i.some((t=>t.value===e.value))&&r.some((t=>t.value===e.value))&&i.push(e);return i},exclude:(e,t,n)=>{if(!n)return t;const r=n.eval(e,t),i=[];for(const e of t)r.some((t=>t.value===e.value))||i.push(e);return i},union:(e,t,n)=>{if(!n)return t;const r=n.eval(e,t);return Ot([...t,...r])},combine:(e,t,n)=>{if(!n)return t;const r=n.eval(e,t);return[...t,...r]},iif:(e,t,n,r,i)=>{const o=n.eval(e,t);if(o.length>1||1===o.length&&"boolean"!=typeof o[0].value)throw new Error("Expected criterion to evaluate to a Boolean");return Rt(o)?r.eval(e,t):i?i.eval(e,t):[]},toBoolean:(e,t)=>{if(0===t.length)return[];const[{value:n}]=Xt(t,1);if("boolean"==typeof n)return[{type:ue.boolean,value:n}];if("number"==typeof n&&(0===n||1===n))return At(!!n);if("string"==typeof n){const e=n.toLowerCase();if(["true","t","yes","y","1","1.0"].includes(e))return At(!0);if(["false","f","no","n","0","0.0"].includes(e))return At(!1)}return[]},convertsToBoolean:(e,t)=>0===t.length?[]:At(1===Gt.toBoolean(e,t).length),toInteger:(e,t)=>{if(0===t.length)return[];const[{value:n}]=Xt(t,1);return"number"==typeof n?[{type:ue.integer,value:n}]:"string"==typeof n&&n.match(/^[+-]?\d+$/)?[{type:ue.integer,value:parseInt(n,10)}]:"boolean"==typeof n?[{type:ue.integer,value:n?1:0}]:[]},convertsToInteger:(e,t)=>0===t.length?[]:At(1===Gt.toInteger(e,t).length),toDate:(e,t)=>{if(0===t.length)return[];const[{value:n}]=Xt(t,1);return"string"==typeof n&&n.match(/^\d{4}(-\d{2}(-\d{2})?)?/)?[{type:ue.date,value:Pt(n)}]:[]},convertsToDate:(e,t)=>0===t.length?[]:At(1===Gt.toDate(e,t).length),toDateTime:(e,t)=>{if(0===t.length)return[];const[{value:n}]=Xt(t,1);return"string"==typeof n&&n.match(/^\d{4}(-\d{2}(-\d{2})?)?/)?[{type:ue.dateTime,value:Pt(n)}]:[]},convertsToDateTime:(e,t)=>0===t.length?[]:At(1===Gt.toDateTime(e,t).length),toDecimal:(e,t)=>{if(0===t.length)return[];const[{value:n}]=Xt(t,1);return"number"==typeof n?[{type:ue.decimal,value:n}]:"string"==typeof n&&n.match(/^-?\d{1,9}(\.\d{1,9})?$/)?[{type:ue.decimal,value:parseFloat(n)}]:"boolean"==typeof n?[{type:ue.decimal,value:n?1:0}]:[]},convertsToDecimal:(e,t)=>0===t.length?[]:At(1===Gt.toDecimal(e,t).length),toQuantity:(e,t)=>{if(0===t.length)return[];const[{value:n}]=Xt(t,1);return Qt(n)?[{type:ue.Quantity,value:n}]:"number"==typeof n?[{type:ue.Quantity,value:{value:n,unit:"1"}}]:"string"==typeof n&&n.match(/^-?\d{1,9}(\.\d{1,9})?/)?[{type:ue.Quantity,value:{value:parseFloat(n),unit:"1"}}]:"boolean"==typeof n?[{type:ue.Quantity,value:{value:n?1:0,unit:"1"}}]:[]},convertsToQuantity:(e,t)=>0===t.length?[]:At(1===Gt.toQuantity(e,t).length),toString:(e,t)=>{if(0===t.length)return[];const[{value:n}]=Xt(t,1);return null==n?[]:Qt(n)?[{type:ue.string,value:`${n.value} '${n.unit}'`}]:[{type:ue.string,value:n.toString()}]},convertsToString:(e,t)=>0===t.length?[]:At(1===Gt.toString(e,t).length),toTime:(e,t)=>{if(0===t.length)return[];const[{value:n}]=Xt(t,1);if("string"==typeof n){const e=n.match(/^T?(\d{2}(:\d{2}(:\d{2})?)?)/);if(e)return[{type:ue.time,value:Pt("T"+e[1])}]}return[]},convertsToTime:(e,t)=>0===t.length?[]:At(1===Gt.toTime(e,t).length),indexOf:(e,t,n)=>Vt(((e,t)=>e.indexOf(t)),e,t,n),substring:(e,t,n,r)=>Vt(((e,t,n)=>{const r=t,i=n?r+n:e.length;return r<0||r>=e.length?void 0:e.substring(r,i)}),e,t,n,r),startsWith:(e,t,n)=>Vt(((e,t)=>e.startsWith(t)),e,t,n),endsWith:(e,t,n)=>Vt(((e,t)=>e.endsWith(t)),e,t,n),contains:(e,t,n)=>Vt(((e,t)=>e.includes(t)),e,t,n),upper:(e,t)=>Vt((e=>e.toUpperCase()),e,t),lower:(e,t)=>Vt((e=>e.toLowerCase()),e,t),replace:(e,t,n,r)=>Vt(((e,t,n)=>e.replaceAll(t,n)),e,t,n,r),matches:(e,t,n)=>Vt(((e,t)=>!!e.match(t)),e,t,n),replaceMatches:(e,t,n,r)=>Vt(((e,t,n)=>e.replaceAll(t,n)),e,t,n,r),length:(e,t)=>Vt((e=>e.length),e,t),toChars:(e,t)=>Vt((e=>e?e.split(""):void 0),e,t),abs:(e,t)=>Jt(Math.abs,e,t),ceiling:(e,t)=>Jt(Math.ceil,e,t),exp:(e,t)=>Jt(Math.exp,e,t),floor:(e,t)=>Jt(Math.floor,e,t),ln:(e,t)=>Jt(Math.log,e,t),log:(e,t,n)=>Jt(((e,t)=>Math.log(e)/Math.log(t)),e,t,n),power:(e,t,n)=>Jt(Math.pow,e,t,n),round:(e,t)=>Jt(Math.round,e,t),sqrt:(e,t)=>Jt(Math.sqrt,e,t),truncate:(e,t)=>Jt((e=>0|e),e,t),children:zt,descendants:zt,trace:(e,t,n)=>(console.log("trace",t,n),t),now:()=>[{type:ue.dateTime,value:(new Date).toISOString()}],timeOfDay:()=>[{type:ue.time,value:(new Date).toISOString().substring(11)}],today:()=>[{type:ue.date,value:(new Date).toISOString().substring(0,10)}],between:(e,t,n,r,i)=>{const o=Gt.toDateTime(e,n.eval(e,t));if(0===o.length)throw new Error("Invalid start date");const s=Gt.toDateTime(e,r.eval(e,t));if(0===s.length)throw new Error("Invalid end date");const a=i.eval(e,t)[0]?.value;if("years"!==a&&"months"!==a&&"days"!==a)throw new Error("Invalid units");const c=D(o[0].value,s[0].value);return[{type:ue.Quantity,value:{value:c[a],unit:a}}]},is:(e,t,n)=>{let r="";return n instanceof Kt?r=n.name:n instanceof cn&&(r=n.left.name+"."+n.right.name),r?t.map((e=>({type:ue.boolean,value:Bt(e,r)}))):[]},not:(e,t)=>Gt.toBoolean(e,t).map((e=>({type:ue.boolean,value:!e.value}))),resolve:(e,t)=>t.map((e=>{const t=e.value;let n;if("string"==typeof t)n=t;else if("object"==typeof t){const e=t;if(e.resource)return Dt(e.resource);e.reference?n=e.reference:e.type&&e.identifier&&(n=`${e.type}?identifier=${e.identifier.system}|${e.identifier.value}`)}if(n?.includes("?")){const[e]=n.split("?");return{type:e,value:{resourceType:e}}}if(n?.includes("/")){const[e,t]=n.split("/");return{type:e,value:{resourceType:e,id:t}}}return{type:ue.BackboneElement,value:void 0}})).filter((e=>!!e.value)),as:(e,t)=>t,type:(e,t)=>t.map((({value:e})=>"boolean"==typeof e?{type:ue.BackboneElement,value:{namespace:"System",name:"Boolean"}}:"number"==typeof e?{type:ue.BackboneElement,value:{namespace:"System",name:"Integer"}}:Ee(e)?{type:ue.BackboneElement,value:{namespace:"FHIR",name:e.resourceType}}:{type:ue.BackboneElement,value:null})),conformsTo:(e,t,n)=>{const r=n.eval(e,t)[0].value;if(!r.startsWith("http://hl7.org/fhir/StructureDefinition/"))throw new Error("Expected a StructureDefinition URL");const i=r.replace("http://hl7.org/fhir/StructureDefinition/","");return t.map((e=>({type:ue.boolean,value:e.value?.resourceType===i})))}};function Vt(e,t,n,...r){if(0===n.length)return[];const[{value:i}]=Xt(n,1);if("string"!=typeof i)throw new Error("String function cannot be called with non-string");const o=e(i,...r.map((e=>e?.eval(t,n)[0]?.value)));return void 0===o?[]:Array.isArray(o)?o.map(Dt):[Dt(o)]}function Jt(e,t,n,...r){if(0===n.length)return[];const[{value:i}]=Xt(n,1),o=Qt(i),s=o?i.value:i;if("number"!=typeof s)throw new Error("Math function cannot be called with non-number");const a=e(s,...r.map((e=>e.eval(t,n)[0]?.value)));return[{type:o?ue.Quantity:n[0].type,value:o?{...i,value:a}:a}]}function Xt(e,t){if(e.length!==t)throw new Error(`Expected ${t} arguments`);for(const t of e)if(null==t)throw new Error("Expected non-null argument");return e}class Yt{constructor(e,t){this.original=e,this.child=t}eval(e,t){try{return t.length>0?t.map((t=>this.child.eval(e,[t]))).flat():this.child.eval(e,[])}catch(e){throw new Error(`FhirPathError on "${this.original}": ${e}`)}}toString(){return this.child.toString()}}class Zt{constructor(e){this.value=e}eval(){return[this.value]}toString(){const e=this.value.value;return"string"==typeof e?`'${e}'`:e.toString()}}class Kt{constructor(e){this.name=e}eval(e,t){if("$this"===this.name)return t;if(this.name.startsWith("%")){const t=e.variables[this.name.slice(1)];if(!t)throw new Error(`Undefined variable ${this.name}`);return[t]}return t.flatMap((e=>this.evalValue(e))).filter((e=>void 0!==e?.value))}evalValue(e){const t=e.value;if(t&&"object"==typeof t)return Ee(t)&&t.resourceType===this.name?e:It(e,this.name)}toString(){return this.name}}class en{eval(){return[]}toString(){return"{}"}}class tn extends St{constructor(e,t,n){super(e,t),this.impl=n}eval(e,t){return this.impl(this.child.eval(e,t))}toString(){return this.child.toString()}}class nn extends wt{constructor(e,t){super("as",e,t)}eval(e,t){return Gt.ofType(e,this.left.eval(e,t),this.right)}}class rn extends wt{constructor(e,t,n,r){super(e,t,n),this.impl=r}eval(e,t){const n=this.left.eval(e,t);if(1!==n.length)return[];const r=this.right.eval(e,t);if(1!==r.length)return[];const i=n[0].value,o=r[0].value,s=Qt(i)?i.value:i,a=Qt(o)?o.value:o,c=this.impl(s,a);return"boolean"==typeof c?At(c):Qt(i)?[{type:ue.Quantity,value:{...i,value:c}}]:[Dt(c)]}}class on extends wt{constructor(e,t){super("&",e,t)}eval(e,t){const n=[...this.left.eval(e,t),...this.right.eval(e,t)];return n.length>0&&n.every((e=>"string"==typeof e.value))?[{type:ue.string,value:n.map((e=>e.value)).join("")}]:n}}class sn extends wt{constructor(e,t){super("contains",e,t)}eval(e,t){const n=this.left.eval(e,t),r=this.right.eval(e,t);return At(n.some((e=>e.value===r[0].value)))}}class an extends wt{constructor(e,t){super("in",e,t)}eval(e,t){const n=this.left.eval(e,t);return At(this.right.eval(e,t).some((e=>e.value===n[0].value)))}}class cn extends wt{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()}`}}class un extends wt{constructor(e,t){super("|",e,t)}eval(e,t){return Ot([...this.left.eval(e,t),...this.right.eval(e,t)])}}class dn extends wt{constructor(e,t){super("=",e,t)}eval(e,t){return Nt(this.left.eval(e,t),this.right.eval(e,t))}}class pn extends wt{constructor(e,t){super("!=",e,t)}eval(e,t){return Lt(Nt(this.left.eval(e,t),this.right.eval(e,t)))}}class ln extends wt{constructor(e,t){super("~",e,t)}eval(e,t){return _t(this.left.eval(e,t),this.right.eval(e,t))}}class hn extends wt{constructor(e,t){super("!~",e,t)}eval(e,t){return Lt(_t(this.left.eval(e,t),this.right.eval(e,t)))}}class fn extends wt{constructor(e,t){super("is",e,t)}eval(e,t){const n=this.left.eval(e,t);if(1!==n.length)return[];const r=this.right.name;return At(Bt(n[0],r))}}class mn extends wt{constructor(e,t){super("and",e,t)}eval(e,t){const n=this.left.eval(e,t),r=this.right.eval(e,t);return!0===n[0]?.value&&!0===r[0]?.value?At(!0):!1===n[0]?.value||!1===r[0]?.value?At(!1):[]}}class yn extends wt{constructor(e,t){super("or",e,t)}eval(e,t){const n=this.left.eval(e,t);if(Rt(n))return n;const r=this.right.eval(e,t);return Rt(r)?r:[]}}class gn extends wt{constructor(e,t){super("xor",e,t)}eval(e,t){const n=this.left.eval(e,t),r=this.right.eval(e,t);if(0===n.length&&0===r.length)return[];const i=0===n.length?null:n[0].value,o=0===r.length?null:r[0].value;return!0===i&&!0!==o||!0!==i&&!0===o?At(!0):!0===i&&!0===o||!1===i&&!1===o?At(!1):[]}}class vn{constructor(e,t){this.name=e,this.args=t}eval(e,t){const n=Gt[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(", ")})`}}class xn{constructor(e,t){this.left=e,this.expr=t}eval(e,t){const n=this.expr.eval(e,t);if(1!==n.length)return[];const r=n[0].value;if("number"!=typeof r)throw new Error("Invalid indexer expression: should return integer}");const i=this.left.eval(e,t);return r in i?[i[r]]:[]}toString(){return`${this.left.toString()}[${this.expr.toString()}]`}}const bn=["true","false"],Sn=["!=","!~","<=",">=","{}","->"];function wn(e){return new Ct(e,bn,Sn).tokenize()}const Tn={parse(e){const t=e.consumeAndParse();if(!e.match(")"))throw new Error("Parse error: expected `)` got `"+e.peek()?.value+"`");return t}},En={parse(e,t){const n=e.consumeAndParse();if(!e.match("]"))throw new Error("Parse error: expected `]`");return new xn(t,n)},precedence:2},kn={parse(e,t){if(!(t instanceof Kt))throw new Error("Unexpected parentheses");const n=[];for(;!e.match(")");)n.push(e.consumeAndParse()),e.match(",");return new vn(t.name,n)},precedence:0};function Cn(e){const t=e.split(" "),n=parseFloat(t[0]);let r=t[1];return r=r?.startsWith("'")&&r.endsWith("'")?r.substring(1,r.length-1):"{"+r+"}",{value:n,unit:r}}function Pn(){return(new Tt).registerPrefix("String",{parse:(e,t)=>new Zt({type:ue.string,value:t.value})}).registerPrefix("DateTime",{parse:(e,t)=>new Zt({type:ue.dateTime,value:Pt(t.value)})}).registerPrefix("Quantity",{parse:(e,t)=>new Zt({type:ue.Quantity,value:Cn(t.value)})}).registerPrefix("Number",{parse:(e,t)=>new Zt({type:ue.decimal,value:parseFloat(t.value)})}).registerPrefix("true",{parse:()=>new Zt({type:ue.boolean,value:!0})}).registerPrefix("false",{parse:()=>new Zt({type:ue.boolean,value:!1})}).registerPrefix("Symbol",{parse:(e,t)=>new Kt(t.value)}).registerPrefix("{}",{parse:()=>new en}).registerPrefix("(",Tn).registerInfix("[",En).registerInfix("(",kn).prefix("+",3,((e,t)=>new tn("+",t,(e=>e)))).prefix("-",3,((e,t)=>new rn("-",t,t,((e,t)=>-t)))).infixLeft(".",1,((e,t,n)=>new cn(e,n))).infixLeft("/",4,((e,t,n)=>new rn("/",e,n,((e,t)=>e/t)))).infixLeft("*",4,((e,t,n)=>new rn("*",e,n,((e,t)=>e*t)))).infixLeft("+",5,((e,t,n)=>new rn("+",e,n,((e,t)=>e+t)))).infixLeft("-",5,((e,t,n)=>new rn("-",e,n,((e,t)=>e-t)))).infixLeft("|",7,((e,t,n)=>new un(e,n))).infixLeft("=",9,((e,t,n)=>new dn(e,n))).infixLeft("!=",9,((e,t,n)=>new pn(e,n))).infixLeft("~",9,((e,t,n)=>new ln(e,n))).infixLeft("!~",9,((e,t,n)=>new hn(e,n))).infixLeft("<",8,((e,t,n)=>new rn("<",e,n,((e,t)=>e<t)))).infixLeft("<=",8,((e,t,n)=>new rn("<=",e,n,((e,t)=>e<=t)))).infixLeft(">",8,((e,t,n)=>new rn(">",e,n,((e,t)=>e>t)))).infixLeft(">=",8,((e,t,n)=>new rn(">=",e,n,((e,t)=>e>=t)))).infixLeft("&",5,((e,t,n)=>new on(e,n))).infixLeft("and",6,((e,t,n)=>new mn(e,n))).infixLeft("as",6,((e,t,n)=>new nn(e,n))).infixLeft("contains",6,((e,t,n)=>new sn(e,n))).infixLeft("div",6,((e,t,n)=>new rn("div",e,n,((e,t)=>e/t|0)))).infixLeft("in",6,((e,t,n)=>new an(e,n))).infixLeft("is",6,((e,t,n)=>new fn(e,n))).infixLeft("mod",6,((e,t,n)=>new rn("mod",e,n,((e,t)=>e%t)))).infixLeft("or",6,((e,t,n)=>new yn(e,n))).infixLeft("xor",6,((e,t,n)=>new gn(e,n)))}const An=Pn();function Dn(e){return new Yt(e,An.construct(wn(e)).consumeAndParse())}function Rn(e,t){const n=Array.isArray(t)?t:[t];for(let e=0;e<n.length;e++){const t=n[e];"object"==typeof t&&"type"in t&&"value"in t||(n[e]=Dt(n[e]))}return In(e,n).map((e=>e.value))}function In(e,t,n){const r=n||{};return Dn(e).eval({variables:r},t)}var Un;function On(e,t){let n=Ce.types[e].searchParamsDetails?.[t.code];return n||(n=function(e,t){const n=t.code,r=function(e){return e.split("-").reduce(((e,t,n)=>e+(n?G(t):t)),"")}(n),i=Nn(e,t.expression)?.split(".");if(!i)return{columnName:r,type:Un.TEXT};let o,s,a=e,c=!1;for(let n=1;n<i.length;n++){let r=i[n],u=!1;const d=/\[\d+\]$/.exec(r);if(d&&(r=r.substring(0,r.length-d[0].length),u=!0),o=Te(a,r),!o)throw new Error(`Element definition not found for ${e} ${t.code}`);"0"===o.max||"1"===o.max||u||(c=!0),s=o.type?.[0].code,n<i.length-1&&(a=Ln(s)?me(o.path?.split(".")):s)}const u=function(e,t){switch(e.type){case"date":return t===ue.date?Un.DATE:Un.DATETIME;case"number":return Un.NUMBER;case"quantity":return Un.QUANTITY;case"reference":return t===ue.canonical?Un.CANONICAL:Un.REFERENCE;case"token":return t===ue.boolean?Un.BOOLEAN:Un.TEXT;default:return Un.TEXT}}(t,s),d={columnName:r,type:u,elementDefinition:o,array:c};return function(e,t,n){const r=Ce.types[e];r.searchParamsDetails||(r.searchParamsDetails={});r.searchParamsDetails[t]=n}(e,n,d),d}(e,t)),n}function Ln(e){return"Element"===e||"BackboneElement"===e}function Nn(e,t){const n=t.split(" | ");for(const t of n){if((r=t).includes(" as Period")||r.includes(" as SampledDate"))continue;const n=Mn(t);if(n.startsWith(e+"."))return n}var r}function Mn(e){let t=e.trim();t.startsWith("(")&&t.endsWith(")")&&(t=t.substring(1,t.length-1));const n=[" != "," as ",".as(",".exists(",".resolve(",".where("];for(const e of n)t.includes(e)&&(t=t.substring(0,t.indexOf(e)));return t}function _n(e,t){if(t.resourceType!==e.resourceType)return!1;if(t.filters)for(const n of t.filters)if(!jn(e,t,n))return!1;return!0}function jn(e,t,n){const r=Ce.types[t.resourceType].searchParams?.[n.code];switch(r?.type){case"reference":return function(e,t,n){const r=Rn(n.expression,e),i=Qn(t.operator);if(""===t.value&&0===r.length)return t.operator===at.EQUALS;const o=r.map((e=>"string"==typeof e?e:e.reference));for(const e of t.value.split(",")){let n=o.includes(e);if(n||"_compartment"!==t.code||(n=o.some((t=>t?.endsWith("/"+e)))),n)return!i}return i}(e,n,r);case"string":case"uri":return $n(e,n,r);case"token":return function(e,t,n){const r=On(e.resourceType,n);return r.type===Un.BOOLEAN?function(e,t,n){const r=Rn(n.expression,e),i="true"===t.value,o=r.includes(i);return Qn(t.operator)?!o:o}(e,t,n):$n(e,t,n,!0)}(e,n,r);case"date":return function(e,t,n){const r=Rn(n.expression,e),i=t.value.split(","),o=Qn(t.operator);for(const e of r)for(const n of i){if(qn(e,t.operator,n))return!o}return o}(e,n,r);default:return!1}}function $n(e,t,n,r){const i=Rn(n.expression,e),o=t.value.split(","),s=Qn(t.operator);for(const e of i)for(const n of o){if(Bn(e,t.operator,n,r))return!s}return s}function Bn(e,t,n,r){if(r&&n.includes("|")){const[r,i]=n.split("|");return Bn(e,t,r,!1)&&(!i||Bn(e,t,i,!1))}let i="";return e&&("string"==typeof e?i=e:"object"==typeof e&&(i=JSON.stringify(e))),i.toLowerCase().includes(n.toLowerCase())}function qn(e,t,n){switch(t){case at.STARTS_AFTER:case at.GREATER_THAN:return e>n;case at.GREATER_THAN_OR_EQUALS:return e>=n;case at.ENDS_BEFORE:case at.LESS_THAN:return e<n;case at.LESS_THAN_OR_EQUALS:return e<=n;case at.EQUALS:case at.NOT_EQUALS:return e===n;default:return!1}}function Qn(e){return e===at.NOT_EQUALS||e===at.NOT}!function(e){e.BOOLEAN="BOOLEAN",e.NUMBER="NUMBER",e.QUANTITY="QUANTITY",e.TEXT="TEXT",e.REFERENCE="REFERENCE",e.CANONICAL="CANONICAL",e.DATE="DATE",e.DATETIME="DATETIME",e.PERIOD="PERIOD",e.UUID="UUID"}(Un||(Un={}));const Fn=["CapabilityStatement","CompartmentDefinition","ImplementationGuide","OperationDefinition","SearchParameter","StructureDefinition"],Wn=["DomainConfiguration","JsonWebKey","Login","User"],Hn=["PasswordChangeRequest","Project","ProjectMembership"];function zn(e,t){if(e.resource)for(const n of e.resource)if(Yn(n.resourceType,t))return!0;return!1}function Gn(e,t){if(Wn.includes(t))return!1;if(Fn.includes(t))return!1;if(e.resource)for(const n of e.resource)if(Yn(n.resourceType,t)&&!n.readonly)return!0;return!1}function Vn(e,t){return!!Gn(e,t.resourceType)&&Jn(e,t,!1)}function Jn(e,t,n){if(e.resource)for(const r of e.resource)if(Xn(t,r,n))return!0;return!1}function Xn(e,t,n){const r=e.resourceType;return!!Yn(t.resourceType,r)&&(!(!n&&t.readonly)&&(!(t.compartment&&!e.meta?.compartment?.find((e=>e.reference===t.compartment?.reference)))&&!(t.criteria&&!_n(e,ht(t.criteria)))))}function Yn(e,t){return e===t||"*"===e&&!Hn.includes(t)}function Zn(e){if("undefined"!=typeof window)return window.atob(e);if("undefined"!=typeof Buffer)return Buffer.from(e,"base64").toString("binary");throw new Error("Unable to decode base64")}function Kn(e){if("undefined"!=typeof window)return window.btoa(e);if("undefined"!=typeof Buffer)return Buffer.from(e,"binary").toString("base64");throw new Error("Unable to encode base64")}function er(e){for(const t of e.entry||[])delete t.resource?.meta,t.fullUrl="urn:uuid:"+t.resource?.id,delete t.resource?.id;const t=e.entry,n=JSON.stringify({resourceType:"Bundle",type:"transaction",entry:t?.map((e=>({fullUrl:e.fullUrl,request:{method:"POST",url:e.resource.resourceType},resource:e.resource})))},tr,2);return JSON.parse(n)}function tr(e,t){return"reference"===e&&"string"==typeof t&&t.includes("/")?"urn:uuid:"+t.split("/")[1]:t}class nr{constructor(e=10){this.max=e,this.cache=new Map}clear(){this.cache.clear()}get(e){const 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}}function rr(){const e=new Uint32Array(28);return crypto.getRandomValues(e),H(e.buffer)}class ir{constructor(){this.listeners={}}addEventListener(e,t){this.listeners[e]||(this.listeners[e]=[]),this.listeners[e].push(t)}removeEventListeneer(e,t){const n=this.listeners[e];if(n)for(let e=0;e<n.length;e++)if(n[e]===t)return void n.splice(e,1)}dispatchEvent(e){const t=this.listeners[e.type];return t&&t.forEach((t=>t.call(this,e))),!e.defaultPrevented}}function or(e){const[t,n,r]=e.split(".");return function(e){const t=Zn(e.replace(/-/g,"+").replace(/_/g,"/")),n=Array.from(t).reduce(((e,t)=>`${e}%${("00"+t.charCodeAt(0).toString(16)).slice(-2)}`),""),r=decodeURIComponent(n);return JSON.parse(r)}(n)}var sr;class ar{constructor(e){this[sr]="ReadablePromise",this.status="pending",this.suspender=e.then((e=>(this.status="success",this.response=e,e)),(e=>{throw this.status="error",this.error=e,e}))}isPending(){return"pending"===this.status}isOk(){return"success"===this.status}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)}}sr=Symbol.toStringTag;class cr{constructor(){this.storage="undefined"!=typeof localStorage?localStorage:new ur}clear(){this.storage.clear()}getString(e){return this.storage.getItem(e)||void 0}setString(e,t){t?this.storage.setItem(e,t):this.storage.removeItem(e)}getObject(e){const t=this.getString(e);return t?JSON.parse(t):void 0}setObject(e,t){this.setString(e,t?M(t):void 0)}}class ur{constructor(){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]}}const dr="2.0.24-8a2dc16",pr="application/fhir+json",lr={resourceType:"Device",id:"system",deviceName:[{name:"System"}]};var hr,fr;!function(e){e.ClientCredentials="client_credentials",e.AuthorizationCode="authorization_code",e.RefreshToken="refresh_token",e.TokenExchange="urn:ietf:params:oauth:grant-type:token-exchange"}(hr||(hr={})),function(e){e.AccessToken="urn:ietf:params:oauth:token-type:access_token",e.RefreshToken="urn:ietf:params:oauth:token-type:refresh_token",e.IdToken="urn:ietf:params:oauth:token-type:id_token",e.Saml1Token="urn:ietf:params:oauth:token-type:saml1",e.Saml2Token="urn:ietf:params:oauth:token-type:saml2"}(fr||(fr={}));class mr extends ir{constructor(e){if(super(),e?.baseUrl&&!e.baseUrl.startsWith("http"))throw new Error("Base URL must start with http or https");this.fetch=e?.fetch??function(){if(!globalThis.fetch)throw new Error("Fetch not available in this environment");return globalThis.fetch.bind(globalThis)}(),this.storage=e?.storage||new cr,this.createPdfImpl=e?.createPdf,this.baseUrl=gr(e?.baseUrl)||"https://api.medplum.com/",this.fhirBaseUrl=this.baseUrl+(gr(e?.fhirUrlPath)||"fhir/R4/"),this.clientId=e?.clientId||"",this.authorizeUrl=e?.authorizeUrl||this.baseUrl+"oauth2/authorize",this.tokenUrl=e?.tokenUrl||this.baseUrl+"oauth2/token",this.logoutUrl=e?.logoutUrl||this.baseUrl+"oauth2/logout",this.onUnauthenticated=e?.onUnauthenticated,this.cacheTime=e?.cacheTime??6e4,this.cacheTime>0?this.requestCache=new nr(e?.resourceCacheSize??1e3):this.requestCache=void 0,e?.autoBatchTime?(this.autoBatchTime=e.autoBatchTime??0,this.autoBatchQueue=[]):(this.autoBatchTime=0,this.autoBatchQueue=void 0);const t=this.getActiveLogin();t&&(this.accessToken=t.accessToken,this.refreshToken=t.refreshToken,this.refreshProfile().catch(console.log)),this.setupStorageListener()}getBaseUrl(){return this.baseUrl}getAuthorizeUrl(){return this.authorizeUrl}clear(){this.storage.clear(),this.clearActiveLogin()}clearActiveLogin(){this.basicAuth||(this.storage.setString("activeLogin",void 0),this.requestCache?.clear(),this.accessToken=void 0,this.refreshToken=void 0,this.sessionDetails=void 0,this.dispatchEvent({type:"change"}))}invalidateUrl(e){e=e.toString(),this.requestCache?.delete(e)}invalidateAll(){this.requestCache?.clear()}invalidateSearches(e){const t=this.fhirBaseUrl+e;if(this.requestCache)for(const e of this.requestCache.keys())(e.endsWith(t)||e.includes(t+"?"))&&this.requestCache.delete(e)}get(e,t={}){e=e.toString();const n=this.getCacheEntry(e,t);if(n)return n.value;let r;r=e.startsWith(this.fhirBaseUrl)&&this.autoBatchQueue?new Promise(((n,r)=>{this.autoBatchQueue.push({method:"GET",url:e.replace(this.fhirBaseUrl,""),options:t,resolve:n,reject:r}),this.autoBatchTimerId||(this.autoBatchTimerId=setTimeout((()=>this.executeAutoBatch()),this.autoBatchTime))})):this.request("GET",e,t);const i=new ar(r);return this.setCacheEntry(e,i),i}post(e,t,n,r={}){return e=e.toString(),t&&this.setRequestBody(r,t),n&&this.setRequestContentType(r,n),this.invalidateUrl(e),this.request("POST",e,r)}put(e,t,n,r={}){return e=e.toString(),t&&this.setRequestBody(r,t),n&&this.setRequestContentType(r,n),this.invalidateUrl(e),this.request("PUT",e,r)}patch(e,t,n={}){return e=e.toString(),this.setRequestBody(n,t),this.setRequestContentType(n,"application/json-patch+json"),this.invalidateUrl(e),this.request("PATCH",e,n)}delete(e,t){return e=e.toString(),this.invalidateUrl(e),this.request("DELETE",e,t)}async startNewUser(e,t){const{codeChallengeMethod:n,codeChallenge:r}=await this.startPkce();return this.post("auth/newuser",{...e,codeChallengeMethod:n,codeChallenge:r},void 0,t)}async startNewProject(e,t){return this.post("auth/newproject",e,void 0,t)}async startNewPatient(e,t){return this.post("auth/newpatient",e,void 0,t)}async startLogin(e,t){return this.post("auth/login",{...await this.ensureCodeChallenge(e),clientId:e.clientId??this.clientId,scope:e.scope},void 0,t)}async startGoogleLogin(e,t){return this.post("auth/google",{...await this.ensureCodeChallenge(e),clientId:e.clientId??this.clientId,scope:e.scope},void 0,t)}async ensureCodeChallenge(e){return e.codeChallenge?e:{...e,...await this.startPkce()}}async signOut(){await this.post(this.logoutUrl,{}),this.clear()}async signInWithRedirect(e){const t=new URLSearchParams(window.location.search).get("code");return t?this.processCode(t):void await this.requestAuthorization(e)}signOutWithRedirect(){window.location.assign(this.logoutUrl)}async signInWithExternalAuth(e,t,n,r){const i=await this.ensureCodeChallenge(r);window.location.assign(this.getExternalAuthRedirectUri(e,t,n,i))}async exchangeExternalAccessToken(e,t){if(!(t=t||this.clientId))throw new Error("MedplumClient is missing clientId");const n=new URLSearchParams;return n.set("grant_type",hr.TokenExchange),n.set("subject_token_type",fr.AccessToken),n.set("client_id",t),n.set("subject_token",e),this.fetchTokens(n)}getExternalAuthRedirectUri(e,t,n,r){const i=new URL(e);return i.searchParams.set("response_type","code"),i.searchParams.set("client_id",t),i.searchParams.set("redirect_uri",n),i.searchParams.set("scope","openid profile email"),i.searchParams.set("state",JSON.stringify(r)),i.toString()}fhirUrl(...e){return new URL(this.fhirBaseUrl+e.join("/"))}fhirSearchUrl(e,t){const n=this.fhirUrl(e);return t&&(n.search=new URLSearchParams(t).toString()),n}search(e,t,n){const r=this.fhirSearchUrl(e,t),i=r.toString()+"-search",o=this.getCacheEntry(i,n);if(o)return o.value;const s=new ar((async()=>{const e=await this.get(r,n);if(e.entry)for(const t of e.entry)this.cacheResource(t.resource);return e})());return this.setCacheEntry(i,s),s}searchOne(e,t,n){const r=this.fhirSearchUrl(e,t);r.searchParams.set("_count","1"),r.searchParams.sort();const i=r.toString()+"-searchOne",o=this.getCacheEntry(i,n);if(o)return o.value;const s=new ar(this.search(e,r.searchParams,n).then((e=>e.entry?.[0]?.resource)));return this.setCacheEntry(i,s),s}searchResources(e,t,n){const r=this.fhirSearchUrl(e,t).toString()+"-searchResources",i=this.getCacheEntry(r,n);if(i)return i.value;const o=new ar(this.search(e,t,n).then((e=>e.entry?.map((e=>e.resource))??[])));return this.setCacheEntry(r,o),o}async*searchResourcePages(e,t,n){let r=this.fhirSearchUrl(e,t);for(;r;){const t=new URL(r).searchParams,i=await this.search(e,t,n),o=i.link?.find((e=>"next"===e.relation));if(!i.entry?.length&&!o)break;yield i.entry?.map((e=>e.resource))??[],r=o?.url?new URL(o.url):void 0}}searchValueSet(e,t,n){const r=this.fhirUrl("ValueSet","$expand");return r.searchParams.set("url",e),r.searchParams.set("filter",t),this.get(r.toString(),n)}getCached(e,t){const n=this.requestCache?.get(this.fhirUrl(e,t).toString())?.value;return n?.isOk()?n.read():void 0}getCachedReference(e){const t=e.reference;if(!t)return;if("system"===t)return lr;const[n,r]=t.split("/");return n&&r?this.getCached(n,r):void 0}readResource(e,t,n){return this.get(this.fhirUrl(e,t),n)}readReference(e,t){const n=e.reference;if(!n)return new ar(Promise.reject(new Error("Missing reference")));if("system"===n)return new ar(Promise.resolve(lr));const[r,i]=n.split("/");return r&&i?this.readResource(r,i,t):new ar(Promise.reject(new Error("Invalid reference")))}getSchema(){return Ce}requestSchema(e){if(e in Ce.types)return Promise.resolve(Ce);const t=e+"-requestSchema",n=this.getCacheEntry(t,void 0);if(n)return n.value;const r=new ar((async()=>{const t=`{\n StructureDefinitionList(name: "${e}") {\n name,\n description,\n snapshot {\n element {\n id,\n path,\n min,\n max,\n type {\n code,\n targetProfile\n },\n binding {\n valueSet\n },\n definition\n }\n }\n }\n SearchParameterList(base: "${e}", _count: 100) {\n base,\n code,\n type,\n expression,\n target\n }\n }`.replace(/\s+/g," "),n=await this.graphql(t);for(const e of n.data.StructureDefinitionList)pe(e);for(const e of n.data.SearchParameterList)he(e);return Ce})());return this.setCacheEntry(t,r),r}readHistory(e,t,n){return this.get(this.fhirUrl(e,t,"_history"),n)}readVersion(e,t,n,r){return this.get(this.fhirUrl(e,t,"_history",n),r)}readPatientEverything(e,t){return this.get(this.fhirUrl("Patient",e,"$everything"),t)}createResource(e,t){if(!e.resourceType)throw new Error("Missing resourceType");return this.invalidateSearches(e.resourceType),this.post(this.fhirUrl(e.resourceType),e,void 0,t)}async createResourceIfNoneExist(e,t,n){return await this.searchOne(e.resourceType,t,n)??this.createResource(e,n)}createBinary(e,t,n,r){const i=this.fhirUrl("Binary");return t&&i.searchParams.set("_filename",t),r?this.uploadwithProgress(i,e,n,r):this.post(i,e,n)}uploadwithProgress(e,t,n,r){return new Promise(((i,o)=>{const s=new XMLHttpRequest;s.responseType="json",s.onabort=()=>o(new Error("Request aborted")),s.onerror=()=>o(new Error("Request error")),r&&(s.upload.onprogress=e=>r(e),s.upload.onload=e=>r(e)),s.onload=()=>{s.status>=200&&s.status<300?i(s.response):o(new Error(s.statusText))},s.open("POST",e),s.withCredentials=!0,s.setRequestHeader("Authorization","Bearer "+this.accessToken),s.setRequestHeader("Cache-Control","no-cache, no-store, max-age=0"),s.setRequestHeader("Content-Type",n),s.setRequestHeader("X-Medplum","extended"),s.send(t)}))}async createPdf(e,t,n,r){if(!this.createPdfImpl)throw new Error("PDF creation not enabled");const i=await this.createPdfImpl(e,n,r);return this.createBinary(i,t,"application/pdf")}createComment(e,t,n){const r=this.getProfile();let i,o;return"Encounter"===e.resourceType&&(i=S(e),o=e.subject),"ServiceRequest"===e.resourceType&&(i=e.encounter,o=e.subject),"Patient"===e.resourceType&&(o=S(e)),this.createResource({resourceType:"Communication",basedOn:[S(e)],encounter:i,subject:o,sender:r?S(r):void 0,sent:(new Date).toISOString(),payload:[{contentString:t}]},n)}async updateResource(e,t){if(!e.resourceType)throw new Error("Missing resourceType");if(!e.id)throw new Error("Missing id");this.invalidateSearches(e.resourceType);let n=await this.put(this.fhirUrl(e.resourceType,e.id),e,void 0,t);return n||(n=e),this.cacheResource(n),n}patchResource(e,t,n,r){return this.invalidateSearches(e),this.patch(this.fhirUrl(e,t),n,r)}deleteResource(e,t,n){return this.deleteCacheEntry(this.fhirUrl(e,t).toString()),this.invalidateSearches(e),this.delete(this.fhirUrl(e,t),n)}validateResource(e,t){return this.post(this.fhirUrl(e.resourceType,"$validate"),e,void 0,t)}executeBot(e,t,n,r){let i;if("string"==typeof e){const t=e;i=this.fhirUrl("Bot",t,"$execute")}else{const t=e;i=this.fhirUrl("Bot","$execute")+`?identifier=${t.system}|${t.value}`}return this.post(i,t,n,r)}executeBatch(e,t){return this.post(this.fhirBaseUrl.slice(0,-1),e,void 0,t)}sendEmail(e,t){return this.post("email/v1/send",e,"application/json",t)}graphql(e,t,n,r){return this.post(this.fhirUrl("$graphql"),{query:e,operationName:t,variables:n},"application/json",r)}readResourceGraph(e,t,n,r){return this.get(`${this.fhirUrl(e,t)}/$graph?graph=${n}`,r)}getActiveLogin(){return this.storage.getObject("activeLogin")}async setActiveLogin(e){this.clearActiveLogin(),this.accessToken=e.accessToken,this.basicAuth||(this.refreshToken=e.refreshToken,this.storage.setObject("activeLogin",e),this.addLogin(e),this.refreshPromise=void 0,await this.refreshProfile())}getAccessToken(){return this.accessToken}setAccessToken(e){this.accessToken=e,this.refreshToken=void 0,this.sessionDetails=void 0}getLogins(){return this.storage.getObject("logins")??[]}addLogin(e){const t=this.getLogins().filter((t=>t.profile?.reference!==e.profile?.reference));t.push(e),this.storage.setObject("logins",t)}async refreshProfile(){return this.profilePromise=new Promise(((e,t)=>{this.basicAuth||this.get("auth/me").then((t=>{this.profilePromise=void 0,this.sessionDetails=t,this.dispatchEvent({type:"change"}),e(t.profile)})).catch(t)})),this.profilePromise}isLoading(){return!!this.profilePromise}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&&await this.profilePromise,this.getProfile()}getUserConfiguration(){return this.sessionDetails?.config}getAccessPolicy(){return this.sessionDetails?.accessPolicy}async download(e,t={}){this.refreshPromise&&await this.refreshPromise,this.addFetchOptionsDefaults(t);return(await this.fetch(e.toString(),t)).blob()}async uploadMedia(e,t,n,r,i){const o=await this.createBinary(e,n,t);return this.createResource({...r,resourceType:"Media",content:{contentType:t,url:"Binary/"+o.id,title:n}},i)}async bulkExport(e="",t,n,r){const i=e?`${e}/`:e,o=this.fhirUrl(`${i}$export`);return t&&o.searchParams.set("_type",t),n&&o.searchParams.set("_since",n),this.startAsyncRequest(o.toString(),r)}async startAsyncRequest(e,t={}){this.addFetchOptionsDefaults(t);t.headers.Prefer="respond-async";const n=await this.fetchWithRetry(e,t);if(202===n.status){const e=n.headers.get("content-location");if(e)return this.pollStatus(e);const t=await n.json();if(Ve(t)&&t.issue?.[0]?.diagnostics)return this.pollStatus(t.issue[0].diagnostics)}return this.parseResponse(n,"POST",e)}getCacheEntry(e,t){if(!this.requestCache||"no-cache"===t?.cache||"reload"===t?.cache)return;const n=this.requestCache.get(e);return!n||n.requestTime+this.cacheTime<Date.now()?void 0:n}setCacheEntry(e,t){this.requestCache&&this.requestCache.set(e,{requestTime:Date.now(),value:t})}cacheResource(e){e?.id&&this.setCacheEntry(this.fhirUrl(e.resourceType,e.id).toString(),new ar(Promise.resolve(e)))}deleteCacheEntry(e){this.requestCache&&this.requestCache.delete(e)}async request(e,t,n={}){this.refreshPromise&&await this.refreshPromise,n.method=e,this.addFetchOptionsDefaults(n);const r=await this.fetchWithRetry(t,n);return this.parseResponse(r,e,t,n)}async parseResponse(e,t,n,r={}){if(401===e.status)return this.handleUnauthenticated(t,n,r);if(204===e.status||304===e.status)return;if(404===e.status){const t=e.headers.get("content-type");if(!t?.includes("application/fhir+json"))throw new tt($e)}let i;try{i=await e.json()}catch(t){throw console.error("Error parsing response",e.status,t),t}if(e.status>=400)throw new tt(nt(i));return i}async fetchWithRetry(e,t){e.startsWith("http")||(e=this.baseUrl+e);let n;for(let r=0;r<3;r++){try{if(n=await this.fetch(e,t),n.status<500)return n}catch(e){this.retryCatch(r,3,e)}await new Promise((e=>{setTimeout(e,200)}))}return n}async pollStatus(e){let t,n=!0;for(;n;){const r={};this.addFetchOptionsDefaults(r);const i=await this.fetchWithRetry(e,r);202!==i.status&&(n=!1,t=i),await new Promise((e=>{setTimeout(e,2e3)}))}return this.parseResponse(t,"POST",e)}async executeAutoBatch(){const e=[...this.autoBatchQueue];if(this.autoBatchQueue.length=0,this.autoBatchTimerId=void 0,1===e.length){const t=e[0];try{t.resolve(await this.request(t.method,this.fhirBaseUrl+t.url,t.options))}catch(e){t.reject(new tt(nt(e)))}return}const t={resourceType:"Bundle",type:"batch",entry:e.map((e=>({request:{method:e.method,url:e.url},resource:e.options.body?JSON.parse(e.options.body):void 0})))},n=await this.post(this.fhirBaseUrl.slice(0,-1),t);for(let t=0;t<e.length;t++){const r=e[t],i=n.entry?.[t];i?.response?.outcome&&!Je(i.response.outcome)?r.reject(new tt(i.response.outcome)):r.resolve(i?.resource)}}addFetchOptionsDefaults(e){let t=e.headers;t||(t={},e.headers=t),t.Accept=pr,t["X-Medplum"]="extended",e.body&&!t["Content-Type"]&&(t["Content-Type"]=pr),this.accessToken?t.Authorization="Bearer "+this.accessToken:this.basicAuth&&(t.Authorization="Basic "+this.basicAuth),e.cache||(e.cache="no-cache"),e.credentials||(e.credentials="include")}setRequestContentType(e,t){e.headers||(e.headers={});e.headers["Content-Type"]=t}setRequestBody(e,t){"string"==typeof t||"undefined"!=typeof Blob&&t instanceof Blob||"undefined"!=typeof File&&t instanceof File||"undefined"!=typeof Uint8Array&&t instanceof Uint8Array?e.body=t:t&&(e.body=JSON.stringify(t))}handleUnauthenticated(e,t,n){return this.refresh()?this.request(e,t,n):(this.clearActiveLogin(),this.onUnauthenticated&&this.onUnauthenticated(),Promise.reject(new Error("Unauthenticated")))}async startPkce(){const e=rr();sessionStorage.setItem("pkceState",e);const t=rr();sessionStorage.setItem("codeVerifier",t);const n=z(await async function(e){return crypto.subtle.digest("SHA-256",(new TextEncoder).encode(e))}(t)).replaceAll("+","-").replaceAll("/","_").replaceAll("=","");return sessionStorage.setItem("codeChallenge",n),{codeChallengeMethod:"S256",codeChallenge:n}}async requestAuthorization(e){const t=await this.ensureCodeChallenge(e||{}),n=new URL(this.authorizeUrl);n.searchParams.set("response_type","code"),n.searchParams.set("state",sessionStorage.getItem("pkceState")),n.searchParams.set("client_id",t.clientId||this.clientId),n.searchParams.set("redirect_uri",t.redirectUri||yr()),n.searchParams.set("code_challenge_method",t.codeChallengeMethod),n.searchParams.set("code_challenge",t.codeChallenge),n.searchParams.set("scope",t.scope||"openid profile"),window.location.assign(n.toString())}processCode(e,t){const n=new URLSearchParams;if(n.set("grant_type",hr.AuthorizationCode),n.set("code",e),n.set("client_id",t?.clientId||this.clientId),n.set("redirect_uri",t?.redirectUri||yr()),"undefined"!=typeof sessionStorage){const e=sessionStorage.getItem("codeVerifier");e&&n.set("code_verifier",e)}return this.fetchTokens(n)}refresh(){if(this.refreshPromise)return this.refreshPromise;if(this.refreshToken){const e=new URLSearchParams;return e.set("grant_type",hr.RefreshToken),e.set("client_id",this.clientId),e.set("refresh_token",this.refreshToken),this.refreshPromise=this.fetchTokens(e),this.refreshPromise}return this.clientId&&this.clientSecret?(this.refreshPromise=this.startClientLogin(this.clientId,this.clientSecret),this.refreshPromise):void 0}async startClientLogin(e,t){this.clientId=e,this.clientSecret=t;const n=new URLSearchParams;return n.set("grant_type",hr.ClientCredentials),n.set("client_id",e),n.set("client_secret",t),this.fetchTokens(n)}setBasicAuth(e,t){this.clientId=e,this.clientSecret=t,this.basicAuth=Kn(e+":"+t)}async invite(e,t){return this.post("admin/projects/"+e+"/invite",t)}async fetchTokens(e){const t={method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:e,credentials:"include"},n=t.headers;this.basicAuth&&(n.Authorization=`Basic ${this.basicAuth}`);const r=await this.fetch(this.tokenUrl,t);if(!r.ok){this.clearActiveLogin();try{const e=await r.json();throw new tt(He(e.error_description))}catch(e){throw new tt(He("Failed to fetch tokens"),e)}}const i=await r.json();return await this.verifyTokens(i),this.getProfile()}async verifyTokens(e){const t=e.access_token,n=or(t);if(Date.now()>=1e3*n.exp)throw this.clearActiveLogin(),new Error("Token expired");if(n.cid){if(n.cid!==this.clientId)throw this.clearActiveLogin(),new Error("Token was not issued for this audience")}else if(this.clientId&&n.client_id!==this.clientId)throw this.clearActiveLogin(),new Error("Token was not issued for this audience");return this.setActiveLogin({accessToken:t,refreshToken:e.refresh_token,project:e.project,profile:e.profile})}setupStorageListener(){try{window.addEventListener("storage",(e=>{null!==e.key&&"activeLogin"!==e.key||window.location.reload()}))}catch(e){}}retryCatch(e,t,n){if("Failed to fetch"===n.message&&1===e&&this.dispatchEvent({type:"offline"}),e>=t-1)throw n}}function yr(){return"undefined"==typeof window?"":window.location.protocol+"//"+window.location.host+"/"}function gr(e){return e?e.endsWith("/")?e:e+"/":e}const vr=[...Sn,"->","<<",">>"];class xr{constructor(e){this.parser=e,this.structureMap={resourceType:"StructureMap"}}parse(){for(this.parser.consume("Symbol","map"),this.structureMap.url=this.parser.consume("String").value,this.parser.consume("="),this.structureMap.name=this.parser.consume().value;this.parser.hasMore();){const e=this.parser.peek()?.value;switch(e){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}parseUses(){this.parser.consume("Symbol","uses");const e={};e.url=this.parser.consume("String").value,"alias"===this.parser.peek()?.value&&(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(){const e={};this.parser.consume("Symbol","group"),e.name=this.parser.consume("Symbol").value,e.input=this.parseParameters(),"extends"===this.parser.peek()?.value&&(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(){const 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(){const 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(){const e=[];for(this.parser.consume("{");this.parser.hasMore()&&"}"!==this.parser.peek()?.value;)e.push(this.parseRule());return this.parser.consume("}"),e}parseRule(){const e={source:this.parseRuleSources()};return"->"===this.parser.peek()?.value&&(this.parser.consume("->"),e.target=this.parseRuleTargets()),"then"===this.parser.peek()?.value&&(this.parser.consume("Symbol","then"),"{"===this.parser.peek()?.id?e.rule=this.parseRules():e.dependent=this.parseRuleDependents()),"String"===this.parser.peek()?.id?e.name=this.parser.consume().value:e.name=e.source?.[0]?.element,this.parser.consume(";"),e}parseRuleSources(){const e=[this.parseRuleSource()];for(;this.parser.hasMore()&&","===this.parser.peek()?.value;)this.parser.consume(","),e.push(this.parseRuleSource());return e}parseRuleSource(){const e={},t=this.parseRuleContext();if(t.includes(".")){const n=t.split(".");e.context=n[0],e.element=n[1]}else e.context=t;if(this.parser.hasMore()&&":"===this.parser.peek()?.value&&(this.parser.consume(":"),e.type=this.parser.consume().value),this.parser.hasMore()&&"default"===this.parser.peek()?.value&&(this.parser.consume("default"),this.parser.consumeAndParse()),"first"!==this.parser.peek()?.value&&"not_first"!==this.parser.peek()?.value&&"last"!==this.parser.peek()?.value&&"not_last"!==this.parser.peek()?.value&&"only_one"!==this.parser.peek()?.value||(e.listMode=this.parser.consume().value),"as"===this.parser.peek()?.value&&(this.parser.consume("Symbol","as"),e.variable=this.parser.consume().value),"where"===this.parser.peek()?.value){this.parser.consume("Symbol","where");const t=this.parser.consumeAndParse(100);e.condition=t.toString()}if("check"===this.parser.peek()?.value){this.parser.consume("Symbol","check");const t=this.parser.consumeAndParse(100);e.check=t.toString()}return e}parseRuleTargets(){const e=[this.parseRuleTarget()];for(;this.parser.hasMore()&&","===this.parser.peek()?.value;)this.parser.consume(","),e.push(this.parseRuleTarget());return e}parseRuleTarget(){const e={},t=this.parseRuleContext();if(t.includes(".")){const n=t.split(".");e.contextType="variable",e.context=n[0],e.element=n[1]}else e.context=t;return"="===this.parser.peek()?.value&&(this.parser.consume("="),this.parseRuleTargetTransform(e)),"as"===this.parser.peek()?.value&&(this.parser.consume("Symbol","as"),e.variable=this.parser.consume().value),"first"!==this.parser.peek()?.value&&"share"!==this.parser.peek()?.value&&"last"!==this.parser.peek()?.value&&"collate"!==this.parser.peek()?.value||(e.listMode=[this.parser.consume().value]),e}parseRuleTargetTransform(e){e.transform="copy";const t=this.parser.consumeAndParse(6);if(t instanceof Kt)this.parseRuleTargetSymbol(e,t);else if(t instanceof vn)this.parseRuleTargetFunction(e,t);else{if(!(t instanceof Zt))throw new Error(`Unexpected FHIRPath: ${t}`);this.parseRuleTargetLiteral(e,t)}}parseRuleTargetSymbol(e,t){e.parameter=[{valueId:t.name}]}parseRuleTargetFunction(e,t){const n=t.name;switch(n){case"create":e.parameter=[{valueString:t.args[0].value.value}];break;case"translate":e.parameter=[{}];break;default:throw new Error("Unknown target function: "+n)}}parseRuleTargetLiteral(e,t){switch(t.value.type){case"boolean":e.parameter=[{valueBoolean:t.value.value}];break;case"decimal":e.parameter=[{valueDecimal:t.value.value}];break;case"string":e.parameter=[{valueString:t.value.value}];break;default:throw new Error("Unknown target literal type: "+t.value.type)}}parseRuleContext(){let e=this.parser.consume().value;for(;"."===this.parser.peek()?.value;)this.parser.consume("."),e+="."+this.parser.consume().value;return e}parseRuleDependents(){const e=this.parser.consumeAndParse(100);return[{name:e.name,variable:e.args.map((e=>e.name))}]}parseConceptMap(){for(;"}"!==this.parser.peek()?.value;)this.parser.consume();this.parser.consume("}")}}const br=Pn().registerInfix("->",{precedence:100}).registerInfix(";",{precedence:200});function Sr(e){const t=br.construct(new Ct(e,bn,vr).tokenize());return t.removeComments(),new xr(t).parse()}const wr=[...Sn,"eq","ne","co"];class Tr{constructor(e,t,n){this.path=e,this.operator=t,this.value=n}}class Er{constructor(e){this.child=e}}class kr{constructor(e,t,n){this.keyword=e,this.left=t,this.right=n}}const Cr={eq:at.EQUALS,ne:at.NOT_EQUALS,co:at.CONTAINS,sw:void 0,ew:void 0,gt:at.GREATER_THAN,lt:at.LESS_THAN,ge:at.GREATER_THAN_OR_EQUALS,le:at.LESS_THAN_OR_EQUALS,ap:at.APPROXIMATELY,sa:at.STARTS_AFTER,eb:at.ENDS_BEFORE,pr:at.MISSING,po:void 0,ss:void 0,sb:void 0,in:at.IN,ni:at.NOT_IN,re:void 0,identifier:at.IDENTIFIER};class Pr{constructor(e){this.parser=e}parse(){let e;"("===this.parser.peek()?.value?(this.parser.consume("("),e=this.parse(),this.parser.consume(")")):"not"===this.parser.peek()?.value?(this.parser.consume("Symbol","not"),this.parser.consume("("),e=new Er(this.parse()),this.parser.consume(")")):e=new Tr(this.parser.consume("Symbol").value,function(e){const t=Cr[e];if(!t)throw new tt(He("Invalid operator: "+e));return t}(this.parser.consume("Symbol").value),this.parser.consume().value);const t=this.parser.peek()?.value;return"and"===t||"or"===t?(this.parser.consume("Symbol",t),new kr(t,e,this.parse())):e}}const Ar=Pn();function Dr(e){const t=Ar.construct(new Ct(e,bn,wr,{dateTimeLiterals:!0,symbolRegex:/[^\s\])]/}).tokenize());return t.removeComments(),new Pr(t).parse()}class Rr{constructor(e="\r",t="|",n="^",r="~",i="\\",o="&"){this.segmentSeparator=e,this.fieldSeparator=t,this.componentSeparator=n,this.repetitionSeparator=r,this.escapeCharacter=i,this.subcomponentSeparator=o}getMsh2(){return this.fieldSeparator+this.componentSeparator+this.repetitionSeparator+this.escapeCharacter+this.subcomponentSeparator}}class Ir{constructor(e,t=new Rr){this.context=t,this.segments=e}get(e){return"number"==typeof e?this.segments[e]:this.segments.find((t=>t.name===e))}getAll(e){return this.segments.filter((t=>t.name===e))}toString(){return this.segments.map((e=>e.toString())).join(this.context.segmentSeparator)}buildAck(){const e=new Date,t=this.get("MSH"),n=t?.get(2)?.toString()||"",r=t?.get(3)?.toString()||"",i=t?.get(4)?.toString()||"",o=t?.get(5)?.toString()||"",s=t?.get(9)?.toString()||"",a=t?.get(12)?.toString()||"2.5.1";return new Ir([new Ur(["MSH",this.context.getMsh2(),i,o,n,r,e.toISOString(),"","ACK",e.getTime().toString(),"P",a],this.context),new Ur(["MSA","AA",s,"OK"],this.context)])}static parse(e){if(!e.startsWith("MSH")){const e=new Error("Invalid HL7 message");throw e.type="entity.parse.failed",e}const t=new Rr("\r",e.charAt(3),e.charAt(4),e.charAt(5),e.charAt(6),e.charAt(7));return new Ir(e.split(/[\r\n]+/).map((e=>Ur.parse(e,t))),t)}}class Ur{constructor(e,t=new Rr){this.context=t,F(e)?this.fields=e.map((e=>Or.parse(e))):this.fields=e,this.name=this.fields[0].components[0][0]}get(e){return this.fields[e]}toString(){return this.fields.map((e=>e.toString())).join(this.context.fieldSeparator)}static parse(e,t=new Rr){return new Ur(e.split(t.fieldSeparator).map((e=>Or.parse(e,t))),t)}}class Or{constructor(e,t=new Rr){this.context=t,this.components=e}get(e,t,n=0){let r=this.components[n][e]||"";return void 0!==t&&(r=r.split(this.context.subcomponentSeparator)[t]||""),r}toString(){return this.components.map((e=>e.join(this.context.componentSeparator))).join(this.context.repetitionSeparator)}static parse(e,t=new Rr){return new Or(e.split(t.repetitionSeparator).map((e=>e.split(t.componentSeparator))),t)}}function Lr(e,t){if(!e)return;t={seconds:!0,tzOffset:"Z",...t};const n=Number.parseInt(e.substring(0,4),10),r=Number.parseInt(e.substring(4,6),10),i=Number.parseInt(e.substring(6,8),10),o=Number.parseInt(e.substring(8,10),10),s=Number.parseInt(e.substring(10,12),10),a=t.seconds?Number.parseInt(e.substring(12,14),10):0;return`${Nr(n)}-${Nr(r)}-${Nr(i)}T${Nr(o)}:${Nr(s)}:${Nr(a)}.000${t.tzOffset}`}function Nr(e){return e.toString().padStart(2,"0")}const Mr={base64Binary:"string",boolean:"boolean",canonical:"string",code:"string",date:"string",dateTime:"string",decimal:"number",id:"string",instant:"string",integer:"number",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"},_r=new Set(["resourceType","id","meta","implicitRules","language","text","contained","extension","modifierExtension"]);function jr(e){const t=Ce.types[e];return t&&t.structureDefinition.id===e&&"resource"===t.structureDefinition.kind}function $r(e){if(!e)throw new tt(ze("Resource type is null"));if(!jr(e))throw new tt(ze("Unknown resource type"))}function Br(e){new qr(e).validate()}class qr{constructor(e){this.issues=[],this.root=e}validate(){const e=this.root;if(!e)throw new tt(ze("Resource is null"));const t=e.resourceType;if(!t)throw new tt(ze("Missing resource type"));if(Qr(e,"",this.issues),this.validateObject(Dt(e),t),this.issues.length>0)throw new tt({resourceType:"OperationOutcome",issue:this.issues})}validateObject(e,t){const n=Ce.types[e.type];if(!n)throw new tt(ze("Unknown type: "+e.type));const r=n.properties;this.checkProperties(t,r,e),this.checkAdditionalProperties(t,e,r)}checkProperties(e,t,n){for(const[r,i]of Object.entries(t))this.checkProperty(e+"."+r,i,n)}checkProperty(e,t,n){const r=It(n,e.split(".").pop());if(j(r))void 0!==t.min&&t.min>0&&this.issues.push(Fr(e,"Missing required property"));else if("*"===t.max){if(!Array.isArray(r))return void this.issues.push(Fr(e,"Expected array for property"));for(const n of r)this.checkPropertyValue(e,t,n)}else{if(Array.isArray(r))return void this.issues.push(Fr(e,"Expected single value for property"));this.checkPropertyValue(e,t,r)}}checkPropertyValue(e,t,n){null!==n.value&&(V(n.type.charAt(0))?this.validatePrimitiveType(t,n):this.validateObject(n,e))}validatePrimitiveType(e,t){const{type:n,value:r}=t;if(null===r)return;const i=Mr[t.type];typeof r===i?"string"===i?this.validateString(e,n,r):"number"===i&&this.validateNumber(e,n,r):this.createIssue(e,"Invalid type for "+n)}validateString(e,t,n){if(!n.trim())return void this.createIssue(e,"Invalid empty string");const r=Ce.types[t]?.properties.value;if(r?.type){const i=L(r.type[0],"http://hl7.org/fhir/StructureDefinition/regex");i&&(n.match(new RegExp(i))||this.createIssue(e,"Invalid "+t+" format"))}}validateNumber(e,t,n){var r;!isNaN(n)&&isFinite(n)?((r=t)!==ue.integer&&r!==ue.positiveInt&&r!==ue.unsignedInt||Number.isInteger(n)||this.createIssue(e,"Number is not an integer"),t===ue.positiveInt&&n<=0&&this.createIssue(e,"Number is less than or equal to zero"),t===ue.unsignedInt&&n<0&&this.createIssue(e,"Number is negative")):this.createIssue(e,"Invalid "+t+" value")}checkAdditionalProperties(e,t,n){const r=t.value;for(const i of Object.keys(r))this.checkAdditionalProperty(e,i,t,n)}checkAdditionalProperty(e,t,n,r){if(!(_r.has(t)||t in r||function(e,t,n){for(const r of Object.keys(n)){if(!r.endsWith("[x]"))continue;const n=r.replace("[x]","");if(!e.startsWith(n))continue;let i=It(t,r);if(i&&(Array.isArray(i)&&(i=i[0]),i&&e===n+G(i.type)))return!0}return!1}(t,n,r)||this.checkPrimitiveElement(e,t,n))){const n=`${e}.${t}`;this.issues.push(Fr(n,`Invalid additional property "${n}"`))}}checkPrimitiveElement(e,t,n){if(!t.startsWith("_"))return!1;return t.slice(1)in n.value&&(this.validateObject({type:"Element",value:n.value[t]},e),!0)}createIssue(e,t){this.issues.push(Fr(e.path,t))}}function Qr(e,t,n){null===e?n.push(Fr(t,"Invalid null value")):Array.isArray(e)?function(e,t,n){for(let r=0;r<e.length;r++)void 0===e[r]?n.push(Fr(`${t}[${r}]`,"Invalid undefined value")):Qr(e[r],`${t}[${r}]`,n)}(e,t,n):"object"==typeof e&&function(e,t,n){for(const[r,i]of Object.entries(e))Qr(i,`${t}${t?".":""}${r}`,n)}(e,t,n)}function Fr(e,t){return{severity:"error",code:"structure",details:{text:t},expression:[e]}}function Wr(e){const t=[];return new Promise(((n,r)=>{e.on("data",(e=>t.push(Buffer.from(e)))),e.on("error",(t=>{e.destroy(),r(t)})),e.on("end",(()=>{n(Buffer.concat(t))})),e.on("close",(()=>{e.destroy()}))}))}function Hr(e){return new Jr(e).parse()}const zr=Object.create(null);function Gr(e){for(const{resource:t}of e.entry??[]){if(!t?.name)throw new Error("Failed loading StructureDefinition from bundle");if("StructureDefinition"!==t.resourceType)continue;const e=Hr(t);zr[t.name]=e;for(const t of e.innerTypes)zr[t.name]=t}}function Vr(e){const t=zr[e];if(!t)throw new tt(Ge(Error("Unknown data type: "+e)));return t}class Jr{constructor(e){if(!e.snapshot?.element||0===e.snapshot.element.length)throw new Error(`No snapshot defined for StructureDefinition '${e.name}'`);const t=e.snapshot.element[0];this.elements=e.snapshot.element.slice(1),this.elementIndex=Object.create(null),this.index=0,this.resourceSchema={name:e.type,fields:{},constraints:this.parseFieldDefinition(t).constraints,innerTypes:[]},this.innerTypes=[]}parse(){let e=this.next();for(;e;){if(e.sliceName)this.parseSliceStart(e);else if(e.id?.includes(":")){if(this.slicingContext?.current){const t=Yr(e,this.slicingContext.path);this.slicingContext.current.fields[t]=this.parseFieldDefinition(e)}}else{const t=this.parseFieldDefinition(e);this.checkFieldEnter(e,t),this.backboneContext&&e.path?.startsWith(this.backboneContext.path+".")?this.backboneContext.type.fields[Yr(e,this.backboneContext.path)]=t:this.backboneContext?.parent&&e.path?.startsWith(this.backboneContext.parent.path+".")?this.backboneContext.parent.type.fields[Yr(e,this.backboneContext.parent.path)]=t:this.resourceSchema.fields[Yr(e,this.resourceSchema.name)]=t,this.checkFieldExit(e)}e=this.next()}return this.checkFieldExit(),this.innerTypes.length>0&&(this.resourceSchema.innerTypes=this.innerTypes),this.resourceSchema}checkFieldEnter(e,t){if(this.isInnerType(e)){for(;this.backboneContext&&!Zr(this.backboneContext?.path,e.path);)this.innerTypes.push(this.backboneContext.type),this.backboneContext=this.backboneContext.parent;this.backboneContext={type:{name:Kr(e.path?.split(".")??[]),fields:{},constraints:this.parseFieldDefinition(e).constraints,innerTypes:[]},path:e.path??"",parent:Zr(this.backboneContext?.path,e.path)?this.backboneContext:this.backboneContext?.parent}}e.slicing&&!this.slicingContext&&(t.slicing={discriminator:(e.slicing?.discriminator??[]).map((e=>({path:e.path,type:e.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&&!Zr(this.backboneContext.path,e?.path))if(this.backboneContext.parent)do{this.innerTypes.push(this.backboneContext.type),this.backboneContext=this.backboneContext.parent}while(this.backboneContext&&!Zr(this.backboneContext.path,e?.path));else this.innerTypes.push(this.backboneContext.type),delete this.backboneContext;this.slicingContext&&!Zr(this.slicingContext.path,e?.path)&&(this.slicingContext?.current&&this.slicingContext.field.slices.push(this.slicingContext.current),delete this.slicingContext)}next(){const e=this.peek();if(e)return this.index++,e}peek(){const e=this.elements[this.index];if(e){if(this.elementIndex[e.path??""]=e,e.contentReference){const t=this.elementIndex[e.contentReference.slice(e.contentReference.indexOf("#")+1)];if(!t)return;return{...t,id:e.id,path:e.path}}return e}}isInnerType(e){const t=this.peek();return!(!Zr(e?.path,t?.path)||!e.type?.some((e=>["BackboneElement","Element"].includes(e.code))))}parseSliceStart(e){if(!this.slicingContext)throw new Error("Invalid slice start before discriminator");this.slicingContext.current&&this.slicingContext.field.slices.push(this.slicingContext.current),this.slicingContext.current={name:e.sliceName??"",fields:{},min:e.min??0,max:"*"===e.max?Number.POSITIVE_INFINITY:Number.parseInt(e.max,10)}}parseFieldDefinition(e){const t=Xr(e.max),n=e.base?.max?Xr(e.base.max):t,r={type:"ElementDefinition",value:e};return{min:e.min??0,max:t,isArray:n>1,constraints:(e.constraint??[]).map((e=>({key:e.key??"",severity:e.severity??"error",expression:e.expression??"",description:e.human??""}))),type:(e.type??[]).map((t=>({code:["BackboneElement","Element"].includes(t.code)?Kr(e.base?.path?.split(".")??[]):t.code??"",targetProfile:t.targetProfile??[]}))),fixed:ei(It(r,"fixed")),pattern:ei(It(r,"pattern")),binding:"required"===e.binding?.strength?e.binding.valueSet:void 0}}}function Xr(e){return"*"===e?Number.POSITIVE_INFINITY:Number.parseInt(e,10)}function Yr(e,t=""){return function(e,t){if(!e)return"";if(t&&e.startsWith(t))return e.substring(t.length+1);return e}(e.path,t)}function Zr(e,t){return!(!e||!t)&&(t.startsWith(e+".")||t===e)}function Kr(e){return 1===e.length?e[0]:e.map(G).join("")}function ei(e){return Array.isArray(e)&&e.length>0?e[0]:j(e)?void 0:e}const ti={base64Binary:"string",boolean:"boolean",canonical:"string",code:"string",date:"string",dateTime:"string",decimal:"number",id:"string",instant:"string",integer:"number",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"},ni={base64Binary:/^([A-Za-z\d+/]{4})*([A-Za-z\d+/]{2}==|[A-Za-z\d+/]{3}=)?$/,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:/^[\s\S]+$/,oid:/^urn:oid:[0-2](\.(0|[1-9]\d*))+$/,string:/^[\s\S]+$/,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:/.*/};function ri(e,t){return new ii(e.resourceType,t).validate(e)}class ii{constructor(e,t){this.issues=[],this.schema=t?Hr(t):Vr(e)}validate(e){if(!e)throw new tt(ze("Resource is null"));const t=e.resourceType;if(!t)throw new tt(ze("Missing resource type"));this.validateObject({type:t,value:e},this.schema,t);const n=this.issues;if(this.issues=[],n.length>0)throw new tt({resourceType:"OperationOutcome",issue:n})}validateObject(e,t,n){for(const[r,i]of Object.entries(t.fields))this.checkProperty(e,r,t,n+"."+r);this.checkAdditionalProperties(e,t.fields,n)}checkProperty(e,t,n,r){const i=function(e,t){const[n,...r]=t.split(".");let i=[It(e,n)];for(const e of r){const t=[];for(const n of i)if(void 0!==n)if(Array.isArray(n))for(const r of n)t.push(It(r,e));else t.push(It(n,e));i=t}return i}(e,t),o=n.fields[t];if(!o)throw new Error(`Missing element validation schema for ${t}`);for(const e of i){if(j(e))return void(o.min>0&&this.issues.push(Fr(r,"Missing required property")));let t;if(o.isArray){if(!Array.isArray(e))return void this.issues.push(Fr(r,"Expected array of values"));t=e}else{if(Array.isArray(e))return void this.issues.push(Fr(r,"Expected single value"));t=[e]}for(const e of t)this.checkPropertyValue(e,r)}}checkPropertyValue(e,t){if(V(e.type.charAt(0)))this.validatePrimitiveType(e,t);else{const n=Vr(e.type);this.validateObject(e,n,t)}}checkAdditionalProperties(e,t,n){const r=e.value;for(const i of Object.keys(r))"resourceType"!==i&&(i in t||oi(e,i,t)||this.isPrimitiveExtension(e,i,n)||this.issues.push(Fr(`${n}.${i}`,`Invalid additional property "${i}"`)))}isPrimitiveExtension(e,t,n){return!!t.startsWith("_")&&(this.validateObject({type:"Element",value:e.value[t]},Vr("Element"),n),!0)}validatePrimitiveType(e,t){const{type:n,value:r}=e,i=ti[n];typeof r===i?"string"===i?this.validateString(r,n,t):"number"===i&&this.validateNumber(r,n,t):this.issues.push(Fr(t,`Invalid JSON type at ${t}: expected ${i}, but got ${typeof r}`))}validateString(e,t,n){if(!e.trim())return void this.issues.push(Fr(n,"String must contain non-whitespace content"));const r=ni[t];r&&!r.exec(e)&&this.issues.push(Fr(n,"Invalid "+t+" format"))}validateNumber(e,t,n){var r;isNaN(e)||!isFinite(e)?this.issues.push(Fr(n,"Invalid numeric value")):(r=t)!==ue.integer&&r!==ue.positiveInt&&r!==ue.unsignedInt||Number.isInteger(e)?t===ue.positiveInt&&e<=0?this.issues.push(Fr(n,"Expected number to be positive")):t===ue.unsignedInt&&e<0&&this.issues.push(Fr(n,"Expected number to be non-negative")):this.issues.push(Fr(n,"Expected number to be an integer"))}}function oi(e,t,n){const r=t.split(/(?=[A-Z])/g);let i="";for(const t of r){if(i+=t,!n[i+"[x]"])continue;return!!It(e,i)}return!1}export{mn as AndAtom,rn as ArithemticOperatorAtom,nn as AsAtom,cr as ClientStorage,on as ConcatAtom,sn as ContainsAtom,st as DEFAULT_SEARCH_COUNT,cn as DotAtom,en as EmptySetAtom,dn as EqualsAtom,ln as EquivalentAtom,bn as FHIRPATH_KEYWORDS,Sn as FHIRPATH_OPERATORS,Tr as FhirFilterComparison,kr as FhirFilterConnective,Er as FhirFilterNegation,Yt as FhirPathAtom,qr as FhirSchemaValidator,vn as FunctionAtom,Rr as Hl7Context,Or as Hl7Field,Ir as Hl7Message,Ur as Hl7Segment,an as InAtom,xn as IndexerAtom,wt as InfixOperatorAtom,fn as IsAtom,nr as LRUCache,Zt as LiteralAtom,dr as MEDPLUM_VERSION,mr as MedplumClient,ur as MemoryStorage,pn as NotEqualsAtom,hn as NotEquivalentAtom,hr as OAuthGrantType,fr as OAuthTokenType,tt as OperationOutcomeError,at as Operator,yn as OrAtom,Et as Parser,Tt as ParserBuilder,St as PrefixOperatorAtom,ue as PropertyType,ar as ReadablePromise,Un as SearchParameterType,Kt as SymbolAtom,Ct as Tokenizer,tn as UnaryOperatorAtom,un as UnionAtom,gn as XorAtom,We as accepted,Me as allOk,z as arrayBufferToBase64,H as arrayBufferToHex,et as assertOk,He as badRequest,At as booleanToTypedValue,me as buildTypeName,D as calculateAge,R as calculateAgeString,zn as canReadResourceType,Vn as canWriteResource,Gn as canWriteResourceType,G as capitalize,Qr as checkForNull,er as convertToTransactionBundle,S as createReference,Fr as createStructureIssue,_e as created,Zn as decodeBase64,B as deepClone,$ as deepEquals,Kn as encodeBase64,Rn as evalFhirPath,In as evalFhirPathTyped,ri as experimentalValidateResource,Nt as fhirPathArrayEquals,_t as fhirPathArrayEquivalent,Mt as fhirPathEquals,jt as fhirPathEquivalent,Bt as fhirPathIs,Lt as fhirPathNot,Y as findObservationInterval,Z as findObservationReferenceRange,ce as findResourceByCode,qe as forbidden,t as formatAddress,g as formatCodeableConcept,v as formatCoding,s as formatDate,c as formatDateTime,i as formatFamilyName,r as formatGivenName,n as formatHumanName,y as formatMoney,x as formatObservationValue,u as formatPeriod,m as formatQuantity,f as formatRange,bt as formatSearchQuery,a as formatTime,h as formatTiming,J as getCodeBySystem,A as getDateProperty,k as getDisplayString,Te as getElementDefinition,fe as getElementDefinitionTypeName,Nn as getExpressionForResourceType,N as getExtension,L as getExtensionValue,O as getIdentifier,C as getImageSrc,be as getPropertyDisplayName,I as getQuestionnaireAnswers,w as getReferenceString,ve as getResourceTypeSchema,ge as getResourceTypes,On as getSearchParameterDetails,xe as getSearchParameters,Ke as getStatus,It as getTypedPropertyValue,Ce as globalSchema,Qe as gone,he as indexSearchParameter,le as indexSearchParameterBundle,pe as indexStructureDefinition,de as indexStructureDefinitionBundle,Pn as initFhirPathParserBuilder,Xe as isAccepted,j as isEmpty,Ze as isGone,V as isLowerCase,Ye as isNotFound,Q as isObject,Je as isOk,Ve as isOperationOutcome,qt as isPeriod,E as isProfileResource,Qt as isQuantity,Ft as isQuantityEquivalent,ke as isReference,Ee as isResource,jr as isResourceType,ye as isResourceTypeSchema,F as isStringArray,q as isUUID,o as isValidDate,Gr as loadDataTypes,Jn as matchesAccessPolicy,ee as matchesRange,_n as matchesSearchRequest,rt as normalizeErrorString,nt as normalizeOperationOutcome,$e as notFound,je as notModified,ot as operationOutcomeIssueToString,it as operationOutcomeToString,ht as parseCriteriaAsSearchRequest,Dn as parseFhirPath,Dr as parseFilterParameter,Lr as parseHl7Date,or as parseJWTPayload,Sr as parseMappingLanguage,lt as parseSearchDefinition,dt as parseSearchRequest,pt as parseSearchUrl,ne as preciseEquals,ie as preciseGreaterThan,se as preciseGreaterThanOrEquals,re as preciseLessThan,oe as preciseLessThanOrEquals,te as preciseRound,Hn as projectAdminResourceTypes,Wn as protectedResourceTypes,Fn as publicResourceTypes,Ot as removeDuplicates,T as resolveId,Ge as serverError,X as setCodeBySystem,Wr as streamToBuffer,M as stringify,Rt as toJsBoolean,Dt as toTypedValue,wn as tokenize,Fe as tooManyRequests,Be as unauthorized,Br as validateResource,$r as validateResourceType,ze as validationError};
|