medplum 5.1.11 → 5.1.13

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.
@@ -1,25 +1,25 @@
1
1
  #!/usr/bin/env node
2
- import{MEDPLUM_VERSION as Vs,normalizeErrorString as rt}from"@medplum/core";import{CommanderError as er,Option as Xs}from"commander";import zs from"dotenv";import{ContentType as tr,EMPTY as qs,isOk as Ys,isUUID as Qs}from"@medplum/core";import{Option as gt}from"commander";import{MedplumClient as Zs}from"@medplum/core";import{ClientStorage as eo}from"@medplum/core";import{existsSync as Tt,mkdirSync as to,readFileSync as ro,writeFileSync as so}from"node:fs";import{homedir as oo}from"node:os";import{resolve as Pt}from"node:path";import{ContentType as qe,encodeBase64 as Nt,OAuthSigningAlgorithm as rr}from"@medplum/core";import{Command as co}from"commander";import{Buffer as lo}from"node:buffer";import*as or from"node:util";import*as ar from"node:crypto";import*as nr from"node:util";import{KeyObject as So}from"node:crypto";import{KeyObject as Po}from"node:crypto";import{constants as Mt,KeyObject as Do}from"node:crypto";import*as Fe from"node:crypto";import{promisify as xo}from"node:util";import{KeyObject as Dt,createSecretKey as Ut}from"node:crypto";import{createHmac as zo,createPrivateKey as qo,randomBytes as Yo}from"node:crypto";import{existsSync as Qo,readFileSync as hr,writeFileSync as mr}from"node:fs";import{basename as fr,extname as Zo,resolve as yt}from"node:path";import{isPromise as ei}from"node:util/types";import{extract as ti}from"tar";import{ContentType as Ne,getDisplayString as wi,MEDPLUM_CLI_CLIENT_ID as yi,normalizeErrorString as Ei}from"@medplum/core";import{exec as vi}from"node:child_process";import{createServer as Si}from"node:http";import{platform as Ii}from"node:os";import{CloudFormationClient as Lr,DescribeStackResourcesCommand as Mi,DescribeStacksCommand as Di,paginateListStacks as Ui}from"@aws-sdk/client-cloudformation";import{CloudFrontClient as _i,CreateInvalidationCommand as xi}from"@aws-sdk/client-cloudfront";import{ECSClient as ji}from"@aws-sdk/client-ecs";import{S3Client as Fi}from"@aws-sdk/client-s3";import{GetParameterCommand as Wi,PutParameterCommand as Hi,SSMClient as Bi}from"@aws-sdk/client-ssm";import{GetCallerIdentityCommand as Ki,STSClient as Gi}from"@aws-sdk/client-sts";import{EMPTY as Ji,normalizeErrorString as Vi}from"@medplum/core";import Xi from"node-fetch";import{readdirSync as zi}from"node:fs";import qi from"node:readline";import{ACMClient as Wr,ListCertificatesCommand as oa,RequestCertificateCommand as ia}from"@aws-sdk/client-acm";import{CloudFrontClient as aa,CreatePublicKeyCommand as na}from"@aws-sdk/client-cloudfront";import{GetCallerIdentityCommand as ca,STSClient as la}from"@aws-sdk/client-sts";import{normalizeErrorString as ua}from"@medplum/core";import{generateKeyPairSync as pa,randomUUID as Ft}from"node:crypto";import{existsSync as da}from"node:fs";import{PutObjectCommand as Sa}from"@aws-sdk/client-s3";import{ContentType as Y}from"@medplum/core";import Ia from"fast-glob";import Br from"node-fetch";import{createReadStream as ba,mkdtempSync as Aa,readdirSync as $a,readFileSync as Ra,rmSync as Ta,writeFileSync as Pa}from"node:fs";import{tmpdir as Na}from"node:os";import{join as Me,sep as Oa}from"node:path";import{pipeline as Ca}from"node:stream/promises";import{GetBucketPolicyCommand as ja,PutBucketPolicyCommand as Fa}from"@aws-sdk/client-s3";import{spawnSync as qa}from"node:child_process";import{EMPTY as Yr}from"@medplum/core";import{createReadStream as tn,createWriteStream as rn}from"node:fs";import{resolve as Qr}from"node:path";import{createInterface as sn}from"node:readline";import{Readable as on}from"node:stream";import{pipeline as an}from"node:stream/promises";import{formatHl7DateTime as pn,Hl7Message as dn}from"@medplum/core";import Ce from"node:assert";import{connect as hn}from"node:net";import{Hl7Message as mn,OperationOutcomeError as ie,ReturnAckCategory as Gt,sleep as fn,validationError as gn}from"@medplum/core";import Jt from"iconv-lite";import"@medplum/core";import{sleep as wn}from"@medplum/core";import yn from"node:net";import{readFileSync as Pn}from"node:fs";import{readdirSync as Ln}from"node:fs";import{homedir as kn}from"node:os";import{resolve as Mn}from"node:path";import{Option as Dn}from"commander";import{convertToTransactionBundle as jn}from"@medplum/core";var gs=Object.create,lt=Object.defineProperty,ws=Object.getOwnPropertyDescriptor,ys=Object.getOwnPropertyNames,Es=Object.getPrototypeOf,vs=Object.prototype.hasOwnProperty,Ss=(e,t,r)=>t in e?lt(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,A=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),Is=(e,t,r,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of ys(t))!vs.call(e,o)&&o!==r&&lt(e,o,{get:()=>t[o],enumerable:!(s=ws(t,o))||s.enumerable});return e},Xt=(e,t,r)=>(r=e!=null?gs(Es(e)):{},Is(t||!e||!e.__esModule?lt(r,"default",{value:e,enumerable:!0}):r,e)),B=(e,t,r)=>Ss(e,typeof t!="symbol"?t+"":t,r),De=A((e,t)=>{"use strict";var r="2.0.0",s=Number.MAX_SAFE_INTEGER||9007199254740991,o=16,i=250,a=["major","premajor","minor","preminor","patch","prepatch","prerelease"];t.exports={MAX_LENGTH:256,MAX_SAFE_COMPONENT_LENGTH:o,MAX_SAFE_BUILD_LENGTH:i,MAX_SAFE_INTEGER:s,RELEASE_TYPES:a,SEMVER_SPEC_VERSION:r,FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2}}),Ue=A((e,t)=>{"use strict";var r=typeof process=="object"&&process.env&&process.env.NODE_DEBUG&&/\bsemver\b/i.test(process.env.NODE_DEBUG)?(...s)=>console.error("SEMVER",...s):()=>{};t.exports=r}),Ie=A((e,t)=>{"use strict";var{MAX_SAFE_COMPONENT_LENGTH:r,MAX_SAFE_BUILD_LENGTH:s,MAX_LENGTH:o}=De(),i=Ue();e=t.exports={};var a=e.re=[],c=e.safeRe=[],n=e.src=[],f=e.safeSrc=[],l=e.t={},u=0,d="[a-zA-Z0-9-]",m=[["\\s",1],["\\d",o],[d,s]],g=N=>{for(let[T,O]of m)N=N.split(`${T}*`).join(`${T}{0,${O}}`).split(`${T}+`).join(`${T}{1,${O}}`);return N},h=(N,T,O)=>{let j=g(T),W=u++;i(N,W,T),l[N]=W,n[W]=T,f[W]=j,a[W]=new RegExp(T,O?"g":void 0),c[W]=new RegExp(j,O?"g":void 0)};h("NUMERICIDENTIFIER","0|[1-9]\\d*"),h("NUMERICIDENTIFIERLOOSE","\\d+"),h("NONNUMERICIDENTIFIER",`\\d*[a-zA-Z-]${d}*`),h("MAINVERSION",`(${n[l.NUMERICIDENTIFIER]})\\.(${n[l.NUMERICIDENTIFIER]})\\.(${n[l.NUMERICIDENTIFIER]})`),h("MAINVERSIONLOOSE",`(${n[l.NUMERICIDENTIFIERLOOSE]})\\.(${n[l.NUMERICIDENTIFIERLOOSE]})\\.(${n[l.NUMERICIDENTIFIERLOOSE]})`),h("PRERELEASEIDENTIFIER",`(?:${n[l.NONNUMERICIDENTIFIER]}|${n[l.NUMERICIDENTIFIER]})`),h("PRERELEASEIDENTIFIERLOOSE",`(?:${n[l.NONNUMERICIDENTIFIER]}|${n[l.NUMERICIDENTIFIERLOOSE]})`),h("PRERELEASE",`(?:-(${n[l.PRERELEASEIDENTIFIER]}(?:\\.${n[l.PRERELEASEIDENTIFIER]})*))`),h("PRERELEASELOOSE",`(?:-?(${n[l.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${n[l.PRERELEASEIDENTIFIERLOOSE]})*))`),h("BUILDIDENTIFIER",`${d}+`),h("BUILD",`(?:\\+(${n[l.BUILDIDENTIFIER]}(?:\\.${n[l.BUILDIDENTIFIER]})*))`),h("FULLPLAIN",`v?${n[l.MAINVERSION]}${n[l.PRERELEASE]}?${n[l.BUILD]}?`),h("FULL",`^${n[l.FULLPLAIN]}$`),h("LOOSEPLAIN",`[v=\\s]*${n[l.MAINVERSIONLOOSE]}${n[l.PRERELEASELOOSE]}?${n[l.BUILD]}?`),h("LOOSE",`^${n[l.LOOSEPLAIN]}$`),h("GTLT","((?:<|>)?=?)"),h("XRANGEIDENTIFIERLOOSE",`${n[l.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`),h("XRANGEIDENTIFIER",`${n[l.NUMERICIDENTIFIER]}|x|X|\\*`),h("XRANGEPLAIN",`[v=\\s]*(${n[l.XRANGEIDENTIFIER]})(?:\\.(${n[l.XRANGEIDENTIFIER]})(?:\\.(${n[l.XRANGEIDENTIFIER]})(?:${n[l.PRERELEASE]})?${n[l.BUILD]}?)?)?`),h("XRANGEPLAINLOOSE",`[v=\\s]*(${n[l.XRANGEIDENTIFIERLOOSE]})(?:\\.(${n[l.XRANGEIDENTIFIERLOOSE]})(?:\\.(${n[l.XRANGEIDENTIFIERLOOSE]})(?:${n[l.PRERELEASELOOSE]})?${n[l.BUILD]}?)?)?`),h("XRANGE",`^${n[l.GTLT]}\\s*${n[l.XRANGEPLAIN]}$`),h("XRANGELOOSE",`^${n[l.GTLT]}\\s*${n[l.XRANGEPLAINLOOSE]}$`),h("COERCEPLAIN",`(^|[^\\d])(\\d{1,${r}})(?:\\.(\\d{1,${r}}))?(?:\\.(\\d{1,${r}}))?`),h("COERCE",`${n[l.COERCEPLAIN]}(?:$|[^\\d])`),h("COERCEFULL",n[l.COERCEPLAIN]+`(?:${n[l.PRERELEASE]})?(?:${n[l.BUILD]})?(?:$|[^\\d])`),h("COERCERTL",n[l.COERCE],!0),h("COERCERTLFULL",n[l.COERCEFULL],!0),h("LONETILDE","(?:~>?)"),h("TILDETRIM",`(\\s*)${n[l.LONETILDE]}\\s+`,!0),e.tildeTrimReplace="$1~",h("TILDE",`^${n[l.LONETILDE]}${n[l.XRANGEPLAIN]}$`),h("TILDELOOSE",`^${n[l.LONETILDE]}${n[l.XRANGEPLAINLOOSE]}$`),h("LONECARET","(?:\\^)"),h("CARETTRIM",`(\\s*)${n[l.LONECARET]}\\s+`,!0),e.caretTrimReplace="$1^",h("CARET",`^${n[l.LONECARET]}${n[l.XRANGEPLAIN]}$`),h("CARETLOOSE",`^${n[l.LONECARET]}${n[l.XRANGEPLAINLOOSE]}$`),h("COMPARATORLOOSE",`^${n[l.GTLT]}\\s*(${n[l.LOOSEPLAIN]})$|^$`),h("COMPARATOR",`^${n[l.GTLT]}\\s*(${n[l.FULLPLAIN]})$|^$`),h("COMPARATORTRIM",`(\\s*)${n[l.GTLT]}\\s*(${n[l.LOOSEPLAIN]}|${n[l.XRANGEPLAIN]})`,!0),e.comparatorTrimReplace="$1$2$3",h("HYPHENRANGE",`^\\s*(${n[l.XRANGEPLAIN]})\\s+-\\s+(${n[l.XRANGEPLAIN]})\\s*$`),h("HYPHENRANGELOOSE",`^\\s*(${n[l.XRANGEPLAINLOOSE]})\\s+-\\s+(${n[l.XRANGEPLAINLOOSE]})\\s*$`),h("STAR","(<|>)?=?\\s*\\*"),h("GTE0","^\\s*>=\\s*0\\.0\\.0\\s*$"),h("GTE0PRE","^\\s*>=\\s*0\\.0\\.0-0\\s*$")}),ut=A((e,t)=>{"use strict";var r=Object.freeze({loose:!0}),s=Object.freeze({}),o=i=>i?typeof i!="object"?r:i:s;t.exports=o}),zt=A((e,t)=>{"use strict";var r=/^[0-9]+$/,s=(i,a)=>{if(typeof i=="number"&&typeof a=="number")return i===a?0:i<a?-1:1;let c=r.test(i),n=r.test(a);return c&&n&&(i=+i,a=+a),i===a?0:c&&!n?-1:n&&!c?1:i<a?-1:1},o=(i,a)=>s(a,i);t.exports={compareIdentifiers:s,rcompareIdentifiers:o}}),G=A((e,t)=>{"use strict";var r=Ue(),{MAX_LENGTH:s,MAX_SAFE_INTEGER:o}=De(),{safeRe:i,t:a}=Ie(),c=ut(),{compareIdentifiers:n}=zt(),f=class Q{constructor(u,d){if(d=c(d),u instanceof Q){if(u.loose===!!d.loose&&u.includePrerelease===!!d.includePrerelease)return u;u=u.version}else if(typeof u!="string")throw new TypeError(`Invalid version. Must be a string. Got type "${typeof u}".`);if(u.length>s)throw new TypeError(`version is longer than ${s} characters`);r("SemVer",u,d),this.options=d,this.loose=!!d.loose,this.includePrerelease=!!d.includePrerelease;let m=u.trim().match(d.loose?i[a.LOOSE]:i[a.FULL]);if(!m)throw new TypeError(`Invalid Version: ${u}`);if(this.raw=u,this.major=+m[1],this.minor=+m[2],this.patch=+m[3],this.major>o||this.major<0)throw new TypeError("Invalid major version");if(this.minor>o||this.minor<0)throw new TypeError("Invalid minor version");if(this.patch>o||this.patch<0)throw new TypeError("Invalid patch version");m[4]?this.prerelease=m[4].split(".").map(g=>{if(/^[0-9]+$/.test(g)){let h=+g;if(h>=0&&h<o)return h}return g}):this.prerelease=[],this.build=m[5]?m[5].split("."):[],this.format()}format(){return this.version=`${this.major}.${this.minor}.${this.patch}`,this.prerelease.length&&(this.version+=`-${this.prerelease.join(".")}`),this.version}toString(){return this.version}compare(u){if(r("SemVer.compare",this.version,this.options,u),!(u instanceof Q)){if(typeof u=="string"&&u===this.version)return 0;u=new Q(u,this.options)}return u.version===this.version?0:this.compareMain(u)||this.comparePre(u)}compareMain(u){return u instanceof Q||(u=new Q(u,this.options)),this.major<u.major?-1:this.major>u.major?1:this.minor<u.minor?-1:this.minor>u.minor?1:this.patch<u.patch?-1:this.patch>u.patch?1:0}comparePre(u){if(u instanceof Q||(u=new Q(u,this.options)),this.prerelease.length&&!u.prerelease.length)return-1;if(!this.prerelease.length&&u.prerelease.length)return 1;if(!this.prerelease.length&&!u.prerelease.length)return 0;let d=0;do{let m=this.prerelease[d],g=u.prerelease[d];if(r("prerelease compare",d,m,g),m===void 0&&g===void 0)return 0;if(g===void 0)return 1;if(m===void 0)return-1;if(m!==g)return n(m,g)}while(++d)}compareBuild(u){u instanceof Q||(u=new Q(u,this.options));let d=0;do{let m=this.build[d],g=u.build[d];if(r("build compare",d,m,g),m===void 0&&g===void 0)return 0;if(g===void 0)return 1;if(m===void 0)return-1;if(m!==g)return n(m,g)}while(++d)}inc(u,d,m){if(u.startsWith("pre")){if(!d&&m===!1)throw new Error("invalid increment argument: identifier is empty");if(d){let g=`-${d}`.match(this.options.loose?i[a.PRERELEASELOOSE]:i[a.PRERELEASE]);if(!g||g[1]!==d)throw new Error(`invalid identifier: ${d}`)}}switch(u){case"premajor":this.prerelease.length=0,this.patch=0,this.minor=0,this.major++,this.inc("pre",d,m);break;case"preminor":this.prerelease.length=0,this.patch=0,this.minor++,this.inc("pre",d,m);break;case"prepatch":this.prerelease.length=0,this.inc("patch",d,m),this.inc("pre",d,m);break;case"prerelease":this.prerelease.length===0&&this.inc("patch",d,m),this.inc("pre",d,m);break;case"release":if(this.prerelease.length===0)throw new Error(`version ${this.raw} is not a prerelease`);this.prerelease.length=0;break;case"major":(this.minor!==0||this.patch!==0||this.prerelease.length===0)&&this.major++,this.minor=0,this.patch=0,this.prerelease=[];break;case"minor":(this.patch!==0||this.prerelease.length===0)&&this.minor++,this.patch=0,this.prerelease=[];break;case"patch":this.prerelease.length===0&&this.patch++,this.prerelease=[];break;case"pre":{let g=Number(m)?1:0;if(this.prerelease.length===0)this.prerelease=[g];else{let h=this.prerelease.length;for(;--h>=0;)typeof this.prerelease[h]=="number"&&(this.prerelease[h]++,h=-2);if(h===-1){if(d===this.prerelease.join(".")&&m===!1)throw new Error("invalid increment argument: identifier already exists");this.prerelease.push(g)}}if(d){let h=[d,g];m===!1&&(h=[d]),n(this.prerelease[0],d)===0?isNaN(this.prerelease[1])&&(this.prerelease=h):this.prerelease=h}break}default:throw new Error(`invalid increment argument: ${u}`)}return this.raw=this.format(),this.build.length&&(this.raw+=`+${this.build.join(".")}`),this}};t.exports=f}),ue=A((e,t)=>{"use strict";var r=G(),s=(o,i,a=!1)=>{if(o instanceof r)return o;try{return new r(o,i)}catch(c){if(!a)return null;throw c}};t.exports=s}),bs=A((e,t)=>{"use strict";var r=ue(),s=(o,i)=>{let a=r(o,i);return a?a.version:null};t.exports=s}),As=A((e,t)=>{"use strict";var r=ue(),s=(o,i)=>{let a=r(o.trim().replace(/^[=v]+/,""),i);return a?a.version:null};t.exports=s}),$s=A((e,t)=>{"use strict";var r=G(),s=(o,i,a,c,n)=>{typeof a=="string"&&(n=c,c=a,a=void 0);try{return new r(o instanceof r?o.version:o,a).inc(i,c,n).version}catch{return null}};t.exports=s}),Rs=A((e,t)=>{"use strict";var r=ue(),s=(o,i)=>{let a=r(o,null,!0),c=r(i,null,!0),n=a.compare(c);if(n===0)return null;let f=n>0,l=f?a:c,u=f?c:a,d=!!l.prerelease.length;if(u.prerelease.length&&!d){if(!u.patch&&!u.minor)return"major";if(u.compareMain(l)===0)return u.minor&&!u.patch?"minor":"patch"}let m=d?"pre":"";return a.major!==c.major?m+"major":a.minor!==c.minor?m+"minor":a.patch!==c.patch?m+"patch":"prerelease"};t.exports=s}),Ts=A((e,t)=>{"use strict";var r=G(),s=(o,i)=>new r(o,i).major;t.exports=s}),Ps=A((e,t)=>{"use strict";var r=G(),s=(o,i)=>new r(o,i).minor;t.exports=s}),Ns=A((e,t)=>{"use strict";var r=G(),s=(o,i)=>new r(o,i).patch;t.exports=s}),Os=A((e,t)=>{"use strict";var r=ue(),s=(o,i)=>{let a=r(o,i);return a&&a.prerelease.length?a.prerelease:null};t.exports=s}),X=A((e,t)=>{"use strict";var r=G(),s=(o,i,a)=>new r(o,a).compare(new r(i,a));t.exports=s}),Cs=A((e,t)=>{"use strict";var r=X(),s=(o,i,a)=>r(i,o,a);t.exports=s}),Ls=A((e,t)=>{"use strict";var r=X(),s=(o,i)=>r(o,i,!0);t.exports=s}),pt=A((e,t)=>{"use strict";var r=G(),s=(o,i,a)=>{let c=new r(o,a),n=new r(i,a);return c.compare(n)||c.compareBuild(n)};t.exports=s}),ks=A((e,t)=>{"use strict";var r=pt(),s=(o,i)=>o.sort((a,c)=>r(a,c,i));t.exports=s}),Ms=A((e,t)=>{"use strict";var r=pt(),s=(o,i)=>o.sort((a,c)=>r(c,a,i));t.exports=s}),_e=A((e,t)=>{"use strict";var r=X(),s=(o,i,a)=>r(o,i,a)>0;t.exports=s}),dt=A((e,t)=>{"use strict";var r=X(),s=(o,i,a)=>r(o,i,a)<0;t.exports=s}),qt=A((e,t)=>{"use strict";var r=X(),s=(o,i,a)=>r(o,i,a)===0;t.exports=s}),Yt=A((e,t)=>{"use strict";var r=X(),s=(o,i,a)=>r(o,i,a)!==0;t.exports=s}),ht=A((e,t)=>{"use strict";var r=X(),s=(o,i,a)=>r(o,i,a)>=0;t.exports=s}),mt=A((e,t)=>{"use strict";var r=X(),s=(o,i,a)=>r(o,i,a)<=0;t.exports=s}),Qt=A((e,t)=>{"use strict";var r=qt(),s=Yt(),o=_e(),i=ht(),a=dt(),c=mt(),n=(f,l,u,d)=>{switch(l){case"===":return typeof f=="object"&&(f=f.version),typeof u=="object"&&(u=u.version),f===u;case"!==":return typeof f=="object"&&(f=f.version),typeof u=="object"&&(u=u.version),f!==u;case"":case"=":case"==":return r(f,u,d);case"!=":return s(f,u,d);case">":return o(f,u,d);case">=":return i(f,u,d);case"<":return a(f,u,d);case"<=":return c(f,u,d);default:throw new TypeError(`Invalid operator: ${l}`)}};t.exports=n}),Ds=A((e,t)=>{"use strict";var r=G(),s=ue(),{safeRe:o,t:i}=Ie(),a=(c,n)=>{if(c instanceof r)return c;if(typeof c=="number"&&(c=String(c)),typeof c!="string")return null;n=n||{};let f=null;if(!n.rtl)f=c.match(n.includePrerelease?o[i.COERCEFULL]:o[i.COERCE]);else{let h=n.includePrerelease?o[i.COERCERTLFULL]:o[i.COERCERTL],N;for(;(N=h.exec(c))&&(!f||f.index+f[0].length!==c.length);)(!f||N.index+N[0].length!==f.index+f[0].length)&&(f=N),h.lastIndex=N.index+N[1].length+N[2].length;h.lastIndex=-1}if(f===null)return null;let l=f[2],u=f[3]||"0",d=f[4]||"0",m=n.includePrerelease&&f[5]?`-${f[5]}`:"",g=n.includePrerelease&&f[6]?`+${f[6]}`:"";return s(`${l}.${u}.${d}${m}${g}`,n)};t.exports=a}),Us=A((e,t)=>{"use strict";var r=class{constructor(){this.max=1e3,this.map=new Map}get(s){let o=this.map.get(s);if(o!==void 0)return this.map.delete(s),this.map.set(s,o),o}delete(s){return this.map.delete(s)}set(s,o){if(!this.delete(s)&&o!==void 0){if(this.map.size>=this.max){let i=this.map.keys().next().value;this.delete(i)}this.map.set(s,o)}return this}};t.exports=r}),z=A((e,t)=>{"use strict";var r=/\s+/g,s=class Le{constructor(w,S){if(S=a(S),w instanceof Le)return w.loose===!!S.loose&&w.includePrerelease===!!S.includePrerelease?w:new Le(w.raw,S);if(w instanceof c)return this.raw=w.value,this.set=[[w]],this.formatted=void 0,this;if(this.options=S,this.loose=!!S.loose,this.includePrerelease=!!S.includePrerelease,this.raw=w.trim().replace(r," "),this.set=this.raw.split("||").map(E=>this.parseRange(E.trim())).filter(E=>E.length),!this.set.length)throw new TypeError(`Invalid SemVer Range: ${this.raw}`);if(this.set.length>1){let E=this.set[0];if(this.set=this.set.filter(I=>!T(I[0])),this.set.length===0)this.set=[E];else if(this.set.length>1){for(let I of this.set)if(I.length===1&&O(I[0])){this.set=[I];break}}}this.formatted=void 0}get range(){if(this.formatted===void 0){this.formatted="";for(let w=0;w<this.set.length;w++){w>0&&(this.formatted+="||");let S=this.set[w];for(let E=0;E<S.length;E++)E>0&&(this.formatted+=" "),this.formatted+=S[E].toString().trim()}}return this.formatted}format(){return this.range}toString(){return this.range}parseRange(w){let S=((this.options.includePrerelease&&h)|(this.options.loose&&N))+":"+w,E=i.get(S);if(E)return E;let I=this.options.loose,v=I?l[u.HYPHENRANGELOOSE]:l[u.HYPHENRANGE];w=w.replace(v,Xe(this.options.includePrerelease)),n("hyphen replace",w),w=w.replace(l[u.COMPARATORTRIM],d),n("comparator trim",w),w=w.replace(l[u.TILDETRIM],m),n("tilde trim",w),w=w.replace(l[u.CARETTRIM],g),n("caret trim",w);let b=w.split(" ").map(D=>W(D,this.options)).join(" ").split(/\s+/).map(D=>Ve(D,this.options));I&&(b=b.filter(D=>(n("loose invalid filter",D,this.options),!!D.match(l[u.COMPARATORLOOSE])))),n("range list",b);let k=new Map,C=b.map(D=>new c(D,this.options));for(let D of C){if(T(D))return[D];k.set(D.value,D)}k.size>1&&k.has("")&&k.delete("");let M=[...k.values()];return i.set(S,M),M}intersects(w,S){if(!(w instanceof Le))throw new TypeError("a Range is required");return this.set.some(E=>j(E,S)&&w.set.some(I=>j(I,S)&&E.every(v=>I.every(b=>v.intersects(b,S)))))}test(w){if(!w)return!1;if(typeof w=="string")try{w=new f(w,this.options)}catch{return!1}for(let S=0;S<this.set.length;S++)if(ze(this.set[S],w,this.options))return!0;return!1}};t.exports=s;var o=Us(),i=new o,a=ut(),c=xe(),n=Ue(),f=G(),{safeRe:l,t:u,comparatorTrimReplace:d,tildeTrimReplace:m,caretTrimReplace:g}=Ie(),{FLAG_INCLUDE_PRERELEASE:h,FLAG_LOOSE:N}=De(),T=y=>y.value==="<0.0.0-0",O=y=>y.value==="",j=(y,w)=>{let S=!0,E=y.slice(),I=E.pop();for(;S&&E.length;)S=E.every(v=>I.intersects(v,w)),I=E.pop();return S},W=(y,w)=>(y=y.replace(l[u.BUILD],""),n("comp",y,w),y=_(y,w),n("caret",y),y=Z(y,w),n("tildes",y),y=$(y,w),n("xrange",y),y=Je(y,w),n("stars",y),y),U=y=>!y||y.toLowerCase()==="x"||y==="*",Z=(y,w)=>y.trim().split(/\s+/).map(S=>J(S,w)).join(" "),J=(y,w)=>{let S=w.loose?l[u.TILDELOOSE]:l[u.TILDE];return y.replace(S,(E,I,v,b,k)=>{n("tilde",y,E,I,v,b,k);let C;return U(I)?C="":U(v)?C=`>=${I}.0.0 <${+I+1}.0.0-0`:U(b)?C=`>=${I}.${v}.0 <${I}.${+v+1}.0-0`:k?(n("replaceTilde pr",k),C=`>=${I}.${v}.${b}-${k} <${I}.${+v+1}.0-0`):C=`>=${I}.${v}.${b} <${I}.${+v+1}.0-0`,n("tilde return",C),C})},_=(y,w)=>y.trim().split(/\s+/).map(S=>H(S,w)).join(" "),H=(y,w)=>{n("caret",y,w);let S=w.loose?l[u.CARETLOOSE]:l[u.CARET],E=w.includePrerelease?"-0":"";return y.replace(S,(I,v,b,k,C)=>{n("caret",y,I,v,b,k,C);let M;return U(v)?M="":U(b)?M=`>=${v}.0.0${E} <${+v+1}.0.0-0`:U(k)?v==="0"?M=`>=${v}.${b}.0${E} <${v}.${+b+1}.0-0`:M=`>=${v}.${b}.0${E} <${+v+1}.0.0-0`:C?(n("replaceCaret pr",C),v==="0"?b==="0"?M=`>=${v}.${b}.${k}-${C} <${v}.${b}.${+k+1}-0`:M=`>=${v}.${b}.${k}-${C} <${v}.${+b+1}.0-0`:M=`>=${v}.${b}.${k}-${C} <${+v+1}.0.0-0`):(n("no pr"),v==="0"?b==="0"?M=`>=${v}.${b}.${k}${E} <${v}.${b}.${+k+1}-0`:M=`>=${v}.${b}.${k}${E} <${v}.${+b+1}.0-0`:M=`>=${v}.${b}.${k} <${+v+1}.0.0-0`),n("caret return",M),M})},$=(y,w)=>(n("replaceXRanges",y,w),y.split(/\s+/).map(S=>me(S,w)).join(" ")),me=(y,w)=>{y=y.trim();let S=w.loose?l[u.XRANGELOOSE]:l[u.XRANGE];return y.replace(S,(E,I,v,b,k,C)=>{n("xRange",y,E,I,v,b,k,C);let M=U(v),D=M||U(b),oe=D||U(k),fe=oe;return I==="="&&fe&&(I=""),C=w.includePrerelease?"-0":"",M?I===">"||I==="<"?E="<0.0.0-0":E="*":I&&fe?(D&&(b=0),k=0,I===">"?(I=">=",D?(v=+v+1,b=0,k=0):(b=+b+1,k=0)):I==="<="&&(I="<",D?v=+v+1:b=+b+1),I==="<"&&(C="-0"),E=`${I+v}.${b}.${k}${C}`):D?E=`>=${v}.0.0${C} <${+v+1}.0.0-0`:oe&&(E=`>=${v}.${b}.0${C} <${v}.${+b+1}.0-0`),n("xRange return",E),E})},Je=(y,w)=>(n("replaceStars",y,w),y.trim().replace(l[u.STAR],"")),Ve=(y,w)=>(n("replaceGTE0",y,w),y.trim().replace(l[w.includePrerelease?u.GTE0PRE:u.GTE0],"")),Xe=y=>(w,S,E,I,v,b,k,C,M,D,oe,fe)=>(U(E)?S="":U(I)?S=`>=${E}.0.0${y?"-0":""}`:U(v)?S=`>=${E}.${I}.0${y?"-0":""}`:b?S=`>=${S}`:S=`>=${S}${y?"-0":""}`,U(M)?C="":U(D)?C=`<${+M+1}.0.0-0`:U(oe)?C=`<${M}.${+D+1}.0-0`:fe?C=`<=${M}.${D}.${oe}-${fe}`:y?C=`<${M}.${D}.${+oe+1}-0`:C=`<=${C}`,`${S} ${C}`.trim()),ze=(y,w,S)=>{for(let E=0;E<y.length;E++)if(!y[E].test(w))return!1;if(w.prerelease.length&&!S.includePrerelease){for(let E=0;E<y.length;E++)if(n(y[E].semver),y[E].semver!==c.ANY&&y[E].semver.prerelease.length>0){let I=y[E].semver;if(I.major===w.major&&I.minor===w.minor&&I.patch===w.patch)return!0}return!1}return!0}}),xe=A((e,t)=>{"use strict";var r=Symbol("SemVer ANY"),s=class tt{static get ANY(){return r}constructor(d,m){if(m=o(m),d instanceof tt){if(d.loose===!!m.loose)return d;d=d.value}d=d.trim().split(/\s+/).join(" "),n("comparator",d,m),this.options=m,this.loose=!!m.loose,this.parse(d),this.semver===r?this.value="":this.value=this.operator+this.semver.version,n("comp",this)}parse(d){let m=this.options.loose?i[a.COMPARATORLOOSE]:i[a.COMPARATOR],g=d.match(m);if(!g)throw new TypeError(`Invalid comparator: ${d}`);this.operator=g[1]!==void 0?g[1]:"",this.operator==="="&&(this.operator=""),g[2]?this.semver=new f(g[2],this.options.loose):this.semver=r}toString(){return this.value}test(d){if(n("Comparator.test",d,this.options.loose),this.semver===r||d===r)return!0;if(typeof d=="string")try{d=new f(d,this.options)}catch{return!1}return c(d,this.operator,this.semver,this.options)}intersects(d,m){if(!(d instanceof tt))throw new TypeError("a Comparator is required");return this.operator===""?this.value===""?!0:new l(d.value,m).test(this.value):d.operator===""?d.value===""?!0:new l(this.value,m).test(d.semver):(m=o(m),m.includePrerelease&&(this.value==="<0.0.0-0"||d.value==="<0.0.0-0")||!m.includePrerelease&&(this.value.startsWith("<0.0.0")||d.value.startsWith("<0.0.0"))?!1:!!(this.operator.startsWith(">")&&d.operator.startsWith(">")||this.operator.startsWith("<")&&d.operator.startsWith("<")||this.semver.version===d.semver.version&&this.operator.includes("=")&&d.operator.includes("=")||c(this.semver,"<",d.semver,m)&&this.operator.startsWith(">")&&d.operator.startsWith("<")||c(this.semver,">",d.semver,m)&&this.operator.startsWith("<")&&d.operator.startsWith(">")))}};t.exports=s;var o=ut(),{safeRe:i,t:a}=Ie(),c=Qt(),n=Ue(),f=G(),l=z()}),je=A((e,t)=>{"use strict";var r=z(),s=(o,i,a)=>{try{i=new r(i,a)}catch{return!1}return i.test(o)};t.exports=s}),_s=A((e,t)=>{"use strict";var r=z(),s=(o,i)=>new r(o,i).set.map(a=>a.map(c=>c.value).join(" ").trim().split(" "));t.exports=s}),xs=A((e,t)=>{"use strict";var r=G(),s=z(),o=(i,a,c)=>{let n=null,f=null,l=null;try{l=new s(a,c)}catch{return null}return i.forEach(u=>{l.test(u)&&(!n||f.compare(u)===-1)&&(n=u,f=new r(n,c))}),n};t.exports=o}),js=A((e,t)=>{"use strict";var r=G(),s=z(),o=(i,a,c)=>{let n=null,f=null,l=null;try{l=new s(a,c)}catch{return null}return i.forEach(u=>{l.test(u)&&(!n||f.compare(u)===1)&&(n=u,f=new r(n,c))}),n};t.exports=o}),Fs=A((e,t)=>{"use strict";var r=G(),s=z(),o=_e(),i=(a,c)=>{a=new s(a,c);let n=new r("0.0.0");if(a.test(n)||(n=new r("0.0.0-0"),a.test(n)))return n;n=null;for(let f=0;f<a.set.length;++f){let l=a.set[f],u=null;l.forEach(d=>{let m=new r(d.semver.version);switch(d.operator){case">":m.prerelease.length===0?m.patch++:m.prerelease.push(0),m.raw=m.format();case"":case">=":(!u||o(m,u))&&(u=m);break;case"<":case"<=":break;default:throw new Error(`Unexpected operation: ${d.operator}`)}}),u&&(!n||o(n,u))&&(n=u)}return n&&a.test(n)?n:null};t.exports=i}),Ws=A((e,t)=>{"use strict";var r=z(),s=(o,i)=>{try{return new r(o,i).range||"*"}catch{return null}};t.exports=s}),ft=A((e,t)=>{"use strict";var r=G(),s=xe(),{ANY:o}=s,i=z(),a=je(),c=_e(),n=dt(),f=mt(),l=ht(),u=(d,m,g,h)=>{d=new r(d,h),m=new i(m,h);let N,T,O,j,W;switch(g){case">":N=c,T=f,O=n,j=">",W=">=";break;case"<":N=n,T=l,O=c,j="<",W="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if(a(d,m,h))return!1;for(let U=0;U<m.set.length;++U){let Z=m.set[U],J=null,_=null;if(Z.forEach(H=>{H.semver===o&&(H=new s(">=0.0.0")),J=J||H,_=_||H,N(H.semver,J.semver,h)?J=H:O(H.semver,_.semver,h)&&(_=H)}),J.operator===j||J.operator===W||(!_.operator||_.operator===j)&&T(d,_.semver)||_.operator===W&&O(d,_.semver))return!1}return!0};t.exports=u}),Hs=A((e,t)=>{"use strict";var r=ft(),s=(o,i,a)=>r(o,i,">",a);t.exports=s}),Bs=A((e,t)=>{"use strict";var r=ft(),s=(o,i,a)=>r(o,i,"<",a);t.exports=s}),Ks=A((e,t)=>{"use strict";var r=z(),s=(o,i,a)=>(o=new r(o,a),i=new r(i,a),o.intersects(i,a));t.exports=s}),Gs=A((e,t)=>{"use strict";var r=je(),s=X();t.exports=(o,i,a)=>{let c=[],n=null,f=null,l=o.sort((g,h)=>s(g,h,a));for(let g of l)r(g,i,a)?(f=g,n||(n=g)):(f&&c.push([n,f]),f=null,n=null);n&&c.push([n,null]);let u=[];for(let[g,h]of c)g===h?u.push(g):!h&&g===l[0]?u.push("*"):h?g===l[0]?u.push(`<=${h}`):u.push(`${g} - ${h}`):u.push(`>=${g}`);let d=u.join(" || "),m=typeof i.raw=="string"?i.raw:String(i);return d.length<m.length?d:i}}),Js=A((e,t)=>{"use strict";var r=z(),s=xe(),{ANY:o}=s,i=je(),a=X(),c=(m,g,h={})=>{if(m===g)return!0;m=new r(m,h),g=new r(g,h);let N=!1;e:for(let T of m.set){for(let O of g.set){let j=l(T,O,h);if(N=N||j!==null,j)continue e}if(N)return!1}return!0},n=[new s(">=0.0.0-0")],f=[new s(">=0.0.0")],l=(m,g,h)=>{if(m===g)return!0;if(m.length===1&&m[0].semver===o){if(g.length===1&&g[0].semver===o)return!0;h.includePrerelease?m=n:m=f}if(g.length===1&&g[0].semver===o){if(h.includePrerelease)return!0;g=f}let N=new Set,T,O;for(let $ of m)$.operator===">"||$.operator===">="?T=u(T,$,h):$.operator==="<"||$.operator==="<="?O=d(O,$,h):N.add($.semver);if(N.size>1)return null;let j;if(T&&O&&(j=a(T.semver,O.semver,h),j>0||j===0&&(T.operator!==">="||O.operator!=="<=")))return null;for(let $ of N){if(T&&!i($,String(T),h)||O&&!i($,String(O),h))return null;for(let me of g)if(!i($,String(me),h))return!1;return!0}let W,U,Z,J,_=O&&!h.includePrerelease&&O.semver.prerelease.length?O.semver:!1,H=T&&!h.includePrerelease&&T.semver.prerelease.length?T.semver:!1;_&&_.prerelease.length===1&&O.operator==="<"&&_.prerelease[0]===0&&(_=!1);for(let $ of g){if(J=J||$.operator===">"||$.operator===">=",Z=Z||$.operator==="<"||$.operator==="<=",T){if(H&&$.semver.prerelease&&$.semver.prerelease.length&&$.semver.major===H.major&&$.semver.minor===H.minor&&$.semver.patch===H.patch&&(H=!1),$.operator===">"||$.operator===">="){if(W=u(T,$,h),W===$&&W!==T)return!1}else if(T.operator===">="&&!i(T.semver,String($),h))return!1}if(O){if(_&&$.semver.prerelease&&$.semver.prerelease.length&&$.semver.major===_.major&&$.semver.minor===_.minor&&$.semver.patch===_.patch&&(_=!1),$.operator==="<"||$.operator==="<="){if(U=d(O,$,h),U===$&&U!==O)return!1}else if(O.operator==="<="&&!i(O.semver,String($),h))return!1}if(!$.operator&&(O||T)&&j!==0)return!1}return!(T&&Z&&!O&&j!==0||O&&J&&!T&&j!==0||H||_)},u=(m,g,h)=>{if(!m)return g;let N=a(m.semver,g.semver,h);return N>0?m:N<0||g.operator===">"&&m.operator===">="?g:m},d=(m,g,h)=>{if(!m)return g;let N=a(m.semver,g.semver,h);return N<0?m:N>0||g.operator==="<"&&m.operator==="<="?g:m};t.exports=c}),Zt=A((e,t)=>{"use strict";var r=Ie(),s=De(),o=G(),i=zt(),a=ue(),c=bs(),n=As(),f=$s(),l=Rs(),u=Ts(),d=Ps(),m=Ns(),g=Os(),h=X(),N=Cs(),T=Ls(),O=pt(),j=ks(),W=Ms(),U=_e(),Z=dt(),J=qt(),_=Yt(),H=ht(),$=mt(),me=Qt(),Je=Ds(),Ve=xe(),Xe=z(),ze=je(),y=_s(),w=xs(),S=js(),E=Fs(),I=Ws(),v=ft(),b=Hs(),k=Bs(),C=Ks(),M=Gs(),D=Js();t.exports={parse:a,valid:c,clean:n,inc:f,diff:l,major:u,minor:d,patch:m,prerelease:g,compare:h,rcompare:N,compareLoose:T,compareBuild:O,sort:j,rsort:W,gt:U,lt:Z,eq:J,neq:_,gte:H,lte:$,cmp:me,coerce:Je,Comparator:Ve,Range:Xe,satisfies:ze,toComparators:y,maxSatisfying:w,minSatisfying:S,minVersion:E,validRange:I,outside:v,gtr:b,ltr:k,intersects:C,simplifyRange:M,subset:D,SemVer:o,re:r.re,src:r.src,tokens:r.t,SEMVER_SPEC_VERSION:s.SEMVER_SPEC_VERSION,RELEASE_TYPES:s.RELEASE_TYPES,compareIdentifiers:i.compareIdentifiers,rcompareIdentifiers:i.rcompareIdentifiers}}),be=class extends eo{constructor(e){super(),B(this,"dirName"),B(this,"fileName"),this.dirName=Pt(oo(),".medplum"),this.fileName=Pt(this.dirName,e+".json")}clear(){this.writeFile({})}getString(e){return this.readFile()?.[e]}setString(e,t){let r=this.readFile()??{};t?r[e]=t:delete r[e],this.writeFile(r)}getObject(e){let t=this.getString(e);return t?JSON.parse(t):void 0}setObject(e,t){this.setString(e,t?JSON.stringify(t):void 0)}readFile(){if(Tt(this.fileName))return JSON.parse(ro(this.fileName,"utf8"))}writeFile(e){Tt(this.dirName)||to(this.dirName),so(this.fileName,JSON.stringify(e,null,2),"utf8")}};async function x(e,t=!0){let r=e.profile??"default",s=new be(r),o=s.getObject("options");if(r!=="default"&&!o)throw new Error(`Profile "${r}" does not exist`);let{baseUrl:i,fhirUrlPath:a,accessToken:c,tokenUrl:n,authorizeUrl:f,clientId:l,clientSecret:u}=io(e,s),d=e.fetch??fetch;e.baseUrl&&e.baseUrl!=="https://api.medplum.com/"&&await ao(e.baseUrl,d);let m=new Zs({fetch:d,baseUrl:i,tokenUrl:n,fhirUrlPath:a,authorizeUrl:f,storage:s,onUnauthenticated:no,verbose:e.verbose});return t&&(c?m.setAccessToken(c):l&&u&&(m.setBasicAuth(l,u),o?.authType!=="basic"&&await m.startClientLogin(l,u))),m}function io(e,t){let r=t.getObject("options"),s=e.baseUrl??r?.baseUrl??process.env.MEDPLUM_BASE_URL??"https://api.medplum.com/",o=e.fhirUrlPath??r?.fhirUrlPath??process.env.MEDPLUM_FHIR_URL_PATH,i=e.accessToken??r?.accessToken??process.env.MEDPLUM_CLIENT_ACCESS_TOKEN,a=e.tokenUrl??r?.tokenUrl??process.env.MEDPLUM_TOKEN_URL,c=e.authorizeUrl??r?.authorizeUrl??process.env.MEDPLUM_AUTHORIZE_URL,n=e.clientId??r?.clientId??process.env.MEDPLUM_CLIENT_ID,f=e.clientSecret??r?.clientSecret??process.env.MEDPLUM_CLIENT_SECRET;return{baseUrl:s,fhirUrlPath:o,accessToken:i,tokenUrl:a,authorizeUrl:c,clientId:n,clientSecret:f}}async function ao(e,t){try{let r=new URL("healthcheck",e).toString(),s=await t(r);if(!s.ok)throw new Error(`Healthcheck returned status ${s.status}`);if((await s.json()).ok===!0)return;throw new Error('Healthcheck response does not have "ok": true')}catch(r){let s=r instanceof Error?r.message:String(r);throw new Error(`Failed to validate base URL "${e}": ${s}`)}}function no(){console.log("Unauthenticated: run `npx medplum login` to sign in")}var Ee=new TextEncoder,Ot=new TextDecoder,rc=2**32;function uo(...e){let t=e.reduce((o,{length:i})=>o+i,0),r=new Uint8Array(t),s=0;for(let o of e)r.set(o,s),s+=o.length;return r}var Ye=e=>lo.from(e).toString("base64url"),Ae=class extends Error{constructor(e,t){super(e,t),B(this,"code","ERR_JOSE_GENERIC"),this.name=this.constructor.name,Error.captureStackTrace?.(this,this.constructor)}};B(Ae,"code","ERR_JOSE_GENERIC");var pe=class extends Ae{constructor(){super(...arguments),B(this,"code","ERR_JOSE_NOT_SUPPORTED")}};B(pe,"code","ERR_JOSE_NOT_SUPPORTED");var ae=class extends Ae{constructor(){super(...arguments),B(this,"code","ERR_JWS_INVALID")}};B(ae,"code","ERR_JWS_INVALID");var sr=class extends Ae{constructor(){super(...arguments),B(this,"code","ERR_JWT_INVALID")}};B(sr,"code","ERR_JWT_INVALID");var Ct,Lt,po=class extends(Lt=Ae,Ct=Symbol.asyncIterator,Lt){constructor(e="multiple matching keys found in the JSON Web Key Set",t){super(e,t),B(this,Ct),B(this,"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS")}};B(po,"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS");var ir=e=>or.types.isKeyObject(e),ho=ar.webcrypto,mo=ho,wt=e=>nr.types.isCryptoKey(e);function q(e,t="algorithm.name"){return new TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`)}function ge(e,t){return e.name===t}function Qe(e){return parseInt(e.name.slice(4),10)}function fo(e){switch(e){case"ES256":return"P-256";case"ES384":return"P-384";case"ES512":return"P-521";default:throw new Error("unreachable")}}function go(e,t){if(t.length&&!t.some(r=>e.usages.includes(r))){let r="CryptoKey does not support this operation, its usages must include ";if(t.length>2){let s=t.pop();r+=`one of ${t.join(", ")}, or ${s}.`}else t.length===2?r+=`one of ${t[0]} or ${t[1]}.`:r+=`${t[0]}.`;throw new TypeError(r)}}function wo(e,t,...r){switch(t){case"HS256":case"HS384":case"HS512":{if(!ge(e.algorithm,"HMAC"))throw q("HMAC");let s=parseInt(t.slice(2),10);if(Qe(e.algorithm.hash)!==s)throw q(`SHA-${s}`,"algorithm.hash");break}case"RS256":case"RS384":case"RS512":{if(!ge(e.algorithm,"RSASSA-PKCS1-v1_5"))throw q("RSASSA-PKCS1-v1_5");let s=parseInt(t.slice(2),10);if(Qe(e.algorithm.hash)!==s)throw q(`SHA-${s}`,"algorithm.hash");break}case"PS256":case"PS384":case"PS512":{if(!ge(e.algorithm,"RSA-PSS"))throw q("RSA-PSS");let s=parseInt(t.slice(2),10);if(Qe(e.algorithm.hash)!==s)throw q(`SHA-${s}`,"algorithm.hash");break}case"EdDSA":{if(e.algorithm.name!=="Ed25519"&&e.algorithm.name!=="Ed448")throw q("Ed25519 or Ed448");break}case"Ed25519":{if(!ge(e.algorithm,"Ed25519"))throw q("Ed25519");break}case"ES256":case"ES384":case"ES512":{if(!ge(e.algorithm,"ECDSA"))throw q("ECDSA");let s=fo(t);if(e.algorithm.namedCurve!==s)throw q(s,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}go(e,r)}function cr(e,t,...r){if(r=r.filter(Boolean),r.length>2){let s=r.pop();e+=`one of type ${r.join(", ")}, or ${s}.`}else r.length===2?e+=`one of type ${r[0]} or ${r[1]}.`:e+=`of type ${r[0]}.`;return t==null?e+=` Received ${t}`:typeof t=="function"&&t.name?e+=` Received function ${t.name}`:typeof t=="object"&&t!=null&&t.constructor?.name&&(e+=` Received an instance of ${t.constructor.name}`),e}var st=(e,...t)=>cr("Key must be ",e,...t);function lr(e,t,...r){return cr(`Key for the ${e} algorithm must be `,t,...r)}var ur=e=>ir(e)||wt(e),ce=["KeyObject"];(globalThis.CryptoKey||mo?.CryptoKey)&&ce.push("CryptoKey");var yo=(...e)=>{let t=e.filter(Boolean);if(t.length===0||t.length===1)return!0;let r;for(let s of t){let o=Object.keys(s);if(!r||r.size===0){r=new Set(o);continue}for(let i of o){if(r.has(i))return!1;r.add(i)}}return!0},Eo=yo;function vo(e){return typeof e=="object"&&e!==null}function pr(e){if(!vo(e)||Object.prototype.toString.call(e)!=="[object Object]")return!1;if(Object.getPrototypeOf(e)===null)return!0;let t=e;for(;Object.getPrototypeOf(t)!==null;)t=Object.getPrototypeOf(t);return Object.getPrototypeOf(e)===t}function $e(e){return pr(e)&&typeof e.kty=="string"}function Io(e){return e.kty!=="oct"&&typeof e.d=="string"}function bo(e){return e.kty!=="oct"&&typeof e.d>"u"}function Ao(e){return $e(e)&&e.kty==="oct"&&typeof e.k=="string"}var $o=e=>{switch(e){case"prime256v1":return"P-256";case"secp384r1":return"P-384";case"secp521r1":return"P-521";case"secp256k1":return"secp256k1";default:throw new pe("Unsupported key curve for this operation")}},Ro=(e,t)=>{let r;if(wt(e))r=So.from(e);else if(ir(e))r=e;else{if($e(e))return e.crv;throw new TypeError(st(e,...ce))}if(r.type==="secret")throw new TypeError('only "private" or "public" type keys can be used for this operation');switch(r.asymmetricKeyType){case"ed25519":case"ed448":return`Ed${r.asymmetricKeyType.slice(2)}`;case"x25519":case"x448":return`X${r.asymmetricKeyType.slice(1)}`;case"ec":{let s=r.asymmetricKeyDetails.namedCurve;return t?s:$o(s)}default:throw new TypeError("Invalid asymmetric key type for this operation")}},To=Ro,kt=(e,t)=>{let r;try{e instanceof Po?r=e.asymmetricKeyDetails?.modulusLength:r=Buffer.from(e.n,"base64url").byteLength<<3}catch{}if(typeof r!="number"||r<2048)throw new TypeError(`${t} requires key modulusLength to be 2048 bits or larger`)},ne=e=>e?.[Symbol.toStringTag],ot=(e,t,r)=>{if(t.use!==void 0&&t.use!=="sig")throw new TypeError("Invalid key for this operation, when present its use must be sig");if(t.key_ops!==void 0&&t.key_ops.includes?.(r)!==!0)throw new TypeError(`Invalid key for this operation, when present its key_ops must include ${r}`);if(t.alg!==void 0&&t.alg!==e)throw new TypeError(`Invalid key for this operation, when present its alg must be ${e}`);return!0},No=(e,t,r,s)=>{if(!(t instanceof Uint8Array)){if(s&&$e(t)){if(Ao(t)&&ot(e,t,r))return;throw new TypeError('JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present')}if(!ur(t))throw new TypeError(lr(e,t,...ce,"Uint8Array",s?"JSON Web Key":null));if(t.type!=="secret")throw new TypeError(`${ne(t)} instances for symmetric algorithms must be of type "secret"`)}},Oo=(e,t,r,s)=>{if(s&&$e(t))switch(r){case"sign":if(Io(t)&&ot(e,t,r))return;throw new TypeError("JSON Web Key for this operation be a private JWK");case"verify":if(bo(t)&&ot(e,t,r))return;throw new TypeError("JSON Web Key for this operation be a public JWK")}if(!ur(t))throw new TypeError(lr(e,t,...ce,s?"JSON Web Key":null));if(t.type==="secret")throw new TypeError(`${ne(t)} instances for asymmetric algorithms must not be of type "secret"`);if(r==="sign"&&t.type==="public")throw new TypeError(`${ne(t)} instances for asymmetric algorithm signing must be of type "private"`);if(r==="decrypt"&&t.type==="public")throw new TypeError(`${ne(t)} instances for asymmetric algorithm decryption must be of type "private"`);if(t.algorithm&&r==="verify"&&t.type==="private")throw new TypeError(`${ne(t)} instances for asymmetric algorithm verifying must be of type "public"`);if(t.algorithm&&r==="encrypt"&&t.type==="private")throw new TypeError(`${ne(t)} instances for asymmetric algorithm encryption must be of type "public"`)};function dr(e,t,r,s){t.startsWith("HS")||t==="dir"||t.startsWith("PBES2")||/^A\d{3}(?:GCM)?KW$/.test(t)?No(t,r,s,e):Oo(t,r,s,e)}var ic=dr.bind(void 0,!1),Co=dr.bind(void 0,!0);function Lo(e,t,r,s,o){if(o.crit!==void 0&&s?.crit===void 0)throw new e('"crit" (Critical) Header Parameter MUST be integrity protected');if(!s||s.crit===void 0)return new Set;if(!Array.isArray(s.crit)||s.crit.length===0||s.crit.some(a=>typeof a!="string"||a.length===0))throw new e('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');let i;r!==void 0?i=new Map([...Object.entries(r),...t.entries()]):i=t;for(let a of s.crit){if(!i.has(a))throw new pe(`Extension Header Parameter "${a}" is not recognized`);if(o[a]===void 0)throw new e(`Extension Header Parameter "${a}" is missing`);if(i.get(a)&&s[a]===void 0)throw new e(`Extension Header Parameter "${a}" MUST be integrity protected`)}return new Set(s.crit)}var ko=Lo;function Mo(e){switch(e){case"PS256":case"RS256":case"ES256":case"ES256K":return"sha256";case"PS384":case"RS384":case"ES384":return"sha384";case"PS512":case"RS512":case"ES512":return"sha512";case"Ed25519":case"EdDSA":return;default:throw new pe(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}var Uo=new Map([["ES256","P-256"],["ES256K","secp256k1"],["ES384","P-384"],["ES512","P-521"]]);function _o(e,t){let r,s,o;if(t instanceof Do)r=t.asymmetricKeyType,s=t.asymmetricKeyDetails;else switch(o=!0,t.kty){case"RSA":r="rsa";break;case"EC":r="ec";break;case"OKP":{if(t.crv==="Ed25519"){r="ed25519";break}if(t.crv==="Ed448"){r="ed448";break}throw new TypeError("Invalid key for this operation, its crv must be Ed25519 or Ed448")}default:throw new TypeError("Invalid key for this operation, its kty must be RSA, OKP, or EC")}let i;switch(e){case"Ed25519":if(r!=="ed25519")throw new TypeError("Invalid key for this operation, its asymmetricKeyType must be ed25519");break;case"EdDSA":if(!["ed25519","ed448"].includes(r))throw new TypeError("Invalid key for this operation, its asymmetricKeyType must be ed25519 or ed448");break;case"RS256":case"RS384":case"RS512":if(r!=="rsa")throw new TypeError("Invalid key for this operation, its asymmetricKeyType must be rsa");kt(t,e);break;case"PS256":case"PS384":case"PS512":if(r==="rsa-pss"){let{hashAlgorithm:a,mgf1HashAlgorithm:c,saltLength:n}=s,f=parseInt(e.slice(-3),10);if(a!==void 0&&(a!==`sha${f}`||c!==a))throw new TypeError(`Invalid key for this operation, its RSA-PSS parameters do not meet the requirements of "alg" ${e}`);if(n!==void 0&&n>f>>3)throw new TypeError(`Invalid key for this operation, its RSA-PSS parameter saltLength does not meet the requirements of "alg" ${e}`)}else if(r!=="rsa")throw new TypeError("Invalid key for this operation, its asymmetricKeyType must be rsa or rsa-pss");kt(t,e),i={padding:Mt.RSA_PKCS1_PSS_PADDING,saltLength:Mt.RSA_PSS_SALTLEN_DIGEST};break;case"ES256":case"ES256K":case"ES384":case"ES512":{if(r!=="ec")throw new TypeError("Invalid key for this operation, its asymmetricKeyType must be ec");let a=To(t),c=Uo.get(e);if(a!==c)throw new TypeError(`Invalid key curve for the algorithm, its curve must be ${c}, got ${a}`);i={dsaEncoding:"ieee-p1363"};break}default:throw new pe(`alg ${e} is not supported either by JOSE or your javascript runtime`)}return o?{format:"jwk",key:t,...i}:i?{...i,key:t}:t}function jo(e){switch(e){case"HS256":return"sha256";case"HS384":return"sha384";case"HS512":return"sha512";default:throw new pe(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}function Fo(e,t,r){if(t instanceof Uint8Array){if(!e.startsWith("HS"))throw new TypeError(st(t,...ce));return Ut(t)}if(t instanceof Dt)return t;if(wt(t))return wo(t,e,r),Dt.from(t);if($e(t))return e.startsWith("HS")?Ut(Buffer.from(t.k,"base64url")):t;throw new TypeError(st(t,...ce,"Uint8Array","JSON Web Key"))}var Wo=xo(Fe.sign),Ho=async(e,t,r)=>{let s=Fo(e,t,"sign");if(e.startsWith("HS")){let o=Fe.createHmac(jo(e),s);return o.update(r),o.digest()}return Wo(Mo(e),r,_o(e,s))},Bo=Ho,ee=e=>Math.floor(e.getTime()/1e3),Ko=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i,Ze=e=>{let t=Ko.exec(e);if(!t||t[4]&&t[1])throw new TypeError("Invalid time period format");let r=parseFloat(t[2]),s=t[3].toLowerCase(),o;switch(s){case"sec":case"secs":case"second":case"seconds":case"s":o=Math.round(r);break;case"minute":case"minutes":case"min":case"mins":case"m":o=Math.round(r*60);break;case"hour":case"hours":case"hr":case"hrs":case"h":o=Math.round(r*3600);break;case"day":case"days":case"d":o=Math.round(r*86400);break;case"week":case"weeks":case"w":o=Math.round(r*604800);break;default:o=Math.round(r*31557600);break}return t[1]==="-"||t[4]==="ago"?-o:o},Go=class{constructor(e){if(B(this,"_payload"),B(this,"_protectedHeader"),B(this,"_unprotectedHeader"),!(e instanceof Uint8Array))throw new TypeError("payload must be an instance of Uint8Array");this._payload=e}setProtectedHeader(e){if(this._protectedHeader)throw new TypeError("setProtectedHeader can only be called once");return this._protectedHeader=e,this}setUnprotectedHeader(e){if(this._unprotectedHeader)throw new TypeError("setUnprotectedHeader can only be called once");return this._unprotectedHeader=e,this}async sign(e,t){if(!this._protectedHeader&&!this._unprotectedHeader)throw new ae("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");if(!Eo(this._protectedHeader,this._unprotectedHeader))throw new ae("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let r={...this._protectedHeader,...this._unprotectedHeader},s=ko(ae,new Map([["b64",!0]]),t?.crit,this._protectedHeader,r),o=!0;if(s.has("b64")&&(o=this._protectedHeader.b64,typeof o!="boolean"))throw new ae('The "b64" (base64url-encode payload) Header Parameter must be a boolean');let{alg:i}=r;if(typeof i!="string"||!i)throw new ae('JWS "alg" (Algorithm) Header Parameter missing or invalid');Co(i,e,"sign");let a=this._payload;o&&(a=Ee.encode(Ye(a)));let c;this._protectedHeader?c=Ee.encode(Ye(JSON.stringify(this._protectedHeader))):c=Ee.encode("");let n=uo(c,Ee.encode("."),a),f=await Bo(i,e,n),l={signature:Ye(f),payload:""};return o&&(l.payload=Ot.decode(a)),this._unprotectedHeader&&(l.header=this._unprotectedHeader),this._protectedHeader&&(l.protected=Ot.decode(c)),l}},Jo=class{constructor(e){B(this,"_flattened"),this._flattened=new Go(e)}setProtectedHeader(e){return this._flattened.setProtectedHeader(e),this}async sign(e,t){let r=await this._flattened.sign(e,t);if(r.payload===void 0)throw new TypeError("use the flattened module for creating JWS with b64: false");return`${r.protected}.${r.payload}.${r.signature}`}};function te(e,t){if(!Number.isFinite(t))throw new TypeError(`Invalid ${e} input`);return t}var Vo=class{constructor(e={}){if(B(this,"_payload"),!pr(e))throw new TypeError("JWT Claims Set MUST be an object");this._payload=e}setIssuer(e){return this._payload={...this._payload,iss:e},this}setSubject(e){return this._payload={...this._payload,sub:e},this}setAudience(e){return this._payload={...this._payload,aud:e},this}setJti(e){return this._payload={...this._payload,jti:e},this}setNotBefore(e){return typeof e=="number"?this._payload={...this._payload,nbf:te("setNotBefore",e)}:e instanceof Date?this._payload={...this._payload,nbf:te("setNotBefore",ee(e))}:this._payload={...this._payload,nbf:ee(new Date)+Ze(e)},this}setExpirationTime(e){return typeof e=="number"?this._payload={...this._payload,exp:te("setExpirationTime",e)}:e instanceof Date?this._payload={...this._payload,exp:te("setExpirationTime",ee(e))}:this._payload={...this._payload,exp:ee(new Date)+Ze(e)},this}setIssuedAt(e){return typeof e>"u"?this._payload={...this._payload,iat:ee(new Date)}:e instanceof Date?this._payload={...this._payload,iat:te("setIssuedAt",ee(e))}:typeof e=="string"?this._payload={...this._payload,iat:te("setIssuedAt",ee(new Date)+Ze(e))}:this._payload={...this._payload,iat:te("setIssuedAt",e)},this}},Xo=class extends Vo{constructor(){super(...arguments),B(this,"_protectedHeader")}setProtectedHeader(e){return this._protectedHeader=e,this}async sign(e,t){let r=new Jo(Ee.encode(JSON.stringify(this._payload)));if(r.setProtectedHeader(this._protectedHeader),Array.isArray(this._protectedHeader?.crit)&&this._protectedHeader.crit.includes("b64")&&this._protectedHeader.b64===!1)throw new sr("JWTs MUST NOT use unencoded payload");return r.sign(e,t)}};function re(e){console.log(JSON.stringify(e,null,2))}async function gr(e,t,r){let s=t.source,o=We(s);if(!o)return;console.log("Saving source code...");let i=await e.createAttachment({data:o,filename:fr(s),contentType:ni(s)});console.log("Updating bot...");let a=await e.updateResource({...r,sourceCode:i});console.log("Success! New bot version: "+a.meta?.versionId)}async function wr(e,t,r){let s=t.dist??t.source,o=We(s);if(!o)return;console.log("Deploying bot...");let i=await e.post(e.fhirUrl("Bot",r.id,"$deploy"),{code:o,filename:fr(s)});console.log("Deploy result: "+i.issue?.[0]?.details?.text)}async function yr(e,t,r,s,o,i,a){let c={name:t,description:"",runtimeVersion:i},n=await e.post("admin/projects/"+r+"/bot",c),f=await e.readResource("Bot",n.id),l={name:t,id:n.id,source:s,dist:o};await gr(e,l,f),await wr(e,l,f),console.log(`Success! Bot created: ${f.id}`),a&&oi(l)}function ri(e){let t=new RegExp("^"+ii(e).replaceAll(String.raw`\*`,".*")+"$");return de()?.bots?.filter(s=>t.test(s.name))||[]}function se(e,t){if(t?.file)return t.file;let r=["medplum"];return e&&r.push(e),r.push("config"),t?.server&&r.push("server"),r.push("json"),r.join(".")}function K(e,t){mr(yt(e),JSON.stringify(t,void 0,2),"utf-8")}function de(e,t){let r=se(e,t),s=We(r);if(s)return JSON.parse(s)}function si(e){let t=We(se(e,{server:!0}));if(t)return JSON.parse(t)}function We(e){let t=yt(e);return Qo(t)?hr(t,"utf8"):""}function oi(e){let t=de()??{};t.bots||(t.bots=[]),t.bots.push(e),mr("medplum.config.json",JSON.stringify(t,null,2),"utf8"),console.log(`Bot added to config: ${e.id}`)}function ii(e){return e.replaceAll(/[/\-\\^$*+?.()|[\]{}]/g,"\\$&")}function ai(e){let t=0,r=0;return ti({cwd:e,filter:(s,o)=>{if(t++,t>100)throw new Error("Tar extractor reached max number of files");if(r+=o.size,r>10485760)throw new Error("Tar extractor reached max size");return!0}})}function _t(){return{url:"http://hl7.org/fhir/StructureDefinition/data-absent-reason",valueCode:"unsupported"}}function ni(e){let t=Zo(e).toLowerCase();return[".cjs",".mjs",".js"].includes(t)?qe.JAVASCRIPT:[".cts",".mts",".ts"].includes(t)?qe.TYPESCRIPT:qe.TEXT}function Er(e,t){let r=new be(e),s={name:e,...t};return r.setObject("options",s),s}function ci(e){return new be(e).getObject("options")}async function li(e,t){let r={typ:"JWT",alg:rr.HS256},s=Math.floor(Date.now()/1e3),o={aud:`${t.baseUrl}${t.audience}`,iss:t.issuer,sub:t.subject,nbf:s,iat:s,exp:s+604800},i=Nt(JSON.stringify(r)),a=Nt(JSON.stringify(o)),c=`${i}.${a}`,n=zo("sha256",t.clientSecret).update(c).digest("base64url"),f=`${c}.${n}`;await e.startJwtBearerLogin(t.clientId,f,t.scope??"")}async function ui(e,t){let r=qo(hr(yt(t.privateKeyPath))),s=await new Xo({}).setProtectedHeader({typ:"JWT",alg:rr.RS384}).setIssuer(t.clientId).setSubject(t.clientId).setAudience(`${t.baseUrl}${t.audience}`).setJti(Yo(16).toString("hex")).setIssuedAt().setExpirationTime("5m").sign(r);await e.startJwtAssertionLogin(s)}function P(e,t){t.configureHelp({showGlobalOptions:!0}),e.addCommand(t)}var R=class extends co{action(e){let t=pi(this,e);return super._actionHandler=t,this}resetOptionDefaults(){this._optionValues={};for(let e of this.options)e.defaultValue!==void 0&&(this._optionValues[e.attributeName()]=e.defaultValue)}};function pi(e,t){return async r=>{let s=e.registeredArguments.length,o=r.slice(0,s);o[s]=e.optsWithGlobals();try{let i=t(...o);ei(i)&&await i}finally{e.resetOptionDefaults()}}}var vr=new R("status").aliases(["info","list","ls"]),Sr=new R("ping"),Ir=new R("push"),br=new R("reload-config"),Ar=new R("upgrade"),he=new R("agent");P(he,vr);P(he,Sr);P(he,Ir);P(he,br);P(he,Ar);vr.description("Get the status of a specified agent").argument("[agentIds...]","The ID(s) of the agent(s) to get the status of").option("--criteria <criteria>","An optional FHIR search criteria to resolve the agent to get the status of. Mutually exclusive with [agentIds...] arg").addOption(new gt("--output <format>","An optional output format, defaults to table").choices(["table","json"]).default("table")).action(async(e,t)=>{await Et({operation:"$bulk-status",agentIds:e,options:t,parseSuccessfulResponse:r=>{let s=mi(r.result,{required:["status","version"],optional:["lastUpdated"]});return{id:r.agent.id,name:r.agent.name,enabledStatus:r.agent.status,version:s.version,connectionStatus:s.status,statusLastUpdated:s.lastUpdated??"N/A"}}})});Sr.description("Ping a host from a specified agent").argument("<ipOrDomain>","The IPv4 address or domain name to ping").argument("[agentId]","Conditionally optional ID of the agent to ping from. Mutually exclusive with --criteria <criteria> option").option("--count <count>","An optional amount of pings to issue before returning results","1").option("--criteria <criteria>","An optional FHIR search criteria to resolve the agent to ping from. Mutually exclusive with [agentId] arg").action(async(e,t,r)=>{let s=await x(r),o=await $r(s,t,r),i=Number.parseInt(r.count,10);if(Number.isNaN(i))throw new Error("--count <count> must be an integer if specified");try{let a=await s.pushToAgent(o,e,`PING ${i}`,tr.PING,!0,{maxRetries:0});console.info(a)}catch(a){throw new Error("Unexpected response from agent while pinging",{cause:a})}});Ir.description("Push a message to a target device via a specified agent").argument("<deviceId>","The ID of the device to push the message to").argument("<message>","The message to send to the destination device").argument("[agentId]","Conditionally optional ID of the agent to send the message from. Mutually exclusive with --criteria <criteria> option").option("--content-type <contentType>","The content type of the message",tr.HL7_V2).option("--no-wait","Tells the server not to wait for a response from the destination device").option("--criteria <criteria>","An optional FHIR search criteria to resolve the agent to ping from. Mutually exclusive with [agentId] arg").action(async(e,t,r,s)=>{let o=await x(s),i=await $r(o,r,s),a;try{a=await o.pushToAgent(i,{reference:`Device/${e}`},t,s.contentType,s.wait!==!1,{maxRetries:0})}catch(c){throw new Error("Unexpected response from agent while pushing message to agent",{cause:c})}console.info(a)});br.description("Reload the config for the specified agent(s)").argument("[agentIds...]","The ID(s) of the agent(s) for which the config should be reloaded. Mutually exclusive with --criteria <criteria> flag").option("--criteria <criteria>","An optional FHIR search criteria to resolve the agent(s) for which to notify to reload their config. Mutually exclusive with [agentIds...] arg").addOption(new gt("--output <format>","An optional output format, defaults to table").choices(["table","json"]).default("table")).action(async(e,t)=>{await Et({operation:"$reload-config",agentIds:e,options:t,parseSuccessfulResponse:r=>({id:r.agent.id,name:r.agent.name})})});Ar.description("Upgrade the version for the specified agent(s)").argument("[agentIds...]","The ID(s) of the agent(s) that should be upgraded. Mutually exclusive with --criteria <criteria> flag").option("--criteria <criteria>","An optional FHIR search criteria to resolve the agent(s) to upgrade. Mutually exclusive with [agentIds...] arg").option("--agentVersion <version>","An optional agent version to upgrade to. Defaults to the latest version if flag not included").option("--force","Forces an upgrade when a pending upgrade is in an inconsistent state. Use with caution.").addOption(new gt("--output <format>","An optional output format, defaults to table").choices(["table","json"]).default("table")).action(async(e,t)=>{let r={};t.agentVersion&&(r.version=t.agentVersion),t.force&&(r.force=!0),await Et({operation:"$upgrade",agentIds:e,options:t,params:r,parseSuccessfulResponse:s=>({id:s.agent.id,name:s.agent.name,version:t.agentVersion??"latest"})})});async function Et({operation:e,agentIds:t,options:r,params:s={},parseSuccessfulResponse:o}){let i=gi(t,r),a=await x(r),c=i.type==="criteria"?i.criteria:`Agent?_id=${i.ids.join(",")}`,n=new URLSearchParams(c.split("?")[1]);for(let[g,h]of Object.entries(s))n.append(g,h.toString());let f;try{let g=a.fhirUrl("Agent",e);g.search=n.toString(),f=await a.get(g,{cache:"reload"})}catch(g){throw new Error(`Operation '${e}' failed`,{cause:g})}if(r.output==="json"){console.info(JSON.stringify(f,null,2));return}let l=[],u=[];switch(f.resourceType){case"Bundle":{let g=di(f);for(let h of g)h.result.resourceType==="Parameters"||Ys(h.result)?l.push(h):u.push(h);break}case"Parameters":case"OperationOutcome":{let g=await a.searchOne("Agent",n,{cache:"reload"});if(!g)throw new Error("Agent not found");f.resourceType==="Parameters"?l.push({agent:g,result:f}):u.push({agent:g,result:f});break}default:throw new Error(`Invalid result received for '${e}' operation: ${JSON.stringify(f)}`)}let d=[];for(let g of l){let h=o(g);d.push(h)}let m=[];for(let g of u){let h=g.result.issue?.[0],N={id:g.agent.id,name:g.agent.name,severity:h.severity,code:h.code,details:h.details?.text??"No details to show"};m.push(N)}console.info(`
3
- ${d.length} successful response(s):
4
- `),console.table(d.length?d:"No successful responses received"),console.info(),m.length&&(console.info(`${m.length} failed response(s):`),console.info(),console.table(m))}async function $r(e,t,r){if(!(t||r.criteria))throw new Error("This command requires either an [agentId] or a --criteria <criteria> flag");if(t&&r.criteria)throw new Error("Ambiguous arguments and options combination; [agentId] arg and --criteria <criteria> flag are mutually exclusive");let s;if(t)s=t;else{Rr(r.criteria);let o=await e.search("Agent",`${r.criteria.split("?")[1]}&_count=2`);if(!o?.entry?.length)throw new Error("Could not find an agent matching the provided criteria");if(o.entry.length!==1)throw new Error("Found more than one agent matching this criteria. This operation requires the criteria to resolve to exactly one agent");s=o.entry[0].resource?.id}return{reference:`Agent/${s}`}}function di(e){let t=[];for(let r of e.entry??qs){if(!r.resource)throw new Error("No Parameter resource found in entry");t.push(hi(r.resource))}return t}function hi(e){let t=e.parameter?.find(s=>s.name==="agent")?.resource;if(!t)throw new Error("Agent bulk operation response missing 'agent'");if(t.resourceType!=="Agent")throw new Error(`Agent bulk operation returned 'agent' with type '${t.resourceType}'`);let r=e.parameter?.find(s=>s.name==="result")?.resource;if(!r)throw new Error("Agent bulk operation response missing result'");if(!(r.resourceType==="Parameters"||r.resourceType==="OperationOutcome"))throw new Error(`Agent bulk operation returned 'result' with type '${r.resourceType}'`);return{agent:t,result:r}}function mi(e,t){let r={},s=t.required,o=t.optional;for(let i of s){let a=e.parameter?.find(n=>n.name===i);if(!a)throw new Error(`Failed to find parameter '${i}'`);let c;for(let n in a)if(n.startsWith("value")){if(c)throw new Error(`Found multiple values for parameter '${i}'`);c=n}if(!c)throw new Error(`Failed to find a value for parameter '${i}'`);r[i]=a[c]}if(o?.length)for(let i of o){let a=e.parameter?.find(n=>n.name===i);if(!a)continue;let c=fi(i,a);r[i]=c}return r}function fi(e,t){let r;for(let s in t)if(s.startsWith("value")){if(r)throw new Error(`Found multiple values for parameter '${e}'`);r=s}if(!r)throw new Error(`Failed to find a value for parameter '${e}'`);return t[r]}function gi(e,t){if(!Array.isArray(e))throw new Error("Invalid agent IDs array");if(e.length){if(t.criteria)throw new Error("Ambiguous arguments and options combination; [agentIds...] arg and --criteria <criteria> flag are mutually exclusive");for(let r of e)if(!Qs(r))throw new Error(`Input '${r}' is not a valid agentId`);return{type:"ids",ids:e}}if(t.criteria)return Rr(t.criteria),{type:"criteria",criteria:t.criteria};throw new Error("Either an [agentId...] arg or a --criteria <criteria> flag is required")}function Rr(e){let t="Criteria must be formatted as a string containing the resource type (Agent) followed by a '?' and valid URL search query params, eg. `Agent?name=Test Agent`";if(typeof e!="string")throw new Error(t);let[r,s]=e.split("?");if(r!=="Agent"||!s)throw new Error(t);try{new URLSearchParams(s)}catch(o){throw new Error(t,{cause:o})}if(!s.includes("="))throw new Error(t,{cause:new Error("Query string lacks at least one `=`")})}var Tr=yi,Pr="http://localhost:9615",Nr=new R("login"),Or=new R("whoami"),Cr=new R("token");Nr.action(async e=>{let t=e.profile??"default",r=Er(t,e),s=await x(e,!1);await bi(s,r)});Or.action(async e=>{let t=await x(e);Ri(t)});Cr.action(async e=>{let t=await x(e);await t.getProfileAsync();let r=t.getAccessToken();if(!r)throw new Error("Not logged in");console.log(r)});async function bi(e,t){switch(t?.authType??"authorization-code"){case"authorization-code":await Ti(e);break;case"basic":e.setBasicAuth(t.clientId,t.clientSecret);break;case"client-credentials":e.setBasicAuth(t.clientId,t.clientSecret),await e.startClientLogin(t.clientId,t.clientSecret);break;case"jwt-bearer":await li(e,t);break;case"jwt-assertion":await ui(e,t);break}}async function Ai(e){let t=Si(async(r,s)=>{let o=new URL(r.url,"http://localhost:9615"),i=o.searchParams.get("code");if(r.method==="OPTIONS"){s.writeHead(200,{Allow:"GET, POST","Content-Type":Ne.TEXT}),s.end("OK");return}if(o.pathname==="/"&&i)try{let a=await e.processCode(i,{clientId:Tr,redirectUri:Pr});s.writeHead(200,{"Content-Type":Ne.TEXT}),s.end(`Signed in as ${wi(a)}. You may close this window.`)}catch(a){s.writeHead(400,{"Content-Type":Ne.TEXT}),s.end(`Error: ${Ei(a)}`)}finally{t.close(),process.exit(0)}else s.writeHead(404,{"Content-Type":Ne.TEXT}),s.end("Not found")}).listen(9615)}async function $i(e){let t=Ii(),r;switch(t){case"openbsd":case"linux":r=`xdg-open '${e}'`;break;case"darwin":r=`open '${e}'`;break;case"win32":r=`cmd /c start "" "${e}"`;break;default:throw new Error("Unsupported platform: "+t)}return new Promise((s,o)=>{vi(r,(i,a,c)=>{if(i){o(i);return}if(c){o(new Error("Could not open browser: "+c));return}s()})})}function Ri(e){let t=e.getActiveLogin();t?(console.log(`Server: ${e.getBaseUrl()}`),console.log(`Profile: ${t.profile.display} (${t.profile.reference})`),console.log(`Project: ${t.project.display} (${t.project.reference})`)):console.log("Not logged in")}async function Ti(e){await Ai(e);let t=new URL(e.getAuthorizeUrl());t.searchParams.set("client_id",Tr),t.searchParams.set("redirect_uri",Pr),t.searchParams.set("scope","openid"),t.searchParams.set("response_type","code"),t.searchParams.set("prompt","login"),await $i(t.toString())}var we="\x1B[0m",Pi="\x1B[1m",Ni="\x1B[31m",Oi="\x1B[32m",Ci="\x1B[33m",Li="\x1B[34m",Se={red:e=>`${Ni}${e}${we}`,green:e=>`${Oi}${e}${we}`,yellow:e=>`${Ci}${e}${we}`,blue:e=>`${Li}${e}${we}`,bold:e=>`${Pi}${e}${we}`},xt=e=>e.replaceAll(/\*\*(.*?)\*\*/g,(t,r)=>Se.bold(r)),ki=Xt(Zt(),1),He;function kr(){He=qi.createInterface({input:process.stdin,output:process.stdout})}function Mr(){He.close()}function p(e){He.write(e+`
2
+ import{MEDPLUM_VERSION as eo,normalizeErrorString as ot}from"@medplum/core";import{CommanderError as or,Option as to}from"commander";import ro from"dotenv";import{ContentType as ir,EMPTY as so,isOk as oo,isUUID as io,normalizeErrorString as ao}from"@medplum/core";import{Option as Fe}from"commander";import{MedplumClient as no}from"@medplum/core";import{ClientStorage as co}from"@medplum/core";import{existsSync as Tt,mkdirSync as lo,readFileSync as uo,writeFileSync as po}from"node:fs";import{homedir as ho}from"node:os";import{resolve as Pt}from"node:path";import{ContentType as Qe,encodeBase64 as Ot,OAuthSigningAlgorithm as ar}from"@medplum/core";import{Command as wo}from"commander";import{Buffer as yo}from"node:buffer";import*as cr from"node:util";import*as ur from"node:crypto";import*as pr from"node:util";import{KeyObject as Oo}from"node:crypto";import{KeyObject as Uo}from"node:crypto";import{constants as Mt,KeyObject as Bo}from"node:crypto";import*as We from"node:crypto";import{promisify as Jo}from"node:util";import{KeyObject as Dt,createSecretKey as Ut}from"node:crypto";import{createHmac as si,createPrivateKey as oi,randomBytes as ii}from"node:crypto";import{existsSync as ai,readFileSync as wr,writeFileSync as yr}from"node:fs";import{basename as Er,extname as ni,resolve as Et}from"node:path";import{isPromise as ci}from"node:util/types";import{extract as li}from"tar";import{ContentType as Ne,getDisplayString as $i,MEDPLUM_CLI_CLIENT_ID as Ri,normalizeErrorString as Ti}from"@medplum/core";import{exec as Pi}from"node:child_process";import{createServer as Oi}from"node:http";import{platform as Ni}from"node:os";import{CloudFormationClient as xr,DescribeStackResourcesCommand as Hi,DescribeStacksCommand as Bi,paginateListStacks as Gi}from"@aws-sdk/client-cloudformation";import{CloudFrontClient as Ki,CreateInvalidationCommand as Ji}from"@aws-sdk/client-cloudfront";import{ECSClient as Vi}from"@aws-sdk/client-ecs";import{S3Client as Xi}from"@aws-sdk/client-s3";import{GetParameterCommand as zi,PutParameterCommand as qi,SSMClient as Yi}from"@aws-sdk/client-ssm";import{GetCallerIdentityCommand as Qi,STSClient as Zi}from"@aws-sdk/client-sts";import{EMPTY as ea,normalizeErrorString as ta}from"@medplum/core";import ra from"node-fetch";import{readdirSync as sa}from"node:fs";import oa from"node:readline";import{ACMClient as Vr,ListCertificatesCommand as da,RequestCertificateCommand as ha}from"@aws-sdk/client-acm";import{CloudFrontClient as ma,CreatePublicKeyCommand as fa}from"@aws-sdk/client-cloudfront";import{GetCallerIdentityCommand as ga,STSClient as wa}from"@aws-sdk/client-sts";import{normalizeErrorString as ya}from"@medplum/core";import{generateKeyPairSync as Ea,randomUUID as Bt}from"node:crypto";import{existsSync as va}from"node:fs";import{PutObjectCommand as Oa}from"@aws-sdk/client-s3";import{ContentType as Y}from"@medplum/core";import Na from"fast-glob";import zr from"node-fetch";import{createReadStream as Ca,mkdtempSync as La,readdirSync as ka,readFileSync as Ma,rmSync as Da,writeFileSync as Ua}from"node:fs";import{tmpdir as _a}from"node:os";import{join as De,sep as xa}from"node:path";import{pipeline as ja}from"node:stream/promises";import{GetBucketPolicyCommand as Va,PutBucketPolicyCommand as Xa}from"@aws-sdk/client-s3";import{spawnSync as an}from"node:child_process";import{EMPTY as ss}from"@medplum/core";import{createReadStream as pn,createWriteStream as dn}from"node:fs";import{resolve as os}from"node:path";import{createInterface as hn}from"node:readline";import{Readable as mn}from"node:stream";import{pipeline as fn}from"node:stream/promises";import{formatHl7DateTime as vn,Hl7Message as Sn}from"@medplum/core";import Le from"node:assert";import{connect as bn}from"node:net";import{Hl7Message as An,OperationOutcomeError as ne,ReturnAckCategory as zt,sleep as In,validationError as $n}from"@medplum/core";import qt from"iconv-lite";import"@medplum/core";import{sleep as Rn}from"@medplum/core";import Tn from"node:net";import{readFileSync as _n}from"node:fs";import{readdirSync as Wn}from"node:fs";import{homedir as Hn}from"node:os";import{resolve as Bn}from"node:path";import{Option as Gn}from"commander";import{convertToTransactionBundle as Xn}from"@medplum/core";var bs=Object.create,pt=Object.defineProperty,As=Object.getOwnPropertyDescriptor,Is=Object.getOwnPropertyNames,$s=Object.getPrototypeOf,Rs=Object.prototype.hasOwnProperty,Ts=(e,t,r)=>t in e?pt(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,I=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),Ps=(e,t,r,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Is(t))!Rs.call(e,o)&&o!==r&&pt(e,o,{get:()=>t[o],enumerable:!(s=As(t,o))||s.enumerable});return e},Qt=(e,t,r)=>(r=e!=null?bs($s(e)):{},Ps(t||!e||!e.__esModule?pt(r,"default",{value:e,enumerable:!0}):r,e)),B=(e,t,r)=>Ts(e,typeof t!="symbol"?t+"":t,r),be=I((e,t)=>{"use strict";var r="2.0.0",s=Number.MAX_SAFE_INTEGER||9007199254740991,o=16,i=250,a=["major","premajor","minor","preminor","patch","prepatch","prerelease"];t.exports={MAX_LENGTH:256,MAX_SAFE_COMPONENT_LENGTH:o,MAX_SAFE_BUILD_LENGTH:i,MAX_SAFE_INTEGER:s,RELEASE_TYPES:a,SEMVER_SPEC_VERSION:r,FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2}}),Ue=I((e,t)=>{"use strict";var r=typeof process=="object"&&process.env&&process.env.NODE_DEBUG&&/\bsemver\b/i.test(process.env.NODE_DEBUG)?(...s)=>console.error("SEMVER",...s):()=>{};t.exports=r}),Ae=I((e,t)=>{"use strict";var{MAX_SAFE_COMPONENT_LENGTH:r,MAX_SAFE_BUILD_LENGTH:s,MAX_LENGTH:o}=be(),i=Ue();e=t.exports={};var a=e.re=[],c=e.safeRe=[],n=e.src=[],m=e.safeSrc=[],l=e.t={},u=0,d="[a-zA-Z0-9-]",f=[["\\s",1],["\\d",o],[d,s]],g=b=>{for(let[R,N]of f)b=b.split(`${R}*`).join(`${R}{0,${N}}`).split(`${R}+`).join(`${R}{1,${N}}`);return b},h=(b,R,N)=>{let j=g(R),W=u++;i(b,W,R),l[b]=W,n[W]=R,m[W]=j,a[W]=new RegExp(R,N?"g":void 0),c[W]=new RegExp(j,N?"g":void 0)};h("NUMERICIDENTIFIER","0|[1-9]\\d*"),h("NUMERICIDENTIFIERLOOSE","\\d+"),h("NONNUMERICIDENTIFIER",`\\d*[a-zA-Z-]${d}*`),h("MAINVERSION",`(${n[l.NUMERICIDENTIFIER]})\\.(${n[l.NUMERICIDENTIFIER]})\\.(${n[l.NUMERICIDENTIFIER]})`),h("MAINVERSIONLOOSE",`(${n[l.NUMERICIDENTIFIERLOOSE]})\\.(${n[l.NUMERICIDENTIFIERLOOSE]})\\.(${n[l.NUMERICIDENTIFIERLOOSE]})`),h("PRERELEASEIDENTIFIER",`(?:${n[l.NONNUMERICIDENTIFIER]}|${n[l.NUMERICIDENTIFIER]})`),h("PRERELEASEIDENTIFIERLOOSE",`(?:${n[l.NONNUMERICIDENTIFIER]}|${n[l.NUMERICIDENTIFIERLOOSE]})`),h("PRERELEASE",`(?:-(${n[l.PRERELEASEIDENTIFIER]}(?:\\.${n[l.PRERELEASEIDENTIFIER]})*))`),h("PRERELEASELOOSE",`(?:-?(${n[l.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${n[l.PRERELEASEIDENTIFIERLOOSE]})*))`),h("BUILDIDENTIFIER",`${d}+`),h("BUILD",`(?:\\+(${n[l.BUILDIDENTIFIER]}(?:\\.${n[l.BUILDIDENTIFIER]})*))`),h("FULLPLAIN",`v?${n[l.MAINVERSION]}${n[l.PRERELEASE]}?${n[l.BUILD]}?`),h("FULL",`^${n[l.FULLPLAIN]}$`),h("LOOSEPLAIN",`[v=\\s]*${n[l.MAINVERSIONLOOSE]}${n[l.PRERELEASELOOSE]}?${n[l.BUILD]}?`),h("LOOSE",`^${n[l.LOOSEPLAIN]}$`),h("GTLT","((?:<|>)?=?)"),h("XRANGEIDENTIFIERLOOSE",`${n[l.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`),h("XRANGEIDENTIFIER",`${n[l.NUMERICIDENTIFIER]}|x|X|\\*`),h("XRANGEPLAIN",`[v=\\s]*(${n[l.XRANGEIDENTIFIER]})(?:\\.(${n[l.XRANGEIDENTIFIER]})(?:\\.(${n[l.XRANGEIDENTIFIER]})(?:${n[l.PRERELEASE]})?${n[l.BUILD]}?)?)?`),h("XRANGEPLAINLOOSE",`[v=\\s]*(${n[l.XRANGEIDENTIFIERLOOSE]})(?:\\.(${n[l.XRANGEIDENTIFIERLOOSE]})(?:\\.(${n[l.XRANGEIDENTIFIERLOOSE]})(?:${n[l.PRERELEASELOOSE]})?${n[l.BUILD]}?)?)?`),h("XRANGE",`^${n[l.GTLT]}\\s*${n[l.XRANGEPLAIN]}$`),h("XRANGELOOSE",`^${n[l.GTLT]}\\s*${n[l.XRANGEPLAINLOOSE]}$`),h("COERCEPLAIN",`(^|[^\\d])(\\d{1,${r}})(?:\\.(\\d{1,${r}}))?(?:\\.(\\d{1,${r}}))?`),h("COERCE",`${n[l.COERCEPLAIN]}(?:$|[^\\d])`),h("COERCEFULL",n[l.COERCEPLAIN]+`(?:${n[l.PRERELEASE]})?(?:${n[l.BUILD]})?(?:$|[^\\d])`),h("COERCERTL",n[l.COERCE],!0),h("COERCERTLFULL",n[l.COERCEFULL],!0),h("LONETILDE","(?:~>?)"),h("TILDETRIM",`(\\s*)${n[l.LONETILDE]}\\s+`,!0),e.tildeTrimReplace="$1~",h("TILDE",`^${n[l.LONETILDE]}${n[l.XRANGEPLAIN]}$`),h("TILDELOOSE",`^${n[l.LONETILDE]}${n[l.XRANGEPLAINLOOSE]}$`),h("LONECARET","(?:\\^)"),h("CARETTRIM",`(\\s*)${n[l.LONECARET]}\\s+`,!0),e.caretTrimReplace="$1^",h("CARET",`^${n[l.LONECARET]}${n[l.XRANGEPLAIN]}$`),h("CARETLOOSE",`^${n[l.LONECARET]}${n[l.XRANGEPLAINLOOSE]}$`),h("COMPARATORLOOSE",`^${n[l.GTLT]}\\s*(${n[l.LOOSEPLAIN]})$|^$`),h("COMPARATOR",`^${n[l.GTLT]}\\s*(${n[l.FULLPLAIN]})$|^$`),h("COMPARATORTRIM",`(\\s*)${n[l.GTLT]}\\s*(${n[l.LOOSEPLAIN]}|${n[l.XRANGEPLAIN]})`,!0),e.comparatorTrimReplace="$1$2$3",h("HYPHENRANGE",`^\\s*(${n[l.XRANGEPLAIN]})\\s+-\\s+(${n[l.XRANGEPLAIN]})\\s*$`),h("HYPHENRANGELOOSE",`^\\s*(${n[l.XRANGEPLAINLOOSE]})\\s+-\\s+(${n[l.XRANGEPLAINLOOSE]})\\s*$`),h("STAR","(<|>)?=?\\s*\\*"),h("GTE0","^\\s*>=\\s*0\\.0\\.0\\s*$"),h("GTE0PRE","^\\s*>=\\s*0\\.0\\.0-0\\s*$")}),dt=I((e,t)=>{"use strict";var r=Object.freeze({loose:!0}),s=Object.freeze({}),o=i=>i?typeof i!="object"?r:i:s;t.exports=o}),Zt=I((e,t)=>{"use strict";var r=/^[0-9]+$/,s=(i,a)=>{if(typeof i=="number"&&typeof a=="number")return i===a?0:i<a?-1:1;let c=r.test(i),n=r.test(a);return c&&n&&(i=+i,a=+a),i===a?0:c&&!n?-1:n&&!c?1:i<a?-1:1},o=(i,a)=>s(a,i);t.exports={compareIdentifiers:s,rcompareIdentifiers:o}}),K=I((e,t)=>{"use strict";var r=Ue(),{MAX_LENGTH:s,MAX_SAFE_INTEGER:o}=be(),{safeRe:i,t:a}=Ae(),c=dt(),{compareIdentifiers:n}=Zt(),m=class Q{constructor(u,d){if(d=c(d),u instanceof Q){if(u.loose===!!d.loose&&u.includePrerelease===!!d.includePrerelease)return u;u=u.version}else if(typeof u!="string")throw new TypeError(`Invalid version. Must be a string. Got type "${typeof u}".`);if(u.length>s)throw new TypeError(`version is longer than ${s} characters`);r("SemVer",u,d),this.options=d,this.loose=!!d.loose,this.includePrerelease=!!d.includePrerelease;let f=u.trim().match(d.loose?i[a.LOOSE]:i[a.FULL]);if(!f)throw new TypeError(`Invalid Version: ${u}`);if(this.raw=u,this.major=+f[1],this.minor=+f[2],this.patch=+f[3],this.major>o||this.major<0)throw new TypeError("Invalid major version");if(this.minor>o||this.minor<0)throw new TypeError("Invalid minor version");if(this.patch>o||this.patch<0)throw new TypeError("Invalid patch version");f[4]?this.prerelease=f[4].split(".").map(g=>{if(/^[0-9]+$/.test(g)){let h=+g;if(h>=0&&h<o)return h}return g}):this.prerelease=[],this.build=f[5]?f[5].split("."):[],this.format()}format(){return this.version=`${this.major}.${this.minor}.${this.patch}`,this.prerelease.length&&(this.version+=`-${this.prerelease.join(".")}`),this.version}toString(){return this.version}compare(u){if(r("SemVer.compare",this.version,this.options,u),!(u instanceof Q)){if(typeof u=="string"&&u===this.version)return 0;u=new Q(u,this.options)}return u.version===this.version?0:this.compareMain(u)||this.comparePre(u)}compareMain(u){return u instanceof Q||(u=new Q(u,this.options)),this.major<u.major?-1:this.major>u.major?1:this.minor<u.minor?-1:this.minor>u.minor?1:this.patch<u.patch?-1:this.patch>u.patch?1:0}comparePre(u){if(u instanceof Q||(u=new Q(u,this.options)),this.prerelease.length&&!u.prerelease.length)return-1;if(!this.prerelease.length&&u.prerelease.length)return 1;if(!this.prerelease.length&&!u.prerelease.length)return 0;let d=0;do{let f=this.prerelease[d],g=u.prerelease[d];if(r("prerelease compare",d,f,g),f===void 0&&g===void 0)return 0;if(g===void 0)return 1;if(f===void 0)return-1;if(f!==g)return n(f,g)}while(++d)}compareBuild(u){u instanceof Q||(u=new Q(u,this.options));let d=0;do{let f=this.build[d],g=u.build[d];if(r("build compare",d,f,g),f===void 0&&g===void 0)return 0;if(g===void 0)return 1;if(f===void 0)return-1;if(f!==g)return n(f,g)}while(++d)}inc(u,d,f){if(u.startsWith("pre")){if(!d&&f===!1)throw new Error("invalid increment argument: identifier is empty");if(d){let g=`-${d}`.match(this.options.loose?i[a.PRERELEASELOOSE]:i[a.PRERELEASE]);if(!g||g[1]!==d)throw new Error(`invalid identifier: ${d}`)}}switch(u){case"premajor":this.prerelease.length=0,this.patch=0,this.minor=0,this.major++,this.inc("pre",d,f);break;case"preminor":this.prerelease.length=0,this.patch=0,this.minor++,this.inc("pre",d,f);break;case"prepatch":this.prerelease.length=0,this.inc("patch",d,f),this.inc("pre",d,f);break;case"prerelease":this.prerelease.length===0&&this.inc("patch",d,f),this.inc("pre",d,f);break;case"release":if(this.prerelease.length===0)throw new Error(`version ${this.raw} is not a prerelease`);this.prerelease.length=0;break;case"major":(this.minor!==0||this.patch!==0||this.prerelease.length===0)&&this.major++,this.minor=0,this.patch=0,this.prerelease=[];break;case"minor":(this.patch!==0||this.prerelease.length===0)&&this.minor++,this.patch=0,this.prerelease=[];break;case"patch":this.prerelease.length===0&&this.patch++,this.prerelease=[];break;case"pre":{let g=Number(f)?1:0;if(this.prerelease.length===0)this.prerelease=[g];else{let h=this.prerelease.length;for(;--h>=0;)typeof this.prerelease[h]=="number"&&(this.prerelease[h]++,h=-2);if(h===-1){if(d===this.prerelease.join(".")&&f===!1)throw new Error("invalid increment argument: identifier already exists");this.prerelease.push(g)}}if(d){let h=[d,g];f===!1&&(h=[d]),n(this.prerelease[0],d)===0?isNaN(this.prerelease[1])&&(this.prerelease=h):this.prerelease=h}break}default:throw new Error(`invalid increment argument: ${u}`)}return this.raw=this.format(),this.build.length&&(this.raw+=`+${this.build.join(".")}`),this}};t.exports=m}),oe=I((e,t)=>{"use strict";var r=K(),s=(o,i,a=!1)=>{if(o instanceof r)return o;try{return new r(o,i)}catch(c){if(!a)return null;throw c}};t.exports=s}),Os=I((e,t)=>{"use strict";var r=oe(),s=(o,i)=>{let a=r(o,i);return a?a.version:null};t.exports=s}),Ns=I((e,t)=>{"use strict";var r=oe(),s=(o,i)=>{let a=r(o.trim().replace(/^[=v]+/,""),i);return a?a.version:null};t.exports=s}),Cs=I((e,t)=>{"use strict";var r=K(),s=(o,i,a,c,n)=>{typeof a=="string"&&(n=c,c=a,a=void 0);try{return new r(o instanceof r?o.version:o,a).inc(i,c,n).version}catch{return null}};t.exports=s}),Ls=I((e,t)=>{"use strict";var r=oe(),s=(o,i)=>{let a=r(o,null,!0),c=r(i,null,!0),n=a.compare(c);if(n===0)return null;let m=n>0,l=m?a:c,u=m?c:a,d=!!l.prerelease.length;if(u.prerelease.length&&!d){if(!u.patch&&!u.minor)return"major";if(u.compareMain(l)===0)return u.minor&&!u.patch?"minor":"patch"}let f=d?"pre":"";return a.major!==c.major?f+"major":a.minor!==c.minor?f+"minor":a.patch!==c.patch?f+"patch":"prerelease"};t.exports=s}),ks=I((e,t)=>{"use strict";var r=K(),s=(o,i)=>new r(o,i).major;t.exports=s}),Ms=I((e,t)=>{"use strict";var r=K(),s=(o,i)=>new r(o,i).minor;t.exports=s}),Ds=I((e,t)=>{"use strict";var r=K(),s=(o,i)=>new r(o,i).patch;t.exports=s}),Us=I((e,t)=>{"use strict";var r=oe(),s=(o,i)=>{let a=r(o,i);return a&&a.prerelease.length?a.prerelease:null};t.exports=s}),X=I((e,t)=>{"use strict";var r=K(),s=(o,i,a)=>new r(o,a).compare(new r(i,a));t.exports=s}),_s=I((e,t)=>{"use strict";var r=X(),s=(o,i,a)=>r(i,o,a);t.exports=s}),xs=I((e,t)=>{"use strict";var r=X(),s=(o,i)=>r(o,i,!0);t.exports=s}),ht=I((e,t)=>{"use strict";var r=K(),s=(o,i,a)=>{let c=new r(o,a),n=new r(i,a);return c.compare(n)||c.compareBuild(n)};t.exports=s}),js=I((e,t)=>{"use strict";var r=ht(),s=(o,i)=>o.sort((a,c)=>r(a,c,i));t.exports=s}),Fs=I((e,t)=>{"use strict";var r=ht(),s=(o,i)=>o.sort((a,c)=>r(c,a,i));t.exports=s}),_e=I((e,t)=>{"use strict";var r=X(),s=(o,i,a)=>r(o,i,a)>0;t.exports=s}),mt=I((e,t)=>{"use strict";var r=X(),s=(o,i,a)=>r(o,i,a)<0;t.exports=s}),er=I((e,t)=>{"use strict";var r=X(),s=(o,i,a)=>r(o,i,a)===0;t.exports=s}),tr=I((e,t)=>{"use strict";var r=X(),s=(o,i,a)=>r(o,i,a)!==0;t.exports=s}),ft=I((e,t)=>{"use strict";var r=X(),s=(o,i,a)=>r(o,i,a)>=0;t.exports=s}),gt=I((e,t)=>{"use strict";var r=X(),s=(o,i,a)=>r(o,i,a)<=0;t.exports=s}),rr=I((e,t)=>{"use strict";var r=er(),s=tr(),o=_e(),i=ft(),a=mt(),c=gt(),n=(m,l,u,d)=>{switch(l){case"===":return typeof m=="object"&&(m=m.version),typeof u=="object"&&(u=u.version),m===u;case"!==":return typeof m=="object"&&(m=m.version),typeof u=="object"&&(u=u.version),m!==u;case"":case"=":case"==":return r(m,u,d);case"!=":return s(m,u,d);case">":return o(m,u,d);case">=":return i(m,u,d);case"<":return a(m,u,d);case"<=":return c(m,u,d);default:throw new TypeError(`Invalid operator: ${l}`)}};t.exports=n}),Ws=I((e,t)=>{"use strict";var r=K(),s=oe(),{safeRe:o,t:i}=Ae(),a=(c,n)=>{if(c instanceof r)return c;if(typeof c=="number"&&(c=String(c)),typeof c!="string")return null;n=n||{};let m=null;if(!n.rtl)m=c.match(n.includePrerelease?o[i.COERCEFULL]:o[i.COERCE]);else{let h=n.includePrerelease?o[i.COERCERTLFULL]:o[i.COERCERTL],b;for(;(b=h.exec(c))&&(!m||m.index+m[0].length!==c.length);)(!m||b.index+b[0].length!==m.index+m[0].length)&&(m=b),h.lastIndex=b.index+b[1].length+b[2].length;h.lastIndex=-1}if(m===null)return null;let l=m[2],u=m[3]||"0",d=m[4]||"0",f=n.includePrerelease&&m[5]?`-${m[5]}`:"",g=n.includePrerelease&&m[6]?`+${m[6]}`:"";return s(`${l}.${u}.${d}${f}${g}`,n)};t.exports=a}),Hs=I((e,t)=>{"use strict";var r=oe(),s=be(),o=K(),i=(m,l,u)=>{if(!s.RELEASE_TYPES.includes(l))return null;let d=a(m,u);return d&&c(d,l)},a=(m,l)=>{let u=m instanceof o?m.version:m;return r(u,l)},c=(m,l)=>{if(n(l))return m.version;switch(m.prerelease=[],l){case"major":m.minor=0,m.patch=0;break;case"minor":m.patch=0;break}return m.format()},n=m=>m.startsWith("pre");t.exports=i}),Bs=I((e,t)=>{"use strict";var r=class{constructor(){this.max=1e3,this.map=new Map}get(s){let o=this.map.get(s);if(o!==void 0)return this.map.delete(s),this.map.set(s,o),o}delete(s){return this.map.delete(s)}set(s,o){if(!this.delete(s)&&o!==void 0){if(this.map.size>=this.max){let i=this.map.keys().next().value;this.delete(i)}this.map.set(s,o)}return this}};t.exports=r}),z=I((e,t)=>{"use strict";var r=/\s+/g,s=class ke{constructor(w,S){if(S=a(S),w instanceof ke)return w.loose===!!S.loose&&w.includePrerelease===!!S.includePrerelease?w:new ke(w.raw,S);if(w instanceof c)return this.raw=w.value,this.set=[[w]],this.formatted=void 0,this;if(this.options=S,this.loose=!!S.loose,this.includePrerelease=!!S.includePrerelease,this.raw=w.trim().replace(r," "),this.set=this.raw.split("||").map(E=>this.parseRange(E.trim())).filter(E=>E.length),!this.set.length)throw new TypeError(`Invalid SemVer Range: ${this.raw}`);if(this.set.length>1){let E=this.set[0];if(this.set=this.set.filter(A=>!R(A[0])),this.set.length===0)this.set=[E];else if(this.set.length>1){for(let A of this.set)if(A.length===1&&N(A[0])){this.set=[A];break}}}this.formatted=void 0}get range(){if(this.formatted===void 0){this.formatted="";for(let w=0;w<this.set.length;w++){w>0&&(this.formatted+="||");let S=this.set[w];for(let E=0;E<S.length;E++)E>0&&(this.formatted+=" "),this.formatted+=S[E].toString().trim()}}return this.formatted}format(){return this.range}toString(){return this.range}parseRange(w){let S=((this.options.includePrerelease&&h)|(this.options.loose&&b))+":"+w,E=i.get(S);if(E)return E;let A=this.options.loose,v=A?l[u.HYPHENRANGELOOSE]:l[u.HYPHENRANGE];w=w.replace(v,qe(this.options.includePrerelease)),n("hyphen replace",w),w=w.replace(l[u.COMPARATORTRIM],d),n("comparator trim",w),w=w.replace(l[u.TILDETRIM],f),n("tilde trim",w),w=w.replace(l[u.CARETTRIM],g),n("caret trim",w);let $=w.split(" ").map(D=>W(D,this.options)).join(" ").split(/\s+/).map(D=>ze(D,this.options));A&&($=$.filter(D=>(n("loose invalid filter",D,this.options),!!D.match(l[u.COMPARATORLOOSE])))),n("range list",$);let k=new Map,C=$.map(D=>new c(D,this.options));for(let D of C){if(R(D))return[D];k.set(D.value,D)}k.size>1&&k.has("")&&k.delete("");let M=[...k.values()];return i.set(S,M),M}intersects(w,S){if(!(w instanceof ke))throw new TypeError("a Range is required");return this.set.some(E=>j(E,S)&&w.set.some(A=>j(A,S)&&E.every(v=>A.every($=>v.intersects($,S)))))}test(w){if(!w)return!1;if(typeof w=="string")try{w=new m(w,this.options)}catch{return!1}for(let S=0;S<this.set.length;S++)if(Ye(this.set[S],w,this.options))return!0;return!1}};t.exports=s;var o=Bs(),i=new o,a=dt(),c=xe(),n=Ue(),m=K(),{safeRe:l,t:u,comparatorTrimReplace:d,tildeTrimReplace:f,caretTrimReplace:g}=Ae(),{FLAG_INCLUDE_PRERELEASE:h,FLAG_LOOSE:b}=be(),R=y=>y.value==="<0.0.0-0",N=y=>y.value==="",j=(y,w)=>{let S=!0,E=y.slice(),A=E.pop();for(;S&&E.length;)S=E.every(v=>A.intersects(v,w)),A=E.pop();return S},W=(y,w)=>(y=y.replace(l[u.BUILD],""),n("comp",y,w),y=_(y,w),n("caret",y),y=Z(y,w),n("tildes",y),y=T(y,w),n("xrange",y),y=Xe(y,w),n("stars",y),y),U=y=>!y||y.toLowerCase()==="x"||y==="*",Z=(y,w)=>y.trim().split(/\s+/).map(S=>J(S,w)).join(" "),J=(y,w)=>{let S=w.loose?l[u.TILDELOOSE]:l[u.TILDE];return y.replace(S,(E,A,v,$,k)=>{n("tilde",y,E,A,v,$,k);let C;return U(A)?C="":U(v)?C=`>=${A}.0.0 <${+A+1}.0.0-0`:U($)?C=`>=${A}.${v}.0 <${A}.${+v+1}.0-0`:k?(n("replaceTilde pr",k),C=`>=${A}.${v}.${$}-${k} <${A}.${+v+1}.0-0`):C=`>=${A}.${v}.${$} <${A}.${+v+1}.0-0`,n("tilde return",C),C})},_=(y,w)=>y.trim().split(/\s+/).map(S=>H(S,w)).join(" "),H=(y,w)=>{n("caret",y,w);let S=w.loose?l[u.CARETLOOSE]:l[u.CARET],E=w.includePrerelease?"-0":"";return y.replace(S,(A,v,$,k,C)=>{n("caret",y,A,v,$,k,C);let M;return U(v)?M="":U($)?M=`>=${v}.0.0${E} <${+v+1}.0.0-0`:U(k)?v==="0"?M=`>=${v}.${$}.0${E} <${v}.${+$+1}.0-0`:M=`>=${v}.${$}.0${E} <${+v+1}.0.0-0`:C?(n("replaceCaret pr",C),v==="0"?$==="0"?M=`>=${v}.${$}.${k}-${C} <${v}.${$}.${+k+1}-0`:M=`>=${v}.${$}.${k}-${C} <${v}.${+$+1}.0-0`:M=`>=${v}.${$}.${k}-${C} <${+v+1}.0.0-0`):(n("no pr"),v==="0"?$==="0"?M=`>=${v}.${$}.${k}${E} <${v}.${$}.${+k+1}-0`:M=`>=${v}.${$}.${k}${E} <${v}.${+$+1}.0-0`:M=`>=${v}.${$}.${k} <${+v+1}.0.0-0`),n("caret return",M),M})},T=(y,w)=>(n("replaceXRanges",y,w),y.split(/\s+/).map(S=>me(S,w)).join(" ")),me=(y,w)=>{y=y.trim();let S=w.loose?l[u.XRANGELOOSE]:l[u.XRANGE];return y.replace(S,(E,A,v,$,k,C)=>{n("xRange",y,E,A,v,$,k,C);let M=U(v),D=M||U($),ee=D||U(k),fe=ee;return A==="="&&fe&&(A=""),C=w.includePrerelease?"-0":"",M?A===">"||A==="<"?E="<0.0.0-0":E="*":A&&fe?(D&&($=0),k=0,A===">"?(A=">=",D?(v=+v+1,$=0,k=0):($=+$+1,k=0)):A==="<="&&(A="<",D?v=+v+1:$=+$+1),A==="<"&&(C="-0"),E=`${A+v}.${$}.${k}${C}`):D?E=`>=${v}.0.0${C} <${+v+1}.0.0-0`:ee&&(E=`>=${v}.${$}.0${C} <${v}.${+$+1}.0-0`),n("xRange return",E),E})},Xe=(y,w)=>(n("replaceStars",y,w),y.trim().replace(l[u.STAR],"")),ze=(y,w)=>(n("replaceGTE0",y,w),y.trim().replace(l[w.includePrerelease?u.GTE0PRE:u.GTE0],"")),qe=y=>(w,S,E,A,v,$,k,C,M,D,ee,fe)=>(U(E)?S="":U(A)?S=`>=${E}.0.0${y?"-0":""}`:U(v)?S=`>=${E}.${A}.0${y?"-0":""}`:$?S=`>=${S}`:S=`>=${S}${y?"-0":""}`,U(M)?C="":U(D)?C=`<${+M+1}.0.0-0`:U(ee)?C=`<${M}.${+D+1}.0-0`:fe?C=`<=${M}.${D}.${ee}-${fe}`:y?C=`<${M}.${D}.${+ee+1}-0`:C=`<=${C}`,`${S} ${C}`.trim()),Ye=(y,w,S)=>{for(let E=0;E<y.length;E++)if(!y[E].test(w))return!1;if(w.prerelease.length&&!S.includePrerelease){for(let E=0;E<y.length;E++)if(n(y[E].semver),y[E].semver!==c.ANY&&y[E].semver.prerelease.length>0){let A=y[E].semver;if(A.major===w.major&&A.minor===w.minor&&A.patch===w.patch)return!0}return!1}return!0}}),xe=I((e,t)=>{"use strict";var r=Symbol("SemVer ANY"),s=class st{static get ANY(){return r}constructor(d,f){if(f=o(f),d instanceof st){if(d.loose===!!f.loose)return d;d=d.value}d=d.trim().split(/\s+/).join(" "),n("comparator",d,f),this.options=f,this.loose=!!f.loose,this.parse(d),this.semver===r?this.value="":this.value=this.operator+this.semver.version,n("comp",this)}parse(d){let f=this.options.loose?i[a.COMPARATORLOOSE]:i[a.COMPARATOR],g=d.match(f);if(!g)throw new TypeError(`Invalid comparator: ${d}`);this.operator=g[1]!==void 0?g[1]:"",this.operator==="="&&(this.operator=""),g[2]?this.semver=new m(g[2],this.options.loose):this.semver=r}toString(){return this.value}test(d){if(n("Comparator.test",d,this.options.loose),this.semver===r||d===r)return!0;if(typeof d=="string")try{d=new m(d,this.options)}catch{return!1}return c(d,this.operator,this.semver,this.options)}intersects(d,f){if(!(d instanceof st))throw new TypeError("a Comparator is required");return this.operator===""?this.value===""?!0:new l(d.value,f).test(this.value):d.operator===""?d.value===""?!0:new l(this.value,f).test(d.semver):(f=o(f),f.includePrerelease&&(this.value==="<0.0.0-0"||d.value==="<0.0.0-0")||!f.includePrerelease&&(this.value.startsWith("<0.0.0")||d.value.startsWith("<0.0.0"))?!1:!!(this.operator.startsWith(">")&&d.operator.startsWith(">")||this.operator.startsWith("<")&&d.operator.startsWith("<")||this.semver.version===d.semver.version&&this.operator.includes("=")&&d.operator.includes("=")||c(this.semver,"<",d.semver,f)&&this.operator.startsWith(">")&&d.operator.startsWith("<")||c(this.semver,">",d.semver,f)&&this.operator.startsWith("<")&&d.operator.startsWith(">")))}};t.exports=s;var o=dt(),{safeRe:i,t:a}=Ae(),c=rr(),n=Ue(),m=K(),l=z()}),je=I((e,t)=>{"use strict";var r=z(),s=(o,i,a)=>{try{i=new r(i,a)}catch{return!1}return i.test(o)};t.exports=s}),Gs=I((e,t)=>{"use strict";var r=z(),s=(o,i)=>new r(o,i).set.map(a=>a.map(c=>c.value).join(" ").trim().split(" "));t.exports=s}),Ks=I((e,t)=>{"use strict";var r=K(),s=z(),o=(i,a,c)=>{let n=null,m=null,l=null;try{l=new s(a,c)}catch{return null}return i.forEach(u=>{l.test(u)&&(!n||m.compare(u)===-1)&&(n=u,m=new r(n,c))}),n};t.exports=o}),Js=I((e,t)=>{"use strict";var r=K(),s=z(),o=(i,a,c)=>{let n=null,m=null,l=null;try{l=new s(a,c)}catch{return null}return i.forEach(u=>{l.test(u)&&(!n||m.compare(u)===1)&&(n=u,m=new r(n,c))}),n};t.exports=o}),Vs=I((e,t)=>{"use strict";var r=K(),s=z(),o=_e(),i=(a,c)=>{a=new s(a,c);let n=new r("0.0.0");if(a.test(n)||(n=new r("0.0.0-0"),a.test(n)))return n;n=null;for(let m=0;m<a.set.length;++m){let l=a.set[m],u=null;l.forEach(d=>{let f=new r(d.semver.version);switch(d.operator){case">":f.prerelease.length===0?f.patch++:f.prerelease.push(0),f.raw=f.format();case"":case">=":(!u||o(f,u))&&(u=f);break;case"<":case"<=":break;default:throw new Error(`Unexpected operation: ${d.operator}`)}}),u&&(!n||o(n,u))&&(n=u)}return n&&a.test(n)?n:null};t.exports=i}),Xs=I((e,t)=>{"use strict";var r=z(),s=(o,i)=>{try{return new r(o,i).range||"*"}catch{return null}};t.exports=s}),wt=I((e,t)=>{"use strict";var r=K(),s=xe(),{ANY:o}=s,i=z(),a=je(),c=_e(),n=mt(),m=gt(),l=ft(),u=(d,f,g,h)=>{d=new r(d,h),f=new i(f,h);let b,R,N,j,W;switch(g){case">":b=c,R=m,N=n,j=">",W=">=";break;case"<":b=n,R=l,N=c,j="<",W="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if(a(d,f,h))return!1;for(let U=0;U<f.set.length;++U){let Z=f.set[U],J=null,_=null;if(Z.forEach(H=>{H.semver===o&&(H=new s(">=0.0.0")),J=J||H,_=_||H,b(H.semver,J.semver,h)?J=H:N(H.semver,_.semver,h)&&(_=H)}),J.operator===j||J.operator===W||(!_.operator||_.operator===j)&&R(d,_.semver)||_.operator===W&&N(d,_.semver))return!1}return!0};t.exports=u}),zs=I((e,t)=>{"use strict";var r=wt(),s=(o,i,a)=>r(o,i,">",a);t.exports=s}),qs=I((e,t)=>{"use strict";var r=wt(),s=(o,i,a)=>r(o,i,"<",a);t.exports=s}),Ys=I((e,t)=>{"use strict";var r=z(),s=(o,i,a)=>(o=new r(o,a),i=new r(i,a),o.intersects(i,a));t.exports=s}),Qs=I((e,t)=>{"use strict";var r=je(),s=X();t.exports=(o,i,a)=>{let c=[],n=null,m=null,l=o.sort((g,h)=>s(g,h,a));for(let g of l)r(g,i,a)?(m=g,n||(n=g)):(m&&c.push([n,m]),m=null,n=null);n&&c.push([n,null]);let u=[];for(let[g,h]of c)g===h?u.push(g):!h&&g===l[0]?u.push("*"):h?g===l[0]?u.push(`<=${h}`):u.push(`${g} - ${h}`):u.push(`>=${g}`);let d=u.join(" || "),f=typeof i.raw=="string"?i.raw:String(i);return d.length<f.length?d:i}}),Zs=I((e,t)=>{"use strict";var r=z(),s=xe(),{ANY:o}=s,i=je(),a=X(),c=(f,g,h={})=>{if(f===g)return!0;f=new r(f,h),g=new r(g,h);let b=!1;e:for(let R of f.set){for(let N of g.set){let j=l(R,N,h);if(b=b||j!==null,j)continue e}if(b)return!1}return!0},n=[new s(">=0.0.0-0")],m=[new s(">=0.0.0")],l=(f,g,h)=>{if(f===g)return!0;if(f.length===1&&f[0].semver===o){if(g.length===1&&g[0].semver===o)return!0;h.includePrerelease?f=n:f=m}if(g.length===1&&g[0].semver===o){if(h.includePrerelease)return!0;g=m}let b=new Set,R,N;for(let T of f)T.operator===">"||T.operator===">="?R=u(R,T,h):T.operator==="<"||T.operator==="<="?N=d(N,T,h):b.add(T.semver);if(b.size>1)return null;let j;if(R&&N&&(j=a(R.semver,N.semver,h),j>0||j===0&&(R.operator!==">="||N.operator!=="<=")))return null;for(let T of b){if(R&&!i(T,String(R),h)||N&&!i(T,String(N),h))return null;for(let me of g)if(!i(T,String(me),h))return!1;return!0}let W,U,Z,J,_=N&&!h.includePrerelease&&N.semver.prerelease.length?N.semver:!1,H=R&&!h.includePrerelease&&R.semver.prerelease.length?R.semver:!1;_&&_.prerelease.length===1&&N.operator==="<"&&_.prerelease[0]===0&&(_=!1);for(let T of g){if(J=J||T.operator===">"||T.operator===">=",Z=Z||T.operator==="<"||T.operator==="<=",R){if(H&&T.semver.prerelease&&T.semver.prerelease.length&&T.semver.major===H.major&&T.semver.minor===H.minor&&T.semver.patch===H.patch&&(H=!1),T.operator===">"||T.operator===">="){if(W=u(R,T,h),W===T&&W!==R)return!1}else if(R.operator===">="&&!i(R.semver,String(T),h))return!1}if(N){if(_&&T.semver.prerelease&&T.semver.prerelease.length&&T.semver.major===_.major&&T.semver.minor===_.minor&&T.semver.patch===_.patch&&(_=!1),T.operator==="<"||T.operator==="<="){if(U=d(N,T,h),U===T&&U!==N)return!1}else if(N.operator==="<="&&!i(N.semver,String(T),h))return!1}if(!T.operator&&(N||R)&&j!==0)return!1}return!(R&&Z&&!N&&j!==0||N&&J&&!R&&j!==0||H||_)},u=(f,g,h)=>{if(!f)return g;let b=a(f.semver,g.semver,h);return b>0?f:b<0||g.operator===">"&&f.operator===">="?g:f},d=(f,g,h)=>{if(!f)return g;let b=a(f.semver,g.semver,h);return b<0?f:b>0||g.operator==="<"&&f.operator==="<="?g:f};t.exports=c}),sr=I((e,t)=>{"use strict";var r=Ae(),s=be(),o=K(),i=Zt(),a=oe(),c=Os(),n=Ns(),m=Cs(),l=Ls(),u=ks(),d=Ms(),f=Ds(),g=Us(),h=X(),b=_s(),R=xs(),N=ht(),j=js(),W=Fs(),U=_e(),Z=mt(),J=er(),_=tr(),H=ft(),T=gt(),me=rr(),Xe=Ws(),ze=Hs(),qe=xe(),Ye=z(),y=je(),w=Gs(),S=Ks(),E=Js(),A=Vs(),v=Xs(),$=wt(),k=zs(),C=qs(),M=Ys(),D=Qs(),ee=Zs();t.exports={parse:a,valid:c,clean:n,inc:m,diff:l,major:u,minor:d,patch:f,prerelease:g,compare:h,rcompare:b,compareLoose:R,compareBuild:N,sort:j,rsort:W,gt:U,lt:Z,eq:J,neq:_,gte:H,lte:T,cmp:me,coerce:Xe,truncate:ze,Comparator:qe,Range:Ye,satisfies:y,toComparators:w,maxSatisfying:S,minSatisfying:E,minVersion:A,validRange:v,outside:$,gtr:k,ltr:C,intersects:M,simplifyRange:D,subset:ee,SemVer:o,re:r.re,src:r.src,tokens:r.t,SEMVER_SPEC_VERSION:s.SEMVER_SPEC_VERSION,RELEASE_TYPES:s.RELEASE_TYPES,compareIdentifiers:i.compareIdentifiers,rcompareIdentifiers:i.rcompareIdentifiers}}),Ie=class extends co{constructor(e){super(),B(this,"dirName"),B(this,"fileName"),this.dirName=Pt(ho(),".medplum"),this.fileName=Pt(this.dirName,e+".json")}clear(){this.writeFile({})}getString(e){return this.readFile()?.[e]}setString(e,t){let r=this.readFile()??{};t?r[e]=t:delete r[e],this.writeFile(r)}getObject(e){let t=this.getString(e);return t?JSON.parse(t):void 0}setObject(e,t){this.setString(e,t?JSON.stringify(t):void 0)}readFile(){if(Tt(this.fileName))return JSON.parse(uo(this.fileName,"utf8"))}writeFile(e){Tt(this.dirName)||lo(this.dirName),po(this.fileName,JSON.stringify(e,null,2),"utf8")}};async function x(e,t=!0){let r=e.profile??"default",s=new Ie(r),o=s.getObject("options");if(r!=="default"&&!o)throw new Error(`Profile "${r}" does not exist`);let{baseUrl:i,fhirUrlPath:a,accessToken:c,tokenUrl:n,authorizeUrl:m,clientId:l,clientSecret:u}=mo(e,s),d=e.fetch??fetch;e.baseUrl&&e.baseUrl!=="https://api.medplum.com/"&&await fo(e.baseUrl,d);let f=new no({fetch:d,baseUrl:i,tokenUrl:n,fhirUrlPath:a,authorizeUrl:m,storage:s,onUnauthenticated:go,verbose:e.verbose});return t&&(c?f.setAccessToken(c):l&&u&&(f.setBasicAuth(l,u),o?.authType!=="basic"&&await f.startClientLogin(l,u))),f}function mo(e,t){let r=t.getObject("options"),s=e.baseUrl??r?.baseUrl??process.env.MEDPLUM_BASE_URL??"https://api.medplum.com/",o=e.fhirUrlPath??r?.fhirUrlPath??process.env.MEDPLUM_FHIR_URL_PATH,i=e.accessToken??r?.accessToken??process.env.MEDPLUM_CLIENT_ACCESS_TOKEN,a=e.tokenUrl??r?.tokenUrl??process.env.MEDPLUM_TOKEN_URL,c=e.authorizeUrl??r?.authorizeUrl??process.env.MEDPLUM_AUTHORIZE_URL,n=e.clientId??r?.clientId??process.env.MEDPLUM_CLIENT_ID,m=e.clientSecret??r?.clientSecret??process.env.MEDPLUM_CLIENT_SECRET;return{baseUrl:s,fhirUrlPath:o,accessToken:i,tokenUrl:a,authorizeUrl:c,clientId:n,clientSecret:m}}async function fo(e,t){try{let r=new URL("healthcheck",e).toString(),s=await t(r);if(!s.ok)throw new Error(`Healthcheck returned status ${s.status}`);if((await s.json()).ok===!0)return;throw new Error('Healthcheck response does not have "ok": true')}catch(r){let s=r instanceof Error?r.message:String(r);throw new Error(`Failed to validate base URL "${e}": ${s}`)}}function go(){console.log("Unauthenticated: run `npx medplum login` to sign in")}var Ee=new TextEncoder,Nt=new TextDecoder,pc=2**32;function Eo(...e){let t=e.reduce((o,{length:i})=>o+i,0),r=new Uint8Array(t),s=0;for(let o of e)r.set(o,s),s+=o.length;return r}var Ze=e=>yo.from(e).toString("base64url"),$e=class extends Error{constructor(e,t){super(e,t),B(this,"code","ERR_JOSE_GENERIC"),this.name=this.constructor.name,Error.captureStackTrace?.(this,this.constructor)}};B($e,"code","ERR_JOSE_GENERIC");var de=class extends $e{constructor(){super(...arguments),B(this,"code","ERR_JOSE_NOT_SUPPORTED")}};B(de,"code","ERR_JOSE_NOT_SUPPORTED");var ce=class extends $e{constructor(){super(...arguments),B(this,"code","ERR_JWS_INVALID")}};B(ce,"code","ERR_JWS_INVALID");var nr=class extends $e{constructor(){super(...arguments),B(this,"code","ERR_JWT_INVALID")}};B(nr,"code","ERR_JWT_INVALID");var Ct,Lt,vo=class extends(Lt=$e,Ct=Symbol.asyncIterator,Lt){constructor(e="multiple matching keys found in the JSON Web Key Set",t){super(e,t),B(this,Ct),B(this,"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS")}};B(vo,"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS");var lr=e=>cr.types.isKeyObject(e),So=ur.webcrypto,bo=So,yt=e=>pr.types.isCryptoKey(e);function q(e,t="algorithm.name"){return new TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`)}function ge(e,t){return e.name===t}function et(e){return parseInt(e.name.slice(4),10)}function Ao(e){switch(e){case"ES256":return"P-256";case"ES384":return"P-384";case"ES512":return"P-521";default:throw new Error("unreachable")}}function Io(e,t){if(t.length&&!t.some(r=>e.usages.includes(r))){let r="CryptoKey does not support this operation, its usages must include ";if(t.length>2){let s=t.pop();r+=`one of ${t.join(", ")}, or ${s}.`}else t.length===2?r+=`one of ${t[0]} or ${t[1]}.`:r+=`${t[0]}.`;throw new TypeError(r)}}function $o(e,t,...r){switch(t){case"HS256":case"HS384":case"HS512":{if(!ge(e.algorithm,"HMAC"))throw q("HMAC");let s=parseInt(t.slice(2),10);if(et(e.algorithm.hash)!==s)throw q(`SHA-${s}`,"algorithm.hash");break}case"RS256":case"RS384":case"RS512":{if(!ge(e.algorithm,"RSASSA-PKCS1-v1_5"))throw q("RSASSA-PKCS1-v1_5");let s=parseInt(t.slice(2),10);if(et(e.algorithm.hash)!==s)throw q(`SHA-${s}`,"algorithm.hash");break}case"PS256":case"PS384":case"PS512":{if(!ge(e.algorithm,"RSA-PSS"))throw q("RSA-PSS");let s=parseInt(t.slice(2),10);if(et(e.algorithm.hash)!==s)throw q(`SHA-${s}`,"algorithm.hash");break}case"EdDSA":{if(e.algorithm.name!=="Ed25519"&&e.algorithm.name!=="Ed448")throw q("Ed25519 or Ed448");break}case"Ed25519":{if(!ge(e.algorithm,"Ed25519"))throw q("Ed25519");break}case"ES256":case"ES384":case"ES512":{if(!ge(e.algorithm,"ECDSA"))throw q("ECDSA");let s=Ao(t);if(e.algorithm.namedCurve!==s)throw q(s,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}Io(e,r)}function dr(e,t,...r){if(r=r.filter(Boolean),r.length>2){let s=r.pop();e+=`one of type ${r.join(", ")}, or ${s}.`}else r.length===2?e+=`one of type ${r[0]} or ${r[1]}.`:e+=`of type ${r[0]}.`;return t==null?e+=` Received ${t}`:typeof t=="function"&&t.name?e+=` Received function ${t.name}`:typeof t=="object"&&t!=null&&t.constructor?.name&&(e+=` Received an instance of ${t.constructor.name}`),e}var it=(e,...t)=>dr("Key must be ",e,...t);function hr(e,t,...r){return dr(`Key for the ${e} algorithm must be `,t,...r)}var mr=e=>lr(e)||yt(e),ue=["KeyObject"];(globalThis.CryptoKey||bo?.CryptoKey)&&ue.push("CryptoKey");var Ro=(...e)=>{let t=e.filter(Boolean);if(t.length===0||t.length===1)return!0;let r;for(let s of t){let o=Object.keys(s);if(!r||r.size===0){r=new Set(o);continue}for(let i of o){if(r.has(i))return!1;r.add(i)}}return!0},To=Ro;function Po(e){return typeof e=="object"&&e!==null}function fr(e){if(!Po(e)||Object.prototype.toString.call(e)!=="[object Object]")return!1;if(Object.getPrototypeOf(e)===null)return!0;let t=e;for(;Object.getPrototypeOf(t)!==null;)t=Object.getPrototypeOf(t);return Object.getPrototypeOf(e)===t}function Re(e){return fr(e)&&typeof e.kty=="string"}function No(e){return e.kty!=="oct"&&typeof e.d=="string"}function Co(e){return e.kty!=="oct"&&typeof e.d>"u"}function Lo(e){return Re(e)&&e.kty==="oct"&&typeof e.k=="string"}var ko=e=>{switch(e){case"prime256v1":return"P-256";case"secp384r1":return"P-384";case"secp521r1":return"P-521";case"secp256k1":return"secp256k1";default:throw new de("Unsupported key curve for this operation")}},Mo=(e,t)=>{let r;if(yt(e))r=Oo.from(e);else if(lr(e))r=e;else{if(Re(e))return e.crv;throw new TypeError(it(e,...ue))}if(r.type==="secret")throw new TypeError('only "private" or "public" type keys can be used for this operation');switch(r.asymmetricKeyType){case"ed25519":case"ed448":return`Ed${r.asymmetricKeyType.slice(2)}`;case"x25519":case"x448":return`X${r.asymmetricKeyType.slice(1)}`;case"ec":{let s=r.asymmetricKeyDetails.namedCurve;return t?s:ko(s)}default:throw new TypeError("Invalid asymmetric key type for this operation")}},Do=Mo,kt=(e,t)=>{let r;try{e instanceof Uo?r=e.asymmetricKeyDetails?.modulusLength:r=Buffer.from(e.n,"base64url").byteLength<<3}catch{}if(typeof r!="number"||r<2048)throw new TypeError(`${t} requires key modulusLength to be 2048 bits or larger`)},le=e=>e?.[Symbol.toStringTag],at=(e,t,r)=>{if(t.use!==void 0&&t.use!=="sig")throw new TypeError("Invalid key for this operation, when present its use must be sig");if(t.key_ops!==void 0&&t.key_ops.includes?.(r)!==!0)throw new TypeError(`Invalid key for this operation, when present its key_ops must include ${r}`);if(t.alg!==void 0&&t.alg!==e)throw new TypeError(`Invalid key for this operation, when present its alg must be ${e}`);return!0},_o=(e,t,r,s)=>{if(!(t instanceof Uint8Array)){if(s&&Re(t)){if(Lo(t)&&at(e,t,r))return;throw new TypeError('JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present')}if(!mr(t))throw new TypeError(hr(e,t,...ue,"Uint8Array",s?"JSON Web Key":null));if(t.type!=="secret")throw new TypeError(`${le(t)} instances for symmetric algorithms must be of type "secret"`)}},xo=(e,t,r,s)=>{if(s&&Re(t))switch(r){case"sign":if(No(t)&&at(e,t,r))return;throw new TypeError("JSON Web Key for this operation be a private JWK");case"verify":if(Co(t)&&at(e,t,r))return;throw new TypeError("JSON Web Key for this operation be a public JWK")}if(!mr(t))throw new TypeError(hr(e,t,...ue,s?"JSON Web Key":null));if(t.type==="secret")throw new TypeError(`${le(t)} instances for asymmetric algorithms must not be of type "secret"`);if(r==="sign"&&t.type==="public")throw new TypeError(`${le(t)} instances for asymmetric algorithm signing must be of type "private"`);if(r==="decrypt"&&t.type==="public")throw new TypeError(`${le(t)} instances for asymmetric algorithm decryption must be of type "private"`);if(t.algorithm&&r==="verify"&&t.type==="private")throw new TypeError(`${le(t)} instances for asymmetric algorithm verifying must be of type "public"`);if(t.algorithm&&r==="encrypt"&&t.type==="private")throw new TypeError(`${le(t)} instances for asymmetric algorithm encryption must be of type "public"`)};function gr(e,t,r,s){t.startsWith("HS")||t==="dir"||t.startsWith("PBES2")||/^A\d{3}(?:GCM)?KW$/.test(t)?_o(t,r,s,e):xo(t,r,s,e)}var mc=gr.bind(void 0,!1),jo=gr.bind(void 0,!0);function Fo(e,t,r,s,o){if(o.crit!==void 0&&s?.crit===void 0)throw new e('"crit" (Critical) Header Parameter MUST be integrity protected');if(!s||s.crit===void 0)return new Set;if(!Array.isArray(s.crit)||s.crit.length===0||s.crit.some(a=>typeof a!="string"||a.length===0))throw new e('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');let i;r!==void 0?i=new Map([...Object.entries(r),...t.entries()]):i=t;for(let a of s.crit){if(!i.has(a))throw new de(`Extension Header Parameter "${a}" is not recognized`);if(o[a]===void 0)throw new e(`Extension Header Parameter "${a}" is missing`);if(i.get(a)&&s[a]===void 0)throw new e(`Extension Header Parameter "${a}" MUST be integrity protected`)}return new Set(s.crit)}var Wo=Fo;function Ho(e){switch(e){case"PS256":case"RS256":case"ES256":case"ES256K":return"sha256";case"PS384":case"RS384":case"ES384":return"sha384";case"PS512":case"RS512":case"ES512":return"sha512";case"Ed25519":case"EdDSA":return;default:throw new de(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}var Go=new Map([["ES256","P-256"],["ES256K","secp256k1"],["ES384","P-384"],["ES512","P-521"]]);function Ko(e,t){let r,s,o;if(t instanceof Bo)r=t.asymmetricKeyType,s=t.asymmetricKeyDetails;else switch(o=!0,t.kty){case"RSA":r="rsa";break;case"EC":r="ec";break;case"OKP":{if(t.crv==="Ed25519"){r="ed25519";break}if(t.crv==="Ed448"){r="ed448";break}throw new TypeError("Invalid key for this operation, its crv must be Ed25519 or Ed448")}default:throw new TypeError("Invalid key for this operation, its kty must be RSA, OKP, or EC")}let i;switch(e){case"Ed25519":if(r!=="ed25519")throw new TypeError("Invalid key for this operation, its asymmetricKeyType must be ed25519");break;case"EdDSA":if(!["ed25519","ed448"].includes(r))throw new TypeError("Invalid key for this operation, its asymmetricKeyType must be ed25519 or ed448");break;case"RS256":case"RS384":case"RS512":if(r!=="rsa")throw new TypeError("Invalid key for this operation, its asymmetricKeyType must be rsa");kt(t,e);break;case"PS256":case"PS384":case"PS512":if(r==="rsa-pss"){let{hashAlgorithm:a,mgf1HashAlgorithm:c,saltLength:n}=s,m=parseInt(e.slice(-3),10);if(a!==void 0&&(a!==`sha${m}`||c!==a))throw new TypeError(`Invalid key for this operation, its RSA-PSS parameters do not meet the requirements of "alg" ${e}`);if(n!==void 0&&n>m>>3)throw new TypeError(`Invalid key for this operation, its RSA-PSS parameter saltLength does not meet the requirements of "alg" ${e}`)}else if(r!=="rsa")throw new TypeError("Invalid key for this operation, its asymmetricKeyType must be rsa or rsa-pss");kt(t,e),i={padding:Mt.RSA_PKCS1_PSS_PADDING,saltLength:Mt.RSA_PSS_SALTLEN_DIGEST};break;case"ES256":case"ES256K":case"ES384":case"ES512":{if(r!=="ec")throw new TypeError("Invalid key for this operation, its asymmetricKeyType must be ec");let a=Do(t),c=Go.get(e);if(a!==c)throw new TypeError(`Invalid key curve for the algorithm, its curve must be ${c}, got ${a}`);i={dsaEncoding:"ieee-p1363"};break}default:throw new de(`alg ${e} is not supported either by JOSE or your javascript runtime`)}return o?{format:"jwk",key:t,...i}:i?{...i,key:t}:t}function Vo(e){switch(e){case"HS256":return"sha256";case"HS384":return"sha384";case"HS512":return"sha512";default:throw new de(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}function Xo(e,t,r){if(t instanceof Uint8Array){if(!e.startsWith("HS"))throw new TypeError(it(t,...ue));return Ut(t)}if(t instanceof Dt)return t;if(yt(t))return $o(t,e,r),Dt.from(t);if(Re(t))return e.startsWith("HS")?Ut(Buffer.from(t.k,"base64url")):t;throw new TypeError(it(t,...ue,"Uint8Array","JSON Web Key"))}var zo=Jo(We.sign),qo=async(e,t,r)=>{let s=Xo(e,t,"sign");if(e.startsWith("HS")){let o=We.createHmac(Vo(e),s);return o.update(r),o.digest()}return zo(Ho(e),r,Ko(e,s))},Yo=qo,te=e=>Math.floor(e.getTime()/1e3),Qo=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i,tt=e=>{let t=Qo.exec(e);if(!t||t[4]&&t[1])throw new TypeError("Invalid time period format");let r=parseFloat(t[2]),s=t[3].toLowerCase(),o;switch(s){case"sec":case"secs":case"second":case"seconds":case"s":o=Math.round(r);break;case"minute":case"minutes":case"min":case"mins":case"m":o=Math.round(r*60);break;case"hour":case"hours":case"hr":case"hrs":case"h":o=Math.round(r*3600);break;case"day":case"days":case"d":o=Math.round(r*86400);break;case"week":case"weeks":case"w":o=Math.round(r*604800);break;default:o=Math.round(r*31557600);break}return t[1]==="-"||t[4]==="ago"?-o:o},Zo=class{constructor(e){if(B(this,"_payload"),B(this,"_protectedHeader"),B(this,"_unprotectedHeader"),!(e instanceof Uint8Array))throw new TypeError("payload must be an instance of Uint8Array");this._payload=e}setProtectedHeader(e){if(this._protectedHeader)throw new TypeError("setProtectedHeader can only be called once");return this._protectedHeader=e,this}setUnprotectedHeader(e){if(this._unprotectedHeader)throw new TypeError("setUnprotectedHeader can only be called once");return this._unprotectedHeader=e,this}async sign(e,t){if(!this._protectedHeader&&!this._unprotectedHeader)throw new ce("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");if(!To(this._protectedHeader,this._unprotectedHeader))throw new ce("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let r={...this._protectedHeader,...this._unprotectedHeader},s=Wo(ce,new Map([["b64",!0]]),t?.crit,this._protectedHeader,r),o=!0;if(s.has("b64")&&(o=this._protectedHeader.b64,typeof o!="boolean"))throw new ce('The "b64" (base64url-encode payload) Header Parameter must be a boolean');let{alg:i}=r;if(typeof i!="string"||!i)throw new ce('JWS "alg" (Algorithm) Header Parameter missing or invalid');jo(i,e,"sign");let a=this._payload;o&&(a=Ee.encode(Ze(a)));let c;this._protectedHeader?c=Ee.encode(Ze(JSON.stringify(this._protectedHeader))):c=Ee.encode("");let n=Eo(c,Ee.encode("."),a),m=await Yo(i,e,n),l={signature:Ze(m),payload:""};return o&&(l.payload=Nt.decode(a)),this._unprotectedHeader&&(l.header=this._unprotectedHeader),this._protectedHeader&&(l.protected=Nt.decode(c)),l}},ei=class{constructor(e){B(this,"_flattened"),this._flattened=new Zo(e)}setProtectedHeader(e){return this._flattened.setProtectedHeader(e),this}async sign(e,t){let r=await this._flattened.sign(e,t);if(r.payload===void 0)throw new TypeError("use the flattened module for creating JWS with b64: false");return`${r.protected}.${r.payload}.${r.signature}`}};function re(e,t){if(!Number.isFinite(t))throw new TypeError(`Invalid ${e} input`);return t}var ti=class{constructor(e={}){if(B(this,"_payload"),!fr(e))throw new TypeError("JWT Claims Set MUST be an object");this._payload=e}setIssuer(e){return this._payload={...this._payload,iss:e},this}setSubject(e){return this._payload={...this._payload,sub:e},this}setAudience(e){return this._payload={...this._payload,aud:e},this}setJti(e){return this._payload={...this._payload,jti:e},this}setNotBefore(e){return typeof e=="number"?this._payload={...this._payload,nbf:re("setNotBefore",e)}:e instanceof Date?this._payload={...this._payload,nbf:re("setNotBefore",te(e))}:this._payload={...this._payload,nbf:te(new Date)+tt(e)},this}setExpirationTime(e){return typeof e=="number"?this._payload={...this._payload,exp:re("setExpirationTime",e)}:e instanceof Date?this._payload={...this._payload,exp:re("setExpirationTime",te(e))}:this._payload={...this._payload,exp:te(new Date)+tt(e)},this}setIssuedAt(e){return typeof e>"u"?this._payload={...this._payload,iat:te(new Date)}:e instanceof Date?this._payload={...this._payload,iat:re("setIssuedAt",te(e))}:typeof e=="string"?this._payload={...this._payload,iat:re("setIssuedAt",te(new Date)+tt(e))}:this._payload={...this._payload,iat:re("setIssuedAt",e)},this}},ri=class extends ti{constructor(){super(...arguments),B(this,"_protectedHeader")}setProtectedHeader(e){return this._protectedHeader=e,this}async sign(e,t){let r=new ei(Ee.encode(JSON.stringify(this._payload)));if(r.setProtectedHeader(this._protectedHeader),Array.isArray(this._protectedHeader?.crit)&&this._protectedHeader.crit.includes("b64")&&this._protectedHeader.b64===!1)throw new nr("JWTs MUST NOT use unencoded payload");return r.sign(e,t)}};function se(e){console.log(JSON.stringify(e,null,2))}async function vr(e,t,r){let s=t.source,o=He(s);if(!o)return;console.log("Saving source code...");let i=await e.createAttachment({data:o,filename:Er(s),contentType:fi(s)});console.log("Updating bot...");let a=await e.updateResource({...r,sourceCode:i});console.log("Success! New bot version: "+a.meta?.versionId)}async function Sr(e,t,r){let s=t.dist??t.source,o=He(s);if(!o)return;console.log("Deploying bot...");let i=await e.post(e.fhirUrl("Bot",r.id,"$deploy"),{code:o,filename:Er(s)});console.log("Deploy result: "+i.issue?.[0]?.details?.text)}async function br(e,t,r,s,o,i,a){let c={name:t,description:"",runtimeVersion:i},n=await e.post("admin/projects/"+r+"/bot",c),m=await e.readResource("Bot",n.id),l={name:t,id:n.id,source:s,dist:o};await vr(e,l,m),await Sr(e,l,m),console.log(`Success! Bot created: ${m.id}`),a&&di(l)}function ui(e){let t=new RegExp("^"+hi(e).replaceAll(String.raw`\*`,".*")+"$");return he()?.bots?.filter(s=>t.test(s.name))||[]}function ie(e,t){if(t?.file)return t.file;let r=["medplum"];return e&&r.push(e),r.push("config"),t?.server&&r.push("server"),r.push("json"),r.join(".")}function G(e,t){yr(Et(e),JSON.stringify(t,void 0,2),"utf-8")}function he(e,t){let r=ie(e,t),s=He(r);if(s)return JSON.parse(s)}function pi(e){let t=He(ie(e,{server:!0}));if(t)return JSON.parse(t)}function He(e){let t=Et(e);return ai(t)?wr(t,"utf8"):""}function di(e){let t=he()??{};t.bots||(t.bots=[]),t.bots.push(e),yr("medplum.config.json",JSON.stringify(t,null,2),"utf8"),console.log(`Bot added to config: ${e.id}`)}function hi(e){return e.replaceAll(/[/\-\\^$*+?.()|[\]{}]/g,"\\$&")}function mi(e){let t=0,r=0;return li({cwd:e,filter:(s,o)=>{if(t++,t>100)throw new Error("Tar extractor reached max number of files");if(r+=o.size,r>10485760)throw new Error("Tar extractor reached max size");return!0}})}function _t(){return{url:"http://hl7.org/fhir/StructureDefinition/data-absent-reason",valueCode:"unsupported"}}function fi(e){let t=ni(e).toLowerCase();return[".cjs",".mjs",".js"].includes(t)?Qe.JAVASCRIPT:[".cts",".mts",".ts"].includes(t)?Qe.TYPESCRIPT:Qe.TEXT}function Ar(e,t){let r=new Ie(e),s={name:e,...t};return r.setObject("options",s),s}function gi(e){return new Ie(e).getObject("options")}async function wi(e,t){let r={typ:"JWT",alg:ar.HS256},s=Math.floor(Date.now()/1e3),o={aud:`${t.baseUrl}${t.audience}`,iss:t.issuer,sub:t.subject,nbf:s,iat:s,exp:s+604800},i=Ot(JSON.stringify(r)),a=Ot(JSON.stringify(o)),c=`${i}.${a}`,n=si("sha256",t.clientSecret).update(c).digest("base64url"),m=`${c}.${n}`;await e.startJwtBearerLogin(t.clientId,m,t.scope??"")}async function yi(e,t){let r=oi(wr(Et(t.privateKeyPath))),s=await new ri({}).setProtectedHeader({typ:"JWT",alg:ar.RS384}).setIssuer(t.clientId).setSubject(t.clientId).setAudience(`${t.baseUrl}${t.audience}`).setJti(ii(16).toString("hex")).setIssuedAt().setExpirationTime("5m").sign(r);await e.startJwtAssertionLogin(s)}function O(e,t){t.configureHelp({showGlobalOptions:!0}),e.addCommand(t)}var P=class extends wo{action(e){let t=Ei(this,e);return super._actionHandler=t,this}resetOptionDefaults(){this._optionValues={};for(let e of this.options)e.defaultValue!==void 0&&(this._optionValues[e.attributeName()]=e.defaultValue)}};function Ei(e,t){return async r=>{let s=e.registeredArguments.length,o=r.slice(0,s);o[s]=e.optsWithGlobals();try{let i=t(...o);ci(i)&&await i}finally{e.resetOptionDefaults()}}}var Ir=new P("status").aliases(["info","list","ls"]),$r=new P("ping"),Rr=new P("push"),Tr=new P("reload-config"),Pr=new P("upgrade"),Or=new P("stats"),ae=new P("agent");O(ae,Ir);O(ae,$r);O(ae,Rr);O(ae,Tr);O(ae,Pr);O(ae,Or);Ir.description("Get the status of a specified agent").argument("[agentIds...]","The ID(s) of the agent(s) to get the status of").option("--criteria <criteria>","An optional FHIR search criteria to resolve the agent to get the status of. Mutually exclusive with [agentIds...] arg").addOption(new Fe("--output <format>","An optional output format, defaults to table").choices(["table","json"]).default("table")).action(async(e,t)=>{await Be({operation:"$bulk-status",agentIds:e,options:t,parseSuccessfulResponse:r=>{let s=Cr(r.result,{required:["status","version"],optional:["lastUpdated"]});return{id:r.agent.id,name:r.agent.name,enabledStatus:r.agent.status,version:s.version,connectionStatus:s.status,statusLastUpdated:s.lastUpdated??"N/A"}}})});$r.description("Ping a host from a specified agent").argument("<ipOrDomain>","The IPv4 address or domain name to ping").argument("[agentId]","Conditionally optional ID of the agent to ping from. Mutually exclusive with --criteria <criteria> option").option("--count <count>","An optional amount of pings to issue before returning results","1").option("--criteria <criteria>","An optional FHIR search criteria to resolve the agent to ping from. Mutually exclusive with [agentId] arg").action(async(e,t,r)=>{let s=await x(r),o=await Nr(s,t,r),i=Number.parseInt(r.count,10);if(Number.isNaN(i))throw new Error("--count <count> must be an integer if specified");try{let a=await s.pushToAgent(o,e,`PING ${i}`,ir.PING,!0,{maxRetries:0});console.info(a)}catch(a){throw new Error("Unexpected response from agent while pinging",{cause:a})}});Rr.description("Push a message to a target device via a specified agent").argument("<deviceId>","The ID of the device to push the message to").argument("<message>","The message to send to the destination device").argument("[agentId]","Conditionally optional ID of the agent to send the message from. Mutually exclusive with --criteria <criteria> option").option("--content-type <contentType>","The content type of the message",ir.HL7_V2).option("--no-wait","Tells the server not to wait for a response from the destination device").option("--criteria <criteria>","An optional FHIR search criteria to resolve the agent to ping from. Mutually exclusive with [agentId] arg").action(async(e,t,r,s)=>{let o=await x(s),i=await Nr(o,r,s),a;try{a=await o.pushToAgent(i,{reference:`Device/${e}`},t,s.contentType,s.wait!==!1,{maxRetries:0})}catch(c){throw new Error("Unexpected response from agent while pushing message to agent",{cause:c})}console.info(a)});Tr.description("Reload the config for the specified agent(s)").argument("[agentIds...]","The ID(s) of the agent(s) for which the config should be reloaded. Mutually exclusive with --criteria <criteria> flag").option("--criteria <criteria>","An optional FHIR search criteria to resolve the agent(s) for which to notify to reload their config. Mutually exclusive with [agentIds...] arg").addOption(new Fe("--output <format>","An optional output format, defaults to table").choices(["table","json"]).default("table")).action(async(e,t)=>{await Be({operation:"$reload-config",agentIds:e,options:t,parseSuccessfulResponse:r=>({id:r.agent.id,name:r.agent.name})})});Pr.description("Upgrade the version for the specified agent(s)").argument("[agentIds...]","The ID(s) of the agent(s) that should be upgraded. Mutually exclusive with --criteria <criteria> flag").option("--criteria <criteria>","An optional FHIR search criteria to resolve the agent(s) to upgrade. Mutually exclusive with [agentIds...] arg").option("--agentVersion <version>","An optional agent version to upgrade to. Defaults to the latest version if flag not included").option("--force","Forces an upgrade when a pending upgrade is in an inconsistent state. Use with caution.").addOption(new Fe("--output <format>","An optional output format, defaults to table").choices(["table","json"]).default("table")).action(async(e,t)=>{let r={};t.agentVersion&&(r.version=t.agentVersion),t.force&&(r.force=!0),await Be({operation:"$upgrade",agentIds:e,options:t,params:r,parseSuccessfulResponse:s=>({id:s.agent.id,name:s.agent.name,version:t.agentVersion??"latest"})})});Or.description("Get runtime statistics for the specified agent(s)").argument("[agentIds...]","The ID(s) of the agent(s) to get stats for. Mutually exclusive with --criteria <criteria> flag").option("--criteria <criteria>","An optional FHIR search criteria to resolve the agent(s) to get stats for. Mutually exclusive with [agentIds...] arg").addOption(new Fe("--output <format>","An optional output format, defaults to table").choices(["table","json"]).default("table")).action(async(e,t)=>{await Be({operation:"$stats",agentIds:e,options:t,parseSuccessfulResponse:r=>{let{stats:s}=Cr(r.result,{required:["stats"]}),o;try{o=JSON.parse(s)}catch(i){console.error(`Failed to parse stats for agent ${r.agent.id}: ${ao(i)}`)}return{id:r.agent.id,name:r.agent.name,stats:o}},renderSuccessfulRows:r=>{for(let s=0;s<r.length;s++)s>0&&console.info(),vi(r[s])}})});var xt=["live","ping","hl7ConnectionsOpen","hl7ClientCount","hl7QueueDepth","webSocketQueueDepth","outstandingHeartbeats"];function jt(e){return e==null?"":typeof e=="object"?JSON.stringify(e):e.toString()}function Ft(e){return e?Object.entries(e).filter(([,t])=>t?.rtt).map(([t,r])=>({name:t,count:r.rtt.count,pending:r.rtt.pendingCount,"min (ms)":r.rtt.min,"avg (ms)":r.rtt.average,"max (ms)":r.rtt.max,"p50 (ms)":r.rtt.p50,"p95 (ms)":r.rtt.p95,"p99 (ms)":r.rtt.p99})):[]}function vi(e){let t=e.name?`${e.name} (${e.id})`:e.id;if(console.info(`Agent: ${t}`),!e.stats){console.info(" (stats unavailable)");return}let r={};for(let a of xt)r[a]=jt(e.stats[a]);let s=new Set([...xt,"channelStats","clientStats"]);for(let[a,c]of Object.entries(e.stats))s.has(a)||(r[a]=jt(c));console.table(r);let o=Ft(e.stats.channelStats);o.length&&(console.info("Channel Stats:"),console.table(o));let i=Ft(e.stats.clientStats);i.length&&(console.info("Client Stats:"),console.table(i))}async function Be({operation:e,agentIds:t,options:r,params:s={},parseSuccessfulResponse:o,renderSuccessfulRows:i}){let a=Ii(t,r),c=await x(r),n=a.type==="criteria"?a.criteria:`Agent?_id=${a.ids.join(",")}`,m=new URLSearchParams(n.split("?")[1]);for(let[h,b]of Object.entries(s))m.append(h,b.toString());let l;try{let h=c.fhirUrl("Agent",e);h.search=m.toString(),l=await c.get(h,{cache:"reload"})}catch(h){throw new Error(`Operation '${e}' failed`,{cause:h})}if(r.output==="json"){console.info(JSON.stringify(l,null,2));return}let u=[],d=[];switch(l.resourceType){case"Bundle":{let h=Si(l);for(let b of h)b.result.resourceType==="Parameters"||oo(b.result)?u.push(b):d.push(b);break}case"Parameters":case"OperationOutcome":{let h=await c.searchOne("Agent",m,{cache:"reload"});if(!h)throw new Error("Agent not found");l.resourceType==="Parameters"?u.push({agent:h,result:l}):d.push({agent:h,result:l});break}default:throw new Error(`Invalid result received for '${e}' operation: ${JSON.stringify(l)}`)}let f=[];for(let h of u){let b=o(h);f.push(b)}let g=[];for(let h of d){let b=h.result.issue?.[0],R={id:h.agent.id,name:h.agent.name,severity:b.severity,code:b.code,details:b.details?.text??"No details to show"};g.push(R)}console.info(`
3
+ ${f.length} successful response(s):
4
+ `),i?f.length?i(f):console.info("No successful responses received"):console.table(f.length?f:"No successful responses received"),console.info(),g.length&&(console.info(`${g.length} failed response(s):`),console.info(),console.table(g))}async function Nr(e,t,r){if(!(t||r.criteria))throw new Error("This command requires either an [agentId] or a --criteria <criteria> flag");if(t&&r.criteria)throw new Error("Ambiguous arguments and options combination; [agentId] arg and --criteria <criteria> flag are mutually exclusive");let s;if(t)s=t;else{Lr(r.criteria);let o=await e.search("Agent",`${r.criteria.split("?")[1]}&_count=2`);if(!o?.entry?.length)throw new Error("Could not find an agent matching the provided criteria");if(o.entry.length!==1)throw new Error("Found more than one agent matching this criteria. This operation requires the criteria to resolve to exactly one agent");s=o.entry[0].resource?.id}return{reference:`Agent/${s}`}}function Si(e){let t=[];for(let r of e.entry??so){if(!r.resource)throw new Error("No Parameter resource found in entry");t.push(bi(r.resource))}return t}function bi(e){let t=e.parameter?.find(s=>s.name==="agent")?.resource;if(!t)throw new Error("Agent bulk operation response missing 'agent'");if(t.resourceType!=="Agent")throw new Error(`Agent bulk operation returned 'agent' with type '${t.resourceType}'`);let r=e.parameter?.find(s=>s.name==="result")?.resource;if(!r)throw new Error("Agent bulk operation response missing result'");if(!(r.resourceType==="Parameters"||r.resourceType==="OperationOutcome"))throw new Error(`Agent bulk operation returned 'result' with type '${r.resourceType}'`);return{agent:t,result:r}}function Cr(e,t){let r={},s=t.required,o=t.optional;for(let i of s){let a=e.parameter?.find(n=>n.name===i);if(!a)throw new Error(`Failed to find parameter '${i}'`);let c;for(let n in a)if(n.startsWith("value")){if(c)throw new Error(`Found multiple values for parameter '${i}'`);c=n}if(!c)throw new Error(`Failed to find a value for parameter '${i}'`);r[i]=a[c]}if(o?.length)for(let i of o){let a=e.parameter?.find(n=>n.name===i);if(!a)continue;let c=Ai(i,a);r[i]=c}return r}function Ai(e,t){let r;for(let s in t)if(s.startsWith("value")){if(r)throw new Error(`Found multiple values for parameter '${e}'`);r=s}if(!r)throw new Error(`Failed to find a value for parameter '${e}'`);return t[r]}function Ii(e,t){if(!Array.isArray(e))throw new Error("Invalid agent IDs array");if(e.length){if(t.criteria)throw new Error("Ambiguous arguments and options combination; [agentIds...] arg and --criteria <criteria> flag are mutually exclusive");for(let r of e)if(!io(r))throw new Error(`Input '${r}' is not a valid agentId`);return{type:"ids",ids:e}}if(t.criteria)return Lr(t.criteria),{type:"criteria",criteria:t.criteria};throw new Error("Either an [agentId...] arg or a --criteria <criteria> flag is required")}function Lr(e){let t="Criteria must be formatted as a string containing the resource type (Agent) followed by a '?' and valid URL search query params, eg. `Agent?name=Test Agent`";if(typeof e!="string")throw new Error(t);let[r,s]=e.split("?");if(r!=="Agent"||!s)throw new Error(t);try{new URLSearchParams(s)}catch(o){throw new Error(t,{cause:o})}if(!s.includes("="))throw new Error(t,{cause:new Error("Query string lacks at least one `=`")})}var kr=Ri,Mr="http://localhost:9615",Dr=new P("login"),Ur=new P("whoami"),_r=new P("token");Dr.action(async e=>{let t=e.profile??"default",r=Ar(t,e),s=await x(e,!1);await Ci(s,r)});Ur.action(async e=>{let t=await x(e);Mi(t)});_r.action(async e=>{let t=await x(e);await t.getProfileAsync();let r=t.getAccessToken();if(!r)throw new Error("Not logged in");console.log(r)});async function Ci(e,t){switch(t?.authType??"authorization-code"){case"authorization-code":await Di(e);break;case"basic":e.setBasicAuth(t.clientId,t.clientSecret);break;case"client-credentials":e.setBasicAuth(t.clientId,t.clientSecret),await e.startClientLogin(t.clientId,t.clientSecret);break;case"jwt-bearer":await wi(e,t);break;case"jwt-assertion":await yi(e,t);break}}async function Li(e){let t=Oi(async(r,s)=>{let o=new URL(r.url,"http://localhost:9615"),i=o.searchParams.get("code");if(r.method==="OPTIONS"){s.writeHead(200,{Allow:"GET, POST","Content-Type":Ne.TEXT}),s.end("OK");return}if(o.pathname==="/"&&i)try{let a=await e.processCode(i,{clientId:kr,redirectUri:Mr});s.writeHead(200,{"Content-Type":Ne.TEXT}),s.end(`Signed in as ${$i(a)}. You may close this window.`)}catch(a){s.writeHead(400,{"Content-Type":Ne.TEXT}),s.end(`Error: ${Ti(a)}`)}finally{t.close(),process.exit(0)}else s.writeHead(404,{"Content-Type":Ne.TEXT}),s.end("Not found")}).listen(9615)}async function ki(e){let t=Ni(),r;switch(t){case"openbsd":case"linux":r=`xdg-open '${e}'`;break;case"darwin":r=`open '${e}'`;break;case"win32":r=`cmd /c start "" "${e}"`;break;default:throw new Error("Unsupported platform: "+t)}return new Promise((s,o)=>{Pi(r,(i,a,c)=>{if(i){o(i);return}if(c){o(new Error("Could not open browser: "+c));return}s()})})}function Mi(e){let t=e.getActiveLogin();t?(console.log(`Server: ${e.getBaseUrl()}`),console.log(`Profile: ${t.profile.display} (${t.profile.reference})`),console.log(`Project: ${t.project.display} (${t.project.reference})`)):console.log("Not logged in")}async function Di(e){await Li(e);let t=new URL(e.getAuthorizeUrl());t.searchParams.set("client_id",kr),t.searchParams.set("redirect_uri",Mr),t.searchParams.set("scope","openid"),t.searchParams.set("response_type","code"),t.searchParams.set("prompt","login"),await ki(t.toString())}var we="\x1B[0m",Ui="\x1B[1m",_i="\x1B[31m",xi="\x1B[32m",ji="\x1B[33m",Fi="\x1B[34m",Se={red:e=>`${_i}${e}${we}`,green:e=>`${xi}${e}${we}`,yellow:e=>`${ji}${e}${we}`,blue:e=>`${Fi}${e}${we}`,bold:e=>`${Ui}${e}${we}`},Wt=e=>e.replaceAll(/\*\*(.*?)\*\*/g,(t,r)=>Se.bold(r)),Wi=Qt(sr(),1),Ge;function jr(){Ge=oa.createInterface({input:process.stdin,output:process.stdout})}function Fr(){Ge.close()}function p(e){Ge.write(e+`
5
5
  `)}function F(e){p(`
6
6
  `+e+`
7
- `)}function V(e,t=""){return new Promise(r=>{He.question(e+(t?" ("+t+")":"")+" ",s=>{r(s||t.toString())})})}async function vt(e,t,r=""){let s=e+" ["+t.map(o=>o===r?"("+o+")":o).join("|")+"]";for(;;){let o=await V(s)||r;if(t.includes(o))return o;p("Please choose one of the following options: "+t.join(", "))}}async function ye(e,t,r){return Number.parseInt(await vt(e,t.map(s=>s.toString()),r.toString()),10)}async function le(e){return(await vt(e,["y","n"])).toLowerCase()==="y"}async function it(e){if(!await le(e))throw p("Exiting..."),new Error("User cancelled")}var ke=new Lr({}),Yi=new _i({region:"us-east-1"}),Pc=new ji({}),St=new Fi({}),Qi="medplum:environment";async function Dr(){let e=[],t=Ui({client:ke},{StackStatusFilter:["CREATE_COMPLETE","CREATE_FAILED","CREATE_IN_PROGRESS","DELETE_FAILED","DELETE_IN_PROGRESS","IMPORT_COMPLETE","IMPORT_IN_PROGRESS","IMPORT_ROLLBACK_COMPLETE","IMPORT_ROLLBACK_FAILED","IMPORT_ROLLBACK_IN_PROGRESS","REVIEW_IN_PROGRESS","ROLLBACK_COMPLETE","ROLLBACK_FAILED","ROLLBACK_IN_PROGRESS","UPDATE_COMPLETE","UPDATE_COMPLETE_CLEANUP_IN_PROGRESS","UPDATE_FAILED","UPDATE_IN_PROGRESS","UPDATE_ROLLBACK_COMPLETE","UPDATE_ROLLBACK_COMPLETE_CLEANUP_IN_PROGRESS","UPDATE_ROLLBACK_FAILED","UPDATE_ROLLBACK_IN_PROGRESS"]});for await(let r of t)for(let s of r.StackSummaries??Ji)e.push(s);return e}async function It(e){let t=await Dr();for(let r of t){let s=r.StackName,o=await Ur(s);if(o?.tag===e)return o}}async function Ur(e){let t={};if(await jt(ke,e,t),await ke.config.region()!=="us-east-1")try{await jt(new Lr({region:"us-east-1"}),e+"-us-east-1",t)}catch{}return t}async function jt(e,t,r){let s=new Di({StackName:t}),o=(await e.send(s))?.Stacks?.[0],i=o?.Tags?.find(c=>c.Key===Qi);if(!i)return;let a=await e.send(new Mi({StackName:t}));if(a.StackResources){e===ke&&(r.stack=o,r.tag=i.Value);for(let c of a.StackResources)Zi(c,r)}}function Zi(e,t){e.ResourceType==="AWS::ECS::Cluster"?t.ecsCluster=e:e.ResourceType==="AWS::ECS::Service"?t.ecsService=e:e.ResourceType==="AWS::S3::Bucket"&&e.LogicalResourceId?.startsWith("FrontEndAppBucket")?t.appBucket=e:e.ResourceType==="AWS::CloudFront::Distribution"&&e.LogicalResourceId?.startsWith("FrontEndAppDistribution")?t.appDistribution=e:e.ResourceType==="AWS::CloudFront::CloudFrontOriginAccessIdentity"&&e.LogicalResourceId?.startsWith("FrontEndOriginAccessIdentity")?t.appOriginAccessIdentity=e:e.ResourceType==="AWS::S3::Bucket"&&e.LogicalResourceId?.startsWith("StorageStorageBucket")?t.storageBucket=e:e.ResourceType==="AWS::CloudFront::Distribution"&&e.LogicalResourceId?.startsWith("StorageStorageDistribution")?t.storageDistribution=e:e.ResourceType==="AWS::CloudFront::CloudFrontOriginAccessIdentity"&&e.LogicalResourceId?.startsWith("StorageOriginAccessIdentity")&&(t.storageOriginAccessIdentity=e)}function _r(e){console.log(`Medplum Tag: ${e.tag}`),console.log(`Stack Name: ${e.stack?.StackName}`),console.log(`Stack ID: ${e.stack?.StackId}`),console.log(`Status: ${e.stack?.StackStatus}`),console.log(`ECS Cluster: ${e.ecsCluster?.PhysicalResourceId}`),console.log(`ECS Service: ${ea(e.ecsService)}`),console.log(`App Bucket: ${e.appBucket?.PhysicalResourceId}`),console.log(`App Distribution: ${e.appDistribution?.PhysicalResourceId}`),console.log(`App OAI: ${e.appOriginAccessIdentity?.PhysicalResourceId}`),console.log(`Storage Bucket: ${e.storageBucket?.PhysicalResourceId}`),console.log(`Storage Distribution: ${e.storageDistribution?.PhysicalResourceId}`),console.log(`Storage OAI: ${e.storageOriginAccessIdentity?.PhysicalResourceId}`)}function ea(e){return e?.PhysicalResourceId?.split("/")?.pop()||""}async function xr(e){let t=await Yi.send(new xi({DistributionId:e,InvalidationBatch:{CallerReference:`invalidate-all-${Date.now()}`,Paths:{Quantity:1,Items:["/*"]}}}));console.log(`Created invalidation with ID: ${t.Invalidation?.Id}`)}async function jr(e){let t=(await(await Xi("https://api.github.com/repos/medplum/medplum/releases?per_page=100",{headers:{Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28"}})).json()).map(r=>r.tag_name.startsWith("v")?r.tag_name.slice(1):r.tag_name);return t.sort((r,s)=>ki.compare(s,r)),e?t.slice(0,t.indexOf(e)):t}async function Fr(e,t,r){let s=new Bi({region:e});for(let[o,i]of Object.entries(r)){let a=t+o,c=i.toString(),n=await ta(s,a);n!==void 0&&n!==c&&(p(`Parameter "${a}" exists with different value.`),await it(`Do you want to overwrite "${a}"?`)),await ra(s,a,c)}}async function ta(e,t){let r=new Wi({Name:t,WithDecryption:!0});try{return(await e.send(r)).Parameter?.Value}catch(s){if(s.name==="ParameterNotFound")return;throw s}}async function ra(e,t,r){let s=new Hi({Name:t,Value:r,Type:"SecureString",Overwrite:!0});await e.send(s)}function Be(e,t){if(console.log(`Config not found: ${e} (${se(e,t)})`),t){let s=Object.entries(t);if(s.length>0){console.log("Additional options:");for(let[o,i]of s)console.log(` ${o}: ${i}`)}}console.log();let r=zi(".",{withFileTypes:!0});if(r=r.filter(s=>s.isFile()&&s.name.startsWith("medplum.")&&s.name.endsWith(".json")).map(s=>s.name),r.length===0)console.log("No configs found");else{console.log("Available configs:");for(let s of r)console.log(` ${s.replaceAll("medplum.","").replaceAll(".config","").replaceAll(".server","").replaceAll(".json","").padEnd(40," ")} (${s})`)}}async function bt(e){console.log(`Stack not found: ${e}`),console.log();try{let t=new Gi,r=new Ki({}),s=await t.send(r),o=await t.config.region();console.log("AWS Region: ",o),console.log("AWS Account ID: ",s.Account),console.log("AWS Account ARN: ",s.Arn),console.log("AWS User ID: ",s.UserId)}catch(t){console.log("Warning: Unable to get AWS account ID",Vi(t))}}async function sa(e){let t=await It(e);if(!t)throw await bt(e),new Error(`Stack not found: ${e}`);_r(t)}var ha=e=>`${e}DomainName`,Hr=e=>`${e}SslCertArn`;async function ma(){let e={apiPort:8103,region:"us-east-1"};kr(),F("MEDPLUM"),p("This tool prepares the necessary prerequisites for deploying Medplum in your AWS account."),p(""),p("Most Medplum infrastructure is deployed using the AWS CDK."),p("However, some AWS resources must be created manually, such as email addresses and SSL certificates."),p("This tool will help you create those resources."),p(""),p("Upon completion, this tool will:"),p(" 1. Generate a Medplum CDK config file (i.e., medplum.demo.config.json)"),p(" 2. Optionally generate an AWS CloudFront signing key"),p(" 3. Optionally request SSL certificates from AWS Certificate Manager"),p(" 4. Optionally write server config settings to AWS Parameter Store"),p(""),p("The Medplum infra config file is an input to the Medplum CDK."),p("The Medplum CDK will create and manage the necessary AWS resources."),p(""),p("We will ask a series of questions to generate your infra config file."),p("Some questions have predefined options in [square brackets]."),p("Some questions have default values in (parentheses), which you can accept by pressing Enter."),p("Press Ctrl+C at any time to exit.");let t=await fa(e.region);t||(p("It appears that you do not have AWS credentials configured."),p("AWS credentials are not strictly required, but will enable some additional features."),p("If you intend to use AWS credentials, please configure them now."),await it("Do you want to continue without AWS credentials?")),F("ENVIRONMENT NAME"),p('Medplum deployments have a short environment name such as "prod", "staging", "alice", or "demo".'),p("The environment name is used in multiple places:"),p(" 1. As part of config file names (i.e., medplum.demo.config.json)"),p(" 2. As the base of CloudFormation stack names (i.e., MedplumDemo)"),p(" 3. AWS Parameter Store keys (i.e., /medplum/demo/...)"),e.name=await V("What is your environment name?","demo"),p('Using environment name "'+e.name+'"...'),F("CONFIG FILE"),p("Medplum Infrastructure will create a config file in the current directory.");let r=await V("What is the config file name?",`medplum.${e.name}.config.json`);da(r)&&(p("Config file already exists."),await it("Do you want to overwrite the config file?")),p('Using config file "'+r+'"...'),K(r,e),F("AWS REGION"),p("Most Medplum resources will be created in a single AWS region."),e.region=await V("Enter your AWS region:","us-east-1"),K(r,e),F("AWS ACCOUNT NUMBER"),p("Medplum Infrastructure will use your AWS account number to create AWS resources."),t&&p("Using the AWS CLI, your current account ID is: "+t),e.accountNumber=await V("What is your AWS account number?",t),K(r,e),F("STACK NAME"),p("Medplum will create a CloudFormation stack to manage AWS resources."),p("AWS CloudFormation stack names ");let s="Medplum"+e.name.charAt(0).toUpperCase()+e.name.slice(1);for(e.stackName=await V("Enter your CloudFormation stack name?",s),K(r,e),F("BASE DOMAIN NAME"),p("Please enter the base domain name for your Medplum deployment."),p(""),p("Medplum deploys multiple subdomains for various services."),p(""),p('For example, "api." for the REST API and "app." for the web application.'),p("The base domain name is the common suffix for all subdomains."),p(""),p('For example, if your base domain name is "example.com",'),p('then the REST API will be "api.example.com".'),p(""),p('The base domain should include the TLD (i.e., ".com", ".org", ".net").'),p(""),p("Note that you must own the base domain, and it must use Route53 DNS.");!e.domainName;)e.domainName=await V("Enter your base domain name:");K(r,e),F("SUPPORT EMAIL"),p("Medplum sends transactional emails to users."),p("For example, emails to new users or for password reset."),p("Medplum will use the support email address to send these emails."),p("Note that you must verify the support email address in SES.");let o=await V("Enter your support email address:");F("API DOMAIN NAME"),p("Medplum deploys a REST API for the backend services."),e.apiDomainName=await V("Enter your REST API domain name:","api."+e.domainName),e.baseUrl=`https://${e.apiDomainName}/`,K(r,e),F("APP DOMAIN NAME"),p("Medplum deploys a web application for the user interface."),e.appDomainName=await V("Enter your web application domain name:","app."+e.domainName),K(r,e),F("STORAGE DOMAIN NAME"),p("Medplum deploys a storage service for file uploads."),e.storageDomainName=await V("Enter your storage domain name:","storage."+e.domainName),K(r,e),F("STORAGE BUCKET"),p("Medplum uses an S3 bucket to store binary content such as file uploads."),p("Medplum will create a the S3 bucket as part of the CloudFormation stack."),e.storageBucketName=await V("Enter your storage bucket name:",e.storageDomainName),K(r,e),F("MAX AVAILABILITY ZONES"),p("Medplum API servers can be deployed in multiple availability zones."),p("This provides redundancy and high availability."),p("However, it also increases the cost of the deployment."),p("If you want to use all availability zones, choose a large number such as 99."),p("If you want to restrict the number, for example to manage EIP limits,"),p("then choose a small number such as 2 or 3."),e.maxAzs=await ye("Enter the maximum number of availability zones:",[2,3,99],2),F("DATABASE INSTANCES"),p("Medplum uses a relational database to store data."),p("Medplum can create a new RDS database as part of the CloudFormation stack,"),p("or can set up your own database and enter the database name, username, and password."),await le("Do you want to create a new RDS database as part of the CloudFormation stack?")?(p("Medplum will create a new RDS database as part of the CloudFormation stack."),p(""),p("If you need high availability, you can choose multiple instances."),p("Use 1 for a single instance, or 2 for a primary and a standby."),e.rdsInstances=await ye("Enter the number of database instances:",[1,2],1)):(p("Medplum will not create a new RDS database."),p("Please create a new RDS database and enter the database name, username, and password."),p('Set the AWS Secrets Manager secret ARN in the config file in the "rdsSecretsArn" setting.'),e.rdsSecretsArn="TODO"),K(r,e),F("SERVER INSTANCES"),p("Medplum uses AWS Fargate to run the API servers."),p("Medplum will create a new Fargate cluster as part of the CloudFormation stack."),p("Fargate will automatically scale the number of servers up and down."),p("If you need high availability, you can choose multiple instances."),e.desiredServerCount=await ye("Enter the number of server instances:",[1,2,3,4,6,8],1),K(r,e),F("SERVER MEMORY"),p("You can choose the amount of memory for each server instance."),p("The default is 512 MB, which is sufficient for getting started."),p("Note that only certain CPU units are compatible with memory units."),p('Consult AWS Fargate "Task Definition Parameters" for more information.'),e.serverMemory=await ye("Enter the server memory (MB):",[512,1024,2048,4096,8192,16384],512),K(r,e),F("SERVER CPU"),p("You can choose the amount of CPU for each server instance."),p("CPU is expressed as an integer using AWS CPU units"),p("The default is 256, which is sufficient for getting started."),p("Note that only certain CPU units are compatible with memory units."),p('Consult AWS Fargate "Task Definition Parameters" for more information.'),e.serverCpu=await ye("Enter the server CPU:",[256,512,1024,2048,4096,8192,16384],256),K(r,e),F("SERVER IMAGE"),p("Medplum uses Docker images for the API servers."),p("You can choose the image to use for the servers."),p("Docker images can be loaded from either Docker Hub or AWS ECR."),p("The default is the latest Medplum release.");let i=(await jr())[0]??"latest";e.serverImage=await V("Enter the server image:",`medplum/medplum-server:${i}`),K(r,e),F("SIGNING KEY"),p("Medplum uses AWS CloudFront Presigned URLs for binary content such as file uploads.");let a=await Ea(e.region,e.stackName+"SigningKey");a?(e.signingKeyId=a.keyId,e.storagePublicKey=a.publicKey,K(r,e)):(p("Unable to generate signing key."),p("Please manually create a signing key and enter the key ID and public key in the config file."),p('You must set the "signingKeyId", "signingKey", and "signingKeyPassphrase" settings.')),F("SSL CERTIFICATES"),p("Medplum will now check for existing SSL certificates for the subdomains.");let c=await ga(e.region);p("Found "+c.length+" certificate(s).");for(let{region:f,certName:l}of[{region:e.region,certName:"api"},{region:"us-east-1",certName:"app"},{region:"us-east-1",certName:"storage"}]){p("");let u=await wa(e,c,f,l);e[Hr(l)]=u,K(r,e)}F("AWS PARAMETER STORE"),p("Medplum uses AWS Parameter Store to store sensitive configuration values."),p("These values will be encrypted at rest."),p(`The values will be stored in the "/medplum/${e.name}" path.`);let n={port:e.apiPort,baseUrl:e.baseUrl,appBaseUrl:`https://${e.appDomainName}/`,storageBaseUrl:`https://${e.storageDomainName}/binary/`,binaryStorage:`s3:${e.storageBucketName}`,supportEmail:o};if(a&&(n.signingKeyId=a.keyId,n.signingKey=a.privateKey,n.signingKeyPassphrase=a.passphrase),p(JSON.stringify({...n,signingKey:"****",signingKeyPassphrase:"****"},null,2)),await le("Do you want to store these values in AWS Parameter Store?"))await Fr(e.region,`/medplum/${e.name}/`,n);else{let f=se(e.name,{server:!0});K(f,n),p("Skipping AWS Parameter Store."),p(`Writing values to local config file: ${f}`),p("Please add these values to AWS Parameter Store manually.")}F("DONE!"),p("Medplum configuration complete."),p("You can now proceed to deploying the Medplum infrastructure with CDK."),p("Run:"),p(""),p(` npx cdk bootstrap -c config=${r}`),p(` npx cdk synth -c config=${r}`),e.region==="us-east-1"?p(` npx cdk deploy -c config=${r}`):p(` npx cdk deploy -c config=${r} --all`),p(""),p("See Medplum documentation for more information:"),p(""),p(" https://www.medplum.com/docs/self-hosting/install-on-aws"),p(""),Mr()}async function fa(e){try{let t=new la({region:e}),r=new ca({});return(await t.send(r)).Account}catch(t){console.log("Warning: Unable to get AWS account ID",t.message);return}}async function ga(e){let t=await Wt(e);if(e!=="us-east-1"){let r=await Wt("us-east-1");t.push(...r)}return t}async function Wt(e){try{let t=new Wr({region:e}),r=new oa({MaxItems:1e3});return(await t.send(r)).CertificateSummaryList}catch(t){return console.log("Warning: Unable to list certificates",t.message),[]}}async function wa(e,t,r,s){let o=e[ha(s)],i=t.find(c=>c.CertificateArn?.includes(r)&&c.DomainName===o);if(i)return p(`Found existing certificate for "${o}" in "${r}.`),i.CertificateArn;if(p(`No existing certificate found for "${o}" in "${r}.`),!await le("Do you want to request a new certificate?"))return p(`Please add your certificate ARN to the config file in the "${Hr(s)}" setting.`),"TODO";let a=await ya(r,o);return p("Certificate ARN: "+a),a}async function ya(e,t){try{let r=await vt("Validate certificate using DNS or email validation?",["dns","email"],"dns"),s=new Wr({region:e}),o=new ia({DomainName:t,ValidationMethod:r.toUpperCase()});return(await s.send(o)).CertificateArn}catch(r){return console.log("Error: Unable to request certificate",r.message),"TODO"}}async function Ea(e,t){let r=Ft(),s=pa("rsa",{modulusLength:2048,publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs1",format:"pem",cipher:"aes-256-cbc",passphrase:r}});try{return{keyId:(await new aa({region:e}).send(new na({PublicKeyConfig:{Name:t,CallerReference:Ft(),EncodedKey:s.publicKey}}))).PublicKey?.Id,publicKey:s.publicKey,privateKey:s.privateKey,passphrase:r}}catch(o){console.log("Error: Unable to create signing key: ",ua(o));return}}async function va(){let e=await Dr();for(let t of e){let r=t.StackName,s=await Ur(r);s&&(_r(s),console.log(""))}}async function La(e,t){let r=de(e,t);if(!r)throw Be(e,t),new Error(`Config not found: ${e}`);let s=await It(e);if(!s)throw await bt(e),new Error(`Stack not found: ${e}`);let o=s.appBucket;if(!o)throw new Error(`App bucket not found for stack ${e}`);let i;if(t.tarPath)i=t.tarPath;else{let a=t?.toVersion??"latest";i=await Ma("@medplum/app",a)}Kr(i,{MEDPLUM_BASE_URL:r.baseUrl,MEDPLUM_CLIENT_ID:r.clientId??"",GOOGLE_CLIENT_ID:r.googleClientId??"",RECAPTCHA_SITE_KEY:r.recaptchaSiteKey??"",MEDPLUM_REGISTER_ENABLED:r.registerEnabled?"true":"false"}),await Ua(i,o.PhysicalResourceId,t),s.appDistribution?.PhysicalResourceId&&!t.dryrun&&await xr(s.appDistribution.PhysicalResourceId),console.log("Done")}async function ka(e,t){let r=`https://registry.npmjs.org/${e}/${t}`;return(await Br(r)).json()}async function Ma(e,t){let r=(await ka(e,t)).dist.tarball,s=Aa(Me(Na(),"tarball-"));try{let o=await Br(r),i=ai(s);return await Ca(o.body,i),Me(s,"package","dist")}catch(o){throw Ta(s,{recursive:!0,force:!0}),o}}function Kr(e,t){for(let r of $a(e,{withFileTypes:!0})){let s=Me(e,r.name);r.isDirectory()?Kr(s,t):r.isFile()&&s.endsWith(".js")&&Da(s,t)}}function Da(e,t){let r=Ra(e,"utf-8");for(let[s,o]of Object.entries(t))r=r.replaceAll(`__${s}__`,o);Pa(e,r)}async function Ua(e,t,r){let s=[["assets/**/*.css",Y.CSS,!0],["assets/**/*.css.map",Y.JSON,!0],["assets/**/*.js",Y.JAVASCRIPT,!0],["assets/**/*.js.map",Y.JSON,!0],["assets/**/*.txt",Y.TEXT,!0],["assets/**/*.ico",Y.FAVICON,!0],["img/**/*.png",Y.PNG,!0],["img/**/*.svg",Y.SVG,!0],["robots.txt",Y.TEXT,!0],["index.html",Y.HTML,!1]];for(let o of s)await _a({rootDir:e,bucketName:t,fileNamePattern:o[0],contentType:o[1],cached:o[2],dryrun:r.dryrun})}async function _a(e){let t=Ia.sync(e.fileNamePattern,{cwd:e.rootDir});for(let r of t)await xa(Me(e.rootDir,r),e)}async function xa(e,t){let r=ba(e),s=e.substring(t.rootDir.length+1).split(Oa).join("/"),o={Bucket:t.bucketName,Key:s,Body:r,ContentType:t.contentType,CacheControl:t.cached?"public, max-age=31536000":"no-cache, no-store, must-revalidate"};console.log(`Uploading ${s} to ${t.bucketName}...`),t.dryrun||await St.send(new Sa(o))}async function Wa(e,t){if(!de(e,t))throw Be(e,t),new Error(`Config not found: ${e}`);let r=await It(e);if(!r)throw await bt(e),new Error(`Stack not found: ${e}`);await Ht("App",r.appBucket,r.appDistribution,r.appOriginAccessIdentity,t),await Ht("Storage",r.storageBucket,r.storageDistribution,r.storageOriginAccessIdentity,t),console.log("Done")}async function Ht(e,t,r,s,o){if(!t?.PhysicalResourceId)throw new Error(`${e} bucket not found`);if(!r?.PhysicalResourceId)throw new Error(`${e} distribution not found`);if(!s?.PhysicalResourceId)throw new Error(`${e} OAI not found`);let i=t.PhysicalResourceId,a=s.PhysicalResourceId,c=await Ha(i);if(Ka(c,i,a))throw new Error(`${e} bucket already has policy statement`);Ga(c,i,a),console.log(`${e} bucket policy:`),console.log(JSON.stringify(c,void 0,2)),o.dryrun?console.log("Dry run - skipping updates"):(console.log("Updating bucket policy..."),await Ba(i,c),console.log("Bucket policy updated"),console.log("Creating CloudFront invalidation..."),await xr(r.PhysicalResourceId),console.log("CloudFront invalidation created"),console.log(`${e} bucket policy updated`))}async function Ha(e){let t=await St.send(new ja({Bucket:e}));return JSON.parse(t.Policy??"{}")}async function Ba(e,t){await St.send(new Fa({Bucket:e,Policy:JSON.stringify(t)}))}function Ka(e,t,r){return!!e?.Statement?.some(s=>s?.Effect==="Allow"&&s?.Principal?.AWS===`arn:aws:iam::cloudfront:user/CloudFront Origin Access Identity ${r}`&&Array.isArray(s?.Action)&&s?.Action?.includes("s3:GetObject*")&&s?.Action?.includes("s3:GetBucket*")&&s?.Action?.includes("s3:List*")&&Array.isArray(s?.Resource)&&s?.Resource?.includes(`arn:aws:s3:::${t}`)&&s?.Resource?.includes(`arn:aws:s3:::${t}/*`))}function Ga(e,t,r){e.Version||(e.Version="2012-10-17"),e.Statement||(e.Statement=[]),e.Statement.push({Effect:"Allow",Principal:{AWS:`arn:aws:iam::cloudfront:user/CloudFront Origin Access Identity ${r}`},Action:["s3:GetObject*","s3:GetBucket*","s3:List*"],Resource:[`arn:aws:s3:::${t}`,`arn:aws:s3:::${t}/*`]})}async function Ja(e,t){try{kr();let r=de(e,t);if(!r)throw Be(e,t),new Error(`Config not found: ${e}`);let s=si(e)??{};if(!t.yes&&Object.keys(s).length===0){let o=se(e,{server:!0});if(console.log(Se.yellow(`Config file ${o} not found!`)),!await le("Do you want to proceed?")){console.log(Se.red(`Run Aborted, please ensure ${o} is present and try again.`));return}}Va(r,s),za(r,s),p("Medplum uses AWS Parameter Store to store sensitive configuration values."),p("These values will be encrypted at rest."),p(`The values will be stored in the "/medplum/${r.name}" path.`),p(JSON.stringify({...s,signingKey:"****",signingKeyPassphrase:"****"},null,2)),t.dryrun?console.log(Se.yellow("Dry run - skipping updates!")):(t.yes||await le("Do you want to store these values in AWS Parameter Store?"))&&await Fr(r.region,`/medplum/${r.name}/`,s)}finally{Mr()}}function Va(e,t){Oe(e.apiPort,t.port,`Infra "apiPort" (${e.apiPort}) does not match server "port" (${t.port})`),Oe(e.baseUrl,t.baseUrl,`Infra "baseUrl" (${e.baseUrl}) does not match server "baseUrl" (${t.baseUrl})`),Oe(e.appDomainName&&`https://${e.appDomainName}/`,t.appBaseUrl,`Infra "appDomainName" (${e.appDomainName}) does not match server "appBaseUrl" (${t.appBaseUrl})`),Oe(e.storageDomainName&&`https://${e.storageDomainName}/binary/`,t.storageBaseUrl,`Infra "storageDomainName" (${e.storageDomainName}) does not match server "storageBaseUrl" (${t.storageBaseUrl})`)}function Oe(e,t,r){if(Xa(e,t))throw new Error(r)}function Xa(e,t){return e!==void 0&&t!==void 0&&e!==t}function za(e,t){e.apiPort&&(t.port=e.apiPort),e.baseUrl&&(t.baseUrl=e.baseUrl),e.appDomainName&&(t.appBaseUrl=`https://${e.appDomainName}/`),e.storageDomainName&&(t.storageBaseUrl=`https://${e.storageDomainName}/binary/`)}var at=Xt(Zt(),1);async function Ya(e,t){let r=await x(t),s=de(e,t);if(!s)throw console.log(`Configuration file ${se(e)} not found`),Be(e,t),new Error(`Config not found: ${e}`);let o=s.serverImage.lastIndexOf(":"),i=s.serverImage.slice(0,o),a=await Qa(r,s),c=await Bt(a);for(;c;){if(t.toVersion&&at.gt(c,t.toVersion)){console.log(`Skipping update to v${c}`);break}console.log(`Performing update to v${c}`),s.serverImage=`${i}:${c}`,Za(e,s),await r.startAsyncRequest("/admin/super/migrate"),c=await Bt(c)}}async function Qa(e,t){let r=t.serverImage.lastIndexOf(":"),s=t.serverImage.slice(r+1);if(s==="latest"){s=(await e.get("/healthcheck")).version;let o=s.indexOf("-");o>-1&&(s=s.slice(0,o))}return s}async function Bt(e,t){let r=await jr(e),s=r[0];return r.filter(o=>o===s||o===t||at.gte(o,at.inc(e,"minor"))).pop()}function Za(e,t){let r=se(e);K(r,t);let s=`npx cdk deploy -c config=${r}${t.region!=="us-east-1"?" --all":""}`;console.log("> "+s);let o=qa(s,{stdio:"inherit"});if(o.status!==0)throw new Error(`Deploy of ${t.serverImage} failed (exit code ${o.status}): ${o.stderr}`);console.log(o.stdout)}function en(){let e=new R("aws").description("Commands to manage AWS resources");return e.command("init").description("Initialize a new Medplum AWS CloudFormation stacks").action(ma),e.command("list").description("List Medplum AWS CloudFormation stacks").action(va),e.command("describe").description("Describe a Medplum AWS CloudFormation stack by tag").argument("<tag>","The Medplum stack tag").action(sa),e.command("update-config").alias("deploy-config").summary("Update the AWS Parameter Store config values.").description(xt(`Update the AWS Parameter Store config values.
7
+ `)}function V(e,t=""){return new Promise(r=>{Ge.question(e+(t?" ("+t+")":"")+" ",s=>{r(s||t.toString())})})}async function vt(e,t,r=""){let s=e+" ["+t.map(o=>o===r?"("+o+")":o).join("|")+"]";for(;;){let o=await V(s)||r;if(t.includes(o))return o;p("Please choose one of the following options: "+t.join(", "))}}async function ye(e,t,r){return Number.parseInt(await vt(e,t.map(s=>s.toString()),r.toString()),10)}async function pe(e){return(await vt(e,["y","n"])).toLowerCase()==="y"}async function nt(e){if(!await pe(e))throw p("Exiting..."),new Error("User cancelled")}var Me=new xr({}),ia=new Ki({region:"us-east-1"}),_c=new Vi({}),St=new Xi({}),aa="medplum:environment";async function Wr(){let e=[],t=Gi({client:Me},{StackStatusFilter:["CREATE_COMPLETE","CREATE_FAILED","CREATE_IN_PROGRESS","DELETE_FAILED","DELETE_IN_PROGRESS","IMPORT_COMPLETE","IMPORT_IN_PROGRESS","IMPORT_ROLLBACK_COMPLETE","IMPORT_ROLLBACK_FAILED","IMPORT_ROLLBACK_IN_PROGRESS","REVIEW_IN_PROGRESS","ROLLBACK_COMPLETE","ROLLBACK_FAILED","ROLLBACK_IN_PROGRESS","UPDATE_COMPLETE","UPDATE_COMPLETE_CLEANUP_IN_PROGRESS","UPDATE_FAILED","UPDATE_IN_PROGRESS","UPDATE_ROLLBACK_COMPLETE","UPDATE_ROLLBACK_COMPLETE_CLEANUP_IN_PROGRESS","UPDATE_ROLLBACK_FAILED","UPDATE_ROLLBACK_IN_PROGRESS"]});for await(let r of t)for(let s of r.StackSummaries??ea)e.push(s);return e}async function bt(e){let t=await Wr();for(let r of t){let s=r.StackName,o=await Hr(s);if(o?.tag===e)return o}}async function Hr(e){let t={};if(await Ht(Me,e,t),await Me.config.region()!=="us-east-1")try{await Ht(new xr({region:"us-east-1"}),e+"-us-east-1",t)}catch{}return t}async function Ht(e,t,r){let s=new Bi({StackName:t}),o=(await e.send(s))?.Stacks?.[0],i=o?.Tags?.find(c=>c.Key===aa);if(!i)return;let a=await e.send(new Hi({StackName:t}));if(a.StackResources){e===Me&&(r.stack=o,r.tag=i.Value);for(let c of a.StackResources)na(c,r)}}function na(e,t){e.ResourceType==="AWS::ECS::Cluster"?t.ecsCluster=e:e.ResourceType==="AWS::ECS::Service"?t.ecsService=e:e.ResourceType==="AWS::S3::Bucket"&&e.LogicalResourceId?.startsWith("FrontEndAppBucket")?t.appBucket=e:e.ResourceType==="AWS::CloudFront::Distribution"&&e.LogicalResourceId?.startsWith("FrontEndAppDistribution")?t.appDistribution=e:e.ResourceType==="AWS::CloudFront::CloudFrontOriginAccessIdentity"&&e.LogicalResourceId?.startsWith("FrontEndOriginAccessIdentity")?t.appOriginAccessIdentity=e:e.ResourceType==="AWS::S3::Bucket"&&e.LogicalResourceId?.startsWith("StorageStorageBucket")?t.storageBucket=e:e.ResourceType==="AWS::CloudFront::Distribution"&&e.LogicalResourceId?.startsWith("StorageStorageDistribution")?t.storageDistribution=e:e.ResourceType==="AWS::CloudFront::CloudFrontOriginAccessIdentity"&&e.LogicalResourceId?.startsWith("StorageOriginAccessIdentity")&&(t.storageOriginAccessIdentity=e)}function Br(e){console.log(`Medplum Tag: ${e.tag}`),console.log(`Stack Name: ${e.stack?.StackName}`),console.log(`Stack ID: ${e.stack?.StackId}`),console.log(`Status: ${e.stack?.StackStatus}`),console.log(`ECS Cluster: ${e.ecsCluster?.PhysicalResourceId}`),console.log(`ECS Service: ${ca(e.ecsService)}`),console.log(`App Bucket: ${e.appBucket?.PhysicalResourceId}`),console.log(`App Distribution: ${e.appDistribution?.PhysicalResourceId}`),console.log(`App OAI: ${e.appOriginAccessIdentity?.PhysicalResourceId}`),console.log(`Storage Bucket: ${e.storageBucket?.PhysicalResourceId}`),console.log(`Storage Distribution: ${e.storageDistribution?.PhysicalResourceId}`),console.log(`Storage OAI: ${e.storageOriginAccessIdentity?.PhysicalResourceId}`)}function ca(e){return e?.PhysicalResourceId?.split("/")?.pop()||""}async function Gr(e){let t=await ia.send(new Ji({DistributionId:e,InvalidationBatch:{CallerReference:`invalidate-all-${Date.now()}`,Paths:{Quantity:1,Items:["/*"]}}}));console.log(`Created invalidation with ID: ${t.Invalidation?.Id}`)}async function Kr(e){let t=(await(await ra("https://api.github.com/repos/medplum/medplum/releases?per_page=100",{headers:{Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28"}})).json()).map(r=>r.tag_name.startsWith("v")?r.tag_name.slice(1):r.tag_name);return t.sort((r,s)=>Wi.compare(s,r)),e?t.slice(0,t.indexOf(e)):t}async function Jr(e,t,r){let s=new Yi({region:e});for(let[o,i]of Object.entries(r)){let a=t+o,c=i.toString(),n=await la(s,a);n!==void 0&&n!==c&&(p(`Parameter "${a}" exists with different value.`),await nt(`Do you want to overwrite "${a}"?`)),await ua(s,a,c)}}async function la(e,t){let r=new zi({Name:t,WithDecryption:!0});try{return(await e.send(r)).Parameter?.Value}catch(s){if(s.name==="ParameterNotFound")return;throw s}}async function ua(e,t,r){let s=new qi({Name:t,Value:r,Type:"SecureString",Overwrite:!0});await e.send(s)}function Ke(e,t){if(console.log(`Config not found: ${e} (${ie(e,t)})`),t){let s=Object.entries(t);if(s.length>0){console.log("Additional options:");for(let[o,i]of s)console.log(` ${o}: ${i}`)}}console.log();let r=sa(".",{withFileTypes:!0});if(r=r.filter(s=>s.isFile()&&s.name.startsWith("medplum.")&&s.name.endsWith(".json")).map(s=>s.name),r.length===0)console.log("No configs found");else{console.log("Available configs:");for(let s of r)console.log(` ${s.replaceAll("medplum.","").replaceAll(".config","").replaceAll(".server","").replaceAll(".json","").padEnd(40," ")} (${s})`)}}async function At(e){console.log(`Stack not found: ${e}`),console.log();try{let t=new Zi,r=new Qi({}),s=await t.send(r),o=await t.config.region();console.log("AWS Region: ",o),console.log("AWS Account ID: ",s.Account),console.log("AWS Account ARN: ",s.Arn),console.log("AWS User ID: ",s.UserId)}catch(t){console.log("Warning: Unable to get AWS account ID",ta(t))}}async function pa(e){let t=await bt(e);if(!t)throw await At(e),new Error(`Stack not found: ${e}`);Br(t)}var Sa=e=>`${e}DomainName`,Xr=e=>`${e}SslCertArn`;async function ba(){let e={apiPort:8103,region:"us-east-1"};jr(),F("MEDPLUM"),p("This tool prepares the necessary prerequisites for deploying Medplum in your AWS account."),p(""),p("Most Medplum infrastructure is deployed using the AWS CDK."),p("However, some AWS resources must be created manually, such as email addresses and SSL certificates."),p("This tool will help you create those resources."),p(""),p("Upon completion, this tool will:"),p(" 1. Generate a Medplum CDK config file (i.e., medplum.demo.config.json)"),p(" 2. Optionally generate an AWS CloudFront signing key"),p(" 3. Optionally request SSL certificates from AWS Certificate Manager"),p(" 4. Optionally write server config settings to AWS Parameter Store"),p(""),p("The Medplum infra config file is an input to the Medplum CDK."),p("The Medplum CDK will create and manage the necessary AWS resources."),p(""),p("We will ask a series of questions to generate your infra config file."),p("Some questions have predefined options in [square brackets]."),p("Some questions have default values in (parentheses), which you can accept by pressing Enter."),p("Press Ctrl+C at any time to exit.");let t=await Aa(e.region);t||(p("It appears that you do not have AWS credentials configured."),p("AWS credentials are not strictly required, but will enable some additional features."),p("If you intend to use AWS credentials, please configure them now."),await nt("Do you want to continue without AWS credentials?")),F("ENVIRONMENT NAME"),p('Medplum deployments have a short environment name such as "prod", "staging", "alice", or "demo".'),p("The environment name is used in multiple places:"),p(" 1. As part of config file names (i.e., medplum.demo.config.json)"),p(" 2. As the base of CloudFormation stack names (i.e., MedplumDemo)"),p(" 3. AWS Parameter Store keys (i.e., /medplum/demo/...)"),e.name=await V("What is your environment name?","demo"),p('Using environment name "'+e.name+'"...'),F("CONFIG FILE"),p("Medplum Infrastructure will create a config file in the current directory.");let r=await V("What is the config file name?",`medplum.${e.name}.config.json`);va(r)&&(p("Config file already exists."),await nt("Do you want to overwrite the config file?")),p('Using config file "'+r+'"...'),G(r,e),F("AWS REGION"),p("Most Medplum resources will be created in a single AWS region."),e.region=await V("Enter your AWS region:","us-east-1"),G(r,e),F("AWS ACCOUNT NUMBER"),p("Medplum Infrastructure will use your AWS account number to create AWS resources."),t&&p("Using the AWS CLI, your current account ID is: "+t),e.accountNumber=await V("What is your AWS account number?",t),G(r,e),F("STACK NAME"),p("Medplum will create a CloudFormation stack to manage AWS resources."),p("AWS CloudFormation stack names ");let s="Medplum"+e.name.charAt(0).toUpperCase()+e.name.slice(1);for(e.stackName=await V("Enter your CloudFormation stack name?",s),G(r,e),F("BASE DOMAIN NAME"),p("Please enter the base domain name for your Medplum deployment."),p(""),p("Medplum deploys multiple subdomains for various services."),p(""),p('For example, "api." for the REST API and "app." for the web application.'),p("The base domain name is the common suffix for all subdomains."),p(""),p('For example, if your base domain name is "example.com",'),p('then the REST API will be "api.example.com".'),p(""),p('The base domain should include the TLD (i.e., ".com", ".org", ".net").'),p(""),p("Note that you must own the base domain, and it must use Route53 DNS.");!e.domainName;)e.domainName=await V("Enter your base domain name:");G(r,e),F("SUPPORT EMAIL"),p("Medplum sends transactional emails to users."),p("For example, emails to new users or for password reset."),p("Medplum will use the support email address to send these emails."),p("Note that you must verify the support email address in SES.");let o=await V("Enter your support email address:");F("API DOMAIN NAME"),p("Medplum deploys a REST API for the backend services."),e.apiDomainName=await V("Enter your REST API domain name:","api."+e.domainName),e.baseUrl=`https://${e.apiDomainName}/`,G(r,e),F("APP DOMAIN NAME"),p("Medplum deploys a web application for the user interface."),e.appDomainName=await V("Enter your web application domain name:","app."+e.domainName),G(r,e),F("STORAGE DOMAIN NAME"),p("Medplum deploys a storage service for file uploads."),e.storageDomainName=await V("Enter your storage domain name:","storage."+e.domainName),G(r,e),F("STORAGE BUCKET"),p("Medplum uses an S3 bucket to store binary content such as file uploads."),p("Medplum will create a the S3 bucket as part of the CloudFormation stack."),e.storageBucketName=await V("Enter your storage bucket name:",e.storageDomainName),G(r,e),F("MAX AVAILABILITY ZONES"),p("Medplum API servers can be deployed in multiple availability zones."),p("This provides redundancy and high availability."),p("However, it also increases the cost of the deployment."),p("If you want to use all availability zones, choose a large number such as 99."),p("If you want to restrict the number, for example to manage EIP limits,"),p("then choose a small number such as 2 or 3."),e.maxAzs=await ye("Enter the maximum number of availability zones:",[2,3,99],2),F("DATABASE INSTANCES"),p("Medplum uses a relational database to store data."),p("Medplum can create a new RDS database as part of the CloudFormation stack,"),p("or can set up your own database and enter the database name, username, and password."),await pe("Do you want to create a new RDS database as part of the CloudFormation stack?")?(p("Medplum will create a new RDS database as part of the CloudFormation stack."),p(""),p("If you need high availability, you can choose multiple instances."),p("Use 1 for a single instance, or 2 for a primary and a standby."),e.rdsInstances=await ye("Enter the number of database instances:",[1,2],1)):(p("Medplum will not create a new RDS database."),p("Please create a new RDS database and enter the database name, username, and password."),p('Set the AWS Secrets Manager secret ARN in the config file in the "rdsSecretsArn" setting.'),e.rdsSecretsArn="TODO"),G(r,e),F("SERVER INSTANCES"),p("Medplum uses AWS Fargate to run the API servers."),p("Medplum will create a new Fargate cluster as part of the CloudFormation stack."),p("Fargate will automatically scale the number of servers up and down."),p("If you need high availability, you can choose multiple instances."),e.desiredServerCount=await ye("Enter the number of server instances:",[1,2,3,4,6,8],1),G(r,e),F("SERVER MEMORY"),p("You can choose the amount of memory for each server instance."),p("The default is 512 MB, which is sufficient for getting started."),p("Note that only certain CPU units are compatible with memory units."),p('Consult AWS Fargate "Task Definition Parameters" for more information.'),e.serverMemory=await ye("Enter the server memory (MB):",[512,1024,2048,4096,8192,16384],512),G(r,e),F("SERVER CPU"),p("You can choose the amount of CPU for each server instance."),p("CPU is expressed as an integer using AWS CPU units"),p("The default is 256, which is sufficient for getting started."),p("Note that only certain CPU units are compatible with memory units."),p('Consult AWS Fargate "Task Definition Parameters" for more information.'),e.serverCpu=await ye("Enter the server CPU:",[256,512,1024,2048,4096,8192,16384],256),G(r,e),F("SERVER IMAGE"),p("Medplum uses Docker images for the API servers."),p("You can choose the image to use for the servers."),p("Docker images can be loaded from either Docker Hub or AWS ECR."),p("The default is the latest Medplum release.");let i=(await Kr())[0]??"latest";e.serverImage=await V("Enter the server image:",`medplum/medplum-server:${i}`),G(r,e),F("SIGNING KEY"),p("Medplum uses AWS CloudFront Presigned URLs for binary content such as file uploads.");let a=await Ta(e.region,e.stackName+"SigningKey");a?(e.signingKeyId=a.keyId,e.storagePublicKey=a.publicKey,G(r,e)):(p("Unable to generate signing key."),p("Please manually create a signing key and enter the key ID and public key in the config file."),p('You must set the "signingKeyId", "signingKey", and "signingKeyPassphrase" settings.')),F("SSL CERTIFICATES"),p("Medplum will now check for existing SSL certificates for the subdomains.");let c=await Ia(e.region);p("Found "+c.length+" certificate(s).");for(let{region:m,certName:l}of[{region:e.region,certName:"api"},{region:"us-east-1",certName:"app"},{region:"us-east-1",certName:"storage"}]){p("");let u=await $a(e,c,m,l);e[Xr(l)]=u,G(r,e)}F("AWS PARAMETER STORE"),p("Medplum uses AWS Parameter Store to store sensitive configuration values."),p("These values will be encrypted at rest."),p(`The values will be stored in the "/medplum/${e.name}" path.`);let n={port:e.apiPort,baseUrl:e.baseUrl,appBaseUrl:`https://${e.appDomainName}/`,storageBaseUrl:`https://${e.storageDomainName}/binary/`,binaryStorage:`s3:${e.storageBucketName}`,supportEmail:o};if(a&&(n.signingKeyId=a.keyId,n.signingKey=a.privateKey,n.signingKeyPassphrase=a.passphrase),p(JSON.stringify({...n,signingKey:"****",signingKeyPassphrase:"****"},null,2)),await pe("Do you want to store these values in AWS Parameter Store?"))await Jr(e.region,`/medplum/${e.name}/`,n);else{let m=ie(e.name,{server:!0});G(m,n),p("Skipping AWS Parameter Store."),p(`Writing values to local config file: ${m}`),p("Please add these values to AWS Parameter Store manually.")}F("DONE!"),p("Medplum configuration complete."),p("You can now proceed to deploying the Medplum infrastructure with CDK."),p("Run:"),p(""),p(` npx cdk bootstrap -c config=${r}`),p(` npx cdk synth -c config=${r}`),e.region==="us-east-1"?p(` npx cdk deploy -c config=${r}`):p(` npx cdk deploy -c config=${r} --all`),p(""),p("See Medplum documentation for more information:"),p(""),p(" https://www.medplum.com/docs/self-hosting/install-on-aws"),p(""),Fr()}async function Aa(e){try{let t=new wa({region:e}),r=new ga({});return(await t.send(r)).Account}catch(t){console.log("Warning: Unable to get AWS account ID",t.message);return}}async function Ia(e){let t=await Gt(e);if(e!=="us-east-1"){let r=await Gt("us-east-1");t.push(...r)}return t}async function Gt(e){try{let t=new Vr({region:e}),r=new da({MaxItems:1e3});return(await t.send(r)).CertificateSummaryList}catch(t){return console.log("Warning: Unable to list certificates",t.message),[]}}async function $a(e,t,r,s){let o=e[Sa(s)],i=t.find(c=>c.CertificateArn?.includes(r)&&c.DomainName===o);if(i)return p(`Found existing certificate for "${o}" in "${r}.`),i.CertificateArn;if(p(`No existing certificate found for "${o}" in "${r}.`),!await pe("Do you want to request a new certificate?"))return p(`Please add your certificate ARN to the config file in the "${Xr(s)}" setting.`),"TODO";let a=await Ra(r,o);return p("Certificate ARN: "+a),a}async function Ra(e,t){try{let r=await vt("Validate certificate using DNS or email validation?",["dns","email"],"dns"),s=new Vr({region:e}),o=new ha({DomainName:t,ValidationMethod:r.toUpperCase()});return(await s.send(o)).CertificateArn}catch(r){return console.log("Error: Unable to request certificate",r.message),"TODO"}}async function Ta(e,t){let r=Bt(),s=Ea("rsa",{modulusLength:2048,publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs1",format:"pem",cipher:"aes-256-cbc",passphrase:r}});try{return{keyId:(await new ma({region:e}).send(new fa({PublicKeyConfig:{Name:t,CallerReference:Bt(),EncodedKey:s.publicKey}}))).PublicKey?.Id,publicKey:s.publicKey,privateKey:s.privateKey,passphrase:r}}catch(o){console.log("Error: Unable to create signing key: ",ya(o));return}}async function Pa(){let e=await Wr();for(let t of e){let r=t.StackName,s=await Hr(r);s&&(Br(s),console.log(""))}}async function Fa(e,t){let r=he(e,t);if(!r)throw Ke(e,t),new Error(`Config not found: ${e}`);let s=await bt(e);if(!s)throw await At(e),new Error(`Stack not found: ${e}`);let o=s.appBucket;if(!o)throw new Error(`App bucket not found for stack ${e}`);let i;if(t.tarPath)i=t.tarPath;else{let a=t?.toVersion??"latest";i=await Ha("@medplum/app",a)}qr(i,{MEDPLUM_BASE_URL:r.baseUrl,MEDPLUM_CLIENT_ID:r.clientId??"",GOOGLE_CLIENT_ID:r.googleClientId??"",RECAPTCHA_SITE_KEY:r.recaptchaSiteKey??"",MEDPLUM_REGISTER_ENABLED:r.registerEnabled?"true":"false"}),await Ga(i,o.PhysicalResourceId,t),s.appDistribution?.PhysicalResourceId&&!t.dryrun&&await Gr(s.appDistribution.PhysicalResourceId),console.log("Done")}async function Wa(e,t){let r=`https://registry.npmjs.org/${e}/${t}`;return(await zr(r)).json()}async function Ha(e,t){let r=(await Wa(e,t)).dist.tarball,s=La(De(_a(),"tarball-"));try{let o=await zr(r),i=mi(s);return await ja(o.body,i),De(s,"package","dist")}catch(o){throw Da(s,{recursive:!0,force:!0}),o}}function qr(e,t){for(let r of ka(e,{withFileTypes:!0})){let s=De(e,r.name);r.isDirectory()?qr(s,t):r.isFile()&&s.endsWith(".js")&&Ba(s,t)}}function Ba(e,t){let r=Ma(e,"utf-8");for(let[s,o]of Object.entries(t))r=r.replaceAll(`__${s}__`,o);Ua(e,r)}async function Ga(e,t,r){let s=[["assets/**/*.css",Y.CSS,!0],["assets/**/*.css.map",Y.JSON,!0],["assets/**/*.js",Y.JAVASCRIPT,!0],["assets/**/*.js.map",Y.JSON,!0],["assets/**/*.txt",Y.TEXT,!0],["assets/**/*.ico",Y.FAVICON,!0],["img/**/*.png",Y.PNG,!0],["img/**/*.svg",Y.SVG,!0],["robots.txt",Y.TEXT,!0],["index.html",Y.HTML,!1]];for(let o of s)await Ka({rootDir:e,bucketName:t,fileNamePattern:o[0],contentType:o[1],cached:o[2],dryrun:r.dryrun})}async function Ka(e){let t=Na.sync(e.fileNamePattern,{cwd:e.rootDir});for(let r of t)await Ja(De(e.rootDir,r),e)}async function Ja(e,t){let r=Ca(e),s=e.substring(t.rootDir.length+1).split(xa).join("/"),o={Bucket:t.bucketName,Key:s,Body:r,ContentType:t.contentType,CacheControl:t.cached?"public, max-age=31536000":"no-cache, no-store, must-revalidate"};console.log(`Uploading ${s} to ${t.bucketName}...`),t.dryrun||await St.send(new Oa(o))}async function za(e,t){if(!he(e,t))throw Ke(e,t),new Error(`Config not found: ${e}`);let r=await bt(e);if(!r)throw await At(e),new Error(`Stack not found: ${e}`);try{await Kt("App",r.appBucket,r.appDistribution,r.appOriginAccessIdentity,t)}catch(s){console.error(`Error updating App bucket policy: ${s.message}`)}try{await Kt("Storage",r.storageBucket,r.storageDistribution,r.storageOriginAccessIdentity,t)}catch(s){console.error(`Error updating Storage bucket policy: ${s.message}`)}console.log("Done")}async function Kt(e,t,r,s,o){if(!t?.PhysicalResourceId)throw new Error(`${e} bucket not found`);if(!r?.PhysicalResourceId)throw new Error(`${e} distribution not found`);if(!s?.PhysicalResourceId)throw new Error(`${e} OAI not found`);let i=t.PhysicalResourceId,a=s.PhysicalResourceId,c=await qa(i);if(Qa(c,i,a))throw new Error(`${e} bucket already has policy statement`);Za(c,i,a),e==="Storage"&&o.guarddutyMalwareProtection&&en(c,i,a),console.log(`${e} bucket policy:`),console.log(JSON.stringify(c,void 0,2)),o.dryrun?console.log("Dry run - skipping updates"):(console.log("Updating bucket policy..."),await Ya(i,c),console.log("Bucket policy updated"),console.log("Creating CloudFront invalidation..."),await Gr(r.PhysicalResourceId),console.log("CloudFront invalidation created"),console.log(`${e} bucket policy updated`))}async function qa(e){let t=await St.send(new Va({Bucket:e}));return JSON.parse(t.Policy??"{}")}async function Ya(e,t){await St.send(new Xa({Bucket:e,Policy:JSON.stringify(t)}))}function Qa(e,t,r){return!!e?.Statement?.some(s=>s?.Effect==="Allow"&&s?.Principal?.AWS===`arn:aws:iam::cloudfront:user/CloudFront Origin Access Identity ${r}`&&Array.isArray(s?.Action)&&s?.Action?.includes("s3:GetObject*")&&s?.Action?.includes("s3:GetBucket*")&&s?.Action?.includes("s3:List*")&&Array.isArray(s?.Resource)&&s?.Resource?.includes(`arn:aws:s3:::${t}`)&&s?.Resource?.includes(`arn:aws:s3:::${t}/*`))}function Za(e,t,r){e.Version||(e.Version="2012-10-17"),e.Statement||(e.Statement=[]),e.Statement.push({Effect:"Allow",Principal:{AWS:`arn:aws:iam::cloudfront:user/CloudFront Origin Access Identity ${r}`},Action:["s3:GetObject*","s3:GetBucket*","s3:List*"],Resource:[`arn:aws:s3:::${t}`,`arn:aws:s3:::${t}/*`]})}function en(e,t,r){e.Statement?.some(s=>s?.Effect==="Deny"&&s?.Principal?.AWS===`arn:aws:iam::cloudfront:user/CloudFront Origin Access Identity ${r}`&&Jt(s,"s3:GetObject")&&Jt(s,"s3:GetObjectVersion")&&s?.Condition?.StringNotEquals?.["s3:ExistingObjectTag/GuardDutyMalwareScanStatus"]==="NO_THREATS_FOUND")||e.Statement?.push({Sid:"GuardDutyMalwareProtectionReadGate",Effect:"Deny",Principal:{AWS:`arn:aws:iam::cloudfront:user/CloudFront Origin Access Identity ${r}`},Action:["s3:GetObject","s3:GetObjectVersion"],Resource:`arn:aws:s3:::${t}/*`,Condition:{StringNotEquals:{"s3:ExistingObjectTag/GuardDutyMalwareScanStatus":"NO_THREATS_FOUND"}}})}function Jt(e,t){return e.Action===t?!0:Array.isArray(e.Action)&&e.Action.includes(t)}async function tn(e,t){try{jr();let r=he(e,t);if(!r)throw Ke(e,t),new Error(`Config not found: ${e}`);let s=pi(e)??{};if(!t.yes&&Object.keys(s).length===0){let o=ie(e,{server:!0});if(console.log(Se.yellow(`Config file ${o} not found!`)),!await pe("Do you want to proceed?")){console.log(Se.red(`Run Aborted, please ensure ${o} is present and try again.`));return}}rn(r,s),on(r,s),p("Medplum uses AWS Parameter Store to store sensitive configuration values."),p("These values will be encrypted at rest."),p(`The values will be stored in the "/medplum/${r.name}" path.`),p(JSON.stringify({...s,signingKey:"****",signingKeyPassphrase:"****"},null,2)),t.dryrun?console.log(Se.yellow("Dry run - skipping updates!")):(t.yes||await pe("Do you want to store these values in AWS Parameter Store?"))&&await Jr(r.region,`/medplum/${r.name}/`,s)}finally{Fr()}}function rn(e,t){Ce(e.apiPort,t.port,`Infra "apiPort" (${e.apiPort}) does not match server "port" (${t.port})`),Ce(e.baseUrl,t.baseUrl,`Infra "baseUrl" (${e.baseUrl}) does not match server "baseUrl" (${t.baseUrl})`),Ce(e.appDomainName&&`https://${e.appDomainName}/`,t.appBaseUrl,`Infra "appDomainName" (${e.appDomainName}) does not match server "appBaseUrl" (${t.appBaseUrl})`),Ce(e.storageDomainName&&`https://${e.storageDomainName}/binary/`,t.storageBaseUrl,`Infra "storageDomainName" (${e.storageDomainName}) does not match server "storageBaseUrl" (${t.storageBaseUrl})`)}function Ce(e,t,r){if(sn(e,t))throw new Error(r)}function sn(e,t){return e!==void 0&&t!==void 0&&e!==t}function on(e,t){e.apiPort&&(t.port=e.apiPort),e.baseUrl&&(t.baseUrl=e.baseUrl),e.appDomainName&&(t.appBaseUrl=`https://${e.appDomainName}/`),e.storageDomainName&&(t.storageBaseUrl=`https://${e.storageDomainName}/binary/`)}var ct=Qt(sr(),1);async function nn(e,t){let r=await x(t),s=he(e,t);if(!s)throw console.log(`Configuration file ${ie(e)} not found`),Ke(e,t),new Error(`Config not found: ${e}`);let o=s.serverImage.lastIndexOf(":"),i=s.serverImage.slice(0,o),a=await cn(r,s),c=await Vt(a);for(;c;){if(t.toVersion&&ct.gt(c,t.toVersion)){console.log(`Skipping update to v${c}`);break}console.log(`Performing update to v${c}`),s.serverImage=`${i}:${c}`,ln(e,s),await r.startAsyncRequest("/admin/super/migrate"),c=await Vt(c)}}async function cn(e,t){let r=t.serverImage.lastIndexOf(":"),s=t.serverImage.slice(r+1);if(s==="latest"){s=(await e.get("/healthcheck")).version;let o=s.indexOf("-");o>-1&&(s=s.slice(0,o))}return s}async function Vt(e,t){let r=await Kr(e),s=r[0];return r.filter(o=>o===s||o===t||ct.gte(o,ct.inc(e,"minor"))).pop()}function ln(e,t){let r=ie(e);G(r,t);let s=`npx cdk deploy -c config=${r}${t.region!=="us-east-1"?" --all":""}`;console.log("> "+s);let o=an(s,{stdio:"inherit"});if(o.status!==0)throw new Error(`Deploy of ${t.serverImage} failed (exit code ${o.status}): ${o.stderr}`);console.log(o.stdout)}function un(){let e=new P("aws").description("Commands to manage AWS resources");return e.command("init").description("Initialize a new Medplum AWS CloudFormation stacks").action(ba),e.command("list").description("List Medplum AWS CloudFormation stacks").action(Pa),e.command("describe").description("Describe a Medplum AWS CloudFormation stack by tag").argument("<tag>","The Medplum stack tag").action(pa),e.command("update-config").alias("deploy-config").summary("Update the AWS Parameter Store config values.").description(Wt(`Update the AWS Parameter Store config values.
8
8
 
9
9
  Configuration values come from a file named **medplum.<tag>.config.server.json** where **<tag>** is the Medplum stack tag.
10
10
 
11
- `+Se.yellow("**Services must be restarted to apply changes.**"))).argument("<tag>","The Medplum stack tag").option("--file [file]",xt("File to provide overrides for **apiPort**, **baseUrl**, **appDomainName** and **storageDomainName** values that appear in the config file.")).option("--dryrun","Displays the operations that would be performed using the specified command without actually running them.").option("--yes","Automatically confirm the update").action(Ja),P(e,new R("update-server").alias("deploy-server").description("Update the server image").argument("<tag>","The Medplum stack tag").option("--file [file]","Specifies the config file to use. If not specified, the file is based on the tag.").option("--to-version [version]","Specifies the version of the configuration to update. If not specified, the latest version is updated.").action(Ya)),e.command("update-app").alias("deploy-app").description("Update the app site").argument("<tag>","The Medplum stack tag").option("--file [file]","Specifies the config file to use. If not specified, the file is based on the tag.").option("--to-version [version]","Specifies the version of the configuration to update. If not specified, the latest version is updated.").option("--dryrun","Displays the operations that would be performed using the specified command without actually running them.").option("--tar-path [tarPath]","Specifies the path to the extracted tarball of the @medplum/app package.").action(La),e.command("update-bucket-policies").description("Update S3 bucket policies").argument("<tag>","The Medplum stack tag").option("--file [file]","Specifies the config file to use. If not specified, the file is based on the tag.").option("--dryrun","Displays the operations that would be performed using the specified command without actually running them.").action(Wa),e}var Gr=new R("save"),Jr=new R("deploy"),Vr=new R("create"),Ke=new R("bot");P(Ke,Gr);P(Ke,Jr);P(Ke,Vr);var Xr=new R("save-bot"),zr=new R("deploy-bot"),qr=new R("create-bot");Gr.description("Saving the bot").argument("<botName>").action(async(e,t)=>{let r=await x(t);await Ge(r,e)});Jr.description("Deploy the app to AWS").argument("<botName>").action(async(e,t)=>{let r=await x(t);await Ge(r,e,!0)});Vr.arguments("<botName> <projectId> <sourceFile> <distFile>").description("Creating a bot").option("--runtime-version <runtimeVersion>","Runtime version (awslambda, vmcontext)").option("--no-write-config","Do not write bot to config").action(async(e,t,r,s,o)=>{let i=await x(o);await yr(i,e,t,r,s,o.runtimeVersion,!!o.writeConfig)});async function Ge(e,t,r=!1){let s=ri(t),o=[],i=[],a=0,c=0;for(let n of s)try{let f=await e.readResource("Bot",n.id);await gr(e,n,f),a++,r&&(await wr(e,n,f),c++)}catch(f){o.push(f),i.push(`${n.name} [${n.id}]`)}if(console.log(`Number of bots saved: ${a}`),console.log(`Number of bots deployed: ${c}`),console.log(`Number of errors: ${o.length}`),o.length)throw new Error(`${o.length} bot(s) had failures. Bots with failures:
11
+ `+Se.yellow("**Services must be restarted to apply changes.**"))).argument("<tag>","The Medplum stack tag").option("--file [file]",Wt("File to provide overrides for **apiPort**, **baseUrl**, **appDomainName** and **storageDomainName** values that appear in the config file.")).option("--dryrun","Displays the operations that would be performed using the specified command without actually running them.").option("--yes","Automatically confirm the update").action(tn),O(e,new P("update-server").alias("deploy-server").description("Update the server image").argument("<tag>","The Medplum stack tag").option("--file [file]","Specifies the config file to use. If not specified, the file is based on the tag.").option("--to-version [version]","Specifies the version of the configuration to update. If not specified, the latest version is updated.").action(nn)),e.command("update-app").alias("deploy-app").description("Update the app site").argument("<tag>","The Medplum stack tag").option("--file [file]","Specifies the config file to use. If not specified, the file is based on the tag.").option("--to-version [version]","Specifies the version of the configuration to update. If not specified, the latest version is updated.").option("--dryrun","Displays the operations that would be performed using the specified command without actually running them.").option("--tar-path [tarPath]","Specifies the path to the extracted tarball of the @medplum/app package.").action(Fa),e.command("update-bucket-policies").description("Update S3 bucket policies").argument("<tag>","The Medplum stack tag").option("--file [file]","Specifies the config file to use. If not specified, the file is based on the tag.").option("--guardduty-malware-protection","Adds the GuardDuty Malware Protection for S3 read-gating deny to the storage bucket policy.").option("--dryrun","Displays the operations that would be performed using the specified command without actually running them.").action(za),e}var Yr=new P("save"),Qr=new P("deploy"),Zr=new P("create"),Je=new P("bot");O(Je,Yr);O(Je,Qr);O(Je,Zr);var es=new P("save-bot"),ts=new P("deploy-bot"),rs=new P("create-bot");Yr.description("Saving the bot").argument("<botName>").action(async(e,t)=>{let r=await x(t);await Ve(r,e)});Qr.description("Deploy the app to AWS").argument("<botName>").action(async(e,t)=>{let r=await x(t);await Ve(r,e,!0)});Zr.arguments("<botName> <projectId> <sourceFile> <distFile>").description("Creating a bot").option("--runtime-version <runtimeVersion>","Runtime version (awslambda, vmcontext)").option("--no-write-config","Do not write bot to config").action(async(e,t,r,s,o)=>{let i=await x(o);await br(i,e,t,r,s,o.runtimeVersion,!!o.writeConfig)});async function Ve(e,t,r=!1){let s=ui(t),o=[],i=[],a=0,c=0;for(let n of s)try{let m=await e.readResource("Bot",n.id);await vr(e,n,m),a++,r&&(await Sr(e,n,m),c++)}catch(m){o.push(m),i.push(`${n.name} [${n.id}]`)}if(console.log(`Number of bots saved: ${a}`),console.log(`Number of bots deployed: ${c}`),console.log(`Number of errors: ${o.length}`),o.length)throw new Error(`${o.length} bot(s) had failures. Bots with failures:
12
12
 
13
13
  ${i.join(`
14
- `)}`,{cause:o})}Xr.description("Saves the bot").argument("<botName>").action(async(e,t)=>{let r=await x(t);await Ge(r,e)});zr.description("Deploy the bot to AWS").argument("<botName>").action(async(e,t)=>{let r=await x(t);await Ge(r,e,!0)});qr.arguments("<botName> <projectId> <sourceFile> <distFile>").description("Creates and saves the bot").action(async(e,t,r,s,o)=>{let i=await x(o);await yr(i,e,t,r,s)});var Zr=new R("export"),es=new R("import"),At=new R("bulk");P(At,Zr);P(At,es);Zr.option("-e, --export-level <exportLevel>",'Optional export level. Defaults to system level export. "Group/:id" - Group of Patients, "Patient" - All Patients.').option("-t, --types <types>","optional resource types to export").option("-s, --since <since>","optional Resources will be included in the response if their state has changed after the supplied time (e.g. if Resource.meta.lastUpdated is later than the supplied _since time).").option("-d, --target-directory <targetDirectory>","optional target directory to save files from the bulk export operations.").action(async e=>{let{exportLevel:t,types:r,since:s,targetDirectory:o}=e,i=await x(e),a=await i.bulkExport(t,r,s,{pollStatusOnAccepted:!0});for(let{type:c,url:n}of a.output??Yr){let f=new URL(n),l=`${c}_${f.pathname}`.replaceAll(/[^a-zA-Z0-9]+/g,"_")+".ndjson",u=Qr(o??"",l),d=await i.downloadResponse(n);if(!d.ok)throw new Error(`Download failed: ${d.status} ${d.statusText}`);if(!d.body)throw new Error("Download response missing body");let m=on.fromWeb(d.body);await an(m,rn(u)),console.log(`${u} is created`)}});es.argument("<filename>","File Name").option("--num-resources-per-request <numResourcesPerRequest>","optional number of resources to import per batch request. Defaults to 25.","25").option("--add-extensions-for-missing-values","optional flag to add extensions for missing values in a resource",!1).option("-d, --target-directory <targetDirectory>","optional target directory of file to be imported").action(async(e,t)=>{let{numResourcesPerRequest:r,addExtensionsForMissingValues:s,targetDirectory:o}=t,i=Qr(o??process.cwd(),e),a=await x(t);await nn(i,Number.parseInt(r,10),a,s)});async function nn(e,t,r,s){let o=[],i=tn(e),a=sn({input:i});for await(let c of a){let n=cn(c,s);o.push({resource:n,request:{method:"POST",url:n.resourceType}}),o.length%t===0&&(await Kt(o,r),o=[])}o.length>0&&await Kt(o,r)}async function Kt(e,t){let r=await t.executeBatch({resourceType:"Bundle",type:"transaction",entry:e});for(let s of r.entry??Yr)re(s.response)}function cn(e,t){let r=JSON.parse(e);return t?ln(r):r}function ln(e){return e.resourceType==="ExplanationOfBenefit"?un(e):e}function un(e){return e.provider||(e.provider=_t()),e.item?.forEach(t=>{t?.productOrService||(t.productOrService=_t())}),e}var En=Object.defineProperty,vn=(e,t,r)=>t in e?En(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,L=(e,t,r)=>vn(e,typeof t!="symbol"?t+"":t,r),ts=class extends EventTarget{addEventListener(e,t,r){super.addEventListener(e,t,r)}removeEventListener(e,t,r){super.removeEventListener(e,t,r)}},Sn=class extends Event{constructor(e,t){super("message"),L(this,"connection"),L(this,"message"),this.connection=e,this.message=t}},In=class extends Event{constructor(e,t){super("enhancedAckSent"),L(this,"connection"),L(this,"message"),this.connection=e,this.message=t}},ve=class extends Event{constructor(e){super("error"),L(this,"error"),this.error=e}},nt=class extends Event{constructor(e){super("warning"),L(this,"error"),this.error=e}},ct=class extends Event{constructor(){super("close")}},Vt="utf-8",bn=5e3,An=60*1e3,rs=class extends ts{constructor(e,t=Vt,r,s={}){super(),L(this,"socket"),L(this,"encoding"),L(this,"enhancedMode"),L(this,"messagesPerMin"),L(this,"gracefulCloseTimeoutMs"),L(this,"chunks",[]),L(this,"pendingMessages",new Map),L(this,"responseQueue",[]),L(this,"lastMessageDispatchedTime",0),L(this,"responseQueueProcessing",!1),L(this,"closing",!1),this.socket=e,this.encoding=t,this.enhancedMode=r,this.messagesPerMin=s.messagesPerMin,this.gracefulCloseTimeoutMs=s.gracefulCloseTimeoutMs??bn,e.on("data",o=>{if(this.closing){this.dispatchEvent(new nt(new ie({resourceType:"OperationOutcome",issue:[{severity:"warning",code:"transient",details:{text:"Data received after close was initiated"}}]})));return}try{this.appendData(o);let i=this.parseMessages();for(let a of i)this.responseQueue.push(new Sn(this,a));this.processResponseQueue().catch(a=>{this.dispatchEvent(new ve(a))})}catch(i){this.dispatchEvent(new ve(i))}}),e.on("error",o=>{this.resetBuffer(),this.dispatchEvent(new ve(o))}),e.on("close",()=>{this.drainPendingMessages(),this.dispatchEvent(new ct)}),this.addEventListener("message",o=>{let i;this.enhancedMode==="standard"?i=o.message.buildAck({ackCode:"CA"}):this.enhancedMode==="aaMode"&&(i=o.message.buildAck({ackCode:"AA"})),i&&(this.send(i),this.dispatchEvent(new In(this,i)));let a=o.message.getSegment("MSA")?.getField(2)?.toString();if(!a)return;let c=this.getPendingMessage(a);if(!c){this.dispatchEvent(new nt(new ie({resourceType:"OperationOutcome",issue:[{severity:"warning",code:"not-found",details:{text:"Response received for unknown message control ID"},diagnostics:`Received ACK for message control ID '${a}' but there was no pending message with this control ID`}]})));return}let n=o.message.getSegment("MSA")?.getField(1)?.toString()?.toUpperCase();n&&(c.returnAck===Gt.APPLICATION&&n==="CA"||(c.timer&&clearTimeout(c.timer),c.resolve(o.message),this.deletePendingMessage(a)))})}isClosed(){return this.socket.closed}sendImpl(e){let t=e.toString(),r=Jt.encode(t,this.encoding),s=Buffer.alloc(r.length+3);s.writeInt8(11,0),r.copy(s,1),s.writeInt8(28,r.length+1),s.writeInt8(13,r.length+2),this.socket.write(s)}async processResponseQueue(){if(!this.responseQueueProcessing){for(this.responseQueueProcessing=!0;this.responseQueue.length;){if(this.messagesPerMin){let t=An/this.messagesPerMin,r=Date.now()-this.lastMessageDispatchedTime;t>r&&await fn(t-r)}let e=this.responseQueue.shift();e&&this.dispatchEvent(e),this.lastMessageDispatchedTime=Date.now()}this.responseQueueProcessing=!1}}parseMessages(){let e=[],t=Buffer.concat(this.chunks);if(this.resetBuffer(),t.length===0)return e;let r=0;for(;r<t.length;){for(;t[r]!==11&&r<t.length;)r++;let s=-1;for(let c=r+1;c<t.length-1;c++)if(t[c]===28&&t[c+1]===13){s=c+1;break}if(s===-1)break;let o=t.subarray(r,s+1).subarray(1,-2),i=Jt.decode(o,this.encoding),a=mn.parse(i);e.push(a),r=s+1}return this.chunks=r<t.length?[t.subarray(r)]:[],e}send(e){this.sendImpl(e)}async sendAndWait(e,t){return new Promise((r,s)=>{let o=e.getSegment("MSH")?.getField(10)?.toString();if(!o){s(new ie(gn("Required field missing: MSH.10")));return}let i;t?.timeoutMs&&(i=setTimeout(()=>{this.deletePendingMessage(o),s(new ie({resourceType:"OperationOutcome",issue:[{severity:"error",code:"timeout",details:{text:"Client timeout"},diagnostics:`Request timed out after waiting ${t.timeoutMs} milliseconds for response`}]}))},t.timeoutMs)),this.setPendingMessage(o,{message:e,resolve:r,reject:s,returnAck:t?.returnAck??Gt.APPLICATION,timer:i}),this.sendImpl(e)})}async close(){this.isClosed()||(this.closing=!0,this.socket.end(),this.drainPendingMessages(),await new Promise(e=>{let t=setTimeout(()=>{this.socket.destroy()},this.gracefulCloseTimeoutMs);this.socket.once("close",()=>{clearTimeout(t),e()})}))}drainPendingMessages(){if(!this.pendingMessages.size)return;let e=this.pendingMessages.size;for(let t of this.pendingMessages.values())t.timer&&clearTimeout(t.timer),t.reject(new ie({resourceType:"OperationOutcome",issue:[{severity:"warning",code:"incomplete",details:{text:"Message was still pending when connection closed"}}]}));this.dispatchEvent(new ve(new ie({resourceType:"OperationOutcome",issue:[{severity:"warning",code:"incomplete",details:{text:"Messages were still pending when connection closed"},diagnostics:`Hl7Connection closed while ${e} messages were pending`}]}))),this.pendingMessages.clear()}appendData(e){this.chunks.push(e)}resetBuffer(){this.chunks=[]}setEncoding(e){this.encoding=e??Vt}getEncoding(){return this.encoding}setEnhancedMode(e){this.enhancedMode=e}getEnhancedMode(){return this.enhancedMode}setMessagesPerMin(e){this.messagesPerMin=e}getMessagesPerMin(){return this.messagesPerMin}getPendingMessageCount(){return this.pendingMessages.size}getPendingMessage(e){return this.pendingMessages.get(e)}setPendingMessage(e,t){this.pendingMessages.set(e,t)}deletePendingMessage(e){this.pendingMessages.delete(e)}},$n=class extends ts{constructor(e){super(),L(this,"options"),L(this,"host"),L(this,"port"),L(this,"encoding"),L(this,"connection"),L(this,"keepAlive"),L(this,"socket"),L(this,"connectTimeout"),L(this,"deferredConnectionPromise"),this.options=e,this.host=this.options.host,this.port=this.options.port,this.encoding=this.options.encoding,this.keepAlive=this.options.keepAlive??!1,this.connectTimeout=this.options.connectTimeout??3e4}connect(){if(this.deferredConnectionPromise)return this.deferredConnectionPromise.promise;let e=this.deferredConnectionPromise=this.createDeferredConnectionPromise();return this.socket=hn({host:this.host,port:this.port,keepAlive:this.keepAlive}),this.connectTimeout>0&&(this.socket.setTimeout(this.connectTimeout),this.registerSocketTimeoutListener(e)),this.registerSocketConnectListener(e),this.registerSocketErrorListener(e),this.registerSocketCloseListener(e),e.promise}registerSocketTimeoutListener(e){Ce(this.socket);let t=this.socket,r=()=>{this.cleanupSocket(t);let s=new Error(`Connection timeout after ${this.connectTimeout}ms`);this.rejectDeferredPromise(e,s)};t.on("timeout",r)}registerSocketConnectListener(e){Ce(this.socket);let t=this.socket,r=()=>{if(t!==this.socket){this.cleanupSocket(t);return}let s;this.connection=s=this.createConnection(t,this.encoding),t.setTimeout(0),this.registerHl7ConnectionListeners(s),e.resolve(s)};t.on("connect",r)}registerSocketErrorListener(e){Ce(this.socket);let t=this.socket,r=s=>{this.cleanupSocket(t),s.constructor.name==="AggregateError"?this.rejectDeferredPromise(e,s.errors[0]):this.rejectDeferredPromise(e,s)};t.on("error",r)}registerSocketCloseListener(e){Ce(this.socket);let t=this.socket,r=()=>{this.cleanupSocket(t),this.rejectDeferredPromise(e,new Error("Socket closed before connection finished"))};t.on("close",r)}registerHl7ConnectionListeners(e){e.addEventListener("close",()=>{this.socket=void 0,this.connection=void 0,this.deferredConnectionPromise=void 0,this.dispatchEvent(new ct)}),e.addEventListener("error",t=>{this.dispatchEvent(new ve(t.error))}),e.addEventListener("warning",t=>{this.dispatchEvent(new nt(t.error))})}createDeferredConnectionPromise(){let e,t;return{promise:new Promise((r,s)=>{e=r,t=s}),resolve:e,reject:t}}rejectDeferredPromise(e,t){e.reject(t),this.deferredConnectionPromise===e&&(this.deferredConnectionPromise=void 0)}cleanupSocket(e){e.destroyed||e.destroy(),e===this.socket&&(this.socket=void 0)}createConnection(e,t,r,s){return new rs(e,t,r,s)}async send(e){return(await this.connect()).send(e)}async sendAndWait(e,t){return(await this.connect()).sendAndWait(e,t)}async close(){if(this.deferredConnectionPromise&&this.rejectDeferredPromise(this.deferredConnectionPromise,new Error("Client closed while connecting")),this.connection){let e=this.connection;delete this.connection,await e.close()}else this.dispatchEvent(new ct);this.socket&&(this.socket.removeAllListeners(),this.socket.destroy(),this.socket=void 0)}},Rn=1e4,Tn=class{constructor(e){L(this,"handler"),L(this,"server"),L(this,"encoding"),L(this,"enhancedMode"),L(this,"messagesPerMin"),L(this,"connections",new Set),this.handler=e}async start(e,t,r,s){t&&this.setEncoding(t),r!==void 0&&this.setEnhancedMode(r),s?.messagesPerMin!==void 0&&this.setMessagesPerMin(s.messagesPerMin);let o=yn.createServer(i=>{let a=new rs(i,this.encoding,this.enhancedMode,{messagesPerMin:this.messagesPerMin});this.handler(a),this.connections.add(a),a.addEventListener("close",()=>{this.connections.delete(a)})});return new Promise((i,a)=>{let c=f=>{o.listen(f,()=>{let l=o.address().port;i(l)})},n=f=>{f?.code==="EADDRINUSE"?o.close(()=>wn(50).then(()=>c(e))):a(f)};o.on("error",n),o.once("listening",()=>{o.off("error",n)}),c(e),this.server=o})}async stop(e){return new Promise((t,r)=>{if(!this.server){r(new Error("Stop was called but there is no server running"));return}let s;e?.forceDrainTimeoutMs!==-1&&(s=setTimeout(()=>{for(let o of this.connections)o.close().catch(console.error)},e?.forceDrainTimeoutMs??Rn)),this.server.close(o=>{if(o){r(o);return}s&&clearTimeout(s),this.connections.clear(),this.server=void 0,t()})})}setEnhancedMode(e){this.enhancedMode=e}getEnhancedMode(){return this.enhancedMode}setEncoding(e){this.encoding=e}getEncoding(){return this.encoding}setMessagesPerMin(e){this.messagesPerMin=e}getMessagesPerMin(){return this.messagesPerMin}},Nn=new R("send").description("Send an HL7 v2 message via MLLP").argument("<host>","The destination host name or IP address").argument("<port>","The destination port number").argument("[body]","Optional HL7 message body").option("--generate-example","Generate a sample HL7 message").option("--file <file>","Read the HL7 message from a file").option("--encoding <encoding>","The encoding to use").action(async(e,t,r,s)=>{if(s.generateExample?r=Cn():s.file&&(r=Pn(s.file,"utf8")),!r)throw new Error("Missing HL7 message body");let o=new $n({host:e,port:Number.parseInt(t,10),encoding:s.encoding});try{let i=await o.sendAndWait(dn.parse(r));console.log(i.toString().replaceAll("\r",`
15
- `))}finally{await o.close()}}),On=new R("listen").description("Starts an HL7 v2 MLLP server").argument("<port>").option("--encoding <encoding>","The encoding to use").action(async(e,t)=>{await new Tn(r=>{r.addEventListener("message",({message:s})=>{console.log(s.toString().replaceAll("\r",`
16
- `)),r.send(s.buildAck())})}).start(Number.parseInt(e,10),t.encoding),console.log("Listening on port "+e)}),$t=new R("hl7");P($t,Nn);P($t,On);function Cn(){let e=pn(new Date),t=Date.now().toString();return`MSH|^~\\&|ADTSYS|HOSPITAL|RECEIVER|DEST|${e}||ADT^A01|${t}|P|2.5|
14
+ `)}`,{cause:o})}es.description("Saves the bot").argument("<botName>").action(async(e,t)=>{let r=await x(t);await Ve(r,e)});ts.description("Deploy the bot to AWS").argument("<botName>").action(async(e,t)=>{let r=await x(t);await Ve(r,e,!0)});rs.arguments("<botName> <projectId> <sourceFile> <distFile>").description("Creates and saves the bot").action(async(e,t,r,s,o)=>{let i=await x(o);await br(i,e,t,r,s)});var is=new P("export"),as=new P("import"),It=new P("bulk");O(It,is);O(It,as);is.option("-e, --export-level <exportLevel>",'Optional export level. Defaults to system level export. "Group/:id" - Group of Patients, "Patient" - All Patients.').option("-t, --types <types>","optional resource types to export").option("-s, --since <since>","optional Resources will be included in the response if their state has changed after the supplied time (e.g. if Resource.meta.lastUpdated is later than the supplied _since time).").option("-d, --target-directory <targetDirectory>","optional target directory to save files from the bulk export operations.").action(async e=>{let{exportLevel:t,types:r,since:s,targetDirectory:o}=e,i=await x(e),a=await i.bulkExport(t,r,s,{pollStatusOnAccepted:!0});for(let{type:c,url:n}of a.output??ss){let m=new URL(n),l=`${c}_${m.pathname}`.replaceAll(/[^a-zA-Z0-9]+/g,"_")+".ndjson",u=os(o??"",l),d=await i.downloadResponse(n);if(!d.ok)throw new Error(`Download failed: ${d.status} ${d.statusText}`);if(!d.body)throw new Error("Download response missing body");let f=mn.fromWeb(d.body);await fn(f,dn(u)),console.log(`${u} is created`)}});as.argument("<filename>","File Name").option("--num-resources-per-request <numResourcesPerRequest>","optional number of resources to import per batch request. Defaults to 25.","25").option("--add-extensions-for-missing-values","optional flag to add extensions for missing values in a resource",!1).option("-d, --target-directory <targetDirectory>","optional target directory of file to be imported").action(async(e,t)=>{let{numResourcesPerRequest:r,addExtensionsForMissingValues:s,targetDirectory:o}=t,i=os(o??process.cwd(),e),a=await x(t);await gn(i,Number.parseInt(r,10),a,s)});async function gn(e,t,r,s){let o=[],i=pn(e),a=hn({input:i});for await(let c of a){let n=wn(c,s);o.push({resource:n,request:{method:"POST",url:n.resourceType}}),o.length%t===0&&(await Xt(o,r),o=[])}o.length>0&&await Xt(o,r)}async function Xt(e,t){let r=await t.executeBatch({resourceType:"Bundle",type:"transaction",entry:e});for(let s of r.entry??ss)se(s.response)}function wn(e,t){let r=JSON.parse(e);return t?yn(r):r}function yn(e){return e.resourceType==="ExplanationOfBenefit"?En(e):e}function En(e){return e.provider||(e.provider=_t()),e.item?.forEach(t=>{t?.productOrService||(t.productOrService=_t())}),e}var Pn=Object.defineProperty,On=(e,t,r)=>t in e?Pn(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,L=(e,t,r)=>On(e,typeof t!="symbol"?t+"":t,r),ns=class extends EventTarget{addEventListener(e,t,r){super.addEventListener(e,t,r)}removeEventListener(e,t,r){super.removeEventListener(e,t,r)}},Nn=class extends Event{constructor(e,t){super("message"),L(this,"connection"),L(this,"message"),this.connection=e,this.message=t}},Cn=class extends Event{constructor(e,t){super("enhancedAckSent"),L(this,"connection"),L(this,"message"),this.connection=e,this.message=t}},ve=class extends Event{constructor(e){super("error"),L(this,"error"),this.error=e}},lt=class extends Event{constructor(e){super("warning"),L(this,"error"),this.error=e}},ut=class extends Event{constructor(){super("close")}},Yt="utf-8",Ln=5e3,kn=60*1e3,cs=class extends ns{constructor(e,t=Yt,r,s={}){super(),L(this,"socket"),L(this,"encoding"),L(this,"enhancedMode"),L(this,"messagesPerMin"),L(this,"gracefulCloseTimeoutMs"),L(this,"chunks",[]),L(this,"pendingMessages",new Map),L(this,"responseQueue",[]),L(this,"lastMessageDispatchedTime",0),L(this,"responseQueueProcessing",!1),L(this,"closing",!1),this.socket=e,this.encoding=t,this.enhancedMode=r,this.messagesPerMin=s.messagesPerMin,this.gracefulCloseTimeoutMs=s.gracefulCloseTimeoutMs??Ln,e.on("data",o=>{if(this.closing){this.dispatchEvent(new lt(new ne({resourceType:"OperationOutcome",issue:[{severity:"warning",code:"transient",details:{text:"Data received after close was initiated"}}]})));return}try{this.appendData(o);let i=this.parseMessages();for(let a of i)this.responseQueue.push(new Nn(this,a));this.processResponseQueue().catch(a=>{this.dispatchEvent(new ve(a))})}catch(i){this.dispatchEvent(new ve(i))}}),e.on("error",o=>{this.resetBuffer(),this.dispatchEvent(new ve(o))}),e.on("close",()=>{this.drainPendingMessages(),this.dispatchEvent(new ut)}),this.addEventListener("message",o=>{let i;this.enhancedMode==="standard"?i=o.message.buildAck({ackCode:"CA"}):this.enhancedMode==="aaMode"&&(i=o.message.buildAck({ackCode:"AA"})),i&&(this.send(i),this.dispatchEvent(new Cn(this,i)));let a=o.message.getSegment("MSA")?.getField(2)?.toString();if(!a)return;let c=this.getPendingMessage(a);if(!c){this.dispatchEvent(new lt(new ne({resourceType:"OperationOutcome",issue:[{severity:"warning",code:"not-found",details:{text:"Response received for unknown message control ID"},diagnostics:`Received ACK for message control ID '${a}' but there was no pending message with this control ID`}]})));return}let n=o.message.getSegment("MSA")?.getField(1)?.toString()?.toUpperCase();n&&(c.returnAck===zt.APPLICATION&&n==="CA"||(c.timer&&clearTimeout(c.timer),c.resolve(o.message),this.deletePendingMessage(a)))})}isClosed(){return this.socket.closed}sendImpl(e){let t=e.toString(),r=qt.encode(t,this.encoding),s=Buffer.alloc(r.length+3);s.writeInt8(11,0),r.copy(s,1),s.writeInt8(28,r.length+1),s.writeInt8(13,r.length+2),this.socket.write(s)}async processResponseQueue(){if(!this.responseQueueProcessing){for(this.responseQueueProcessing=!0;this.responseQueue.length;){if(this.messagesPerMin){let t=kn/this.messagesPerMin,r=Date.now()-this.lastMessageDispatchedTime;t>r&&await In(t-r)}let e=this.responseQueue.shift();e&&this.dispatchEvent(e),this.lastMessageDispatchedTime=Date.now()}this.responseQueueProcessing=!1}}parseMessages(){let e=[],t=Buffer.concat(this.chunks);if(this.resetBuffer(),t.length===0)return e;let r=0;for(;r<t.length;){for(;t[r]!==11&&r<t.length;)r++;let s=-1;for(let c=r+1;c<t.length-1;c++)if(t[c]===28&&t[c+1]===13){s=c+1;break}if(s===-1)break;let o=t.subarray(r,s+1).subarray(1,-2),i=qt.decode(o,this.encoding),a=An.parse(i);e.push(a),r=s+1}return this.chunks=r<t.length?[t.subarray(r)]:[],e}send(e){this.sendImpl(e)}async sendAndWait(e,t){return new Promise((r,s)=>{let o=e.getSegment("MSH")?.getField(10)?.toString();if(!o){s(new ne($n("Required field missing: MSH.10")));return}let i;t?.timeoutMs&&(i=setTimeout(()=>{this.deletePendingMessage(o),s(new ne({resourceType:"OperationOutcome",issue:[{severity:"error",code:"timeout",details:{text:"Client timeout"},diagnostics:`Request timed out after waiting ${t.timeoutMs} milliseconds for response`}]}))},t.timeoutMs)),this.setPendingMessage(o,{message:e,resolve:r,reject:s,returnAck:t?.returnAck??zt.APPLICATION,timer:i}),this.sendImpl(e)})}async close(){this.isClosed()||(this.closing=!0,this.socket.end(),this.drainPendingMessages(),await new Promise(e=>{let t=setTimeout(()=>{this.socket.destroy()},this.gracefulCloseTimeoutMs);this.socket.once("close",()=>{clearTimeout(t),e()})}))}drainPendingMessages(){if(!this.pendingMessages.size)return;let e=this.pendingMessages.size;for(let t of this.pendingMessages.values())t.timer&&clearTimeout(t.timer),t.reject(new ne({resourceType:"OperationOutcome",issue:[{severity:"warning",code:"incomplete",details:{text:"Message was still pending when connection closed"}}]}));this.dispatchEvent(new ve(new ne({resourceType:"OperationOutcome",issue:[{severity:"warning",code:"incomplete",details:{text:"Messages were still pending when connection closed"},diagnostics:`Hl7Connection closed while ${e} messages were pending`}]}))),this.pendingMessages.clear()}appendData(e){this.chunks.push(e)}resetBuffer(){this.chunks=[]}setEncoding(e){this.encoding=e??Yt}getEncoding(){return this.encoding}setEnhancedMode(e){this.enhancedMode=e}getEnhancedMode(){return this.enhancedMode}setMessagesPerMin(e){this.messagesPerMin=e}getMessagesPerMin(){return this.messagesPerMin}getPendingMessageCount(){return this.pendingMessages.size}getPendingMessage(e){return this.pendingMessages.get(e)}setPendingMessage(e,t){this.pendingMessages.set(e,t)}deletePendingMessage(e){this.pendingMessages.delete(e)}},Mn=class extends ns{constructor(e){super(),L(this,"options"),L(this,"host"),L(this,"port"),L(this,"encoding"),L(this,"connection"),L(this,"keepAlive"),L(this,"socket"),L(this,"connectTimeout"),L(this,"deferredConnectionPromise"),this.options=e,this.host=this.options.host,this.port=this.options.port,this.encoding=this.options.encoding,this.keepAlive=this.options.keepAlive??!1,this.connectTimeout=this.options.connectTimeout??3e4}connect(){if(this.deferredConnectionPromise)return this.deferredConnectionPromise.promise;let e=this.deferredConnectionPromise=this.createDeferredConnectionPromise();return this.socket=bn({host:this.host,port:this.port,keepAlive:this.keepAlive}),this.connectTimeout>0&&(this.socket.setTimeout(this.connectTimeout),this.registerSocketTimeoutListener(e)),this.registerSocketConnectListener(e),this.registerSocketErrorListener(e),this.registerSocketCloseListener(e),e.promise}registerSocketTimeoutListener(e){Le(this.socket);let t=this.socket,r=()=>{this.cleanupSocket(t);let s=new Error(`Connection timeout after ${this.connectTimeout}ms`);this.rejectDeferredPromise(e,s)};t.on("timeout",r)}registerSocketConnectListener(e){Le(this.socket);let t=this.socket,r=()=>{if(t!==this.socket){this.cleanupSocket(t);return}let s;this.connection=s=this.createConnection(t,this.encoding),t.setTimeout(0),this.registerHl7ConnectionListeners(s),e.resolve(s)};t.on("connect",r)}registerSocketErrorListener(e){Le(this.socket);let t=this.socket,r=s=>{this.cleanupSocket(t),s.constructor.name==="AggregateError"?this.rejectDeferredPromise(e,s.errors[0]):this.rejectDeferredPromise(e,s)};t.on("error",r)}registerSocketCloseListener(e){Le(this.socket);let t=this.socket,r=()=>{this.cleanupSocket(t),this.rejectDeferredPromise(e,new Error("Socket closed before connection finished"))};t.on("close",r)}registerHl7ConnectionListeners(e){e.addEventListener("close",()=>{this.socket=void 0,this.connection=void 0,this.deferredConnectionPromise=void 0,this.dispatchEvent(new ut)}),e.addEventListener("error",t=>{this.dispatchEvent(new ve(t.error))}),e.addEventListener("warning",t=>{this.dispatchEvent(new lt(t.error))})}createDeferredConnectionPromise(){let e,t;return{promise:new Promise((r,s)=>{e=r,t=s}),resolve:e,reject:t}}rejectDeferredPromise(e,t){e.reject(t),this.deferredConnectionPromise===e&&(this.deferredConnectionPromise=void 0)}cleanupSocket(e){e.destroyed||e.destroy(),e===this.socket&&(this.socket=void 0)}createConnection(e,t,r,s){return new cs(e,t,r,s)}async send(e){return(await this.connect()).send(e)}async sendAndWait(e,t){return(await this.connect()).sendAndWait(e,t)}async close(){if(this.deferredConnectionPromise&&this.rejectDeferredPromise(this.deferredConnectionPromise,new Error("Client closed while connecting")),this.connection){let e=this.connection;delete this.connection,await e.close()}else this.dispatchEvent(new ut);this.socket&&(this.socket.removeAllListeners(),this.socket.destroy(),this.socket=void 0)}},Dn=1e4,Un=class{constructor(e){L(this,"handler"),L(this,"server"),L(this,"encoding"),L(this,"enhancedMode"),L(this,"messagesPerMin"),L(this,"connections",new Set),this.handler=e}async start(e,t,r,s){t&&this.setEncoding(t),r!==void 0&&this.setEnhancedMode(r),s?.messagesPerMin!==void 0&&this.setMessagesPerMin(s.messagesPerMin);let o=Tn.createServer(i=>{let a=new cs(i,this.encoding,this.enhancedMode,{messagesPerMin:this.messagesPerMin});this.handler(a),this.connections.add(a),a.addEventListener("close",()=>{this.connections.delete(a)})});return new Promise((i,a)=>{let c=m=>{o.listen(m,()=>{let l=o.address().port;i(l)})},n=m=>{m?.code==="EADDRINUSE"?o.close(()=>Rn(50).then(()=>c(e))):a(m)};o.on("error",n),o.once("listening",()=>{o.off("error",n)}),c(e),this.server=o})}async stop(e){return new Promise((t,r)=>{if(!this.server){r(new Error("Stop was called but there is no server running"));return}let s;e?.forceDrainTimeoutMs!==-1&&(s=setTimeout(()=>{for(let o of this.connections)o.close().catch(console.error)},e?.forceDrainTimeoutMs??Dn)),this.server.close(o=>{if(o){r(o);return}s&&clearTimeout(s),this.connections.clear(),this.server=void 0,t()})})}setEnhancedMode(e){this.enhancedMode=e}getEnhancedMode(){return this.enhancedMode}setEncoding(e){this.encoding=e}getEncoding(){return this.encoding}setMessagesPerMin(e){this.messagesPerMin=e}getMessagesPerMin(){return this.messagesPerMin}},xn=new P("send").description("Send an HL7 v2 message via MLLP").argument("<host>","The destination host name or IP address").argument("<port>","The destination port number").argument("[body]","Optional HL7 message body").option("--generate-example","Generate a sample HL7 message").option("--file <file>","Read the HL7 message from a file").option("--encoding <encoding>","The encoding to use").action(async(e,t,r,s)=>{if(s.generateExample?r=Fn():s.file&&(r=_n(s.file,"utf8")),!r)throw new Error("Missing HL7 message body");let o=new Mn({host:e,port:Number.parseInt(t,10),encoding:s.encoding});try{let i=await o.sendAndWait(Sn.parse(r));console.log(i.toString().replaceAll("\r",`
15
+ `))}finally{await o.close()}}),jn=new P("listen").description("Starts an HL7 v2 MLLP server").argument("<port>").option("--encoding <encoding>","The encoding to use").action(async(e,t)=>{await new Un(r=>{r.addEventListener("message",({message:s})=>{console.log(s.toString().replaceAll("\r",`
16
+ `)),r.send(s.buildAck())})}).start(Number.parseInt(e,10),t.encoding),console.log("Listening on port "+e)}),$t=new P("hl7");O($t,xn);O($t,jn);function Fn(){let e=vn(new Date),t=Date.now().toString();return`MSH|^~\\&|ADTSYS|HOSPITAL|RECEIVER|DEST|${e}||ADT^A01|${t}|P|2.5|
17
17
  EVN|A01|${e}||
18
18
  PID|1|12345|12345^^^HOSP^MR|123456|DOE^JOHN^MIDDLE^SUFFIX|19800101|M|||123 STREET^APT 4B^CITY^ST^12345-6789||555-555-5555||S|
19
- PV1|1|I|2000^2012^01||||12345^DOCTOR^DOC||||||||||1234567^DOCTOR^DOC||AMB|||||||||||||||||||||||||202309280900|`}var ss=new R("set"),os=new R("remove"),is=new R("list"),as=new R("describe"),Re=new R("profile");P(Re,ss);P(Re,os);P(Re,is);P(Re,as);ss.argument("<profileName>","Name of the profile").description("Create a new profile or replace it with the given name and its associated properties").action(async(e,t)=>{Er(e,t)});os.argument("<profileName>","Name of the profile").description("Remove a profile by name").action(async e=>{new be(e).setObject("options",void 0),console.log(`${e} profile removed`)});is.description("List all profiles saved").action(async()=>{let e=Mn(kn(),".medplum"),t=Ln(e),r=[];t.forEach(s=>{let o=s.split(".")[0],i=new be(o).getObject("options");i&&r.push({profileName:o,profile:i})}),console.log(r)});as.argument("<profileName>","Name of the profile").description("Describes a profile").action(async e=>{let t=ci(e);console.log(t)});var ns=new R("list"),cs=new R("current"),ls=new R("switch"),us=new R("invite"),Te=new R("project");P(Te,ns);P(Te,cs);P(Te,ls);P(Te,us);ns.description("List of current projects").action(async e=>{let t=await x(e);Un(t)});function Un(e){let t=e.getLogins().map(r=>`${r.project.display} (${r.project.reference})`).join(`
19
+ PV1|1|I|2000^2012^01||||12345^DOCTOR^DOC||||||||||1234567^DOCTOR^DOC||AMB|||||||||||||||||||||||||202309280900|`}var ls=new P("set"),us=new P("remove"),ps=new P("list"),ds=new P("describe"),Te=new P("profile");O(Te,ls);O(Te,us);O(Te,ps);O(Te,ds);ls.argument("<profileName>","Name of the profile").description("Create a new profile or replace it with the given name and its associated properties").action(async(e,t)=>{Ar(e,t)});us.argument("<profileName>","Name of the profile").description("Remove a profile by name").action(async e=>{new Ie(e).setObject("options",void 0),console.log(`${e} profile removed`)});ps.description("List all profiles saved").action(async()=>{let e=Bn(Hn(),".medplum"),t=Wn(e),r=[];t.forEach(s=>{let o=s.split(".")[0],i=new Ie(o).getObject("options");i&&r.push({profileName:o,profile:i})}),console.log(r)});ds.argument("<profileName>","Name of the profile").description("Describes a profile").action(async e=>{let t=gi(e);console.log(t)});var hs=new P("list"),ms=new P("current"),fs=new P("switch"),gs=new P("invite"),Pe=new P("project");O(Pe,hs);O(Pe,ms);O(Pe,fs);O(Pe,gs);hs.description("List of current projects").action(async e=>{let t=await x(e);Kn(t)});function Kn(e){let t=e.getLogins().map(r=>`${r.project.display} (${r.project.reference})`).join(`
20
20
 
21
- `);console.log(t)}cs.description("Project you are currently on").action(async e=>{let t=(await x(e)).getActiveLogin();if(!t)throw new Error("Unauthenticated: run `npx medplum login` to login");console.log(`${t.project.display} (${t.project.reference})`)});ls.description("Switching to another project from the current one").argument("<projectId>").action(async(e,t)=>{let r=await x(t);await _n(r,e)});us.description("Invite a member to your current project (run npx medplum project current to confirm)").arguments("<firstName> <lastName> <email>").option("--send-email","If you want to send the email when inviting the user").option("--admin","If the user you are inviting is an admin").addOption(new Dn("-r, --role <role>","Role of user").choices(["Practitioner","Patient","RelatedPerson"]).default("Practitioner")).action(async(e,t,r,s)=>{let o=await x(s),i=o.getActiveLogin();if(!i)throw new Error("Unauthenticated: run `npx medplum login` to login");if(!i?.project?.reference)throw new Error("No current project to invite user to");let a=i.project.reference.split("/")[1],c={resourceType:s.role,firstName:e,lastName:t,email:r,sendEmail:!!s.sendEmail,admin:!!s.admin};await xn(a,c,o)});async function _n(e,t){let r=e.getLogins().find(s=>s.project.reference?.includes(t));if(!r)throw new Error(`Project ${t} not found. Make sure you are added as a user to this project`);await e.setActiveLogin(r),console.log(`Switched to project ${t}
22
- `)}async function xn(e,t,r){await r.invite(e,t),t.sendEmail&&console.log("Email sent"),console.log("See your users at https://app.medplum.com/admin/users")}var ps=new R("delete"),ds=new R("get"),hs=new R("patch"),ms=new R("post"),fs=new R("put");ps.argument("<url>","Resource/$id").action(async(e,t)=>{let r=await x(t);re(await r.delete(Pe(r,e)))});ds.argument("<url>","Resource/$id").option("--as-transaction","Print out the bundle as a transaction type").action(async(e,t)=>{let r=await x(t),s=await r.get(Pe(r,e));t.asTransaction?re(jn(s)):re(s)});hs.arguments("<url> <body>").action(async(e,t,r)=>{let s=await x(r);re(await s.patch(Pe(s,e),Rt(t)))});ms.arguments("<url> <body>").option("--prefer-async",'Sets the Prefer header to "respond-async"').action(async(e,t,r)=>{let s=await x(r),o=r.preferAsync?{Prefer:"respond-async"}:void 0;re(await s.post(Pe(s,e),Rt(t),void 0,{headers:o}))});fs.arguments("<url> <body>").action(async(e,t,r)=>{let s=await x(r);re(await s.put(Pe(s,e),Rt(t)))});function Rt(e){if(e)try{return JSON.parse(e)}catch{return e}}function Pe(e,t){return["admin/","auth/","fhir/R4"].some(r=>t.startsWith(r))?t:e.fhirUrl(t).toString()}async function Fn(e){let t=new R("medplum").description("Command to access Medplum CLI").option("--client-id <clientId>","FHIR server client id").option("--client-secret <clientSecret>","FHIR server client secret").option("--base-url <baseUrl>","FHIR server base URL, must be absolute").option("--token-url <tokenUrl>","FHIR server token URL, absolute or relative to base URL").option("--authorize-url <authorizeUrl>","FHIR server authorize URL, absolute or relative to base URL").option("--fhir-url, --fhir-url-path <fhirUrlPath>","FHIR server URL, absolute or relative to base URL").option("--scope <scope>","JWT scope").option("--access-token <accessToken>","Access token for token exchange authentication").option("--callback-url <callbackUrl>","Callback URL for authorization code flow").option("--subject <subject>","Subject for JWT authentication").option("--audience <audience>","Audience for JWT authentication").option("--issuer <issuer>","Issuer for JWT authentication").option("--private-key-path <privateKeyPath>","Private key path for JWT assertion").option("-p, --profile <profile>","Profile name").option("-v --verbose","Verbose output").addOption(new Xs("--auth-type <authType>","Type of authentication").choices(["basic","client-credentials","authorization-code","jwt-bearer","token-exchange","jwt-assertion"])).on("option:verbose",()=>{process.env.VERBOSE="1"});t.exitOverride(),t.version(Vs),t.configureHelp({showGlobalOptions:!0}),P(t,Nr),P(t,Or),P(t,Cr),P(t,ds),P(t,ms),P(t,hs),P(t,fs),P(t,ps),P(t,Te),P(t,At),P(t,Ke),P(t,he),P(t,Xr),P(t,zr),P(t,qr),P(t,Re),P(t,en()),P(t,$t);try{await t.parseAsync(e)}catch(r){Wn(r)}}function Wn(e){let t=1,r=!0;if(e instanceof er&&(process.env.VERBOSE||(r=!1),t=e.exitCode),t!==0&&r){et(e,!!process.env.VERBOSE);let s=e.cause;if(process.env.VERBOSE)if(Array.isArray(s))for(let o of s)et(o,!0);else s instanceof Error&&et(s,!0)}process.exit(t)}function et(e,t=!1){if(t){console.error(e);return}e instanceof er?process.stderr.write(`${rt(e)}
23
- `):process.stderr.write(`Error: ${rt(e)}
24
- `)}async function Hn(){zs.config({quiet:!0}),await Fn(process.argv)}import.meta.main&&Hn().catch(e=>{console.error("Unhandled error:",rt(e)),process.exit(1)});
21
+ `);console.log(t)}ms.description("Project you are currently on").action(async e=>{let t=(await x(e)).getActiveLogin();if(!t)throw new Error("Unauthenticated: run `npx medplum login` to login");console.log(`${t.project.display} (${t.project.reference})`)});fs.description("Switching to another project from the current one").argument("<projectId>").action(async(e,t)=>{let r=await x(t);await Jn(r,e)});gs.description("Invite a member to your current project (run npx medplum project current to confirm)").arguments("<firstName> <lastName> <email>").option("--send-email","If you want to send the email when inviting the user").option("--admin","If the user you are inviting is an admin").addOption(new Gn("-r, --role <role>","Role of user").choices(["Practitioner","Patient","RelatedPerson"]).default("Practitioner")).action(async(e,t,r,s)=>{let o=await x(s),i=o.getActiveLogin();if(!i)throw new Error("Unauthenticated: run `npx medplum login` to login");if(!i?.project?.reference)throw new Error("No current project to invite user to");let a=i.project.reference.split("/")[1],c={resourceType:s.role,firstName:e,lastName:t,email:r,sendEmail:!!s.sendEmail,admin:!!s.admin};await Vn(a,c,o)});async function Jn(e,t){let r=e.getLogins().find(s=>s.project.reference?.includes(t));if(!r)throw new Error(`Project ${t} not found. Make sure you are added as a user to this project`);await e.setActiveLogin(r),console.log(`Switched to project ${t}
22
+ `)}async function Vn(e,t,r){await r.invite(e,t),t.sendEmail&&console.log("Email sent"),console.log("See your users at https://app.medplum.com/admin/users")}var ws=new P("delete"),ys=new P("get"),Es=new P("patch"),vs=new P("post"),Ss=new P("put");ws.argument("<url>","Resource/$id").action(async(e,t)=>{let r=await x(t);se(await r.delete(Oe(r,e)))});ys.argument("<url>","Resource/$id").option("--as-transaction","Print out the bundle as a transaction type").action(async(e,t)=>{let r=await x(t),s=await r.get(Oe(r,e));t.asTransaction?se(Xn(s)):se(s)});Es.arguments("<url> <body>").action(async(e,t,r)=>{let s=await x(r);se(await s.patch(Oe(s,e),Rt(t)))});vs.arguments("<url> <body>").option("--prefer-async",'Sets the Prefer header to "respond-async"').action(async(e,t,r)=>{let s=await x(r),o=r.preferAsync?{Prefer:"respond-async"}:void 0;se(await s.post(Oe(s,e),Rt(t),void 0,{headers:o}))});Ss.arguments("<url> <body>").action(async(e,t,r)=>{let s=await x(r);se(await s.put(Oe(s,e),Rt(t)))});function Rt(e){if(e)try{return JSON.parse(e)}catch{return e}}function Oe(e,t){return["admin/","auth/","fhir/R4"].some(r=>t.startsWith(r))?t:e.fhirUrl(t).toString()}async function zn(e){let t=new P("medplum").description("Command to access Medplum CLI").option("--client-id <clientId>","FHIR server client id").option("--client-secret <clientSecret>","FHIR server client secret").option("--base-url <baseUrl>","FHIR server base URL, must be absolute").option("--token-url <tokenUrl>","FHIR server token URL, absolute or relative to base URL").option("--authorize-url <authorizeUrl>","FHIR server authorize URL, absolute or relative to base URL").option("--fhir-url, --fhir-url-path <fhirUrlPath>","FHIR server URL, absolute or relative to base URL").option("--scope <scope>","JWT scope").option("--access-token <accessToken>","Access token for token exchange authentication").option("--callback-url <callbackUrl>","Callback URL for authorization code flow").option("--subject <subject>","Subject for JWT authentication").option("--audience <audience>","Audience for JWT authentication").option("--issuer <issuer>","Issuer for JWT authentication").option("--private-key-path <privateKeyPath>","Private key path for JWT assertion").option("-p, --profile <profile>","Profile name").option("-v --verbose","Verbose output").addOption(new to("--auth-type <authType>","Type of authentication").choices(["basic","client-credentials","authorization-code","jwt-bearer","token-exchange","jwt-assertion"])).on("option:verbose",()=>{process.env.VERBOSE="1"});t.exitOverride(),t.version(eo),t.configureHelp({showGlobalOptions:!0}),O(t,Dr),O(t,Ur),O(t,_r),O(t,ys),O(t,vs),O(t,Es),O(t,Ss),O(t,ws),O(t,Pe),O(t,It),O(t,Je),O(t,ae),O(t,es),O(t,ts),O(t,rs),O(t,Te),O(t,un()),O(t,$t);try{await t.parseAsync(e)}catch(r){qn(r)}}function qn(e){let t=1,r=!0;if(e instanceof or&&(process.env.VERBOSE||(r=!1),t=e.exitCode),t!==0&&r){rt(e,!!process.env.VERBOSE);let s=e.cause;if(process.env.VERBOSE)if(Array.isArray(s))for(let o of s)rt(o,!0);else s instanceof Error&&rt(s,!0)}process.exit(t)}function rt(e,t=!1){if(t){console.error(e);return}e instanceof or?process.stderr.write(`${ot(e)}
23
+ `):process.stderr.write(`Error: ${ot(e)}
24
+ `)}async function Yn(){ro.config({quiet:!0}),await zn(process.argv)}import.meta.main&&Yn().catch(e=>{console.error("Unhandled error:",ot(e)),process.exit(1)});
25
25
  //# sourceMappingURL=index.mjs.map