@medplum/cli 2.2.7 → 2.2.10
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/index.cjs +7 -7
- package/dist/cjs/index.cjs.map +3 -3
- package/dist/esm/index.mjs +7 -7
- package/dist/esm/index.mjs.map +3 -3
- package/package.json +11 -11
package/dist/cjs/index.cjs
CHANGED
|
@@ -1,14 +1,14 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
"use strict";var Co=Object.create;var ne=Object.defineProperty;var Ao=Object.getOwnPropertyDescriptor;var Po=Object.getOwnPropertyNames;var vo=Object.getPrototypeOf,xo=Object.prototype.hasOwnProperty;var _o=(e,t,r)=>t in e?ne(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;var Io=(e,t)=>{for(var r in t)ne(e,r,{get:t[r],enumerable:!0})},xt=(e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of Po(t))!xo.call(e,n)&&n!==r&&ne(e,n,{get:()=>t[n],enumerable:!(o=Ao(t,n))||o.enumerable});return e};var T=(e,t,r)=>(r=e!=null?Co(vo(e)):{},xt(t||!e||!e.__esModule?ne(r,"default",{value:e,enumerable:!0}):r,e)),To=e=>xt(ne({},"__esModule",{value:!0}),e);var l=(e,t,r)=>(_o(e,typeof t!="symbol"?t+"":t,r),r);var ui={};Io(ui,{main:()=>Eo,run:()=>bo});module.exports=To(ui);var $e=require("@medplum/core"),wo=require("commander"),So=T(require("dotenv"));var $=require("@medplum/core"),nr=require("child_process"),ir=require("http"),ar=require("os");var Tt=require("@medplum/core");var _t=require("@medplum/core"),O=require("fs"),It=require("os"),Be=require("path"),R=class extends _t.ClientStorage{constructor(r){super();this.dirName=(0,Be.resolve)((0,It.homedir)(),".medplum"),this.fileName=(0,Be.resolve)(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((0,O.existsSync)(this.fileName))return JSON.parse((0,O.readFileSync)(this.fileName,"utf8"))}writeFile(r){(0,O.existsSync)(this.dirName)||(0,O.mkdirSync)(this.dirName),(0,O.writeFileSync)(this.fileName,JSON.stringify(r,null,2),"utf8")}};async function u(e,t=!0){let r=e.profile??"default",o=new R(r),n=o.getObject("options");if(r!=="default"&&!n)throw new Error(`Profile "${r}" does not exist`);let{baseUrl:a,fhirUrlPath:s,accessToken:c,tokenUrl:p,authorizeUrl:g,clientId:b,clientSecret:k}=Ko(e,o),ye=e.fetch??fetch,ge=new Tt.MedplumClient({fetch:ye,baseUrl:a,tokenUrl:p,fhirUrlPath:s,authorizeUrl:g,storage:o,onUnauthenticated:Ho,verbose:e.verbose});return t&&(c?ge.setAccessToken(c):b&&k&&(ge.setBasicAuth(b,k),n?.authType!=="basic"&&await ge.startClientLogin(b,k))),ge}function Ko(e,t){let r=t.getObject("options"),o=e.baseUrl??r?.baseUrl??process.env.MEDPLUM_BASE_URL??"https://api.medplum.com/",n=e.fhirUrlPath??r?.fhirUrlPath??process.env.MEDPLUM_FHIR_URL_PATH,a=e.accessToken??r?.accessToken??process.env.MEDPLUM_CLIENT_ACCESS_TOKEN,s=e.tokenUrl??r?.tokenUrl??process.env.MEDPLUM_TOKEN_URL,c=e.authorizeUrl??r?.authorizeUrl??process.env.MEDPLUM_AUTHORIZE_URL,p=e.clientId??r?.clientId??process.env.MEDPLUM_CLIENT_ID,g=e.clientSecret??r?.clientSecret??process.env.MEDPLUM_CLIENT_SECRET;return{baseUrl:o,fhirUrlPath:n,accessToken:a,tokenUrl:s,authorizeUrl:c,clientId:p,clientSecret:g}}function Ho(){console.log("Unauthenticated: run `npx medplum login` to sign in")}var we=require("commander");function d(e){return new we.Command(e).option("--client-id <clientId>","FHIR server client id").option("--client-secret <clientSecret>","FHIR server client secret").option("--base-url <baseUrl>","FHIR server base URL, must be absolute").option("--token-url <tokenUrl>","FHIR server token URL, absolute or relative to base URL").option("--authorize-url <authorizeUrl>","FHIR server authorize URL, absolute or relative to base URL").option("--fhir-url, --fhir-url-path <fhirUrlPath>","FHIR server URL, absolute or relative to base URL").option("--scope <scope>","JWT scope").option("--access-token <accessToken>","Access token for token exchange authentication").option("--callback-url <callbackUrl>","Callback URL for authorization code flow").option("--subject <subject>","Subject for JWT authentication").option("--audience <audience>","Audience for JWT authentication").option("--issuer <issuer>","Issuer for JWT authentication").option("--private-key-path <privateKeyPath>","Private key path for JWT assertion").option("--audience <audience>","Audience for JWT assertion").option("-p, --profile <profile>","Profile name").option("-v --verbose","Verbose output").addOption(new we.Option("--auth-type <authType>","Type of authentication").choices(["basic","client-credentials","authorization-code","jwt-bearer","token-exchange","jwt-assertion"]))}var G=require("@medplum/core"),te=require("crypto"),V=require("fs");var Kt=require("buffer");var C=new TextEncoder,S=new TextDecoder,Ci=2**32;function K(...e){let t=e.reduce((n,{length:a})=>n+a,0),r=new Uint8Array(t),o=0;return e.forEach(n=>{r.set(n,o),o+=n.length}),r}var A=e=>Kt.Buffer.from(e).toString("base64url");var j=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 j{constructor(){super(...arguments);l(this,"code","ERR_JOSE_NOT_SUPPORTED")}static get code(){return"ERR_JOSE_NOT_SUPPORTED"}};var P=class extends j{constructor(){super(...arguments);l(this,"code","ERR_JWS_INVALID")}static get code(){return"ERR_JWS_INVALID"}},J=class extends j{constructor(){super(...arguments);l(this,"code","ERR_JWT_INVALID")}static get code(){return"ERR_JWT_INVALID"}};var Oo,Fe=class extends j{constructor(){super(...arguments);l(this,Oo);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"}};Oo=Symbol.asyncIterator;var kt=T(require("util"),1),v=e=>kt.types.isKeyObject(e);var Rt=T(require("crypto"),1),Ot=T(require("util"),1),Do=Rt.webcrypto,Dt=Do,E=e=>Ot.types.isCryptoKey(e);function D(e,t="algorithm.name"){return new TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`)}function Se(e,t){return e.name===t}function Ge(e){return parseInt(e.name.slice(4),10)}function Wo(e){switch(e){case"ES256":return"P-256";case"ES384":return"P-384";case"ES512":return"P-521";default:throw new Error("unreachable")}}function Mo(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 Wt(e,t,...r){switch(t){case"HS256":case"HS384":case"HS512":{if(!Se(e.algorithm,"HMAC"))throw D("HMAC");let o=parseInt(t.slice(2),10);if(Ge(e.algorithm.hash)!==o)throw D(`SHA-${o}`,"algorithm.hash");break}case"RS256":case"RS384":case"RS512":{if(!Se(e.algorithm,"RSASSA-PKCS1-v1_5"))throw D("RSASSA-PKCS1-v1_5");let o=parseInt(t.slice(2),10);if(Ge(e.algorithm.hash)!==o)throw D(`SHA-${o}`,"algorithm.hash");break}case"PS256":case"PS384":case"PS512":{if(!Se(e.algorithm,"RSA-PSS"))throw D("RSA-PSS");let o=parseInt(t.slice(2),10);if(Ge(e.algorithm.hash)!==o)throw D(`SHA-${o}`,"algorithm.hash");break}case"EdDSA":{if(e.algorithm.name!=="Ed25519"&&e.algorithm.name!=="Ed448")throw D("Ed25519 or Ed448");break}case"ES256":case"ES384":case"ES512":{if(!Se(e.algorithm,"ECDSA"))throw D("ECDSA");let o=Wo(t);if(e.algorithm.namedCurve!==o)throw D(o,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}Mo(e,r)}function Mt(e,t,...r){if(r.length>2){let o=r.pop();e+=`one of type ${r.join(", ")}, or ${o}.`}else r.length===2?e+=`one of type ${r[0]} or ${r[1]}.`:e+=`of type ${r[0]}.`;return t==null?e+=` Received ${t}`:typeof t=="function"&&t.name?e+=` Received function ${t.name}`:typeof t=="object"&&t!=null&&t.constructor&&t.constructor.name&&(e+=` Received an instance of ${t.constructor.name}`),e}var x=(e,...t)=>Mt("Key must be ",e,...t);function Ve(e,t,...r){return Mt(`Key for the ${e} algorithm must be `,t,...r)}var ze=e=>v(e)||E(e),f=["KeyObject"];(globalThis.CryptoKey||Dt?.CryptoKey)&&f.push("CryptoKey");var $o=(...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},q=$o;function Bo(e){return typeof e=="object"&&e!==null}function w(e){if(!Bo(e)||Object.prototype.toString.call(e)!=="[object Object]")return!1;if(Object.getPrototypeOf(e)===null)return!0;let t=e;for(;Object.getPrototypeOf(t)!==null;)t=Object.getPrototypeOf(t);return Object.getPrototypeOf(e)===t}var Ee=require("crypto"),Ut=require("util");var Nt=require("crypto");var Fo=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")}},jo=(e,t)=>{let r;if(E(e))r=Nt.KeyObject.from(e);else if(v(e))r=e;else throw new TypeError(x(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:Fo(o)}default:throw new TypeError("Invalid asymmetric key type for this operation")}},Xe=jo;var Ma=(0,Ut.promisify)(Ee.generateKeyPair);var $t=require("util"),qe=require("crypto");var Za=(0,$t.promisify)(qe.pbkdf2);var ae=require("crypto"),Bt=require("util");var be=(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 ss=(0,Bt.deprecate)(()=>ae.constants.RSA_PKCS1_PADDING,'The RSA1_5 "alg" (JWE Algorithm) is deprecated and will be removed in the next major revision.');var zo=(e,t)=>{if(!(t instanceof Uint8Array)){if(!ze(t))throw new TypeError(Ve(e,t,...f,"Uint8Array"));if(t.type!=="secret")throw new TypeError(`${f.join(" or ")} instances for symmetric algorithms must be of type "secret"`)}},Xo=(e,t,r)=>{if(!ze(t))throw new TypeError(Ve(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"`)},qo=(e,t,r)=>{e.startsWith("HS")||e==="dir"||e.startsWith("PBES2")||/^A\d{3}(?:GCM)?KW$/.test(e)?zo(e,t):Xo(e,t,r)},ce=qo;function on(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 Y=on;var dn=Symbol();var tt=T(require("crypto"),1),zt=require("util");function Ce(e){switch(e){case"PS256":case"RS256":case"ES256":case"ES256K":return"sha256";case"PS384":case"RS384":case"ES384":return"sha384";case"PS512":case"RS512":case"ES512":return"sha512";case"EdDSA":return;default:throw new m(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}var Ze=require("crypto");var pn={padding:Ze.constants.RSA_PKCS1_PSS_PADDING,saltLength:Ze.constants.RSA_PSS_SALTLEN_DIGEST},mn=new Map([["ES256","P-256"],["ES256K","secp256k1"],["ES384","P-384"],["ES512","P-521"]]);function Ae(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 be(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 be(t,e),{key:t,...pn};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=Xe(t),o=mn.get(e);if(r!==o)throw new TypeError(`Invalid key curve for the algorithm, its curve must be ${o}, got ${r}`);return{dsaEncoding:"ieee-p1363",key:t}}default:throw new m(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}var ve=T(require("crypto"),1),Vt=require("util");function Qe(e){switch(e){case"HS256":return"sha256";case"HS384":return"sha384";case"HS512":return"sha512";default:throw new m(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}var de=require("crypto");function Pe(e,t,r){if(t instanceof Uint8Array){if(!e.startsWith("HS"))throw new TypeError(x(t,...f));return(0,de.createSecretKey)(t)}if(t instanceof de.KeyObject)return t;if(E(t))return Wt(t,e,r),de.KeyObject.from(t);throw new TypeError(x(t,...f,"Uint8Array"))}var ln=(0,Vt.promisify)(ve.sign),un=async(e,t,r)=>{let o=Pe(e,t,"sign");if(e.startsWith("HS")){let n=ve.createHmac(Qe(e),o);return n.update(r),n.digest()}return ln(Ce(e),r,Ae(e,o))},et=un;var Gd=(0,zt.promisify)(tt.verify);var U=e=>Math.floor(e.getTime()/1e3);var hn=/^(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)$/i,xe=e=>{let t=hn.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 Z=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 P("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");if(!q(this._protectedHeader,this._unprotectedHeader))throw new P("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let o={...this._protectedHeader,...this._unprotectedHeader},n=Y(P,new Map([["b64",!0]]),r?.crit,this._protectedHeader,o),a=!0;if(n.has("b64")&&(a=this._protectedHeader.b64,typeof a!="boolean"))throw new P('The "b64" (base64url-encode payload) Header Parameter must be a boolean');let{alg:s}=o;if(typeof s!="string"||!s)throw new P('JWS "alg" (Algorithm) Header Parameter missing or invalid');ce(s,t,"sign");let c=this._payload;a&&(c=C.encode(A(c)));let p;this._protectedHeader?p=C.encode(A(JSON.stringify(this._protectedHeader))):p=C.encode("");let g=K(p,C.encode("."),c),b=await et(s,t,g),k={signature:A(b),payload:""};return a&&(k.payload=S.decode(c)),this._unprotectedHeader&&(k.header=this._unprotectedHeader),this._protectedHeader&&(k.protected=S.decode(p)),k}};var pe=class{constructor(t){l(this,"_flattened");this._flattened=new Z(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 Q(e,t){if(!Number.isFinite(t))throw new TypeError(`Invalid ${e} input`);return t}var ee=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:Q("setNotBefore",t)}:t instanceof Date?this._payload={...this._payload,nbf:Q("setNotBefore",U(t))}:this._payload={...this._payload,nbf:U(new Date)+xe(t)},this}setExpirationTime(t){return typeof t=="number"?this._payload={...this._payload,exp:Q("setExpirationTime",t)}:t instanceof Date?this._payload={...this._payload,exp:Q("setExpirationTime",U(t))}:this._payload={...this._payload,exp:U(new Date)+xe(t)},this}setIssuedAt(t){return typeof t>"u"?this._payload={...this._payload,iat:U(new Date)}:t instanceof Date?this._payload={...this._payload,iat:Q("setIssuedAt",U(t))}:this._payload={...this._payload,iat:Q("setIssuedAt",t)},this}};var me=class extends ee{constructor(){super(...arguments);l(this,"_protectedHeader")}setProtectedHeader(r){return this._protectedHeader=r,this}async sign(r,o){let n=new pe(C.encode(JSON.stringify(this._payload)));if(n.setProtectedHeader(this._protectedHeader),Array.isArray(this._protectedHeader?.crit)&&this._protectedHeader.crit.includes("b64")&&this._protectedHeader.b64===!1)throw new J("JWTs MUST NOT use unencoded payload");return n.sign(r,o)}};var Cn;(typeof navigator>"u"||!navigator.userAgent?.startsWith?.("Mozilla/5.0 "))&&(Cn="jose/v5.1.3");var rt=require("crypto"),Yt=require("util");var tl=(0,Yt.promisify)(rt.generateKeyPair);var L=require("path"),Zt=T(require("tar"));function W(e){console.log(JSON.stringify(e,null,2))}async function ot(e,t,r){let o=t.source,n=at(o);if(n)try{console.log("Saving source code...");let a=await e.createAttachment(n,(0,L.basename)(o),_n(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 nt(e,t,r){let o=t.dist??t.source,n=at(o);if(n)try{console.log("Deploying bot...");let a=await e.post(e.fhirUrl("Bot",r.id,"$deploy"),{code:n,filename:(0,L.basename)(o)});console.log("Deploy result: "+a.issue?.[0]?.details?.text)}catch(a){console.log("Deploy error: ",a)}}async function it(e,t,r,o,n,a,s){try{let c={name:t,description:"",runtimeVersion:a},p=await e.post("admin/projects/"+r+"/bot",c),g=await e.readResource("Bot",p.id),b={name:t,id:p.id,source:o,dist:n};await ot(e,b,g),await nt(e,b,g),console.log(`Success! Bot created: ${g.id}`),s&&vn(b)}catch(c){console.log("Error while creating new bot: "+c)}}function Qt(e){let t=new RegExp("^"+xn(e).replace(/\\\*/g,".*")+"$"),r=re()?.bots?.filter(o=>t.test(o.name));return r||[]}function re(e){let t=e?`medplum.${e}.config.json`:"medplum.config.json",r=at(t);if(r)return JSON.parse(r)}function at(e){let t=(0,L.resolve)(process.cwd(),e);return(0,V.existsSync)(t)?(0,V.readFileSync)(t,"utf8"):""}function vn(e){let t=re()??{};t.bots||(t.bots=[]),t.bots.push(e),(0,V.writeFileSync)("medplum.config.json",JSON.stringify(t,null,2),"utf8"),console.log(`Bot added to config: ${e.id}`)}function xn(e){return e.replace(/[/\-\\^$*+?.()|[\]{}]/g,"\\$&")}function er(e){let o=0,n=0;return Zt.default.x({cwd:e,filter:(a,s)=>{if(o++,o>100)throw new Error("Tar extractor reached max number of files");if(n+=s.size,n>10485760)throw new Error("Tar extractor reached max size");return!0}})}function st(){return{extension:[{url:"http://hl7.org/fhir/StructureDefinition/data-absent-reason",valueCode:"unsupported"}]}}function _n(e){let t=(0,L.extname)(e).toLowerCase();return[".cjs",".mjs",".js"].includes(t)?G.ContentType.JAVASCRIPT:[".cts",".mts",".ts"].includes(t)?G.ContentType.TYPESCRIPT:G.ContentType.TEXT}function _e(e,t){let r=new R(e),o={name:e,...t};return r.setObject("options",o),console.log(`${e} profile created`),o}function tr(e){return new R(e).getObject("options")}async function rr(e,t){let r={typ:"JWT",alg:"HS256"},o=Math.floor(Date.now()/1e3),n={aud:`${t.baseUrl}${t.audience}`,iss:t.issuer,sub:t.subject,nbf:o,iat:o,exp:o+604800},a=(0,G.encodeBase64)(JSON.stringify(r)),s=(0,G.encodeBase64)(JSON.stringify(n)),c=`${a}.${s}`,p=(0,te.createHmac)("sha256",t.clientSecret).update(c).digest("base64url"),g=`${c}.${p}`;await e.startJwtBearerLogin(t.clientId,g,t.scope??"")}async function or(e,t){let r=(0,te.createPrivateKey)((0,V.readFileSync)((0,L.resolve)(t.privateKeyPath))),o=await new me({}).setProtectedHeader({alg:"RS384",typ:"JWT"}).setIssuer(t.clientId).setSubject(t.clientId).setAudience(`${t.baseUrl}${t.audience}`).setJti((0,te.randomBytes)(16).toString("hex")).setIssuedAt().setExpirationTime("5m").sign(r);await e.startJwtAssertionLogin(o)}var sr="medplum-cli",cr="http://localhost:9615",ct=d("login"),dt=d("whoami");ct.action(async e=>{let t=e.profile??"default",r=_e(t,e),o=await u(e,!1);await In(o,r)});dt.action(async e=>{let t=await u(e);Hn(t)});async function In(e,t){switch(t?.authType??"authorization-code"){case"authorization-code":await kn(e);break;case"basic":e.setBasicAuth(t.clientId,t.clientSecret);break;case"client-credentials":e.setBasicAuth(t.clientId,t.clientSecret),await e.startClientLogin(t.clientId,t.clientSecret);break;case"jwt-bearer":await rr(e,t);break;case"jwt-assertion":await or(e,t);break}console.log("Login successful")}async function Tn(e){let t=(0,ir.createServer)(async(r,o)=>{let n=new URL(r.url,"http://localhost:9615"),a=n.searchParams.get("code");if(n.pathname==="/"&&a)try{let s=await e.processCode(a,{clientId:sr,redirectUri:cr});o.writeHead(200,{"Content-Type":$.ContentType.TEXT}),o.end(`Signed in as ${(0,$.getDisplayString)(s)}. You may close this window.`)}catch(s){o.writeHead(400,{"Content-Type":$.ContentType.TEXT}),o.end(`Error: ${(0,$.normalizeErrorString)(s)}`)}finally{t.close()}else o.writeHead(404,{"Content-Type":$.ContentType.TEXT}),o.end("Not found")}).listen(9615)}async function Kn(e){let t=(0,ar.platform)(),r;switch(t){case"openbsd":case"linux":r=`xdg-open '${e}'`;break;case"darwin":r=`open '${e}'`;break;case"win32":r=`cmd /c start "" "${e}"`;break;default:throw new Error("Unsupported platform: "+t)}(0,nr.exec)(r)}function Hn(e){let t=e.getActiveLogin();t?(console.log(`Server: ${e.getBaseUrl()}`),console.log(`Profile: ${t.profile.display} (${t.profile.reference})`),console.log(`Project: ${t.project.display} (${t.project.reference})`)):console.log("Not logged in")}async function kn(e){await Tn(e);let t=new URL(e.getAuthorizeUrl());t.searchParams.set("client_id",sr),t.searchParams.set("redirect_uri",cr),t.searchParams.set("scope","openid"),t.searchParams.set("response_type","code"),t.searchParams.set("prompt","login"),await Kn(t.toString())}var Hr=require("commander");var M=require("@aws-sdk/client-cloudformation"),Te=require("@aws-sdk/client-cloudfront"),pr=require("@aws-sdk/client-ecs"),mr=require("@aws-sdk/client-s3"),Ie=new M.CloudFormationClient({}),Rn=new Te.CloudFrontClient({region:"us-east-1"}),lr=new pr.ECSClient({}),le=new mr.S3Client({}),On="medplum:environment";async function pt(){return(await Ie.send(new M.ListStacksCommand({}))).StackSummaries?.filter(t=>t.StackName&&t.StackStatus!=="DELETE_COMPLETE")||[]}async function B(e){let t=await pt();for(let r of t){let o=r.StackName,n=await mt(o);if(n?.tag===e)return n}}async function mt(e){let t={};return await dr(Ie,e,t),await Ie.config.region()!=="us-east-1"&&await dr(new M.CloudFormationClient({region:"us-east-1"}),e+"-us-east-1",t),t}async function dr(e,t,r){let o=new M.DescribeStacksCommand({StackName:t}),a=(await e.send(o))?.Stacks?.[0],s=a?.Tags?.find(p=>p.Key===On);if(!s)return;let c=await e.send(new M.DescribeStackResourcesCommand({StackName:t}));if(c.StackResources){e===Ie&&(r.stack=a,r.tag=s.Value);for(let p of c.StackResources)Dn(p,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 Ke(e){console.log(`Medplum Tag: ${e.tag}`),console.log(`Stack Name: ${e.stack?.StackName}`),console.log(`Stack ID: ${e.stack?.StackId}`),console.log(`Status: ${e.stack?.StackStatus}`),console.log(`ECS Cluster: ${e.ecsCluster?.PhysicalResourceId}`),console.log(`ECS Service: ${lt(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 lt(e){return e?.PhysicalResourceId?.split("/")?.pop()||""}async function He(e){let t=await Rn.send(new Te.CreateInvalidationCommand({DistributionId:e,InvalidationBatch:{CallerReference:`invalidate-all-${Date.now()}`,Paths:{Quantity:1,Items:["/*"]}}}));console.log(`Created invalidation with ID: ${t.Invalidation?.Id}`)}async function ur(e){let t=await B(e);if(!t){console.log("Stack not found");return}Ke(t)}var z=require("@aws-sdk/client-acm"),Oe=require("@aws-sdk/client-cloudfront"),oe=require("@aws-sdk/client-ssm"),De=require("@aws-sdk/client-sts"),hr=require("@medplum/core"),fe=require("crypto"),We=require("fs"),yr=require("path"),gr=T(require("readline")),Wn=e=>`${e}DomainName`,wr=e=>`${e}SslCertArn`,ke;async function Sr(){let e={apiPort:8103,region:"us-east-1"};ke=gr.default.createInterface({input:process.stdin,output:process.stdout}),h("MEDPLUM"),i("This tool prepares the necessary prerequisites for deploying Medplum in your AWS account."),i(""),i("Most Medplum infrastructure is deployed using the AWS CDK."),i("However, some AWS resources must be created manually, such as email addresses and SSL certificates."),i("This tool will help you create those resources."),i(""),i("Upon completion, this tool will:"),i(" 1. Generate a Medplum CDK config file (i.e., medplum.demo.config.json)"),i(" 2. Optionally generate an AWS CloudFront signing key"),i(" 3. Optionally request SSL certificates from AWS Certificate Manager"),i(" 4. Optionally write server config settings to AWS Parameter Store"),i(""),i("The Medplum infra config file is an input to the Medplum CDK."),i("The Medplum CDK will create and manage the necessary AWS resources."),i(""),i("We will ask a series of questions to generate your infra config file."),i("Some questions have predefined options in [square brackets]."),i("Some questions have default values in (parentheses), which you can accept by pressing Enter."),i("Press Ctrl+C at any time to exit.");let t=await Mn(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 ut("Do you want to continue without AWS credentials?")),h("ENVIRONMENT NAME"),i('Medplum deployments have a short environment name such as "prod", "staging", "alice", or "demo".'),i("The environment name is used in multiple places:"),i(" 1. As part of config file names (i.e., medplum.demo.config.json)"),i(" 2. As the base of CloudFormation stack names (i.e., MedplumDemo)"),i(" 3. AWS Parameter Store keys (i.e., /medplum/demo/...)"),e.name=await _("What is your environment name?","demo"),i('Using environment name "'+e.name+'"...'),h("CONFIG FILE"),i("Medplum Infrastructure will create a config file in the current directory.");let r=await _("What is the config file name?",`medplum.${e.name}.config.json`);(0,We.existsSync)(r)&&(i("Config file already exists."),await ut("Do you want to overwrite the config file?")),i('Using config file "'+r+'"...'),y(r,e),h("AWS REGION"),i("Most Medplum resources will be created in a single AWS region."),e.region=await _("Enter your AWS region:","us-east-1"),y(r,e),h("AWS ACCOUNT NUMBER"),i("Medplum Infrastructure will use your AWS account number to create AWS resources."),t&&i("Using the AWS CLI, your current account ID is: "+t),e.accountNumber=await _("What is your AWS account number?",t),y(r,e),h("STACK NAME"),i("Medplum will create a CloudFormation stack to manage AWS resources."),i("AWS CloudFormation stack names ");let o="Medplum"+e.name.charAt(0).toUpperCase()+e.name.slice(1);for(e.stackName=await _("Enter your CloudFormation stack name?",o),y(r,e),h("BASE DOMAIN NAME"),i("Please enter the base domain name for your Medplum deployment."),i(""),i("Medplum deploys multiple subdomains for various services."),i(""),i('For example, "api." for the REST API and "app." for the web application.'),i("The base domain name is the common suffix for all subdomains."),i(""),i('For example, if your base domain name is "example.com",'),i('then the REST API will be "api.example.com".'),i(""),i('The base domain should include the TLD (i.e., ".com", ".org", ".net").'),i(""),i("Note that you must own the base domain, and it must use Route53 DNS.");!e.domainName;)e.domainName=await _("Enter your base domain name:");y(r,e),h("SUPPORT EMAIL"),i("Medplum sends transactional emails to users."),i("For example, emails to new users or for password reset."),i("Medplum will use the support email address to send these emails."),i("Note that you must verify the support email address in SES.");let n=await _("Enter your support email address:");h("API DOMAIN NAME"),i("Medplum deploys a REST API for the backend services."),e.apiDomainName=await _("Enter your REST API domain name:","api."+e.domainName),e.baseUrl=`https://${e.apiDomainName}/`,y(r,e),h("APP DOMAIN NAME"),i("Medplum deploys a web application for the user interface."),e.appDomainName=await _("Enter your web application domain name:","app."+e.domainName),y(r,e),h("STORAGE DOMAIN NAME"),i("Medplum deploys a storage service for file uploads."),e.storageDomainName=await _("Enter your storage domain name:","storage."+e.domainName),y(r,e),h("STORAGE BUCKET"),i("Medplum uses an S3 bucket to store binary content such as file uploads."),i("Medplum will create a the S3 bucket as part of the CloudFormation stack."),e.storageBucketName=await _("Enter your storage bucket name:",e.storageDomainName),y(r,e),h("MAX AVAILABILITY ZONES"),i("Medplum API servers can be deployed in multiple availability zones."),i("This provides redundancy and high availability."),i("However, it also increases the cost of the deployment."),i("If you want to use all availability zones, choose a large number such as 99."),i("If you want to restrict the number, for example to manage EIP limits,"),i("then choose a small number such as 2 or 3."),e.maxAzs=await ue("Enter the maximum number of availability zones:",[2,3,99],2),h("DATABASE INSTANCES"),i("Medplum uses a relational database to store data."),i("You can set up your own database,"),i("or Medplum can create a new RDS database as part of the CloudFormation stack."),await Re("Do you want to create a new RDS database as part of the CloudFormation stack?")?(i("Medplum will create a new RDS database as part of the CloudFormation stack."),i(""),i("If you need high availability, you can choose multiple instances."),i("Use 1 for a single instance, or 2 for a primary and a standby."),e.rdsInstances=await ue("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 ue("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 ue("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 ue("Enter the server CPU:",[256,512,1024,2048,4096,8192,16384],256),y(r,e),h("SERVER IMAGE"),i("Medplum uses Docker images for the API servers."),i("You can choose the image to use for the servers."),i("Docker images can be loaded from either Docker Hub or AWS ECR."),i("The default is the latest Medplum release."),e.serverImage=await _("Enter the server image:","medplum/medplum-server:latest"),y(r,e),h("SIGNING KEY"),i("Medplum uses AWS CloudFront Presigned URLs for binary content such as file uploads.");let a=await Ln(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 Jn(e.region);i("Found "+s.length+" certificate(s).");for(let{region:p,certName:g}of[{region:e.region,certName:"api"},{region:"us-east-1",certName:"app"},{region:"us-east-1",certName:"storage"}]){i("");let b=await Nn(e,s,p,g);e[wr(g)]=b,y(r,e)}h("AWS PARAMETER STORE"),i("Medplum uses AWS Parameter Store to store sensitive configuration values."),i("These values will be encrypted at rest."),i(`The values will be stored in the "/medplum/${e.name}" path.`);let c={port:e.apiPort,baseUrl:e.baseUrl,appBaseUrl:`https://${e.appDomainName}/`,storageBaseUrl:`https://${e.storageDomainName}/binary/`,binaryStorage:`s3:${e.storageBucketName}`,supportEmail:n};if(a&&(c.signingKeyId=a.keyId,c.signingKey=a.privateKey,c.signingKeyPassphrase=a.passphrase),i(JSON.stringify({...c,signingKey:"****",signingKeyPassphrase:"****"},null,2)),await Re("Do you want to store these values in AWS Parameter Store?"))await Fn(e.region,`/medplum/${e.name}/`,c);else{let p=r.replace(".json",".server.json");y(p,c),i("Skipping AWS Parameter Store."),i("Writing values to local config file: "+p),i("Please add these values to AWS Parameter Store manually.")}h("DONE!"),i("Medplum configuration complete."),i("You can now proceed to deploying the Medplum infrastructure with CDK."),i("Run:"),i(""),i(` npx cdk bootstrap -c config=${r}`),i(` npx cdk synth -c config=${r}`),e.region==="us-east-1"?i(` npx cdk deploy -c config=${r}`):i(` npx cdk deploy -c config=${r} --all`),i(""),i("See Medplum documentation for more information:"),i(""),i(" https://www.medplum.com/docs/self-hosting/install-on-aws"),i(""),ke.close()}function i(e){ke.write(e+`
|
|
2
|
+
"use strict";var bo=Object.create;var ne=Object.defineProperty;var Co=Object.getOwnPropertyDescriptor;var Ao=Object.getOwnPropertyNames;var Po=Object.getPrototypeOf,vo=Object.prototype.hasOwnProperty;var xo=(e,t,r)=>t in e?ne(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;var _o=(e,t)=>{for(var r in t)ne(e,r,{get:t[r],enumerable:!0})},vt=(e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of Ao(t))!vo.call(e,n)&&n!==r&&ne(e,n,{get:()=>t[n],enumerable:!(o=Co(t,n))||o.enumerable});return e};var T=(e,t,r)=>(r=e!=null?bo(Po(e)):{},vt(t||!e||!e.__esModule?ne(r,"default",{value:e,enumerable:!0}):r,e)),Io=e=>vt(ne({},"__esModule",{value:!0}),e);var f=(e,t,r)=>(xo(e,typeof t!="symbol"?t+"":t,r),r);var mi={};_o(mi,{main:()=>So,run:()=>Eo});module.exports=Io(mi);var $e=require("@medplum/core"),go=require("commander"),wo=T(require("dotenv"));var $=require("@medplum/core"),or=require("child_process"),nr=require("http"),ir=require("os");var It=require("@medplum/core");var xt=require("@medplum/core"),O=require("fs"),_t=require("os"),Be=require("path"),R=class extends xt.ClientStorage{constructor(t){super(),this.dirName=(0,Be.resolve)((0,_t.homedir)(),".medplum"),this.fileName=(0,Be.resolve)(this.dirName,t+".json")}clear(){this.writeFile({})}getString(t){return this.readFile()?.[t]}setString(t,r){let o=this.readFile()??{};r?o[t]=r:delete o[t],this.writeFile(o)}getObject(t){let r=this.getString(t);return r?JSON.parse(r):void 0}setObject(t,r){this.setString(t,r?JSON.stringify(r):void 0)}readFile(){if((0,O.existsSync)(this.fileName))return JSON.parse((0,O.readFileSync)(this.fileName,"utf8"))}writeFile(t){(0,O.existsSync)(this.dirName)||(0,O.mkdirSync)(this.dirName),(0,O.writeFileSync)(this.fileName,JSON.stringify(t,null,2),"utf8")}};async function l(e,t=!0){let r=e.profile??"default",o=new R(r),n=o.getObject("options");if(r!=="default"&&!n)throw new Error(`Profile "${r}" does not exist`);let{baseUrl:a,fhirUrlPath:s,accessToken:c,tokenUrl:p,authorizeUrl:g,clientId:b,clientSecret:k}=To(e,o),ge=e.fetch??fetch,we=new It.MedplumClient({fetch:ge,baseUrl:a,tokenUrl:p,fhirUrlPath:s,authorizeUrl:g,storage:o,onUnauthenticated:Ko,verbose:e.verbose});return t&&(c?we.setAccessToken(c):b&&k&&(we.setBasicAuth(b,k),n?.authType!=="basic"&&await we.startClientLogin(b,k))),we}function To(e,t){let r=t.getObject("options"),o=e.baseUrl??r?.baseUrl??process.env.MEDPLUM_BASE_URL??"https://api.medplum.com/",n=e.fhirUrlPath??r?.fhirUrlPath??process.env.MEDPLUM_FHIR_URL_PATH,a=e.accessToken??r?.accessToken??process.env.MEDPLUM_CLIENT_ACCESS_TOKEN,s=e.tokenUrl??r?.tokenUrl??process.env.MEDPLUM_TOKEN_URL,c=e.authorizeUrl??r?.authorizeUrl??process.env.MEDPLUM_AUTHORIZE_URL,p=e.clientId??r?.clientId??process.env.MEDPLUM_CLIENT_ID,g=e.clientSecret??r?.clientSecret??process.env.MEDPLUM_CLIENT_SECRET;return{baseUrl:o,fhirUrlPath:n,accessToken:a,tokenUrl:s,authorizeUrl:c,clientId:p,clientSecret:g}}function Ko(){console.log("Unauthenticated: run `npx medplum login` to sign in")}var Se=require("commander");function d(e){return new Se.Command(e).option("--client-id <clientId>","FHIR server client id").option("--client-secret <clientSecret>","FHIR server client secret").option("--base-url <baseUrl>","FHIR server base URL, must be absolute").option("--token-url <tokenUrl>","FHIR server token URL, absolute or relative to base URL").option("--authorize-url <authorizeUrl>","FHIR server authorize URL, absolute or relative to base URL").option("--fhir-url, --fhir-url-path <fhirUrlPath>","FHIR server URL, absolute or relative to base URL").option("--scope <scope>","JWT scope").option("--access-token <accessToken>","Access token for token exchange authentication").option("--callback-url <callbackUrl>","Callback URL for authorization code flow").option("--subject <subject>","Subject for JWT authentication").option("--audience <audience>","Audience for JWT authentication").option("--issuer <issuer>","Issuer for JWT authentication").option("--private-key-path <privateKeyPath>","Private key path for JWT assertion").option("--audience <audience>","Audience for JWT assertion").option("-p, --profile <profile>","Profile name").option("-v --verbose","Verbose output").addOption(new Se.Option("--auth-type <authType>","Type of authentication").choices(["basic","client-credentials","authorization-code","jwt-bearer","token-exchange","jwt-assertion"]))}var G=require("@medplum/core"),te=require("crypto"),V=require("fs");var Tt=require("buffer");var C=new TextEncoder,S=new TextDecoder,Ei=2**32;function K(...e){let t=e.reduce((n,{length:a})=>n+a,0),r=new Uint8Array(t),o=0;return e.forEach(n=>{r.set(n,o),o+=n.length}),r}var A=e=>Tt.Buffer.from(e).toString("base64url");var q=class extends Error{constructor(r){super(r);f(this,"code","ERR_JOSE_GENERIC");this.name=this.constructor.name,Error.captureStackTrace?.(this,this.constructor)}static get code(){return"ERR_JOSE_GENERIC"}};var m=class extends q{constructor(){super(...arguments);f(this,"code","ERR_JOSE_NOT_SUPPORTED")}static get code(){return"ERR_JOSE_NOT_SUPPORTED"}};var P=class extends q{constructor(){super(...arguments);f(this,"code","ERR_JWS_INVALID")}static get code(){return"ERR_JWS_INVALID"}},N=class extends q{constructor(){super(...arguments);f(this,"code","ERR_JWT_INVALID")}static get code(){return"ERR_JWT_INVALID"}};var Ht=T(require("util"),1),v=e=>Ht.types.isKeyObject(e);var kt=T(require("crypto"),1),Rt=T(require("util"),1),Ro=kt.webcrypto,Ot=Ro,E=e=>Rt.types.isCryptoKey(e);function D(e,t="algorithm.name"){return new TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`)}function Ee(e,t){return e.name===t}function je(e){return parseInt(e.name.slice(4),10)}function Oo(e){switch(e){case"ES256":return"P-256";case"ES384":return"P-384";case"ES512":return"P-521";default:throw new Error("unreachable")}}function Do(e,t){if(t.length&&!t.some(r=>e.usages.includes(r))){let r="CryptoKey does not support this operation, its usages must include ";if(t.length>2){let o=t.pop();r+=`one of ${t.join(", ")}, or ${o}.`}else t.length===2?r+=`one of ${t[0]} or ${t[1]}.`:r+=`${t[0]}.`;throw new TypeError(r)}}function Dt(e,t,...r){switch(t){case"HS256":case"HS384":case"HS512":{if(!Ee(e.algorithm,"HMAC"))throw D("HMAC");let o=parseInt(t.slice(2),10);if(je(e.algorithm.hash)!==o)throw D(`SHA-${o}`,"algorithm.hash");break}case"RS256":case"RS384":case"RS512":{if(!Ee(e.algorithm,"RSASSA-PKCS1-v1_5"))throw D("RSASSA-PKCS1-v1_5");let o=parseInt(t.slice(2),10);if(je(e.algorithm.hash)!==o)throw D(`SHA-${o}`,"algorithm.hash");break}case"PS256":case"PS384":case"PS512":{if(!Ee(e.algorithm,"RSA-PSS"))throw D("RSA-PSS");let o=parseInt(t.slice(2),10);if(je(e.algorithm.hash)!==o)throw D(`SHA-${o}`,"algorithm.hash");break}case"EdDSA":{if(e.algorithm.name!=="Ed25519"&&e.algorithm.name!=="Ed448")throw D("Ed25519 or Ed448");break}case"ES256":case"ES384":case"ES512":{if(!Ee(e.algorithm,"ECDSA"))throw D("ECDSA");let o=Oo(t);if(e.algorithm.namedCurve!==o)throw D(o,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}Do(e,r)}function Wt(e,t,...r){if(r.length>2){let o=r.pop();e+=`one of type ${r.join(", ")}, or ${o}.`}else r.length===2?e+=`one of type ${r[0]} or ${r[1]}.`:e+=`of type ${r[0]}.`;return t==null?e+=` Received ${t}`:typeof t=="function"&&t.name?e+=` Received function ${t.name}`:typeof t=="object"&&t!=null&&t.constructor&&t.constructor.name&&(e+=` Received an instance of ${t.constructor.name}`),e}var x=(e,...t)=>Wt("Key must be ",e,...t);function Ge(e,t,...r){return Wt(`Key for the ${e} algorithm must be `,t,...r)}var Ve=e=>v(e)||E(e),u=["KeyObject"];(globalThis.CryptoKey||Ot?.CryptoKey)&&u.push("CryptoKey");var Uo=(...e)=>{let t=e.filter(Boolean);if(t.length===0||t.length===1)return!0;let r;for(let o of t){let n=Object.keys(o);if(!r||r.size===0){r=new Set(n);continue}for(let a of n){if(r.has(a))return!1;r.add(a)}}return!0},Y=Uo;function Lo(e){return typeof e=="object"&&e!==null}function w(e){if(!Lo(e)||Object.prototype.toString.call(e)!=="[object Object]")return!1;if(Object.getPrototypeOf(e)===null)return!0;let t=e;for(;Object.getPrototypeOf(t)!==null;)t=Object.getPrototypeOf(t);return Object.getPrototypeOf(e)===t}var be=require("crypto"),Nt=require("util");var Jt=require("crypto");var $o=e=>{switch(e){case"prime256v1":return"P-256";case"secp384r1":return"P-384";case"secp521r1":return"P-521";case"secp256k1":return"secp256k1";default:throw new m("Unsupported key curve for this operation")}},Bo=(e,t)=>{let r;if(E(e))r=Jt.KeyObject.from(e);else if(v(e))r=e;else throw new TypeError(x(e,...u));if(r.type==="secret")throw new TypeError('only "private" or "public" type keys can be used for this operation');switch(r.asymmetricKeyType){case"ed25519":case"ed448":return`Ed${r.asymmetricKeyType.slice(2)}`;case"x25519":case"x448":return`X${r.asymmetricKeyType.slice(1)}`;case"ec":{let o=r.asymmetricKeyDetails.namedCurve;return t?o:$o(o)}default:throw new TypeError("Invalid asymmetric key type for this operation")}},ze=Bo;var Da=(0,Nt.promisify)(be.generateKeyPair);var Lt=require("util"),Xe=require("crypto");var qa=(0,Lt.promisify)(Xe.pbkdf2);var ae=require("crypto"),$t=require("util");var Ce=(e,t)=>{let{modulusLength:r}=e.asymmetricKeyDetails;if(typeof r!="number"||r<2048)throw new TypeError(`${t} requires key modulusLength to be 2048 bits or larger`)};var is=(0,$t.deprecate)(()=>ae.constants.RSA_PKCS1_PADDING,'The RSA1_5 "alg" (JWE Algorithm) is deprecated and will be removed in the next major revision.');var Go=(e,t)=>{if(!(t instanceof Uint8Array)){if(!Ve(t))throw new TypeError(Ge(e,t,...u,"Uint8Array"));if(t.type!=="secret")throw new TypeError(`${u.join(" or ")} instances for symmetric algorithms must be of type "secret"`)}},Vo=(e,t,r)=>{if(!Ve(t))throw new TypeError(Ge(e,t,...u));if(t.type==="secret")throw new TypeError(`${u.join(" or ")} instances for asymmetric algorithms must not be of type "secret"`);if(r==="sign"&&t.type==="public")throw new TypeError(`${u.join(" or ")} instances for asymmetric algorithm signing must be of type "private"`);if(r==="decrypt"&&t.type==="public")throw new TypeError(`${u.join(" or ")} instances for asymmetric algorithm decryption must be of type "private"`);if(t.algorithm&&r==="verify"&&t.type==="private")throw new TypeError(`${u.join(" or ")} instances for asymmetric algorithm verifying must be of type "public"`);if(t.algorithm&&r==="encrypt"&&t.type==="private")throw new TypeError(`${u.join(" or ")} instances for asymmetric algorithm encryption must be of type "public"`)},zo=(e,t,r)=>{e.startsWith("HS")||e==="dir"||e.startsWith("PBES2")||/^A\d{3}(?:GCM)?KW$/.test(e)?Go(e,t):Vo(e,t,r)},ce=zo;function tn(e,t,r,o,n){if(n.crit!==void 0&&o.crit===void 0)throw new e('"crit" (Critical) Header Parameter MUST be integrity protected');if(!o||o.crit===void 0)return new Set;if(!Array.isArray(o.crit)||o.crit.length===0||o.crit.some(s=>typeof s!="string"||s.length===0))throw new e('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');let a;r!==void 0?a=new Map([...Object.entries(r),...t.entries()]):a=t;for(let s of o.crit){if(!a.has(s))throw new m(`Extension Header Parameter "${s}" is not recognized`);if(n[s]===void 0)throw new e(`Extension Header Parameter "${s}" is missing`);if(a.get(s)&&o[s]===void 0)throw new e(`Extension Header Parameter "${s}" MUST be integrity protected`)}return new Set(o.crit)}var Z=tn;var sn=Symbol();var et=T(require("crypto"),1),Vt=require("util");function Ae(e){switch(e){case"PS256":case"RS256":case"ES256":case"ES256K":return"sha256";case"PS384":case"RS384":case"ES384":return"sha384";case"PS512":case"RS512":case"ES512":return"sha512";case"EdDSA":return;default:throw new m(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}var Ye=require("crypto");var cn={padding:Ye.constants.RSA_PKCS1_PSS_PADDING,saltLength:Ye.constants.RSA_PSS_SALTLEN_DIGEST},dn=new Map([["ES256","P-256"],["ES256K","secp256k1"],["ES384","P-384"],["ES512","P-521"]]);function Pe(e,t){switch(e){case"EdDSA":if(!["ed25519","ed448"].includes(t.asymmetricKeyType))throw new TypeError("Invalid key for this operation, its asymmetricKeyType must be ed25519 or ed448");return t;case"RS256":case"RS384":case"RS512":if(t.asymmetricKeyType!=="rsa")throw new TypeError("Invalid key for this operation, its asymmetricKeyType must be rsa");return Ce(t,e),t;case"PS256":case"PS384":case"PS512":if(t.asymmetricKeyType==="rsa-pss"){let{hashAlgorithm:r,mgf1HashAlgorithm:o,saltLength:n}=t.asymmetricKeyDetails,a=parseInt(e.slice(-3),10);if(r!==void 0&&(r!==`sha${a}`||o!==r))throw new TypeError(`Invalid key for this operation, its RSA-PSS parameters do not meet the requirements of "alg" ${e}`);if(n!==void 0&&n>a>>3)throw new TypeError(`Invalid key for this operation, its RSA-PSS parameter saltLength does not meet the requirements of "alg" ${e}`)}else if(t.asymmetricKeyType!=="rsa")throw new TypeError("Invalid key for this operation, its asymmetricKeyType must be rsa or rsa-pss");return Ce(t,e),{key:t,...cn};case"ES256":case"ES256K":case"ES384":case"ES512":{if(t.asymmetricKeyType!=="ec")throw new TypeError("Invalid key for this operation, its asymmetricKeyType must be ec");let r=ze(t),o=dn.get(e);if(r!==o)throw new TypeError(`Invalid key curve for the algorithm, its curve must be ${o}, got ${r}`);return{dsaEncoding:"ieee-p1363",key:t}}default:throw new m(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}var xe=T(require("crypto"),1),Gt=require("util");function Ze(e){switch(e){case"HS256":return"sha256";case"HS384":return"sha384";case"HS512":return"sha512";default:throw new m(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}var de=require("crypto");function ve(e,t,r){if(t instanceof Uint8Array){if(!e.startsWith("HS"))throw new TypeError(x(t,...u));return(0,de.createSecretKey)(t)}if(t instanceof de.KeyObject)return t;if(E(t))return Dt(t,e,r),de.KeyObject.from(t);throw new TypeError(x(t,...u,"Uint8Array"))}var pn=(0,Gt.promisify)(xe.sign),mn=async(e,t,r)=>{let o=ve(e,t,"sign");if(e.startsWith("HS")){let n=xe.createHmac(Ze(e),o);return n.update(r),n.digest()}return pn(Ae(e),r,Pe(e,o))},Qe=mn;var Fd=(0,Vt.promisify)(et.verify);var W=e=>Math.floor(e.getTime()/1e3);var un=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i,pe=e=>{let t=un.exec(e);if(!t||t[4]&&t[1])throw new TypeError("Invalid time period format");let r=parseFloat(t[2]),o=t[3].toLowerCase(),n;switch(o){case"sec":case"secs":case"second":case"seconds":case"s":n=Math.round(r);break;case"minute":case"minutes":case"min":case"mins":case"m":n=Math.round(r*60);break;case"hour":case"hours":case"hr":case"hrs":case"h":n=Math.round(r*3600);break;case"day":case"days":case"d":n=Math.round(r*86400);break;case"week":case"weeks":case"w":n=Math.round(r*604800);break;default:n=Math.round(r*31557600);break}return t[1]==="-"||t[4]==="ago"?-n:n};var Q=class{constructor(t){f(this,"_payload");f(this,"_protectedHeader");f(this,"_unprotectedHeader");if(!(t instanceof Uint8Array))throw new TypeError("payload must be an instance of Uint8Array");this._payload=t}setProtectedHeader(t){if(this._protectedHeader)throw new TypeError("setProtectedHeader can only be called once");return this._protectedHeader=t,this}setUnprotectedHeader(t){if(this._unprotectedHeader)throw new TypeError("setUnprotectedHeader can only be called once");return this._unprotectedHeader=t,this}async sign(t,r){if(!this._protectedHeader&&!this._unprotectedHeader)throw new P("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");if(!Y(this._protectedHeader,this._unprotectedHeader))throw new P("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let o={...this._protectedHeader,...this._unprotectedHeader},n=Z(P,new Map([["b64",!0]]),r?.crit,this._protectedHeader,o),a=!0;if(n.has("b64")&&(a=this._protectedHeader.b64,typeof a!="boolean"))throw new P('The "b64" (base64url-encode payload) Header Parameter must be a boolean');let{alg:s}=o;if(typeof s!="string"||!s)throw new P('JWS "alg" (Algorithm) Header Parameter missing or invalid');ce(s,t,"sign");let c=this._payload;a&&(c=C.encode(A(c)));let p;this._protectedHeader?p=C.encode(A(JSON.stringify(this._protectedHeader))):p=C.encode("");let g=K(p,C.encode("."),c),b=await Qe(s,t,g),k={signature:A(b),payload:""};return a&&(k.payload=S.decode(c)),this._unprotectedHeader&&(k.header=this._unprotectedHeader),this._protectedHeader&&(k.protected=S.decode(p)),k}};var me=class{constructor(t){f(this,"_flattened");this._flattened=new Q(t)}setProtectedHeader(t){return this._flattened.setProtectedHeader(t),this}async sign(t,r){let o=await this._flattened.sign(t,r);if(o.payload===void 0)throw new TypeError("use the flattened module for creating JWS with b64: false");return`${o.protected}.${o.payload}.${o.signature}`}};function j(e,t){if(!Number.isFinite(t))throw new TypeError(`Invalid ${e} input`);return t}var ee=class{constructor(t={}){f(this,"_payload");if(!w(t))throw new TypeError("JWT Claims Set MUST be an object");this._payload=t}setIssuer(t){return this._payload={...this._payload,iss:t},this}setSubject(t){return this._payload={...this._payload,sub:t},this}setAudience(t){return this._payload={...this._payload,aud:t},this}setJti(t){return this._payload={...this._payload,jti:t},this}setNotBefore(t){return typeof t=="number"?this._payload={...this._payload,nbf:j("setNotBefore",t)}:t instanceof Date?this._payload={...this._payload,nbf:j("setNotBefore",W(t))}:this._payload={...this._payload,nbf:W(new Date)+pe(t)},this}setExpirationTime(t){return typeof t=="number"?this._payload={...this._payload,exp:j("setExpirationTime",t)}:t instanceof Date?this._payload={...this._payload,exp:j("setExpirationTime",W(t))}:this._payload={...this._payload,exp:W(new Date)+pe(t)},this}setIssuedAt(t){return typeof t>"u"?this._payload={...this._payload,iat:W(new Date)}:t instanceof Date?this._payload={...this._payload,iat:j("setIssuedAt",W(t))}:typeof t=="string"?this._payload={...this._payload,iat:j("setIssuedAt",W(new Date)+pe(t))}:this._payload={...this._payload,iat:j("setIssuedAt",t)},this}};var le=class extends ee{constructor(){super(...arguments);f(this,"_protectedHeader")}setProtectedHeader(r){return this._protectedHeader=r,this}async sign(r,o){let n=new me(C.encode(JSON.stringify(this._payload)));if(n.setProtectedHeader(this._protectedHeader),Array.isArray(this._protectedHeader?.crit)&&this._protectedHeader.crit.includes("b64")&&this._protectedHeader.b64===!1)throw new N("JWTs MUST NOT use unencoded payload");return n.sign(r,o)}};var En;(typeof navigator>"u"||!navigator.userAgent?.startsWith?.("Mozilla/5.0 "))&&(En="jose/v5.2.0");var tt=require("crypto"),qt=require("util");var el=(0,qt.promisify)(tt.generateKeyPair);var L=require("path"),Yt=T(require("tar"));function M(e){console.log(JSON.stringify(e,null,2))}async function rt(e,t,r){let o=t.source,n=it(o);if(n)try{console.log("Saving source code...");let a=await e.createAttachment(n,(0,L.basename)(o),vn(o));console.log("Updating bot.....");let s=await e.updateResource({...r,sourceCode:a});console.log("Success! New bot version: "+s.meta?.versionId)}catch(a){console.log("Update error: ",a)}}async function ot(e,t,r){let o=t.dist??t.source,n=it(o);if(n)try{console.log("Deploying bot...");let a=await e.post(e.fhirUrl("Bot",r.id,"$deploy"),{code:n,filename:(0,L.basename)(o)});console.log("Deploy result: "+a.issue?.[0]?.details?.text)}catch(a){console.log("Deploy error: ",a)}}async function nt(e,t,r,o,n,a,s){try{let c={name:t,description:"",runtimeVersion:a},p=await e.post("admin/projects/"+r+"/bot",c),g=await e.readResource("Bot",p.id),b={name:t,id:p.id,source:o,dist:n};await rt(e,b,g),await ot(e,b,g),console.log(`Success! Bot created: ${g.id}`),s&&An(b)}catch(c){console.log("Error while creating new bot: "+c)}}function Zt(e){let t=new RegExp("^"+Pn(e).replace(/\\\*/g,".*")+"$"),r=re()?.bots?.filter(o=>t.test(o.name));return r||[]}function re(e){let t=e?`medplum.${e}.config.json`:"medplum.config.json",r=it(t);if(r)return JSON.parse(r)}function it(e){let t=(0,L.resolve)(process.cwd(),e);return(0,V.existsSync)(t)?(0,V.readFileSync)(t,"utf8"):""}function An(e){let t=re()??{};t.bots||(t.bots=[]),t.bots.push(e),(0,V.writeFileSync)("medplum.config.json",JSON.stringify(t,null,2),"utf8"),console.log(`Bot added to config: ${e.id}`)}function Pn(e){return e.replace(/[/\-\\^$*+?.()|[\]{}]/g,"\\$&")}function Qt(e){let o=0,n=0;return Yt.default.x({cwd:e,filter:(a,s)=>{if(o++,o>100)throw new Error("Tar extractor reached max number of files");if(n+=s.size,n>10485760)throw new Error("Tar extractor reached max size");return!0}})}function at(){return{extension:[{url:"http://hl7.org/fhir/StructureDefinition/data-absent-reason",valueCode:"unsupported"}]}}function vn(e){let t=(0,L.extname)(e).toLowerCase();return[".cjs",".mjs",".js"].includes(t)?G.ContentType.JAVASCRIPT:[".cts",".mts",".ts"].includes(t)?G.ContentType.TYPESCRIPT:G.ContentType.TEXT}function _e(e,t){let r=new R(e),o={name:e,...t};return r.setObject("options",o),console.log(`${e} profile created`),o}function er(e){return new R(e).getObject("options")}async function tr(e,t){let r={typ:"JWT",alg:"HS256"},o=Math.floor(Date.now()/1e3),n={aud:`${t.baseUrl}${t.audience}`,iss:t.issuer,sub:t.subject,nbf:o,iat:o,exp:o+604800},a=(0,G.encodeBase64)(JSON.stringify(r)),s=(0,G.encodeBase64)(JSON.stringify(n)),c=`${a}.${s}`,p=(0,te.createHmac)("sha256",t.clientSecret).update(c).digest("base64url"),g=`${c}.${p}`;await e.startJwtBearerLogin(t.clientId,g,t.scope??"")}async function rr(e,t){let r=(0,te.createPrivateKey)((0,V.readFileSync)((0,L.resolve)(t.privateKeyPath))),o=await new le({}).setProtectedHeader({alg:"RS384",typ:"JWT"}).setIssuer(t.clientId).setSubject(t.clientId).setAudience(`${t.baseUrl}${t.audience}`).setJti((0,te.randomBytes)(16).toString("hex")).setIssuedAt().setExpirationTime("5m").sign(r);await e.startJwtAssertionLogin(o)}var ar="medplum-cli",sr="http://localhost:9615",st=d("login"),ct=d("whoami");st.action(async e=>{let t=e.profile??"default",r=_e(t,e),o=await l(e,!1);await xn(o,r)});ct.action(async e=>{let t=await l(e);Tn(t)});async function xn(e,t){switch(t?.authType??"authorization-code"){case"authorization-code":await Kn(e);break;case"basic":e.setBasicAuth(t.clientId,t.clientSecret);break;case"client-credentials":e.setBasicAuth(t.clientId,t.clientSecret),await e.startClientLogin(t.clientId,t.clientSecret);break;case"jwt-bearer":await tr(e,t);break;case"jwt-assertion":await rr(e,t);break}console.log("Login successful")}async function _n(e){let t=(0,nr.createServer)(async(r,o)=>{let n=new URL(r.url,"http://localhost:9615"),a=n.searchParams.get("code");if(n.pathname==="/"&&a)try{let s=await e.processCode(a,{clientId:ar,redirectUri:sr});o.writeHead(200,{"Content-Type":$.ContentType.TEXT}),o.end(`Signed in as ${(0,$.getDisplayString)(s)}. You may close this window.`)}catch(s){o.writeHead(400,{"Content-Type":$.ContentType.TEXT}),o.end(`Error: ${(0,$.normalizeErrorString)(s)}`)}finally{t.close()}else o.writeHead(404,{"Content-Type":$.ContentType.TEXT}),o.end("Not found")}).listen(9615)}async function In(e){let t=(0,ir.platform)(),r;switch(t){case"openbsd":case"linux":r=`xdg-open '${e}'`;break;case"darwin":r=`open '${e}'`;break;case"win32":r=`cmd /c start "" "${e}"`;break;default:throw new Error("Unsupported platform: "+t)}(0,or.exec)(r)}function Tn(e){let t=e.getActiveLogin();t?(console.log(`Server: ${e.getBaseUrl()}`),console.log(`Profile: ${t.profile.display} (${t.profile.reference})`),console.log(`Project: ${t.project.display} (${t.project.reference})`)):console.log("Not logged in")}async function Kn(e){await _n(e);let t=new URL(e.getAuthorizeUrl());t.searchParams.set("client_id",ar),t.searchParams.set("redirect_uri",sr),t.searchParams.set("scope","openid"),t.searchParams.set("response_type","code"),t.searchParams.set("prompt","login"),await In(t.toString())}var Kr=require("commander");var J=require("@aws-sdk/client-cloudformation"),Te=require("@aws-sdk/client-cloudfront"),dr=require("@aws-sdk/client-ecs"),pr=require("@aws-sdk/client-s3"),Ie=new J.CloudFormationClient({}),Hn=new Te.CloudFrontClient({region:"us-east-1"}),mr=new dr.ECSClient({}),ue=new pr.S3Client({}),kn="medplum:environment";async function dt(){return(await Ie.send(new J.ListStacksCommand({}))).StackSummaries?.filter(t=>t.StackName&&t.StackStatus!=="DELETE_COMPLETE")||[]}async function B(e){let t=await dt();for(let r of t){let o=r.StackName,n=await pt(o);if(n?.tag===e)return n}}async function pt(e){let t={};return await cr(Ie,e,t),await Ie.config.region()!=="us-east-1"&&await cr(new J.CloudFormationClient({region:"us-east-1"}),e+"-us-east-1",t),t}async function cr(e,t,r){let o=new J.DescribeStacksCommand({StackName:t}),a=(await e.send(o))?.Stacks?.[0],s=a?.Tags?.find(p=>p.Key===kn);if(!s)return;let c=await e.send(new J.DescribeStackResourcesCommand({StackName:t}));if(c.StackResources){e===Ie&&(r.stack=a,r.tag=s.Value);for(let p of c.StackResources)Rn(p,r)}}function Rn(e,t){e.ResourceType==="AWS::ECS::Cluster"?t.ecsCluster=e:e.ResourceType==="AWS::ECS::Service"?t.ecsService=e:e.ResourceType==="AWS::S3::Bucket"&&e.LogicalResourceId?.startsWith("FrontEndAppBucket")?t.appBucket=e:e.ResourceType==="AWS::CloudFront::Distribution"&&e.LogicalResourceId?.startsWith("FrontEndAppDistribution")?t.appDistribution=e:e.ResourceType==="AWS::CloudFront::CloudFrontOriginAccessIdentity"&&e.LogicalResourceId?.startsWith("FrontEndOriginAccessIdentity")?t.appOriginAccessIdentity=e:e.ResourceType==="AWS::S3::Bucket"&&e.LogicalResourceId?.startsWith("StorageStorageBucket")?t.storageBucket=e:e.ResourceType==="AWS::CloudFront::Distribution"&&e.LogicalResourceId?.startsWith("StorageStorageDistribution")?t.storageDistribution=e:e.ResourceType==="AWS::CloudFront::CloudFrontOriginAccessIdentity"&&e.LogicalResourceId?.startsWith("StorageOriginAccessIdentity")&&(t.storageOriginAccessIdentity=e)}function Ke(e){console.log(`Medplum Tag: ${e.tag}`),console.log(`Stack Name: ${e.stack?.StackName}`),console.log(`Stack ID: ${e.stack?.StackId}`),console.log(`Status: ${e.stack?.StackStatus}`),console.log(`ECS Cluster: ${e.ecsCluster?.PhysicalResourceId}`),console.log(`ECS Service: ${mt(e.ecsService)}`),console.log(`App Bucket: ${e.appBucket?.PhysicalResourceId}`),console.log(`App Distribution: ${e.appDistribution?.PhysicalResourceId}`),console.log(`App OAI: ${e.appOriginAccessIdentity?.PhysicalResourceId}`),console.log(`Storage Bucket: ${e.storageBucket?.PhysicalResourceId}`),console.log(`Storage Distribution: ${e.storageDistribution?.PhysicalResourceId}`),console.log(`Storage OAI: ${e.storageOriginAccessIdentity?.PhysicalResourceId}`)}function mt(e){return e?.PhysicalResourceId?.split("/")?.pop()||""}async function He(e){let t=await Hn.send(new Te.CreateInvalidationCommand({DistributionId:e,InvalidationBatch:{CallerReference:`invalidate-all-${Date.now()}`,Paths:{Quantity:1,Items:["/*"]}}}));console.log(`Created invalidation with ID: ${t.Invalidation?.Id}`)}async function lr(e){let t=await B(e);if(!t){console.log("Stack not found");return}Ke(t)}var z=require("@aws-sdk/client-acm"),Oe=require("@aws-sdk/client-cloudfront"),oe=require("@aws-sdk/client-ssm"),De=require("@aws-sdk/client-sts"),fr=require("@medplum/core"),he=require("crypto"),We=require("fs"),hr=require("path"),yr=T(require("readline")),On=e=>`${e}DomainName`,gr=e=>`${e}SslCertArn`,ke;async function wr(){let e={apiPort:8103,region:"us-east-1"};ke=yr.default.createInterface({input:process.stdin,output:process.stdout}),h("MEDPLUM"),i("This tool prepares the necessary prerequisites for deploying Medplum in your AWS account."),i(""),i("Most Medplum infrastructure is deployed using the AWS CDK."),i("However, some AWS resources must be created manually, such as email addresses and SSL certificates."),i("This tool will help you create those resources."),i(""),i("Upon completion, this tool will:"),i(" 1. Generate a Medplum CDK config file (i.e., medplum.demo.config.json)"),i(" 2. Optionally generate an AWS CloudFront signing key"),i(" 3. Optionally request SSL certificates from AWS Certificate Manager"),i(" 4. Optionally write server config settings to AWS Parameter Store"),i(""),i("The Medplum infra config file is an input to the Medplum CDK."),i("The Medplum CDK will create and manage the necessary AWS resources."),i(""),i("We will ask a series of questions to generate your infra config file."),i("Some questions have predefined options in [square brackets]."),i("Some questions have default values in (parentheses), which you can accept by pressing Enter."),i("Press Ctrl+C at any time to exit.");let t=await Dn(e.region);t||(i("It appears that you do not have AWS credentials configured."),i("AWS credentials are not strictly required, but will enable some additional features."),i("If you intend to use AWS credentials, please configure them now."),await lt("Do you want to continue without AWS credentials?")),h("ENVIRONMENT NAME"),i('Medplum deployments have a short environment name such as "prod", "staging", "alice", or "demo".'),i("The environment name is used in multiple places:"),i(" 1. As part of config file names (i.e., medplum.demo.config.json)"),i(" 2. As the base of CloudFormation stack names (i.e., MedplumDemo)"),i(" 3. AWS Parameter Store keys (i.e., /medplum/demo/...)"),e.name=await _("What is your environment name?","demo"),i('Using environment name "'+e.name+'"...'),h("CONFIG FILE"),i("Medplum Infrastructure will create a config file in the current directory.");let r=await _("What is the config file name?",`medplum.${e.name}.config.json`);(0,We.existsSync)(r)&&(i("Config file already exists."),await lt("Do you want to overwrite the config file?")),i('Using config file "'+r+'"...'),y(r,e),h("AWS REGION"),i("Most Medplum resources will be created in a single AWS region."),e.region=await _("Enter your AWS region:","us-east-1"),y(r,e),h("AWS ACCOUNT NUMBER"),i("Medplum Infrastructure will use your AWS account number to create AWS resources."),t&&i("Using the AWS CLI, your current account ID is: "+t),e.accountNumber=await _("What is your AWS account number?",t),y(r,e),h("STACK NAME"),i("Medplum will create a CloudFormation stack to manage AWS resources."),i("AWS CloudFormation stack names ");let o="Medplum"+e.name.charAt(0).toUpperCase()+e.name.slice(1);for(e.stackName=await _("Enter your CloudFormation stack name?",o),y(r,e),h("BASE DOMAIN NAME"),i("Please enter the base domain name for your Medplum deployment."),i(""),i("Medplum deploys multiple subdomains for various services."),i(""),i('For example, "api." for the REST API and "app." for the web application.'),i("The base domain name is the common suffix for all subdomains."),i(""),i('For example, if your base domain name is "example.com",'),i('then the REST API will be "api.example.com".'),i(""),i('The base domain should include the TLD (i.e., ".com", ".org", ".net").'),i(""),i("Note that you must own the base domain, and it must use Route53 DNS.");!e.domainName;)e.domainName=await _("Enter your base domain name:");y(r,e),h("SUPPORT EMAIL"),i("Medplum sends transactional emails to users."),i("For example, emails to new users or for password reset."),i("Medplum will use the support email address to send these emails."),i("Note that you must verify the support email address in SES.");let n=await _("Enter your support email address:");h("API DOMAIN NAME"),i("Medplum deploys a REST API for the backend services."),e.apiDomainName=await _("Enter your REST API domain name:","api."+e.domainName),e.baseUrl=`https://${e.apiDomainName}/`,y(r,e),h("APP DOMAIN NAME"),i("Medplum deploys a web application for the user interface."),e.appDomainName=await _("Enter your web application domain name:","app."+e.domainName),y(r,e),h("STORAGE DOMAIN NAME"),i("Medplum deploys a storage service for file uploads."),e.storageDomainName=await _("Enter your storage domain name:","storage."+e.domainName),y(r,e),h("STORAGE BUCKET"),i("Medplum uses an S3 bucket to store binary content such as file uploads."),i("Medplum will create a the S3 bucket as part of the CloudFormation stack."),e.storageBucketName=await _("Enter your storage bucket name:",e.storageDomainName),y(r,e),h("MAX AVAILABILITY ZONES"),i("Medplum API servers can be deployed in multiple availability zones."),i("This provides redundancy and high availability."),i("However, it also increases the cost of the deployment."),i("If you want to use all availability zones, choose a large number such as 99."),i("If you want to restrict the number, for example to manage EIP limits,"),i("then choose a small number such as 2 or 3."),e.maxAzs=await fe("Enter the maximum number of availability zones:",[2,3,99],2),h("DATABASE INSTANCES"),i("Medplum uses a relational database to store data."),i("You can set up your own database,"),i("or Medplum can create a new RDS database as part of the CloudFormation stack."),await Re("Do you want to create a new RDS database as part of the CloudFormation stack?")?(i("Medplum will create a new RDS database as part of the CloudFormation stack."),i(""),i("If you need high availability, you can choose multiple instances."),i("Use 1 for a single instance, or 2 for a primary and a standby."),e.rdsInstances=await fe("Enter the number of database instances:",[1,2],1)):(i("Medplum will not create a new RDS database."),i("Please create a new RDS database and enter the database name, username, and password."),i('Set the AWS Secrets Manager secret ARN in the config file in the "rdsSecretsArn" setting.'),e.rdsSecretsArn="TODO"),y(r,e),h("SERVER INSTANCES"),i("Medplum uses AWS Fargate to run the API servers."),i("Medplum will create a new Fargate cluster as part of the CloudFormation stack."),i("Fargate will automatically scale the number of servers up and down."),i("If you need high availability, you can choose multiple instances."),e.desiredServerCount=await fe("Enter the number of server instances:",[1,2,3,4,6,8],1),y(r,e),h("SERVER MEMORY"),i("You can choose the amount of memory for each server instance."),i("The default is 512 MB, which is sufficient for getting started."),i("Note that only certain CPU units are compatible with memory units."),i('Consult AWS Fargate "Task Definition Parameters" for more information.'),e.serverMemory=await fe("Enter the server memory (MB):",[512,1024,2048,4096,8192,16384],512),y(r,e),h("SERVER CPU"),i("You can choose the amount of CPU for each server instance."),i("CPU is expressed as an integer using AWS CPU units"),i("The default is 256, which is sufficient for getting started."),i("Note that only certain CPU units are compatible with memory units."),i('Consult AWS Fargate "Task Definition Parameters" for more information.'),e.serverCpu=await fe("Enter the server CPU:",[256,512,1024,2048,4096,8192,16384],256),y(r,e),h("SERVER IMAGE"),i("Medplum uses Docker images for the API servers."),i("You can choose the image to use for the servers."),i("Docker images can be loaded from either Docker Hub or AWS ECR."),i("The default is the latest Medplum release."),e.serverImage=await _("Enter the server image:","medplum/medplum-server:latest"),y(r,e),h("SIGNING KEY"),i("Medplum uses AWS CloudFront Presigned URLs for binary content such as file uploads.");let a=await Nn(e.stackName+"SigningKey");a?(e.signingKeyId=a.keyId,e.storagePublicKey=a.publicKey,y(r,e)):(i("Unable to generate signing key."),i("Please manually create a signing key and enter the key ID and public key in the config file."),i('You must set the "signingKeyId", "signingKey", and "signingKeyPassphrase" settings.')),h("SSL CERTIFICATES"),i("Medplum will now check for existing SSL certificates for the subdomains.");let s=await Wn(e.region);i("Found "+s.length+" certificate(s).");for(let{region:p,certName:g}of[{region:e.region,certName:"api"},{region:"us-east-1",certName:"app"},{region:"us-east-1",certName:"storage"}]){i("");let b=await Mn(e,s,p,g);e[gr(g)]=b,y(r,e)}h("AWS PARAMETER STORE"),i("Medplum uses AWS Parameter Store to store sensitive configuration values."),i("These values will be encrypted at rest."),i(`The values will be stored in the "/medplum/${e.name}" path.`);let c={port:e.apiPort,baseUrl:e.baseUrl,appBaseUrl:`https://${e.appDomainName}/`,storageBaseUrl:`https://${e.storageDomainName}/binary/`,binaryStorage:`s3:${e.storageBucketName}`,supportEmail:n};if(a&&(c.signingKeyId=a.keyId,c.signingKey=a.privateKey,c.signingKeyPassphrase=a.passphrase),i(JSON.stringify({...c,signingKey:"****",signingKeyPassphrase:"****"},null,2)),await Re("Do you want to store these values in AWS Parameter Store?"))await $n(e.region,`/medplum/${e.name}/`,c);else{let p=r.replace(".json",".server.json");y(p,c),i("Skipping AWS Parameter Store."),i("Writing values to local config file: "+p),i("Please add these values to AWS Parameter Store manually.")}h("DONE!"),i("Medplum configuration complete."),i("You can now proceed to deploying the Medplum infrastructure with CDK."),i("Run:"),i(""),i(` npx cdk bootstrap -c config=${r}`),i(` npx cdk synth -c config=${r}`),e.region==="us-east-1"?i(` npx cdk deploy -c config=${r}`):i(` npx cdk deploy -c config=${r} --all`),i(""),i("See Medplum documentation for more information:"),i(""),i(" https://www.medplum.com/docs/self-hosting/install-on-aws"),i(""),ke.close()}function i(e){ke.write(e+`
|
|
3
3
|
`)}function h(e){i(`
|
|
4
4
|
`+e+`
|
|
5
|
-
`)}function _(e,t=""){return new Promise(r=>{ke.question(e+(t?" ("+t+")":"")+" ",o=>{r(o||t.toString())})})}async function ft(e,t,r=""){let o=e+" ["+t.map(n=>n===r?"("+n+")":n).join("|")+"]";for(;;){let n=await _(o)||r;if(t.includes(n))return n;i("Please choose one of the following options: "+t.join(", "))}}async function ue(e,t,r){return parseInt(await ft(e,t.map(o=>o.toString()),r.toString()),10)}async function Re(e){return(await ft(e,["y","n"])).toLowerCase()==="y"}async function ut(e){if(!await Re(e))throw i("Exiting..."),new Error("User cancelled")}function y(e,t){(0,We.writeFileSync)((0,yr.resolve)(e),JSON.stringify(t,void 0,2),"utf-8")}async function Mn(e){try{let t=new De.STSClient({region:e}),r=new De.GetCallerIdentityCommand({});return(await t.send(r)).Account}catch(t){console.log("Warning: Unable to get AWS account ID",t.message);return}}async function Jn(e){let t=await fr(e);if(e!=="us-east-1"){let r=await fr("us-east-1");t.push(...r)}return t}async function fr(e){try{let t=new z.ACMClient({region:e}),r=new z.ListCertificatesCommand({MaxItems:1e3});return(await t.send(r)).CertificateSummaryList}catch(t){return console.log("Warning: Unable to list certificates",t.message),[]}}async function Nn(e,t,r,o){let n=e[Wn(o)],a=t.find(c=>c.CertificateArn?.includes(r)&&c.DomainName===n);if(a)return i(`Found existing certificate for "${n}" in "${r}.`),a.CertificateArn;if(i(`No existing certificate found for "${n}" in "${r}.`),!await Re("Do you want to request a new certificate?"))return i(`Please add your certificate ARN to the config file in the "${wr(o)}" setting.`),"TODO";let s=await Un(r,n);return i("Certificate ARN: "+s),s}async function Un(e,t){try{let r=await ft("Validate certificate using DNS or email validation?",["dns","email"],"dns"),o=new z.ACMClient({region:e}),n=new z.RequestCertificateCommand({DomainName:t,ValidationMethod:r.toUpperCase()});return(await o.send(n)).CertificateArn}catch(r){return console.log("Error: Unable to request certificate",r.message),"TODO"}}async function Ln(e){let t=(0,fe.randomUUID)(),r=(0,fe.generateKeyPairSync)("rsa",{modulusLength:2048,publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs1",format:"pem",cipher:"aes-256-cbc",passphrase:t}});try{return{keyId:(await new Oe.CloudFrontClient({}).send(new Oe.CreatePublicKeyCommand({PublicKeyConfig:{Name:e,CallerReference:(0,fe.randomUUID)(),EncodedKey:r.publicKey}}))).PublicKey?.Id,publicKey:r.publicKey,privateKey:r.privateKey,passphrase:t}}catch(o){console.log("Error: Unable to create signing key: ",(0,hr.normalizeErrorString)(o));return}}async function $n(e,t){let r=new oe.GetParameterCommand({Name:t,WithDecryption:!0});try{return(await e.send(r)).Parameter?.Value}catch(o){if(o.name==="ParameterNotFound")return;throw o}}async function Bn(e,t,r){let o=new oe.PutParameterCommand({Name:t,Value:r,Type:"SecureString",Overwrite:!0});await e.send(o)}async function Fn(e,t,r){let o=new oe.SSMClient({region:e});for(let[n,a]of Object.entries(r)){let s=t+n,c=a.toString(),p=await $n(o,s);p!==void 0&&p!==c&&(i(`Parameter "${s}" exists with different value.`),await ut(`Do you want to overwrite "${s}"?`)),await Bn(o,s,c)}}async function Er(){let e=await pt();for(let t of e){let r=t.StackName,o=await mt(r);o&&(Ke(o),console.log(""))}}var br=require("@aws-sdk/client-s3"),H=require("@medplum/core"),Cr=T(require("fast-glob")),I=require("fs"),ht=T(require("node-fetch")),Ar=require("os"),X=require("path"),Pr=require("stream/promises");async function vr(e,t){let r=re(e);if(!r){console.log("Config not found");return}let o=await B(e);if(!o){console.log("Stack not found");return}let n=o.appBucket;if(!n){console.log("App bucket not found");return}let a=await Gn("@medplum/app","latest");xr(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 He(o.appDistribution.PhysicalResourceId),console.log("Done")}async function jn(e,t){let r=`https://registry.npmjs.org/${e}/${t}`;return(await(0,ht.default)(r)).json()}async function Gn(e,t){let o=(await jn(e,t)).dist.tarball,n=(0,I.mkdtempSync)((0,X.join)((0,Ar.tmpdir)(),"tarball-"));try{let a=await(0,ht.default)(o),s=er(n);return await(0,Pr.pipeline)(a.body,s),(0,X.join)(n,"package","dist")}catch(a){throw(0,I.rmSync)(n,{recursive:!0,force:!0}),a}}function xr(e,t){for(let r of(0,I.readdirSync)(e,{withFileTypes:!0})){let o=(0,X.join)(e,r.name);r.isDirectory()?xr(o,t):r.isFile()&&o.endsWith(".js")&&Vn(o,t)}}function Vn(e,t){let r=(0,I.readFileSync)(e,"utf-8");for(let[o,n]of Object.entries(t))r=r.replaceAll(`__${o}__`,n);(0,I.writeFileSync)(e,r)}async function zn(e,t,r){let o=[["assets/**/*.css",H.ContentType.CSS,!0],["assets/**/*.css.map",H.ContentType.JSON,!0],["assets/**/*.js",H.ContentType.JAVASCRIPT,!0],["assets/**/*.js.map",H.ContentType.JSON,!0],["assets/**/*.txt",H.ContentType.TEXT,!0],["assets/**/*.ico",H.ContentType.FAVICON,!0],["img/**/*.png",H.ContentType.PNG,!0],["img/**/*.svg",H.ContentType.SVG,!0],["robots.txt",H.ContentType.TEXT,!0],["index.html",H.ContentType.HTML,!1]];for(let n of o)await Xn({rootDir:e,bucketName:t,fileNamePattern:n[0],contentType:n[1],cached:n[2],dryrun:r.dryrun})}async function Xn(e){let t=Cr.default.sync(e.fileNamePattern,{cwd:e.rootDir});for(let r of t)await qn((0,X.join)(e.rootDir,r),e)}async function qn(e,t){let r=(0,I.createReadStream)(e),o=e.substring(t.rootDir.length+1).split(X.sep).join("/"),n={Bucket:t.bucketName,Key:o,Body:r,ContentType:t.contentType,CacheControl:t.cached?"public, max-age=31536000":"no-cache, no-store, must-revalidate"};console.log(`Uploading ${o} to ${t.bucketName}...`),t.dryrun||await le.send(new br.PutObjectCommand(n))}var Me=require("@aws-sdk/client-s3");async function Ir(e,t){if(!re(e)){console.log("Config not found");return}let o=await B(e);if(!o){console.log("Stack not found");return}await _r("App",o.appBucket,o.appDistribution,o.appOriginAccessIdentity,t),await _r("Storage",o.storageBucket,o.storageDistribution,o.storageOriginAccessIdentity,t),console.log("Done")}async function _r(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 Yn(a);if(Qn(c,a,s)){console.log(`${e} bucket already has policy statement`);return}ei(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 Zn(a,c),console.log("Bucket policy updated"),console.log("Creating CloudFront invalidation..."),await He(r.PhysicalResourceId),console.log("CloudFront invalidation created"),console.log(`${e} bucket policy updated`))}async function Yn(e){let t=await le.send(new Me.GetBucketPolicyCommand({Bucket:e}));return JSON.parse(t.Policy??"{}")}async function Zn(e,t){await le.send(new Me.PutBucketPolicyCommand({Bucket:e,Policy:JSON.stringify(t)}))}function Qn(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 ei(e,t,r){e.Version||(e.Version="2012-10-17"),e.Statement||(e.Statement=[]),e.Statement.push({Effect:"Allow",Principal:{AWS:`arn:aws:iam::cloudfront:user/CloudFront Origin Access Identity ${r}`},Action:["s3:GetObject*","s3:GetBucket*","s3:List*"],Resource:[`arn:aws:s3:::${t}`,`arn:aws:s3:::${t}/*`]})}var Tr=require("@aws-sdk/client-ecs");async function Kr(e){let t=await B(e);if(!t){console.log("Stack not found");return}let r=t.ecsCluster?.PhysicalResourceId;if(!r){console.log("ECS Cluster not found");return}let o=lt(t.ecsService);if(!o){console.log("ECS Service not found");return}await lr.send(new Tr.UpdateServiceCommand({cluster:r,service:o,forceNewDeployment:!0})),console.log(`Service "${o}" updated successfully.`)}var F=new Hr.Command("aws").description("Commands to manage AWS resources");F.command("init").description("Initialize a new Medplum AWS CloudFormation stacks").action(Sr);F.command("list").description("List Medplum AWS CloudFormation stacks").action(Er);F.command("describe").description("Describe a Medplum AWS CloudFormation stack by tag").argument("<tag>").action(ur);F.command("update-server").alias("deploy-server").description("Update the server image").argument("<tag>").action(Kr);F.command("update-app").alias("deploy-app").description("Update the app site").argument("<tag>").option("--dryrun","Displays the operations that would be performed using the specified command without actually running them.").action(vr);F.command("update-bucket-policies").description("Update S3 bucket policies").argument("<tag>").option("--dryrun","Displays the operations that would be performed using the specified command without actually running them.").action(Ir);var kr=require("commander");var Rr=d("save"),Or=d("deploy"),Dr=d("create"),Wr=new kr.Command("bot").addCommand(Rr).addCommand(Or).addCommand(Dr),yt=d("save-bot"),gt=d("deploy-bot"),wt=d("create-bot");Rr.description("Saving the bot").argument("<botName>").action(async(e,t)=>{let r=await u(t);await Je(r,e)});Or.description("Deploy the app to AWS").argument("<botName>").action(async(e,t)=>{let r=await u(t);await Je(r,e,!0)});Dr.arguments("<botName> <projectId> <sourceFile> <distFile>").description("Creating a bot").option("--runtime-version <runtimeVersion>","Runtime version (awslambda, vmcontext)").option("--no-write-config","Do not write bot to config").action(async(e,t,r,o,n)=>{let a=await u(n);await it(a,e,t,r,o,n.runtimeVersion,!!n.writeConfig)});async function Je(e,t,r=!1){let o=Qt(t);for(let n of o){let a=await e.readResource("Bot",n.id);await ot(e,n,a),r&&await nt(e,n,a)}console.log(`Number of bots deployed: ${o.length}`)}yt.description("Saves the bot").argument("<botName>").action(async(e,t)=>{let r=await u(t);await Je(r,e)});gt.description("Deploy the bot to AWS").argument("<botName>").action(async(e,t)=>{let r=await u(t);await Je(r,e,!0)});wt.arguments("<botName> <projectId> <sourceFile> <distFile>").description("Creates and saves the bot").action(async(e,t,r,o,n)=>{let a=await u(n);await it(a,e,t,r,o)});var Jr=require("commander"),Ne=require("fs"),St=require("path"),Nr=require("readline");var Ur=d("export"),Lr=d("import"),$r=new Jr.Command("bulk").addCommand(Ur).addCommand(Lr);Ur.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 g=new URL(p),b=await a.download(p),k=`${c}_${g.pathname}`.replace(/[^a-zA-Z0-9]+/g,"_")+".ndjson",ye=(0,St.resolve)(n??"",k);(0,Ne.writeFile)(`${ye}`,await b.text(),()=>{console.log(`${ye} is created`)})})});Lr.argument("<filename>","File Name").option("--num-resources-per-request <numResourcesPerRequest>","optional number of resources to import per batch request. Defaults to 25.","25").option("--add-extensions-for-missing-values","optional flag to add extensions for missing values in a resource",!1).option("-d, --target-directory <targetDirectory>","optional target directory of file to be imported").action(async(e,t)=>{let{numResourcesPerRequest:r,addExtensionsForMissingValues:o,targetDirectory:n}=t,a=(0,St.resolve)(n??process.cwd(),e),s=await u(t);await ti(a,parseInt(r,10),s,o)});async function ti(e,t,r,o){let n=[],a=(0,Ne.createReadStream)(e),s=(0,Nr.createInterface)({input:a});for await(let c of s){let p=ri(c,o);n.push({resource:p,request:{method:"POST",url:p.resourceType}}),n.length%t===0&&(await Mr(n,r),n=[])}n.length>0&&await Mr(n,r)}async function Mr(e,t){(await t.executeBatch({resourceType:"Bundle",type:"transaction",entry:e})).entry?.forEach(o=>{W(o.response)})}function ri(e,t){let r=JSON.parse(e);return t?oi(r):r}function oi(e){return e.resourceType==="ExplanationOfBenefit"?ni(e):e}function ni(e){return e.provider||(e.provider=st()),e.item?.forEach(t=>{t?.productOrService||(t.productOrService=st())}),e}var Ue=require("@medplum/core");var Vr=require("net"),zr=require("@medplum/core"),Yr=T(require("net"),1),Gr=class extends EventTarget{addEventListener(e,t,r){super.addEventListener(e,t,r)}removeEventListener(e,t,r){super.removeEventListener(e,t,r)}},ii="\v",Br="",Fr="\r",ai=class extends Event{constructor(e,t){super("message"),this.connection=e,this.message=t}},jr=class extends Event{constructor(e){super("error"),this.error=e}},Xr=class extends Gr{constructor(e,t){super(),this.socket=e,this.encoding=t;let r="";e.on("data",o=>{try{if(r+=o.toString(),r.endsWith(Br+Fr)){let n=zr.Hl7Message.parse(r.substring(1,r.length-2));this.dispatchEvent(new ai(this,n)),r=""}}catch(n){this.dispatchEvent(new jr(n))}}).setEncoding(t??"utf-8"),e.on("error",o=>{r="",this.dispatchEvent(new jr(o))})}send(e){this.socket.write(ii+e.toString()+Br+Fr)}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()}},qr=class extends Gr{constructor(e){super(),this.options=e,this.host=this.options.host,this.port=this.options.port}connect(){return this.connection?Promise.resolve(this.connection):new Promise(e=>{let t=(0,Vr.connect)({host:this.host,port:this.port},()=>{this.connection=new Xr(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)}},Zr=class{constructor(e){this.handler=e}start(e,t){let r=Yr.default.createServer(o=>{let n=new Xr(o,t);this.handler(n)});r.listen(e),this.server=r}stop(){this.server&&(this.server.close(),this.server=void 0)}};var Qr=require("commander"),eo=require("fs");var si=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=di():o.file&&(r=(0,eo.readFileSync)(o.file,"utf8")),!r)throw new Error("Missing HL7 message body");let n=new qr({host:e,port:parseInt(t,10)});try{let a=await n.sendAndWait(Ue.Hl7Message.parse(r));console.log(a.toString().replaceAll("\r",`
|
|
6
|
-
`))}finally{n.close()}}),
|
|
7
|
-
`)),r.send(o.buildAck())})}).start(parseInt(e,10)),console.log("Listening on port "+e)}),
|
|
5
|
+
`)}function _(e,t=""){return new Promise(r=>{ke.question(e+(t?" ("+t+")":"")+" ",o=>{r(o||t.toString())})})}async function ut(e,t,r=""){let o=e+" ["+t.map(n=>n===r?"("+n+")":n).join("|")+"]";for(;;){let n=await _(o)||r;if(t.includes(n))return n;i("Please choose one of the following options: "+t.join(", "))}}async function fe(e,t,r){return parseInt(await ut(e,t.map(o=>o.toString()),r.toString()),10)}async function Re(e){return(await ut(e,["y","n"])).toLowerCase()==="y"}async function lt(e){if(!await Re(e))throw i("Exiting..."),new Error("User cancelled")}function y(e,t){(0,We.writeFileSync)((0,hr.resolve)(e),JSON.stringify(t,void 0,2),"utf-8")}async function Dn(e){try{let t=new De.STSClient({region:e}),r=new De.GetCallerIdentityCommand({});return(await t.send(r)).Account}catch(t){console.log("Warning: Unable to get AWS account ID",t.message);return}}async function Wn(e){let t=await ur(e);if(e!=="us-east-1"){let r=await ur("us-east-1");t.push(...r)}return t}async function ur(e){try{let t=new z.ACMClient({region:e}),r=new z.ListCertificatesCommand({MaxItems:1e3});return(await t.send(r)).CertificateSummaryList}catch(t){return console.log("Warning: Unable to list certificates",t.message),[]}}async function Mn(e,t,r,o){let n=e[On(o)],a=t.find(c=>c.CertificateArn?.includes(r)&&c.DomainName===n);if(a)return i(`Found existing certificate for "${n}" in "${r}.`),a.CertificateArn;if(i(`No existing certificate found for "${n}" in "${r}.`),!await Re("Do you want to request a new certificate?"))return i(`Please add your certificate ARN to the config file in the "${gr(o)}" setting.`),"TODO";let s=await Jn(r,n);return i("Certificate ARN: "+s),s}async function Jn(e,t){try{let r=await ut("Validate certificate using DNS or email validation?",["dns","email"],"dns"),o=new z.ACMClient({region:e}),n=new z.RequestCertificateCommand({DomainName:t,ValidationMethod:r.toUpperCase()});return(await o.send(n)).CertificateArn}catch(r){return console.log("Error: Unable to request certificate",r.message),"TODO"}}async function Nn(e){let t=(0,he.randomUUID)(),r=(0,he.generateKeyPairSync)("rsa",{modulusLength:2048,publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs1",format:"pem",cipher:"aes-256-cbc",passphrase:t}});try{return{keyId:(await new Oe.CloudFrontClient({}).send(new Oe.CreatePublicKeyCommand({PublicKeyConfig:{Name:e,CallerReference:(0,he.randomUUID)(),EncodedKey:r.publicKey}}))).PublicKey?.Id,publicKey:r.publicKey,privateKey:r.privateKey,passphrase:t}}catch(o){console.log("Error: Unable to create signing key: ",(0,fr.normalizeErrorString)(o));return}}async function Un(e,t){let r=new oe.GetParameterCommand({Name:t,WithDecryption:!0});try{return(await e.send(r)).Parameter?.Value}catch(o){if(o.name==="ParameterNotFound")return;throw o}}async function Ln(e,t,r){let o=new oe.PutParameterCommand({Name:t,Value:r,Type:"SecureString",Overwrite:!0});await e.send(o)}async function $n(e,t,r){let o=new oe.SSMClient({region:e});for(let[n,a]of Object.entries(r)){let s=t+n,c=a.toString(),p=await Un(o,s);p!==void 0&&p!==c&&(i(`Parameter "${s}" exists with different value.`),await lt(`Do you want to overwrite "${s}"?`)),await Ln(o,s,c)}}async function Sr(){let e=await dt();for(let t of e){let r=t.StackName,o=await pt(r);o&&(Ke(o),console.log(""))}}var Er=require("@aws-sdk/client-s3"),H=require("@medplum/core"),br=T(require("fast-glob")),I=require("fs"),ft=T(require("node-fetch")),Cr=require("os"),X=require("path"),Ar=require("stream/promises");async function Pr(e,t){let r=re(e);if(!r){console.log("Config not found");return}let o=await B(e);if(!o){console.log("Stack not found");return}let n=o.appBucket;if(!n){console.log("App bucket not found");return}let a=await Fn("@medplum/app","latest");vr(a,{MEDPLUM_BASE_URL:r.baseUrl,MEDPLUM_CLIENT_ID:r.clientId??"",GOOGLE_CLIENT_ID:r.googleClientId??"",RECAPTCHA_SITE_KEY:r.recaptchaSiteKey??"",MEDPLUM_REGISTER_ENABLED:r.registerEnabled?"true":"false"}),await Gn(a,n.PhysicalResourceId,t),o.appDistribution?.PhysicalResourceId&&!t.dryrun&&await He(o.appDistribution.PhysicalResourceId),console.log("Done")}async function Bn(e,t){let r=`https://registry.npmjs.org/${e}/${t}`;return(await(0,ft.default)(r)).json()}async function Fn(e,t){let o=(await Bn(e,t)).dist.tarball,n=(0,I.mkdtempSync)((0,X.join)((0,Cr.tmpdir)(),"tarball-"));try{let a=await(0,ft.default)(o),s=Qt(n);return await(0,Ar.pipeline)(a.body,s),(0,X.join)(n,"package","dist")}catch(a){throw(0,I.rmSync)(n,{recursive:!0,force:!0}),a}}function vr(e,t){for(let r of(0,I.readdirSync)(e,{withFileTypes:!0})){let o=(0,X.join)(e,r.name);r.isDirectory()?vr(o,t):r.isFile()&&o.endsWith(".js")&&jn(o,t)}}function jn(e,t){let r=(0,I.readFileSync)(e,"utf-8");for(let[o,n]of Object.entries(t))r=r.replaceAll(`__${o}__`,n);(0,I.writeFileSync)(e,r)}async function Gn(e,t,r){let o=[["assets/**/*.css",H.ContentType.CSS,!0],["assets/**/*.css.map",H.ContentType.JSON,!0],["assets/**/*.js",H.ContentType.JAVASCRIPT,!0],["assets/**/*.js.map",H.ContentType.JSON,!0],["assets/**/*.txt",H.ContentType.TEXT,!0],["assets/**/*.ico",H.ContentType.FAVICON,!0],["img/**/*.png",H.ContentType.PNG,!0],["img/**/*.svg",H.ContentType.SVG,!0],["robots.txt",H.ContentType.TEXT,!0],["index.html",H.ContentType.HTML,!1]];for(let n of o)await Vn({rootDir:e,bucketName:t,fileNamePattern:n[0],contentType:n[1],cached:n[2],dryrun:r.dryrun})}async function Vn(e){let t=br.default.sync(e.fileNamePattern,{cwd:e.rootDir});for(let r of t)await zn((0,X.join)(e.rootDir,r),e)}async function zn(e,t){let r=(0,I.createReadStream)(e),o=e.substring(t.rootDir.length+1).split(X.sep).join("/"),n={Bucket:t.bucketName,Key:o,Body:r,ContentType:t.contentType,CacheControl:t.cached?"public, max-age=31536000":"no-cache, no-store, must-revalidate"};console.log(`Uploading ${o} to ${t.bucketName}...`),t.dryrun||await ue.send(new Er.PutObjectCommand(n))}var Me=require("@aws-sdk/client-s3");async function _r(e,t){if(!re(e)){console.log("Config not found");return}let o=await B(e);if(!o){console.log("Stack not found");return}await xr("App",o.appBucket,o.appDistribution,o.appOriginAccessIdentity,t),await xr("Storage",o.storageBucket,o.storageDistribution,o.storageOriginAccessIdentity,t),console.log("Done")}async function xr(e,t,r,o,n){if(!t?.PhysicalResourceId){console.log(`${e} bucket not found`);return}if(!r?.PhysicalResourceId){console.log(`${e} distribution not found`);return}if(!o?.PhysicalResourceId){console.log(`${e} OAI not found`);return}let a=t.PhysicalResourceId,s=o.PhysicalResourceId,c=await Xn(a);if(Yn(c,a,s)){console.log(`${e} bucket already has policy statement`);return}Zn(c,a,s),console.log(`${e} bucket policy:`),console.log(JSON.stringify(c,void 0,2)),n.dryrun?console.log("Dry run - skipping updates"):(console.log("Updating bucket policy..."),await qn(a,c),console.log("Bucket policy updated"),console.log("Creating CloudFront invalidation..."),await He(r.PhysicalResourceId),console.log("CloudFront invalidation created"),console.log(`${e} bucket policy updated`))}async function Xn(e){let t=await ue.send(new Me.GetBucketPolicyCommand({Bucket:e}));return JSON.parse(t.Policy??"{}")}async function qn(e,t){await ue.send(new Me.PutBucketPolicyCommand({Bucket:e,Policy:JSON.stringify(t)}))}function Yn(e,t,r){return!!e?.Statement?.some(o=>o?.Effect==="Allow"&&o?.Principal?.AWS===`arn:aws:iam::cloudfront:user/CloudFront Origin Access Identity ${r}`&&Array.isArray(o?.Action)&&o?.Action?.includes("s3:GetObject*")&&o?.Action?.includes("s3:GetBucket*")&&o?.Action?.includes("s3:List*")&&Array.isArray(o?.Resource)&&o?.Resource?.includes(`arn:aws:s3:::${t}`)&&o?.Resource?.includes(`arn:aws:s3:::${t}/*`))}function Zn(e,t,r){e.Version||(e.Version="2012-10-17"),e.Statement||(e.Statement=[]),e.Statement.push({Effect:"Allow",Principal:{AWS:`arn:aws:iam::cloudfront:user/CloudFront Origin Access Identity ${r}`},Action:["s3:GetObject*","s3:GetBucket*","s3:List*"],Resource:[`arn:aws:s3:::${t}`,`arn:aws:s3:::${t}/*`]})}var Ir=require("@aws-sdk/client-ecs");async function Tr(e){let t=await B(e);if(!t){console.log("Stack not found");return}let r=t.ecsCluster?.PhysicalResourceId;if(!r){console.log("ECS Cluster not found");return}let o=mt(t.ecsService);if(!o){console.log("ECS Service not found");return}await mr.send(new Ir.UpdateServiceCommand({cluster:r,service:o,forceNewDeployment:!0})),console.log(`Service "${o}" updated successfully.`)}var F=new Kr.Command("aws").description("Commands to manage AWS resources");F.command("init").description("Initialize a new Medplum AWS CloudFormation stacks").action(wr);F.command("list").description("List Medplum AWS CloudFormation stacks").action(Sr);F.command("describe").description("Describe a Medplum AWS CloudFormation stack by tag").argument("<tag>").action(lr);F.command("update-server").alias("deploy-server").description("Update the server image").argument("<tag>").action(Tr);F.command("update-app").alias("deploy-app").description("Update the app site").argument("<tag>").option("--dryrun","Displays the operations that would be performed using the specified command without actually running them.").action(Pr);F.command("update-bucket-policies").description("Update S3 bucket policies").argument("<tag>").option("--dryrun","Displays the operations that would be performed using the specified command without actually running them.").action(_r);var Hr=require("commander");var kr=d("save"),Rr=d("deploy"),Or=d("create"),Dr=new Hr.Command("bot").addCommand(kr).addCommand(Rr).addCommand(Or),ht=d("save-bot"),yt=d("deploy-bot"),gt=d("create-bot");kr.description("Saving the bot").argument("<botName>").action(async(e,t)=>{let r=await l(t);await Je(r,e)});Rr.description("Deploy the app to AWS").argument("<botName>").action(async(e,t)=>{let r=await l(t);await Je(r,e,!0)});Or.arguments("<botName> <projectId> <sourceFile> <distFile>").description("Creating a bot").option("--runtime-version <runtimeVersion>","Runtime version (awslambda, vmcontext)").option("--no-write-config","Do not write bot to config").action(async(e,t,r,o,n)=>{let a=await l(n);await nt(a,e,t,r,o,n.runtimeVersion,!!n.writeConfig)});async function Je(e,t,r=!1){let o=Zt(t);for(let n of o){let a=await e.readResource("Bot",n.id);await rt(e,n,a),r&&await ot(e,n,a)}console.log(`Number of bots deployed: ${o.length}`)}ht.description("Saves the bot").argument("<botName>").action(async(e,t)=>{let r=await l(t);await Je(r,e)});yt.description("Deploy the bot to AWS").argument("<botName>").action(async(e,t)=>{let r=await l(t);await Je(r,e,!0)});gt.arguments("<botName> <projectId> <sourceFile> <distFile>").description("Creates and saves the bot").action(async(e,t,r,o,n)=>{let a=await l(n);await nt(a,e,t,r,o)});var Mr=require("commander"),Ne=require("fs"),wt=require("path"),Jr=require("readline");var Nr=d("export"),Ur=d("import"),Lr=new Mr.Command("bulk").addCommand(Nr).addCommand(Ur);Nr.option("-e, --export-level <exportLevel>",'Optional export level. Defaults to system level export. "Group/:id" - Group of Patients, "Patient" - All Patients.').option("-t, --types <types>","optional resource types to export").option("-s, --since <since>","optional Resources will be included in the response if their state has changed after the supplied time (e.g. if Resource.meta.lastUpdated is later than the supplied _since time).").option("-d, --target-directory <targetDirectory>","optional target directory to save files from the bulk export operations.").action(async e=>{let{exportLevel:t,types:r,since:o,targetDirectory:n}=e,a=await l(e);(await a.bulkExport(t,r,o)).output?.forEach(async({type:c,url:p})=>{let g=new URL(p),b=await a.download(p),k=`${c}_${g.pathname}`.replace(/[^a-zA-Z0-9]+/g,"_")+".ndjson",ge=(0,wt.resolve)(n??"",k);(0,Ne.writeFile)(`${ge}`,await b.text(),()=>{console.log(`${ge} is created`)})})});Ur.argument("<filename>","File Name").option("--num-resources-per-request <numResourcesPerRequest>","optional number of resources to import per batch request. Defaults to 25.","25").option("--add-extensions-for-missing-values","optional flag to add extensions for missing values in a resource",!1).option("-d, --target-directory <targetDirectory>","optional target directory of file to be imported").action(async(e,t)=>{let{numResourcesPerRequest:r,addExtensionsForMissingValues:o,targetDirectory:n}=t,a=(0,wt.resolve)(n??process.cwd(),e),s=await l(t);await Qn(a,parseInt(r,10),s,o)});async function Qn(e,t,r,o){let n=[],a=(0,Ne.createReadStream)(e),s=(0,Jr.createInterface)({input:a});for await(let c of s){let p=ei(c,o);n.push({resource:p,request:{method:"POST",url:p.resourceType}}),n.length%t===0&&(await Wr(n,r),n=[])}n.length>0&&await Wr(n,r)}async function Wr(e,t){(await t.executeBatch({resourceType:"Bundle",type:"transaction",entry:e})).entry?.forEach(o=>{M(o.response)})}function ei(e,t){let r=JSON.parse(e);return t?ti(r):r}function ti(e){return e.resourceType==="ExplanationOfBenefit"?ri(e):e}function ri(e){return e.provider||(e.provider=at()),e.item?.forEach(t=>{t?.productOrService||(t.productOrService=at())}),e}var Ue=require("@medplum/core");var Gr=require("net"),Vr=require("@medplum/core"),qr=T(require("net"),1),jr=class extends EventTarget{addEventListener(e,t,r){super.addEventListener(e,t,r)}removeEventListener(e,t,r){super.removeEventListener(e,t,r)}},oi="\v",$r="",Br="\r",ni=class extends Event{constructor(e,t){super("message"),this.connection=e,this.message=t}},Fr=class extends Event{constructor(e){super("error"),this.error=e}},zr=class extends jr{constructor(e,t){super(),this.socket=e,this.encoding=t;let r="";e.on("data",o=>{try{if(r+=o.toString(),r.endsWith($r+Br)){let n=Vr.Hl7Message.parse(r.substring(1,r.length-2));this.dispatchEvent(new ni(this,n)),r=""}}catch(n){this.dispatchEvent(new Fr(n))}}).setEncoding(t??"utf-8"),e.on("error",o=>{r="",this.dispatchEvent(new Fr(o))})}send(e){this.socket.write(oi+e.toString()+$r+Br)}async sendAndWait(e){let t=new Promise(r=>{function o(n){n.target.removeEventListener("message",o),r(n.message)}this.addEventListener("message",o)});return this.send(e),t}close(){this.socket.end(),this.socket.destroy()}},Xr=class extends jr{constructor(e){super(),this.options=e,this.host=this.options.host,this.port=this.options.port}connect(){return this.connection?Promise.resolve(this.connection):new Promise(e=>{let t=(0,Gr.connect)({host:this.host,port:this.port},()=>{this.connection=new zr(t),e(this.connection)})})}async send(e){return(await this.connect()).send(e)}async sendAndWait(e){return(await this.connect()).sendAndWait(e)}close(){this.connection&&(this.connection.close(),delete this.connection)}},Yr=class{constructor(e){this.handler=e}start(e,t){let r=qr.default.createServer(o=>{let n=new zr(o,t);this.handler(n)});r.listen(e),this.server=r}stop(){this.server&&(this.server.close(),this.server=void 0)}};var Zr=require("commander"),Qr=require("fs");var ii=d("send").description("Send an HL7 v2 message via MLLP").argument("<host>","The destination host name or IP address").argument("<port>","The destination port number").argument("[body]","Optional HL7 message body").option("--generate-example","Generate a sample HL7 message").option("--file <file>","Read the HL7 message from a file").action(async(e,t,r,o)=>{if(o.generateExample?r=si():o.file&&(r=(0,Qr.readFileSync)(o.file,"utf8")),!r)throw new Error("Missing HL7 message body");let n=new Xr({host:e,port:parseInt(t,10)});try{let a=await n.sendAndWait(Ue.Hl7Message.parse(r));console.log(a.toString().replaceAll("\r",`
|
|
6
|
+
`))}finally{n.close()}}),ai=d("listen").description("Starts an HL7 v2 MLLP server").argument("<port>").action(async e=>{new Yr(r=>{r.addEventListener("message",({message:o})=>{console.log(o.toString().replaceAll("\r",`
|
|
7
|
+
`)),r.send(o.buildAck())})}).start(parseInt(e,10)),console.log("Listening on port "+e)}),eo=new Zr.Command("hl7").addCommand(ii).addCommand(ai);function si(){let e=(0,Ue.formatHl7DateTime)(new Date),t=Date.now().toString();return`MSH|^~\\&|ADTSYS|HOSPITAL|RECEIVER|DEST|${e}||ADT^A01|${t}|P|2.5|
|
|
8
8
|
EVN|A01|${e}||
|
|
9
9
|
PID|1|12345|12345^^^HOSP^MR|123456|DOE^JOHN^MIDDLE^SUFFIX|19800101|M|||123 STREET^APT 4B^CITY^ST^12345-6789||555-555-5555||S|
|
|
10
|
-
PV1|1|I|2000^2012^01||||12345^DOCTOR^DOC||||||||||1234567^DOCTOR^DOC||AMB|||||||||||||||||||||||||202309280900|`}var
|
|
10
|
+
PV1|1|I|2000^2012^01||||12345^DOCTOR^DOC||||||||||1234567^DOCTOR^DOC||AMB|||||||||||||||||||||||||202309280900|`}var to=require("commander");var ro=require("path"),oo=require("fs"),no=require("os");var io=d("set"),ao=d("remove"),so=d("list"),co=d("describe"),po=new to.Command("profile").addCommand(io).addCommand(ao).addCommand(so).addCommand(co);io.argument("<profileName>","Name of the profile").description("Create a new profile or replace it with the given name and its associated properties").action(async(e,t)=>{_e(e,t)});ao.argument("<profileName>","Name of the profile").description("Remove a profile by name").action(async e=>{new R(e).setObject("options",void 0),console.log(`${e} profile removed`)});so.description("List all profiles saved").action(async()=>{let e=(0,ro.resolve)((0,no.homedir)(),".medplum"),t=(0,oo.readdirSync)(e),r=[];t.forEach(o=>{let n=o.split(".")[0],s=new R(n).getObject("options");s&&r.push({profileName:n,profile:s})}),console.log(r)});co.argument("<profileName>","Name of the profile").description("Describes a profile").action(async e=>{let t=er(e);console.log(t)});var Le=require("commander");var mo=d("list"),lo=d("current"),uo=d("switch"),fo=d("invite"),ho=new Le.Command("project").addCommand(mo).addCommand(lo).addCommand(uo).addCommand(fo);mo.description("List of current projects").action(async e=>{let t=await l(e);ci(t)});function ci(e){let r=e.getLogins().map(o=>`${o.project.display} (${o.project.reference})`).join(`
|
|
11
11
|
|
|
12
|
-
`);console.log(r)}
|
|
13
|
-
`)):console.log(`Error: project ${t} not found. Make sure you are added as a user to this project`)}async function
|
|
12
|
+
`);console.log(r)}lo.description("Project you are currently on").action(async e=>{let r=(await l(e)).getActiveLogin();if(!r)throw new Error("Unauthenticated: run `npx medplum login` to login");console.log(`${r.project.display} (${r.project.reference})`)});uo.description("Switching to another project from the current one").argument("<projectId>").action(async(e,t)=>{let r=await l(t);await di(r,e)});fo.description("Invite a member to your current project (run npx medplum project current to confirm)").arguments("<firstName> <lastName> <email>").option("--send-email","If you want to send the email when inviting the user").option("--admin","If the user you are inviting is an admin").addOption(new Le.Option("-r, --role <role>","Role of user").choices(["Practitioner","Patient","RelatedPerson"]).default("Practitioner")).action(async(e,t,r,o)=>{let n=await l(o),a=n.getActiveLogin();if(!a)throw new Error("Unauthenticated: run `npx medplum login` to login");if(!a.project.reference)throw new Error("No current project to invite user to");let s=a.project.reference.split("/")[1],c={resourceType:o.role,firstName:e,lastName:t,email:r,sendEmail:!!o.sendEmail,admin:!!o.admin};await pi(s,c,n)});async function di(e,t){let o=e.getLogins().find(n=>n.project.reference?.includes(t));o?(await e.setActiveLogin(o),console.log(`Switched to project ${t}
|
|
13
|
+
`)):console.log(`Error: project ${t} not found. Make sure you are added as a user to this project`)}async function pi(e,t,r){try{await r.invite(e,t),t.sendEmail&&console.log("Email sent"),console.log("See your users at https://app.medplum.com/admin/users")}catch(o){console.log("Error while sending invite "+o)}}var yo=require("@medplum/core");var St=d("delete"),Et=d("get"),bt=d("patch"),Ct=d("post"),At=d("put");St.argument("<url>","Resource/$id").action(async(e,t)=>{let r=await l(t);M(await r.delete(ye(r,e)))});Et.argument("<url>","Resource/$id").option("--as-transaction","Print out the bundle as a transaction type").action(async(e,t)=>{let r=await l(t),o=await r.get(ye(r,e));t.asTransaction?M((0,yo.convertToTransactionBundle)(o)):M(o)});bt.arguments("<url> <body>").action(async(e,t,r)=>{let o=await l(r);M(await o.patch(ye(o,e),Pt(t)))});Ct.arguments("<url> <body>").action(async(e,t,r)=>{let o=await l(r);M(await o.post(ye(o,e),Pt(t)))});At.arguments("<url> <body>").action(async(e,t,r)=>{let o=await l(r);M(await o.put(ye(o,e),Pt(t)))});function Pt(e){if(e)try{return JSON.parse(e)}catch{return e}}function ye(e,t){return["admin/","auth/","fhir/R4"].some(o=>t.startsWith(o))?t:e.fhirUrl(t).toString()}async function So(e){try{let t=new go.Command("medplum").description("Command to access Medplum CLI");t.version($e.MEDPLUM_VERSION),t.addCommand(st),t.addCommand(ct),t.addCommand(Et),t.addCommand(Ct),t.addCommand(bt),t.addCommand(At),t.addCommand(St),t.addCommand(ho),t.addCommand(Lr),t.addCommand(Dr),t.addCommand(ht),t.addCommand(yt),t.addCommand(gt),t.addCommand(po),t.addCommand(F),t.addCommand(eo),await t.parseAsync(e)}catch(t){console.error("Error: "+(0,$e.normalizeErrorString)(t))}}async function Eo(){wo.default.config(),await So(process.argv)}require.main===module&&Eo().catch(e=>console.error("Unhandled error:",e));0&&(module.exports={main,run});
|
|
14
14
|
//# sourceMappingURL=index.cjs.map
|