@medplum/core 2.0.13 → 2.0.15

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.
Files changed (59) hide show
  1. package/dist/cjs/index.cjs +1259 -1065
  2. package/dist/cjs/index.cjs.map +1 -1
  3. package/dist/cjs/index.min.cjs +1 -1
  4. package/dist/esm/base64.mjs +33 -0
  5. package/dist/esm/base64.mjs.map +1 -0
  6. package/dist/esm/bundle.mjs +36 -0
  7. package/dist/esm/bundle.mjs.map +1 -0
  8. package/dist/esm/cache.mjs +17 -23
  9. package/dist/esm/cache.mjs.map +1 -1
  10. package/dist/esm/client.mjs +523 -385
  11. package/dist/esm/client.mjs.map +1 -1
  12. package/dist/esm/eventtarget.mjs +6 -11
  13. package/dist/esm/eventtarget.mjs.map +1 -1
  14. package/dist/esm/fhirlexer/parse.mjs +15 -23
  15. package/dist/esm/fhirlexer/parse.mjs.map +1 -1
  16. package/dist/esm/fhirlexer/tokenize.mjs +190 -180
  17. package/dist/esm/fhirlexer/tokenize.mjs.map +1 -1
  18. package/dist/esm/fhirmapper/parse.mjs +264 -252
  19. package/dist/esm/fhirmapper/parse.mjs.map +1 -1
  20. package/dist/esm/fhirmapper/tokenize.mjs +2 -4
  21. package/dist/esm/fhirmapper/tokenize.mjs.map +1 -1
  22. package/dist/esm/fhirpath/atoms.mjs +13 -20
  23. package/dist/esm/fhirpath/atoms.mjs.map +1 -1
  24. package/dist/esm/fhirpath/parse.mjs +0 -1
  25. package/dist/esm/fhirpath/parse.mjs.map +1 -1
  26. package/dist/esm/fhirpath/tokenize.mjs +0 -1
  27. package/dist/esm/fhirpath/tokenize.mjs.map +1 -1
  28. package/dist/esm/filter/parse.mjs +1 -4
  29. package/dist/esm/filter/parse.mjs.map +1 -1
  30. package/dist/esm/filter/tokenize.mjs +2 -4
  31. package/dist/esm/filter/tokenize.mjs.map +1 -1
  32. package/dist/esm/index.min.mjs +1 -1
  33. package/dist/esm/index.mjs +1 -0
  34. package/dist/esm/index.mjs.map +1 -1
  35. package/dist/esm/jwt.mjs +2 -9
  36. package/dist/esm/jwt.mjs.map +1 -1
  37. package/dist/esm/readablepromise.mjs +18 -23
  38. package/dist/esm/readablepromise.mjs.map +1 -1
  39. package/dist/esm/schema.mjs +149 -127
  40. package/dist/esm/schema.mjs.map +1 -1
  41. package/dist/esm/search/match.mjs +1 -4
  42. package/dist/esm/search/match.mjs.map +1 -1
  43. package/dist/esm/storage.mjs +13 -19
  44. package/dist/esm/storage.mjs.map +1 -1
  45. package/dist/types/base64.d.ts +14 -0
  46. package/dist/types/bundle.d.ts +11 -0
  47. package/dist/types/cache.d.ts +3 -1
  48. package/dist/types/client.d.ts +164 -1
  49. package/dist/types/eventtarget.d.ts +1 -1
  50. package/dist/types/fhirlexer/parse.d.ts +5 -2
  51. package/dist/types/fhirlexer/tokenize.d.ts +28 -1
  52. package/dist/types/fhirpath/atoms.d.ts +1 -1
  53. package/dist/types/index.d.ts +1 -0
  54. package/dist/types/readablepromise.d.ts +4 -1
  55. package/dist/types/schema.d.ts +33 -1
  56. package/dist/types/storage.d.ts +2 -2
  57. package/package.json +1 -1
  58. package/dist/esm/node_modules/tslib/tslib.es6.mjs +0 -30
  59. package/dist/esm/node_modules/tslib/tslib.es6.mjs.map +0 -1
@@ -1 +1 @@
1
- function e(e,t,n,i){if("a"===n&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?i:"a"===n?i.call(e):i?i.value:t.get(e)}function t(e,t,n,i,r){if("m"===i)throw new TypeError("Private method is not writable");if("a"===i&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===i?r.call(e,n):r?r.value=n:t.set(e,n),n}var n,i,r,o;class s{constructor(e=10){n.add(this),i.set(this,void 0),r.set(this,void 0),t(this,i,e,"f"),t(this,r,new Map,"f")}clear(){e(this,r,"f").clear()}get(t){const n=e(this,r,"f").get(t);return n&&(e(this,r,"f").delete(t),e(this,r,"f").set(t,n)),n}set(t,s){e(this,r,"f").has(t)?e(this,r,"f").delete(t):e(this,r,"f").size>=e(this,i,"f")&&e(this,r,"f").delete(e(this,n,"m",o).call(this)),e(this,r,"f").set(t,s)}delete(t){e(this,r,"f").delete(t)}keys(){return e(this,r,"f").keys()}}function a(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 c(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 u(e){const t=[];return e.given&&t.push(...e.given),t.join(" ").trim()}function l(e){return e.family||""}function d(e){return e instanceof Date&&!isNaN(e.getTime())}function p(e,t,n){if(!e)return"";const i=new Date(e);return d(i)?(i.setUTCHours(0,0,0,0),i.toLocaleDateString(t,{timeZone:"UTC",...n})):""}function h(e,t,n){if(!e)return"";const i=new Date("2000-01-01T"+e+"Z");return d(i)?i.toLocaleTimeString(t,n):""}function f(e,t,n){if(!e)return"";const i=new Date(e);return d(i)?i.toLocaleString(t,n):""}function m(e,t,n){return e&&(e.start||e.end)?f(e.start,t,n)+" - "+f(e.end,t,n):""}i=new WeakMap,r=new WeakMap,n=new WeakSet,o=function(){return e(this,r,"f").keys().next().value};const y={s:"every second",min:"every minute",h:"hourly",d:"daily",wk:"weekly",mo:"monthly",a:"annually"},g={s:"second",min:"minute",h:"hour",d:"day",wk:"week",mo:"month",a:"year"},v={s:"seconds",min:"minutes",h:"hours",d:"days",wk:"weeks",mo:"months",a:"years"};function x(e){if(!e)return"";const t=[];if(e.repeat?.periodUnit){const n=e.repeat.frequency||1,i=e.repeat.period||1,r=e.repeat.periodUnit;1===n&&1===i?t.push(y[r]):(1===n?t.push("once"):t.push(n+" times"),1===i?t.push("per "+g[r]):t.push("per "+i+" "+v[r])),e.repeat.dayOfWeek&&t.push("on "+e.repeat.dayOfWeek.map(Z).join(", ")),e.repeat.timeOfDay&&t.push("at "+e.repeat.timeOfDay.map((e=>h(e))).join(", "))}return e.event&&t.push(e.event.map((e=>f(e))).join(", ")),Z(t.join(" ").trim())}function w(e,t,n=!1){if(n&&void 0===t)throw new Error("Precision must be specified for exclusive ranges");const i=e?.low&&{...e.low},r=e?.high&&{...e.high};return!e||void 0===i?.value&&void 0===r?.value?"":void 0!==e.low?.value&&void 0===e.high?.value?n&&void 0!==t?(e.low.value=function(e,t,n=1){return(k(e,t)-n)*Math.pow(10,-t)}(e.low.value,t),`> ${S(e.low,t)}`):`>= ${S(e.low,t)}`:void 0===e.low?.value&&void 0!==e.high?.value?n&&void 0!==t?(e.high.value=function(e,t,n=1){return(k(e,t)+n)*Math.pow(10,-t)}(e.high.value,t),`< ${S(e.high,t)}`):`<= ${S(e.high,t)}`:(i?.unit===r?.unit&&delete i?.unit,`${S(i,t)} - ${S(r,t)}`)}function S(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 b(e){return void 0===e?.value?"":e.value.toLocaleString(void 0,{style:"currency",currency:e.currency||"USD",currencyDisplay:"narrowSymbol"})}function E(e){return e?e.text?e.text:e.coding?e.coding.map((e=>T(e))).join(", "):"":""}function T(e){return e?.display||e?.code||""}function D(e){return e?"component"in e?e.component.map((e=>D(e))).join(" / "):e?.valueQuantity?S(e.valueQuantity):e.valueCodeableConcept?E(e.valueCodeableConcept):e.valueString?e.valueString:"":""}function k(e,t){return void 0===t?e:Math.round(e*Math.pow(10,t))}function C(e){const t=A(e),n=M(e);return n===t?{reference:t}:{reference:t,display:n}}function A(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 M(e){if(R(e)){const t=function(e){const t=e.name;if(t&&t.length>0)return c(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:A(e)}function I(e){if(!("photo"in e))return;const t=e.photo;if(t){if(!Array.isArray(t))return U(t);for(const e of t){const t=U(e);if(t)return t}}}function U(e){if(e.url&&e.contentType&&e.contentType.startsWith("image/"))return e.url}function O(e){return e?new Date(e):void 0}function L(e,t){const n=new Date(e);n.setUTCHours(0,0,0,0);const i=t?new Date(t):new Date;i.setUTCHours(0,0,0,0);const r=n.getUTCFullYear(),o=n.getUTCMonth(),s=n.getUTCDate(),a=i.getUTCFullYear(),c=i.getUTCMonth(),u=i.getUTCDate();let l=a-r;(c<o||c===o&&u<s)&&l--;let d=12*a+c-(12*r+o);u<s&&d--;return{years:l,months:d,days:Math.floor((i.getTime()-n.getTime())/864e5)}}function _(e,t){const{years:n,months:i,days:r}=L(e,t);return n>=2?n.toString().padStart(3,"0")+"Y":i>=1?i.toString().padStart(3,"0")+"M":r.toString().padStart(3,"0")+"D"}function N(e){const t={};return j(e.item,t),t}function j(e,t){if(e)for(const n of e)n.linkId&&n.answer&&n.answer.length>0&&(t[n.linkId]=n.answer[0]),j(n.item,t)}function W(e,t){const n=e.identifier;if(!n)return;const i=Array.isArray(n)?n:[n];for(const e of i)if(e.system===t)return e.value}function $(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 Q(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 B(e,t){return JSON.stringify(e,q,t?2:void 0)}function q(e,t){return!function(e){return!!e.match(/\d+$/)}(e)&&F(t)?void 0:t}function F(e){if(null==e)return!0;const t=typeof e;return"string"===t&&""===e||"object"===t&&0===Object.keys(e).length}function H(e,t,n){return e===t||(!(!F(e)||!F(t))||!F(e)&&!F(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(!H(e[n],t[n]))return!1;return!0}(e,t):!Array.isArray(e)&&!Array.isArray(t)&&(V(e)&&V(t)?function(e,t,n){const i=new Set;Object.keys(e).forEach((e=>i.add(e))),Object.keys(t).forEach((e=>i.add(e))),"meta"===n&&(i.delete("versionId"),i.delete("lastUpdated"),i.delete("author"));for(const n of i){if(!H(e[n],t[n],n))return!1}return!0}(e,t,n):(V(e)||V(t),!1))))}function z(e){return JSON.parse(JSON.stringify(e))}function G(e){return!!e.match(/^\w{8}-\w{4}-\w{4}-\w{4}-\w{12}$/i)}function V(e){return null!==e&&"object"==typeof e}function X(e){return e.every((e=>"string"==typeof e))}const J=[];for(let e=0;e<256;e++)J.push(e.toString(16).padStart(2,"0"));function Y(e){const t=new Uint8Array(e),n=new Array(t.length);for(let e=0;e<t.length;e++)n[e]=J[t[e]];return n.join("")}function K(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 Z(e){return e.charAt(0).toUpperCase()+e.substring(1)}function ee(e){return e===e.toLowerCase()&&e!==e.toUpperCase()}function te(e,t){return e?.coding?.find((e=>e.system===t))?.code}function ne(e,t,n){e.coding||(e.coding=[]);const i=e.coding?.find((e=>e.system===t));i?i.code=n:e.coding?.push({system:t,code:n})}function ie(e,t,n,i){return e.qualifiedInterval?.find((r=>oe(r,t)&&function(e,t,n){return!!e.range&&se(t,e.range,n)}(r,n,e.quantitativeDetails?.decimalPrecision)&&(void 0===i||r.category===i)))}function re(e,t,n){return e.qualifiedInterval?.find((e=>oe(e,t)&&n.includes(e.condition)))}function oe(e,t){return function(e,t){return!e.gender||e.gender===t.gender}(e,t)&&function(e,t){return!e.age||se(L(t.birthDate).years,e.age)}(e,t)}function se(e,t,n){return(void 0===t.low?.value||pe(e,t.low.value,n))&&(void 0===t.high?.value||de(e,t.high.value,n))}function ae(e,t){return parseFloat(e.toFixed(t))}function ce(e,t,n){return he(e,n)===he(t,n)}function ue(e,t,n){return he(e,n)<he(t,n)}function le(e,t,n){return he(e,n)>he(t,n)}function de(e,t,n){return he(e,n)<=he(t,n)}function pe(e,t,n){return he(e,n)>=he(t,n)}function he(e,t){return void 0===t?e:Math.round(e*Math.pow(10,t))}function fe(){const e=new Uint32Array(28);return crypto.getRandomValues(e),Y(e.buffer)}var me;class ye{constructor(){me.set(this,void 0),t(this,me,{},"f")}addEventListener(t,n){e(this,me,"f")[t]||(e(this,me,"f")[t]=[]),e(this,me,"f")[t].push(n)}removeEventListeneer(t,n){const i=e(this,me,"f")[t];if(i)for(let e=0;e<i.length;e++)if(i[e]===n)return void i.splice(e,1)}dispatchEvent(t){const n=e(this,me,"f")[t.type];return n&&n.forEach((e=>e.call(this,t))),!t.defaultPrevented}}function ge(e){const t=function(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")}(e.replace(/-/g,"+").replace(/_/g,"/")),n=Array.from(t).reduce(((e,t)=>`${e}%${("00"+t.charCodeAt(0).toString(16)).slice(-2)}`),""),i=decodeURIComponent(n);return JSON.parse(i)}function ve(e){const[t,n,i]=e.split(".");return ge(n)}me=new WeakMap;const xe="ok",we="created",Se="gone",be="not-modified",Ee="not-found",Te="unauthorized",De="forbidden",ke="too-many-requests",Ce={resourceType:"OperationOutcome",id:xe,issue:[{severity:"information",code:"informational",details:{text:"All OK"}}]},Ae={resourceType:"OperationOutcome",id:we,issue:[{severity:"information",code:"informational",details:{text:"Created"}}]},Pe={resourceType:"OperationOutcome",id:be,issue:[{severity:"information",code:"informational",details:{text:"Not Modified"}}]},Re={resourceType:"OperationOutcome",id:Ee,issue:[{severity:"error",code:"not-found",details:{text:"Not found"}}]},Me={resourceType:"OperationOutcome",id:Te,issue:[{severity:"error",code:"login",details:{text:"Unauthorized"}}]},Ie={resourceType:"OperationOutcome",id:De,issue:[{severity:"error",code:"forbidden",details:{text:"Forbidden"}}]},Ue={resourceType:"OperationOutcome",id:Se,issue:[{severity:"error",code:"deleted",details:{text:"Gone"}}]},Oe={resourceType:"OperationOutcome",id:ke,issue:[{severity:"error",code:"throttled",details:{text:"Too Many Requests"}}]};function Le(e,t){return{resourceType:"OperationOutcome",issue:[{severity:"error",code:"invalid",details:{text:e},expression:t?[t]:void 0}]}}function _e(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 je(e){return e.id===xe||e.id===we||e.id===be}function We(e){return e.id===Ee}function $e(e){return e.id===Se}function Qe(e){return e.id===xe?200:e.id===we?201:e.id===be?304:e.id===Te?401:e.id===De?403:e.id===Ee?404:e.id===Se?410:e.id===ke?429:400}function Be(e,t){if(!je(e)||void 0===t)throw new qe(e)}class qe extends Error{constructor(e,t){super(ze(e)),this.outcome=e,this.cause=t}}function Fe(e){return e instanceof qe?e.outcome:Ne(e)?e:Le(He(e))}function He(e){return e?"string"==typeof e?e:e instanceof Error?e.message:Ne(e)?ze(e):JSON.stringify(e):"Unknown error"}function ze(e){const t=[];if(e.issue)for(const n of e.issue){let e=n.details?.text||"Unknown error";n.expression?.length&&(e+=` (${n.expression.join(", ")})`),t.push(e)}return t.length>0?t.join("; "):"Unknown error"}var Ge,Ve,Xe,Je,Ye,Ke,Ze;class et{constructor(e){this[Ye]="ReadablePromise",Ge.set(this,void 0),Ve.set(this,"pending"),Xe.set(this,void 0),Je.set(this,void 0),t(this,Ge,e.then((e=>(t(this,Ve,"success","f"),t(this,Xe,e,"f"),e)),(e=>{throw t(this,Ve,"error","f"),t(this,Je,e,"f"),e})),"f")}isPending(){return"pending"===e(this,Ve,"f")}isOk(){return"success"===e(this,Ve,"f")}read(){switch(e(this,Ve,"f")){case"pending":throw e(this,Ge,"f");case"error":throw e(this,Je,"f");default:return e(this,Xe,"f")}}then(t,n){return e(this,Ge,"f").then(t,n)}catch(t){return e(this,Ge,"f").catch(t)}finally(t){return e(this,Ge,"f").finally(t)}}Ge=new WeakMap,Ve=new WeakMap,Xe=new WeakMap,Je=new WeakMap,Ye=Symbol.toStringTag;class tt{constructor(){Ke.set(this,void 0),t(this,Ke,"undefined"!=typeof localStorage?localStorage:new nt,"f")}clear(){e(this,Ke,"f").clear()}getString(t){return e(this,Ke,"f").getItem(t)||void 0}setString(t,n){n?e(this,Ke,"f").setItem(t,n):e(this,Ke,"f").removeItem(t)}getObject(e){const t=this.getString(e);return t?JSON.parse(t):void 0}setObject(e,t){this.setString(e,t?B(t):void 0)}}Ke=new WeakMap;class nt{constructor(){Ze.set(this,void 0),t(this,Ze,new Map,"f")}get length(){return e(this,Ze,"f").size}clear(){e(this,Ze,"f").clear()}getItem(t){return e(this,Ze,"f").get(t)??null}setItem(t,n){n?e(this,Ze,"f").set(t,n):e(this,Ze,"f").delete(t)}removeItem(t){e(this,Ze,"f").delete(t)}key(t){return Array.from(e(this,Ze,"f").keys())[t]}}Ze=new WeakMap;var it,rt={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 ot(e){for(const t of e.entry){const e=t.resource;"StructureDefinition"===e.resourceType&&st(e)}}function st(e){if(!e.name)return;const t=e.snapshot?.element;t&&(t.forEach((t=>function(e,t){const n=t.path,i=t.type?.[0]?.code;if(void 0!==i&&"Element"!==i&&"BackboneElement"!==i)return;const r=n.split(".");r[0]=e.name;const o=lt(r);let s=St.types[o];s||(St.types[o]=s={});s.parentType=s.parentType||lt(r.slice(0,r.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,i=n.split(".");if(1===i.length)return;i[0]=e.name;const r=lt(i.slice(0,i.length-1)),o=St.types[r];if(!o)return;const s=i[i.length-1];o.properties[s]=t}(e,t))))}function at(e){for(const t of e.entry){const e=t.resource;"SearchParameter"===e.resourceType&&ct(e)}}function ct(e){if(e.base)for(const t of e.base){const n=St.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 ut(e){const t=e.type?.[0]?.code;return"BackboneElement"===t||"Element"===t?lt(e.path?.split(".")):t}function lt(e){return 1===e.length?e[0]:e.map(Z).join("")}function dt(e){const t=e.structureDefinition;return t&&t.name===e.elementDefinition?.path&&"resource"===t.kind&&!t.abstract}function pt(){const e=[];for(const[t,n]of Object.entries(St.types))dt(n)&&e.push(t);return e}function ht(e){return St.types[e]}function ft(e){return St.types[e].searchParams}function mt(e){return e.replaceAll("[x]","").split(".").pop().split(/(?=[A-Z])/).map(gt).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"}(it||(it={}));const yt=new Set(["ID","IP","PKCE","JWKS","URI","URL"]);function gt(e){const t=e.toUpperCase();return yt.has(t)?t:t.charAt(0)+e.slice(1)}function vt(e,t){const n=St.types[e];if(!n)return;const i=n.properties[t]??n.properties[t+"[x]"];if(i){if(i.contentReference){const e=i.contentReference.substring(1).split("."),t=e.pop();return vt(lt(e),t)}return i}}function xt(e){return!(!e||"object"!=typeof e||!("resourceType"in e))}function wt(e){return!(!e||"object"!=typeof e||!("reference"in e))}const St=rt;var bt,Et,Tt,Dt,kt,Ct,At,Pt,Rt,Mt,It,Ut,Ot,Lt,_t,Nt,jt,Wt,$t,Qt,Bt,qt,Ft,Ht,zt,Gt,Vt,Xt,Jt,Yt,Kt,Zt,en,tn,nn,rn,on,sn,an,cn,un;const ln="2.0.13-ee64d72c",dn={resourceType:"Device",id:"system",deviceName:[{name:"System"}]};class pn extends ye{constructor(n){if(super(),bt.add(this),Et.set(this,void 0),Tt.set(this,void 0),Dt.set(this,void 0),kt.set(this,void 0),Ct.set(this,void 0),At.set(this,void 0),Pt.set(this,void 0),Rt.set(this,void 0),Mt.set(this,void 0),It.set(this,void 0),Ut.set(this,void 0),Ot.set(this,void 0),Lt.set(this,void 0),_t.set(this,void 0),Nt.set(this,void 0),jt.set(this,void 0),Wt.set(this,void 0),$t.set(this,void 0),Qt.set(this,void 0),Bt.set(this,void 0),qt.set(this,void 0),Ft.set(this,void 0),n?.baseUrl&&!n.baseUrl.startsWith("http"))throw new Error("Base URL must start with http or https");t(this,Et,n?.fetch||function(){if(!globalThis.fetch)throw new Error("Fetch not available in this environment");return globalThis.fetch.bind(globalThis)}(),"f"),t(this,Dt,n?.storage||new tt,"f"),t(this,Tt,n?.createPdf,"f"),t(this,kt,new s(n?.resourceCacheSize??1e3),"f"),t(this,Ct,n?.cacheTime??6e4,"f"),t(this,At,function(e){if(!e)return e;return e.endsWith("/")?e:e+"/"}(n?.baseUrl)||"https://api.medplum.com/","f"),t(this,Pt,e(this,At,"f")+"fhir/R4/","f"),t(this,_t,n?.clientId||"","f"),t(this,Rt,n?.authorizeUrl||e(this,At,"f")+"oauth2/authorize","f"),t(this,Mt,n?.tokenUrl||e(this,At,"f")+"oauth2/token","f"),t(this,It,n?.logoutUrl||e(this,At,"f")+"oauth2/logout","f"),t(this,Ut,n?.onUnauthenticated,"f"),t(this,Ot,n?.autoBatchTime??0,"f"),t(this,Lt,[],"f");const i=this.getActiveLogin();i&&(t(this,Wt,i.accessToken,"f"),t(this,$t,i.refreshToken,"f"),e(this,bt,"m",zt).call(this).catch(console.log)),e(this,bt,"m",un).call(this)}getBaseUrl(){return e(this,At,"f")}clear(){e(this,Dt,"f").clear(),this.clearActiveLogin()}clearActiveLogin(){e(this,Dt,"f").setString("activeLogin",void 0),e(this,kt,"f").clear(),t(this,Wt,void 0,"f"),t(this,$t,void 0,"f"),t(this,qt,void 0,"f"),t(this,Ft,void 0,"f"),this.dispatchEvent({type:"change"})}invalidateUrl(t){t=t.toString(),e(this,kt,"f").delete(t)}invalidateSearches(t){const n="fhir/R4/"+t;for(const t of e(this,kt,"f").keys())(t.endsWith(n)||t.includes(n+"?"))&&e(this,kt,"f").delete(t)}get(n,i={}){n=n.toString();const r=e(this,bt,"m",Gt).call(this,n,i);if(r)return r.value;let o;o=n.startsWith(e(this,Pt,"f"))&&e(this,Ot,"f")>0?new Promise(((r,o)=>{e(this,Lt,"f").push({method:"GET",url:n.replace(e(this,Pt,"f"),""),options:i,resolve:r,reject:o}),e(this,jt,"f")||t(this,jt,setTimeout((()=>e(this,bt,"m",Zt).call(this)),e(this,Ot,"f")),"f")})):e(this,bt,"m",Yt).call(this,"GET",n,i);const s=new et(o);return e(this,bt,"m",Vt).call(this,n,s),s}post(t,n,i,r={}){return t=t.toString(),n&&e(this,bt,"m",nn).call(this,r,n),i&&e(this,bt,"m",tn).call(this,r,i),this.invalidateUrl(t),e(this,bt,"m",Yt).call(this,"POST",t,r)}put(t,n,i,r={}){return t=t.toString(),n&&e(this,bt,"m",nn).call(this,r,n),i&&e(this,bt,"m",tn).call(this,r,i),this.invalidateUrl(t),e(this,bt,"m",Yt).call(this,"PUT",t,r)}patch(t,n,i={}){return t=t.toString(),e(this,bt,"m",nn).call(this,i,n),e(this,bt,"m",tn).call(this,i,"application/json-patch+json"),this.invalidateUrl(t),e(this,bt,"m",Yt).call(this,"PATCH",t,i)}delete(t,n={}){return t=t.toString(),this.invalidateUrl(t),e(this,bt,"m",Yt).call(this,"DELETE",t,n)}async startNewUser(e){const{codeChallengeMethod:t,codeChallenge:n}=await this.startPkce();return this.post("auth/newuser",{...e,codeChallengeMethod:t,codeChallenge:n})}async startNewProject(e){return this.post("auth/newproject",e)}async startNewPatient(e){return this.post("auth/newpatient",e)}async startLogin(t){return this.post("auth/login",{...await this.ensureCodeChallenge(t),clientId:t.clientId??e(this,_t,"f"),scope:t.scope})}async startGoogleLogin(t){return this.post("auth/google",{...await this.ensureCodeChallenge(t),clientId:t.clientId??e(this,_t,"f"),scope:t.scope})}async ensureCodeChallenge(e){return e.codeChallenge?e:{...e,...await this.startPkce()}}async signOut(){await this.post(e(this,It,"f"),{}),this.clear()}async signInWithRedirect(t){const n=new URLSearchParams(window.location.search).get("code");return n?this.processCode(n):void await e(this,bt,"m",on).call(this,t)}signOutWithRedirect(){window.location.assign(e(this,It,"f"))}async signInWithExternalAuth(e,t,n,i){const r=await this.ensureCodeChallenge(i);window.location.assign(this.getExternalAuthRedirectUri(e,t,n,r))}getExternalAuthRedirectUri(e,t,n,i){const r=new URL(e);return r.searchParams.set("response_type","code"),r.searchParams.set("client_id",t),r.searchParams.set("redirect_uri",n),r.searchParams.set("scope","openid profile email"),r.searchParams.set("state",JSON.stringify(i)),r.toString()}fhirUrl(...t){return new URL(e(this,Pt,"f")+t.join("/"))}fhirSearchUrl(e,t){const n=this.fhirUrl(e);return t&&(n.search=new URLSearchParams(t).toString()),n}search(t,n,i={}){const r=this.fhirSearchUrl(t,n),o=r.toString()+"-search",s=e(this,bt,"m",Gt).call(this,o,i);if(s)return s.value;const a=new et((async()=>{const t=await this.get(r,i);if(t.entry)for(const n of t.entry)e(this,bt,"m",Xt).call(this,n.resource);return t})());return e(this,bt,"m",Vt).call(this,o,a),a}searchOne(t,n,i={}){const r=this.fhirSearchUrl(t,n);r.searchParams.set("_count","1"),r.searchParams.sort();const o=r.toString()+"-searchOne",s=e(this,bt,"m",Gt).call(this,o,i);if(s)return s.value;const a=new et(this.search(t,r.searchParams,i).then((e=>e.entry?.[0]?.resource)));return e(this,bt,"m",Vt).call(this,o,a),a}searchResources(t,n,i={}){const r=this.fhirSearchUrl(t,n).toString()+"-searchResources",o=e(this,bt,"m",Gt).call(this,r,i);if(o)return o.value;const s=new et(this.search(t,n,i).then((e=>e.entry?.map((e=>e.resource))??[])));return e(this,bt,"m",Vt).call(this,r,s),s}searchValueSet(e,t,n={}){const i=this.fhirUrl("ValueSet","$expand");return i.searchParams.set("url",e),i.searchParams.set("filter",t),this.get(i.toString(),n)}getCached(t,n){const i=e(this,kt,"f").get(this.fhirUrl(t,n).toString())?.value;return i&&i.isOk()?i.read():void 0}getCachedReference(e){const t=e.reference;if(!t)return;if("system"===t)return dn;const[n,i]=t.split("/");return n&&i?this.getCached(n,i):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 et(Promise.reject(new Error("Missing reference")));if("system"===n)return new et(Promise.resolve(dn));const[i,r]=n.split("/");return i&&r?this.readResource(i,r,t):new et(Promise.reject(new Error("Invalid reference")))}getSchema(){return St}requestSchema(t){if(t in St.types)return Promise.resolve(St);const n=t+"-requestSchema",i=e(this,bt,"m",Gt).call(this,n,void 0);if(i)return i.value;const r=new et((async()=>{const e=`{\n StructureDefinitionList(name: "${t}") {\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: "${t}", _count: 100) {\n base,\n code,\n type,\n expression,\n target\n }\n }`.replace(/\s+/g," "),n=await this.graphql(e);for(const e of n.data.StructureDefinitionList)st(e);for(const e of n.data.SearchParameterList)ct(e);return St})());return e(this,bt,"m",Vt).call(this,n,r),r}readHistory(e,t,n={}){return this.get(this.fhirUrl(e,t,"_history"),n)}readVersion(e,t,n,i={}){return this.get(this.fhirUrl(e,t,"_history",n),i)}readPatientEverything(e,t={}){return this.get(this.fhirUrl("Patient",e,"$everything"),t)}createResource(e){if(!e.resourceType)throw new Error("Missing resourceType");return this.invalidateSearches(e.resourceType),this.post(this.fhirUrl(e.resourceType),e)}async createResourceIfNoneExist(e,t){return await this.searchOne(e.resourceType,t)??this.createResource(e)}createBinary(e,t,n,i){const r=this.fhirUrl("Binary");return t&&r.searchParams.set("_filename",t),i?this.uploadwithProgress(r,e,n,i):this.post(r,e,n)}uploadwithProgress(t,n,i,r){return new Promise(((o,s)=>{const a=new XMLHttpRequest;a.responseType="json",a.onabort=()=>s(new Error("Request aborted")),a.onerror=()=>s(new Error("Request error")),r&&(a.upload.onprogress=e=>r(e),a.upload.onload=e=>r(e)),a.onload=()=>{a.status>=200&&a.status<300?o(a.response):s(new Error(a.statusText))},a.open("POST",t),a.withCredentials=!0,a.setRequestHeader("Authorization","Bearer "+e(this,Wt,"f")),a.setRequestHeader("Cache-Control","no-cache, no-store, max-age=0"),a.setRequestHeader("Content-Type",i),a.setRequestHeader("X-Medplum","extended"),a.send(n)}))}async createPdf(t,n,i,r){if(!e(this,Tt,"f"))throw new Error("PDF creation not enabled");const o=await e(this,Tt,"f").call(this,t,i,r);return this.createBinary(o,n,"application/pdf")}createComment(e,t){const n=this.getProfile();let i,r;return"Encounter"===e.resourceType&&(i=C(e),r=e.subject),"ServiceRequest"===e.resourceType&&(i=e.encounter,r=e.subject),"Patient"===e.resourceType&&(r=C(e)),this.createResource({resourceType:"Communication",basedOn:[C(e)],encounter:i,subject:r,sender:n?C(n):void 0,sent:(new Date).toISOString(),payload:[{contentString:t}]})}async updateResource(t){if(!t.resourceType)throw new Error("Missing resourceType");if(!t.id)throw new Error("Missing id");this.invalidateSearches(t.resourceType);let n=await this.put(this.fhirUrl(t.resourceType,t.id),t);return n||(n=t),e(this,bt,"m",Xt).call(this,n),n}patchResource(e,t,n){return this.invalidateSearches(e),this.patch(this.fhirUrl(e,t),n)}deleteResource(t,n){return e(this,bt,"m",Jt).call(this,this.fhirUrl(t,n).toString()),this.invalidateSearches(t),this.delete(this.fhirUrl(t,n))}validateResource(e){return this.post(this.fhirUrl(e.resourceType,"$validate"),e)}executeBot(e,t,n,i={}){let r;if("string"==typeof e){const t=e;r=this.fhirUrl("Bot",t,"$execute")}else{const t=e;r=this.fhirUrl("Bot","$execute")+`?identifier=${t.system}|${t.value}`}return this.post(r,t,n,i)}executeBatch(e){return this.post("fhir/R4",e)}sendEmail(e){return this.post("email/v1/send",e,"application/json")}graphql(e,t,n,i){return this.post(this.fhirUrl("$graphql"),{query:e,operationName:t,variables:n},"application/json",i)}readResourceGraph(e,t,n){return this.get(`${this.fhirUrl(e,t)}/$graph?graph=${n}`)}getActiveLogin(){return e(this,Dt,"f").getObject("activeLogin")}async setActiveLogin(n){this.clearActiveLogin(),t(this,Wt,n.accessToken,"f"),t(this,$t,n.refreshToken,"f"),e(this,Dt,"f").setObject("activeLogin",n),e(this,bt,"m",Ht).call(this,n),t(this,Qt,void 0,"f"),await e(this,bt,"m",zt).call(this)}getAccessToken(){return e(this,Wt,"f")}setAccessToken(e){t(this,Wt,e,"f"),t(this,$t,void 0,"f"),t(this,qt,void 0,"f"),t(this,Ft,void 0,"f")}getLogins(){return e(this,Dt,"f").getObject("logins")??[]}isLoading(){return!!e(this,Bt,"f")}getProfile(){return e(this,qt,"f")}async getProfileAsync(){return e(this,Bt,"f")&&await e(this,Bt,"f"),this.getProfile()}getUserConfiguration(){return e(this,Ft,"f")}async download(t,n={}){e(this,Qt,"f")&&await e(this,Qt,"f"),e(this,bt,"m",en).call(this,n);return(await e(this,Et,"f").call(this,t.toString(),n)).blob()}async startPkce(){const e=fe();sessionStorage.setItem("pkceState",e);const t=fe();sessionStorage.setItem("codeVerifier",t);const n=K(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",n),{codeChallengeMethod:"S256",codeChallenge:n}}processCode(t,n){const i=new URLSearchParams;if(i.set("grant_type","authorization_code"),i.set("code",t),i.set("client_id",n?.clientId||e(this,_t,"f")),i.set("redirect_uri",n?.redirectUri||hn()),"undefined"!=typeof sessionStorage){const e=sessionStorage.getItem("codeVerifier");e&&i.set("code_verifier",e)}return e(this,bt,"m",an).call(this,i)}async startClientLogin(n,i){t(this,_t,n,"f"),t(this,Nt,i,"f");const r=new URLSearchParams;return r.set("grant_type","client_credentials"),r.set("client_id",n),r.set("client_secret",i),e(this,bt,"m",an).call(this,r)}async invite(e,t){return this.post("admin/projects/"+e+"/invite",t)}}function hn(){return"undefined"==typeof window?"":window.location.protocol+"//"+window.location.host+"/"}var fn,mn,yn,gn,vn,xn,wn,Sn,bn,En,Tn,Dn,kn,Cn,An,Pn,Rn,Mn,In,Un,On,Ln,_n,Nn,jn,Wn,$n,Qn,Bn,qn,Fn,Hn,zn,Gn;Et=new WeakMap,Tt=new WeakMap,Dt=new WeakMap,kt=new WeakMap,Ct=new WeakMap,At=new WeakMap,Pt=new WeakMap,Rt=new WeakMap,Mt=new WeakMap,It=new WeakMap,Ut=new WeakMap,Ot=new WeakMap,Lt=new WeakMap,_t=new WeakMap,Nt=new WeakMap,jt=new WeakMap,Wt=new WeakMap,$t=new WeakMap,Qt=new WeakMap,Bt=new WeakMap,qt=new WeakMap,Ft=new WeakMap,bt=new WeakSet,Ht=function(t){const n=this.getLogins().filter((e=>e.profile?.reference!==t.profile?.reference));n.push(t),e(this,Dt,"f").setObject("logins",n)},zt=async function(){return t(this,Bt,new Promise(((n,i)=>{this.get("auth/me").then((i=>{t(this,Bt,void 0,"f"),t(this,qt,i.profile,"f"),t(this,Ft,i.config,"f"),this.dispatchEvent({type:"change"}),n(e(this,qt,"f"))})).catch(i)})),"f"),e(this,Bt,"f")},Gt=function(t,n){if(e(this,Ct,"f")<=0||"no-cache"===n?.cache||"reload"===n?.cache)return;const i=e(this,kt,"f").get(t);return!i||i.requestTime+e(this,Ct,"f")<Date.now()?void 0:i},Vt=function(t,n){e(this,Ct,"f")>0&&e(this,kt,"f").set(t,{requestTime:Date.now(),value:n})},Xt=function(t){t?.id&&e(this,bt,"m",Vt).call(this,this.fhirUrl(t.resourceType,t.id).toString(),new et(Promise.resolve(t)))},Jt=function(t){e(this,Ct,"f")>0&&e(this,kt,"f").delete(t)},Yt=async function(t,n,i={}){e(this,Qt,"f")&&await e(this,Qt,"f"),n.startsWith("http")||(n=e(this,At,"f")+n),i.method=t,e(this,bt,"m",en).call(this,i);const r=await e(this,bt,"m",Kt).call(this,n,i);if(401===r.status)return e(this,bt,"m",rn).call(this,t,n,i);if(204===r.status||304===r.status)return;let o;try{o=await r.json()}catch(e){throw console.error("Error parsing response",r.status,e),e}if(r.status>=400)throw new qe(Fe(o));return o},Kt=async function(t,n){let i;for(let r=0;r<3;r++){if(i=await e(this,Et,"f").call(this,t,n),i.status<500)return i;await new Promise((e=>setTimeout(e,200)))}return i},Zt=async function(){const n=[...e(this,Lt,"f")];if(e(this,Lt,"f").length=0,t(this,jt,void 0,"f"),1===n.length){const t=n[0];return void t.resolve(await e(this,bt,"m",Yt).call(this,t.method,e(this,Pt,"f")+t.url,t.options))}const i={resourceType:"Bundle",type:"batch",entry:n.map((e=>({request:{method:e.method,url:e.url},resource:e.options.body?JSON.parse(e.options.body):void 0})))},r=await this.post("fhir/R4",i);for(let e=0;e<n.length;e++){const t=n[e],i=r.entry?.[e];i?.response?.outcome&&!je(i.response.outcome)?t.reject(new qe(i.response.outcome)):t.resolve(i?.resource)}},en=function(t){t.headers||(t.headers={});const n=t.headers;n["X-Medplum"]="extended",n["Content-Type"]||(n["Content-Type"]="application/fhir+json"),e(this,Wt,"f")&&(n.Authorization="Bearer "+e(this,Wt,"f")),t.cache||(t.cache="no-cache"),t.credentials||(t.credentials="include")},tn=function(e,t){e.headers||(e.headers={});e.headers["Content-Type"]=t},nn=function(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))},rn=function(t,n,i){return e(this,bt,"m",sn).call(this)?e(this,bt,"m",Yt).call(this,t,n,i):(this.clearActiveLogin(),e(this,Ut,"f")&&e(this,Ut,"f").call(this),Promise.reject(new Error("Unauthenticated")))},on=async function(t){const n=await this.ensureCodeChallenge(t||{}),i=new URL(e(this,Rt,"f"));i.searchParams.set("response_type","code"),i.searchParams.set("state",sessionStorage.getItem("pkceState")),i.searchParams.set("client_id",n.clientId||e(this,_t,"f")),i.searchParams.set("redirect_uri",n.redirectUri||hn()),i.searchParams.set("code_challenge_method",n.codeChallengeMethod),i.searchParams.set("code_challenge",n.codeChallenge),i.searchParams.set("scope",n.scope||"openid profile"),window.location.assign(i.toString())},sn=function(){if(e(this,Qt,"f"))return e(this,Qt,"f");if(e(this,$t,"f")){const n=new URLSearchParams;return n.set("grant_type","refresh_token"),n.set("client_id",e(this,_t,"f")),n.set("refresh_token",e(this,$t,"f")),t(this,Qt,e(this,bt,"m",an).call(this,n),"f"),e(this,Qt,"f")}return e(this,_t,"f")&&e(this,Nt,"f")?(t(this,Qt,this.startClientLogin(e(this,_t,"f"),e(this,Nt,"f")),"f"),e(this,Qt,"f")):void 0},an=async function(t){const n=await e(this,Et,"f").call(this,e(this,Mt,"f"),{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:t,credentials:"include"});if(!n.ok)throw this.clearActiveLogin(),new Error("Failed to fetch tokens");const i=await n.json();return await e(this,bt,"m",cn).call(this,i),this.getProfile()},cn=async function(t){const n=t.access_token,i=ve(n);if(Date.now()>=1e3*i.exp)throw this.clearActiveLogin(),new Error("Token expired");if(e(this,_t,"f")&&i.client_id!==e(this,_t,"f"))throw this.clearActiveLogin(),new Error("Token was not issued for this audience");return this.setActiveLogin({accessToken:n,refreshToken:t.refresh_token,project:t.project,profile:t.profile})},un=function(){try{window.addEventListener("storage",(e=>{null!==e.key&&"activeLogin"!==e.key||window.location.reload()}))}catch(e){}};class Vn{constructor(e,t){this.operator=e,this.child=t}toString(){return`${this.operator}(${this.child.toString()})`}}class Xn{constructor(e,t,n){this.operator=e,this.left=t,this.right=n}toString(){return`${this.left.toString()} ${this.operator} ${this.right.toString()}`}}class Jn{constructor(){fn.set(this,{}),mn.set(this,{})}registerInfix(t,n){return e(this,mn,"f")[t]=n,this}registerPrefix(t,n){return e(this,fn,"f")[t]=n,this}prefix(e,t,n){return this.registerPrefix(e,{parse(e,i){const r=e.consumeAndParse(t);return n(i,r)}})}infixLeft(e,t,n){return this.registerInfix(e,{parse(e,i,r){const o=e.consumeAndParse(t);return n(i,r,o)},precedence:t})}construct(t){return new Yn(t,e(this,fn,"f"),e(this,mn,"f"))}}fn=new WeakMap,mn=new WeakMap;class Yn{constructor(e,n,i){yn.set(this,void 0),gn.set(this,void 0),vn.set(this,void 0),t(this,yn,e,"f"),t(this,gn,n,"f"),t(this,vn,i,"f")}hasMore(){return e(this,yn,"f").length>0}match(e){const t=this.peek();return t?.id===e&&(this.consume(),!0)}consumeAndParse(t=1/0){const n=this.consume(),i=e(this,gn,"f")[n.id];if(!i)throw Error(`Parse error at "${n.value}" (line ${n.line}, column ${n.column}). No matching prefix parselet.`);let r=i.parse(this,n);for(;t>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(t,n){if(!e(this,yn,"f").length)throw Error("Cant consume unknown more tokens.");if(t&&this.peek()?.id!==t){const e=this.peek();throw Error(`Expected ${t} but got "${e.id}" at line ${e.line} column ${e.column}.`)}if(n&&this.peek()?.value!==n){const e=this.peek();throw Error(`Expected "${n}" but got "${e.value}" at line ${e.line} column ${e.column}.`)}return e(this,yn,"f").shift()}peek(){return e(this,yn,"f").length>0?e(this,yn,"f")[0]:void 0}removeComments(){t(this,yn,e(this,yn,"f").filter((e=>"Comment"!==e.id)),"f")}getInfixParselet(t){return e(this,vn,"f")["Symbol"===t.id?t.value:t.id]}}yn=new WeakMap,gn=new WeakMap,vn=new WeakMap;const Kn=["year","years","month","months","week","weeks","day","days","hour","hours","minute","minutes","second","seconds","millisecond","milliseconds"];class Zn{constructor(e,n,i,r){xn.add(this),wn.set(this,void 0),Sn.set(this,void 0),bn.set(this,void 0),En.set(this,void 0),Tn.set(this,void 0),Dn.set(this,[]),kn.set(this,{index:0,line:1,column:0}),Cn.set(this,[]),t(this,wn,e,"f"),t(this,Sn,n,"f"),t(this,bn,i,"f"),t(this,En,!!r?.dateTimeLiterals,"f"),t(this,Tn,r?.symbolRegex??/[$\w]/,"f")}tokenize(){for(;e(this,kn,"f").index<e(this,wn,"f").length;){const t=e(this,xn,"m",Rn).call(this);t&&e(this,Dn,"f").push(t)}return e(this,Dn,"f")}}function ei(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 ti(e){return[{type:it.boolean,value:e}]}function ni(e){return null==e?{type:"undefined",value:void 0}:Number.isSafeInteger(e)?{type:it.integer,value:e}:"number"==typeof e?{type:it.decimal,value:e}:"boolean"==typeof e?{type:it.boolean,value:e}:"string"==typeof e?{type:it.string,value:e}:mi(e)?{type:it.Quantity,value:e}:xt(e)?{type:e.resourceType,value:e}:{type:it.BackboneElement,value:e}}function ii(e){return 0!==e.length&&!!e[0].value}function ri(e,t){if(!e?.value)return;const n=vt(e.type,t);if(n){const i=function(e,t,n){const i=n.type;if(!i||0===i.length)return;let r,o="undefined";if(1===i.length)r=e.value[t],o=i[0].code;else for(const n of i){const i=t.replace("[x]","")+Z(n.code);if(i in e.value){r=e.value[i],o=n.code;break}}if(F(r))return;"Element"!==o&&"BackboneElement"!==o||(o=lt(n.path?.split(".")));return Array.isArray(r)?r.map((e=>oi(e,o))):oi(r,o)}(e,t,n);if(i)return i}return function(e,t){const n=e.value;if(!n||"object"!=typeof n)return;let i;if(t in n)i=n[t];else for(const e in it){const r=t+Z(e);if(r in n){i=n[r];break}}if(F(i))return;return Array.isArray(i)?i.map(ni):ni(i)}(e,t)}function oi(e,t){return"Resource"===t&&xt(e)&&(t=e.resourceType),{type:t,value:e}}function si(e){const t=[];for(const n of e){let e=!1;for(const i of t)if(ii(ui(n,i))){e=!0;break}e||t.push(n)}return t}function ai(e){return ti(!ii(e))}function ci(e,t){return 0===e.length||0===t.length?[]:e.length!==t.length?ti(!1):ti(e.every(((e,n)=>ii(ui(e,t[n])))))}function ui(e,t){const n=e.value,i=t.value;return"number"==typeof n&&"number"==typeof i?ti(Math.abs(n-i)<1e-8):mi(n)&&mi(i)?ti(yi(n,i)):ti("object"==typeof n&&"object"==typeof i?gi(e,t):n===i)}function li(e,t){return 0===e.length&&0===t.length?ti(!0):e.length!==t.length?ti(!1):(e.sort(pi),t.sort(pi),ti(e.every(((e,n)=>ii(di(e,t[n]))))))}function di(e,t){const n=e.value,i=t.value;return"number"==typeof n&&"number"==typeof i?ti(Math.abs(n-i)<.01):mi(n)&&mi(i)?ti(yi(n,i)):ti("object"==typeof n&&"object"==typeof i?gi(n,i):"string"==typeof n&&"string"==typeof i?n.toLowerCase()===i.toLowerCase():n===i)}function pi(e,t){const n=e.value,i=t.value;return"number"==typeof n&&"number"==typeof i?n-i:"string"==typeof n&&"string"==typeof i?n.localeCompare(i):0}function hi(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 fi(n);case"Quantity":return mi(n);default:return"object"==typeof n&&n?.resourceType===t}}function fi(e){return!(!e||"object"!=typeof e||!("start"in e))}function mi(e){return!(!e||"object"!=typeof e||!("value"in e)||"number"!=typeof e.value)}function yi(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 gi(e,t){const n=Object.keys(e),i=Object.keys(t);if(n.length!==i.length)return!1;for(const i of n){const n=e[i],r=t[i];if(vi(n)&&vi(r)){if(!gi(n,r))return!1}else if(n!==r)return!1}return!0}function vi(e){return null!==e&&"object"==typeof e}wn=new WeakMap,Sn=new WeakMap,bn=new WeakMap,En=new WeakMap,Tn=new WeakMap,Dn=new WeakMap,kn=new WeakMap,Cn=new WeakMap,xn=new WeakSet,An=function(){return e(this,Dn,"f").slice(-1)[0]},Pn=function(){e(this,xn,"m",Fn).call(this);const t=e(this,xn,"m",Rn).call(this);return e(this,xn,"m",Hn).call(this),t},Rn=function(){e(this,xn,"m",Mn).call(this);const t=e(this,xn,"m",Qn).call(this);if(!t)return;e(this,xn,"m",Fn).call(this);const n=e(this,xn,"m",qn).call(this);return"/"===t&&"*"===n?e(this,xn,"m",In).call(this):"/"===t&&"/"===n?e(this,xn,"m",Un).call(this):"'"===t||'"'===t?e(this,xn,"m",On).call(this,t):"`"===t?e(this,xn,"m",Ln).call(this):"@"===t?e(this,xn,"m",_n).call(this):t.match(/\d/)?e(this,xn,"m",Nn).call(this):t.match(/\w/)||"$"===t&&n.match(/\w/)?e(this,xn,"m",jn).call(this):e(this,xn,"m",Wn).call(this)},Mn=function(){e(this,xn,"m",$n).call(this,(()=>e(this,xn,"m",Qn).call(this).match(/\s/)))},In=function(){const t=e(this,kn,"f").index;return e(this,xn,"m",$n).call(this,(()=>"*"!==e(this,xn,"m",Qn).call(this)||"/"!==e(this,xn,"m",qn).call(this))),e(this,xn,"m",zn).call(this),e(this,xn,"m",zn).call(this),e(this,xn,"m",Gn).call(this,"Comment",e(this,wn,"f").substring(t,e(this,kn,"f").index))},Un=function(){return e(this,xn,"m",Gn).call(this,"Comment",e(this,xn,"m",$n).call(this,(()=>"\n"!==e(this,xn,"m",Qn).call(this))))},On=function(t){e(this,xn,"m",zn).call(this);const n=e(this,xn,"m",Gn).call(this,"String",e(this,xn,"m",$n).call(this,(()=>"\\"===e(this,xn,"m",Bn).call(this)||e(this,xn,"m",Qn).call(this)!==t)));return e(this,xn,"m",zn).call(this),n},Ln=function(){e(this,xn,"m",zn).call(this);const t=e(this,xn,"m",Gn).call(this,"Symbol",e(this,xn,"m",$n).call(this,(()=>"`"!==e(this,xn,"m",Qn).call(this))));return e(this,xn,"m",zn).call(this),t},_n=function(){e(this,xn,"m",zn).call(this);const t=e(this,kn,"f").index;return e(this,xn,"m",$n).call(this,(()=>e(this,xn,"m",Qn).call(this).match(/[\d-]/))),"T"===e(this,xn,"m",Qn).call(this)&&(e(this,xn,"m",zn).call(this),e(this,xn,"m",$n).call(this,(()=>e(this,xn,"m",Qn).call(this).match(/[\d:]/))),"."===e(this,xn,"m",Qn).call(this)&&e(this,xn,"m",qn).call(this).match(/\d/)&&(e(this,xn,"m",zn).call(this),e(this,xn,"m",$n).call(this,(()=>e(this,xn,"m",Qn).call(this).match(/\d/)))),"Z"===e(this,xn,"m",Qn).call(this)?e(this,xn,"m",zn).call(this):"+"!==e(this,xn,"m",Qn).call(this)&&"-"!==e(this,xn,"m",Qn).call(this)||(e(this,xn,"m",zn).call(this),e(this,xn,"m",$n).call(this,(()=>e(this,xn,"m",Qn).call(this).match(/[\d:]/))))),e(this,xn,"m",Gn).call(this,"DateTime",e(this,wn,"f").substring(t,e(this,kn,"f").index))},Nn=function(){const t=e(this,kn,"f").index;let n="Number";return e(this,xn,"m",$n).call(this,(()=>e(this,xn,"m",Qn).call(this).match(/\d/))),"."===e(this,xn,"m",Qn).call(this)&&e(this,xn,"m",qn).call(this).match(/\d/)&&(e(this,xn,"m",zn).call(this),e(this,xn,"m",$n).call(this,(()=>e(this,xn,"m",Qn).call(this).match(/\d/)))),"-"===e(this,xn,"m",Qn).call(this)&&e(this,En,"f")?(e(this,kn,"f").index=t-1,e(this,xn,"m",_n).call(this)):(" "===e(this,xn,"m",Qn).call(this)&&function(e){if(e){if("String"===e.id)return!0;if("Symbol"===e.id&&Kn.includes(e.value))return!0}return!1}(e(this,xn,"m",Pn).call(this))&&(n="Quantity",e(this,xn,"m",Rn).call(this)),e(this,xn,"m",Gn).call(this,n,e(this,wn,"f").substring(t,e(this,kn,"f").index)))},jn=function(){const t=e(this,xn,"m",$n).call(this,(()=>e(this,xn,"m",Qn).call(this).match(e(this,Tn,"f"))));return"."!==e(this,xn,"m",An).call(this)?.value&&e(this,Sn,"f").includes(t)?e(this,xn,"m",Gn).call(this,t,t):e(this,xn,"m",Gn).call(this,"Symbol",t)},Wn=function(){const t=e(this,xn,"m",Qn).call(this),n=t+e(this,xn,"m",qn).call(this);return e(this,bn,"f").includes(n)?(e(this,xn,"m",zn).call(this),e(this,xn,"m",zn).call(this),e(this,xn,"m",Gn).call(this,n,n)):(e(this,xn,"m",zn).call(this),e(this,xn,"m",Gn).call(this,t,t))},$n=function(t){const n=e(this,kn,"f").index;for(;e(this,kn,"f").index<e(this,wn,"f").length&&t();)e(this,xn,"m",zn).call(this);return e(this,wn,"f").substring(n,e(this,kn,"f").index)},Qn=function(){return e(this,wn,"f")[e(this,kn,"f").index]},Bn=function(){return e(this,wn,"f")[e(this,kn,"f").index-1]??""},qn=function(){return e(this,wn,"f")[e(this,kn,"f").index+1]??""},Fn=function(){e(this,Cn,"f").push({...e(this,kn,"f")})},Hn=function(){const t=e(this,Cn,"f").pop();if(!t)throw new Error("No mark to reset to");e(this,kn,"f").index=t.index,e(this,kn,"f").line=t.line,e(this,kn,"f").column=t.column},zn=function(){e(this,kn,"f").index++,"\n"===e(this,xn,"m",Qn).call(this)?(e(this,kn,"f").line++,e(this,kn,"f").column=0):e(this,kn,"f").column++},Gn=function(t,n){const i=e(this,Cn,"f").pop();if(!i)throw new Error("No mark for token");return{id:t,value:n,...i}};const xi=()=>[],wi={empty:e=>ti(0===e.length),exists:(e,t)=>ti(t?e.filter((e=>ii(t.eval([e])))).length>0:e.length>0),all:(e,t)=>ti(e.every((e=>ii(t.eval([e]))))),allTrue:e=>{for(const t of e)if(!t.value)return ti(!1);return ti(!0)},anyTrue:e=>{for(const t of e)if(t.value)return ti(!0);return ti(!1)},allFalse:e=>{for(const t of e)if(t.value)return ti(!1);return ti(!0)},anyFalse:e=>{for(const t of e)if(!t.value)return ti(!0);return ti(!1)},subsetOf:xi,supersetOf:xi,count:e=>[{type:it.integer,value:e.length}],distinct:e=>{const t=[];for(const n of e)t.some((e=>e.value===n.value))||t.push(n);return t},isDistinct:e=>ti(e.length===wi.distinct(e).length),where:(e,t)=>e.filter((e=>ii(t.eval([e])))),select:(e,t)=>e.map((e=>t.eval([e]))).flat(),repeat:xi,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 n=t.eval(e)[0]?.value;if("number"!=typeof n)throw new Error("Expected a number for skip(num)");return n>=e.length?[]:n<=0?e:e.slice(n,e.length)},take:(e,t)=>{const n=t.eval(e)[0]?.value;if("number"!=typeof n)throw new Error("Expected a number for take(num)");return n>=e.length?e:n<=0?[]:e.slice(0,n)},intersect:(e,t)=>{if(!t)return e;const n=t.eval(e),i=[];for(const t of e)!i.some((e=>e.value===t.value))&&n.some((e=>e.value===t.value))&&i.push(t);return i},exclude:(e,t)=>{if(!t)return e;const n=t.eval(e),i=[];for(const t of e)n.some((e=>e.value===t.value))||i.push(t);return i},union:(e,t)=>{if(!t)return e;const n=t.eval(e);return si([...e,...n])},combine:(e,t)=>{if(!t)return e;const n=t.eval(e);return[...e,...n]},iif:(e,t,n,i)=>{const r=t.eval(e);if(r.length>1||1===r.length&&"boolean"!=typeof r[0].value)throw new Error("Expected criterion to evaluate to a Boolean");return ii(r)?n.eval(e):i?i.eval(e):[]},toBoolean:e=>{if(0===e.length)return[];const[{value:t}]=Ei(e,1);if("boolean"==typeof t)return[{type:it.boolean,value:t}];if("number"==typeof t&&(0===t||1===t))return ti(!!t);if("string"==typeof t){const e=t.toLowerCase();if(["true","t","yes","y","1","1.0"].includes(e))return ti(!0);if(["false","f","no","n","0","0.0"].includes(e))return ti(!1)}return[]},convertsToBoolean:e=>0===e.length?[]:ti(1===wi.toBoolean(e).length),toInteger:e=>{if(0===e.length)return[];const[{value:t}]=Ei(e,1);return"number"==typeof t?[{type:it.integer,value:t}]:"string"==typeof t&&t.match(/^[+-]?\d+$/)?[{type:it.integer,value:parseInt(t,10)}]:"boolean"==typeof t?[{type:it.integer,value:t?1:0}]:[]},convertsToInteger:e=>0===e.length?[]:ti(1===wi.toInteger(e).length),toDate:e=>{if(0===e.length)return[];const[{value:t}]=Ei(e,1);return"string"==typeof t&&t.match(/^\d{4}(-\d{2}(-\d{2})?)?/)?[{type:it.date,value:ei(t)}]:[]},convertsToDate:e=>0===e.length?[]:ti(1===wi.toDate(e).length),toDateTime:e=>{if(0===e.length)return[];const[{value:t}]=Ei(e,1);return"string"==typeof t&&t.match(/^\d{4}(-\d{2}(-\d{2})?)?/)?[{type:it.dateTime,value:ei(t)}]:[]},convertsToDateTime:e=>0===e.length?[]:ti(1===wi.toDateTime(e).length),toDecimal:e=>{if(0===e.length)return[];const[{value:t}]=Ei(e,1);return"number"==typeof t?[{type:it.decimal,value:t}]:"string"==typeof t&&t.match(/^-?\d{1,9}(\.\d{1,9})?$/)?[{type:it.decimal,value:parseFloat(t)}]:"boolean"==typeof t?[{type:it.decimal,value:t?1:0}]:[]},convertsToDecimal:e=>0===e.length?[]:ti(1===wi.toDecimal(e).length),toQuantity:e=>{if(0===e.length)return[];const[{value:t}]=Ei(e,1);return mi(t)?[{type:it.Quantity,value:t}]:"number"==typeof t?[{type:it.Quantity,value:{value:t,unit:"1"}}]:"string"==typeof t&&t.match(/^-?\d{1,9}(\.\d{1,9})?/)?[{type:it.Quantity,value:{value:parseFloat(t),unit:"1"}}]:"boolean"==typeof t?[{type:it.Quantity,value:{value:t?1:0,unit:"1"}}]:[]},convertsToQuantity:e=>0===e.length?[]:ti(1===wi.toQuantity(e).length),toString:e=>{if(0===e.length)return[];const[{value:t}]=Ei(e,1);return null==t?[]:mi(t)?[{type:it.string,value:`${t.value} '${t.unit}'`}]:[{type:it.string,value:t.toString()}]},convertsToString:e=>0===e.length?[]:ti(1===wi.toString(e).length),toTime:e=>{if(0===e.length)return[];const[{value:t}]=Ei(e,1);if("string"==typeof t){const e=t.match(/^T?(\d{2}(:\d{2}(:\d{2})?)?)/);if(e)return[{type:it.time,value:ei("T"+e[1])}]}return[]},convertsToTime:e=>0===e.length?[]:ti(1===wi.toTime(e).length),indexOf:(e,t)=>Si(((e,t)=>e.indexOf(t)),e,t),substring:(e,t,n)=>Si(((e,t,n)=>{const i=t,r=n?i+n:e.length;return i<0||i>=e.length?void 0:e.substring(i,r)}),e,t,n),startsWith:(e,t)=>Si(((e,t)=>e.startsWith(t)),e,t),endsWith:(e,t)=>Si(((e,t)=>e.endsWith(t)),e,t),contains:(e,t)=>Si(((e,t)=>e.includes(t)),e,t),upper:e=>Si((e=>e.toUpperCase()),e),lower:e=>Si((e=>e.toLowerCase()),e),replace:(e,t,n)=>Si(((e,t,n)=>e.replaceAll(t,n)),e,t,n),matches:(e,t)=>Si(((e,t)=>!!e.match(t)),e,t),replaceMatches:(e,t,n)=>Si(((e,t,n)=>e.replaceAll(t,n)),e,t,n),length:e=>Si((e=>e.length),e),toChars:e=>Si((e=>e?e.split(""):void 0),e),abs:e=>bi(Math.abs,e),ceiling:e=>bi(Math.ceil,e),exp:e=>bi(Math.exp,e),floor:e=>bi(Math.floor,e),ln:e=>bi(Math.log,e),log:(e,t)=>bi(((e,t)=>Math.log(e)/Math.log(t)),e,t),power:(e,t)=>bi(Math.pow,e,t),round:e=>bi(Math.round,e),sqrt:e=>bi(Math.sqrt,e),truncate:e=>bi((e=>0|e),e),children:xi,descendants:xi,trace:(e,t)=>(console.log("trace",e,t),e),now:()=>[{type:it.dateTime,value:(new Date).toISOString()}],timeOfDay:()=>[{type:it.time,value:(new Date).toISOString().substring(11)}],today:()=>[{type:it.date,value:(new Date).toISOString().substring(0,10)}],between:(e,t,n,i)=>{const r=wi.toDateTime(t.eval(e));if(0===r.length)throw new Error("Invalid start date");const o=wi.toDateTime(n.eval(e));if(0===o.length)throw new Error("Invalid end date");const s=i.eval(e)[0]?.value;if("years"!==s&&"months"!==s&&"days"!==s)throw new Error("Invalid units");const a=L(r[0].value,o[0].value);return[{type:it.Quantity,value:{value:a[s],unit:s}}]},is:(e,t)=>{let n="";return t instanceof Ai?n=t.name:t instanceof _i&&(n=t.left.name+"."+t.right.name),n?e.map((e=>({type:it.boolean,value:hi(e,n)}))):[]},not:e=>wi.toBoolean(e).map((e=>({type:it.boolean,value:!e.value}))),resolve:e=>e.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 ni(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:it.BackboneElement,value:void 0}})).filter((e=>!!e.value)),as:e=>e,type:e=>e.map((({value:e})=>"boolean"==typeof e?{type:it.BackboneElement,value:{namespace:"System",name:"Boolean"}}:"number"==typeof e?{type:it.BackboneElement,value:{namespace:"System",name:"Integer"}}:xt(e)?{type:it.BackboneElement,value:{namespace:"FHIR",name:e.resourceType}}:{type:it.BackboneElement,value:null})),conformsTo:(e,t)=>{const n=t.eval(e)[0].value;if(!n.startsWith("http://hl7.org/fhir/StructureDefinition/"))throw new Error("Expected a StructureDefinition URL");const i=n.replace("http://hl7.org/fhir/StructureDefinition/","");return e.map((e=>({type:it.boolean,value:e.value?.resourceType===i})))}};function Si(e,t,...n){if(0===t.length)return[];const[{value:i}]=Ei(t,1);if("string"!=typeof i)throw new Error("String function cannot be called with non-string");const r=e(i,...n.map((e=>e&&e.eval(t)?.[0]?.value)));return void 0===r?[]:Array.isArray(r)?r.map(ni):[ni(r)]}function bi(e,t,...n){if(0===t.length)return[];const[{value:i}]=Ei(t,1),r=mi(i),o=r?i.value:i;if("number"!=typeof o)throw new Error("Math function cannot be called with non-number");const s=e(o,...n.map((e=>e.eval(t)?.[0]?.value)));return[{type:r?it.Quantity:t[0].type,value:r?{...i,value:s}:s}]}function Ei(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}var Ti,Di;class ki{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 Ci{constructor(e){this.value=e}eval(){return[this.value]}toString(){const e=this.value.value;return"string"==typeof e?`'${e}'`:e.toString()}}class Ai{constructor(e){Ti.add(this),this.name=e}eval(t){return"$this"===this.name?t:t.map((t=>e(this,Ti,"m",Di).call(this,t))).flat().filter((e=>void 0!==e?.value))}toString(){return this.name}}Ti=new WeakSet,Di=function(e){const t=e.value;if(t&&"object"==typeof t)return xt(t)&&t.resourceType===this.name?e:ri(e,this.name)};class Pi{eval(){return[]}toString(){return"{}"}}class Ri extends Vn{constructor(e,t,n){super(e,t),this.impl=n}eval(e){return this.impl(this.child.eval(e))}toString(){return this.child.toString()}}class Mi extends Xn{constructor(e,t){super("as",e,t)}eval(e){return wi.ofType(this.left.eval(e),this.right)}}class Ii extends Xn{constructor(e,t,n,i){super(e,t,n),this.impl=i}eval(e){const t=this.left.eval(e);if(1!==t.length)return[];const n=this.right.eval(e);if(1!==n.length)return[];const i=t[0].value,r=n[0].value,o=mi(i)?i.value:i,s=mi(r)?r.value:r,a=this.impl(o,s);return"boolean"==typeof a?ti(a):mi(i)?[{type:it.Quantity,value:{...i,value:a}}]:[ni(a)]}}class Ui extends Xn{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:it.string,value:t.map((e=>e.value)).join("")}]:t}}class Oi extends Xn{constructor(e,t){super("contains",e,t)}eval(e){const t=this.left.eval(e),n=this.right.eval(e);return ti(t.some((e=>e.value===n[0].value)))}}class Li extends Xn{constructor(e,t){super("in",e,t)}eval(e){const t=this.left.eval(e);return ti(this.right.eval(e).some((e=>e.value===t[0].value)))}}class _i extends Xn{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 Ni extends Xn{constructor(e,t){super("|",e,t)}eval(e){return si([...this.left.eval(e),...this.right.eval(e)])}}class ji extends Xn{constructor(e,t){super("=",e,t)}eval(e){return ci(this.left.eval(e),this.right.eval(e))}}class Wi extends Xn{constructor(e,t){super("!=",e,t)}eval(e){return ai(ci(this.left.eval(e),this.right.eval(e)))}}class $i extends Xn{constructor(e,t){super("~",e,t)}eval(e){return li(this.left.eval(e),this.right.eval(e))}}class Qi extends Xn{constructor(e,t){super("!~",e,t)}eval(e){return ai(li(this.left.eval(e),this.right.eval(e)))}}class Bi extends Xn{constructor(e,t){super("is",e,t)}eval(e){const t=this.left.eval(e);if(1!==t.length)return[];const n=this.right.name;return ti(hi(t[0],n))}}class qi extends Xn{constructor(e,t){super("and",e,t)}eval(e){const t=this.left.eval(e),n=this.right.eval(e);return!0===t[0]?.value&&!0===n[0]?.value?ti(!0):!1===t[0]?.value||!1===n[0]?.value?ti(!1):[]}}class Fi extends Xn{constructor(e,t){super("or",e,t)}eval(e){const t=this.left.eval(e);if(ii(t))return t;const n=this.right.eval(e);return ii(n)?n:[]}}class Hi extends Xn{constructor(e,t){super("xor",e,t)}eval(e){const t=this.left.eval(e),n=this.right.eval(e);if(0===t.length&&0===n.length)return[];const i=0===t.length?null:t[0].value,r=0===n.length?null:n[0].value;return!0===i&&!0!==r||!0!==i&&!0===r?ti(!0):!0===i&&!0===r||!1===i&&!1===r?ti(!1):[]}}class zi{constructor(e,t){this.name=e,this.args=t}eval(e){const t=wi[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 Gi{constructor(e,t){this.left=e,this.expr=t}eval(e){const t=this.expr.eval(e);if(1!==t.length)return[];const n=t[0].value;if("number"!=typeof n)throw new Error("Invalid indexer expression: should return integer}");const i=this.left.eval(e);return n in i?[i[n]]:[]}toString(){return`${this.left.toString()}[${this.expr.toString()}]`}}const Vi=["true","false"],Xi=["!=","!~","<=",">=","{}","->"];function Ji(e){return new Zn(e,Vi,Xi).tokenize()}const Yi={parse(e){const t=e.consumeAndParse();if(!e.match(")"))throw new Error("Parse error: expected `)` got `"+e.peek()?.value+"`");return t}},Ki={parse(e,t){const n=e.consumeAndParse();if(!e.match("]"))throw new Error("Parse error: expected `]`");return new Gi(t,n)},precedence:2},Zi={parse(e,t){if(!(t instanceof Ai))throw new Error("Unexpected parentheses");const n=[];for(;!e.match(")");)n.push(e.consumeAndParse()),e.match(",");return new zi(t.name,n)},precedence:0};function er(e){const t=e.split(" "),n=parseFloat(t[0]);let i=t[1];return i=i&&i.startsWith("'")&&i.endsWith("'")?i.substring(1,i.length-1):"{"+i+"}",{value:n,unit:i}}function tr(){return(new Jn).registerPrefix("String",{parse:(e,t)=>new Ci({type:it.string,value:t.value})}).registerPrefix("DateTime",{parse:(e,t)=>new Ci({type:it.dateTime,value:ei(t.value)})}).registerPrefix("Quantity",{parse:(e,t)=>new Ci({type:it.Quantity,value:er(t.value)})}).registerPrefix("Number",{parse:(e,t)=>new Ci({type:it.decimal,value:parseFloat(t.value)})}).registerPrefix("true",{parse:()=>new Ci({type:it.boolean,value:!0})}).registerPrefix("false",{parse:()=>new Ci({type:it.boolean,value:!1})}).registerPrefix("Symbol",{parse:(e,t)=>new Ai(t.value)}).registerPrefix("{}",{parse:()=>new Pi}).registerPrefix("(",Yi).registerInfix("[",Ki).registerInfix("(",Zi).prefix("+",3,((e,t)=>new Ri("+",t,(e=>e)))).prefix("-",3,((e,t)=>new Ii("-",t,t,((e,t)=>-t)))).infixLeft(".",1,((e,t,n)=>new _i(e,n))).infixLeft("/",4,((e,t,n)=>new Ii("/",e,n,((e,t)=>e/t)))).infixLeft("*",4,((e,t,n)=>new Ii("*",e,n,((e,t)=>e*t)))).infixLeft("+",5,((e,t,n)=>new Ii("+",e,n,((e,t)=>e+t)))).infixLeft("-",5,((e,t,n)=>new Ii("-",e,n,((e,t)=>e-t)))).infixLeft("|",7,((e,t,n)=>new Ni(e,n))).infixLeft("=",9,((e,t,n)=>new ji(e,n))).infixLeft("!=",9,((e,t,n)=>new Wi(e,n))).infixLeft("~",9,((e,t,n)=>new $i(e,n))).infixLeft("!~",9,((e,t,n)=>new Qi(e,n))).infixLeft("<",8,((e,t,n)=>new Ii("<",e,n,((e,t)=>e<t)))).infixLeft("<=",8,((e,t,n)=>new Ii("<=",e,n,((e,t)=>e<=t)))).infixLeft(">",8,((e,t,n)=>new Ii(">",e,n,((e,t)=>e>t)))).infixLeft(">=",8,((e,t,n)=>new Ii(">=",e,n,((e,t)=>e>=t)))).infixLeft("&",5,((e,t,n)=>new Ui(e,n))).infixLeft("and",6,((e,t,n)=>new qi(e,n))).infixLeft("as",6,((e,t,n)=>new Mi(e,n))).infixLeft("contains",6,((e,t,n)=>new Oi(e,n))).infixLeft("div",6,((e,t,n)=>new Ii("div",e,n,((e,t)=>e/t|0)))).infixLeft("in",6,((e,t,n)=>new Li(e,n))).infixLeft("is",6,((e,t,n)=>new Bi(e,n))).infixLeft("mod",6,((e,t,n)=>new Ii("mod",e,n,((e,t)=>e%t)))).infixLeft("or",6,((e,t,n)=>new Fi(e,n))).infixLeft("xor",6,((e,t,n)=>new Hi(e,n)))}const nr=tr();function ir(e){return new ki(e,nr.construct(Ji(e)).consumeAndParse())}function rr(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]=ni(n[e]))}return or(e,n).map((e=>e.value))}function or(e,t){return ir(e).eval(t)}const sr=[...Xi,"->","<<",">>"];var ar,cr,ur,lr,dr,pr,hr,fr,mr,yr,gr,vr,xr,wr,Sr,br,Er,Tr,Dr;class kr{constructor(e){ar.add(this),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 t=this.parser.peek()?.value;switch(t){case"uses":e(this,ar,"m",cr).call(this);break;case"imports":e(this,ar,"m",ur).call(this);break;case"group":e(this,ar,"m",lr).call(this);break;case"conceptmap":e(this,ar,"m",Dr).call(this);break;default:throw new Error(`Unexpected token: ${t}`)}}return this.structureMap}}ar=new WeakSet,cr=function(){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)},ur=function(){this.parser.consume("Symbol","imports"),this.structureMap.import||(this.structureMap.import=[]),this.structureMap.import.push(this.parser.consume("String").value)},lr=function(){const t={};this.parser.consume("Symbol","group"),t.name=this.parser.consume("Symbol").value,t.input=e(this,ar,"m",dr).call(this),"extends"===this.parser.peek()?.value&&(this.parser.consume("Symbol","extends"),t.extends=this.parser.consume("Symbol").value),"<<"===this.parser.peek()?.value?(this.parser.consume("<<"),t.typeMode=this.parser.consume().value,"+"===this.parser.peek()?.value&&(this.parser.consume("+"),t.typeMode="type-and-types"),this.parser.consume(">>")):t.typeMode="none",t.rule=e(this,ar,"m",hr).call(this),this.structureMap.group||(this.structureMap.group=[]),this.structureMap.group.push(t)},dr=function(){const t=[];for(this.parser.consume("(");this.parser.hasMore()&&")"!==this.parser.peek()?.value;)t.push(e(this,ar,"m",pr).call(this)),","===this.parser.peek()?.value&&this.parser.consume(",");return this.parser.consume(")"),t},pr=function(){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},hr=function(){const t=[];for(this.parser.consume("{");this.parser.hasMore()&&"}"!==this.parser.peek()?.value;)t.push(e(this,ar,"m",fr).call(this));return this.parser.consume("}"),t},fr=function(){const t={source:e(this,ar,"m",mr).call(this)};return"->"===this.parser.peek()?.value&&(this.parser.consume("->"),t.target=e(this,ar,"m",gr).call(this)),"then"===this.parser.peek()?.value&&(this.parser.consume("Symbol","then"),"{"===this.parser.peek()?.id?t.rule=e(this,ar,"m",hr).call(this):t.dependent=e(this,ar,"m",Tr).call(this)),"String"===this.parser.peek()?.id?t.name=this.parser.consume().value:t.name=t.source?.[0]?.element,this.parser.consume(";"),t},mr=function(){const t=[e(this,ar,"m",yr).call(this)];for(;this.parser.hasMore()&&","===this.parser.peek()?.value;)this.parser.consume(","),t.push(e(this,ar,"m",yr).call(this));return t},yr=function(){const t={},n=e(this,ar,"m",Er).call(this);if(n.includes(".")){const e=n.split(".");t.context=e[0],t.element=e[1]}else t.context=n;if(this.parser.hasMore()&&":"===this.parser.peek()?.value&&(this.parser.consume(":"),t.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||(t.listMode=this.parser.consume().value),"as"===this.parser.peek()?.value&&(this.parser.consume("Symbol","as"),t.variable=this.parser.consume().value),"where"===this.parser.peek()?.value){this.parser.consume("Symbol","where");const e=this.parser.consumeAndParse(100);t.condition=e.toString()}if("check"===this.parser.peek()?.value){this.parser.consume("Symbol","check");const e=this.parser.consumeAndParse(100);t.check=e.toString()}return t},gr=function(){const t=[e(this,ar,"m",vr).call(this)];for(;this.parser.hasMore()&&","===this.parser.peek()?.value;)this.parser.consume(","),t.push(e(this,ar,"m",vr).call(this));return t},vr=function(){const t={},n=e(this,ar,"m",Er).call(this);if(n.includes(".")){const e=n.split(".");t.contextType="variable",t.context=e[0],t.element=e[1]}else t.context=n;return"="===this.parser.peek()?.value&&(this.parser.consume("="),e(this,ar,"m",xr).call(this,t)),"as"===this.parser.peek()?.value&&(this.parser.consume("Symbol","as"),t.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||(t.listMode=[this.parser.consume().value]),t},xr=function(t){t.transform="copy";const n=this.parser.consumeAndParse(6);if(n instanceof Ai)e(this,ar,"m",wr).call(this,t,n);else if(n instanceof zi)e(this,ar,"m",Sr).call(this,t,n);else{if(!(n instanceof Ci))throw new Error(`Unexpected FHIRPath: ${n}`);e(this,ar,"m",br).call(this,t,n)}},wr=function(e,t){e.parameter=[{valueId:t.name}]},Sr=function(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)}},br=function(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)}},Er=function(){let e=this.parser.consume().value;for(;"."===this.parser.peek()?.value;)this.parser.consume("."),e+="."+this.parser.consume().value;return e},Tr=function(){const e=this.parser.consumeAndParse(100);return[{name:e.name,variable:e.args.map((e=>e.name))}]},Dr=function(){for(;"}"!==this.parser.peek()?.value;)this.parser.consume();this.parser.consume("}")};const Cr=tr().registerInfix("->",{precedence:100}).registerInfix(";",{precedence:200});function Ar(e){const t=Cr.construct(new Zn(e,Vi,sr).tokenize());return t.removeComments(),new kr(t).parse()}const Pr=[...Xi,"eq","ne","co"];class Rr{constructor(e,t,n){this.path=e,this.operator=t,this.value=n}}class Mr{constructor(e){this.child=e}}class Ir{constructor(e,t,n){this.keyword=e,this.left=t,this.right=n}}class Ur{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 Mr(this.parse()),this.parser.consume(")")):e=new Rr(this.parser.consume("Symbol").value,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 Ir(t,e,this.parse())):e}}const Or=tr();function Lr(e){const t=Or.construct(new Zn(e,Vi,Pr,{dateTimeLiterals:!0,symbolRegex:/[^\s\])]/}).tokenize());return t.removeComments(),new Ur(t).parse()}class _r{constructor(e="\r",t="|",n="^",i="~",r="\\",o="&"){this.segmentSeparator=e,this.fieldSeparator=t,this.componentSeparator=n,this.repetitionSeparator=i,this.escapeCharacter=r,this.subcomponentSeparator=o}getMsh2(){return this.fieldSeparator+this.componentSeparator+this.repetitionSeparator+this.escapeCharacter+this.subcomponentSeparator}}class Nr{constructor(e,t=new _r){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()||"",i=t?.get(3)?.toString()||"",r=t?.get(4)?.toString()||"",o=t?.get(5)?.toString()||"",s=t?.get(9)?.toString()||"",a=t?.get(12)?.toString()||"2.5.1";return new Nr([new jr(["MSH",this.context.getMsh2(),r,o,n,i,e.toISOString(),"","ACK",e.getTime().toString(),"P",a],this.context),new jr(["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 _r("\r",e.charAt(3),e.charAt(4),e.charAt(5),e.charAt(6),e.charAt(7));return new Nr(e.split(/[\r\n]+/).map((e=>jr.parse(e,t))),t)}}class jr{constructor(e,t=new _r){this.context=t,X(e)?this.fields=e.map((e=>Wr.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 _r){return new jr(e.split(t.fieldSeparator).map((e=>Wr.parse(e,t))),t)}}class Wr{constructor(e,t=new _r){this.context=t,this.components=e}get(e,t,n=0){let i=this.components[n][e]||"";return void 0!==t&&(i=i.split(this.context.subcomponentSeparator)[t]||""),i}toString(){return this.components.map((e=>e.join(this.context.componentSeparator))).join(this.context.repetitionSeparator)}static parse(e,t=new _r){return new Wr(e.split(t.repetitionSeparator).map((e=>e.split(t.componentSeparator))),t)}}var $r,Qr,Br,qr,Fr,Hr,zr,Gr,Vr,Xr,Jr,Yr,Kr,Zr;const eo={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"},to=new Set(["resourceType","id","meta","implicitRules","language","text","contained","extension","modifierExtension"]);function no(e){const t=St.types[e];return t&&t.structureDefinition.id===e&&"resource"===t.structureDefinition.kind}function io(e){if(!e)throw new qe(_e("Resource type is null"));if(!no(e))throw new qe(_e("Unknown resource type"))}function ro(e){new oo(e).validate()}class oo{constructor(e){$r.add(this),Qr.set(this,void 0),Br.set(this,void 0),t(this,Qr,[],"f"),t(this,Br,e,"f")}validate(){const t=e(this,Br,"f");if(!t)throw new qe(_e("Resource is null"));const n=t.resourceType;if(!n)throw new qe(_e("Missing resource type"));if(so(t,"",e(this,Qr,"f")),e(this,$r,"m",qr).call(this,ni(t),n),e(this,Qr,"f").length>0)throw new qe({resourceType:"OperationOutcome",issue:e(this,Qr,"f")})}}function so(e,t,n){null===e?n.push(ao(t,"Invalid null value")):Array.isArray(e)?function(e,t,n){for(let i=0;i<e.length;i++)void 0===e[i]?n.push(ao(`${t}[${i}]`,"Invalid undefined value")):so(e[i],`${t}[${i}]`,n)}(e,t,n):"object"==typeof e&&function(e,t,n){for(const[i,r]of Object.entries(e))so(r,`${t}${t?".":""}${i}`,n)}(e,t,n)}function ao(e,t){return{severity:"error",code:"structure",details:{text:t},expression:[e]}}var co;function uo(e,t){let n=St.types[e]?.searchParamsDetails?.[t.code];return n||(n=function(e,t){const n=t.code,i=function(e){return e.split("-").reduce(((e,t,n)=>e+(n?Z(t):t)),"")}(n),r=ho(e,t.expression)?.split(".");if(!r)return{columnName:i,type:co.TEXT};const o=po(t);let s,a,c=e,u=!1;for(let n=1;n<r.length;n++){if(s=vt(c,r[n]),!s)throw new Error(`Element definition not found for ${e} ${t.code}`);if("*"===s.max&&(u=!0),a=s.type?.[0].code,!a)return{columnName:i,type:o,array:u};n<r.length-1&&(c=lo(a)?lt(s.path?.split(".")):a)}const l=po(t,a),d={columnName:i,type:l,elementDefinition:s,array:u};return function(e,t,n){const i=St.types[e];i.searchParamsDetails||(i.searchParamsDetails={});i.searchParamsDetails[t]=n}(e,n,d),d}(e,t)),n}function lo(e){return"Element"===e||"BackboneElement"===e}function po(e,t){let n=co.TEXT;switch(e.type){case"date":n=t===it.dateTime||t===it.instant?co.DATETIME:co.DATE;break;case"number":n=co.NUMBER;break;case"quantity":n=co.QUANTITY;break;case"reference":n=co.REFERENCE;break;case"token":"boolean"===t&&(n=co.BOOLEAN)}return n}function ho(e,t){const n=t.split(" | ");for(const t of n){if((i=t).includes(" as Period")||i.includes(" as SampledDate"))continue;const n=fo(t);if(n.startsWith(e+"."))return n}var i}function fo(e){let t=e.trim();t.startsWith("(")&&t.endsWith(")")&&(t=t.substring(1,t.length-1)),t.includes("[0]")&&(t=t.replaceAll("[0]",""));const n=[" != "," as ",".as(",".exists(",".resolve(",".where("];for(const e of n)t.includes(e)&&(t=t.substring(0,t.indexOf(e)));return t}Qr=new WeakMap,Br=new WeakMap,$r=new WeakSet,qr=function(t,n){const i=St.types[t.type];if(!i)throw new qe(_e("Unknown type: "+t.type));const r=i.properties;e(this,$r,"m",Fr).call(this,n,r,t),e(this,$r,"m",Jr).call(this,n,t,r)},Fr=function(t,n,i){for(const[r,o]of Object.entries(n))e(this,$r,"m",Hr).call(this,t+"."+r,o,i)},Hr=function(t,n,i){const r=ri(i,t.split(".").pop());if(F(r))void 0!==n.min&&n.min>0&&e(this,Qr,"f").push(ao(t,"Missing required property"));else if("*"===n.max){if(!Array.isArray(r))return void e(this,Qr,"f").push(ao(t,"Expected array for property"));for(const i of r)e(this,$r,"m",zr).call(this,t,n,i)}else{if(Array.isArray(r))return void e(this,Qr,"f").push(ao(t,"Expected single value for property"));e(this,$r,"m",zr).call(this,t,n,r)}},zr=function(t,n,i){null!==i.value&&(ee(i.type.charAt(0))?e(this,$r,"m",Gr).call(this,n,i):e(this,$r,"m",qr).call(this,i,t))},Gr=function(t,n){const{type:i,value:r}=n;if(null===r)return;const o=eo[n.type];typeof r===o?"string"===o?e(this,$r,"m",Vr).call(this,t,i,r):"number"===o&&e(this,$r,"m",Xr).call(this,t,i,r):e(this,$r,"m",Zr).call(this,t,"Invalid type for "+i)},Vr=function(t,n,i){if(!i.trim())return void e(this,$r,"m",Zr).call(this,t,"Invalid empty string");const r=St.types[n]?.properties?.value;if(r?.type){const o=$(r.type[0],"http://hl7.org/fhir/StructureDefinition/regex");o&&(i.match(new RegExp(o))||e(this,$r,"m",Zr).call(this,t,"Invalid "+n+" format"))}},Xr=function(t,n,i){var r;!isNaN(i)&&isFinite(i)?((r=n)!==it.integer&&r!==it.positiveInt&&r!==it.unsignedInt||Number.isInteger(i)||e(this,$r,"m",Zr).call(this,t,"Number is not an integer"),n===it.positiveInt&&i<=0&&e(this,$r,"m",Zr).call(this,t,"Number is less than or equal to zero"),n===it.unsignedInt&&i<0&&e(this,$r,"m",Zr).call(this,t,"Number is negative")):e(this,$r,"m",Zr).call(this,t,"Invalid "+n+" value")},Jr=function(t,n,i){const r=n.value;for(const o of Object.keys(r))e(this,$r,"m",Yr).call(this,t,o,n,i)},Yr=function(t,n,i,r){if(!(to.has(n)||n in r||function(e,t,n){for(const i of Object.keys(n)){if(!i.endsWith("[x]"))continue;const n=i.replace("[x]","");if(!e.startsWith(n))continue;let r=ri(t,i);if(r&&(Array.isArray(r)&&(r=r[0]),r&&e===n+Z(r.type)))return!0}return!1}(n,i,r)||e(this,$r,"m",Kr).call(this,t,n,i))){const i=`${t}.${n}`;e(this,Qr,"f").push(ao(i,`Invalid additional property "${i}"`))}},Kr=function(t,n,i){if(!n.startsWith("_"))return!1;return n.slice(1)in i.value&&(e(this,$r,"m",qr).call(this,{type:"Element",value:i.value[n]},t),!0)},Zr=function(t,n){e(this,Qr,"f").push(ao(t.path,n))},function(e){e.BOOLEAN="BOOLEAN",e.NUMBER="NUMBER",e.QUANTITY="QUANTITY",e.TEXT="TEXT",e.REFERENCE="REFERENCE",e.DATE="DATE",e.DATETIME="DATETIME",e.PERIOD="PERIOD",e.UUID="UUID"}(co||(co={}));const mo=20;var yo;!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"}(yo||(yo={}));const go={contains:yo.CONTAINS,exact:yo.EXACT,above:yo.ABOVE,below:yo.BELOW,text:yo.TEXT,not:yo.NOT,in:yo.IN,"not-in":yo.NOT_IN,"of-type":yo.OF_TYPE,missing:yo.MISSING,identifier:yo.IDENTIFIER},vo={eq:yo.EQUALS,ne:yo.NOT_EQUALS,lt:yo.LESS_THAN,le:yo.LESS_THAN_OR_EQUALS,gt:yo.GREATER_THAN,ge:yo.GREATER_THAN_OR_EQUALS,sa:yo.STARTS_AFTER,eb:yo.ENDS_BEFORE,ap:yo.APPROXIMATELY};function xo(e,t){return bo(e,t)}function wo(e){return bo(e.pathname.split("/").filter(Boolean).pop(),Object.fromEntries(e.searchParams.entries()))}function So(e){return wo(new URL(e,"https://example.com/"))}function bo(e,t){const n={resourceType:e};for(const[e,i]of Object.entries(t))Array.isArray(i)?i.forEach((t=>Eo(n,e,t))):Eo(n,e,i??"");return n}function Eo(e,t,n){let i,r;const o=t.indexOf(":");switch(o>=0?(i=t.substring(0,o),r=t.substring(o+1)):(i=t,r=""),i){case"_sort":!function(e,t){for(const n of t.split(",")){let t,i=!1;n.startsWith("-")?(t=n.substring(1),i=!0):t=n,e.sortRules||(e.sortRules=[]),e.sortRules.push({code:t,descending:i})}}(e,n);break;case"_count":e.count=parseInt(n);break;case"_offset":e.offset=parseInt(n);break;case"_total":e.total=n;break;case"_summary":e.total="estimate",e.count=0;break;case"_include":e.include=n;break;case"_revinclude":e.revInclude=n;break;case"_fields":e.fields=n.split(",");break;default:{const t=St.types[e.resourceType]?.searchParams?.[i];t?function(e,t,n,i){if("missing"===n)return void ko(e,{code:t.code,operator:yo.MISSING,value:i});switch(t.type){case"number":case"date":!function(e,t,n){const{operator:i,value:r}=To(n);ko(e,{code:t.code,operator:i,value:r})}(e,t,i);break;case"reference":case"string":case"token":case"uri":!function(e,t,n,i){ko(e,{code:t.code,operator:Do(n),value:i})}(e,t,n,i);break;case"quantity":!function(e,t,n){const[i,r,o]=n.split("|"),{operator:s,value:a}=To(i);ko(e,{code:t.code,operator:s,value:a,unitSystem:r,unitCode:o})}(e,t,i)}}(e,t,r,n):function(e,t,n,i){let r=yo.EQUALS;if(n)r=n;else if(i.length>=2){const e=i.substring(0,2);e in vo&&(2===i.length||i.at(2)?.match(/\d/))&&(r=e,i=i.substring(e.length))}ko(e,{code:t,operator:r,value:i})}(e,i,r,n)}}}function To(e){const t=e.substring(0,2),n=vo[t];return n?{operator:n,value:e.substring(2)}:{operator:yo.EQUALS,value:e}}function Do(e){return go[e]||yo.EQUALS}function ko(e,t){e.filters?e.filters.push(t):e.filters=[t]}function Co(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 go?":"+e.operator:"",n=e.operator!==yo.EQUALS&&e.operator in vo?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("&"))}function Ao(e,t){if(t.resourceType!==e.resourceType)return!1;if(t.filters)for(const n of t.filters)if(!Po(e,t,n))return!1;return!0}function Po(e,t,n){const i=St.types[t.resourceType]?.searchParams?.[n.code];switch(i?.type){case"reference":return function(e,t,n){const i=rr(n.expression,e),r=Uo(t.operator);if(""===t.value&&0===i.length)return t.operator===yo.EQUALS;const o=i.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!r}return r}(e,n,i);case"string":case"uri":return Ro(e,n,i);case"token":return function(e,t,n){const i=uo(e.resourceType,n);return i.type===co.BOOLEAN?function(e,t,n){const i=rr(n.expression,e),r="true"===t.value,o=i.includes(r);return Uo(t.operator)?!o:o}(e,t,n):Ro(e,t,n,!0)}(e,n,i);case"date":return function(e,t,n){const i=rr(n.expression,e),r=t.value.split(","),o=Uo(t.operator);for(const e of i)for(const n of r){if(Io(e,t.operator,n))return!o}return o}(e,n,i)}return!1}function Ro(e,t,n,i){const r=rr(n.expression,e),o=t.value.split(","),s=Uo(t.operator);for(const e of r)for(const n of o){if(Mo(e,t.operator,n,i))return!s}return s}function Mo(e,t,n,i){if(i&&n.includes("|")){const[i,r]=n.split("|");return Mo(e,t,i,!1)&&(!r||Mo(e,t,r,!1))}let r="";return e&&("string"==typeof e?r=e:"object"==typeof e&&(r=JSON.stringify(e))),r.toLowerCase().includes(n.toLowerCase())}function Io(e,t,n){switch(t){case yo.STARTS_AFTER:case yo.GREATER_THAN:return e>n;case yo.GREATER_THAN_OR_EQUALS:return e>=n;case yo.ENDS_BEFORE:case yo.LESS_THAN:return e<n;case yo.LESS_THAN_OR_EQUALS:return e<=n;case yo.EQUALS:case yo.NOT_EQUALS:return e===n}return!1}function Uo(e){return e===yo.NOT_EQUALS||e===yo.NOT}export{qi as AndAtom,Ii as ArithemticOperatorAtom,Mi as AsAtom,tt as ClientStorage,Ui as ConcatAtom,Oi as ContainsAtom,mo as DEFAULT_SEARCH_COUNT,_i as DotAtom,Pi as EmptySetAtom,ji as EqualsAtom,$i as EquivalentAtom,Vi as FHIRPATH_KEYWORDS,Xi as FHIRPATH_OPERATORS,Rr as FhirFilterComparison,Ir as FhirFilterConnective,Mr as FhirFilterNegation,ki as FhirPathAtom,oo as FhirSchemaValidator,zi as FunctionAtom,_r as Hl7Context,Wr as Hl7Field,Nr as Hl7Message,jr as Hl7Segment,Li as InAtom,Gi as IndexerAtom,Xn as InfixOperatorAtom,Bi as IsAtom,s as LRUCache,Ci as LiteralAtom,ln as MEDPLUM_VERSION,pn as MedplumClient,nt as MemoryStorage,Wi as NotEqualsAtom,Qi as NotEquivalentAtom,qe as OperationOutcomeError,yo as Operator,Fi as OrAtom,Yn as Parser,Jn as ParserBuilder,Vn as PrefixOperatorAtom,it as PropertyType,et as ReadablePromise,co as SearchParameterType,Ai as SymbolAtom,Zn as Tokenizer,Ri as UnaryOperatorAtom,Ni as UnionAtom,Hi as XorAtom,Ce as allOk,K as arrayBufferToBase64,Y as arrayBufferToHex,Be as assertOk,Le as badRequest,ti as booleanToTypedValue,lt as buildTypeName,L as calculateAge,_ as calculateAgeString,Z as capitalize,so as checkForNull,C as createReference,ao as createStructureIssue,Ae as created,z as deepClone,H as deepEquals,rr as evalFhirPath,or as evalFhirPathTyped,ci as fhirPathArrayEquals,li as fhirPathArrayEquivalent,ui as fhirPathEquals,di as fhirPathEquivalent,hi as fhirPathIs,ai as fhirPathNot,ie as findObservationInterval,re as findObservationReferenceRange,Ie as forbidden,a as formatAddress,E as formatCodeableConcept,T as formatCoding,p as formatDate,f as formatDateTime,l as formatFamilyName,u as formatGivenName,c as formatHumanName,b as formatMoney,D as formatObservationValue,m as formatPeriod,S as formatQuantity,w as formatRange,Co as formatSearchQuery,h as formatTime,x as formatTiming,te as getCodeBySystem,O as getDateProperty,M as getDisplayString,vt as getElementDefinition,ut as getElementDefinitionTypeName,ho as getExpressionForResourceType,Q as getExtension,$ as getExtensionValue,W as getIdentifier,I as getImageSrc,mt as getPropertyDisplayName,N as getQuestionnaireAnswers,A as getReferenceString,ht as getResourceTypeSchema,pt as getResourceTypes,uo as getSearchParameterDetails,ft as getSearchParameters,Qe as getStatus,ri as getTypedPropertyValue,St as globalSchema,Ue as gone,ct as indexSearchParameter,at as indexSearchParameterBundle,st as indexStructureDefinition,ot as indexStructureDefinitionBundle,tr as initFhirPathParserBuilder,F as isEmpty,$e as isGone,ee as isLowerCase,We as isNotFound,V as isObject,je as isOk,Ne as isOperationOutcome,fi as isPeriod,R as isProfileResource,mi as isQuantity,yi as isQuantityEquivalent,wt as isReference,xt as isResource,no as isResourceType,dt as isResourceTypeSchema,X as isStringArray,G as isUUID,d as isValidDate,se as matchesRange,Ao as matchesSearchRequest,He as normalizeErrorString,Fe as normalizeOperationOutcome,Re as notFound,Pe as notModified,ze as operationOutcomeToString,ir as parseFhirPath,Lr as parseFilterParameter,ve as parseJWTPayload,Ar as parseMappingLanguage,So as parseSearchDefinition,xo as parseSearchRequest,wo as parseSearchUrl,ce as preciseEquals,le as preciseGreaterThan,pe as preciseGreaterThanOrEquals,ue as preciseLessThan,de as preciseLessThanOrEquals,ae as preciseRound,si as removeDuplicates,P as resolveId,ne as setCodeBySystem,B as stringify,ii as toJsBoolean,ni as toTypedValue,Ji as tokenize,Oe as tooManyRequests,Me as unauthorized,ro as validateResource,io as validateResourceType,_e as validationError};
1
+ function e(e){for(const t of e.entry||[])delete t?.resource?.meta,t.fullUrl="urn:uuid:"+t?.resource?.id,delete t?.resource?.id;const r=e.entry,n=JSON.stringify({resourceType:"Bundle",type:"transaction",entry:r?.map((e=>({fullUrl:e.fullUrl,request:{method:"POST",url:e.resource.resourceType},resource:e.resource})))},t,2);return JSON.parse(n)}function t(e,t){return"reference"===e&&"string"==typeof t&&t.includes("/")?"urn:uuid:"+t.split("/")[1]:t}class r{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 n(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 i(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 o(e){const t=[];return e.given&&t.push(...e.given),t.join(" ").trim()}function s(e){return e.family||""}function a(e){return e instanceof Date&&!isNaN(e.getTime())}function c(e,t,r){if(!e)return"";const n=new Date(e);return a(n)?(n.setUTCHours(0,0,0,0),n.toLocaleDateString(t,{timeZone:"UTC",...r})):""}function u(e,t,r){if(!e)return"";const n=new Date("2000-01-01T"+e+"Z");return a(n)?n.toLocaleTimeString(t,r):""}function d(e,t,r){if(!e)return"";const n=new Date(e);return a(n)?n.toLocaleString(t,r):""}function p(e,t,r){return e&&(e.start||e.end)?d(e.start,t,r)+" - "+d(e.end,t,r):""}const l={s:"every second",min:"every minute",h:"hourly",d:"daily",wk:"weekly",mo:"monthly",a:"annually"},h={s:"second",min:"minute",h:"hour",d:"day",wk:"week",mo:"month",a:"year"},f={s:"seconds",min:"minutes",h:"hours",d:"days",wk:"weeks",mo:"months",a:"years"};function m(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(l[i]):(1===r?t.push("once"):t.push(r+" times"),1===n?t.push("per "+h[i]):t.push("per "+n+" "+f[i])),e.repeat.dayOfWeek&&t.push("on "+e.repeat.dayOfWeek.map(J).join(", ")),e.repeat.timeOfDay&&t.push("at "+e.repeat.timeOfDay.map((e=>u(e))).join(", "))}return e.event&&t.push(e.event.map((e=>d(e))).join(", ")),J(t.join(" ").trim())}function y(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},i=e?.high&&{...e.high};return!e||void 0===n?.value&&void 0===i?.value?"":void 0!==e.low?.value&&void 0===e.high?.value?r&&void 0!==t?(e.low.value=function(e,t,r=1){return(b(e,t)-r)*Math.pow(10,-t)}(e.low.value,t),`> ${g(e.low,t)}`):`>= ${g(e.low,t)}`:void 0===e.low?.value&&void 0!==e.high?.value?r&&void 0!==t?(e.high.value=function(e,t,r=1){return(b(e,t)+r)*Math.pow(10,-t)}(e.high.value,t),`< ${g(e.high,t)}`):`<= ${g(e.high,t)}`:(n?.unit===i?.unit&&delete n?.unit,`${g(n,t)} - ${g(i,t)}`)}function g(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 v(e){return void 0===e?.value?"":e.value.toLocaleString(void 0,{style:"currency",currency:e.currency||"USD",currencyDisplay:"narrowSymbol"})}function x(e){return e?e.text?e.text:e.coding?e.coding.map((e=>S(e))).join(", "):"":""}function S(e){return e?.display||e?.code||""}function w(e){return e?"component"in e?e.component.map((e=>w(e))).join(" / "):e?.valueQuantity?g(e.valueQuantity):e.valueCodeableConcept?x(e.valueCodeableConcept):e.valueString?e.valueString:"":""}function b(e,t){return void 0===t?e:Math.round(e*Math.pow(10,t))}function E(e){const t=T(e),r=P(e);return r===t?{reference:t}:{reference:t,display:r}}function T(e){return e.resourceType+"/"+e.id}function k(e){return e?.reference?.split("/")[1]}function C(e){return"Patient"===e.resourceType||"Practitioner"===e.resourceType||"RelatedPerson"===e.resourceType}function P(e){if(C(e)){const t=function(e){const t=e.name;if(t&&t.length>0)return i(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:T(e)}function D(e){if(!("photo"in e))return;const t=e.photo;if(t){if(!Array.isArray(t))return R(t);for(const e of t){const t=R(e);if(t)return t}}}function R(e){if(e.url&&e.contentType&&e.contentType.startsWith("image/"))return e.url}function A(e){return e?new Date(e):void 0}function I(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 U(e,t){const{years:r,months:n,days:i}=I(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 O(e){const t={};return L(e.item,t),t}function L(e,t){if(e)for(const r of e)r.linkId&&r.answer&&r.answer.length>0&&(t[r.linkId]=r.answer[0]),L(r.item,t)}function M(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 N(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 _(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 B(e,t){return JSON.stringify(e,j,t?2:void 0)}function j(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 Q(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(!Q(e[r],t[r]))return!1;return!0}(e,t):!Array.isArray(e)&&!Array.isArray(t)&&(F(e)&&F(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(!Q(e[r],t[r],r))return!1}return!0}(e,t,r):(F(e)||F(t),!1))))}function $(e){return JSON.parse(JSON.stringify(e))}function W(e){return!!e.match(/^\w{8}-\w{4}-\w{4}-\w{4}-\w{12}$/i)}function F(e){return null!==e&&"object"==typeof e}function H(e){return e.every((e=>"string"==typeof e))}const z=[];for(let e=0;e<256;e++)z.push(e.toString(16).padStart(2,"0"));function G(e){const t=new Uint8Array(e),r=new Array(t.length);for(let e=0;e<t.length;e++)r[e]=z[t[e]];return r.join("")}function V(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 J(e){return e.charAt(0).toUpperCase()+e.substring(1)}function X(e){return e===e.toLowerCase()&&e!==e.toUpperCase()}function Y(e,t){return e?.coding?.find((e=>e.system===t))?.code}function K(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 Z(e,t,r,n){return e.qualifiedInterval?.find((i=>te(i,t)&&function(e,t,r){return!!e.range&&re(t,e.range,r)}(i,r,e.quantitativeDetails?.decimalPrecision)&&(void 0===n||i.category===n)))}function ee(e,t,r){return e.qualifiedInterval?.find((e=>te(e,t)&&r.includes(e.condition)))}function te(e,t){return function(e,t){return!e.gender||e.gender===t.gender}(e,t)&&function(e,t){return!e.age||re(I(t.birthDate).years,e.age)}(e,t)}function re(e,t,r){return(void 0===t.low?.value||ce(e,t.low.value,r))&&(void 0===t.high?.value||ae(e,t.high.value,r))}function ne(e,t){return parseFloat(e.toFixed(t))}function ie(e,t,r){return ue(e,r)===ue(t,r)}function oe(e,t,r){return ue(e,r)<ue(t,r)}function se(e,t,r){return ue(e,r)>ue(t,r)}function ae(e,t,r){return ue(e,r)<=ue(t,r)}function ce(e,t,r){return ue(e,r)>=ue(t,r)}function ue(e,t){return void 0===t?e:Math.round(e*Math.pow(10,t))}function de(){const e=new Uint32Array(28);return crypto.getRandomValues(e),G(e.buffer)}class pe{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 le(e){const t=function(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")}(e.replace(/-/g,"+").replace(/_/g,"/")),r=Array.from(t).reduce(((e,t)=>`${e}%${("00"+t.charCodeAt(0).toString(16)).slice(-2)}`),""),n=decodeURIComponent(r);return JSON.parse(n)}function he(e){const[t,r,n]=e.split(".");return le(r)}const fe="ok",me="created",ye="gone",ge="not-modified",ve="not-found",xe="unauthorized",Se="forbidden",we="too-many-requests",be={resourceType:"OperationOutcome",id:fe,issue:[{severity:"information",code:"informational",details:{text:"All OK"}}]},Ee={resourceType:"OperationOutcome",id:me,issue:[{severity:"information",code:"informational",details:{text:"Created"}}]},Te={resourceType:"OperationOutcome",id:ge,issue:[{severity:"information",code:"informational",details:{text:"Not Modified"}}]},ke={resourceType:"OperationOutcome",id:ve,issue:[{severity:"error",code:"not-found",details:{text:"Not found"}}]},Ce={resourceType:"OperationOutcome",id:xe,issue:[{severity:"error",code:"login",details:{text:"Unauthorized"}}]},Pe={resourceType:"OperationOutcome",id:Se,issue:[{severity:"error",code:"forbidden",details:{text:"Forbidden"}}]},De={resourceType:"OperationOutcome",id:ye,issue:[{severity:"error",code:"deleted",details:{text:"Gone"}}]},Re={resourceType:"OperationOutcome",id:we,issue:[{severity:"error",code:"throttled",details:{text:"Too Many Requests"}}]};function Ae(e,t){return{resourceType:"OperationOutcome",issue:[{severity:"error",code:"invalid",details:{text:e},expression:t?[t]:void 0}]}}function Ie(e){return{resourceType:"OperationOutcome",issue:[{severity:"error",code:"structure",details:{text:e}}]}}function Ue(e){return"object"==typeof e&&null!==e&&"OperationOutcome"===e.resourceType}function Oe(e){return e.id===fe||e.id===me||e.id===ge}function Le(e){return e.id===ve}function Me(e){return e.id===ye}function Ne(e){return e.id===fe?200:e.id===me?201:e.id===ge?304:e.id===xe?401:e.id===Se?403:e.id===ve?404:e.id===ye?410:e.id===we?429:400}function _e(e,t){if(!Oe(e)||void 0===t)throw new Be(e)}class Be extends Error{constructor(e,t){super(Qe(e)),this.outcome=e,this.cause=t}}function je(e){return e instanceof Be?e.outcome:Ue(e)?e:Ae(qe(e))}function qe(e){return e?"string"==typeof e?e:e instanceof Error?e.message:Ue(e)?Qe(e):JSON.stringify(e):"Unknown error"}function Qe(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 $e;class We{constructor(e){this[$e]="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)}}$e=Symbol.toStringTag;class Fe{constructor(){this.storage="undefined"!=typeof localStorage?localStorage:new He}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?B(t):void 0)}}class He{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 ze,Ge={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 Ve(e){for(const t of e.entry){const e=t.resource;"StructureDefinition"===e.resourceType&&Je(e)}}function Je(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=Ze(i);let s=dt.types[o];s||(dt.types[o]=s={});s.parentType=s.parentType||Ze(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=Ze(n.slice(0,n.length-1)),o=dt.types[i];if(!o)return;const s=n[n.length-1];o.properties[s]=t}(e,t))))}function Xe(e){for(const t of e.entry){const e=t.resource;"SearchParameter"===e.resourceType&&Ye(e)}}function Ye(e){if(e.base)for(const t of e.base){const r=dt.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 Ke(e){const t=e.type?.[0]?.code;return"BackboneElement"===t||"Element"===t?Ze(e.path?.split(".")):t}function Ze(e){return 1===e.length?e[0]:e.map(J).join("")}function et(e){const t=e.structureDefinition;return t&&t.name===e.elementDefinition?.path&&"resource"===t.kind&&!t.abstract}function tt(){const e=[];for(const[t,r]of Object.entries(dt.types))et(r)&&e.push(t);return e}function rt(e){return dt.types[e]}function nt(e){return dt.types[e].searchParams}function it(e){return e.replaceAll("[x]","").split(".").pop().split(/(?=[A-Z])/).map(st).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"}(ze||(ze={}));const ot=new Set(["ID","IP","PKCE","JWKS","URI","URL"]);function st(e){const t=e.toUpperCase();return ot.has(t)?t:t.charAt(0)+e.slice(1)}function at(e,t){const r=dt.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 at(Ze(e),t)}return n}}function ct(e){return!(!e||"object"!=typeof e||!("resourceType"in e))}function ut(e){return!(!e||"object"!=typeof e||!("reference"in e))}const dt=Ge,pt="2.0.15-025c3c04",lt={resourceType:"Device",id:"system",deviceName:[{name:"System"}]};class ht extends pe{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 Fe,this.createPdfImpl=e?.createPdf,this.baseUrl=mt(e?.baseUrl)||"https://api.medplum.com/",this.fhirBaseUrl=this.baseUrl+(mt(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.exchangeUrl=this.baseUrl+"auth/exchange",this.onUnauthenticated=e?.onUnauthenticated,this.cacheTime=e?.cacheTime??6e4,this.cacheTime>0?this.requestCache=new r(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.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)}invalidateSearches(e){const t="fhir/R4/"+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 We(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){const{codeChallengeMethod:t,codeChallenge:r}=await this.startPkce();return this.post("auth/newuser",{...e,codeChallengeMethod:t,codeChallenge:r})}async startNewProject(e){return this.post("auth/newproject",e)}async startNewPatient(e){return this.post("auth/newpatient",e)}async startLogin(e){return this.post("auth/login",{...await this.ensureCodeChallenge(e),clientId:e.clientId??this.clientId,scope:e.scope})}async startGoogleLogin(e){return this.post("auth/google",{...await this.ensureCodeChallenge(e),clientId:e.clientId??this.clientId,scope:e.scope})}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=await this.fetch(this.exchangeUrl,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({clientId:this.clientId,externalAccessToken:e}),credentials:"include"});if(!r.ok)throw this.clearActiveLogin(),new Error("Failed to fetch tokens");const n=await r.json();return await this.verifyTokens(n),this.getProfile()}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 We((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 We(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 We(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 lt;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 We(Promise.reject(new Error("Missing reference")));if("system"===r)return new We(Promise.resolve(lt));const[n,i]=r.split("/");return n&&i?this.readResource(n,i,t):new We(Promise.reject(new Error("Invalid reference")))}getSchema(){return dt}requestSchema(e){if(e in dt.types)return Promise.resolve(dt);const t=e+"-requestSchema",r=this.getCacheEntry(t,void 0);if(r)return r.value;const n=new We((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)Je(e);for(const e of r.data.SearchParameterList)Ye(e);return dt})());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){if(!e.resourceType)throw new Error("Missing resourceType");return this.invalidateSearches(e.resourceType),this.post(this.fhirUrl(e.resourceType),e)}async createResourceIfNoneExist(e,t){return await this.searchOne(e.resourceType,t)??this.createResource(e)}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){const r=this.getProfile();let n,i;return"Encounter"===e.resourceType&&(n=E(e),i=e.subject),"ServiceRequest"===e.resourceType&&(n=e.encounter,i=e.subject),"Patient"===e.resourceType&&(i=E(e)),this.createResource({resourceType:"Communication",basedOn:[E(e)],encounter:n,subject:i,sender:r?E(r):void 0,sent:(new Date).toISOString(),payload:[{contentString:t}]})}async updateResource(e){if(!e.resourceType)throw new Error("Missing resourceType");if(!e.id)throw new Error("Missing id");this.invalidateSearches(e.resourceType);let t=await this.put(this.fhirUrl(e.resourceType,e.id),e);return t||(t=e),this.cacheResource(t),t}patchResource(e,t,r){return this.invalidateSearches(e),this.patch(this.fhirUrl(e,t),r)}deleteResource(e,t){return this.deleteCacheEntry(this.fhirUrl(e,t).toString()),this.invalidateSearches(e),this.delete(this.fhirUrl(e,t))}validateResource(e){return this.post(this.fhirUrl(e.resourceType,"$validate"),e)}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){return this.post("fhir/R4",e)}sendEmail(e){return this.post("email/v1/send",e,"application/json")}graphql(e,t,r,n){return this.post(this.fhirUrl("$graphql"),{query:e,operationName:t,variables:r},"application/json",n)}readResourceGraph(e,t,r){return this.get(`${this.fhirUrl(e,t)}/$graph?graph=${r}`)}getActiveLogin(){return this.storage.getObject("activeLogin")}async setActiveLogin(e){this.clearActiveLogin(),this.accessToken=e.accessToken,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.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()}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 We(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);if(401===n.status)return this.handleUnauthenticated(e,t,r);if(204===n.status||304===n.status)return;let i;try{i=await n.json()}catch(e){throw console.error("Error parsing response",n.status,e),e}if(n.status>=400)throw new Be(je(i));return i}async fetchWithRetry(e,t){let r;for(let n=0;n<3;n++){if(r=await this.fetch(e,t),r.status<500)return r;await new Promise((e=>setTimeout(e,200)))}return r}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 Be(je(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("fhir/R4",t);for(let t=0;t<e.length;t++){const n=e[t],i=r.entry?.[t];i?.response?.outcome&&!Oe(i.response.outcome)?n.reject(new Be(i.response.outcome)):n.resolve(i?.resource)}}addFetchOptionsDefaults(e){let t=e.headers;t||(t={},e.headers=t),t["X-Medplum"]="extended",e.body&&!t["Content-Type"]&&(t["Content-Type"]="application/fhir+json"),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=de();sessionStorage.setItem("pkceState",e);const t=de();sessionStorage.setItem("codeVerifier",t);const r=V(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||ft()),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","authorization_code"),r.set("code",e),r.set("client_id",t?.clientId||this.clientId),r.set("redirect_uri",t?.redirectUri||ft()),"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","refresh_token"),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","client_credentials"),r.set("client_id",e),r.set("client_secret",t),this.fetchTokens(r)}setBasicAuth(e,t){this.clientId=e,this.clientSecret=t,this.basicAuth=function(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")}(e+":"+t)}async invite(e,t){return this.post("admin/projects/"+e+"/invite",t)}async fetchTokens(e){const t=await this.fetch(this.tokenUrl,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:e,credentials:"include"});if(!t.ok)throw this.clearActiveLogin(),new Error("Failed to fetch tokens");const r=await t.json();return await this.verifyTokens(r),this.getProfile()}async verifyTokens(e){const t=e.access_token,r=he(t);if(Date.now()>=1e3*r.exp)throw this.clearActiveLogin(),new Error("Token expired");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){}}}function ft(){return"undefined"==typeof window?"":window.location.protocol+"//"+window.location.host+"/"}function mt(e){return e?e.endsWith("/")?e:e+"/":e}class yt{constructor(e,t){this.operator=e,this.child=t}toString(){return`${this.operator}(${this.child.toString()})`}}class gt{constructor(e,t,r){this.operator=e,this.left=t,this.right=r}toString(){return`${this.left.toString()} ${this.operator} ${this.right.toString()}`}}class vt{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 xt(e,this.prefixParselets,this.infixParselets)}}class xt{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 St=["year","years","month","months","week","weeks","day","days","hour","hours","minute","minutes","second","seconds","millisecond","milliseconds"];class wt{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&&St.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 bt(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 Et(e){return[{type:ze.boolean,value:e}]}function Tt(e){return null==e?{type:"undefined",value:void 0}:Number.isSafeInteger(e)?{type:ze.integer,value:e}:"number"==typeof e?{type:ze.decimal,value:e}:"boolean"==typeof e?{type:ze.boolean,value:e}:"string"==typeof e?{type:ze.string,value:e}:_t(e)?{type:ze.Quantity,value:e}:ct(e)?{type:e.resourceType,value:e}:{type:ze.BackboneElement,value:e}}function kt(e){return 0!==e.length&&!!e[0].value}function Ct(e,t){if(!e?.value)return;const r=at(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]","")+J(r.code);if(n in e.value){i=e.value[n],o=r.code;break}}if(q(i))return;"Element"!==o&&"BackboneElement"!==o||(o=Ze(r.path?.split(".")));return Array.isArray(i)?i.map((e=>Pt(e,o))):Pt(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 ze){const i=t+J(e);if(i in r){n=r[i];break}}if(q(n))return;return Array.isArray(n)?n.map(Tt):Tt(n)}(e,t)}function Pt(e,t){return"Resource"===t&&ct(e)&&(t=e.resourceType),{type:t,value:e}}function Dt(e){const t=[];for(const r of e){let e=!1;for(const n of t)if(kt(It(r,n))){e=!0;break}e||t.push(r)}return t}function Rt(e){return Et(!kt(e))}function At(e,t){return 0===e.length||0===t.length?[]:e.length!==t.length?Et(!1):Et(e.every(((e,r)=>kt(It(e,t[r])))))}function It(e,t){const r=e.value,n=t.value;return"number"==typeof r&&"number"==typeof n?Et(Math.abs(r-n)<1e-8):_t(r)&&_t(n)?Et(Bt(r,n)):Et("object"==typeof r&&"object"==typeof n?jt(e,t):r===n)}function Ut(e,t){return 0===e.length&&0===t.length?Et(!0):e.length!==t.length?Et(!1):(e.sort(Lt),t.sort(Lt),Et(e.every(((e,r)=>kt(Ot(e,t[r]))))))}function Ot(e,t){const r=e.value,n=t.value;return"number"==typeof r&&"number"==typeof n?Et(Math.abs(r-n)<.01):_t(r)&&_t(n)?Et(Bt(r,n)):Et("object"==typeof r&&"object"==typeof n?jt(r,n):"string"==typeof r&&"string"==typeof n?r.toLowerCase()===n.toLowerCase():r===n)}function Lt(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 Mt(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 Nt(r);case"Quantity":return _t(r);default:return"object"==typeof r&&r?.resourceType===t}}function Nt(e){return!(!e||"object"!=typeof e||!("start"in e))}function _t(e){return!(!e||"object"!=typeof e||!("value"in e)||"number"!=typeof e.value)}function Bt(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 jt(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(qt(r)&&qt(i)){if(!jt(r,i))return!1}else if(r!==i)return!1}return!0}function qt(e){return null!==e&&"object"==typeof e}const Qt=()=>[],$t={empty:e=>Et(0===e.length),exists:(e,t)=>Et(t?e.filter((e=>kt(t.eval([e])))).length>0:e.length>0),all:(e,t)=>Et(e.every((e=>kt(t.eval([e]))))),allTrue:e=>{for(const t of e)if(!t.value)return Et(!1);return Et(!0)},anyTrue:e=>{for(const t of e)if(t.value)return Et(!0);return Et(!1)},allFalse:e=>{for(const t of e)if(t.value)return Et(!1);return Et(!0)},anyFalse:e=>{for(const t of e)if(!t.value)return Et(!0);return Et(!1)},subsetOf:Qt,supersetOf:Qt,count:e=>[{type:ze.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=>Et(e.length===$t.distinct(e).length),where:(e,t)=>e.filter((e=>kt(t.eval([e])))),select:(e,t)=>e.map((e=>t.eval([e]))).flat(),repeat:Qt,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 Dt([...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 kt(i)?r.eval(e):n?n.eval(e):[]},toBoolean:e=>{if(0===e.length)return[];const[{value:t}]=Ht(e,1);if("boolean"==typeof t)return[{type:ze.boolean,value:t}];if("number"==typeof t&&(0===t||1===t))return Et(!!t);if("string"==typeof t){const e=t.toLowerCase();if(["true","t","yes","y","1","1.0"].includes(e))return Et(!0);if(["false","f","no","n","0","0.0"].includes(e))return Et(!1)}return[]},convertsToBoolean:e=>0===e.length?[]:Et(1===$t.toBoolean(e).length),toInteger:e=>{if(0===e.length)return[];const[{value:t}]=Ht(e,1);return"number"==typeof t?[{type:ze.integer,value:t}]:"string"==typeof t&&t.match(/^[+-]?\d+$/)?[{type:ze.integer,value:parseInt(t,10)}]:"boolean"==typeof t?[{type:ze.integer,value:t?1:0}]:[]},convertsToInteger:e=>0===e.length?[]:Et(1===$t.toInteger(e).length),toDate:e=>{if(0===e.length)return[];const[{value:t}]=Ht(e,1);return"string"==typeof t&&t.match(/^\d{4}(-\d{2}(-\d{2})?)?/)?[{type:ze.date,value:bt(t)}]:[]},convertsToDate:e=>0===e.length?[]:Et(1===$t.toDate(e).length),toDateTime:e=>{if(0===e.length)return[];const[{value:t}]=Ht(e,1);return"string"==typeof t&&t.match(/^\d{4}(-\d{2}(-\d{2})?)?/)?[{type:ze.dateTime,value:bt(t)}]:[]},convertsToDateTime:e=>0===e.length?[]:Et(1===$t.toDateTime(e).length),toDecimal:e=>{if(0===e.length)return[];const[{value:t}]=Ht(e,1);return"number"==typeof t?[{type:ze.decimal,value:t}]:"string"==typeof t&&t.match(/^-?\d{1,9}(\.\d{1,9})?$/)?[{type:ze.decimal,value:parseFloat(t)}]:"boolean"==typeof t?[{type:ze.decimal,value:t?1:0}]:[]},convertsToDecimal:e=>0===e.length?[]:Et(1===$t.toDecimal(e).length),toQuantity:e=>{if(0===e.length)return[];const[{value:t}]=Ht(e,1);return _t(t)?[{type:ze.Quantity,value:t}]:"number"==typeof t?[{type:ze.Quantity,value:{value:t,unit:"1"}}]:"string"==typeof t&&t.match(/^-?\d{1,9}(\.\d{1,9})?/)?[{type:ze.Quantity,value:{value:parseFloat(t),unit:"1"}}]:"boolean"==typeof t?[{type:ze.Quantity,value:{value:t?1:0,unit:"1"}}]:[]},convertsToQuantity:e=>0===e.length?[]:Et(1===$t.toQuantity(e).length),toString:e=>{if(0===e.length)return[];const[{value:t}]=Ht(e,1);return null==t?[]:_t(t)?[{type:ze.string,value:`${t.value} '${t.unit}'`}]:[{type:ze.string,value:t.toString()}]},convertsToString:e=>0===e.length?[]:Et(1===$t.toString(e).length),toTime:e=>{if(0===e.length)return[];const[{value:t}]=Ht(e,1);if("string"==typeof t){const e=t.match(/^T?(\d{2}(:\d{2}(:\d{2})?)?)/);if(e)return[{type:ze.time,value:bt("T"+e[1])}]}return[]},convertsToTime:e=>0===e.length?[]:Et(1===$t.toTime(e).length),indexOf:(e,t)=>Wt(((e,t)=>e.indexOf(t)),e,t),substring:(e,t,r)=>Wt(((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)=>Wt(((e,t)=>e.startsWith(t)),e,t),endsWith:(e,t)=>Wt(((e,t)=>e.endsWith(t)),e,t),contains:(e,t)=>Wt(((e,t)=>e.includes(t)),e,t),upper:e=>Wt((e=>e.toUpperCase()),e),lower:e=>Wt((e=>e.toLowerCase()),e),replace:(e,t,r)=>Wt(((e,t,r)=>e.replaceAll(t,r)),e,t,r),matches:(e,t)=>Wt(((e,t)=>!!e.match(t)),e,t),replaceMatches:(e,t,r)=>Wt(((e,t,r)=>e.replaceAll(t,r)),e,t,r),length:e=>Wt((e=>e.length),e),toChars:e=>Wt((e=>e?e.split(""):void 0),e),abs:e=>Ft(Math.abs,e),ceiling:e=>Ft(Math.ceil,e),exp:e=>Ft(Math.exp,e),floor:e=>Ft(Math.floor,e),ln:e=>Ft(Math.log,e),log:(e,t)=>Ft(((e,t)=>Math.log(e)/Math.log(t)),e,t),power:(e,t)=>Ft(Math.pow,e,t),round:e=>Ft(Math.round,e),sqrt:e=>Ft(Math.sqrt,e),truncate:e=>Ft((e=>0|e),e),children:Qt,descendants:Qt,trace:(e,t)=>(console.log("trace",e,t),e),now:()=>[{type:ze.dateTime,value:(new Date).toISOString()}],timeOfDay:()=>[{type:ze.time,value:(new Date).toISOString().substring(11)}],today:()=>[{type:ze.date,value:(new Date).toISOString().substring(0,10)}],between:(e,t,r,n)=>{const i=$t.toDateTime(t.eval(e));if(0===i.length)throw new Error("Invalid start date");const o=$t.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=I(i[0].value,o[0].value);return[{type:ze.Quantity,value:{value:a[s],unit:s}}]},is:(e,t)=>{let r="";return t instanceof Vt?r=t.name:t instanceof rr&&(r=t.left.name+"."+t.right.name),r?e.map((e=>({type:ze.boolean,value:Mt(e,r)}))):[]},not:e=>$t.toBoolean(e).map((e=>({type:ze.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 Tt(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:ze.BackboneElement,value:void 0}})).filter((e=>!!e.value)),as:e=>e,type:e=>e.map((({value:e})=>"boolean"==typeof e?{type:ze.BackboneElement,value:{namespace:"System",name:"Boolean"}}:"number"==typeof e?{type:ze.BackboneElement,value:{namespace:"System",name:"Integer"}}:ct(e)?{type:ze.BackboneElement,value:{namespace:"FHIR",name:e.resourceType}}:{type:ze.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:ze.boolean,value:e.value?.resourceType===n})))}};function Wt(e,t,...r){if(0===t.length)return[];const[{value:n}]=Ht(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(Tt):[Tt(i)]}function Ft(e,t,...r){if(0===t.length)return[];const[{value:n}]=Ht(t,1),i=_t(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?ze.Quantity:t[0].type,value:i?{...n,value:s}:s}]}function Ht(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 Gt{constructor(e){this.value=e}eval(){return[this.value]}toString(){const e=this.value.value;return"string"==typeof e?`'${e}'`:e.toString()}}class Vt{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 ct(t)&&t.resourceType===this.name?e:Ct(e,this.name)}toString(){return this.name}}class Jt{eval(){return[]}toString(){return"{}"}}class Xt extends yt{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 Yt extends gt{constructor(e,t){super("as",e,t)}eval(e){return $t.ofType(this.left.eval(e),this.right)}}class Kt extends gt{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=_t(n)?n.value:n,s=_t(i)?i.value:i,a=this.impl(o,s);return"boolean"==typeof a?Et(a):_t(n)?[{type:ze.Quantity,value:{...n,value:a}}]:[Tt(a)]}}class Zt extends gt{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:ze.string,value:t.map((e=>e.value)).join("")}]:t}}class er extends gt{constructor(e,t){super("contains",e,t)}eval(e){const t=this.left.eval(e),r=this.right.eval(e);return Et(t.some((e=>e.value===r[0].value)))}}class tr extends gt{constructor(e,t){super("in",e,t)}eval(e){const t=this.left.eval(e);return Et(this.right.eval(e).some((e=>e.value===t[0].value)))}}class rr extends gt{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 nr extends gt{constructor(e,t){super("|",e,t)}eval(e){return Dt([...this.left.eval(e),...this.right.eval(e)])}}class ir extends gt{constructor(e,t){super("=",e,t)}eval(e){return At(this.left.eval(e),this.right.eval(e))}}class or extends gt{constructor(e,t){super("!=",e,t)}eval(e){return Rt(At(this.left.eval(e),this.right.eval(e)))}}class sr extends gt{constructor(e,t){super("~",e,t)}eval(e){return Ut(this.left.eval(e),this.right.eval(e))}}class ar extends gt{constructor(e,t){super("!~",e,t)}eval(e){return Rt(Ut(this.left.eval(e),this.right.eval(e)))}}class cr extends gt{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 Et(Mt(t[0],r))}}class ur extends gt{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?Et(!0):!1===t[0]?.value||!1===r[0]?.value?Et(!1):[]}}class dr extends gt{constructor(e,t){super("or",e,t)}eval(e){const t=this.left.eval(e);if(kt(t))return t;const r=this.right.eval(e);return kt(r)?r:[]}}class pr extends gt{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?Et(!0):!0===n&&!0===i||!1===n&&!1===i?Et(!1):[]}}class lr{constructor(e,t){this.name=e,this.args=t}eval(e){const t=$t[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 hr{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 fr=["true","false"],mr=["!=","!~","<=",">=","{}","->"];function yr(e){return new wt(e,fr,mr).tokenize()}const gr={parse(e){const t=e.consumeAndParse();if(!e.match(")"))throw new Error("Parse error: expected `)` got `"+e.peek()?.value+"`");return t}},vr={parse(e,t){const r=e.consumeAndParse();if(!e.match("]"))throw new Error("Parse error: expected `]`");return new hr(t,r)},precedence:2},xr={parse(e,t){if(!(t instanceof Vt))throw new Error("Unexpected parentheses");const r=[];for(;!e.match(")");)r.push(e.consumeAndParse()),e.match(",");return new lr(t.name,r)},precedence:0};function Sr(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 wr(){return(new vt).registerPrefix("String",{parse:(e,t)=>new Gt({type:ze.string,value:t.value})}).registerPrefix("DateTime",{parse:(e,t)=>new Gt({type:ze.dateTime,value:bt(t.value)})}).registerPrefix("Quantity",{parse:(e,t)=>new Gt({type:ze.Quantity,value:Sr(t.value)})}).registerPrefix("Number",{parse:(e,t)=>new Gt({type:ze.decimal,value:parseFloat(t.value)})}).registerPrefix("true",{parse:()=>new Gt({type:ze.boolean,value:!0})}).registerPrefix("false",{parse:()=>new Gt({type:ze.boolean,value:!1})}).registerPrefix("Symbol",{parse:(e,t)=>new Vt(t.value)}).registerPrefix("{}",{parse:()=>new Jt}).registerPrefix("(",gr).registerInfix("[",vr).registerInfix("(",xr).prefix("+",3,((e,t)=>new Xt("+",t,(e=>e)))).prefix("-",3,((e,t)=>new Kt("-",t,t,((e,t)=>-t)))).infixLeft(".",1,((e,t,r)=>new rr(e,r))).infixLeft("/",4,((e,t,r)=>new Kt("/",e,r,((e,t)=>e/t)))).infixLeft("*",4,((e,t,r)=>new Kt("*",e,r,((e,t)=>e*t)))).infixLeft("+",5,((e,t,r)=>new Kt("+",e,r,((e,t)=>e+t)))).infixLeft("-",5,((e,t,r)=>new Kt("-",e,r,((e,t)=>e-t)))).infixLeft("|",7,((e,t,r)=>new nr(e,r))).infixLeft("=",9,((e,t,r)=>new ir(e,r))).infixLeft("!=",9,((e,t,r)=>new or(e,r))).infixLeft("~",9,((e,t,r)=>new sr(e,r))).infixLeft("!~",9,((e,t,r)=>new ar(e,r))).infixLeft("<",8,((e,t,r)=>new Kt("<",e,r,((e,t)=>e<t)))).infixLeft("<=",8,((e,t,r)=>new Kt("<=",e,r,((e,t)=>e<=t)))).infixLeft(">",8,((e,t,r)=>new Kt(">",e,r,((e,t)=>e>t)))).infixLeft(">=",8,((e,t,r)=>new Kt(">=",e,r,((e,t)=>e>=t)))).infixLeft("&",5,((e,t,r)=>new Zt(e,r))).infixLeft("and",6,((e,t,r)=>new ur(e,r))).infixLeft("as",6,((e,t,r)=>new Yt(e,r))).infixLeft("contains",6,((e,t,r)=>new er(e,r))).infixLeft("div",6,((e,t,r)=>new Kt("div",e,r,((e,t)=>e/t|0)))).infixLeft("in",6,((e,t,r)=>new tr(e,r))).infixLeft("is",6,((e,t,r)=>new cr(e,r))).infixLeft("mod",6,((e,t,r)=>new Kt("mod",e,r,((e,t)=>e%t)))).infixLeft("or",6,((e,t,r)=>new dr(e,r))).infixLeft("xor",6,((e,t,r)=>new pr(e,r)))}const br=wr();function Er(e){return new zt(e,br.construct(yr(e)).consumeAndParse())}function Tr(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]=Tt(r[e]))}return kr(e,r).map((e=>e.value))}function kr(e,t){return Er(e).eval(t)}const Cr=[...mr,"->","<<",">>"];class Pr{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 Vt)this.parseRuleTargetSymbol(e,t);else if(t instanceof lr)this.parseRuleTargetFunction(e,t);else{if(!(t instanceof Gt))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 Dr=wr().registerInfix("->",{precedence:100}).registerInfix(";",{precedence:200});function Rr(e){const t=Dr.construct(new wt(e,fr,Cr).tokenize());return t.removeComments(),new Pr(t).parse()}const Ar=[...mr,"eq","ne","co"];class Ir{constructor(e,t,r){this.path=e,this.operator=t,this.value=r}}class Ur{constructor(e){this.child=e}}class Or{constructor(e,t,r){this.keyword=e,this.left=t,this.right=r}}class Lr{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 Ur(this.parse()),this.parser.consume(")")):e=new Ir(this.parser.consume("Symbol").value,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 Or(t,e,this.parse())):e}}const Mr=wr();function Nr(e){const t=Mr.construct(new wt(e,fr,Ar,{dateTimeLiterals:!0,symbolRegex:/[^\s\])]/}).tokenize());return t.removeComments(),new Lr(t).parse()}class _r{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 Br{constructor(e,t=new _r){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 Br([new jr(["MSH",this.context.getMsh2(),i,o,r,n,e.toISOString(),"","ACK",e.getTime().toString(),"P",a],this.context),new jr(["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 _r("\r",e.charAt(3),e.charAt(4),e.charAt(5),e.charAt(6),e.charAt(7));return new Br(e.split(/[\r\n]+/).map((e=>jr.parse(e,t))),t)}}class jr{constructor(e,t=new _r){this.context=t,H(e)?this.fields=e.map((e=>qr.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 _r){return new jr(e.split(t.fieldSeparator).map((e=>qr.parse(e,t))),t)}}class qr{constructor(e,t=new _r){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 _r){return new qr(e.split(t.repetitionSeparator).map((e=>e.split(t.componentSeparator))),t)}}const Qr={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 Wr(e){const t=dt.types[e];return t&&t.structureDefinition.id===e&&"resource"===t.structureDefinition.kind}function Fr(e){if(!e)throw new Be(Ie("Resource type is null"));if(!Wr(e))throw new Be(Ie("Unknown resource type"))}function Hr(e){new zr(e).validate()}class zr{constructor(e){this.issues=[],this.root=e}validate(){const e=this.root;if(!e)throw new Be(Ie("Resource is null"));const t=e.resourceType;if(!t)throw new Be(Ie("Missing resource type"));if(Gr(e,"",this.issues),this.validateObject(Tt(e),t),this.issues.length>0)throw new Be({resourceType:"OperationOutcome",issue:this.issues})}validateObject(e,t){const r=dt.types[e.type];if(!r)throw new Be(Ie("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=Ct(r,e.split(".").pop());if(q(n))void 0!==t.min&&t.min>0&&this.issues.push(Vr(e,"Missing required property"));else if("*"===t.max){if(!Array.isArray(n))return void this.issues.push(Vr(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(Vr(e,"Expected single value for property"));this.checkPropertyValue(e,t,n)}}checkPropertyValue(e,t,r){null!==r.value&&(X(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=Qr[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=dt.types[t]?.properties?.value;if(n?.type){const i=N(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)!==ze.integer&&n!==ze.positiveInt&&n!==ze.unsignedInt||Number.isInteger(r)||this.createIssue(e,"Number is not an integer"),t===ze.positiveInt&&r<=0&&this.createIssue(e,"Number is less than or equal to zero"),t===ze.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(!($r.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=Ct(t,n);if(i&&(Array.isArray(i)&&(i=i[0]),i&&e===r+J(i.type)))return!0}return!1}(t,r,n)||this.checkPrimitiveElement(e,t,r))){const r=`${e}.${t}`;this.issues.push(Vr(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(Vr(e.path,t))}}function Gr(e,t,r){null===e?r.push(Vr(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(Vr(`${t}[${n}]`,"Invalid undefined value")):Gr(e[n],`${t}[${n}]`,r)}(e,t,r):"object"==typeof e&&function(e,t,r){for(const[n,i]of Object.entries(e))Gr(i,`${t}${t?".":""}${n}`,r)}(e,t,r)}function Vr(e,t){return{severity:"error",code:"structure",details:{text:t},expression:[e]}}var Jr;function Xr(e,t){let r=dt.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?J(t):t)),"")}(r),i=Zr(e,t.expression)?.split(".");if(!i)return{columnName:n,type:Jr.TEXT};const o=Kr(t);let s,a,c=e,u=!1;for(let r=1;r<i.length;r++){if(s=at(c,i[r]),!s)throw new Error(`Element definition not found for ${e} ${t.code}`);if("*"===s.max&&(u=!0),a=s.type?.[0].code,!a)return{columnName:n,type:o,array:u};r<i.length-1&&(c=Yr(a)?Ze(s.path?.split(".")):a)}const d=Kr(t,a),p={columnName:n,type:d,elementDefinition:s,array:u};return function(e,t,r){const n=dt.types[e];n.searchParamsDetails||(n.searchParamsDetails={});n.searchParamsDetails[t]=r}(e,r,p),p}(e,t)),r}function Yr(e){return"Element"===e||"BackboneElement"===e}function Kr(e,t){let r=Jr.TEXT;switch(e.type){case"date":r=t===ze.dateTime||t===ze.instant?Jr.DATETIME:Jr.DATE;break;case"number":r=Jr.NUMBER;break;case"quantity":r=Jr.QUANTITY;break;case"reference":r=Jr.REFERENCE;break;case"token":"boolean"===t&&(r=Jr.BOOLEAN)}return r}function Zr(e,t){const r=t.split(" | ");for(const t of r){if((n=t).includes(" as Period")||n.includes(" as SampledDate"))continue;const r=en(t);if(r.startsWith(e+"."))return r}var n}function en(e){let t=e.trim();t.startsWith("(")&&t.endsWith(")")&&(t=t.substring(1,t.length-1)),t.includes("[0]")&&(t=t.replaceAll("[0]",""));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(e){e.BOOLEAN="BOOLEAN",e.NUMBER="NUMBER",e.QUANTITY="QUANTITY",e.TEXT="TEXT",e.REFERENCE="REFERENCE",e.DATE="DATE",e.DATETIME="DATETIME",e.PERIOD="PERIOD",e.UUID="UUID"}(Jr||(Jr={}));const tn=20;var rn;!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"}(rn||(rn={}));const nn={contains:rn.CONTAINS,exact:rn.EXACT,above:rn.ABOVE,below:rn.BELOW,text:rn.TEXT,not:rn.NOT,in:rn.IN,"not-in":rn.NOT_IN,"of-type":rn.OF_TYPE,missing:rn.MISSING,identifier:rn.IDENTIFIER},on={eq:rn.EQUALS,ne:rn.NOT_EQUALS,lt:rn.LESS_THAN,le:rn.LESS_THAN_OR_EQUALS,gt:rn.GREATER_THAN,ge:rn.GREATER_THAN_OR_EQUALS,sa:rn.STARTS_AFTER,eb:rn.ENDS_BEFORE,ap:rn.APPROXIMATELY};function sn(e,t){return un(e,t)}function an(e){return un(e.pathname.split("/").filter(Boolean).pop(),Object.fromEntries(e.searchParams.entries()))}function cn(e){return an(new URL(e,"https://example.com/"))}function un(e,t){const r={resourceType:e};for(const[e,n]of Object.entries(t))Array.isArray(n)?n.forEach((t=>dn(r,e,t))):dn(r,e,n??"");return r}function dn(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="estimate",e.count=0;break;case"_include":e.include=r;break;case"_revinclude":e.revInclude=r;break;case"_fields":e.fields=r.split(",");break;default:{const t=dt.types[e.resourceType]?.searchParams?.[n];t?function(e,t,r,n){if("missing"===r)return void hn(e,{code:t.code,operator:rn.MISSING,value:n});switch(t.type){case"number":case"date":!function(e,t,r){const{operator:n,value:i}=pn(r);hn(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){hn(e,{code:t.code,operator:ln(r),value:n})}(e,t,r,n);break;case"quantity":!function(e,t,r){const[n,i,o]=r.split("|"),{operator:s,value:a}=pn(n);hn(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=rn.EQUALS;if(r)i=r;else if(n.length>=2){const e=n.substring(0,2);e in on&&(2===n.length||n.at(2)?.match(/\d/))&&(i=e,n=n.substring(e.length))}hn(e,{code:t,operator:i,value:n})}(e,n,i,r)}}}function pn(e){const t=e.substring(0,2),r=on[t];return r?{operator:r,value:e.substring(2)}:{operator:rn.EQUALS,value:e}}function ln(e){return nn[e]||rn.EQUALS}function hn(e,t){e.filters?e.filters.push(t):e.filters=[t]}function fn(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 nn?":"+e.operator:"",r=e.operator!==rn.EQUALS&&e.operator in on?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("&"))}function mn(e,t){if(t.resourceType!==e.resourceType)return!1;if(t.filters)for(const r of t.filters)if(!yn(e,t,r))return!1;return!0}function yn(e,t,r){const n=dt.types[t.resourceType]?.searchParams?.[r.code];switch(n?.type){case"reference":return function(e,t,r){const n=Tr(r.expression,e),i=Sn(t.operator);if(""===t.value&&0===n.length)return t.operator===rn.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 gn(e,r,n);case"token":return function(e,t,r){const n=Xr(e.resourceType,r);return n.type===Jr.BOOLEAN?function(e,t,r){const n=Tr(r.expression,e),i="true"===t.value,o=n.includes(i);return Sn(t.operator)?!o:o}(e,t,r):gn(e,t,r,!0)}(e,r,n);case"date":return function(e,t,r){const n=Tr(r.expression,e),i=t.value.split(","),o=Sn(t.operator);for(const e of n)for(const r of i){if(xn(e,t.operator,r))return!o}return o}(e,r,n)}return!1}function gn(e,t,r,n){const i=Tr(r.expression,e),o=t.value.split(","),s=Sn(t.operator);for(const e of i)for(const r of o){if(vn(e,t.operator,r,n))return!s}return s}function vn(e,t,r,n){if(n&&r.includes("|")){const[n,i]=r.split("|");return vn(e,t,n,!1)&&(!i||vn(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 xn(e,t,r){switch(t){case rn.STARTS_AFTER:case rn.GREATER_THAN:return e>r;case rn.GREATER_THAN_OR_EQUALS:return e>=r;case rn.ENDS_BEFORE:case rn.LESS_THAN:return e<r;case rn.LESS_THAN_OR_EQUALS:return e<=r;case rn.EQUALS:case rn.NOT_EQUALS:return e===r}return!1}function Sn(e){return e===rn.NOT_EQUALS||e===rn.NOT}export{ur as AndAtom,Kt as ArithemticOperatorAtom,Yt as AsAtom,Fe as ClientStorage,Zt as ConcatAtom,er as ContainsAtom,tn as DEFAULT_SEARCH_COUNT,rr as DotAtom,Jt as EmptySetAtom,ir as EqualsAtom,sr as EquivalentAtom,fr as FHIRPATH_KEYWORDS,mr as FHIRPATH_OPERATORS,Ir as FhirFilterComparison,Or as FhirFilterConnective,Ur as FhirFilterNegation,zt as FhirPathAtom,zr as FhirSchemaValidator,lr as FunctionAtom,_r as Hl7Context,qr as Hl7Field,Br as Hl7Message,jr as Hl7Segment,tr as InAtom,hr as IndexerAtom,gt as InfixOperatorAtom,cr as IsAtom,r as LRUCache,Gt as LiteralAtom,pt as MEDPLUM_VERSION,ht as MedplumClient,He as MemoryStorage,or as NotEqualsAtom,ar as NotEquivalentAtom,Be as OperationOutcomeError,rn as Operator,dr as OrAtom,xt as Parser,vt as ParserBuilder,yt as PrefixOperatorAtom,ze as PropertyType,We as ReadablePromise,Jr as SearchParameterType,Vt as SymbolAtom,wt as Tokenizer,Xt as UnaryOperatorAtom,nr as UnionAtom,pr as XorAtom,be as allOk,V as arrayBufferToBase64,G as arrayBufferToHex,_e as assertOk,Ae as badRequest,Et as booleanToTypedValue,Ze as buildTypeName,I as calculateAge,U as calculateAgeString,J as capitalize,Gr as checkForNull,e as convertToTransactionBundle,E as createReference,Vr as createStructureIssue,Ee as created,$ as deepClone,Q as deepEquals,Tr as evalFhirPath,kr as evalFhirPathTyped,At as fhirPathArrayEquals,Ut as fhirPathArrayEquivalent,It as fhirPathEquals,Ot as fhirPathEquivalent,Mt as fhirPathIs,Rt as fhirPathNot,Z as findObservationInterval,ee as findObservationReferenceRange,Pe as forbidden,n as formatAddress,x as formatCodeableConcept,S as formatCoding,c as formatDate,d as formatDateTime,s as formatFamilyName,o as formatGivenName,i as formatHumanName,v as formatMoney,w as formatObservationValue,p as formatPeriod,g as formatQuantity,y as formatRange,fn as formatSearchQuery,u as formatTime,m as formatTiming,Y as getCodeBySystem,A as getDateProperty,P as getDisplayString,at as getElementDefinition,Ke as getElementDefinitionTypeName,Zr as getExpressionForResourceType,_ as getExtension,N as getExtensionValue,M as getIdentifier,D as getImageSrc,it as getPropertyDisplayName,O as getQuestionnaireAnswers,T as getReferenceString,rt as getResourceTypeSchema,tt as getResourceTypes,Xr as getSearchParameterDetails,nt as getSearchParameters,Ne as getStatus,Ct as getTypedPropertyValue,dt as globalSchema,De as gone,Ye as indexSearchParameter,Xe as indexSearchParameterBundle,Je as indexStructureDefinition,Ve as indexStructureDefinitionBundle,wr as initFhirPathParserBuilder,q as isEmpty,Me as isGone,X as isLowerCase,Le as isNotFound,F as isObject,Oe as isOk,Ue as isOperationOutcome,Nt as isPeriod,C as isProfileResource,_t as isQuantity,Bt as isQuantityEquivalent,ut as isReference,ct as isResource,Wr as isResourceType,et as isResourceTypeSchema,H as isStringArray,W as isUUID,a as isValidDate,re as matchesRange,mn as matchesSearchRequest,qe as normalizeErrorString,je as normalizeOperationOutcome,ke as notFound,Te as notModified,Qe as operationOutcomeToString,Er as parseFhirPath,Nr as parseFilterParameter,he as parseJWTPayload,Rr as parseMappingLanguage,cn as parseSearchDefinition,sn as parseSearchRequest,an as parseSearchUrl,ie as preciseEquals,se as preciseGreaterThan,ce as preciseGreaterThanOrEquals,oe as preciseLessThan,ae as preciseLessThanOrEquals,ne as preciseRound,Dt as removeDuplicates,k as resolveId,K as setCodeBySystem,B as stringify,kt as toJsBoolean,Tt as toTypedValue,yr as tokenize,Re as tooManyRequests,Ce as unauthorized,Hr as validateResource,Fr as validateResourceType,Ie as validationError};