@medplum/cli 2.2.10 → 3.0.0

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,14 +1,14 @@
1
1
  #!/usr/bin/env node
2
- "use strict";var bo=Object.create;var ne=Object.defineProperty;var Co=Object.getOwnPropertyDescriptor;var Ao=Object.getOwnPropertyNames;var Po=Object.getPrototypeOf,vo=Object.prototype.hasOwnProperty;var xo=(e,t,r)=>t in e?ne(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;var _o=(e,t)=>{for(var r in t)ne(e,r,{get:t[r],enumerable:!0})},vt=(e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of Ao(t))!vo.call(e,n)&&n!==r&&ne(e,n,{get:()=>t[n],enumerable:!(o=Co(t,n))||o.enumerable});return e};var T=(e,t,r)=>(r=e!=null?bo(Po(e)):{},vt(t||!e||!e.__esModule?ne(r,"default",{value:e,enumerable:!0}):r,e)),Io=e=>vt(ne({},"__esModule",{value:!0}),e);var f=(e,t,r)=>(xo(e,typeof t!="symbol"?t+"":t,r),r);var mi={};_o(mi,{main:()=>So,run:()=>Eo});module.exports=Io(mi);var $e=require("@medplum/core"),go=require("commander"),wo=T(require("dotenv"));var $=require("@medplum/core"),or=require("child_process"),nr=require("http"),ir=require("os");var It=require("@medplum/core");var xt=require("@medplum/core"),O=require("fs"),_t=require("os"),Be=require("path"),R=class extends xt.ClientStorage{constructor(t){super(),this.dirName=(0,Be.resolve)((0,_t.homedir)(),".medplum"),this.fileName=(0,Be.resolve)(this.dirName,t+".json")}clear(){this.writeFile({})}getString(t){return this.readFile()?.[t]}setString(t,r){let o=this.readFile()??{};r?o[t]=r:delete o[t],this.writeFile(o)}getObject(t){let r=this.getString(t);return r?JSON.parse(r):void 0}setObject(t,r){this.setString(t,r?JSON.stringify(r):void 0)}readFile(){if((0,O.existsSync)(this.fileName))return JSON.parse((0,O.readFileSync)(this.fileName,"utf8"))}writeFile(t){(0,O.existsSync)(this.dirName)||(0,O.mkdirSync)(this.dirName),(0,O.writeFileSync)(this.fileName,JSON.stringify(t,null,2),"utf8")}};async function l(e,t=!0){let r=e.profile??"default",o=new R(r),n=o.getObject("options");if(r!=="default"&&!n)throw new Error(`Profile "${r}" does not exist`);let{baseUrl:a,fhirUrlPath:s,accessToken:c,tokenUrl:p,authorizeUrl:g,clientId:b,clientSecret:k}=To(e,o),ge=e.fetch??fetch,we=new It.MedplumClient({fetch:ge,baseUrl:a,tokenUrl:p,fhirUrlPath:s,authorizeUrl:g,storage:o,onUnauthenticated:Ko,verbose:e.verbose});return t&&(c?we.setAccessToken(c):b&&k&&(we.setBasicAuth(b,k),n?.authType!=="basic"&&await we.startClientLogin(b,k))),we}function To(e,t){let r=t.getObject("options"),o=e.baseUrl??r?.baseUrl??process.env.MEDPLUM_BASE_URL??"https://api.medplum.com/",n=e.fhirUrlPath??r?.fhirUrlPath??process.env.MEDPLUM_FHIR_URL_PATH,a=e.accessToken??r?.accessToken??process.env.MEDPLUM_CLIENT_ACCESS_TOKEN,s=e.tokenUrl??r?.tokenUrl??process.env.MEDPLUM_TOKEN_URL,c=e.authorizeUrl??r?.authorizeUrl??process.env.MEDPLUM_AUTHORIZE_URL,p=e.clientId??r?.clientId??process.env.MEDPLUM_CLIENT_ID,g=e.clientSecret??r?.clientSecret??process.env.MEDPLUM_CLIENT_SECRET;return{baseUrl:o,fhirUrlPath:n,accessToken:a,tokenUrl:s,authorizeUrl:c,clientId:p,clientSecret:g}}function Ko(){console.log("Unauthenticated: run `npx medplum login` to sign in")}var Se=require("commander");function d(e){return new Se.Command(e).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("--audience <audience>","Audience for JWT assertion").option("-p, --profile <profile>","Profile name").option("-v --verbose","Verbose output").addOption(new Se.Option("--auth-type <authType>","Type of authentication").choices(["basic","client-credentials","authorization-code","jwt-bearer","token-exchange","jwt-assertion"]))}var G=require("@medplum/core"),te=require("crypto"),V=require("fs");var Tt=require("buffer");var C=new TextEncoder,S=new TextDecoder,Ei=2**32;function K(...e){let t=e.reduce((n,{length:a})=>n+a,0),r=new Uint8Array(t),o=0;return e.forEach(n=>{r.set(n,o),o+=n.length}),r}var A=e=>Tt.Buffer.from(e).toString("base64url");var q=class extends Error{constructor(r){super(r);f(this,"code","ERR_JOSE_GENERIC");this.name=this.constructor.name,Error.captureStackTrace?.(this,this.constructor)}static get code(){return"ERR_JOSE_GENERIC"}};var m=class extends q{constructor(){super(...arguments);f(this,"code","ERR_JOSE_NOT_SUPPORTED")}static get code(){return"ERR_JOSE_NOT_SUPPORTED"}};var P=class extends q{constructor(){super(...arguments);f(this,"code","ERR_JWS_INVALID")}static get code(){return"ERR_JWS_INVALID"}},N=class extends q{constructor(){super(...arguments);f(this,"code","ERR_JWT_INVALID")}static get code(){return"ERR_JWT_INVALID"}};var Ht=T(require("util"),1),v=e=>Ht.types.isKeyObject(e);var kt=T(require("crypto"),1),Rt=T(require("util"),1),Ro=kt.webcrypto,Ot=Ro,E=e=>Rt.types.isCryptoKey(e);function D(e,t="algorithm.name"){return new TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`)}function Ee(e,t){return e.name===t}function je(e){return parseInt(e.name.slice(4),10)}function Oo(e){switch(e){case"ES256":return"P-256";case"ES384":return"P-384";case"ES512":return"P-521";default:throw new Error("unreachable")}}function Do(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 o=t.pop();r+=`one of ${t.join(", ")}, or ${o}.`}else t.length===2?r+=`one of ${t[0]} or ${t[1]}.`:r+=`${t[0]}.`;throw new TypeError(r)}}function Dt(e,t,...r){switch(t){case"HS256":case"HS384":case"HS512":{if(!Ee(e.algorithm,"HMAC"))throw D("HMAC");let o=parseInt(t.slice(2),10);if(je(e.algorithm.hash)!==o)throw D(`SHA-${o}`,"algorithm.hash");break}case"RS256":case"RS384":case"RS512":{if(!Ee(e.algorithm,"RSASSA-PKCS1-v1_5"))throw D("RSASSA-PKCS1-v1_5");let o=parseInt(t.slice(2),10);if(je(e.algorithm.hash)!==o)throw D(`SHA-${o}`,"algorithm.hash");break}case"PS256":case"PS384":case"PS512":{if(!Ee(e.algorithm,"RSA-PSS"))throw D("RSA-PSS");let o=parseInt(t.slice(2),10);if(je(e.algorithm.hash)!==o)throw D(`SHA-${o}`,"algorithm.hash");break}case"EdDSA":{if(e.algorithm.name!=="Ed25519"&&e.algorithm.name!=="Ed448")throw D("Ed25519 or Ed448");break}case"ES256":case"ES384":case"ES512":{if(!Ee(e.algorithm,"ECDSA"))throw D("ECDSA");let o=Oo(t);if(e.algorithm.namedCurve!==o)throw D(o,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}Do(e,r)}function Wt(e,t,...r){if(r.length>2){let o=r.pop();e+=`one of type ${r.join(", ")}, or ${o}.`}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&&t.constructor.name&&(e+=` Received an instance of ${t.constructor.name}`),e}var x=(e,...t)=>Wt("Key must be ",e,...t);function Ge(e,t,...r){return Wt(`Key for the ${e} algorithm must be `,t,...r)}var Ve=e=>v(e)||E(e),u=["KeyObject"];(globalThis.CryptoKey||Ot?.CryptoKey)&&u.push("CryptoKey");var Uo=(...e)=>{let t=e.filter(Boolean);if(t.length===0||t.length===1)return!0;let r;for(let o of t){let n=Object.keys(o);if(!r||r.size===0){r=new Set(n);continue}for(let a of n){if(r.has(a))return!1;r.add(a)}}return!0},Y=Uo;function Lo(e){return typeof e=="object"&&e!==null}function w(e){if(!Lo(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}var be=require("crypto"),Nt=require("util");var Jt=require("crypto");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 m("Unsupported key curve for this operation")}},Bo=(e,t)=>{let r;if(E(e))r=Jt.KeyObject.from(e);else if(v(e))r=e;else throw new TypeError(x(e,...u));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 o=r.asymmetricKeyDetails.namedCurve;return t?o:$o(o)}default:throw new TypeError("Invalid asymmetric key type for this operation")}},ze=Bo;var Da=(0,Nt.promisify)(be.generateKeyPair);var Lt=require("util"),Xe=require("crypto");var qa=(0,Lt.promisify)(Xe.pbkdf2);var ae=require("crypto"),$t=require("util");var Ce=(e,t)=>{let{modulusLength:r}=e.asymmetricKeyDetails;if(typeof r!="number"||r<2048)throw new TypeError(`${t} requires key modulusLength to be 2048 bits or larger`)};var is=(0,$t.deprecate)(()=>ae.constants.RSA_PKCS1_PADDING,'The RSA1_5 "alg" (JWE Algorithm) is deprecated and will be removed in the next major revision.');var Go=(e,t)=>{if(!(t instanceof Uint8Array)){if(!Ve(t))throw new TypeError(Ge(e,t,...u,"Uint8Array"));if(t.type!=="secret")throw new TypeError(`${u.join(" or ")} instances for symmetric algorithms must be of type "secret"`)}},Vo=(e,t,r)=>{if(!Ve(t))throw new TypeError(Ge(e,t,...u));if(t.type==="secret")throw new TypeError(`${u.join(" or ")} instances for asymmetric algorithms must not be of type "secret"`);if(r==="sign"&&t.type==="public")throw new TypeError(`${u.join(" or ")} instances for asymmetric algorithm signing must be of type "private"`);if(r==="decrypt"&&t.type==="public")throw new TypeError(`${u.join(" or ")} instances for asymmetric algorithm decryption must be of type "private"`);if(t.algorithm&&r==="verify"&&t.type==="private")throw new TypeError(`${u.join(" or ")} instances for asymmetric algorithm verifying must be of type "public"`);if(t.algorithm&&r==="encrypt"&&t.type==="private")throw new TypeError(`${u.join(" or ")} instances for asymmetric algorithm encryption must be of type "public"`)},zo=(e,t,r)=>{e.startsWith("HS")||e==="dir"||e.startsWith("PBES2")||/^A\d{3}(?:GCM)?KW$/.test(e)?Go(e,t):Vo(e,t,r)},ce=zo;function tn(e,t,r,o,n){if(n.crit!==void 0&&o.crit===void 0)throw new e('"crit" (Critical) Header Parameter MUST be integrity protected');if(!o||o.crit===void 0)return new Set;if(!Array.isArray(o.crit)||o.crit.length===0||o.crit.some(s=>typeof s!="string"||s.length===0))throw new e('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');let a;r!==void 0?a=new Map([...Object.entries(r),...t.entries()]):a=t;for(let s of o.crit){if(!a.has(s))throw new m(`Extension Header Parameter "${s}" is not recognized`);if(n[s]===void 0)throw new e(`Extension Header Parameter "${s}" is missing`);if(a.get(s)&&o[s]===void 0)throw new e(`Extension Header Parameter "${s}" MUST be integrity protected`)}return new Set(o.crit)}var Z=tn;var sn=Symbol();var et=T(require("crypto"),1),Vt=require("util");function Ae(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"EdDSA":return;default:throw new m(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}var Ye=require("crypto");var cn={padding:Ye.constants.RSA_PKCS1_PSS_PADDING,saltLength:Ye.constants.RSA_PSS_SALTLEN_DIGEST},dn=new Map([["ES256","P-256"],["ES256K","secp256k1"],["ES384","P-384"],["ES512","P-521"]]);function Pe(e,t){switch(e){case"EdDSA":if(!["ed25519","ed448"].includes(t.asymmetricKeyType))throw new TypeError("Invalid key for this operation, its asymmetricKeyType must be ed25519 or ed448");return t;case"RS256":case"RS384":case"RS512":if(t.asymmetricKeyType!=="rsa")throw new TypeError("Invalid key for this operation, its asymmetricKeyType must be rsa");return Ce(t,e),t;case"PS256":case"PS384":case"PS512":if(t.asymmetricKeyType==="rsa-pss"){let{hashAlgorithm:r,mgf1HashAlgorithm:o,saltLength:n}=t.asymmetricKeyDetails,a=parseInt(e.slice(-3),10);if(r!==void 0&&(r!==`sha${a}`||o!==r))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>a>>3)throw new TypeError(`Invalid key for this operation, its RSA-PSS parameter saltLength does not meet the requirements of "alg" ${e}`)}else if(t.asymmetricKeyType!=="rsa")throw new TypeError("Invalid key for this operation, its asymmetricKeyType must be rsa or rsa-pss");return Ce(t,e),{key:t,...cn};case"ES256":case"ES256K":case"ES384":case"ES512":{if(t.asymmetricKeyType!=="ec")throw new TypeError("Invalid key for this operation, its asymmetricKeyType must be ec");let r=ze(t),o=dn.get(e);if(r!==o)throw new TypeError(`Invalid key curve for the algorithm, its curve must be ${o}, got ${r}`);return{dsaEncoding:"ieee-p1363",key:t}}default:throw new m(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}var xe=T(require("crypto"),1),Gt=require("util");function Ze(e){switch(e){case"HS256":return"sha256";case"HS384":return"sha384";case"HS512":return"sha512";default:throw new m(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}var de=require("crypto");function ve(e,t,r){if(t instanceof Uint8Array){if(!e.startsWith("HS"))throw new TypeError(x(t,...u));return(0,de.createSecretKey)(t)}if(t instanceof de.KeyObject)return t;if(E(t))return Dt(t,e,r),de.KeyObject.from(t);throw new TypeError(x(t,...u,"Uint8Array"))}var pn=(0,Gt.promisify)(xe.sign),mn=async(e,t,r)=>{let o=ve(e,t,"sign");if(e.startsWith("HS")){let n=xe.createHmac(Ze(e),o);return n.update(r),n.digest()}return pn(Ae(e),r,Pe(e,o))},Qe=mn;var Fd=(0,Vt.promisify)(et.verify);var W=e=>Math.floor(e.getTime()/1e3);var un=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i,pe=e=>{let t=un.exec(e);if(!t||t[4]&&t[1])throw new TypeError("Invalid time period format");let r=parseFloat(t[2]),o=t[3].toLowerCase(),n;switch(o){case"sec":case"secs":case"second":case"seconds":case"s":n=Math.round(r);break;case"minute":case"minutes":case"min":case"mins":case"m":n=Math.round(r*60);break;case"hour":case"hours":case"hr":case"hrs":case"h":n=Math.round(r*3600);break;case"day":case"days":case"d":n=Math.round(r*86400);break;case"week":case"weeks":case"w":n=Math.round(r*604800);break;default:n=Math.round(r*31557600);break}return t[1]==="-"||t[4]==="ago"?-n:n};var Q=class{constructor(t){f(this,"_payload");f(this,"_protectedHeader");f(this,"_unprotectedHeader");if(!(t instanceof Uint8Array))throw new TypeError("payload must be an instance of Uint8Array");this._payload=t}setProtectedHeader(t){if(this._protectedHeader)throw new TypeError("setProtectedHeader can only be called once");return this._protectedHeader=t,this}setUnprotectedHeader(t){if(this._unprotectedHeader)throw new TypeError("setUnprotectedHeader can only be called once");return this._unprotectedHeader=t,this}async sign(t,r){if(!this._protectedHeader&&!this._unprotectedHeader)throw new P("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");if(!Y(this._protectedHeader,this._unprotectedHeader))throw new P("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let o={...this._protectedHeader,...this._unprotectedHeader},n=Z(P,new Map([["b64",!0]]),r?.crit,this._protectedHeader,o),a=!0;if(n.has("b64")&&(a=this._protectedHeader.b64,typeof a!="boolean"))throw new P('The "b64" (base64url-encode payload) Header Parameter must be a boolean');let{alg:s}=o;if(typeof s!="string"||!s)throw new P('JWS "alg" (Algorithm) Header Parameter missing or invalid');ce(s,t,"sign");let c=this._payload;a&&(c=C.encode(A(c)));let p;this._protectedHeader?p=C.encode(A(JSON.stringify(this._protectedHeader))):p=C.encode("");let g=K(p,C.encode("."),c),b=await Qe(s,t,g),k={signature:A(b),payload:""};return a&&(k.payload=S.decode(c)),this._unprotectedHeader&&(k.header=this._unprotectedHeader),this._protectedHeader&&(k.protected=S.decode(p)),k}};var me=class{constructor(t){f(this,"_flattened");this._flattened=new Q(t)}setProtectedHeader(t){return this._flattened.setProtectedHeader(t),this}async sign(t,r){let o=await this._flattened.sign(t,r);if(o.payload===void 0)throw new TypeError("use the flattened module for creating JWS with b64: false");return`${o.protected}.${o.payload}.${o.signature}`}};function j(e,t){if(!Number.isFinite(t))throw new TypeError(`Invalid ${e} input`);return t}var ee=class{constructor(t={}){f(this,"_payload");if(!w(t))throw new TypeError("JWT Claims Set MUST be an object");this._payload=t}setIssuer(t){return this._payload={...this._payload,iss:t},this}setSubject(t){return this._payload={...this._payload,sub:t},this}setAudience(t){return this._payload={...this._payload,aud:t},this}setJti(t){return this._payload={...this._payload,jti:t},this}setNotBefore(t){return typeof t=="number"?this._payload={...this._payload,nbf:j("setNotBefore",t)}:t instanceof Date?this._payload={...this._payload,nbf:j("setNotBefore",W(t))}:this._payload={...this._payload,nbf:W(new Date)+pe(t)},this}setExpirationTime(t){return typeof t=="number"?this._payload={...this._payload,exp:j("setExpirationTime",t)}:t instanceof Date?this._payload={...this._payload,exp:j("setExpirationTime",W(t))}:this._payload={...this._payload,exp:W(new Date)+pe(t)},this}setIssuedAt(t){return typeof t>"u"?this._payload={...this._payload,iat:W(new Date)}:t instanceof Date?this._payload={...this._payload,iat:j("setIssuedAt",W(t))}:typeof t=="string"?this._payload={...this._payload,iat:j("setIssuedAt",W(new Date)+pe(t))}:this._payload={...this._payload,iat:j("setIssuedAt",t)},this}};var le=class extends ee{constructor(){super(...arguments);f(this,"_protectedHeader")}setProtectedHeader(r){return this._protectedHeader=r,this}async sign(r,o){let n=new me(C.encode(JSON.stringify(this._payload)));if(n.setProtectedHeader(this._protectedHeader),Array.isArray(this._protectedHeader?.crit)&&this._protectedHeader.crit.includes("b64")&&this._protectedHeader.b64===!1)throw new N("JWTs MUST NOT use unencoded payload");return n.sign(r,o)}};var En;(typeof navigator>"u"||!navigator.userAgent?.startsWith?.("Mozilla/5.0 "))&&(En="jose/v5.2.0");var tt=require("crypto"),qt=require("util");var el=(0,qt.promisify)(tt.generateKeyPair);var L=require("path"),Yt=T(require("tar"));function M(e){console.log(JSON.stringify(e,null,2))}async function rt(e,t,r){let o=t.source,n=it(o);if(n)try{console.log("Saving source code...");let a=await e.createAttachment(n,(0,L.basename)(o),vn(o));console.log("Updating bot.....");let s=await e.updateResource({...r,sourceCode:a});console.log("Success! New bot version: "+s.meta?.versionId)}catch(a){console.log("Update error: ",a)}}async function ot(e,t,r){let o=t.dist??t.source,n=it(o);if(n)try{console.log("Deploying bot...");let a=await e.post(e.fhirUrl("Bot",r.id,"$deploy"),{code:n,filename:(0,L.basename)(o)});console.log("Deploy result: "+a.issue?.[0]?.details?.text)}catch(a){console.log("Deploy error: ",a)}}async function nt(e,t,r,o,n,a,s){try{let c={name:t,description:"",runtimeVersion:a},p=await e.post("admin/projects/"+r+"/bot",c),g=await e.readResource("Bot",p.id),b={name:t,id:p.id,source:o,dist:n};await rt(e,b,g),await ot(e,b,g),console.log(`Success! Bot created: ${g.id}`),s&&An(b)}catch(c){console.log("Error while creating new bot: "+c)}}function Zt(e){let t=new RegExp("^"+Pn(e).replace(/\\\*/g,".*")+"$"),r=re()?.bots?.filter(o=>t.test(o.name));return r||[]}function re(e){let t=e?`medplum.${e}.config.json`:"medplum.config.json",r=it(t);if(r)return JSON.parse(r)}function it(e){let t=(0,L.resolve)(process.cwd(),e);return(0,V.existsSync)(t)?(0,V.readFileSync)(t,"utf8"):""}function An(e){let t=re()??{};t.bots||(t.bots=[]),t.bots.push(e),(0,V.writeFileSync)("medplum.config.json",JSON.stringify(t,null,2),"utf8"),console.log(`Bot added to config: ${e.id}`)}function Pn(e){return e.replace(/[/\-\\^$*+?.()|[\]{}]/g,"\\$&")}function Qt(e){let o=0,n=0;return Yt.default.x({cwd:e,filter:(a,s)=>{if(o++,o>100)throw new Error("Tar extractor reached max number of files");if(n+=s.size,n>10485760)throw new Error("Tar extractor reached max size");return!0}})}function at(){return{extension:[{url:"http://hl7.org/fhir/StructureDefinition/data-absent-reason",valueCode:"unsupported"}]}}function vn(e){let t=(0,L.extname)(e).toLowerCase();return[".cjs",".mjs",".js"].includes(t)?G.ContentType.JAVASCRIPT:[".cts",".mts",".ts"].includes(t)?G.ContentType.TYPESCRIPT:G.ContentType.TEXT}function _e(e,t){let r=new R(e),o={name:e,...t};return r.setObject("options",o),console.log(`${e} profile created`),o}function er(e){return new R(e).getObject("options")}async function tr(e,t){let r={typ:"JWT",alg:"HS256"},o=Math.floor(Date.now()/1e3),n={aud:`${t.baseUrl}${t.audience}`,iss:t.issuer,sub:t.subject,nbf:o,iat:o,exp:o+604800},a=(0,G.encodeBase64)(JSON.stringify(r)),s=(0,G.encodeBase64)(JSON.stringify(n)),c=`${a}.${s}`,p=(0,te.createHmac)("sha256",t.clientSecret).update(c).digest("base64url"),g=`${c}.${p}`;await e.startJwtBearerLogin(t.clientId,g,t.scope??"")}async function rr(e,t){let r=(0,te.createPrivateKey)((0,V.readFileSync)((0,L.resolve)(t.privateKeyPath))),o=await new le({}).setProtectedHeader({alg:"RS384",typ:"JWT"}).setIssuer(t.clientId).setSubject(t.clientId).setAudience(`${t.baseUrl}${t.audience}`).setJti((0,te.randomBytes)(16).toString("hex")).setIssuedAt().setExpirationTime("5m").sign(r);await e.startJwtAssertionLogin(o)}var ar="medplum-cli",sr="http://localhost:9615",st=d("login"),ct=d("whoami");st.action(async e=>{let t=e.profile??"default",r=_e(t,e),o=await l(e,!1);await xn(o,r)});ct.action(async e=>{let t=await l(e);Tn(t)});async function xn(e,t){switch(t?.authType??"authorization-code"){case"authorization-code":await Kn(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 tr(e,t);break;case"jwt-assertion":await rr(e,t);break}console.log("Login successful")}async function _n(e){let t=(0,nr.createServer)(async(r,o)=>{let n=new URL(r.url,"http://localhost:9615"),a=n.searchParams.get("code");if(n.pathname==="/"&&a)try{let s=await e.processCode(a,{clientId:ar,redirectUri:sr});o.writeHead(200,{"Content-Type":$.ContentType.TEXT}),o.end(`Signed in as ${(0,$.getDisplayString)(s)}. You may close this window.`)}catch(s){o.writeHead(400,{"Content-Type":$.ContentType.TEXT}),o.end(`Error: ${(0,$.normalizeErrorString)(s)}`)}finally{t.close()}else o.writeHead(404,{"Content-Type":$.ContentType.TEXT}),o.end("Not found")}).listen(9615)}async function In(e){let t=(0,ir.platform)(),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)}(0,or.exec)(r)}function Tn(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 Kn(e){await _n(e);let t=new URL(e.getAuthorizeUrl());t.searchParams.set("client_id",ar),t.searchParams.set("redirect_uri",sr),t.searchParams.set("scope","openid"),t.searchParams.set("response_type","code"),t.searchParams.set("prompt","login"),await In(t.toString())}var Kr=require("commander");var J=require("@aws-sdk/client-cloudformation"),Te=require("@aws-sdk/client-cloudfront"),dr=require("@aws-sdk/client-ecs"),pr=require("@aws-sdk/client-s3"),Ie=new J.CloudFormationClient({}),Hn=new Te.CloudFrontClient({region:"us-east-1"}),mr=new dr.ECSClient({}),ue=new pr.S3Client({}),kn="medplum:environment";async function dt(){return(await Ie.send(new J.ListStacksCommand({}))).StackSummaries?.filter(t=>t.StackName&&t.StackStatus!=="DELETE_COMPLETE")||[]}async function B(e){let t=await dt();for(let r of t){let o=r.StackName,n=await pt(o);if(n?.tag===e)return n}}async function pt(e){let t={};return await cr(Ie,e,t),await Ie.config.region()!=="us-east-1"&&await cr(new J.CloudFormationClient({region:"us-east-1"}),e+"-us-east-1",t),t}async function cr(e,t,r){let o=new J.DescribeStacksCommand({StackName:t}),a=(await e.send(o))?.Stacks?.[0],s=a?.Tags?.find(p=>p.Key===kn);if(!s)return;let c=await e.send(new J.DescribeStackResourcesCommand({StackName:t}));if(c.StackResources){e===Ie&&(r.stack=a,r.tag=s.Value);for(let p of c.StackResources)Rn(p,r)}}function Rn(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 Ke(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: ${mt(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 mt(e){return e?.PhysicalResourceId?.split("/")?.pop()||""}async function He(e){let t=await Hn.send(new Te.CreateInvalidationCommand({DistributionId:e,InvalidationBatch:{CallerReference:`invalidate-all-${Date.now()}`,Paths:{Quantity:1,Items:["/*"]}}}));console.log(`Created invalidation with ID: ${t.Invalidation?.Id}`)}async function lr(e){let t=await B(e);if(!t){console.log("Stack not found");return}Ke(t)}var z=require("@aws-sdk/client-acm"),Oe=require("@aws-sdk/client-cloudfront"),oe=require("@aws-sdk/client-ssm"),De=require("@aws-sdk/client-sts"),fr=require("@medplum/core"),he=require("crypto"),We=require("fs"),hr=require("path"),yr=T(require("readline")),On=e=>`${e}DomainName`,gr=e=>`${e}SslCertArn`,ke;async function wr(){let e={apiPort:8103,region:"us-east-1"};ke=yr.default.createInterface({input:process.stdin,output:process.stdout}),h("MEDPLUM"),i("This tool prepares the necessary prerequisites for deploying Medplum in your AWS account."),i(""),i("Most Medplum infrastructure is deployed using the AWS CDK."),i("However, some AWS resources must be created manually, such as email addresses and SSL certificates."),i("This tool will help you create those resources."),i(""),i("Upon completion, this tool will:"),i(" 1. Generate a Medplum CDK config file (i.e., medplum.demo.config.json)"),i(" 2. Optionally generate an AWS CloudFront signing key"),i(" 3. Optionally request SSL certificates from AWS Certificate Manager"),i(" 4. Optionally write server config settings to AWS Parameter Store"),i(""),i("The Medplum infra config file is an input to the Medplum CDK."),i("The Medplum CDK will create and manage the necessary AWS resources."),i(""),i("We will ask a series of questions to generate your infra config file."),i("Some questions have predefined options in [square brackets]."),i("Some questions have default values in (parentheses), which you can accept by pressing Enter."),i("Press Ctrl+C at any time to exit.");let t=await Dn(e.region);t||(i("It appears that you do not have AWS credentials configured."),i("AWS credentials are not strictly required, but will enable some additional features."),i("If you intend to use AWS credentials, please configure them now."),await lt("Do you want to continue without AWS credentials?")),h("ENVIRONMENT NAME"),i('Medplum deployments have a short environment name such as "prod", "staging", "alice", or "demo".'),i("The environment name is used in multiple places:"),i(" 1. As part of config file names (i.e., medplum.demo.config.json)"),i(" 2. As the base of CloudFormation stack names (i.e., MedplumDemo)"),i(" 3. AWS Parameter Store keys (i.e., /medplum/demo/...)"),e.name=await _("What is your environment name?","demo"),i('Using environment name "'+e.name+'"...'),h("CONFIG FILE"),i("Medplum Infrastructure will create a config file in the current directory.");let r=await _("What is the config file name?",`medplum.${e.name}.config.json`);(0,We.existsSync)(r)&&(i("Config file already exists."),await lt("Do you want to overwrite the config file?")),i('Using config file "'+r+'"...'),y(r,e),h("AWS REGION"),i("Most Medplum resources will be created in a single AWS region."),e.region=await _("Enter your AWS region:","us-east-1"),y(r,e),h("AWS ACCOUNT NUMBER"),i("Medplum Infrastructure will use your AWS account number to create AWS resources."),t&&i("Using the AWS CLI, your current account ID is: "+t),e.accountNumber=await _("What is your AWS account number?",t),y(r,e),h("STACK NAME"),i("Medplum will create a CloudFormation stack to manage AWS resources."),i("AWS CloudFormation stack names ");let o="Medplum"+e.name.charAt(0).toUpperCase()+e.name.slice(1);for(e.stackName=await _("Enter your CloudFormation stack name?",o),y(r,e),h("BASE DOMAIN NAME"),i("Please enter the base domain name for your Medplum deployment."),i(""),i("Medplum deploys multiple subdomains for various services."),i(""),i('For example, "api." for the REST API and "app." for the web application.'),i("The base domain name is the common suffix for all subdomains."),i(""),i('For example, if your base domain name is "example.com",'),i('then the REST API will be "api.example.com".'),i(""),i('The base domain should include the TLD (i.e., ".com", ".org", ".net").'),i(""),i("Note that you must own the base domain, and it must use Route53 DNS.");!e.domainName;)e.domainName=await _("Enter your base domain name:");y(r,e),h("SUPPORT EMAIL"),i("Medplum sends transactional emails to users."),i("For example, emails to new users or for password reset."),i("Medplum will use the support email address to send these emails."),i("Note that you must verify the support email address in SES.");let n=await _("Enter your support email address:");h("API DOMAIN NAME"),i("Medplum deploys a REST API for the backend services."),e.apiDomainName=await _("Enter your REST API domain name:","api."+e.domainName),e.baseUrl=`https://${e.apiDomainName}/`,y(r,e),h("APP DOMAIN NAME"),i("Medplum deploys a web application for the user interface."),e.appDomainName=await _("Enter your web application domain name:","app."+e.domainName),y(r,e),h("STORAGE DOMAIN NAME"),i("Medplum deploys a storage service for file uploads."),e.storageDomainName=await _("Enter your storage domain name:","storage."+e.domainName),y(r,e),h("STORAGE BUCKET"),i("Medplum uses an S3 bucket to store binary content such as file uploads."),i("Medplum will create a the S3 bucket as part of the CloudFormation stack."),e.storageBucketName=await _("Enter your storage bucket name:",e.storageDomainName),y(r,e),h("MAX AVAILABILITY ZONES"),i("Medplum API servers can be deployed in multiple availability zones."),i("This provides redundancy and high availability."),i("However, it also increases the cost of the deployment."),i("If you want to use all availability zones, choose a large number such as 99."),i("If you want to restrict the number, for example to manage EIP limits,"),i("then choose a small number such as 2 or 3."),e.maxAzs=await fe("Enter the maximum number of availability zones:",[2,3,99],2),h("DATABASE INSTANCES"),i("Medplum uses a relational database to store data."),i("You can set up your own database,"),i("or Medplum can create a new RDS database as part of the CloudFormation stack."),await Re("Do you want to create a new RDS database as part of the CloudFormation stack?")?(i("Medplum will create a new RDS database as part of the CloudFormation stack."),i(""),i("If you need high availability, you can choose multiple instances."),i("Use 1 for a single instance, or 2 for a primary and a standby."),e.rdsInstances=await fe("Enter the number of database instances:",[1,2],1)):(i("Medplum will not create a new RDS database."),i("Please create a new RDS database and enter the database name, username, and password."),i('Set the AWS Secrets Manager secret ARN in the config file in the "rdsSecretsArn" setting.'),e.rdsSecretsArn="TODO"),y(r,e),h("SERVER INSTANCES"),i("Medplum uses AWS Fargate to run the API servers."),i("Medplum will create a new Fargate cluster as part of the CloudFormation stack."),i("Fargate will automatically scale the number of servers up and down."),i("If you need high availability, you can choose multiple instances."),e.desiredServerCount=await fe("Enter the number of server instances:",[1,2,3,4,6,8],1),y(r,e),h("SERVER MEMORY"),i("You can choose the amount of memory for each server instance."),i("The default is 512 MB, which is sufficient for getting started."),i("Note that only certain CPU units are compatible with memory units."),i('Consult AWS Fargate "Task Definition Parameters" for more information.'),e.serverMemory=await fe("Enter the server memory (MB):",[512,1024,2048,4096,8192,16384],512),y(r,e),h("SERVER CPU"),i("You can choose the amount of CPU for each server instance."),i("CPU is expressed as an integer using AWS CPU units"),i("The default is 256, which is sufficient for getting started."),i("Note that only certain CPU units are compatible with memory units."),i('Consult AWS Fargate "Task Definition Parameters" for more information.'),e.serverCpu=await fe("Enter the server CPU:",[256,512,1024,2048,4096,8192,16384],256),y(r,e),h("SERVER IMAGE"),i("Medplum uses Docker images for the API servers."),i("You can choose the image to use for the servers."),i("Docker images can be loaded from either Docker Hub or AWS ECR."),i("The default is the latest Medplum release."),e.serverImage=await _("Enter the server image:","medplum/medplum-server:latest"),y(r,e),h("SIGNING KEY"),i("Medplum uses AWS CloudFront Presigned URLs for binary content such as file uploads.");let a=await Nn(e.stackName+"SigningKey");a?(e.signingKeyId=a.keyId,e.storagePublicKey=a.publicKey,y(r,e)):(i("Unable to generate signing key."),i("Please manually create a signing key and enter the key ID and public key in the config file."),i('You must set the "signingKeyId", "signingKey", and "signingKeyPassphrase" settings.')),h("SSL CERTIFICATES"),i("Medplum will now check for existing SSL certificates for the subdomains.");let s=await Wn(e.region);i("Found "+s.length+" certificate(s).");for(let{region:p,certName:g}of[{region:e.region,certName:"api"},{region:"us-east-1",certName:"app"},{region:"us-east-1",certName:"storage"}]){i("");let b=await Mn(e,s,p,g);e[gr(g)]=b,y(r,e)}h("AWS PARAMETER STORE"),i("Medplum uses AWS Parameter Store to store sensitive configuration values."),i("These values will be encrypted at rest."),i(`The values will be stored in the "/medplum/${e.name}" path.`);let c={port:e.apiPort,baseUrl:e.baseUrl,appBaseUrl:`https://${e.appDomainName}/`,storageBaseUrl:`https://${e.storageDomainName}/binary/`,binaryStorage:`s3:${e.storageBucketName}`,supportEmail:n};if(a&&(c.signingKeyId=a.keyId,c.signingKey=a.privateKey,c.signingKeyPassphrase=a.passphrase),i(JSON.stringify({...c,signingKey:"****",signingKeyPassphrase:"****"},null,2)),await Re("Do you want to store these values in AWS Parameter Store?"))await $n(e.region,`/medplum/${e.name}/`,c);else{let p=r.replace(".json",".server.json");y(p,c),i("Skipping AWS Parameter Store."),i("Writing values to local config file: "+p),i("Please add these values to AWS Parameter Store manually.")}h("DONE!"),i("Medplum configuration complete."),i("You can now proceed to deploying the Medplum infrastructure with CDK."),i("Run:"),i(""),i(` npx cdk bootstrap -c config=${r}`),i(` npx cdk synth -c config=${r}`),e.region==="us-east-1"?i(` npx cdk deploy -c config=${r}`):i(` npx cdk deploy -c config=${r} --all`),i(""),i("See Medplum documentation for more information:"),i(""),i(" https://www.medplum.com/docs/self-hosting/install-on-aws"),i(""),ke.close()}function i(e){ke.write(e+`
3
- `)}function h(e){i(`
2
+ "use strict";var yn=Object.create;var Pe=Object.defineProperty;var gn=Object.getOwnPropertyDescriptor;var wn=Object.getOwnPropertyNames;var En=Object.getPrototypeOf,Sn=Object.prototype.hasOwnProperty;var An=(e,t,r)=>t in e?Pe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;var bn=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),Cn=(e,t)=>{for(var r in t)Pe(e,r,{get:t[r],enumerable:!0})},pr=(e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of wn(t))!Sn.call(e,n)&&n!==r&&Pe(e,n,{get:()=>t[n],enumerable:!(o=gn(t,n))||o.enumerable});return e};var H=(e,t,r)=>(r=e!=null?yn(En(e)):{},pr(t||!e||!e.__esModule?Pe(r,"default",{value:e,enumerable:!0}):r,e)),vn=e=>pr(Pe({},"__esModule",{value:!0}),e);var P=(e,t,r)=>(An(e,typeof t!="symbol"?t+"":t,r),r);var Ao=bn((u,So)=>{"use strict";u=So.exports=m;var g;typeof process=="object"&&process.env&&process.env.NODE_DEBUG&&/\bsemver\b/i.test(process.env.NODE_DEBUG)?g=function(){var e=Array.prototype.slice.call(arguments,0);e.unshift("SEMVER"),console.log.apply(console,e)}:g=function(){};u.SEMVER_SPEC_VERSION="2.0.0";var Me=256,mt=Number.MAX_SAFE_INTEGER||9007199254740991,jt=16,Yi=Me-6,ve=u.re=[],y=u.safeRe=[],p=u.src=[],a=u.tokens={},wo=0;function f(e){a[e]=wo++}var Xt="[a-zA-Z0-9-]",Vt=[["\\s",1],["\\d",Me],[Xt,Yi]];function Ue(e){for(var t=0;t<Vt.length;t++){var r=Vt[t][0],o=Vt[t][1];e=e.split(r+"*").join(r+"{0,"+o+"}").split(r+"+").join(r+"{1,"+o+"}")}return e}f("NUMERICIDENTIFIER");p[a.NUMERICIDENTIFIER]="0|[1-9]\\d*";f("NUMERICIDENTIFIERLOOSE");p[a.NUMERICIDENTIFIERLOOSE]="\\d+";f("NONNUMERICIDENTIFIER");p[a.NONNUMERICIDENTIFIER]="\\d*[a-zA-Z-]"+Xt+"*";f("MAINVERSION");p[a.MAINVERSION]="("+p[a.NUMERICIDENTIFIER]+")\\.("+p[a.NUMERICIDENTIFIER]+")\\.("+p[a.NUMERICIDENTIFIER]+")";f("MAINVERSIONLOOSE");p[a.MAINVERSIONLOOSE]="("+p[a.NUMERICIDENTIFIERLOOSE]+")\\.("+p[a.NUMERICIDENTIFIERLOOSE]+")\\.("+p[a.NUMERICIDENTIFIERLOOSE]+")";f("PRERELEASEIDENTIFIER");p[a.PRERELEASEIDENTIFIER]="(?:"+p[a.NUMERICIDENTIFIER]+"|"+p[a.NONNUMERICIDENTIFIER]+")";f("PRERELEASEIDENTIFIERLOOSE");p[a.PRERELEASEIDENTIFIERLOOSE]="(?:"+p[a.NUMERICIDENTIFIERLOOSE]+"|"+p[a.NONNUMERICIDENTIFIER]+")";f("PRERELEASE");p[a.PRERELEASE]="(?:-("+p[a.PRERELEASEIDENTIFIER]+"(?:\\."+p[a.PRERELEASEIDENTIFIER]+")*))";f("PRERELEASELOOSE");p[a.PRERELEASELOOSE]="(?:-?("+p[a.PRERELEASEIDENTIFIERLOOSE]+"(?:\\."+p[a.PRERELEASEIDENTIFIERLOOSE]+")*))";f("BUILDIDENTIFIER");p[a.BUILDIDENTIFIER]=Xt+"+";f("BUILD");p[a.BUILD]="(?:\\+("+p[a.BUILDIDENTIFIER]+"(?:\\."+p[a.BUILDIDENTIFIER]+")*))";f("FULL");f("FULLPLAIN");p[a.FULLPLAIN]="v?"+p[a.MAINVERSION]+p[a.PRERELEASE]+"?"+p[a.BUILD]+"?";p[a.FULL]="^"+p[a.FULLPLAIN]+"$";f("LOOSEPLAIN");p[a.LOOSEPLAIN]="[v=\\s]*"+p[a.MAINVERSIONLOOSE]+p[a.PRERELEASELOOSE]+"?"+p[a.BUILD]+"?";f("LOOSE");p[a.LOOSE]="^"+p[a.LOOSEPLAIN]+"$";f("GTLT");p[a.GTLT]="((?:<|>)?=?)";f("XRANGEIDENTIFIERLOOSE");p[a.XRANGEIDENTIFIERLOOSE]=p[a.NUMERICIDENTIFIERLOOSE]+"|x|X|\\*";f("XRANGEIDENTIFIER");p[a.XRANGEIDENTIFIER]=p[a.NUMERICIDENTIFIER]+"|x|X|\\*";f("XRANGEPLAIN");p[a.XRANGEPLAIN]="[v=\\s]*("+p[a.XRANGEIDENTIFIER]+")(?:\\.("+p[a.XRANGEIDENTIFIER]+")(?:\\.("+p[a.XRANGEIDENTIFIER]+")(?:"+p[a.PRERELEASE]+")?"+p[a.BUILD]+"?)?)?";f("XRANGEPLAINLOOSE");p[a.XRANGEPLAINLOOSE]="[v=\\s]*("+p[a.XRANGEIDENTIFIERLOOSE]+")(?:\\.("+p[a.XRANGEIDENTIFIERLOOSE]+")(?:\\.("+p[a.XRANGEIDENTIFIERLOOSE]+")(?:"+p[a.PRERELEASELOOSE]+")?"+p[a.BUILD]+"?)?)?";f("XRANGE");p[a.XRANGE]="^"+p[a.GTLT]+"\\s*"+p[a.XRANGEPLAIN]+"$";f("XRANGELOOSE");p[a.XRANGELOOSE]="^"+p[a.GTLT]+"\\s*"+p[a.XRANGEPLAINLOOSE]+"$";f("COERCE");p[a.COERCE]="(^|[^\\d])(\\d{1,"+jt+"})(?:\\.(\\d{1,"+jt+"}))?(?:\\.(\\d{1,"+jt+"}))?(?:$|[^\\d])";f("COERCERTL");ve[a.COERCERTL]=new RegExp(p[a.COERCE],"g");y[a.COERCERTL]=new RegExp(Ue(p[a.COERCE]),"g");f("LONETILDE");p[a.LONETILDE]="(?:~>?)";f("TILDETRIM");p[a.TILDETRIM]="(\\s*)"+p[a.LONETILDE]+"\\s+";ve[a.TILDETRIM]=new RegExp(p[a.TILDETRIM],"g");y[a.TILDETRIM]=new RegExp(Ue(p[a.TILDETRIM]),"g");var Zi="$1~";f("TILDE");p[a.TILDE]="^"+p[a.LONETILDE]+p[a.XRANGEPLAIN]+"$";f("TILDELOOSE");p[a.TILDELOOSE]="^"+p[a.LONETILDE]+p[a.XRANGEPLAINLOOSE]+"$";f("LONECARET");p[a.LONECARET]="(?:\\^)";f("CARETTRIM");p[a.CARETTRIM]="(\\s*)"+p[a.LONECARET]+"\\s+";ve[a.CARETTRIM]=new RegExp(p[a.CARETTRIM],"g");y[a.CARETTRIM]=new RegExp(Ue(p[a.CARETTRIM]),"g");var Qi="$1^";f("CARET");p[a.CARET]="^"+p[a.LONECARET]+p[a.XRANGEPLAIN]+"$";f("CARETLOOSE");p[a.CARETLOOSE]="^"+p[a.LONECARET]+p[a.XRANGEPLAINLOOSE]+"$";f("COMPARATORLOOSE");p[a.COMPARATORLOOSE]="^"+p[a.GTLT]+"\\s*("+p[a.LOOSEPLAIN]+")$|^$";f("COMPARATOR");p[a.COMPARATOR]="^"+p[a.GTLT]+"\\s*("+p[a.FULLPLAIN]+")$|^$";f("COMPARATORTRIM");p[a.COMPARATORTRIM]="(\\s*)"+p[a.GTLT]+"\\s*("+p[a.LOOSEPLAIN]+"|"+p[a.XRANGEPLAIN]+")";ve[a.COMPARATORTRIM]=new RegExp(p[a.COMPARATORTRIM],"g");y[a.COMPARATORTRIM]=new RegExp(Ue(p[a.COMPARATORTRIM]),"g");var ea="$1$2$3";f("HYPHENRANGE");p[a.HYPHENRANGE]="^\\s*("+p[a.XRANGEPLAIN]+")\\s+-\\s+("+p[a.XRANGEPLAIN]+")\\s*$";f("HYPHENRANGELOOSE");p[a.HYPHENRANGELOOSE]="^\\s*("+p[a.XRANGEPLAINLOOSE]+")\\s+-\\s+("+p[a.XRANGEPLAINLOOSE]+")\\s*$";f("STAR");p[a.STAR]="(<|>)?=?\\s*\\*";for(V=0;V<wo;V++)g(V,p[V]),ve[V]||(ve[V]=new RegExp(p[V]),y[V]=new RegExp(Ue(p[V])));var V;u.parse=me;function me(e,t){if((!t||typeof t!="object")&&(t={loose:!!t,includePrerelease:!1}),e instanceof m)return e;if(typeof e!="string"||e.length>Me)return null;var r=t.loose?y[a.LOOSE]:y[a.FULL];if(!r.test(e))return null;try{return new m(e,t)}catch{return null}}u.valid=ta;function ta(e,t){var r=me(e,t);return r?r.version:null}u.clean=ra;function ra(e,t){var r=me(e.trim().replace(/^[=v]+/,""),t);return r?r.version:null}u.SemVer=m;function m(e,t){if((!t||typeof t!="object")&&(t={loose:!!t,includePrerelease:!1}),e instanceof m){if(e.loose===t.loose)return e;e=e.version}else if(typeof e!="string")throw new TypeError("Invalid Version: "+e);if(e.length>Me)throw new TypeError("version is longer than "+Me+" characters");if(!(this instanceof m))return new m(e,t);g("SemVer",e,t),this.options=t,this.loose=!!t.loose;var r=e.trim().match(t.loose?y[a.LOOSE]:y[a.FULL]);if(!r)throw new TypeError("Invalid Version: "+e);if(this.raw=e,this.major=+r[1],this.minor=+r[2],this.patch=+r[3],this.major>mt||this.major<0)throw new TypeError("Invalid major version");if(this.minor>mt||this.minor<0)throw new TypeError("Invalid minor version");if(this.patch>mt||this.patch<0)throw new TypeError("Invalid patch version");r[4]?this.prerelease=r[4].split(".").map(function(o){if(/^[0-9]+$/.test(o)){var n=+o;if(n>=0&&n<mt)return n}return o}):this.prerelease=[],this.build=r[5]?r[5].split("."):[],this.format()}m.prototype.format=function(){return this.version=this.major+"."+this.minor+"."+this.patch,this.prerelease.length&&(this.version+="-"+this.prerelease.join(".")),this.version};m.prototype.toString=function(){return this.version};m.prototype.compare=function(e){return g("SemVer.compare",this.version,this.options,e),e instanceof m||(e=new m(e,this.options)),this.compareMain(e)||this.comparePre(e)};m.prototype.compareMain=function(e){return e instanceof m||(e=new m(e,this.options)),ue(this.major,e.major)||ue(this.minor,e.minor)||ue(this.patch,e.patch)};m.prototype.comparePre=function(e){if(e instanceof m||(e=new m(e,this.options)),this.prerelease.length&&!e.prerelease.length)return-1;if(!this.prerelease.length&&e.prerelease.length)return 1;if(!this.prerelease.length&&!e.prerelease.length)return 0;var t=0;do{var r=this.prerelease[t],o=e.prerelease[t];if(g("prerelease compare",t,r,o),r===void 0&&o===void 0)return 0;if(o===void 0)return 1;if(r===void 0)return-1;if(r===o)continue;return ue(r,o)}while(++t)};m.prototype.compareBuild=function(e){e instanceof m||(e=new m(e,this.options));var t=0;do{var r=this.build[t],o=e.build[t];if(g("prerelease compare",t,r,o),r===void 0&&o===void 0)return 0;if(o===void 0)return 1;if(r===void 0)return-1;if(r===o)continue;return ue(r,o)}while(++t)};m.prototype.inc=function(e,t){switch(e){case"premajor":this.prerelease.length=0,this.patch=0,this.minor=0,this.major++,this.inc("pre",t);break;case"preminor":this.prerelease.length=0,this.patch=0,this.minor++,this.inc("pre",t);break;case"prepatch":this.prerelease.length=0,this.inc("patch",t),this.inc("pre",t);break;case"prerelease":this.prerelease.length===0&&this.inc("patch",t),this.inc("pre",t);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":if(this.prerelease.length===0)this.prerelease=[0];else{for(var r=this.prerelease.length;--r>=0;)typeof this.prerelease[r]=="number"&&(this.prerelease[r]++,r=-2);r===-1&&this.prerelease.push(0)}t&&(this.prerelease[0]===t?isNaN(this.prerelease[1])&&(this.prerelease=[t,0]):this.prerelease=[t,0]);break;default:throw new Error("invalid increment argument: "+e)}return this.format(),this.raw=this.version,this};u.inc=oa;function oa(e,t,r,o){typeof r=="string"&&(o=r,r=void 0);try{return new m(e,r).inc(t,o).version}catch{return null}}u.diff=na;function na(e,t){if(zt(e,t))return null;var r=me(e),o=me(t),n="";if(r.prerelease.length||o.prerelease.length){n="pre";var i="prerelease"}for(var c in r)if((c==="major"||c==="minor"||c==="patch")&&r[c]!==o[c])return n+c;return i}u.compareIdentifiers=ue;var yo=/^[0-9]+$/;function ue(e,t){var r=yo.test(e),o=yo.test(t);return r&&o&&(e=+e,t=+t),e===t?0:r&&!o?-1:o&&!r?1:e<t?-1:1}u.rcompareIdentifiers=ia;function ia(e,t){return ue(t,e)}u.major=aa;function aa(e,t){return new m(e,t).major}u.minor=sa;function sa(e,t){return new m(e,t).minor}u.patch=ca;function ca(e,t){return new m(e,t).patch}u.compare=ee;function ee(e,t,r){return new m(e,r).compare(new m(t,r))}u.compareLoose=pa;function pa(e,t){return ee(e,t,!0)}u.compareBuild=da;function da(e,t,r){var o=new m(e,r),n=new m(t,r);return o.compare(n)||o.compareBuild(n)}u.rcompare=la;function la(e,t,r){return ee(t,e,r)}u.sort=ua;function ua(e,t){return e.sort(function(r,o){return u.compareBuild(r,o,t)})}u.rsort=ma;function ma(e,t){return e.sort(function(r,o){return u.compareBuild(o,r,t)})}u.gt=We;function We(e,t,r){return ee(e,t,r)>0}u.lt=ft;function ft(e,t,r){return ee(e,t,r)<0}u.eq=zt;function zt(e,t,r){return ee(e,t,r)===0}u.neq=Eo;function Eo(e,t,r){return ee(e,t,r)!==0}u.gte=qt;function qt(e,t,r){return ee(e,t,r)>=0}u.lte=Yt;function Yt(e,t,r){return ee(e,t,r)<=0}u.cmp=ht;function ht(e,t,r,o){switch(t){case"===":return typeof e=="object"&&(e=e.version),typeof r=="object"&&(r=r.version),e===r;case"!==":return typeof e=="object"&&(e=e.version),typeof r=="object"&&(r=r.version),e!==r;case"":case"=":case"==":return zt(e,r,o);case"!=":return Eo(e,r,o);case">":return We(e,r,o);case">=":return qt(e,r,o);case"<":return ft(e,r,o);case"<=":return Yt(e,r,o);default:throw new TypeError("Invalid operator: "+t)}}u.Comparator=$;function $(e,t){if((!t||typeof t!="object")&&(t={loose:!!t,includePrerelease:!1}),e instanceof $){if(e.loose===!!t.loose)return e;e=e.value}if(!(this instanceof $))return new $(e,t);e=e.trim().split(/\s+/).join(" "),g("comparator",e,t),this.options=t,this.loose=!!t.loose,this.parse(e),this.semver===Ie?this.value="":this.value=this.operator+this.semver.version,g("comp",this)}var Ie={};$.prototype.parse=function(e){var t=this.options.loose?y[a.COMPARATORLOOSE]:y[a.COMPARATOR],r=e.match(t);if(!r)throw new TypeError("Invalid comparator: "+e);this.operator=r[1]!==void 0?r[1]:"",this.operator==="="&&(this.operator=""),r[2]?this.semver=new m(r[2],this.options.loose):this.semver=Ie};$.prototype.toString=function(){return this.value};$.prototype.test=function(e){if(g("Comparator.test",e,this.options.loose),this.semver===Ie||e===Ie)return!0;if(typeof e=="string")try{e=new m(e,this.options)}catch{return!1}return ht(e,this.operator,this.semver,this.options)};$.prototype.intersects=function(e,t){if(!(e instanceof $))throw new TypeError("a Comparator is required");(!t||typeof t!="object")&&(t={loose:!!t,includePrerelease:!1});var r;if(this.operator==="")return this.value===""?!0:(r=new I(e.value,t),yt(this.value,r,t));if(e.operator==="")return e.value===""?!0:(r=new I(this.value,t),yt(e.semver,r,t));var o=(this.operator===">="||this.operator===">")&&(e.operator===">="||e.operator===">"),n=(this.operator==="<="||this.operator==="<")&&(e.operator==="<="||e.operator==="<"),i=this.semver.version===e.semver.version,c=(this.operator===">="||this.operator==="<=")&&(e.operator===">="||e.operator==="<="),l=ht(this.semver,"<",e.semver,t)&&(this.operator===">="||this.operator===">")&&(e.operator==="<="||e.operator==="<"),d=ht(this.semver,">",e.semver,t)&&(this.operator==="<="||this.operator==="<")&&(e.operator===">="||e.operator===">");return o||n||i&&c||l||d};u.Range=I;function I(e,t){if((!t||typeof t!="object")&&(t={loose:!!t,includePrerelease:!1}),e instanceof I)return e.loose===!!t.loose&&e.includePrerelease===!!t.includePrerelease?e:new I(e.raw,t);if(e instanceof $)return new I(e.value,t);if(!(this instanceof I))return new I(e,t);if(this.options=t,this.loose=!!t.loose,this.includePrerelease=!!t.includePrerelease,this.raw=e.trim().split(/\s+/).join(" "),this.set=this.raw.split("||").map(function(r){return this.parseRange(r.trim())},this).filter(function(r){return r.length}),!this.set.length)throw new TypeError("Invalid SemVer Range: "+this.raw);this.format()}I.prototype.format=function(){return this.range=this.set.map(function(e){return e.join(" ").trim()}).join("||").trim(),this.range};I.prototype.toString=function(){return this.range};I.prototype.parseRange=function(e){var t=this.options.loose,r=t?y[a.HYPHENRANGELOOSE]:y[a.HYPHENRANGE];e=e.replace(r,Ca),g("hyphen replace",e),e=e.replace(y[a.COMPARATORTRIM],ea),g("comparator trim",e,y[a.COMPARATORTRIM]),e=e.replace(y[a.TILDETRIM],Zi),e=e.replace(y[a.CARETTRIM],Qi),e=e.split(/\s+/).join(" ");var o=t?y[a.COMPARATORLOOSE]:y[a.COMPARATOR],n=e.split(" ").map(function(i){return ha(i,this.options)},this).join(" ").split(/\s+/);return this.options.loose&&(n=n.filter(function(i){return!!i.match(o)})),n=n.map(function(i){return new $(i,this.options)},this),n};I.prototype.intersects=function(e,t){if(!(e instanceof I))throw new TypeError("a Range is required");return this.set.some(function(r){return go(r,t)&&e.set.some(function(o){return go(o,t)&&r.every(function(n){return o.every(function(i){return n.intersects(i,t)})})})})};function go(e,t){for(var r=!0,o=e.slice(),n=o.pop();r&&o.length;)r=o.every(function(i){return n.intersects(i,t)}),n=o.pop();return r}u.toComparators=fa;function fa(e,t){return new I(e,t).set.map(function(r){return r.map(function(o){return o.value}).join(" ").trim().split(" ")})}function ha(e,t){return g("comp",e,t),e=wa(e,t),g("caret",e),e=ya(e,t),g("tildes",e),e=Sa(e,t),g("xrange",e),e=ba(e,t),g("stars",e),e}function O(e){return!e||e.toLowerCase()==="x"||e==="*"}function ya(e,t){return e.trim().split(/\s+/).map(function(r){return ga(r,t)}).join(" ")}function ga(e,t){var r=t.loose?y[a.TILDELOOSE]:y[a.TILDE];return e.replace(r,function(o,n,i,c,l){g("tilde",e,o,n,i,c,l);var d;return O(n)?d="":O(i)?d=">="+n+".0.0 <"+(+n+1)+".0.0":O(c)?d=">="+n+"."+i+".0 <"+n+"."+(+i+1)+".0":l?(g("replaceTilde pr",l),d=">="+n+"."+i+"."+c+"-"+l+" <"+n+"."+(+i+1)+".0"):d=">="+n+"."+i+"."+c+" <"+n+"."+(+i+1)+".0",g("tilde return",d),d})}function wa(e,t){return e.trim().split(/\s+/).map(function(r){return Ea(r,t)}).join(" ")}function Ea(e,t){g("caret",e,t);var r=t.loose?y[a.CARETLOOSE]:y[a.CARET];return e.replace(r,function(o,n,i,c,l){g("caret",e,o,n,i,c,l);var d;return O(n)?d="":O(i)?d=">="+n+".0.0 <"+(+n+1)+".0.0":O(c)?n==="0"?d=">="+n+"."+i+".0 <"+n+"."+(+i+1)+".0":d=">="+n+"."+i+".0 <"+(+n+1)+".0.0":l?(g("replaceCaret pr",l),n==="0"?i==="0"?d=">="+n+"."+i+"."+c+"-"+l+" <"+n+"."+i+"."+(+c+1):d=">="+n+"."+i+"."+c+"-"+l+" <"+n+"."+(+i+1)+".0":d=">="+n+"."+i+"."+c+"-"+l+" <"+(+n+1)+".0.0"):(g("no pr"),n==="0"?i==="0"?d=">="+n+"."+i+"."+c+" <"+n+"."+i+"."+(+c+1):d=">="+n+"."+i+"."+c+" <"+n+"."+(+i+1)+".0":d=">="+n+"."+i+"."+c+" <"+(+n+1)+".0.0"),g("caret return",d),d})}function Sa(e,t){return g("replaceXRanges",e,t),e.split(/\s+/).map(function(r){return Aa(r,t)}).join(" ")}function Aa(e,t){e=e.trim();var r=t.loose?y[a.XRANGELOOSE]:y[a.XRANGE];return e.replace(r,function(o,n,i,c,l,d){g("xRange",e,o,n,i,c,l,d);var w=O(i),A=w||O(c),b=A||O(l),T=b;return n==="="&&T&&(n=""),d=t.includePrerelease?"-0":"",w?n===">"||n==="<"?o="<0.0.0-0":o="*":n&&T?(A&&(c=0),l=0,n===">"?(n=">=",A?(i=+i+1,c=0,l=0):(c=+c+1,l=0)):n==="<="&&(n="<",A?i=+i+1:c=+c+1),o=n+i+"."+c+"."+l+d):A?o=">="+i+".0.0"+d+" <"+(+i+1)+".0.0"+d:b&&(o=">="+i+"."+c+".0"+d+" <"+i+"."+(+c+1)+".0"+d),g("xRange return",o),o})}function ba(e,t){return g("replaceStars",e,t),e.trim().replace(y[a.STAR],"")}function Ca(e,t,r,o,n,i,c,l,d,w,A,b,T){return O(r)?t="":O(o)?t=">="+r+".0.0":O(n)?t=">="+r+"."+o+".0":t=">="+t,O(d)?l="":O(w)?l="<"+(+d+1)+".0.0":O(A)?l="<"+d+"."+(+w+1)+".0":b?l="<="+d+"."+w+"."+A+"-"+b:l="<="+l,(t+" "+l).trim()}I.prototype.test=function(e){if(!e)return!1;if(typeof e=="string")try{e=new m(e,this.options)}catch{return!1}for(var t=0;t<this.set.length;t++)if(va(this.set[t],e,this.options))return!0;return!1};function va(e,t,r){for(var o=0;o<e.length;o++)if(!e[o].test(t))return!1;if(t.prerelease.length&&!r.includePrerelease){for(o=0;o<e.length;o++)if(g(e[o].semver),e[o].semver!==Ie&&e[o].semver.prerelease.length>0){var n=e[o].semver;if(n.major===t.major&&n.minor===t.minor&&n.patch===t.patch)return!0}return!1}return!0}u.satisfies=yt;function yt(e,t,r){try{t=new I(t,r)}catch{return!1}return t.test(e)}u.maxSatisfying=Ia;function Ia(e,t,r){var o=null,n=null;try{var i=new I(t,r)}catch{return null}return e.forEach(function(c){i.test(c)&&(!o||n.compare(c)===-1)&&(o=c,n=new m(o,r))}),o}u.minSatisfying=Pa;function Pa(e,t,r){var o=null,n=null;try{var i=new I(t,r)}catch{return null}return e.forEach(function(c){i.test(c)&&(!o||n.compare(c)===1)&&(o=c,n=new m(o,r))}),o}u.minVersion=Ra;function Ra(e,t){e=new I(e,t);var r=new m("0.0.0");if(e.test(r)||(r=new m("0.0.0-0"),e.test(r)))return r;r=null;for(var o=0;o<e.set.length;++o){var n=e.set[o];n.forEach(function(i){var c=new m(i.semver.version);switch(i.operator){case">":c.prerelease.length===0?c.patch++:c.prerelease.push(0),c.raw=c.format();case"":case">=":(!r||We(r,c))&&(r=c);break;case"<":case"<=":break;default:throw new Error("Unexpected operation: "+i.operator)}})}return r&&e.test(r)?r:null}u.validRange=Ta;function Ta(e,t){try{return new I(e,t).range||"*"}catch{return null}}u.ltr=xa;function xa(e,t,r){return Zt(e,t,"<",r)}u.gtr=Oa;function Oa(e,t,r){return Zt(e,t,">",r)}u.outside=Zt;function Zt(e,t,r,o){e=new m(e,o),t=new I(t,o);var n,i,c,l,d;switch(r){case">":n=We,i=Yt,c=ft,l=">",d=">=";break;case"<":n=ft,i=qt,c=We,l="<",d="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if(yt(e,t,o))return!1;for(var w=0;w<t.set.length;++w){var A=t.set[w],b=null,T=null;if(A.forEach(function(K){K.semver===Ie&&(K=new $(">=0.0.0")),b=b||K,T=T||K,n(K.semver,b.semver,o)?b=K:c(K.semver,T.semver,o)&&(T=K)}),b.operator===l||b.operator===d||(!T.operator||T.operator===l)&&i(e,T.semver))return!1;if(T.operator===d&&c(e,T.semver))return!1}return!0}u.prerelease=Na;function Na(e,t){var r=me(e,t);return r&&r.prerelease.length?r.prerelease:null}u.intersects=_a;function _a(e,t,r){return e=new I(e,r),t=new I(t,r),e.intersects(t)}u.coerce=Da;function Da(e,t){if(e instanceof m)return e;if(typeof e=="number"&&(e=String(e)),typeof e!="string")return null;t=t||{};var r=null;if(!t.rtl)r=e.match(y[a.COERCE]);else{for(var o;(o=y[a.COERCERTL].exec(e))&&(!r||r.index+r[0].length!==e.length);)(!r||o.index+o[0].length!==r.index+r[0].length)&&(r=o),y[a.COERCERTL].lastIndex=o.index+o[1].length+o[2].length;y[a.COERCERTL].lastIndex=-1}return r===null?null:me(r[2]+"."+(r[3]||"0")+"."+(r[4]||"0"),t)}});var Va={};Cn(Va,{main:()=>fn,run:()=>hn});module.exports=vn(Va);var bt=require("@medplum/core"),un=require("commander"),mn=H(require("dotenv"));var ae=require("@medplum/core"),Jr=require("child_process"),$r=require("http"),Fr=require("os");var ur=require("@medplum/core");var dr=require("@medplum/core"),X=require("fs"),lr=require("os"),Ct=require("path"),j=class extends dr.ClientStorage{constructor(t){super(),this.dirName=(0,Ct.resolve)((0,lr.homedir)(),".medplum"),this.fileName=(0,Ct.resolve)(this.dirName,t+".json")}clear(){this.writeFile({})}getString(t){return this.readFile()?.[t]}setString(t,r){let o=this.readFile()??{};r?o[t]=r:delete o[t],this.writeFile(o)}getObject(t){let r=this.getString(t);return r?JSON.parse(r):void 0}setObject(t,r){this.setString(t,r?JSON.stringify(r):void 0)}readFile(){if((0,X.existsSync)(this.fileName))return JSON.parse((0,X.readFileSync)(this.fileName,"utf8"))}writeFile(t){(0,X.existsSync)(this.dirName)||(0,X.mkdirSync)(this.dirName),(0,X.writeFileSync)(this.fileName,JSON.stringify(t,null,2),"utf8")}};async function S(e,t=!0){let r=e.profile??"default",o=new j(r),n=o.getObject("options");if(r!=="default"&&!n)throw new Error(`Profile "${r}" does not exist`);let{baseUrl:i,fhirUrlPath:c,accessToken:l,tokenUrl:d,authorizeUrl:w,clientId:A,clientSecret:b}=In(e,o),T=e.fetch??fetch,K=new ur.MedplumClient({fetch:T,baseUrl:i,tokenUrl:d,fhirUrlPath:c,authorizeUrl:w,storage:o,onUnauthenticated:Pn,verbose:e.verbose});return t&&(l?K.setAccessToken(l):A&&b&&(K.setBasicAuth(A,b),n?.authType!=="basic"&&await K.startClientLogin(A,b))),K}function In(e,t){let r=t.getObject("options"),o=e.baseUrl??r?.baseUrl??process.env.MEDPLUM_BASE_URL??"https://api.medplum.com/",n=e.fhirUrlPath??r?.fhirUrlPath??process.env.MEDPLUM_FHIR_URL_PATH,i=e.accessToken??r?.accessToken??process.env.MEDPLUM_CLIENT_ACCESS_TOKEN,c=e.tokenUrl??r?.tokenUrl??process.env.MEDPLUM_TOKEN_URL,l=e.authorizeUrl??r?.authorizeUrl??process.env.MEDPLUM_AUTHORIZE_URL,d=e.clientId??r?.clientId??process.env.MEDPLUM_CLIENT_ID,w=e.clientSecret??r?.clientSecret??process.env.MEDPLUM_CLIENT_SECRET;return{baseUrl:o,fhirUrlPath:n,accessToken:i,tokenUrl:c,authorizeUrl:l,clientId:d,clientSecret:w}}function Pn(){console.log("Unauthenticated: run `npx medplum login` to sign in")}var $e=require("commander");function h(e){return new $e.Command(e).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("--audience <audience>","Audience for JWT assertion").option("-p, --profile <profile>","Profile name").option("-v --verbose","Verbose output").addOption(new $e.Option("--auth-type <authType>","Type of authentication").choices(["basic","client-credentials","authorization-code","jwt-bearer","token-exchange","jwt-assertion"]))}var ce=require("@medplum/core"),Ee=require("crypto"),ne=require("fs");var mr=require("buffer");var k=new TextEncoder,N=new TextDecoder,rs=2**32;function F(...e){let t=e.reduce((n,{length:i})=>n+i,0),r=new Uint8Array(t),o=0;return e.forEach(n=>{r.set(n,o),o+=n.length}),r}var L=e=>mr.Buffer.from(e).toString("base64url");var fe=class extends Error{constructor(r){super(r);P(this,"code","ERR_JOSE_GENERIC");this.name=this.constructor.name,Error.captureStackTrace?.(this,this.constructor)}static get code(){return"ERR_JOSE_GENERIC"}};var E=class extends fe{constructor(){super(...arguments);P(this,"code","ERR_JOSE_NOT_SUPPORTED")}static get code(){return"ERR_JOSE_NOT_SUPPORTED"}};var M=class extends fe{constructor(){super(...arguments);P(this,"code","ERR_JWS_INVALID")}static get code(){return"ERR_JWS_INVALID"}},re=class extends fe{constructor(){super(...arguments);P(this,"code","ERR_JWT_INVALID")}static get code(){return"ERR_JWT_INVALID"}};var hr=H(require("util"),1),W=e=>hr.types.isKeyObject(e);var yr=H(require("crypto"),1),gr=H(require("util"),1),xn=yr.webcrypto,wr=xn,_=e=>gr.types.isCryptoKey(e);function z(e,t="algorithm.name"){return new TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`)}function Fe(e,t){return e.name===t}function It(e){return parseInt(e.name.slice(4),10)}function On(e){switch(e){case"ES256":return"P-256";case"ES384":return"P-384";case"ES512":return"P-521";default:throw new Error("unreachable")}}function Nn(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 o=t.pop();r+=`one of ${t.join(", ")}, or ${o}.`}else t.length===2?r+=`one of ${t[0]} or ${t[1]}.`:r+=`${t[0]}.`;throw new TypeError(r)}}function Er(e,t,...r){switch(t){case"HS256":case"HS384":case"HS512":{if(!Fe(e.algorithm,"HMAC"))throw z("HMAC");let o=parseInt(t.slice(2),10);if(It(e.algorithm.hash)!==o)throw z(`SHA-${o}`,"algorithm.hash");break}case"RS256":case"RS384":case"RS512":{if(!Fe(e.algorithm,"RSASSA-PKCS1-v1_5"))throw z("RSASSA-PKCS1-v1_5");let o=parseInt(t.slice(2),10);if(It(e.algorithm.hash)!==o)throw z(`SHA-${o}`,"algorithm.hash");break}case"PS256":case"PS384":case"PS512":{if(!Fe(e.algorithm,"RSA-PSS"))throw z("RSA-PSS");let o=parseInt(t.slice(2),10);if(It(e.algorithm.hash)!==o)throw z(`SHA-${o}`,"algorithm.hash");break}case"EdDSA":{if(e.algorithm.name!=="Ed25519"&&e.algorithm.name!=="Ed448")throw z("Ed25519 or Ed448");break}case"ES256":case"ES384":case"ES512":{if(!Fe(e.algorithm,"ECDSA"))throw z("ECDSA");let o=On(t);if(e.algorithm.namedCurve!==o)throw z(o,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}Nn(e,r)}function Sr(e,t,...r){if(r.length>2){let o=r.pop();e+=`one of type ${r.join(", ")}, or ${o}.`}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&&t.constructor.name&&(e+=` Received an instance of ${t.constructor.name}`),e}var U=(e,...t)=>Sr("Key must be ",e,...t);function Pt(e,t,...r){return Sr(`Key for the ${e} algorithm must be `,t,...r)}var Rt=e=>W(e)||_(e),C=["KeyObject"];(globalThis.CryptoKey||wr?.CryptoKey)&&C.push("CryptoKey");var kn=(...e)=>{let t=e.filter(Boolean);if(t.length===0||t.length===1)return!0;let r;for(let o of t){let n=Object.keys(o);if(!r||r.size===0){r=new Set(n);continue}for(let i of n){if(r.has(i))return!1;r.add(i)}}return!0},he=kn;function Ln(e){return typeof e=="object"&&e!==null}function x(e){if(!Ln(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}var Be=require("crypto"),Cr=require("util");var br=require("crypto");var Mn=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 E("Unsupported key curve for this operation")}},Wn=(e,t)=>{let r;if(_(e))r=br.KeyObject.from(e);else if(W(e))r=e;else throw new TypeError(U(e,...C));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 o=r.asymmetricKeyDetails.namedCurve;return t?o:Mn(o)}default:throw new TypeError("Invalid asymmetric key type for this operation")}},Tt=Wn;var gc=(0,Cr.promisify)(Be.generateKeyPair);var Ir=require("util"),xt=require("crypto");var _c=(0,Ir.promisify)(xt.pbkdf2);var Te=require("crypto"),Pr=require("util");var Ge=(e,t)=>{let{modulusLength:r}=e.asymmetricKeyDetails;if(typeof r!="number"||r<2048)throw new TypeError(`${t} requires key modulusLength to be 2048 bits or larger`)};var Jc=(0,Pr.deprecate)(()=>Te.constants.RSA_PKCS1_PADDING,'The RSA1_5 "alg" (JWE Algorithm) is deprecated and will be removed in the next major revision.');var $n=(e,t)=>{if(!(t instanceof Uint8Array)){if(!Rt(t))throw new TypeError(Pt(e,t,...C,"Uint8Array"));if(t.type!=="secret")throw new TypeError(`${C.join(" or ")} instances for symmetric algorithms must be of type "secret"`)}},Fn=(e,t,r)=>{if(!Rt(t))throw new TypeError(Pt(e,t,...C));if(t.type==="secret")throw new TypeError(`${C.join(" or ")} instances for asymmetric algorithms must not be of type "secret"`);if(r==="sign"&&t.type==="public")throw new TypeError(`${C.join(" or ")} instances for asymmetric algorithm signing must be of type "private"`);if(r==="decrypt"&&t.type==="public")throw new TypeError(`${C.join(" or ")} instances for asymmetric algorithm decryption must be of type "private"`);if(t.algorithm&&r==="verify"&&t.type==="private")throw new TypeError(`${C.join(" or ")} instances for asymmetric algorithm verifying must be of type "public"`);if(t.algorithm&&r==="encrypt"&&t.type==="private")throw new TypeError(`${C.join(" or ")} instances for asymmetric algorithm encryption must be of type "public"`)},Bn=(e,t,r)=>{e.startsWith("HS")||e==="dir"||e.startsWith("PBES2")||/^A\d{3}(?:GCM)?KW$/.test(e)?$n(e,t):Fn(e,t,r)},Oe=Bn;function Yn(e,t,r,o,n){if(n.crit!==void 0&&o.crit===void 0)throw new e('"crit" (Critical) Header Parameter MUST be integrity protected');if(!o||o.crit===void 0)return new Set;if(!Array.isArray(o.crit)||o.crit.length===0||o.crit.some(c=>typeof c!="string"||c.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 c of o.crit){if(!i.has(c))throw new E(`Extension Header Parameter "${c}" is not recognized`);if(n[c]===void 0)throw new e(`Extension Header Parameter "${c}" is missing`);if(i.get(c)&&o[c]===void 0)throw new e(`Extension Header Parameter "${c}" MUST be integrity protected`)}return new Set(o.crit)}var ye=Yn;var ri=Symbol();var Kt=H(require("crypto"),1),Nr=require("util");function je(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"EdDSA":return;default:throw new E(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}var Nt=require("crypto");var oi={padding:Nt.constants.RSA_PKCS1_PSS_PADDING,saltLength:Nt.constants.RSA_PSS_SALTLEN_DIGEST},ni=new Map([["ES256","P-256"],["ES256K","secp256k1"],["ES384","P-384"],["ES512","P-521"]]);function Ve(e,t){switch(e){case"EdDSA":if(!["ed25519","ed448"].includes(t.asymmetricKeyType))throw new TypeError("Invalid key for this operation, its asymmetricKeyType must be ed25519 or ed448");return t;case"RS256":case"RS384":case"RS512":if(t.asymmetricKeyType!=="rsa")throw new TypeError("Invalid key for this operation, its asymmetricKeyType must be rsa");return Ge(t,e),t;case"PS256":case"PS384":case"PS512":if(t.asymmetricKeyType==="rsa-pss"){let{hashAlgorithm:r,mgf1HashAlgorithm:o,saltLength:n}=t.asymmetricKeyDetails,i=parseInt(e.slice(-3),10);if(r!==void 0&&(r!==`sha${i}`||o!==r))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>i>>3)throw new TypeError(`Invalid key for this operation, its RSA-PSS parameter saltLength does not meet the requirements of "alg" ${e}`)}else if(t.asymmetricKeyType!=="rsa")throw new TypeError("Invalid key for this operation, its asymmetricKeyType must be rsa or rsa-pss");return Ge(t,e),{key:t,...oi};case"ES256":case"ES256K":case"ES384":case"ES512":{if(t.asymmetricKeyType!=="ec")throw new TypeError("Invalid key for this operation, its asymmetricKeyType must be ec");let r=Tt(t),o=ni.get(e);if(r!==o)throw new TypeError(`Invalid key curve for the algorithm, its curve must be ${o}, got ${r}`);return{dsaEncoding:"ieee-p1363",key:t}}default:throw new E(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}var ze=H(require("crypto"),1),Or=require("util");function _t(e){switch(e){case"HS256":return"sha256";case"HS384":return"sha384";case"HS512":return"sha512";default:throw new E(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}var Ne=require("crypto");function Xe(e,t,r){if(t instanceof Uint8Array){if(!e.startsWith("HS"))throw new TypeError(U(t,...C));return(0,Ne.createSecretKey)(t)}if(t instanceof Ne.KeyObject)return t;if(_(t))return Er(t,e,r),Ne.KeyObject.from(t);throw new TypeError(U(t,...C,"Uint8Array"))}var ii=(0,Or.promisify)(ze.sign),ai=async(e,t,r)=>{let o=Xe(e,t,"sign");if(e.startsWith("HS")){let n=ze.createHmac(_t(e),o);return n.update(r),n.digest()}return ii(je(e),r,Ve(e,o))},Dt=ai;var Pl=(0,Nr.promisify)(Kt.verify);var q=e=>Math.floor(e.getTime()/1e3);var ci=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i,_e=e=>{let t=ci.exec(e);if(!t||t[4]&&t[1])throw new TypeError("Invalid time period format");let r=parseFloat(t[2]),o=t[3].toLowerCase(),n;switch(o){case"sec":case"secs":case"second":case"seconds":case"s":n=Math.round(r);break;case"minute":case"minutes":case"min":case"mins":case"m":n=Math.round(r*60);break;case"hour":case"hours":case"hr":case"hrs":case"h":n=Math.round(r*3600);break;case"day":case"days":case"d":n=Math.round(r*86400);break;case"week":case"weeks":case"w":n=Math.round(r*604800);break;default:n=Math.round(r*31557600);break}return t[1]==="-"||t[4]==="ago"?-n:n};var ge=class{constructor(t){P(this,"_payload");P(this,"_protectedHeader");P(this,"_unprotectedHeader");if(!(t instanceof Uint8Array))throw new TypeError("payload must be an instance of Uint8Array");this._payload=t}setProtectedHeader(t){if(this._protectedHeader)throw new TypeError("setProtectedHeader can only be called once");return this._protectedHeader=t,this}setUnprotectedHeader(t){if(this._unprotectedHeader)throw new TypeError("setUnprotectedHeader can only be called once");return this._unprotectedHeader=t,this}async sign(t,r){if(!this._protectedHeader&&!this._unprotectedHeader)throw new M("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");if(!he(this._protectedHeader,this._unprotectedHeader))throw new M("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let o={...this._protectedHeader,...this._unprotectedHeader},n=ye(M,new Map([["b64",!0]]),r?.crit,this._protectedHeader,o),i=!0;if(n.has("b64")&&(i=this._protectedHeader.b64,typeof i!="boolean"))throw new M('The "b64" (base64url-encode payload) Header Parameter must be a boolean');let{alg:c}=o;if(typeof c!="string"||!c)throw new M('JWS "alg" (Algorithm) Header Parameter missing or invalid');Oe(c,t,"sign");let l=this._payload;i&&(l=k.encode(L(l)));let d;this._protectedHeader?d=k.encode(L(JSON.stringify(this._protectedHeader))):d=k.encode("");let w=F(d,k.encode("."),l),A=await Dt(c,t,w),b={signature:L(A),payload:""};return i&&(b.payload=N.decode(l)),this._unprotectedHeader&&(b.header=this._unprotectedHeader),this._protectedHeader&&(b.protected=N.decode(d)),b}};var De=class{constructor(t){P(this,"_flattened");this._flattened=new ge(t)}setProtectedHeader(t){return this._flattened.setProtectedHeader(t),this}async sign(t,r){let o=await this._flattened.sign(t,r);if(o.payload===void 0)throw new TypeError("use the flattened module for creating JWS with b64: false");return`${o.protected}.${o.payload}.${o.signature}`}};function se(e,t){if(!Number.isFinite(t))throw new TypeError(`Invalid ${e} input`);return t}var we=class{constructor(t={}){P(this,"_payload");if(!x(t))throw new TypeError("JWT Claims Set MUST be an object");this._payload=t}setIssuer(t){return this._payload={...this._payload,iss:t},this}setSubject(t){return this._payload={...this._payload,sub:t},this}setAudience(t){return this._payload={...this._payload,aud:t},this}setJti(t){return this._payload={...this._payload,jti:t},this}setNotBefore(t){return typeof t=="number"?this._payload={...this._payload,nbf:se("setNotBefore",t)}:t instanceof Date?this._payload={...this._payload,nbf:se("setNotBefore",q(t))}:this._payload={...this._payload,nbf:q(new Date)+_e(t)},this}setExpirationTime(t){return typeof t=="number"?this._payload={...this._payload,exp:se("setExpirationTime",t)}:t instanceof Date?this._payload={...this._payload,exp:se("setExpirationTime",q(t))}:this._payload={...this._payload,exp:q(new Date)+_e(t)},this}setIssuedAt(t){return typeof t>"u"?this._payload={...this._payload,iat:q(new Date)}:t instanceof Date?this._payload={...this._payload,iat:se("setIssuedAt",q(t))}:typeof t=="string"?this._payload={...this._payload,iat:se("setIssuedAt",q(new Date)+_e(t))}:this._payload={...this._payload,iat:se("setIssuedAt",t)},this}};var Ke=class extends we{constructor(){super(...arguments);P(this,"_protectedHeader")}setProtectedHeader(r){return this._protectedHeader=r,this}async sign(r,o){let n=new De(k.encode(JSON.stringify(this._payload)));if(n.setProtectedHeader(this._protectedHeader),Array.isArray(this._protectedHeader?.crit)&&this._protectedHeader.crit.includes("b64")&&this._protectedHeader.b64===!1)throw new re("JWTs MUST NOT use unencoded payload");return n.sign(r,o)}};var hi;(typeof navigator>"u"||!navigator.userAgent?.startsWith?.("Mozilla/5.0 "))&&(hi="jose/v5.2.0");var Ht=require("crypto"),Kr=require("util");var km=(0,Kr.promisify)(Ht.generateKeyPair);var Y=require("path"),Hr=H(require("tar"));function Z(e){console.log(JSON.stringify(e,null,2))}async function kt(e,t,r){let o=t.source,n=Wt(o);if(n)try{console.log("Saving source code...");let i=await e.createAttachment(n,(0,Y.basename)(o),Si(o));console.log("Updating bot.....");let c=await e.updateResource({...r,sourceCode:i});console.log("Success! New bot version: "+c.meta?.versionId)}catch(i){console.log("Update error: ",i)}}async function Lt(e,t,r){let o=t.dist??t.source,n=Wt(o);if(n)try{console.log("Deploying bot...");let i=await e.post(e.fhirUrl("Bot",r.id,"$deploy"),{code:n,filename:(0,Y.basename)(o)});console.log("Deploy result: "+i.issue?.[0]?.details?.text)}catch(i){console.log("Deploy error: ",i)}}async function Mt(e,t,r,o,n,i,c){try{let l={name:t,description:"",runtimeVersion:i},d=await e.post("admin/projects/"+r+"/bot",l),w=await e.readResource("Bot",d.id),A={name:t,id:d.id,source:o,dist:n};await kt(e,A,w),await Lt(e,A,w),console.log(`Success! Bot created: ${w.id}`),c&&wi(A)}catch(l){console.log("Error while creating new bot: "+l)}}function kr(e){let t=new RegExp("^"+Ei(e).replace(/\\\*/g,".*")+"$"),r=B()?.bots?.filter(o=>t.test(o.name));return r||[]}function ie(e,t=!1){let r=["medplum"];return e&&r.push(e),r.push("config"),t&&r.push("server"),r.push("json"),r.join(".")}function R(e,t){(0,ne.writeFileSync)((0,Y.resolve)(e),JSON.stringify(t,void 0,2),"utf-8")}function B(e,t=!1){let r=Wt(ie(e,t));if(r)return JSON.parse(r)}function Wt(e){let t=(0,Y.resolve)(process.cwd(),e);return(0,ne.existsSync)(t)?(0,ne.readFileSync)(t,"utf8"):""}function wi(e){let t=B()??{};t.bots||(t.bots=[]),t.bots.push(e),(0,ne.writeFileSync)("medplum.config.json",JSON.stringify(t,null,2),"utf8"),console.log(`Bot added to config: ${e.id}`)}function Ei(e){return e.replace(/[/\-\\^$*+?.()|[\]{}]/g,"\\$&")}function Lr(e){let o=0,n=0;return Hr.default.x({cwd:e,filter:(i,c)=>{if(o++,o>100)throw new Error("Tar extractor reached max number of files");if(n+=c.size,n>10485760)throw new Error("Tar extractor reached max size");return!0}})}function Ut(){return{url:"http://hl7.org/fhir/StructureDefinition/data-absent-reason",valueCode:"unsupported"}}function Si(e){let t=(0,Y.extname)(e).toLowerCase();return[".cjs",".mjs",".js"].includes(t)?ce.ContentType.JAVASCRIPT:[".cts",".mts",".ts"].includes(t)?ce.ContentType.TYPESCRIPT:ce.ContentType.TEXT}function qe(e,t){let r=new j(e),o={name:e,...t};return r.setObject("options",o),console.log(`${e} profile created`),o}function Mr(e){return new j(e).getObject("options")}async function Wr(e,t){let r={typ:"JWT",alg:"HS256"},o=Math.floor(Date.now()/1e3),n={aud:`${t.baseUrl}${t.audience}`,iss:t.issuer,sub:t.subject,nbf:o,iat:o,exp:o+604800},i=(0,ce.encodeBase64)(JSON.stringify(r)),c=(0,ce.encodeBase64)(JSON.stringify(n)),l=`${i}.${c}`,d=(0,Ee.createHmac)("sha256",t.clientSecret).update(l).digest("base64url"),w=`${l}.${d}`;await e.startJwtBearerLogin(t.clientId,w,t.scope??"")}async function Ur(e,t){let r=(0,Ee.createPrivateKey)((0,ne.readFileSync)((0,Y.resolve)(t.privateKeyPath))),o=await new Ke({}).setProtectedHeader({alg:"RS384",typ:"JWT"}).setIssuer(t.clientId).setSubject(t.clientId).setAudience(`${t.baseUrl}${t.audience}`).setJti((0,Ee.randomBytes)(16).toString("hex")).setIssuedAt().setExpirationTime("5m").sign(r);await e.startJwtAssertionLogin(o)}var Br="medplum-cli",Gr="http://localhost:9615",Jt=h("login"),$t=h("whoami");Jt.action(async e=>{let t=e.profile??"default",r=qe(t,e),o=await S(e,!1);await Ai(o,r)});$t.action(async e=>{let t=await S(e);vi(t)});async function Ai(e,t){switch(t?.authType??"authorization-code"){case"authorization-code":await Ii(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 Wr(e,t);break;case"jwt-assertion":await Ur(e,t);break}console.log("Login successful")}async function bi(e){let t=(0,$r.createServer)(async(r,o)=>{let n=new URL(r.url,"http://localhost:9615"),i=n.searchParams.get("code");if(n.pathname==="/"&&i)try{let c=await e.processCode(i,{clientId:Br,redirectUri:Gr});o.writeHead(200,{"Content-Type":ae.ContentType.TEXT}),o.end(`Signed in as ${(0,ae.getDisplayString)(c)}. You may close this window.`)}catch(c){o.writeHead(400,{"Content-Type":ae.ContentType.TEXT}),o.end(`Error: ${(0,ae.normalizeErrorString)(c)}`)}finally{t.close()}else o.writeHead(404,{"Content-Type":ae.ContentType.TEXT}),o.end("Not found")}).listen(9615)}async function Ci(e){let t=(0,Fr.platform)(),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)}(0,Jr.exec)(r)}function vi(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 Ii(e){await bi(e);let t=new URL(e.getAuthorizeUrl());t.searchParams.set("client_id",Br),t.searchParams.set("redirect_uri",Gr),t.searchParams.set("scope","openid"),t.searchParams.set("response_type","code"),t.searchParams.set("prompt","login"),await Ci(t.toString())}var Io=require("commander");var Q=require("@aws-sdk/client-cloudformation"),rt=require("@aws-sdk/client-cloudfront"),Xr=require("@aws-sdk/client-ecs"),zr=require("@aws-sdk/client-s3"),Ae=require("@aws-sdk/client-ssm"),ot=require("@aws-sdk/client-sts"),qr=require("@medplum/core"),Yr=require("fs"),Zr=H(require("node-fetch"));var jr=H(require("readline")),Ye;function Ze(){Ye=jr.default.createInterface({input:process.stdin,output:process.stdout})}function Qe(){Ye.close()}function s(e){Ye.write(e+`
3
+ `)}function v(e){s(`
4
4
  `+e+`
5
- `)}function _(e,t=""){return new Promise(r=>{ke.question(e+(t?" ("+t+")":"")+" ",o=>{r(o||t.toString())})})}async function ut(e,t,r=""){let o=e+" ["+t.map(n=>n===r?"("+n+")":n).join("|")+"]";for(;;){let n=await _(o)||r;if(t.includes(n))return n;i("Please choose one of the following options: "+t.join(", "))}}async function fe(e,t,r){return parseInt(await ut(e,t.map(o=>o.toString()),r.toString()),10)}async function Re(e){return(await ut(e,["y","n"])).toLowerCase()==="y"}async function lt(e){if(!await Re(e))throw i("Exiting..."),new Error("User cancelled")}function y(e,t){(0,We.writeFileSync)((0,hr.resolve)(e),JSON.stringify(t,void 0,2),"utf-8")}async function Dn(e){try{let t=new De.STSClient({region:e}),r=new De.GetCallerIdentityCommand({});return(await t.send(r)).Account}catch(t){console.log("Warning: Unable to get AWS account ID",t.message);return}}async function Wn(e){let t=await ur(e);if(e!=="us-east-1"){let r=await ur("us-east-1");t.push(...r)}return t}async function ur(e){try{let t=new z.ACMClient({region:e}),r=new z.ListCertificatesCommand({MaxItems:1e3});return(await t.send(r)).CertificateSummaryList}catch(t){return console.log("Warning: Unable to list certificates",t.message),[]}}async function Mn(e,t,r,o){let n=e[On(o)],a=t.find(c=>c.CertificateArn?.includes(r)&&c.DomainName===n);if(a)return i(`Found existing certificate for "${n}" in "${r}.`),a.CertificateArn;if(i(`No existing certificate found for "${n}" in "${r}.`),!await Re("Do you want to request a new certificate?"))return i(`Please add your certificate ARN to the config file in the "${gr(o)}" setting.`),"TODO";let s=await Jn(r,n);return i("Certificate ARN: "+s),s}async function Jn(e,t){try{let r=await ut("Validate certificate using DNS or email validation?",["dns","email"],"dns"),o=new z.ACMClient({region:e}),n=new z.RequestCertificateCommand({DomainName:t,ValidationMethod:r.toUpperCase()});return(await o.send(n)).CertificateArn}catch(r){return console.log("Error: Unable to request certificate",r.message),"TODO"}}async function Nn(e){let t=(0,he.randomUUID)(),r=(0,he.generateKeyPairSync)("rsa",{modulusLength:2048,publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs1",format:"pem",cipher:"aes-256-cbc",passphrase:t}});try{return{keyId:(await new Oe.CloudFrontClient({}).send(new Oe.CreatePublicKeyCommand({PublicKeyConfig:{Name:e,CallerReference:(0,he.randomUUID)(),EncodedKey:r.publicKey}}))).PublicKey?.Id,publicKey:r.publicKey,privateKey:r.privateKey,passphrase:t}}catch(o){console.log("Error: Unable to create signing key: ",(0,fr.normalizeErrorString)(o));return}}async function Un(e,t){let r=new oe.GetParameterCommand({Name:t,WithDecryption:!0});try{return(await e.send(r)).Parameter?.Value}catch(o){if(o.name==="ParameterNotFound")return;throw o}}async function Ln(e,t,r){let o=new oe.PutParameterCommand({Name:t,Value:r,Type:"SecureString",Overwrite:!0});await e.send(o)}async function $n(e,t,r){let o=new oe.SSMClient({region:e});for(let[n,a]of Object.entries(r)){let s=t+n,c=a.toString(),p=await Un(o,s);p!==void 0&&p!==c&&(i(`Parameter "${s}" exists with different value.`),await lt(`Do you want to overwrite "${s}"?`)),await Ln(o,s,c)}}async function Sr(){let e=await dt();for(let t of e){let r=t.StackName,o=await pt(r);o&&(Ke(o),console.log(""))}}var Er=require("@aws-sdk/client-s3"),H=require("@medplum/core"),br=T(require("fast-glob")),I=require("fs"),ft=T(require("node-fetch")),Cr=require("os"),X=require("path"),Ar=require("stream/promises");async function Pr(e,t){let r=re(e);if(!r){console.log("Config not found");return}let o=await B(e);if(!o){console.log("Stack not found");return}let n=o.appBucket;if(!n){console.log("App bucket not found");return}let a=await Fn("@medplum/app","latest");vr(a,{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 Gn(a,n.PhysicalResourceId,t),o.appDistribution?.PhysicalResourceId&&!t.dryrun&&await He(o.appDistribution.PhysicalResourceId),console.log("Done")}async function Bn(e,t){let r=`https://registry.npmjs.org/${e}/${t}`;return(await(0,ft.default)(r)).json()}async function Fn(e,t){let o=(await Bn(e,t)).dist.tarball,n=(0,I.mkdtempSync)((0,X.join)((0,Cr.tmpdir)(),"tarball-"));try{let a=await(0,ft.default)(o),s=Qt(n);return await(0,Ar.pipeline)(a.body,s),(0,X.join)(n,"package","dist")}catch(a){throw(0,I.rmSync)(n,{recursive:!0,force:!0}),a}}function vr(e,t){for(let r of(0,I.readdirSync)(e,{withFileTypes:!0})){let o=(0,X.join)(e,r.name);r.isDirectory()?vr(o,t):r.isFile()&&o.endsWith(".js")&&jn(o,t)}}function jn(e,t){let r=(0,I.readFileSync)(e,"utf-8");for(let[o,n]of Object.entries(t))r=r.replaceAll(`__${o}__`,n);(0,I.writeFileSync)(e,r)}async function Gn(e,t,r){let o=[["assets/**/*.css",H.ContentType.CSS,!0],["assets/**/*.css.map",H.ContentType.JSON,!0],["assets/**/*.js",H.ContentType.JAVASCRIPT,!0],["assets/**/*.js.map",H.ContentType.JSON,!0],["assets/**/*.txt",H.ContentType.TEXT,!0],["assets/**/*.ico",H.ContentType.FAVICON,!0],["img/**/*.png",H.ContentType.PNG,!0],["img/**/*.svg",H.ContentType.SVG,!0],["robots.txt",H.ContentType.TEXT,!0],["index.html",H.ContentType.HTML,!1]];for(let n of o)await Vn({rootDir:e,bucketName:t,fileNamePattern:n[0],contentType:n[1],cached:n[2],dryrun:r.dryrun})}async function Vn(e){let t=br.default.sync(e.fileNamePattern,{cwd:e.rootDir});for(let r of t)await zn((0,X.join)(e.rootDir,r),e)}async function zn(e,t){let r=(0,I.createReadStream)(e),o=e.substring(t.rootDir.length+1).split(X.sep).join("/"),n={Bucket:t.bucketName,Key:o,Body:r,ContentType:t.contentType,CacheControl:t.cached?"public, max-age=31536000":"no-cache, no-store, must-revalidate"};console.log(`Uploading ${o} to ${t.bucketName}...`),t.dryrun||await ue.send(new Er.PutObjectCommand(n))}var Me=require("@aws-sdk/client-s3");async function _r(e,t){if(!re(e)){console.log("Config not found");return}let o=await B(e);if(!o){console.log("Stack not found");return}await xr("App",o.appBucket,o.appDistribution,o.appOriginAccessIdentity,t),await xr("Storage",o.storageBucket,o.storageDistribution,o.storageOriginAccessIdentity,t),console.log("Done")}async function xr(e,t,r,o,n){if(!t?.PhysicalResourceId){console.log(`${e} bucket not found`);return}if(!r?.PhysicalResourceId){console.log(`${e} distribution not found`);return}if(!o?.PhysicalResourceId){console.log(`${e} OAI not found`);return}let a=t.PhysicalResourceId,s=o.PhysicalResourceId,c=await Xn(a);if(Yn(c,a,s)){console.log(`${e} bucket already has policy statement`);return}Zn(c,a,s),console.log(`${e} bucket policy:`),console.log(JSON.stringify(c,void 0,2)),n.dryrun?console.log("Dry run - skipping updates"):(console.log("Updating bucket policy..."),await qn(a,c),console.log("Bucket policy updated"),console.log("Creating CloudFront invalidation..."),await He(r.PhysicalResourceId),console.log("CloudFront invalidation created"),console.log(`${e} bucket policy updated`))}async function Xn(e){let t=await ue.send(new Me.GetBucketPolicyCommand({Bucket:e}));return JSON.parse(t.Policy??"{}")}async function qn(e,t){await ue.send(new Me.PutBucketPolicyCommand({Bucket:e,Policy:JSON.stringify(t)}))}function Yn(e,t,r){return!!e?.Statement?.some(o=>o?.Effect==="Allow"&&o?.Principal?.AWS===`arn:aws:iam::cloudfront:user/CloudFront Origin Access Identity ${r}`&&Array.isArray(o?.Action)&&o?.Action?.includes("s3:GetObject*")&&o?.Action?.includes("s3:GetBucket*")&&o?.Action?.includes("s3:List*")&&Array.isArray(o?.Resource)&&o?.Resource?.includes(`arn:aws:s3:::${t}`)&&o?.Resource?.includes(`arn:aws:s3:::${t}/*`))}function Zn(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}/*`]})}var Ir=require("@aws-sdk/client-ecs");async function Tr(e){let t=await B(e);if(!t){console.log("Stack not found");return}let r=t.ecsCluster?.PhysicalResourceId;if(!r){console.log("ECS Cluster not found");return}let o=mt(t.ecsService);if(!o){console.log("ECS Service not found");return}await mr.send(new Ir.UpdateServiceCommand({cluster:r,service:o,forceNewDeployment:!0})),console.log(`Service "${o}" updated successfully.`)}var F=new Kr.Command("aws").description("Commands to manage AWS resources");F.command("init").description("Initialize a new Medplum AWS CloudFormation stacks").action(wr);F.command("list").description("List Medplum AWS CloudFormation stacks").action(Sr);F.command("describe").description("Describe a Medplum AWS CloudFormation stack by tag").argument("<tag>").action(lr);F.command("update-server").alias("deploy-server").description("Update the server image").argument("<tag>").action(Tr);F.command("update-app").alias("deploy-app").description("Update the app site").argument("<tag>").option("--dryrun","Displays the operations that would be performed using the specified command without actually running them.").action(Pr);F.command("update-bucket-policies").description("Update S3 bucket policies").argument("<tag>").option("--dryrun","Displays the operations that would be performed using the specified command without actually running them.").action(_r);var Hr=require("commander");var kr=d("save"),Rr=d("deploy"),Or=d("create"),Dr=new Hr.Command("bot").addCommand(kr).addCommand(Rr).addCommand(Or),ht=d("save-bot"),yt=d("deploy-bot"),gt=d("create-bot");kr.description("Saving the bot").argument("<botName>").action(async(e,t)=>{let r=await l(t);await Je(r,e)});Rr.description("Deploy the app to AWS").argument("<botName>").action(async(e,t)=>{let r=await l(t);await Je(r,e,!0)});Or.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,o,n)=>{let a=await l(n);await nt(a,e,t,r,o,n.runtimeVersion,!!n.writeConfig)});async function Je(e,t,r=!1){let o=Zt(t);for(let n of o){let a=await e.readResource("Bot",n.id);await rt(e,n,a),r&&await ot(e,n,a)}console.log(`Number of bots deployed: ${o.length}`)}ht.description("Saves the bot").argument("<botName>").action(async(e,t)=>{let r=await l(t);await Je(r,e)});yt.description("Deploy the bot to AWS").argument("<botName>").action(async(e,t)=>{let r=await l(t);await Je(r,e,!0)});gt.arguments("<botName> <projectId> <sourceFile> <distFile>").description("Creates and saves the bot").action(async(e,t,r,o,n)=>{let a=await l(n);await nt(a,e,t,r,o)});var Mr=require("commander"),Ne=require("fs"),wt=require("path"),Jr=require("readline");var Nr=d("export"),Ur=d("import"),Lr=new Mr.Command("bulk").addCommand(Nr).addCommand(Ur);Nr.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:o,targetDirectory:n}=e,a=await l(e);(await a.bulkExport(t,r,o)).output?.forEach(async({type:c,url:p})=>{let g=new URL(p),b=await a.download(p),k=`${c}_${g.pathname}`.replace(/[^a-zA-Z0-9]+/g,"_")+".ndjson",ge=(0,wt.resolve)(n??"",k);(0,Ne.writeFile)(`${ge}`,await b.text(),()=>{console.log(`${ge} is created`)})})});Ur.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:o,targetDirectory:n}=t,a=(0,wt.resolve)(n??process.cwd(),e),s=await l(t);await Qn(a,parseInt(r,10),s,o)});async function Qn(e,t,r,o){let n=[],a=(0,Ne.createReadStream)(e),s=(0,Jr.createInterface)({input:a});for await(let c of s){let p=ei(c,o);n.push({resource:p,request:{method:"POST",url:p.resourceType}}),n.length%t===0&&(await Wr(n,r),n=[])}n.length>0&&await Wr(n,r)}async function Wr(e,t){(await t.executeBatch({resourceType:"Bundle",type:"transaction",entry:e})).entry?.forEach(o=>{M(o.response)})}function ei(e,t){let r=JSON.parse(e);return t?ti(r):r}function ti(e){return e.resourceType==="ExplanationOfBenefit"?ri(e):e}function ri(e){return e.provider||(e.provider=at()),e.item?.forEach(t=>{t?.productOrService||(t.productOrService=at())}),e}var Ue=require("@medplum/core");var Gr=require("net"),Vr=require("@medplum/core"),qr=T(require("net"),1),jr=class extends EventTarget{addEventListener(e,t,r){super.addEventListener(e,t,r)}removeEventListener(e,t,r){super.removeEventListener(e,t,r)}},oi="\v",$r="",Br="\r",ni=class extends Event{constructor(e,t){super("message"),this.connection=e,this.message=t}},Fr=class extends Event{constructor(e){super("error"),this.error=e}},zr=class extends jr{constructor(e,t){super(),this.socket=e,this.encoding=t;let r="";e.on("data",o=>{try{if(r+=o.toString(),r.endsWith($r+Br)){let n=Vr.Hl7Message.parse(r.substring(1,r.length-2));this.dispatchEvent(new ni(this,n)),r=""}}catch(n){this.dispatchEvent(new Fr(n))}}).setEncoding(t??"utf-8"),e.on("error",o=>{r="",this.dispatchEvent(new Fr(o))})}send(e){this.socket.write(oi+e.toString()+$r+Br)}async sendAndWait(e){let t=new Promise(r=>{function o(n){n.target.removeEventListener("message",o),r(n.message)}this.addEventListener("message",o)});return this.send(e),t}close(){this.socket.end(),this.socket.destroy()}},Xr=class extends jr{constructor(e){super(),this.options=e,this.host=this.options.host,this.port=this.options.port}connect(){return this.connection?Promise.resolve(this.connection):new Promise(e=>{let t=(0,Gr.connect)({host:this.host,port:this.port},()=>{this.connection=new zr(t),e(this.connection)})})}async send(e){return(await this.connect()).send(e)}async sendAndWait(e){return(await this.connect()).sendAndWait(e)}close(){this.connection&&(this.connection.close(),delete this.connection)}},Yr=class{constructor(e){this.handler=e}start(e,t){let r=qr.default.createServer(o=>{let n=new zr(o,t);this.handler(n)});r.listen(e),this.server=r}stop(){this.server&&(this.server.close(),this.server=void 0)}};var Zr=require("commander"),Qr=require("fs");var ii=d("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").action(async(e,t,r,o)=>{if(o.generateExample?r=si():o.file&&(r=(0,Qr.readFileSync)(o.file,"utf8")),!r)throw new Error("Missing HL7 message body");let n=new Xr({host:e,port:parseInt(t,10)});try{let a=await n.sendAndWait(Ue.Hl7Message.parse(r));console.log(a.toString().replaceAll("\r",`
6
- `))}finally{n.close()}}),ai=d("listen").description("Starts an HL7 v2 MLLP server").argument("<port>").action(async e=>{new Yr(r=>{r.addEventListener("message",({message:o})=>{console.log(o.toString().replaceAll("\r",`
7
- `)),r.send(o.buildAck())})}).start(parseInt(e,10)),console.log("Listening on port "+e)}),eo=new Zr.Command("hl7").addCommand(ii).addCommand(ai);function si(){let e=(0,Ue.formatHl7DateTime)(new Date),t=Date.now().toString();return`MSH|^~\\&|ADTSYS|HOSPITAL|RECEIVER|DEST|${e}||ADT^A01|${t}|P|2.5|
5
+ `)}function D(e,t=""){return new Promise(r=>{Ye.question(e+(t?" ("+t+")":"")+" ",o=>{r(o||t.toString())})})}async function et(e,t,r=""){let o=e+" ["+t.map(n=>n===r?"("+n+")":n).join("|")+"]";for(;;){let n=await D(o)||r;if(t.includes(n))return n;s("Please choose one of the following options: "+t.join(", "))}}async function Se(e,t,r){return parseInt(await et(e,t.map(o=>o.toString()),r.toString()),10)}async function pe(e){return(await et(e,["y","n"])).toLowerCase()==="y"}async function He(e){if(!await pe(e))throw s("Exiting..."),new Error("User cancelled")}var tt=new Q.CloudFormationClient({}),Pi=new rt.CloudFrontClient({region:"us-east-1"}),ch=new Xr.ECSClient({}),ke=new zr.S3Client({}),Ri="medplum:environment";async function Ft(){return(await tt.send(new Q.ListStacksCommand({}))).StackSummaries?.filter(t=>t.StackName&&t.StackStatus!=="DELETE_COMPLETE")||[]}async function be(e){let t=await Ft();for(let r of t){let o=r.StackName,n=await Bt(o);if(n?.tag===e)return n}}async function Bt(e){let t={};if(await Vr(tt,e,t),await tt.config.region()!=="us-east-1")try{await Vr(new Q.CloudFormationClient({region:"us-east-1"}),e+"-us-east-1",t)}catch{}return t}async function Vr(e,t,r){let o=new Q.DescribeStacksCommand({StackName:t}),i=(await e.send(o))?.Stacks?.[0],c=i?.Tags?.find(d=>d.Key===Ri);if(!c)return;let l=await e.send(new Q.DescribeStackResourcesCommand({StackName:t}));if(l.StackResources){e===tt&&(r.stack=i,r.tag=c.Value);for(let d of l.StackResources)Ti(d,r)}}function Ti(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 nt(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: ${xi(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 xi(e){return e?.PhysicalResourceId?.split("/")?.pop()||""}async function it(e){let t=await Pi.send(new rt.CreateInvalidationCommand({DistributionId:e,InvalidationBatch:{CallerReference:`invalidate-all-${Date.now()}`,Paths:{Quantity:1,Items:["/*"]}}}));console.log(`Created invalidation with ID: ${t.Invalidation?.Id}`)}async function at(e){let o=(await(await(0,Zr.default)("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(n=>n.tag_name.startsWith("v")?n.tag_name.slice(1):n.tag_name);return e?o.slice(0,o.indexOf(e)):o}async function st(e,t,r){let o=new Ae.SSMClient({region:e});for(let[n,i]of Object.entries(r)){let c=t+n,l=i.toString(),d=await Oi(o,c);d!==void 0&&d!==l&&(s(`Parameter "${c}" exists with different value.`),await He(`Do you want to overwrite "${c}"?`)),await Ni(o,c,l)}}async function Oi(e,t){let r=new Ae.GetParameterCommand({Name:t,WithDecryption:!0});try{return(await e.send(r)).Parameter?.Value}catch(o){if(o.name==="ParameterNotFound")return;throw o}}async function Ni(e,t,r){let o=new Ae.PutParameterCommand({Name:t,Value:r,Type:"SecureString",Overwrite:!0});await e.send(o)}async function ct(e){console.log(`Config not found: ${e}`),console.log();let t=(0,Yr.readdirSync)(".",{withFileTypes:!0});if(t=t.filter(r=>r.isFile()&&r.name.startsWith("medplum.")&&r.name.endsWith(".json")).map(r=>r.name),t.length===0)console.log("No configs found");else{console.log("Available configs:");for(let r of t)console.log(` ${r.replaceAll("medplum.","").replaceAll(".config","").replaceAll(".server","").replaceAll(".json","").padEnd(40," ")} (${r})`)}}async function Ce(e){console.log(`Stack not found: ${e}`),console.log();try{let t=new ot.STSClient,r=new ot.GetCallerIdentityCommand({}),o=await t.send(r),n=await t.config.region();console.log("AWS Region: ",n),console.log("AWS Account ID: ",o.Account),console.log("AWS Account ARN: ",o.Arn),console.log("AWS User ID: ",o.UserId)}catch(t){console.log("Warning: Unable to get AWS account ID",(0,qr.normalizeErrorString)(t))}}async function Qr(e){let t=await be(e);if(!t){await Ce(e);return}nt(t)}var de=require("@aws-sdk/client-acm"),pt=require("@aws-sdk/client-cloudfront"),dt=require("@aws-sdk/client-sts"),to=require("@medplum/core"),Le=require("crypto"),ro=require("fs");var _i=e=>`${e}DomainName`,oo=e=>`${e}SslCertArn`;async function no(){let e={apiPort:8103,region:"us-east-1"};Ze(),v("MEDPLUM"),s("This tool prepares the necessary prerequisites for deploying Medplum in your AWS account."),s(""),s("Most Medplum infrastructure is deployed using the AWS CDK."),s("However, some AWS resources must be created manually, such as email addresses and SSL certificates."),s("This tool will help you create those resources."),s(""),s("Upon completion, this tool will:"),s(" 1. Generate a Medplum CDK config file (i.e., medplum.demo.config.json)"),s(" 2. Optionally generate an AWS CloudFront signing key"),s(" 3. Optionally request SSL certificates from AWS Certificate Manager"),s(" 4. Optionally write server config settings to AWS Parameter Store"),s(""),s("The Medplum infra config file is an input to the Medplum CDK."),s("The Medplum CDK will create and manage the necessary AWS resources."),s(""),s("We will ask a series of questions to generate your infra config file."),s("Some questions have predefined options in [square brackets]."),s("Some questions have default values in (parentheses), which you can accept by pressing Enter."),s("Press Ctrl+C at any time to exit.");let t=await Di(e.region);t||(s("It appears that you do not have AWS credentials configured."),s("AWS credentials are not strictly required, but will enable some additional features."),s("If you intend to use AWS credentials, please configure them now."),await He("Do you want to continue without AWS credentials?")),v("ENVIRONMENT NAME"),s('Medplum deployments have a short environment name such as "prod", "staging", "alice", or "demo".'),s("The environment name is used in multiple places:"),s(" 1. As part of config file names (i.e., medplum.demo.config.json)"),s(" 2. As the base of CloudFormation stack names (i.e., MedplumDemo)"),s(" 3. AWS Parameter Store keys (i.e., /medplum/demo/...)"),e.name=await D("What is your environment name?","demo"),s('Using environment name "'+e.name+'"...'),v("CONFIG FILE"),s("Medplum Infrastructure will create a config file in the current directory.");let r=await D("What is the config file name?",`medplum.${e.name}.config.json`);(0,ro.existsSync)(r)&&(s("Config file already exists."),await He("Do you want to overwrite the config file?")),s('Using config file "'+r+'"...'),R(r,e),v("AWS REGION"),s("Most Medplum resources will be created in a single AWS region."),e.region=await D("Enter your AWS region:","us-east-1"),R(r,e),v("AWS ACCOUNT NUMBER"),s("Medplum Infrastructure will use your AWS account number to create AWS resources."),t&&s("Using the AWS CLI, your current account ID is: "+t),e.accountNumber=await D("What is your AWS account number?",t),R(r,e),v("STACK NAME"),s("Medplum will create a CloudFormation stack to manage AWS resources."),s("AWS CloudFormation stack names ");let o="Medplum"+e.name.charAt(0).toUpperCase()+e.name.slice(1);for(e.stackName=await D("Enter your CloudFormation stack name?",o),R(r,e),v("BASE DOMAIN NAME"),s("Please enter the base domain name for your Medplum deployment."),s(""),s("Medplum deploys multiple subdomains for various services."),s(""),s('For example, "api." for the REST API and "app." for the web application.'),s("The base domain name is the common suffix for all subdomains."),s(""),s('For example, if your base domain name is "example.com",'),s('then the REST API will be "api.example.com".'),s(""),s('The base domain should include the TLD (i.e., ".com", ".org", ".net").'),s(""),s("Note that you must own the base domain, and it must use Route53 DNS.");!e.domainName;)e.domainName=await D("Enter your base domain name:");R(r,e),v("SUPPORT EMAIL"),s("Medplum sends transactional emails to users."),s("For example, emails to new users or for password reset."),s("Medplum will use the support email address to send these emails."),s("Note that you must verify the support email address in SES.");let n=await D("Enter your support email address:");v("API DOMAIN NAME"),s("Medplum deploys a REST API for the backend services."),e.apiDomainName=await D("Enter your REST API domain name:","api."+e.domainName),e.baseUrl=`https://${e.apiDomainName}/`,R(r,e),v("APP DOMAIN NAME"),s("Medplum deploys a web application for the user interface."),e.appDomainName=await D("Enter your web application domain name:","app."+e.domainName),R(r,e),v("STORAGE DOMAIN NAME"),s("Medplum deploys a storage service for file uploads."),e.storageDomainName=await D("Enter your storage domain name:","storage."+e.domainName),R(r,e),v("STORAGE BUCKET"),s("Medplum uses an S3 bucket to store binary content such as file uploads."),s("Medplum will create a the S3 bucket as part of the CloudFormation stack."),e.storageBucketName=await D("Enter your storage bucket name:",e.storageDomainName),R(r,e),v("MAX AVAILABILITY ZONES"),s("Medplum API servers can be deployed in multiple availability zones."),s("This provides redundancy and high availability."),s("However, it also increases the cost of the deployment."),s("If you want to use all availability zones, choose a large number such as 99."),s("If you want to restrict the number, for example to manage EIP limits,"),s("then choose a small number such as 2 or 3."),e.maxAzs=await Se("Enter the maximum number of availability zones:",[2,3,99],2),v("DATABASE INSTANCES"),s("Medplum uses a relational database to store data."),s("You can set up your own database,"),s("or Medplum can create a new RDS database as part of the CloudFormation stack."),await pe("Do you want to create a new RDS database as part of the CloudFormation stack?")?(s("Medplum will create a new RDS database as part of the CloudFormation stack."),s(""),s("If you need high availability, you can choose multiple instances."),s("Use 1 for a single instance, or 2 for a primary and a standby."),e.rdsInstances=await Se("Enter the number of database instances:",[1,2],1)):(s("Medplum will not create a new RDS database."),s("Please create a new RDS database and enter the database name, username, and password."),s('Set the AWS Secrets Manager secret ARN in the config file in the "rdsSecretsArn" setting.'),e.rdsSecretsArn="TODO"),R(r,e),v("SERVER INSTANCES"),s("Medplum uses AWS Fargate to run the API servers."),s("Medplum will create a new Fargate cluster as part of the CloudFormation stack."),s("Fargate will automatically scale the number of servers up and down."),s("If you need high availability, you can choose multiple instances."),e.desiredServerCount=await Se("Enter the number of server instances:",[1,2,3,4,6,8],1),R(r,e),v("SERVER MEMORY"),s("You can choose the amount of memory for each server instance."),s("The default is 512 MB, which is sufficient for getting started."),s("Note that only certain CPU units are compatible with memory units."),s('Consult AWS Fargate "Task Definition Parameters" for more information.'),e.serverMemory=await Se("Enter the server memory (MB):",[512,1024,2048,4096,8192,16384],512),R(r,e),v("SERVER CPU"),s("You can choose the amount of CPU for each server instance."),s("CPU is expressed as an integer using AWS CPU units"),s("The default is 256, which is sufficient for getting started."),s("Note that only certain CPU units are compatible with memory units."),s('Consult AWS Fargate "Task Definition Parameters" for more information.'),e.serverCpu=await Se("Enter the server CPU:",[256,512,1024,2048,4096,8192,16384],256),R(r,e),v("SERVER IMAGE"),s("Medplum uses Docker images for the API servers."),s("You can choose the image to use for the servers."),s("Docker images can be loaded from either Docker Hub or AWS ECR."),s("The default is the latest Medplum release.");let i=(await at())[0]??"latest";e.serverImage=await D("Enter the server image:",`medplum/medplum-server:${i}`),R(r,e),v("SIGNING KEY"),s("Medplum uses AWS CloudFront Presigned URLs for binary content such as file uploads.");let c=await Li(e.stackName+"SigningKey");c?(e.signingKeyId=c.keyId,e.storagePublicKey=c.publicKey,R(r,e)):(s("Unable to generate signing key."),s("Please manually create a signing key and enter the key ID and public key in the config file."),s('You must set the "signingKeyId", "signingKey", and "signingKeyPassphrase" settings.')),v("SSL CERTIFICATES"),s("Medplum will now check for existing SSL certificates for the subdomains.");let l=await Ki(e.region);s("Found "+l.length+" certificate(s).");for(let{region:w,certName:A}of[{region:e.region,certName:"api"},{region:"us-east-1",certName:"app"},{region:"us-east-1",certName:"storage"}]){s("");let b=await Hi(e,l,w,A);e[oo(A)]=b,R(r,e)}v("AWS PARAMETER STORE"),s("Medplum uses AWS Parameter Store to store sensitive configuration values."),s("These values will be encrypted at rest."),s(`The values will be stored in the "/medplum/${e.name}" path.`);let d={port:e.apiPort,baseUrl:e.baseUrl,appBaseUrl:`https://${e.appDomainName}/`,storageBaseUrl:`https://${e.storageDomainName}/binary/`,binaryStorage:`s3:${e.storageBucketName}`,supportEmail:n};if(c&&(d.signingKeyId=c.keyId,d.signingKey=c.privateKey,d.signingKeyPassphrase=c.passphrase),s(JSON.stringify({...d,signingKey:"****",signingKeyPassphrase:"****"},null,2)),await pe("Do you want to store these values in AWS Parameter Store?"))await st(e.region,`/medplum/${e.name}/`,d);else{let w=ie(e.name,!0);R(w,d),s("Skipping AWS Parameter Store."),s(`Writing values to local config file: ${w}`),s("Please add these values to AWS Parameter Store manually.")}v("DONE!"),s("Medplum configuration complete."),s("You can now proceed to deploying the Medplum infrastructure with CDK."),s("Run:"),s(""),s(` npx cdk bootstrap -c config=${r}`),s(` npx cdk synth -c config=${r}`),e.region==="us-east-1"?s(` npx cdk deploy -c config=${r}`):s(` npx cdk deploy -c config=${r} --all`),s(""),s("See Medplum documentation for more information:"),s(""),s(" https://www.medplum.com/docs/self-hosting/install-on-aws"),s(""),Qe()}async function Di(e){try{let t=new dt.STSClient({region:e}),r=new dt.GetCallerIdentityCommand({});return(await t.send(r)).Account}catch(t){console.log("Warning: Unable to get AWS account ID",t.message);return}}async function Ki(e){let t=await eo(e);if(e!=="us-east-1"){let r=await eo("us-east-1");t.push(...r)}return t}async function eo(e){try{let t=new de.ACMClient({region:e}),r=new de.ListCertificatesCommand({MaxItems:1e3});return(await t.send(r)).CertificateSummaryList}catch(t){return console.log("Warning: Unable to list certificates",t.message),[]}}async function Hi(e,t,r,o){let n=e[_i(o)],i=t.find(l=>l.CertificateArn?.includes(r)&&l.DomainName===n);if(i)return s(`Found existing certificate for "${n}" in "${r}.`),i.CertificateArn;if(s(`No existing certificate found for "${n}" in "${r}.`),!await pe("Do you want to request a new certificate?"))return s(`Please add your certificate ARN to the config file in the "${oo(o)}" setting.`),"TODO";let c=await ki(r,n);return s("Certificate ARN: "+c),c}async function ki(e,t){try{let r=await et("Validate certificate using DNS or email validation?",["dns","email"],"dns"),o=new de.ACMClient({region:e}),n=new de.RequestCertificateCommand({DomainName:t,ValidationMethod:r.toUpperCase()});return(await o.send(n)).CertificateArn}catch(r){return console.log("Error: Unable to request certificate",r.message),"TODO"}}async function Li(e){let t=(0,Le.randomUUID)(),r=(0,Le.generateKeyPairSync)("rsa",{modulusLength:2048,publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs1",format:"pem",cipher:"aes-256-cbc",passphrase:t}});try{return{keyId:(await new pt.CloudFrontClient({}).send(new pt.CreatePublicKeyCommand({PublicKeyConfig:{Name:e,CallerReference:(0,Le.randomUUID)(),EncodedKey:r.publicKey}}))).PublicKey?.Id,publicKey:r.publicKey,privateKey:r.privateKey,passphrase:t}}catch(o){console.log("Error: Unable to create signing key: ",(0,to.normalizeErrorString)(o));return}}async function io(){let e=await Ft();for(let t of e){let r=t.StackName,o=await Bt(r);o&&(nt(o),console.log(""))}}var ao=require("@aws-sdk/client-s3"),G=require("@medplum/core"),so=H(require("fast-glob")),J=require("fs"),Gt=H(require("node-fetch")),co=require("os"),le=require("path"),po=require("stream/promises");async function lo(e,t){let r=B(e);if(!r){await ct(e);return}let o=await be(e);if(!o){await Ce(e);return}let n=o.appBucket;if(!n){console.log("App bucket not found");return}let i=await Wi("@medplum/app","latest");uo(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 Ji(i,n.PhysicalResourceId,t),o.appDistribution?.PhysicalResourceId&&!t.dryrun&&await it(o.appDistribution.PhysicalResourceId),console.log("Done")}async function Mi(e,t){let r=`https://registry.npmjs.org/${e}/${t}`;return(await(0,Gt.default)(r)).json()}async function Wi(e,t){let o=(await Mi(e,t)).dist.tarball,n=(0,J.mkdtempSync)((0,le.join)((0,co.tmpdir)(),"tarball-"));try{let i=await(0,Gt.default)(o),c=Lr(n);return await(0,po.pipeline)(i.body,c),(0,le.join)(n,"package","dist")}catch(i){throw(0,J.rmSync)(n,{recursive:!0,force:!0}),i}}function uo(e,t){for(let r of(0,J.readdirSync)(e,{withFileTypes:!0})){let o=(0,le.join)(e,r.name);r.isDirectory()?uo(o,t):r.isFile()&&o.endsWith(".js")&&Ui(o,t)}}function Ui(e,t){let r=(0,J.readFileSync)(e,"utf-8");for(let[o,n]of Object.entries(t))r=r.replaceAll(`__${o}__`,n);(0,J.writeFileSync)(e,r)}async function Ji(e,t,r){let o=[["assets/**/*.css",G.ContentType.CSS,!0],["assets/**/*.css.map",G.ContentType.JSON,!0],["assets/**/*.js",G.ContentType.JAVASCRIPT,!0],["assets/**/*.js.map",G.ContentType.JSON,!0],["assets/**/*.txt",G.ContentType.TEXT,!0],["assets/**/*.ico",G.ContentType.FAVICON,!0],["img/**/*.png",G.ContentType.PNG,!0],["img/**/*.svg",G.ContentType.SVG,!0],["robots.txt",G.ContentType.TEXT,!0],["index.html",G.ContentType.HTML,!1]];for(let n of o)await $i({rootDir:e,bucketName:t,fileNamePattern:n[0],contentType:n[1],cached:n[2],dryrun:r.dryrun})}async function $i(e){let t=so.default.sync(e.fileNamePattern,{cwd:e.rootDir});for(let r of t)await Fi((0,le.join)(e.rootDir,r),e)}async function Fi(e,t){let r=(0,J.createReadStream)(e),o=e.substring(t.rootDir.length+1).split(le.sep).join("/"),n={Bucket:t.bucketName,Key:o,Body:r,ContentType:t.contentType,CacheControl:t.cached?"public, max-age=31536000":"no-cache, no-store, must-revalidate"};console.log(`Uploading ${o} to ${t.bucketName}...`),t.dryrun||await ke.send(new ao.PutObjectCommand(n))}var lt=require("@aws-sdk/client-s3");async function fo(e,t){if(!B(e)){await ct(e);return}let o=await be(e);if(!o){await Ce(e);return}await mo("App",o.appBucket,o.appDistribution,o.appOriginAccessIdentity,t),await mo("Storage",o.storageBucket,o.storageDistribution,o.storageOriginAccessIdentity,t),console.log("Done")}async function mo(e,t,r,o,n){if(!t?.PhysicalResourceId){console.log(`${e} bucket not found`);return}if(!r?.PhysicalResourceId){console.log(`${e} distribution not found`);return}if(!o?.PhysicalResourceId){console.log(`${e} OAI not found`);return}let i=t.PhysicalResourceId,c=o.PhysicalResourceId,l=await Bi(i);if(ji(l,i,c)){console.log(`${e} bucket already has policy statement`);return}Vi(l,i,c),console.log(`${e} bucket policy:`),console.log(JSON.stringify(l,void 0,2)),n.dryrun?console.log("Dry run - skipping updates"):(console.log("Updating bucket policy..."),await Gi(i,l),console.log("Bucket policy updated"),console.log("Creating CloudFront invalidation..."),await it(r.PhysicalResourceId),console.log("CloudFront invalidation created"),console.log(`${e} bucket policy updated`))}async function Bi(e){let t=await ke.send(new lt.GetBucketPolicyCommand({Bucket:e}));return JSON.parse(t.Policy??"{}")}async function Gi(e,t){await ke.send(new lt.PutBucketPolicyCommand({Bucket:e,Policy:JSON.stringify(t)}))}function ji(e,t,r){return!!e?.Statement?.some(o=>o?.Effect==="Allow"&&o?.Principal?.AWS===`arn:aws:iam::cloudfront:user/CloudFront Origin Access Identity ${r}`&&Array.isArray(o?.Action)&&o?.Action?.includes("s3:GetObject*")&&o?.Action?.includes("s3:GetBucket*")&&o?.Action?.includes("s3:List*")&&Array.isArray(o?.Resource)&&o?.Resource?.includes(`arn:aws:s3:::${t}`)&&o?.Resource?.includes(`arn:aws:s3:::${t}/*`))}function Vi(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 ho(e){try{Ze();let t=B(e);if(!t){console.log(`Configuration file ${ie(e)} not found`);return}let r=B(e,!0)??{};Xi(t,r),qi(t,r),s("Medplum uses AWS Parameter Store to store sensitive configuration values."),s("These values will be encrypted at rest."),s(`The values will be stored in the "/medplum/${t.name}" path.`),s(JSON.stringify({...r,signingKey:"****",signingKeyPassphrase:"****"},null,2)),await pe("Do you want to store these values in AWS Parameter Store?")&&await st(t.region,`/medplum/${t.name}/`,r)}finally{Qe()}}function Xi(e,t){ut(e.apiPort,t.port,`Infra "apiPort" (${e.apiPort}) does not match server "port" (${t.port})`),ut(e.baseUrl,t.baseUrl,`Infra "baseUrl" (${e.baseUrl}) does not match server "baseUrl" (${t.baseUrl})`),ut(e.appDomainName&&`https://${e.appDomainName}/`,t.appBaseUrl,`Infra "appDomainName" (${e.appDomainName}) does not match server "appBaseUrl" (${t.appBaseUrl})`),ut(e.storageDomainName&&`https://${e.storageDomainName}/`,t.storageBaseUrl,`Infra "storageDomainName" (${e.storageDomainName}) does not match server "storageBaseUrl" (${t.storageBaseUrl})`)}function ut(e,t,r){if(zi(e,t))throw new Error(r)}function zi(e,t){return e!==void 0&&t!==void 0&&e!==t}function qi(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}/`)}var Co=require("child_process"),gt=H(Ao());async function vo(e,t){let r=await S(t),o=B(e);if(!o){console.log(`Configuration file ${ie(e)} not found`);return}let n=o.serverImage.lastIndexOf(":"),i=o.serverImage.slice(n+1);if(i==="latest"){i=JSON.parse(await r.get("/healthcheck")).version;let d=i.indexOf("-");d>-1&&(i=i.slice(0,d))}let c=await bo(i);for(;c;)console.log(`Performing update to v${c}`),o.serverImage=`${o.serverImage.slice(0,n)}:${c}`,Ka(e,o),await r.startAsyncRequest("/admin/super/migrate"),c=await bo(c)}async function bo(e){return(await at(e)).filter(t=>gt.gte(t,gt.inc(e,"minor"))).pop()}function Ka(e,t){let r=ie(e);R(r,t);let o=`npx cdk deploy -c config=${r}${t.region!=="us-east-1"?" --all":""}`;console.log("> "+o);let n=(0,Co.spawnSync)(o,{stdio:"inherit"});if(n.status!==0)throw new Error(`Deploy of ${t.serverImage} failed (exit code ${n.status}): ${n.stderr}`);console.log(n.stdout)}var te=new Io.Command("aws").description("Commands to manage AWS resources");te.command("init").description("Initialize a new Medplum AWS CloudFormation stacks").action(no);te.command("list").description("List Medplum AWS CloudFormation stacks").action(io);te.command("describe").description("Describe a Medplum AWS CloudFormation stack by tag").argument("<tag>").action(Qr);te.command("update-config").alias("deploy-config").description("Update the AWS Parameter Store config values").argument("<tag>").option("--dryrun","Displays the operations that would be performed using the specified command without actually running them.").action(ho);te.addCommand(h("update-server").alias("deploy-server").description("Update the server image").argument("<tag>").action(vo));te.command("update-app").alias("deploy-app").description("Update the app site").argument("<tag>").option("--dryrun","Displays the operations that would be performed using the specified command without actually running them.").action(lo);te.command("update-bucket-policies").description("Update S3 bucket policies").argument("<tag>").option("--dryrun","Displays the operations that would be performed using the specified command without actually running them.").action(fo);var Po=require("commander");var Ro=h("save"),To=h("deploy"),xo=h("create"),Oo=new Po.Command("bot").addCommand(Ro).addCommand(To).addCommand(xo),Qt=h("save-bot"),er=h("deploy-bot"),tr=h("create-bot");Ro.description("Saving the bot").argument("<botName>").action(async(e,t)=>{let r=await S(t);await wt(r,e)});To.description("Deploy the app to AWS").argument("<botName>").action(async(e,t)=>{let r=await S(t);await wt(r,e,!0)});xo.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,o,n)=>{let i=await S(n);await Mt(i,e,t,r,o,n.runtimeVersion,!!n.writeConfig)});async function wt(e,t,r=!1){let o=kr(t);for(let n of o){let i=await e.readResource("Bot",n.id);await kt(e,n,i),r&&await Lt(e,n,i)}console.log(`Number of bots deployed: ${o.length}`)}Qt.description("Saves the bot").argument("<botName>").action(async(e,t)=>{let r=await S(t);await wt(r,e)});er.description("Deploy the bot to AWS").argument("<botName>").action(async(e,t)=>{let r=await S(t);await wt(r,e,!0)});tr.arguments("<botName> <projectId> <sourceFile> <distFile>").description("Creates and saves the bot").action(async(e,t,r,o,n)=>{let i=await S(n);await Mt(i,e,t,r,o)});var _o=require("commander"),Et=require("fs"),rr=require("path"),Do=require("readline");var Ko=h("export"),Ho=h("import"),ko=new _o.Command("bulk").addCommand(Ko).addCommand(Ho);Ko.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:o,targetDirectory:n}=e,i=await S(e);(await i.bulkExport(t,r,o)).output?.forEach(async({type:l,url:d})=>{let w=new URL(d),A=await i.download(d),b=`${l}_${w.pathname}`.replace(/[^a-zA-Z0-9]+/g,"_")+".ndjson",T=(0,rr.resolve)(n??"",b);(0,Et.writeFile)(`${T}`,await A.text(),()=>{console.log(`${T} is created`)})})});Ho.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:o,targetDirectory:n}=t,i=(0,rr.resolve)(n??process.cwd(),e),c=await S(t);await Ha(i,parseInt(r,10),c,o)});async function Ha(e,t,r,o){let n=[],i=(0,Et.createReadStream)(e),c=(0,Do.createInterface)({input:i});for await(let l of c){let d=ka(l,o);n.push({resource:d,request:{method:"POST",url:d.resourceType}}),n.length%t===0&&(await No(n,r),n=[])}n.length>0&&await No(n,r)}async function No(e,t){(await t.executeBatch({resourceType:"Bundle",type:"transaction",entry:e})).entry?.forEach(o=>{Z(o.response)})}function ka(e,t){let r=JSON.parse(e);return t?La(r):r}function La(e){return e.resourceType==="ExplanationOfBenefit"?Ma(e):e}function Ma(e){return e.provider||(e.provider=Ut()),e.item?.forEach(t=>{t?.productOrService||(t.productOrService=Ut())}),e}var St=require("@medplum/core");var Jo=require("net"),$o=require("@medplum/core"),Go=H(require("net"),1),Uo=class extends EventTarget{addEventListener(e,t,r){super.addEventListener(e,t,r)}removeEventListener(e,t,r){super.removeEventListener(e,t,r)}},Wa="\v",Lo="",Mo="\r",Ua=class extends Event{constructor(e,t){super("message"),this.connection=e,this.message=t}},Wo=class extends Event{constructor(e){super("error"),this.error=e}},Fo=class extends Uo{constructor(e,t){super(),this.socket=e,this.encoding=t;let r="";e.on("data",o=>{try{if(r+=o.toString(),r.endsWith(Lo+Mo)){let n=$o.Hl7Message.parse(r.substring(1,r.length-2));this.dispatchEvent(new Ua(this,n)),r=""}}catch(n){this.dispatchEvent(new Wo(n))}}).setEncoding(t??"utf-8"),e.on("error",o=>{r="",this.dispatchEvent(new Wo(o))})}send(e){this.socket.write(Wa+e.toString()+Lo+Mo)}async sendAndWait(e){let t=new Promise(r=>{function o(n){n.target.removeEventListener("message",o),r(n.message)}this.addEventListener("message",o)});return this.send(e),t}close(){this.socket.end(),this.socket.destroy()}},Bo=class extends Uo{constructor(e){super(),this.options=e,this.host=this.options.host,this.port=this.options.port}connect(){return this.connection?Promise.resolve(this.connection):new Promise(e=>{let t=(0,Jo.connect)({host:this.host,port:this.port},()=>{this.connection=new Fo(t),e(this.connection)})})}async send(e){return(await this.connect()).send(e)}async sendAndWait(e){return(await this.connect()).sendAndWait(e)}close(){this.connection&&(this.connection.close(),delete this.connection)}},jo=class{constructor(e){this.handler=e}start(e,t){let r=Go.default.createServer(o=>{let n=new Fo(o,t);this.handler(n)});r.listen(e),this.server=r}stop(){this.server&&(this.server.close(),this.server=void 0)}};var Vo=require("commander"),Xo=require("fs");var Ja=h("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").action(async(e,t,r,o)=>{if(o.generateExample?r=Fa():o.file&&(r=(0,Xo.readFileSync)(o.file,"utf8")),!r)throw new Error("Missing HL7 message body");let n=new Bo({host:e,port:parseInt(t,10)});try{let i=await n.sendAndWait(St.Hl7Message.parse(r));console.log(i.toString().replaceAll("\r",`
6
+ `))}finally{n.close()}}),$a=h("listen").description("Starts an HL7 v2 MLLP server").argument("<port>").action(async e=>{new jo(r=>{r.addEventListener("message",({message:o})=>{console.log(o.toString().replaceAll("\r",`
7
+ `)),r.send(o.buildAck())})}).start(parseInt(e,10)),console.log("Listening on port "+e)}),zo=new Vo.Command("hl7").addCommand(Ja).addCommand($a);function Fa(){let e=(0,St.formatHl7DateTime)(new Date),t=Date.now().toString();return`MSH|^~\\&|ADTSYS|HOSPITAL|RECEIVER|DEST|${e}||ADT^A01|${t}|P|2.5|
8
8
  EVN|A01|${e}||
9
9
  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|
10
- PV1|1|I|2000^2012^01||||12345^DOCTOR^DOC||||||||||1234567^DOCTOR^DOC||AMB|||||||||||||||||||||||||202309280900|`}var to=require("commander");var ro=require("path"),oo=require("fs"),no=require("os");var io=d("set"),ao=d("remove"),so=d("list"),co=d("describe"),po=new to.Command("profile").addCommand(io).addCommand(ao).addCommand(so).addCommand(co);io.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)=>{_e(e,t)});ao.argument("<profileName>","Name of the profile").description("Remove a profile by name").action(async e=>{new R(e).setObject("options",void 0),console.log(`${e} profile removed`)});so.description("List all profiles saved").action(async()=>{let e=(0,ro.resolve)((0,no.homedir)(),".medplum"),t=(0,oo.readdirSync)(e),r=[];t.forEach(o=>{let n=o.split(".")[0],s=new R(n).getObject("options");s&&r.push({profileName:n,profile:s})}),console.log(r)});co.argument("<profileName>","Name of the profile").description("Describes a profile").action(async e=>{let t=er(e);console.log(t)});var Le=require("commander");var mo=d("list"),lo=d("current"),uo=d("switch"),fo=d("invite"),ho=new Le.Command("project").addCommand(mo).addCommand(lo).addCommand(uo).addCommand(fo);mo.description("List of current projects").action(async e=>{let t=await l(e);ci(t)});function ci(e){let r=e.getLogins().map(o=>`${o.project.display} (${o.project.reference})`).join(`
10
+ PV1|1|I|2000^2012^01||||12345^DOCTOR^DOC||||||||||1234567^DOCTOR^DOC||AMB|||||||||||||||||||||||||202309280900|`}var qo=require("commander");var Yo=require("path"),Zo=require("fs"),Qo=require("os");var en=h("set"),tn=h("remove"),rn=h("list"),on=h("describe"),nn=new qo.Command("profile").addCommand(en).addCommand(tn).addCommand(rn).addCommand(on);en.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)=>{qe(e,t)});tn.argument("<profileName>","Name of the profile").description("Remove a profile by name").action(async e=>{new j(e).setObject("options",void 0),console.log(`${e} profile removed`)});rn.description("List all profiles saved").action(async()=>{let e=(0,Yo.resolve)((0,Qo.homedir)(),".medplum"),t=(0,Zo.readdirSync)(e),r=[];t.forEach(o=>{let n=o.split(".")[0],c=new j(n).getObject("options");c&&r.push({profileName:n,profile:c})}),console.log(r)});on.argument("<profileName>","Name of the profile").description("Describes a profile").action(async e=>{let t=Mr(e);console.log(t)});var At=require("commander");var an=h("list"),sn=h("current"),cn=h("switch"),pn=h("invite"),dn=new At.Command("project").addCommand(an).addCommand(sn).addCommand(cn).addCommand(pn);an.description("List of current projects").action(async e=>{let t=await S(e);Ba(t)});function Ba(e){let r=e.getLogins().map(o=>`${o.project.display} (${o.project.reference})`).join(`
11
11
 
12
- `);console.log(r)}lo.description("Project you are currently on").action(async e=>{let r=(await l(e)).getActiveLogin();if(!r)throw new Error("Unauthenticated: run `npx medplum login` to login");console.log(`${r.project.display} (${r.project.reference})`)});uo.description("Switching to another project from the current one").argument("<projectId>").action(async(e,t)=>{let r=await l(t);await di(r,e)});fo.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 Le.Option("-r, --role <role>","Role of user").choices(["Practitioner","Patient","RelatedPerson"]).default("Practitioner")).action(async(e,t,r,o)=>{let n=await l(o),a=n.getActiveLogin();if(!a)throw new Error("Unauthenticated: run `npx medplum login` to login");if(!a.project.reference)throw new Error("No current project to invite user to");let s=a.project.reference.split("/")[1],c={resourceType:o.role,firstName:e,lastName:t,email:r,sendEmail:!!o.sendEmail,admin:!!o.admin};await pi(s,c,n)});async function di(e,t){let o=e.getLogins().find(n=>n.project.reference?.includes(t));o?(await e.setActiveLogin(o),console.log(`Switched to project ${t}
13
- `)):console.log(`Error: project ${t} not found. Make sure you are added as a user to this project`)}async function pi(e,t,r){try{await r.invite(e,t),t.sendEmail&&console.log("Email sent"),console.log("See your users at https://app.medplum.com/admin/users")}catch(o){console.log("Error while sending invite "+o)}}var yo=require("@medplum/core");var St=d("delete"),Et=d("get"),bt=d("patch"),Ct=d("post"),At=d("put");St.argument("<url>","Resource/$id").action(async(e,t)=>{let r=await l(t);M(await r.delete(ye(r,e)))});Et.argument("<url>","Resource/$id").option("--as-transaction","Print out the bundle as a transaction type").action(async(e,t)=>{let r=await l(t),o=await r.get(ye(r,e));t.asTransaction?M((0,yo.convertToTransactionBundle)(o)):M(o)});bt.arguments("<url> <body>").action(async(e,t,r)=>{let o=await l(r);M(await o.patch(ye(o,e),Pt(t)))});Ct.arguments("<url> <body>").action(async(e,t,r)=>{let o=await l(r);M(await o.post(ye(o,e),Pt(t)))});At.arguments("<url> <body>").action(async(e,t,r)=>{let o=await l(r);M(await o.put(ye(o,e),Pt(t)))});function Pt(e){if(e)try{return JSON.parse(e)}catch{return e}}function ye(e,t){return["admin/","auth/","fhir/R4"].some(o=>t.startsWith(o))?t:e.fhirUrl(t).toString()}async function So(e){try{let t=new go.Command("medplum").description("Command to access Medplum CLI");t.version($e.MEDPLUM_VERSION),t.addCommand(st),t.addCommand(ct),t.addCommand(Et),t.addCommand(Ct),t.addCommand(bt),t.addCommand(At),t.addCommand(St),t.addCommand(ho),t.addCommand(Lr),t.addCommand(Dr),t.addCommand(ht),t.addCommand(yt),t.addCommand(gt),t.addCommand(po),t.addCommand(F),t.addCommand(eo),await t.parseAsync(e)}catch(t){console.error("Error: "+(0,$e.normalizeErrorString)(t))}}async function Eo(){wo.default.config(),await So(process.argv)}require.main===module&&Eo().catch(e=>console.error("Unhandled error:",e));0&&(module.exports={main,run});
12
+ `);console.log(r)}sn.description("Project you are currently on").action(async e=>{let r=(await S(e)).getActiveLogin();if(!r)throw new Error("Unauthenticated: run `npx medplum login` to login");console.log(`${r.project.display} (${r.project.reference})`)});cn.description("Switching to another project from the current one").argument("<projectId>").action(async(e,t)=>{let r=await S(t);await Ga(r,e)});pn.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 At.Option("-r, --role <role>","Role of user").choices(["Practitioner","Patient","RelatedPerson"]).default("Practitioner")).action(async(e,t,r,o)=>{let n=await S(o),i=n.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 c=i.project.reference.split("/")[1],l={resourceType:o.role,firstName:e,lastName:t,email:r,sendEmail:!!o.sendEmail,admin:!!o.admin};await ja(c,l,n)});async function Ga(e,t){let o=e.getLogins().find(n=>n.project.reference?.includes(t));o?(await e.setActiveLogin(o),console.log(`Switched to project ${t}
13
+ `)):console.log(`Error: project ${t} not found. Make sure you are added as a user to this project`)}async function ja(e,t,r){try{await r.invite(e,t),t.sendEmail&&console.log("Email sent"),console.log("See your users at https://app.medplum.com/admin/users")}catch(o){console.log("Error while sending invite "+o)}}var ln=require("@medplum/core");var or=h("delete"),nr=h("get"),ir=h("patch"),ar=h("post"),sr=h("put");or.argument("<url>","Resource/$id").action(async(e,t)=>{let r=await S(t);Z(await r.delete(Je(r,e)))});nr.argument("<url>","Resource/$id").option("--as-transaction","Print out the bundle as a transaction type").action(async(e,t)=>{let r=await S(t),o=await r.get(Je(r,e));t.asTransaction?Z((0,ln.convertToTransactionBundle)(o)):Z(o)});ir.arguments("<url> <body>").action(async(e,t,r)=>{let o=await S(r);Z(await o.patch(Je(o,e),cr(t)))});ar.arguments("<url> <body>").action(async(e,t,r)=>{let o=await S(r);Z(await o.post(Je(o,e),cr(t)))});sr.arguments("<url> <body>").action(async(e,t,r)=>{let o=await S(r);Z(await o.put(Je(o,e),cr(t)))});function cr(e){if(e)try{return JSON.parse(e)}catch{return e}}function Je(e,t){return["admin/","auth/","fhir/R4"].some(o=>t.startsWith(o))?t:e.fhirUrl(t).toString()}async function fn(e){try{let t=new un.Command("medplum").description("Command to access Medplum CLI");t.version(bt.MEDPLUM_VERSION),t.addCommand(Jt),t.addCommand($t),t.addCommand(nr),t.addCommand(ar),t.addCommand(ir),t.addCommand(sr),t.addCommand(or),t.addCommand(dn),t.addCommand(ko),t.addCommand(Oo),t.addCommand(Qt),t.addCommand(er),t.addCommand(tr),t.addCommand(nn),t.addCommand(te),t.addCommand(zo),await t.parseAsync(e)}catch(t){console.error("Error: "+(0,bt.normalizeErrorString)(t))}}async function hn(){mn.default.config(),await fn(process.argv)}require.main===module&&hn().catch(e=>console.error("Unhandled error:",e));0&&(module.exports={main,run});
14
14
  //# sourceMappingURL=index.cjs.map