@medplum/cli 2.1.19 → 2.1.21

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
- var hr=Object.defineProperty;var yr=(e,t,r)=>t in e?hr(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;var qe=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,r)=>(typeof require<"u"?require:t)[r]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var l=(e,t,r)=>(yr(e,typeof t!="symbol"?t+"":t,r),r);import{MEDPLUM_VERSION as Ri,normalizeErrorString as Oi}from"@medplum/core";import{Command as Di}from"commander";import Mi from"dotenv";import{ContentType as Re,getDisplayString as Lo,normalizeErrorString as $o}from"@medplum/core";import{exec as Bo}from"child_process";import{createServer as Fo}from"http";import{platform as jo}from"os";import{MedplumClient as Cr}from"@medplum/core";import{ClientStorage as gr}from"@medplum/core";import{existsSync as Ye,mkdirSync as wr,readFileSync as Sr,writeFileSync as Er}from"fs";import{homedir as br}from"os";import{resolve as Ze}from"path";var K=class extends gr{constructor(r){super();this.dirName=Ze(br(),".medplum"),this.fileName=Ze(this.dirName,r+".json")}clear(){this.writeFile({})}getString(r){return this.readFile()?.[r]}setString(r,o){let n=this.readFile()??{};o?n[r]=o:delete n[r],this.writeFile(n)}getObject(r){let o=this.getString(r);return o?JSON.parse(o):void 0}setObject(r,o){this.setString(r,o?JSON.stringify(o):void 0)}readFile(){if(Ye(this.fileName))return JSON.parse(Sr(this.fileName,"utf8"))}writeFile(r){Ye(this.dirName)||wr(this.dirName),Er(this.fileName,JSON.stringify(r,null,2),"utf8")}};async function u(e,t=!0){let r=e.profile??"default",o=new K(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:y,clientId:T,clientSecret:_}=Ar(e,o),N=e.fetch??fetch,L=new Cr({fetch:N,baseUrl:a,tokenUrl:p,fhirUrlPath:s,authorizeUrl:y,storage:o,onUnauthenticated:Pr,verbose:e.verbose});return t&&(c?L.setAccessToken(c):T&&_&&(L.setBasicAuth(T,_),n?.authType!=="basic"&&await L.startClientLogin(T,_))),L}function Ar(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,y=e.clientSecret??r?.clientSecret??process.env.MEDPLUM_CLIENT_SECRET;return{baseUrl:o,fhirUrlPath:n,accessToken:a,tokenUrl:s,authorizeUrl:c,clientId:p,clientSecret:y}}function Pr(){console.log("Unauthenticated: run `npx medplum login` to sign in")}import{Command as vr,Option as xr}from"commander";function d(e){return new vr(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 xr("--auth-type <authType>","Type of authentication").choices(["basic","client-credentials","authorization-code","jwt-bearer","token-exchange","jwt-assertion"]))}import{ContentType as _e,encodeBase64 as ht}from"@medplum/core";import{createHmac as Ho,createPrivateKey as ko,randomBytes as Ro}from"crypto";import{existsSync as Oo,readFileSync as yt,writeFileSync as Do}from"fs";import{Buffer as Ir}from"buffer";var b=new TextEncoder,S=new TextDecoder,Qi=2**32;function I(...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 C=e=>Ir.from(e).toString("base64url");var U=class extends Error{constructor(r){super(r);l(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 U{constructor(){super(...arguments);l(this,"code","ERR_JOSE_NOT_SUPPORTED")}static get code(){return"ERR_JOSE_NOT_SUPPORTED"}};var A=class extends U{constructor(){super(...arguments);l(this,"code","ERR_JWS_INVALID")}static get code(){return"ERR_JWS_INVALID"}},O=class extends U{constructor(){super(...arguments);l(this,"code","ERR_JWT_INVALID")}static get code(){return"ERR_JWT_INVALID"}};var Kr,ge=class extends U{constructor(){super(...arguments);l(this,Kr);l(this,"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS");l(this,"message","multiple matching keys found in the JSON Web Key Set")}static get code(){return"ERR_JWKS_MULTIPLE_MATCHING_KEYS"}};Kr=Symbol.asyncIterator;import*as et from"util";var P=e=>et.types.isKeyObject(e);import*as tt from"crypto";import*as rt from"util";var Hr=tt.webcrypto,ot=Hr,E=e=>rt.types.isCryptoKey(e);function k(e,t="algorithm.name"){return new TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`)}function re(e,t){return e.name===t}function Se(e){return parseInt(e.name.slice(4),10)}function kr(e){switch(e){case"ES256":return"P-256";case"ES384":return"P-384";case"ES512":return"P-521";default:throw new Error("unreachable")}}function Rr(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 nt(e,t,...r){switch(t){case"HS256":case"HS384":case"HS512":{if(!re(e.algorithm,"HMAC"))throw k("HMAC");let o=parseInt(t.slice(2),10);if(Se(e.algorithm.hash)!==o)throw k(`SHA-${o}`,"algorithm.hash");break}case"RS256":case"RS384":case"RS512":{if(!re(e.algorithm,"RSASSA-PKCS1-v1_5"))throw k("RSASSA-PKCS1-v1_5");let o=parseInt(t.slice(2),10);if(Se(e.algorithm.hash)!==o)throw k(`SHA-${o}`,"algorithm.hash");break}case"PS256":case"PS384":case"PS512":{if(!re(e.algorithm,"RSA-PSS"))throw k("RSA-PSS");let o=parseInt(t.slice(2),10);if(Se(e.algorithm.hash)!==o)throw k(`SHA-${o}`,"algorithm.hash");break}case"EdDSA":{if(e.algorithm.name!=="Ed25519"&&e.algorithm.name!=="Ed448")throw k("Ed25519 or Ed448");break}case"ES256":case"ES384":case"ES512":{if(!re(e.algorithm,"ECDSA"))throw k("ECDSA");let o=kr(t);if(e.algorithm.namedCurve!==o)throw k(o,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}Rr(e,r)}function it(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 v=(e,...t)=>it("Key must be ",e,...t);function Ee(e,t,...r){return it(`Key for the ${e} algorithm must be `,t,...r)}var be=e=>P(e)||E(e),f=["KeyObject"];(globalThis.CryptoKey||ot?.CryptoKey)&&f.push("CryptoKey");var Jr=(...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},$=Jr;function Nr(e){return typeof e=="object"&&e!==null}function w(e){if(!Nr(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}import{diffieHellman as ds,generateKeyPair as Br,KeyObject as ps}from"crypto";import{promisify as Fr}from"util";import{KeyObject as Ur}from"crypto";var Lr=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")}},$r=(e,t)=>{let r;if(E(e))r=Ur.from(e);else if(P(e))r=e;else throw new TypeError(v(e,...f));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:Lr(o)}default:throw new TypeError("Invalid asymmetric key type for this operation")}},Ce=$r;var Es=Fr(Br);import{promisify as Vr}from"util";import{KeyObject as _s,pbkdf2 as zr}from"crypto";var Js=Vr(zr);var oe=(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 Xr=(e,t)=>{if(!(t instanceof Uint8Array)){if(!be(t))throw new TypeError(Ee(e,t,...f,"Uint8Array"));if(t.type!=="secret")throw new TypeError(`${f.join(" or ")} instances for symmetric algorithms must be of type "secret"`)}},qr=(e,t,r)=>{if(!be(t))throw new TypeError(Ee(e,t,...f));if(t.type==="secret")throw new TypeError(`${f.join(" or ")} instances for asymmetric algorithms must not be of type "secret"`);if(r==="sign"&&t.type==="public")throw new TypeError(`${f.join(" or ")} instances for asymmetric algorithm signing must be of type "private"`);if(r==="decrypt"&&t.type==="public")throw new TypeError(`${f.join(" or ")} instances for asymmetric algorithm decryption must be of type "private"`);if(t.algorithm&&r==="verify"&&t.type==="private")throw new TypeError(`${f.join(" or ")} instances for asymmetric algorithm verifying must be of type "public"`);if(t.algorithm&&r==="encrypt"&&t.type==="private")throw new TypeError(`${f.join(" or ")} instances for asymmetric algorithm encryption must be of type "public"`)},Yr=(e,t,r)=>{e.startsWith("HS")||e==="dir"||e.startsWith("PBES2")||/^A\d{3}(?:GCM)?KW$/.test(e)?Xr(e,t):qr(e,t,r)},q=Yr;function no(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 B=no;var po=Symbol();import*as xe from"crypto";import{promisify as go}from"util";function ne(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`)}}import{constants as mt}from"crypto";var mo={padding:mt.RSA_PKCS1_PSS_PADDING,saltLength:mt.RSA_PSS_SALTLEN_DIGEST},lo=new Map([["ES256","P-256"],["ES256K","secp256k1"],["ES384","P-384"],["ES512","P-521"]]);function ie(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 oe(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 oe(t,e),{key:t,...mo};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=Ce(t),o=lo.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`)}}import*as se from"crypto";import{promisify as fo}from"util";function Pe(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`)}}import{KeyObject as lt,createSecretKey as uo}from"crypto";function ae(e,t,r){if(t instanceof Uint8Array){if(!e.startsWith("HS"))throw new TypeError(v(t,...f));return uo(t)}if(t instanceof lt)return t;if(E(t))return nt(t,e,r),lt.from(t);throw new TypeError(v(t,...f,"Uint8Array"))}var ho=fo(se.sign),yo=async(e,t,r)=>{let o=ae(e,t,"sign");if(e.startsWith("HS")){let n=se.createHmac(Pe(e),o);return n.update(r),n.digest()}return ho(ne(e),r,ie(e,o))},ve=yo;var Dp=go(xe.verify);var M=e=>Math.floor(e.getTime()/1e3);var So=/^(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)$/i,ce=e=>{let t=So.exec(e);if(!t)throw new TypeError("Invalid time period format");let r=parseFloat(t[1]);switch(t[2].toLowerCase()){case"sec":case"secs":case"second":case"seconds":case"s":return Math.round(r);case"minute":case"minutes":case"min":case"mins":case"m":return Math.round(r*60);case"hour":case"hours":case"hr":case"hrs":case"h":return Math.round(r*3600);case"day":case"days":case"d":return Math.round(r*86400);case"week":case"weeks":case"w":return Math.round(r*604800);default:return Math.round(r*31557600)}};var F=class{constructor(t){l(this,"_payload");l(this,"_protectedHeader");l(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 A("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");if(!$(this._protectedHeader,this._unprotectedHeader))throw new A("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let o={...this._protectedHeader,...this._unprotectedHeader},n=B(A,new Map([["b64",!0]]),r?.crit,this._protectedHeader,o),a=!0;if(n.has("b64")&&(a=this._protectedHeader.b64,typeof a!="boolean"))throw new A('The "b64" (base64url-encode payload) Header Parameter must be a boolean');let{alg:s}=o;if(typeof s!="string"||!s)throw new A('JWS "alg" (Algorithm) Header Parameter missing or invalid');q(s,t,"sign");let c=this._payload;a&&(c=b.encode(C(c)));let p;this._protectedHeader?p=b.encode(C(JSON.stringify(this._protectedHeader))):p=b.encode("");let y=I(p,b.encode("."),c),T=await ve(s,t,y),_={signature:C(T),payload:""};return a&&(_.payload=S.decode(c)),this._unprotectedHeader&&(_.header=this._unprotectedHeader),this._protectedHeader&&(_.protected=S.decode(p)),_}};var Y=class{constructor(t){l(this,"_flattened");this._flattened=new F(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 G=class{constructor(t={}){l(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",M(t))}:this._payload={...this._payload,nbf:M(new Date)+ce(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",M(t))}:this._payload={...this._payload,exp:M(new Date)+ce(t)},this}setIssuedAt(t){return typeof t>"u"?this._payload={...this._payload,iat:M(new Date)}:t instanceof Date?this._payload={...this._payload,iat:j("setIssuedAt",M(t))}:this._payload={...this._payload,iat:j("setIssuedAt",t)},this}};var Z=class extends G{constructor(){super(...arguments);l(this,"_protectedHeader")}setProtectedHeader(r){return this._protectedHeader=r,this}async sign(r,o){let n=new Y(b.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 O("JWTs MUST NOT use unencoded payload");return n.sign(r,o)}};var xo;(typeof navigator>"u"||!navigator.userAgent?.startsWith?.("Mozilla/5.0 "))&&(xo="jose/v5.1.0");import{createSecretKey as Bl,generateKeyPair as To}from"crypto";import{promisify as Ko}from"util";var Vl=Ko(To);import{basename as gt,extname as Mo,resolve as wt}from"path";import Wo from"tar";function R(e){console.log(JSON.stringify(e,null,2))}async function Ie(e,t,r){let o=t.source,n=He(o);if(n)try{console.log("Saving source code...");let a=await e.createAttachment(n,gt(o),Uo(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 Te(e,t,r){let o=t.dist??t.source,n=He(o);if(n)try{console.log("Deploying bot...");let a=await e.post(e.fhirUrl("Bot",r.id,"$deploy"),{code:n,filename:gt(o)});console.log("Deploy result: "+a.issue?.[0]?.details?.text)}catch(a){console.log("Deploy error: ",a)}}async function Ke(e,t,r,o,n,a){try{let s={name:t,description:"",runtimeVersion:a},c=await e.post("admin/projects/"+r+"/bot",s),p=await e.readResource("Bot",c.id),y={name:t,id:c.id,source:o,dist:n};await Ie(e,y,p),await Te(e,y,p),console.log(`Success! Bot created: ${p.id}`),Jo(y)}catch(s){console.log("Error while creating new bot: "+s)}}function St(e){let t=new RegExp("^"+No(e).replace(/\\\*/g,".*")+"$"),r=V()?.bots?.filter(o=>t.test(o.name));return r||[]}function V(e){let t=e?`medplum.${e}.config.json`:"medplum.config.json",r=He(t);if(r)return JSON.parse(r)}function He(e){let t=wt(process.cwd(),e);return Oo(t)?yt(t,"utf8"):""}function Jo(e){let t=V()??{};t.bots||(t.bots=[]),t.bots.push(e),Do("medplum.config.json",JSON.stringify(t,null,2),"utf8"),console.log(`Bot added to config: ${e.id}`)}function No(e){return e.replace(/[/\-\\^$*+?.()|[\]{}]/g,"\\$&")}function Et(e){let o=0,n=0;return Wo.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 ke(){return{extension:[{url:"http://hl7.org/fhir/StructureDefinition/data-absent-reason",valueCode:"unsupported"}]}}function Uo(e){let t=Mo(e).toLowerCase();return[".cjs",".mjs",".js"].includes(t)?_e.JAVASCRIPT:[".cts",".mts",".ts"].includes(t)?_e.TYPESCRIPT:_e.TEXT}function de(e,t){let r=new K(e),o={name:e,...t};return r.setObject("options",o),console.log(`${e} profile created`),o}function bt(e){return new K(e).getObject("options")}async function Ct(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=ht(JSON.stringify(r)),s=ht(JSON.stringify(n)),c=`${a}.${s}`,p=Ho("sha256",t.clientSecret).update(c).digest("base64url"),y=`${c}.${p}`;await e.startJwtBearerLogin(t.clientId,y,t.scope??"")}async function At(e,t){let r=ko(yt(wt(t.privateKeyPath))),o=await new Z({}).setProtectedHeader({alg:"RS384",typ:"JWT"}).setIssuer(t.clientId).setSubject(t.clientId).setAudience(`${t.baseUrl}${t.audience}`).setJti(Ro(16).toString("hex")).setIssuedAt().setExpirationTime("5m").sign(r);await e.startJwtAssertionLogin(o)}var Pt="medplum-cli",vt="http://localhost:9615",Oe=d("login"),De=d("whoami");Oe.action(async e=>{let t=e.profile??"default",r=de(t,e),o=await u(e,!1);await Go(o,r)});De.action(async e=>{let t=await u(e);Xo(t)});async function Go(e,t){switch(t?.authType??"authorization-code"){case"authorization-code":await qo(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 Ct(e,t);break;case"jwt-assertion":await At(e,t);break}console.log("Login successful")}async function Vo(e){let t=Fo(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:Pt,redirectUri:vt});o.writeHead(200,{"Content-Type":Re.TEXT}),o.end(`Signed in as ${Lo(s)}. You may close this window.`)}catch(s){o.writeHead(400,{"Content-Type":Re.TEXT}),o.end(`Error: ${$o(s)}`)}finally{t.close()}else o.writeHead(404,{"Content-Type":Re.TEXT}),o.end("Not found")}).listen(9615)}async function zo(e){let t=jo(),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)}Bo(r)}function Xo(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 qo(e){await Vo(e);let t=new URL(e.getAuthorizeUrl());t.searchParams.set("client_id",Pt),t.searchParams.set("redirect_uri",vt),t.searchParams.set("scope","openid"),t.searchParams.set("response_type","code"),t.searchParams.set("prompt","login"),await zo(t.toString())}import{Command as ti}from"commander";import{CloudFormationClient as _t,DescribeStackResourcesCommand as Yo,DescribeStacksCommand as Zo,ListStacksCommand as Qo}from"@aws-sdk/client-cloudformation";import{CloudFrontClient as en,CreateInvalidationCommand as tn}from"@aws-sdk/client-cloudfront";import{ECSClient as rn}from"@aws-sdk/client-ecs";import{S3Client as on}from"@aws-sdk/client-s3";var pe=new _t({}),nn=new en({region:"us-east-1"}),It=new rn({}),Q=new on({}),an="medplum:environment";async function Me(){return(await pe.send(new Qo({}))).StackSummaries?.filter(t=>t.StackName&&t.StackStatus!=="DELETE_COMPLETE")||[]}async function W(e){let t=await Me();for(let r of t){let o=r.StackName,n=await We(o);if(n?.tag===e)return n}}async function We(e){let t={};return await xt(pe,e,t),await pe.config.region()!=="us-east-1"&&await xt(new _t({region:"us-east-1"}),e+"-us-east-1",t),t}async function xt(e,t,r){let o=new Zo({StackName:t}),a=(await e.send(o))?.Stacks?.[0],s=a?.Tags?.find(p=>p.Key===an);if(!s)return;let c=await e.send(new Yo({StackName:t}));if(c.StackResources){e===pe&&(r.stack=a,r.tag=s.Value);for(let p of c.StackResources)sn(p,r)}}function sn(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 me(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: ${Je(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 Je(e){return e?.PhysicalResourceId?.split("/")?.pop()||""}async function le(e){let t=await nn.send(new tn({DistributionId:e,InvalidationBatch:{CallerReference:`invalidate-all-${Date.now()}`,Paths:{Quantity:1,Items:["/*"]}}}));console.log(`Created invalidation with ID: ${t.Invalidation?.Id}`)}async function Tt(e){let t=await W(e);if(!t){console.log("Stack not found");return}me(t)}import{ACMClient as kt,ListCertificatesCommand as cn,RequestCertificateCommand as dn}from"@aws-sdk/client-acm";import{CloudFrontClient as pn,CreatePublicKeyCommand as mn}from"@aws-sdk/client-cloudfront";import{GetParameterCommand as ln,PutParameterCommand as un,SSMClient as fn}from"@aws-sdk/client-ssm";import{GetCallerIdentityCommand as hn,STSClient as yn}from"@aws-sdk/client-sts";import{generateKeyPairSync as gn,randomUUID as Kt}from"crypto";import{existsSync as wn,writeFileSync as Sn}from"fs";import{resolve as En}from"path";import bn from"readline";var Cn=e=>`${e}DomainName`,Rt=e=>`${e}SslCertArn`,fe;async function Ot(){let e={apiPort:8103,region:"us-east-1"};fe=bn.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 An(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 ue("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 x("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 x("What is the config file name?",`medplum.${e.name}.config.json`);wn(r)&&(i("Config file already exists."),await ue("Do you want to overwrite the config file?")),i('Using config file "'+r+'"...'),g(r,e),h("AWS REGION"),i("Most Medplum resources will be created in a single AWS region."),e.region=await x("Enter your AWS region:","us-east-1"),g(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 x("What is your AWS account number?",t),g(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 x("Enter your CloudFormation stack name?",o),g(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 x("Enter your base domain name:");g(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 x("Enter your support email address:");h("API DOMAIN NAME"),i("Medplum deploys a REST API for the backend services."),e.apiDomainName=await x("Enter your REST API domain name:","api."+e.domainName),e.baseUrl=`https://${e.apiDomainName}/`,g(r,e),h("APP DOMAIN NAME"),i("Medplum deploys a web application for the user interface."),e.appDomainName=await x("Enter your web application domain name:","app."+e.domainName),g(r,e),h("STORAGE DOMAIN NAME"),i("Medplum deploys a storage service for file uploads."),e.storageDomainName=await x("Enter your storage domain name:","storage."+e.domainName),g(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 x("Enter your storage bucket name:",e.storageDomainName),g(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 ee("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 Ue("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 ee("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"),g(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 ee("Enter the number of server instances:",[1,2,3,4,6,8],1),g(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 ee("Enter the server memory (MB):",[512,1024,2048,4096,8192,16384],512),g(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 ee("Enter the server CPU:",[256,512,1024,2048,4096,8192,16384],256),g(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 x("Enter the server image:","medplum/medplum-server:latest"),g(r,e),h("SIGNING KEY"),i("Medplum uses AWS CloudFront Presigned URLs for binary content such as file uploads.");let{keyId:a,privateKey:s,publicKey:c,passphrase:p}=await _n(e.stackName+"SigningKey");e.signingKeyId=a,e.storagePublicKey=c,g(r,e),h("SSL CERTIFICATES"),i("Medplum will now check for existing SSL certificates for the subdomains.");let y=await Pn(e.region);i("Found "+y.length+" certificate(s).");for(let{region:_,certName:N}of[{region:e.region,certName:"api"},{region:"us-east-1",certName:"app"},{region:"us-east-1",certName:"storage"}]){i("");let L=await vn(e,y,_,N);e[Rt(N)]=L,g(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 T={port:e.apiPort,baseUrl:e.baseUrl,appBaseUrl:`https://${e.appDomainName}/`,storageBaseUrl:`https://${e.storageDomainName}/binary/`,binaryStorage:`s3:${e.storageBucketName}`,signingKeyId:e.signingKeyId,signingKey:s,signingKeyPassphrase:p,supportEmail:n};i(JSON.stringify({...T,signingKey:"****",signingKeyPassphrase:"****"},null,2)),await ue("Do you want to store these values in AWS Parameter Store?"),await Kn(e.region,`/medplum/${e.name}/`,T),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(""),fe.close()}function i(e){fe.write(e+`
2
+ var hr=Object.defineProperty;var yr=(e,t,r)=>t in e?hr(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;var qe=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,r)=>(typeof require<"u"?require:t)[r]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var l=(e,t,r)=>(yr(e,typeof t!="symbol"?t+"":t,r),r);import{MEDPLUM_VERSION as Wi,normalizeErrorString as Mi}from"@medplum/core";import{Command as Ji}from"commander";import Ni from"dotenv";import{ContentType as Re,getDisplayString as Bo,normalizeErrorString as Fo}from"@medplum/core";import{exec as jo}from"child_process";import{createServer as Go}from"http";import{platform as Vo}from"os";import{MedplumClient as Ar}from"@medplum/core";import{ClientStorage as gr}from"@medplum/core";import{existsSync as Ye,mkdirSync as wr,readFileSync as Sr,writeFileSync as Er}from"fs";import{homedir as br}from"os";import{resolve as Ze}from"path";var T=class extends gr{constructor(r){super();this.dirName=Ze(br(),".medplum"),this.fileName=Ze(this.dirName,r+".json")}clear(){this.writeFile({})}getString(r){return this.readFile()?.[r]}setString(r,o){let n=this.readFile()??{};o?n[r]=o:delete n[r],this.writeFile(n)}getObject(r){let o=this.getString(r);return o?JSON.parse(o):void 0}setObject(r,o){this.setString(r,o?JSON.stringify(o):void 0)}readFile(){if(Ye(this.fileName))return JSON.parse(Sr(this.fileName,"utf8"))}writeFile(r){Ye(this.dirName)||wr(this.dirName),Er(this.fileName,JSON.stringify(r,null,2),"utf8")}};async function u(e,t=!0){let r=e.profile??"default",o=new T(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:d,authorizeUrl:g,clientId:H,clientSecret:I}=Cr(e,o),ee=e.fetch??fetch,te=new Ar({fetch:ee,baseUrl:a,tokenUrl:d,fhirUrlPath:s,authorizeUrl:g,storage:o,onUnauthenticated:Pr,verbose:e.verbose});return t&&(c?te.setAccessToken(c):H&&I&&(te.setBasicAuth(H,I),n?.authType!=="basic"&&await te.startClientLogin(H,I))),te}function Cr(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,d=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:d,clientSecret:g}}function Pr(){console.log("Unauthenticated: run `npx medplum login` to sign in")}import{Command as vr,Option as xr}from"commander";function p(e){return new vr(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 xr("--auth-type <authType>","Type of authentication").choices(["basic","client-credentials","authorization-code","jwt-bearer","token-exchange","jwt-assertion"]))}import{ContentType as _e,encodeBase64 as ht}from"@medplum/core";import{createHmac as Ro,createPrivateKey as Oo,randomBytes as Do}from"crypto";import{existsSync as Wo,readFileSync as yt,writeFileSync as Mo}from"fs";import{Buffer as Ir}from"buffer";var b=new TextEncoder,S=new TextDecoder,ra=2**32;function _(...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=>Ir.from(e).toString("base64url");var N=class extends Error{constructor(r){super(r);l(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 N{constructor(){super(...arguments);l(this,"code","ERR_JOSE_NOT_SUPPORTED")}static get code(){return"ERR_JOSE_NOT_SUPPORTED"}};var C=class extends N{constructor(){super(...arguments);l(this,"code","ERR_JWS_INVALID")}static get code(){return"ERR_JWS_INVALID"}},O=class extends N{constructor(){super(...arguments);l(this,"code","ERR_JWT_INVALID")}static get code(){return"ERR_JWT_INVALID"}};var Kr,ge=class extends N{constructor(){super(...arguments);l(this,Kr);l(this,"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS");l(this,"message","multiple matching keys found in the JSON Web Key Set")}static get code(){return"ERR_JWKS_MULTIPLE_MATCHING_KEYS"}};Kr=Symbol.asyncIterator;import*as et from"util";var P=e=>et.types.isKeyObject(e);import*as tt from"crypto";import*as rt from"util";var Hr=tt.webcrypto,ot=Hr,E=e=>rt.types.isCryptoKey(e);function k(e,t="algorithm.name"){return new TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`)}function re(e,t){return e.name===t}function Se(e){return parseInt(e.name.slice(4),10)}function kr(e){switch(e){case"ES256":return"P-256";case"ES384":return"P-384";case"ES512":return"P-521";default:throw new Error("unreachable")}}function Rr(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 nt(e,t,...r){switch(t){case"HS256":case"HS384":case"HS512":{if(!re(e.algorithm,"HMAC"))throw k("HMAC");let o=parseInt(t.slice(2),10);if(Se(e.algorithm.hash)!==o)throw k(`SHA-${o}`,"algorithm.hash");break}case"RS256":case"RS384":case"RS512":{if(!re(e.algorithm,"RSASSA-PKCS1-v1_5"))throw k("RSASSA-PKCS1-v1_5");let o=parseInt(t.slice(2),10);if(Se(e.algorithm.hash)!==o)throw k(`SHA-${o}`,"algorithm.hash");break}case"PS256":case"PS384":case"PS512":{if(!re(e.algorithm,"RSA-PSS"))throw k("RSA-PSS");let o=parseInt(t.slice(2),10);if(Se(e.algorithm.hash)!==o)throw k(`SHA-${o}`,"algorithm.hash");break}case"EdDSA":{if(e.algorithm.name!=="Ed25519"&&e.algorithm.name!=="Ed448")throw k("Ed25519 or Ed448");break}case"ES256":case"ES384":case"ES512":{if(!re(e.algorithm,"ECDSA"))throw k("ECDSA");let o=kr(t);if(e.algorithm.namedCurve!==o)throw k(o,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}Rr(e,r)}function it(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 v=(e,...t)=>it("Key must be ",e,...t);function Ee(e,t,...r){return it(`Key for the ${e} algorithm must be `,t,...r)}var be=e=>P(e)||E(e),f=["KeyObject"];(globalThis.CryptoKey||ot?.CryptoKey)&&f.push("CryptoKey");var Jr=(...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},U=Jr;function Nr(e){return typeof e=="object"&&e!==null}function w(e){if(!Nr(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}import{diffieHellman as ls,generateKeyPair as Br,KeyObject as us}from"crypto";import{promisify as Fr}from"util";import{KeyObject as Ur}from"crypto";var Lr=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")}},$r=(e,t)=>{let r;if(E(e))r=Ur.from(e);else if(P(e))r=e;else throw new TypeError(v(e,...f));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:Lr(o)}default:throw new TypeError("Invalid asymmetric key type for this operation")}},Ae=$r;var Cs=Fr(Br);import{promisify as Vr}from"util";import{KeyObject as Ks,pbkdf2 as zr}from"crypto";var Ls=Vr(zr);import{KeyObject as js,publicEncrypt as Gs,constants as Xr,privateDecrypt as Vs}from"crypto";import{deprecate as qr}from"util";var oe=(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 tc=qr(()=>Xr.RSA_PKCS1_PADDING,'The RSA1_5 "alg" (JWE Algorithm) is deprecated and will be removed in the next major revision.');var Yr=(e,t)=>{if(!(t instanceof Uint8Array)){if(!be(t))throw new TypeError(Ee(e,t,...f,"Uint8Array"));if(t.type!=="secret")throw new TypeError(`${f.join(" or ")} instances for symmetric algorithms must be of type "secret"`)}},Zr=(e,t,r)=>{if(!be(t))throw new TypeError(Ee(e,t,...f));if(t.type==="secret")throw new TypeError(`${f.join(" or ")} instances for asymmetric algorithms must not be of type "secret"`);if(r==="sign"&&t.type==="public")throw new TypeError(`${f.join(" or ")} instances for asymmetric algorithm signing must be of type "private"`);if(r==="decrypt"&&t.type==="public")throw new TypeError(`${f.join(" or ")} instances for asymmetric algorithm decryption must be of type "private"`);if(t.algorithm&&r==="verify"&&t.type==="private")throw new TypeError(`${f.join(" or ")} instances for asymmetric algorithm verifying must be of type "public"`);if(t.algorithm&&r==="encrypt"&&t.type==="private")throw new TypeError(`${f.join(" or ")} instances for asymmetric algorithm encryption must be of type "public"`)},Qr=(e,t,r)=>{e.startsWith("HS")||e==="dir"||e.startsWith("PBES2")||/^A\d{3}(?:GCM)?KW$/.test(e)?Yr(e,t):Zr(e,t,r)},z=Qr;function ao(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 L=ao;var lo=Symbol();import*as xe from"crypto";import{promisify as So}from"util";function ne(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`)}}import{constants as mt}from"crypto";var uo={padding:mt.RSA_PKCS1_PSS_PADDING,saltLength:mt.RSA_PSS_SALTLEN_DIGEST},fo=new Map([["ES256","P-256"],["ES256K","secp256k1"],["ES384","P-384"],["ES512","P-521"]]);function ie(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 oe(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 oe(t,e),{key:t,...uo};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=Ae(t),o=fo.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`)}}import*as se from"crypto";import{promisify as yo}from"util";function Pe(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`)}}import{KeyObject as lt,createSecretKey as ho}from"crypto";function ae(e,t,r){if(t instanceof Uint8Array){if(!e.startsWith("HS"))throw new TypeError(v(t,...f));return ho(t)}if(t instanceof lt)return t;if(E(t))return nt(t,e,r),lt.from(t);throw new TypeError(v(t,...f,"Uint8Array"))}var go=yo(se.sign),wo=async(e,t,r)=>{let o=ae(e,t,"sign");if(e.startsWith("HS")){let n=se.createHmac(Pe(e),o);return n.update(r),n.digest()}return go(ne(e),r,ie(e,o))},ve=wo;var Fp=So(xe.verify);var W=e=>Math.floor(e.getTime()/1e3);var bo=/^(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)$/i,ce=e=>{let t=bo.exec(e);if(!t)throw new TypeError("Invalid time period format");let r=parseFloat(t[1]);switch(t[2].toLowerCase()){case"sec":case"secs":case"second":case"seconds":case"s":return Math.round(r);case"minute":case"minutes":case"min":case"mins":case"m":return Math.round(r*60);case"hour":case"hours":case"hr":case"hrs":case"h":return Math.round(r*3600);case"day":case"days":case"d":return Math.round(r*86400);case"week":case"weeks":case"w":return Math.round(r*604800);default:return Math.round(r*31557600)}};var $=class{constructor(t){l(this,"_payload");l(this,"_protectedHeader");l(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 C("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");if(!U(this._protectedHeader,this._unprotectedHeader))throw new C("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let o={...this._protectedHeader,...this._unprotectedHeader},n=L(C,new Map([["b64",!0]]),r?.crit,this._protectedHeader,o),a=!0;if(n.has("b64")&&(a=this._protectedHeader.b64,typeof a!="boolean"))throw new C('The "b64" (base64url-encode payload) Header Parameter must be a boolean');let{alg:s}=o;if(typeof s!="string"||!s)throw new C('JWS "alg" (Algorithm) Header Parameter missing or invalid');z(s,t,"sign");let c=this._payload;a&&(c=b.encode(A(c)));let d;this._protectedHeader?d=b.encode(A(JSON.stringify(this._protectedHeader))):d=b.encode("");let g=_(d,b.encode("."),c),H=await ve(s,t,g),I={signature:A(H),payload:""};return a&&(I.payload=S.decode(c)),this._unprotectedHeader&&(I.header=this._unprotectedHeader),this._protectedHeader&&(I.protected=S.decode(d)),I}};var X=class{constructor(t){l(this,"_flattened");this._flattened=new $(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 B(e,t){if(!Number.isFinite(t))throw new TypeError(`Invalid ${e} input`);return t}var F=class{constructor(t={}){l(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:B("setNotBefore",t)}:t instanceof Date?this._payload={...this._payload,nbf:B("setNotBefore",W(t))}:this._payload={...this._payload,nbf:W(new Date)+ce(t)},this}setExpirationTime(t){return typeof t=="number"?this._payload={...this._payload,exp:B("setExpirationTime",t)}:t instanceof Date?this._payload={...this._payload,exp:B("setExpirationTime",W(t))}:this._payload={...this._payload,exp:W(new Date)+ce(t)},this}setIssuedAt(t){return typeof t>"u"?this._payload={...this._payload,iat:W(new Date)}:t instanceof Date?this._payload={...this._payload,iat:B("setIssuedAt",W(t))}:this._payload={...this._payload,iat:B("setIssuedAt",t)},this}};var q=class extends F{constructor(){super(...arguments);l(this,"_protectedHeader")}setProtectedHeader(r){return this._protectedHeader=r,this}async sign(r,o){let n=new X(b.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 O("JWTs MUST NOT use unencoded payload");return n.sign(r,o)}};var Io;(typeof navigator>"u"||!navigator.userAgent?.startsWith?.("Mozilla/5.0 "))&&(Io="jose/v5.1.1");import{createSecretKey as Zl,generateKeyPair as Ho}from"crypto";import{promisify as ko}from"util";var ru=ko(Ho);import{basename as gt,extname as Jo,resolve as wt}from"path";import No from"tar";function R(e){console.log(JSON.stringify(e,null,2))}async function Ie(e,t,r){let o=t.source,n=He(o);if(n)try{console.log("Saving source code...");let a=await e.createAttachment(n,gt(o),$o(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 Te(e,t,r){let o=t.dist??t.source,n=He(o);if(n)try{console.log("Deploying bot...");let a=await e.post(e.fhirUrl("Bot",r.id,"$deploy"),{code:n,filename:gt(o)});console.log("Deploy result: "+a.issue?.[0]?.details?.text)}catch(a){console.log("Deploy error: ",a)}}async function Ke(e,t,r,o,n,a){try{let s={name:t,description:"",runtimeVersion:a},c=await e.post("admin/projects/"+r+"/bot",s),d=await e.readResource("Bot",c.id),g={name:t,id:c.id,source:o,dist:n};await Ie(e,g,d),await Te(e,g,d),console.log(`Success! Bot created: ${d.id}`),Uo(g)}catch(s){console.log("Error while creating new bot: "+s)}}function St(e){let t=new RegExp("^"+Lo(e).replace(/\\\*/g,".*")+"$"),r=j()?.bots?.filter(o=>t.test(o.name));return r||[]}function j(e){let t=e?`medplum.${e}.config.json`:"medplum.config.json",r=He(t);if(r)return JSON.parse(r)}function He(e){let t=wt(process.cwd(),e);return Wo(t)?yt(t,"utf8"):""}function Uo(e){let t=j()??{};t.bots||(t.bots=[]),t.bots.push(e),Mo("medplum.config.json",JSON.stringify(t,null,2),"utf8"),console.log(`Bot added to config: ${e.id}`)}function Lo(e){return e.replace(/[/\-\\^$*+?.()|[\]{}]/g,"\\$&")}function Et(e){let o=0,n=0;return No.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 ke(){return{extension:[{url:"http://hl7.org/fhir/StructureDefinition/data-absent-reason",valueCode:"unsupported"}]}}function $o(e){let t=Jo(e).toLowerCase();return[".cjs",".mjs",".js"].includes(t)?_e.JAVASCRIPT:[".cts",".mts",".ts"].includes(t)?_e.TYPESCRIPT:_e.TEXT}function de(e,t){let r=new T(e),o={name:e,...t};return r.setObject("options",o),console.log(`${e} profile created`),o}function bt(e){return new T(e).getObject("options")}async function At(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=ht(JSON.stringify(r)),s=ht(JSON.stringify(n)),c=`${a}.${s}`,d=Ro("sha256",t.clientSecret).update(c).digest("base64url"),g=`${c}.${d}`;await e.startJwtBearerLogin(t.clientId,g,t.scope??"")}async function Ct(e,t){let r=Oo(yt(wt(t.privateKeyPath))),o=await new q({}).setProtectedHeader({alg:"RS384",typ:"JWT"}).setIssuer(t.clientId).setSubject(t.clientId).setAudience(`${t.baseUrl}${t.audience}`).setJti(Do(16).toString("hex")).setIssuedAt().setExpirationTime("5m").sign(r);await e.startJwtAssertionLogin(o)}var Pt="medplum-cli",vt="http://localhost:9615",Oe=p("login"),De=p("whoami");Oe.action(async e=>{let t=e.profile??"default",r=de(t,e),o=await u(e,!1);await zo(o,r)});De.action(async e=>{let t=await u(e);Yo(t)});async function zo(e,t){switch(t?.authType??"authorization-code"){case"authorization-code":await Zo(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 At(e,t);break;case"jwt-assertion":await Ct(e,t);break}console.log("Login successful")}async function Xo(e){let t=Go(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:Pt,redirectUri:vt});o.writeHead(200,{"Content-Type":Re.TEXT}),o.end(`Signed in as ${Bo(s)}. You may close this window.`)}catch(s){o.writeHead(400,{"Content-Type":Re.TEXT}),o.end(`Error: ${Fo(s)}`)}finally{t.close()}else o.writeHead(404,{"Content-Type":Re.TEXT}),o.end("Not found")}).listen(9615)}async function qo(e){let t=Vo(),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)}jo(r)}function Yo(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 Zo(e){await Xo(e);let t=new URL(e.getAuthorizeUrl());t.searchParams.set("client_id",Pt),t.searchParams.set("redirect_uri",vt),t.searchParams.set("scope","openid"),t.searchParams.set("response_type","code"),t.searchParams.set("prompt","login"),await qo(t.toString())}import{Command as ni}from"commander";import{CloudFormationClient as _t,DescribeStackResourcesCommand as Qo,DescribeStacksCommand as en,ListStacksCommand as tn}from"@aws-sdk/client-cloudformation";import{CloudFrontClient as rn,CreateInvalidationCommand as on}from"@aws-sdk/client-cloudfront";import{ECSClient as nn}from"@aws-sdk/client-ecs";import{S3Client as an}from"@aws-sdk/client-s3";var pe=new _t({}),sn=new rn({region:"us-east-1"}),It=new nn({}),Y=new an({}),cn="medplum:environment";async function We(){return(await pe.send(new tn({}))).StackSummaries?.filter(t=>t.StackName&&t.StackStatus!=="DELETE_COMPLETE")||[]}async function M(e){let t=await We();for(let r of t){let o=r.StackName,n=await Me(o);if(n?.tag===e)return n}}async function Me(e){let t={};return await xt(pe,e,t),await pe.config.region()!=="us-east-1"&&await xt(new _t({region:"us-east-1"}),e+"-us-east-1",t),t}async function xt(e,t,r){let o=new en({StackName:t}),a=(await e.send(o))?.Stacks?.[0],s=a?.Tags?.find(d=>d.Key===cn);if(!s)return;let c=await e.send(new Qo({StackName:t}));if(c.StackResources){e===pe&&(r.stack=a,r.tag=s.Value);for(let d of c.StackResources)dn(d,r)}}function dn(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 me(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: ${Je(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 Je(e){return e?.PhysicalResourceId?.split("/")?.pop()||""}async function le(e){let t=await sn.send(new on({DistributionId:e,InvalidationBatch:{CallerReference:`invalidate-all-${Date.now()}`,Paths:{Quantity:1,Items:["/*"]}}}));console.log(`Created invalidation with ID: ${t.Invalidation?.Id}`)}async function Tt(e){let t=await M(e);if(!t){console.log("Stack not found");return}me(t)}import{ACMClient as kt,ListCertificatesCommand as pn,RequestCertificateCommand as mn}from"@aws-sdk/client-acm";import{CloudFrontClient as ln,CreatePublicKeyCommand as un}from"@aws-sdk/client-cloudfront";import{GetParameterCommand as fn,PutParameterCommand as hn,SSMClient as yn}from"@aws-sdk/client-ssm";import{GetCallerIdentityCommand as gn,STSClient as wn}from"@aws-sdk/client-sts";import{normalizeErrorString as Sn}from"@medplum/core";import{generateKeyPairSync as En,randomUUID as Kt}from"crypto";import{existsSync as bn,writeFileSync as An}from"fs";import{resolve as Cn}from"path";import Pn from"readline";var vn=e=>`${e}DomainName`,Rt=e=>`${e}SslCertArn`,ue;async function Ot(){let e={apiPort:8103,region:"us-east-1"};ue=Pn.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 xn(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 Ne("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 x("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 x("What is the config file name?",`medplum.${e.name}.config.json`);bn(r)&&(i("Config file already exists."),await Ne("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 x("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 x("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 x("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 x("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 x("Enter your support email address:");h("API DOMAIN NAME"),i("Medplum deploys a REST API for the backend services."),e.apiDomainName=await x("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 x("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 x("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 x("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 Z("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 fe("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 Z("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 Z("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 Z("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 Z("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 x("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 Kn(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 _n(e.region);i("Found "+s.length+" certificate(s).");for(let{region:d,certName:g}of[{region:e.region,certName:"api"},{region:"us-east-1",certName:"app"},{region:"us-east-1",certName:"storage"}]){i("");let H=await In(e,s,d,g);e[Rt(g)]=H,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 fe("Do you want to store these values in AWS Parameter Store?"))await Rn(e.region,`/medplum/${e.name}/`,c);else{let d=r.replace(".json",".server.json");y(d,c),i("Skipping AWS Parameter Store."),i("Writing values to local config file: "+d),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(""),ue.close()}function i(e){ue.write(e+`
3
3
  `)}function h(e){i(`
4
4
  `+e+`
5
- `)}function x(e,t=""){return new Promise(r=>{fe.question(e+(t?" ("+t+")":"")+" ",o=>{r(o||t.toString())})})}async function Ne(e,t,r=""){let o=e+" ["+t.map(n=>n===r?"("+n+")":n).join("|")+"]";for(;;){let n=await x(o)||r;if(t.includes(n))return n;i("Please choose one of the following options: "+t.join(", "))}}async function ee(e,t,r){return parseInt(await Ne(e,t.map(o=>o.toString()),r.toString()),10)}async function Ue(e){return(await Ne(e,["y","n"])).toLowerCase()==="y"}async function ue(e){if(!await Ue(e))throw i("Exiting..."),new Error("User cancelled")}function g(e,t){Sn(En(e),JSON.stringify(t,void 0,2),"utf-8")}async function An(e){try{let t=new yn({region:e}),r=new hn({});return(await t.send(r)).Account}catch(t){console.log("Warning: Unable to get AWS account ID",t.message);return}}async function Pn(e){let t=await Ht(e);if(e!=="us-east-1"){let r=await Ht("us-east-1");t.push(...r)}return t}async function Ht(e){try{let t=new kt({region:e}),r=new cn({MaxItems:1e3});return(await t.send(r)).CertificateSummaryList}catch(t){return console.log("Warning: Unable to list certificates",t.message),[]}}async function vn(e,t,r,o){let n=e[Cn(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 Ue("Do you want to request a new certificate?"))return i(`Please add your certificate ARN to the config file in the "${Rt(o)}" setting.`),"TODO";let s=await xn(r,n);return i("Certificate ARN: "+s),s}async function xn(e,t){try{let r=await Ne("Validate certificate using DNS or email validation?",["dns","email"],"dns"),o=new kt({region:e}),n=new dn({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 _n(e){let t=Kt(),r=gn("rsa",{modulusLength:2048,publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs1",format:"pem",cipher:"aes-256-cbc",passphrase:t}});return{keyId:(await new pn({}).send(new mn({PublicKeyConfig:{Name:e,CallerReference:Kt(),EncodedKey:r.publicKey}}))).PublicKey?.Id,publicKey:r.publicKey,privateKey:r.privateKey,passphrase:t}}async function In(e,t){let r=new ln({Name:t,WithDecryption:!0});try{return(await e.send(r)).Parameter?.Value}catch(o){if(o.name==="ParameterNotFound")return;throw o}}async function Tn(e,t,r){let o=new un({Name:t,Value:r,Type:"SecureString",Overwrite:!0});await e.send(o)}async function Kn(e,t,r){let o=new fn({region:e});for(let[n,a]of Object.entries(r)){let s=t+n,c=a.toString(),p=await In(o,s);p!==void 0&&p!==c&&(i(`Parameter "${s}" exists with different value.`),await ue(`Do you want to overwrite "${s}"?`)),await Tn(o,s,c)}}async function Dt(){let e=await Me();for(let t of e){let r=t.StackName,o=await We(r);o&&(me(o),console.log(""))}}import{PutObjectCommand as Hn}from"@aws-sdk/client-s3";import{ContentType as H}from"@medplum/core";import kn from"fast-glob";import{createReadStream as Rn,mkdtempSync as On,readdirSync as Dn,readFileSync as Mn,rmSync as Wn,writeFileSync as Jn}from"fs";import Mt from"node-fetch";import{tmpdir as Nn}from"os";import{join as he,sep as Un}from"path";import{pipeline as Ln}from"stream/promises";async function Wt(e,t){let r=V(e);if(!r){console.log("Config not found");return}let o=await W(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 Bn("@medplum/app","latest");Jt(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 jn(a,n.PhysicalResourceId,t),o.appDistribution?.PhysicalResourceId&&!t.dryrun&&await le(o.appDistribution.PhysicalResourceId),console.log("Done")}async function $n(e,t){let r=`https://registry.npmjs.org/${e}/${t}`;return(await Mt(r)).json()}async function Bn(e,t){let o=(await $n(e,t)).dist.tarball,n=On(he(Nn(),"tarball-"));try{let a=await Mt(o),s=Et(n);return await Ln(a.body,s),he(n,"package","dist")}catch(a){throw Wn(n,{recursive:!0,force:!0}),a}}function Jt(e,t){for(let r of Dn(e,{withFileTypes:!0})){let o=he(e,r.name);r.isDirectory()?Jt(o,t):r.isFile()&&o.endsWith(".js")&&Fn(o,t)}}function Fn(e,t){let r=Mn(e,"utf-8");for(let[o,n]of Object.entries(t))r=r.replaceAll(`__${o}__`,n);Jn(e,r)}async function jn(e,t,r){let o=[["assets/**/*.css",H.CSS,!0],["assets/**/*.css.map",H.JSON,!0],["assets/**/*.js",H.JAVASCRIPT,!0],["assets/**/*.js.map",H.JSON,!0],["assets/**/*.txt",H.TEXT,!0],["assets/**/*.ico",H.FAVICON,!0],["img/**/*.png",H.PNG,!0],["img/**/*.svg",H.SVG,!0],["robots.txt",H.TEXT,!0],["index.html",H.HTML,!1]];for(let n of o)await Gn({rootDir:e,bucketName:t,fileNamePattern:n[0],contentType:n[1],cached:n[2],dryrun:r.dryrun})}async function Gn(e){let t=kn.sync(e.fileNamePattern,{cwd:e.rootDir});for(let r of t)await Vn(he(e.rootDir,r),e)}async function Vn(e,t){let r=Rn(e),o=e.substring(t.rootDir.length+1).split(Un).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 Q.send(new Hn(n))}import{GetBucketPolicyCommand as zn,PutBucketPolicyCommand as Xn}from"@aws-sdk/client-s3";async function Ut(e,t){if(!V(e)){console.log("Config not found");return}let o=await W(e);if(!o){console.log("Stack not found");return}await Nt("App",o.appBucket,o.appDistribution,o.appOriginAccessIdentity,t),await Nt("Storage",o.storageBucket,o.storageDistribution,o.storageOriginAccessIdentity,t),console.log("Done")}async function Nt(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 qn(a);if(Zn(c,a,s)){console.log(`${e} bucket already has policy statement`);return}Qn(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 Yn(a,c),console.log("Bucket policy updated"),console.log("Creating CloudFront invalidation..."),await le(r.PhysicalResourceId),console.log("CloudFront invalidation created"),console.log(`${e} bucket policy updated`))}async function qn(e){let t=await Q.send(new zn({Bucket:e}));return JSON.parse(t.Policy??"{}")}async function Yn(e,t){await Q.send(new Xn({Bucket:e,Policy:JSON.stringify(t)}))}function Zn(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 Qn(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}/*`]})}import{UpdateServiceCommand as ei}from"@aws-sdk/client-ecs";async function Lt(e){let t=await W(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=Je(t.ecsService);if(!o){console.log("ECS Service not found");return}await It.send(new ei({cluster:r,service:o,forceNewDeployment:!0})),console.log(`Service "${o}" updated successfully.`)}var J=new ti("aws").description("Commands to manage AWS resources");J.command("init").description("Initialize a new Medplum AWS CloudFormation stacks").action(Ot);J.command("list").description("List Medplum AWS CloudFormation stacks").action(Dt);J.command("describe").description("Describe a Medplum AWS CloudFormation stack by tag").argument("<tag>").action(Tt);J.command("update-server").alias("deploy-server").description("Update the server image").argument("<tag>").action(Lt);J.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(Wt);J.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(Ut);import{Command as ri}from"commander";var $t=d("save"),Bt=d("deploy"),Ft=d("create"),jt=new ri("bot").addCommand($t).addCommand(Bt).addCommand(Ft),Le=d("save-bot"),$e=d("deploy-bot"),Be=d("create-bot");$t.description("Saving the bot").argument("<botName>").action(async(e,t)=>{let r=await u(t);await ye(r,e)});Bt.description("Deploy the app to AWS").argument("<botName>").action(async(e,t)=>{let r=await u(t);await ye(r,e,!0)});Ft.arguments("<botName> <projectId> <sourceFile> <distFile>").description("Creating a bot").option("--runtime-version <runtimeVersion>","Runtime version (awslambda, vmcontext)").action(async(e,t,r,o,n)=>{let a=await u(n);await Ke(a,e,t,r,o,n.runtimeVersion)});async function ye(e,t,r=!1){let o=St(t);for(let n of o){let a=await e.readResource("Bot",n.id);await Ie(e,n,a),r&&await Te(e,n,a)}console.log(`Number of bots deployed: ${o.length}`)}Le.description("Saves the bot").argument("<botName>").action(async(e,t)=>{let r=await u(t);await ye(r,e)});$e.description("Deploy the bot to AWS").argument("<botName>").action(async(e,t)=>{let r=await u(t);await ye(r,e,!0)});Be.arguments("<botName> <projectId> <sourceFile> <distFile>").description("Creates and saves the bot").action(async(e,t,r,o,n)=>{let a=await u(n);await Ke(a,e,t,r,o)});import{Command as oi}from"commander";import{createReadStream as ni,writeFile as ii}from"fs";import{resolve as Vt}from"path";import{createInterface as ai}from"readline";var zt=d("export"),Xt=d("import"),qt=new oi("bulk").addCommand(zt).addCommand(Xt);zt.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 u(e);(await a.bulkExport(t,r,o)).output?.forEach(async({type:c,url:p})=>{let y=new URL(p),T=await a.download(p),_=`${c}_${y.pathname}`.replace(/[^a-zA-Z0-9]+/g,"_")+".ndjson",N=Vt(n??"",_);ii(`${N}`,await T.text(),()=>{console.log(`${N} is created`)})})});Xt.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=Vt(n??process.cwd(),e),s=await u(t);await si(a,parseInt(r,10),s,o)});async function si(e,t,r,o){let n=[],a=ni(e),s=ai({input:a});for await(let c of s){let p=ci(c,o);n.push({resource:p,request:{method:"POST",url:p.resourceType}}),n.length%t===0&&(await Gt(n,r),n=[])}n.length>0&&await Gt(n,r)}async function Gt(e,t){(await t.executeBatch({resourceType:"Bundle",type:"transaction",entry:e})).entry?.forEach(o=>{R(o.response)})}function ci(e,t){let r=JSON.parse(e);return t?di(r):r}function di(e){return e.resourceType==="ExplanationOfBenefit"?pi(e):e}function pi(e){return e.provider||(e.provider=ke()),e.item?.forEach(t=>{t?.productOrService||(t.productOrService=ke())}),e}import{formatHl7DateTime as yi,Hl7Message as gi}from"@medplum/core";import{connect as mi}from"net";import{Hl7Message as li}from"@medplum/core";import hi from"net";var er=class extends EventTarget{addEventListener(e,t,r){super.addEventListener(e,t,r)}removeEventListener(e,t,r){super.removeEventListener(e,t,r)}},ui=String.fromCharCode(11),Yt=String.fromCharCode(28),Zt=String.fromCharCode(13),fi=class extends Event{constructor(e,t){super("message"),this.connection=e,this.message=t}},Qt=class extends Event{constructor(e){super("error"),this.error=e}},tr=class extends er{constructor(e,t){super(),this.socket=e,this.encoding=t;let r="";e.on("data",o=>{try{if(r+=o.toString(),r.endsWith(Yt+Zt)){let n=li.parse(r.substring(1,r.length-2));this.dispatchEvent(new fi(this,n)),r=""}}catch(n){this.dispatchEvent(new Qt(n))}}).setEncoding(t??"utf-8"),e.on("error",o=>{r="",this.dispatchEvent(new Qt(o))})}send(e){this.socket.write(ui+e.toString()+Yt+Zt)}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()}},rr=class extends er{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=mi({host:this.host,port:this.port},()=>{this.connection=new tr(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)}},or=class{constructor(e){this.handler=e}start(e,t){let r=hi.createServer(o=>{let n=new tr(o,t);this.handler(n)});r.listen(e),this.server=r}stop(){this.server&&(this.server.close(),this.server=void 0)}};import{Command as wi}from"commander";import{readFileSync as Si}from"fs";var Ei=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=Ci():o.file&&(r=Si(o.file,"utf8")),!r)throw new Error("Missing HL7 message body");let n=new rr({host:e,port:parseInt(t,10)});try{let a=await n.sendAndWait(gi.parse(r));console.log(a.toString().replaceAll("\r",`
6
- `))}finally{n.close()}}),bi=d("listen").description("Starts an HL7 v2 MLLP server").argument("<port>").action(async e=>{new or(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)}),nr=new wi("hl7").addCommand(Ei).addCommand(bi);function Ci(){let e=yi(new Date),t=Date.now().toString();return`MSH|^~\\&|ADTSYS|HOSPITAL|RECEIVER|DEST|${e}||ADT^A01|${t}|P|2.5|
5
+ `)}function x(e,t=""){return new Promise(r=>{ue.question(e+(t?" ("+t+")":"")+" ",o=>{r(o||t.toString())})})}async function Ue(e,t,r=""){let o=e+" ["+t.map(n=>n===r?"("+n+")":n).join("|")+"]";for(;;){let n=await x(o)||r;if(t.includes(n))return n;i("Please choose one of the following options: "+t.join(", "))}}async function Z(e,t,r){return parseInt(await Ue(e,t.map(o=>o.toString()),r.toString()),10)}async function fe(e){return(await Ue(e,["y","n"])).toLowerCase()==="y"}async function Ne(e){if(!await fe(e))throw i("Exiting..."),new Error("User cancelled")}function y(e,t){An(Cn(e),JSON.stringify(t,void 0,2),"utf-8")}async function xn(e){try{let t=new wn({region:e}),r=new gn({});return(await t.send(r)).Account}catch(t){console.log("Warning: Unable to get AWS account ID",t.message);return}}async function _n(e){let t=await Ht(e);if(e!=="us-east-1"){let r=await Ht("us-east-1");t.push(...r)}return t}async function Ht(e){try{let t=new kt({region:e}),r=new pn({MaxItems:1e3});return(await t.send(r)).CertificateSummaryList}catch(t){return console.log("Warning: Unable to list certificates",t.message),[]}}async function In(e,t,r,o){let n=e[vn(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 fe("Do you want to request a new certificate?"))return i(`Please add your certificate ARN to the config file in the "${Rt(o)}" setting.`),"TODO";let s=await Tn(r,n);return i("Certificate ARN: "+s),s}async function Tn(e,t){try{let r=await Ue("Validate certificate using DNS or email validation?",["dns","email"],"dns"),o=new kt({region:e}),n=new mn({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 Kn(e){let t=Kt(),r=En("rsa",{modulusLength:2048,publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs1",format:"pem",cipher:"aes-256-cbc",passphrase:t}});try{return{keyId:(await new ln({}).send(new un({PublicKeyConfig:{Name:e,CallerReference:Kt(),EncodedKey:r.publicKey}}))).PublicKey?.Id,publicKey:r.publicKey,privateKey:r.privateKey,passphrase:t}}catch(o){console.log("Error: Unable to create signing key: ",Sn(o));return}}async function Hn(e,t){let r=new fn({Name:t,WithDecryption:!0});try{return(await e.send(r)).Parameter?.Value}catch(o){if(o.name==="ParameterNotFound")return;throw o}}async function kn(e,t,r){let o=new hn({Name:t,Value:r,Type:"SecureString",Overwrite:!0});await e.send(o)}async function Rn(e,t,r){let o=new yn({region:e});for(let[n,a]of Object.entries(r)){let s=t+n,c=a.toString(),d=await Hn(o,s);d!==void 0&&d!==c&&(i(`Parameter "${s}" exists with different value.`),await Ne(`Do you want to overwrite "${s}"?`)),await kn(o,s,c)}}async function Dt(){let e=await We();for(let t of e){let r=t.StackName,o=await Me(r);o&&(me(o),console.log(""))}}import{PutObjectCommand as On}from"@aws-sdk/client-s3";import{ContentType as K}from"@medplum/core";import Dn from"fast-glob";import{createReadStream as Wn,mkdtempSync as Mn,readdirSync as Jn,readFileSync as Nn,rmSync as Un,writeFileSync as Ln}from"fs";import Wt from"node-fetch";import{tmpdir as $n}from"os";import{join as he,sep as Bn}from"path";import{pipeline as Fn}from"stream/promises";async function Mt(e,t){let r=j(e);if(!r){console.log("Config not found");return}let o=await M(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 Gn("@medplum/app","latest");Jt(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 zn(a,n.PhysicalResourceId,t),o.appDistribution?.PhysicalResourceId&&!t.dryrun&&await le(o.appDistribution.PhysicalResourceId),console.log("Done")}async function jn(e,t){let r=`https://registry.npmjs.org/${e}/${t}`;return(await Wt(r)).json()}async function Gn(e,t){let o=(await jn(e,t)).dist.tarball,n=Mn(he($n(),"tarball-"));try{let a=await Wt(o),s=Et(n);return await Fn(a.body,s),he(n,"package","dist")}catch(a){throw Un(n,{recursive:!0,force:!0}),a}}function Jt(e,t){for(let r of Jn(e,{withFileTypes:!0})){let o=he(e,r.name);r.isDirectory()?Jt(o,t):r.isFile()&&o.endsWith(".js")&&Vn(o,t)}}function Vn(e,t){let r=Nn(e,"utf-8");for(let[o,n]of Object.entries(t))r=r.replaceAll(`__${o}__`,n);Ln(e,r)}async function zn(e,t,r){let o=[["assets/**/*.css",K.CSS,!0],["assets/**/*.css.map",K.JSON,!0],["assets/**/*.js",K.JAVASCRIPT,!0],["assets/**/*.js.map",K.JSON,!0],["assets/**/*.txt",K.TEXT,!0],["assets/**/*.ico",K.FAVICON,!0],["img/**/*.png",K.PNG,!0],["img/**/*.svg",K.SVG,!0],["robots.txt",K.TEXT,!0],["index.html",K.HTML,!1]];for(let n of o)await Xn({rootDir:e,bucketName:t,fileNamePattern:n[0],contentType:n[1],cached:n[2],dryrun:r.dryrun})}async function Xn(e){let t=Dn.sync(e.fileNamePattern,{cwd:e.rootDir});for(let r of t)await qn(he(e.rootDir,r),e)}async function qn(e,t){let r=Wn(e),o=e.substring(t.rootDir.length+1).split(Bn).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 Y.send(new On(n))}import{GetBucketPolicyCommand as Yn,PutBucketPolicyCommand as Zn}from"@aws-sdk/client-s3";async function Ut(e,t){if(!j(e)){console.log("Config not found");return}let o=await M(e);if(!o){console.log("Stack not found");return}await Nt("App",o.appBucket,o.appDistribution,o.appOriginAccessIdentity,t),await Nt("Storage",o.storageBucket,o.storageDistribution,o.storageOriginAccessIdentity,t),console.log("Done")}async function Nt(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 Qn(a);if(ti(c,a,s)){console.log(`${e} bucket already has policy statement`);return}ri(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 ei(a,c),console.log("Bucket policy updated"),console.log("Creating CloudFront invalidation..."),await le(r.PhysicalResourceId),console.log("CloudFront invalidation created"),console.log(`${e} bucket policy updated`))}async function Qn(e){let t=await Y.send(new Yn({Bucket:e}));return JSON.parse(t.Policy??"{}")}async function ei(e,t){await Y.send(new Zn({Bucket:e,Policy:JSON.stringify(t)}))}function ti(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 ri(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}/*`]})}import{UpdateServiceCommand as oi}from"@aws-sdk/client-ecs";async function Lt(e){let t=await M(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=Je(t.ecsService);if(!o){console.log("ECS Service not found");return}await It.send(new oi({cluster:r,service:o,forceNewDeployment:!0})),console.log(`Service "${o}" updated successfully.`)}var J=new ni("aws").description("Commands to manage AWS resources");J.command("init").description("Initialize a new Medplum AWS CloudFormation stacks").action(Ot);J.command("list").description("List Medplum AWS CloudFormation stacks").action(Dt);J.command("describe").description("Describe a Medplum AWS CloudFormation stack by tag").argument("<tag>").action(Tt);J.command("update-server").alias("deploy-server").description("Update the server image").argument("<tag>").action(Lt);J.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(Mt);J.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(Ut);import{Command as ii}from"commander";var $t=p("save"),Bt=p("deploy"),Ft=p("create"),jt=new ii("bot").addCommand($t).addCommand(Bt).addCommand(Ft),Le=p("save-bot"),$e=p("deploy-bot"),Be=p("create-bot");$t.description("Saving the bot").argument("<botName>").action(async(e,t)=>{let r=await u(t);await ye(r,e)});Bt.description("Deploy the app to AWS").argument("<botName>").action(async(e,t)=>{let r=await u(t);await ye(r,e,!0)});Ft.arguments("<botName> <projectId> <sourceFile> <distFile>").description("Creating a bot").option("--runtime-version <runtimeVersion>","Runtime version (awslambda, vmcontext)").action(async(e,t,r,o,n)=>{let a=await u(n);await Ke(a,e,t,r,o,n.runtimeVersion)});async function ye(e,t,r=!1){let o=St(t);for(let n of o){let a=await e.readResource("Bot",n.id);await Ie(e,n,a),r&&await Te(e,n,a)}console.log(`Number of bots deployed: ${o.length}`)}Le.description("Saves the bot").argument("<botName>").action(async(e,t)=>{let r=await u(t);await ye(r,e)});$e.description("Deploy the bot to AWS").argument("<botName>").action(async(e,t)=>{let r=await u(t);await ye(r,e,!0)});Be.arguments("<botName> <projectId> <sourceFile> <distFile>").description("Creates and saves the bot").action(async(e,t,r,o,n)=>{let a=await u(n);await Ke(a,e,t,r,o)});import{Command as ai}from"commander";import{createReadStream as si,writeFile as ci}from"fs";import{resolve as Vt}from"path";import{createInterface as di}from"readline";var zt=p("export"),Xt=p("import"),qt=new ai("bulk").addCommand(zt).addCommand(Xt);zt.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 u(e);(await a.bulkExport(t,r,o)).output?.forEach(async({type:c,url:d})=>{let g=new URL(d),H=await a.download(d),I=`${c}_${g.pathname}`.replace(/[^a-zA-Z0-9]+/g,"_")+".ndjson",ee=Vt(n??"",I);ci(`${ee}`,await H.text(),()=>{console.log(`${ee} is created`)})})});Xt.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=Vt(n??process.cwd(),e),s=await u(t);await pi(a,parseInt(r,10),s,o)});async function pi(e,t,r,o){let n=[],a=si(e),s=di({input:a});for await(let c of s){let d=mi(c,o);n.push({resource:d,request:{method:"POST",url:d.resourceType}}),n.length%t===0&&(await Gt(n,r),n=[])}n.length>0&&await Gt(n,r)}async function Gt(e,t){(await t.executeBatch({resourceType:"Bundle",type:"transaction",entry:e})).entry?.forEach(o=>{R(o.response)})}function mi(e,t){let r=JSON.parse(e);return t?li(r):r}function li(e){return e.resourceType==="ExplanationOfBenefit"?ui(e):e}function ui(e){return e.provider||(e.provider=ke()),e.item?.forEach(t=>{t?.productOrService||(t.productOrService=ke())}),e}import{formatHl7DateTime as Si,Hl7Message as Ei}from"@medplum/core";import{connect as fi}from"net";import{Hl7Message as hi}from"@medplum/core";import wi from"net";var er=class extends EventTarget{addEventListener(e,t,r){super.addEventListener(e,t,r)}removeEventListener(e,t,r){super.removeEventListener(e,t,r)}},yi="\v",Yt="",Zt="\r",gi=class extends Event{constructor(e,t){super("message"),this.connection=e,this.message=t}},Qt=class extends Event{constructor(e){super("error"),this.error=e}},tr=class extends er{constructor(e,t){super(),this.socket=e,this.encoding=t;let r="";e.on("data",o=>{try{if(r+=o.toString(),r.endsWith(Yt+Zt)){let n=hi.parse(r.substring(1,r.length-2));this.dispatchEvent(new gi(this,n)),r=""}}catch(n){this.dispatchEvent(new Qt(n))}}).setEncoding(t??"utf-8"),e.on("error",o=>{r="",this.dispatchEvent(new Qt(o))})}send(e){this.socket.write(yi+e.toString()+Yt+Zt)}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()}},rr=class extends er{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=fi({host:this.host,port:this.port},()=>{this.connection=new tr(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)}},or=class{constructor(e){this.handler=e}start(e,t){let r=wi.createServer(o=>{let n=new tr(o,t);this.handler(n)});r.listen(e),this.server=r}stop(){this.server&&(this.server.close(),this.server=void 0)}};import{Command as bi}from"commander";import{readFileSync as Ai}from"fs";var Ci=p("send").description("Send an HL7 v2 message via MLLP").argument("<host>","The destination host name or IP address").argument("<port>","The destination port number").argument("[body]","Optional HL7 message body").option("--generate-example","Generate a sample HL7 message").option("--file <file>","Read the HL7 message from a file").action(async(e,t,r,o)=>{if(o.generateExample?r=vi():o.file&&(r=Ai(o.file,"utf8")),!r)throw new Error("Missing HL7 message body");let n=new rr({host:e,port:parseInt(t,10)});try{let a=await n.sendAndWait(Ei.parse(r));console.log(a.toString().replaceAll("\r",`
6
+ `))}finally{n.close()}}),Pi=p("listen").description("Starts an HL7 v2 MLLP server").argument("<port>").action(async e=>{new or(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)}),nr=new bi("hl7").addCommand(Ci).addCommand(Pi);function vi(){let e=Si(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|`}import{Command as Ai}from"commander";import{resolve as Pi}from"path";import{readdirSync as vi}from"fs";import{homedir as xi}from"os";var ir=d("set"),ar=d("remove"),sr=d("list"),cr=d("describe"),dr=new Ai("profile").addCommand(ir).addCommand(ar).addCommand(sr).addCommand(cr);ir.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)=>{de(e,t)});ar.argument("<profileName>","Name of the profile").description("Remove a profile by name").action(async e=>{new K(e).setObject("options",void 0),console.log(`${e} profile removed`)});sr.description("List all profiles saved").action(async()=>{let e=Pi(xi(),".medplum"),t=vi(e),r=[];t.forEach(o=>{let n=o.split(".")[0],s=new K(n).getObject("options");s&&r.push({profileName:n,profile:s})}),console.log(r)});cr.argument("<profileName>","Name of the profile").description("Describes a profile").action(async e=>{let t=bt(e);console.log(t)});import{Command as _i,Option as Ii}from"commander";var pr=d("list"),mr=d("current"),lr=d("switch"),ur=d("invite"),fr=new _i("project").addCommand(pr).addCommand(mr).addCommand(lr).addCommand(ur);pr.description("List of current projects").action(async e=>{let t=await u(e);Ti(t)});function Ti(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|`}import{Command as xi}from"commander";import{resolve as _i}from"path";import{readdirSync as Ii}from"fs";import{homedir as Ti}from"os";var ir=p("set"),ar=p("remove"),sr=p("list"),cr=p("describe"),dr=new xi("profile").addCommand(ir).addCommand(ar).addCommand(sr).addCommand(cr);ir.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)=>{de(e,t)});ar.argument("<profileName>","Name of the profile").description("Remove a profile by name").action(async e=>{new T(e).setObject("options",void 0),console.log(`${e} profile removed`)});sr.description("List all profiles saved").action(async()=>{let e=_i(Ti(),".medplum"),t=Ii(e),r=[];t.forEach(o=>{let n=o.split(".")[0],s=new T(n).getObject("options");s&&r.push({profileName:n,profile:s})}),console.log(r)});cr.argument("<profileName>","Name of the profile").description("Describes a profile").action(async e=>{let t=bt(e);console.log(t)});import{Command as Ki,Option as Hi}from"commander";var pr=p("list"),mr=p("current"),lr=p("switch"),ur=p("invite"),fr=new Ki("project").addCommand(pr).addCommand(mr).addCommand(lr).addCommand(ur);pr.description("List of current projects").action(async e=>{let t=await u(e);ki(t)});function ki(e){let r=e.getLogins().map(o=>`${o.project.display} (${o.project.reference})`).join(`
11
11
 
12
- `);console.log(r)}mr.description("Project you are currently on").action(async e=>{let r=(await u(e)).getActiveLogin();if(!r)throw new Error("Unauthenticated: run `npx medplum login` to login");console.log(`${r.project.display} (${r.project.reference})`)});lr.description("Switching to another project from the current one").argument("<projectId>").action(async(e,t)=>{let r=await u(t);await Ki(r,e)});ur.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 Ii("-r, --role <role>","Role of user").choices(["Practitioner","Patient","RelatedPerson"]).default("Practitioner")).action(async(e,t,r,o)=>{let n=await u(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 Hi(s,c,n)});async function Ki(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 Hi(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)}}import{convertToTransactionBundle as ki}from"@medplum/core";var Fe=d("delete"),je=d("get"),Ge=d("patch"),Ve=d("post"),ze=d("put");Fe.argument("<url>","Resource/$id").action(async(e,t)=>{let r=await u(t);R(await r.delete(te(r,e)))});je.argument("<url>","Resource/$id").option("--as-transaction","Print out the bundle as a transaction type").action(async(e,t)=>{let r=await u(t),o=await r.get(te(r,e));t.asTransaction?R(ki(o)):R(o)});Ge.arguments("<url> <body>").action(async(e,t,r)=>{let o=await u(r);R(await o.patch(te(o,e),Xe(t)))});Ve.arguments("<url> <body>").action(async(e,t,r)=>{let o=await u(r);R(await o.post(te(o,e),Xe(t)))});ze.arguments("<url> <body>").action(async(e,t,r)=>{let o=await u(r);R(await o.put(te(o,e),Xe(t)))});function Xe(e){if(e)try{return JSON.parse(e)}catch{return e}}function te(e,t){return["admin/","auth/","fhir/R4"].some(o=>t.startsWith(o))?t:e.fhirUrl(t).toString()}async function Wi(e){try{let t=new Di("medplum").description("Command to access Medplum CLI");t.version(Ri),t.addCommand(Oe),t.addCommand(De),t.addCommand(je),t.addCommand(Ve),t.addCommand(Ge),t.addCommand(ze),t.addCommand(Fe),t.addCommand(fr),t.addCommand(qt),t.addCommand(jt),t.addCommand(Le),t.addCommand($e),t.addCommand(Be),t.addCommand(dr),t.addCommand(J),t.addCommand(nr),await t.parseAsync(e)}catch(t){console.error("Error: "+Oi(t))}}async function Ji(){Mi.config(),await Wi(process.argv)}qe.main===module&&Ji().catch(e=>console.error("Unhandled error:",e));export{Wi as main,Ji as run};
12
+ `);console.log(r)}mr.description("Project you are currently on").action(async e=>{let r=(await u(e)).getActiveLogin();if(!r)throw new Error("Unauthenticated: run `npx medplum login` to login");console.log(`${r.project.display} (${r.project.reference})`)});lr.description("Switching to another project from the current one").argument("<projectId>").action(async(e,t)=>{let r=await u(t);await Ri(r,e)});ur.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 Hi("-r, --role <role>","Role of user").choices(["Practitioner","Patient","RelatedPerson"]).default("Practitioner")).action(async(e,t,r,o)=>{let n=await u(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 Oi(s,c,n)});async function Ri(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 Oi(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)}}import{convertToTransactionBundle as Di}from"@medplum/core";var Fe=p("delete"),je=p("get"),Ge=p("patch"),Ve=p("post"),ze=p("put");Fe.argument("<url>","Resource/$id").action(async(e,t)=>{let r=await u(t);R(await r.delete(Q(r,e)))});je.argument("<url>","Resource/$id").option("--as-transaction","Print out the bundle as a transaction type").action(async(e,t)=>{let r=await u(t),o=await r.get(Q(r,e));t.asTransaction?R(Di(o)):R(o)});Ge.arguments("<url> <body>").action(async(e,t,r)=>{let o=await u(r);R(await o.patch(Q(o,e),Xe(t)))});Ve.arguments("<url> <body>").action(async(e,t,r)=>{let o=await u(r);R(await o.post(Q(o,e),Xe(t)))});ze.arguments("<url> <body>").action(async(e,t,r)=>{let o=await u(r);R(await o.put(Q(o,e),Xe(t)))});function Xe(e){if(e)try{return JSON.parse(e)}catch{return e}}function Q(e,t){return["admin/","auth/","fhir/R4"].some(o=>t.startsWith(o))?t:e.fhirUrl(t).toString()}async function Ui(e){try{let t=new Ji("medplum").description("Command to access Medplum CLI");t.version(Wi),t.addCommand(Oe),t.addCommand(De),t.addCommand(je),t.addCommand(Ve),t.addCommand(Ge),t.addCommand(ze),t.addCommand(Fe),t.addCommand(fr),t.addCommand(qt),t.addCommand(jt),t.addCommand(Le),t.addCommand($e),t.addCommand(Be),t.addCommand(dr),t.addCommand(J),t.addCommand(nr),await t.parseAsync(e)}catch(t){console.error("Error: "+Mi(t))}}async function Li(){Ni.config(),await Ui(process.argv)}qe.main===module&&Li().catch(e=>console.error("Unhandled error:",e));export{Ui as main,Li as run};
14
14
  //# sourceMappingURL=index.mjs.map