@medplum/cli 2.0.32 → 2.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,9 +1,9 @@
1
1
  #!/usr/bin/env node
2
- var ot=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,r)=>(typeof require<"u"?require:t)[r]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});import{MEDPLUM_VERSION as _i,normalizeErrorString as Ki}from"@medplum/core";import{Command as Ti}from"commander";import Ii from"dotenv";import{ContentType as Ne,getDisplayString as Qo,normalizeErrorString as en}from"@medplum/core";import{exec as tn}from"child_process";import{createServer as rn}from"http";import{platform as on}from"os";import{ClientStorage as fr}from"@medplum/core";import{existsSync as nt,mkdirSync as hr,readFileSync as yr,writeFileSync as gr}from"fs";import{homedir as wr}from"os";import{resolve as it}from"path";var E=class extends fr{constructor(r){super();this.dirName=it(wr(),".medplum"),this.fileName=it(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(nt(this.fileName))return JSON.parse(yr(this.fileName,"utf8"))}writeFile(r){nt(this.dirName)||hr(this.dirName),gr(this.fileName,JSON.stringify(r,null,2),"utf8")}};import{MedplumClient as Sr}from"@medplum/core";async function u(e){let t=e.profile??"default",r=new E(t),o=r.getObject("options");if(t!=="default"&&!o)throw new Error(`Profile "${t}" does not exist`);let{baseUrl:n,fhirUrlPath:a,accessToken:s,tokenUrl:c,authorizeUrl:p,clientId:f,clientSecret:y}=Er(e,r),T=e.fetch??fetch,I=new Sr({fetch:T,baseUrl:n,tokenUrl:c,fhirUrlPath:a,authorizeUrl:p,storage:r,onUnauthenticated:br});return s&&I.setAccessToken(s),o?.authType==="client_credentials"?(I.setBasicAuth(f,y),await I.startClientLogin(f,y)):o?.authType==="basic"&&I.setBasicAuth(f,y),I}function Er(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,f=e.clientSecret??r?.clientSecret??process.env.MEDPLUM_CLIENT_SECRET;return{baseUrl:o,fhirUrlPath:n,accessToken:a,tokenUrl:s,authorizeUrl:c,clientId:p,clientSecret:f}}function br(){console.log("Unauthenticated: run `npx medplum login` to sign in")}import{Command as Cr,Option as vr}from"commander";function m(e){return new Cr(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").option("--token-url <tokenUrl>","FHIR server token url").option("--authorize-url <authorizeUrl>","FHIR server authorize url").option("--fhir-url-path <fhirUrlPath>","FHIR server url path").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").addOption(new vr("--auth-type <authType>","Type of authentication").choices(["basic","client-credentials","authorization-code","jwt-bearer","token-exchange","jwt-assertion"]))}import{ContentType as We,encodeBase64 as At}from"@medplum/core";import{createHmac as No,createPrivateKey as Uo,randomBytes as Lo}from"crypto";import{existsSync as $o,readFileSync as xt,writeFile as Bo}from"fs";import{Buffer as be}from"buffer";var A=new TextEncoder,b=new TextDecoder,ji=2**32;function H(...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 w;be.isEncoding("base64url")?w=e=>be.from(e).toString("base64url"):w=e=>be.from(e).toString("base64").replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_");var U=class extends Error{static get code(){return"ERR_JOSE_GENERIC"}constructor(t){var r;super(t),this.code="ERR_JOSE_GENERIC",this.name=this.constructor.name,(r=Error.captureStackTrace)===null||r===void 0||r.call(Error,this,this.constructor)}};var d=class extends U{constructor(){super(...arguments),this.code="ERR_JOSE_NOT_SUPPORTED"}static get code(){return"ERR_JOSE_NOT_SUPPORTED"}};var x=class extends U{constructor(){super(...arguments),this.code="ERR_JWS_INVALID"}static get code(){return"ERR_JWS_INVALID"}},R=class extends U{constructor(){super(...arguments),this.code="ERR_JWT_INVALID"}static get code(){return"ERR_JWT_INVALID"}};import{KeyObject as Pr}from"crypto";import*as ve from"util";var P=ve.types.isKeyObject?e=>ve.types.isKeyObject(e):e=>e!=null&&e instanceof Pr;import*as st from"crypto";import*as Ae from"util";var _r=st.webcrypto,oe=_r,C=Ae.types.isCryptoKey?e=>Ae.types.isCryptoKey(e):e=>!1;function O(e,t="algorithm.name"){return new TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`)}function ne(e,t){return e.name===t}function xe(e){return parseInt(e.name.slice(4),10)}function Kr(e){switch(e){case"ES256":return"P-256";case"ES384":return"P-384";case"ES512":return"P-521";default:throw new Error("unreachable")}}function Tr(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 ct(e,t,...r){switch(t){case"HS256":case"HS384":case"HS512":{if(!ne(e.algorithm,"HMAC"))throw O("HMAC");let o=parseInt(t.slice(2),10);if(xe(e.algorithm.hash)!==o)throw O(`SHA-${o}`,"algorithm.hash");break}case"RS256":case"RS384":case"RS512":{if(!ne(e.algorithm,"RSASSA-PKCS1-v1_5"))throw O("RSASSA-PKCS1-v1_5");let o=parseInt(t.slice(2),10);if(xe(e.algorithm.hash)!==o)throw O(`SHA-${o}`,"algorithm.hash");break}case"PS256":case"PS384":case"PS512":{if(!ne(e.algorithm,"RSA-PSS"))throw O("RSA-PSS");let o=parseInt(t.slice(2),10);if(xe(e.algorithm.hash)!==o)throw O(`SHA-${o}`,"algorithm.hash");break}case"EdDSA":{if(e.algorithm.name!=="Ed25519"&&e.algorithm.name!=="Ed448")throw O("Ed25519 or Ed448");break}case"ES256":case"ES384":case"ES512":{if(!ne(e.algorithm,"ECDSA"))throw O("ECDSA");let o=Kr(t);if(e.algorithm.namedCurve!==o)throw O(o,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}Tr(e,r)}function dt(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 _=(e,...t)=>dt("Key must be ",e,...t);function Pe(e,t,...r){return dt(`Key for the ${e} algorithm must be `,t,...r)}var _e=e=>P(e)||C(e),l=["KeyObject"];(globalThis.CryptoKey||!(oe===null||oe===void 0)&&oe.CryptoKey)&&l.push("CryptoKey");import{promisify as mt}from"util";import{inflateRaw as Wr,deflateRaw as Rr}from"zlib";var Da=mt(Wr),Ja=mt(Rr);var Mr=(...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},L=Mr;function Dr(e){return typeof e=="object"&&e!==null}function S(e){if(!Dr(e)||Object.prototype.toString.call(e)!=="[object Object]")return!1;if(Object.getPrototypeOf(e)===null)return!0;let t=e;for(;Object.getPrototypeOf(t)!==null;)t=Object.getPrototypeOf(t);return Object.getPrototypeOf(e)===t}import{diffieHellman as ds,generateKeyPair as Gr,KeyObject as ps}from"crypto";import{promisify as zr}from"util";import{Buffer as ie}from"buffer";import{createPublicKey as Jr,KeyObject as Nr}from"crypto";var Ur=ie.from([42,134,72,206,61,3,1,7]),Lr=ie.from([43,129,4,0,34]),$r=ie.from([43,129,4,0,35]),Br=ie.from([43,129,4,0,10]),Ke=new WeakMap,Fr=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 d("Unsupported key curve for this operation")}},ut=(e,t)=>{var r;let o;if(C(e))o=Nr.from(e);else if(P(e))o=e;else throw new TypeError(_(e,...l));if(o.type==="secret")throw new TypeError('only "private" or "public" type keys can be used for this operation');switch(o.asymmetricKeyType){case"ed25519":case"ed448":return`Ed${o.asymmetricKeyType.slice(2)}`;case"x25519":case"x448":return`X${o.asymmetricKeyType.slice(1)}`;case"ec":{if(Ke.has(o))return Ke.get(o);let n=(r=o.asymmetricKeyDetails)===null||r===void 0?void 0:r.namedCurve;if(!n&&o.type==="private")n=ut(Jr(o),!0);else if(!n){let s=o.export({format:"der",type:"spki"}),c=s[1]<128?14:15,p=s[c],f=s.slice(c+1,c+1+p);if(f.equals(Ur))n="prime256v1";else if(f.equals(Lr))n="secp384r1";else if(f.equals($r))n="secp521r1";else if(f.equals(Br))n="secp256k1";else throw new d("Unsupported key curve for this operation")}if(t)return n;let a=Fr(n);return Ke.set(o,a),a}default:throw new TypeError("Invalid asymmetric key type for this operation")}};var ae=ut;var Es=zr(Gr);import{promisify as qr}from"util";import{KeyObject as _s,pbkdf2 as Xr}from"crypto";var Js=qr(Xr);var Te=new WeakMap,se=(e,t)=>{let r=e.readUInt8(1);if(!(r&128))return t===0?r:se(e.subarray(2+r),t-1);let o=r&127;r=0;for(let n=0;n<o;n++){r<<=8;let a=e.readUInt8(2+n);r|=a}return t===0?r:se(e.subarray(2+r),t-1)},Yr=(e,t)=>{let r=e.readUInt8(1);if(!(r&128))return se(e.subarray(2),t);let o=r&127;return se(e.subarray(2+o),t)},Zr=e=>{var t,r;if(Te.has(e))return Te.get(e);let o=(r=(t=e.asymmetricKeyDetails)===null||t===void 0?void 0:t.modulusLength)!==null&&r!==void 0?r:Yr(e.export({format:"der",type:"pkcs1"}),e.type==="private"?1:0)-1<<3;return Te.set(e,o),o};var q=(e,t)=>{if(Zr(e)<2048)throw new TypeError(`${t} requires key modulusLength to be 2048 bits or larger`)};import{Buffer as v}from"buffer";var Qr=2,eo=3,to=4,ro=48,nc=v.from([0]),ic=v.from([Qr]),ac=v.from([eo]),sc=v.from([ro]),cc=v.from([to]);var dc=new Map([["P-256",v.from("06 08 2A 86 48 CE 3D 03 01 07".replace(/ /g,""),"hex")],["secp256k1",v.from("06 05 2B 81 04 00 0A".replace(/ /g,""),"hex")],["P-384",v.from("06 05 2B 81 04 00 22".replace(/ /g,""),"hex")],["P-521",v.from("06 05 2B 81 04 00 23".replace(/ /g,""),"hex")],["ecPublicKey",v.from("06 07 2A 86 48 CE 3D 02 01".replace(/ /g,""),"hex")],["X25519",v.from("06 03 2B 65 6E".replace(/ /g,""),"hex")],["X448",v.from("06 03 2B 65 6F".replace(/ /g,""),"hex")],["Ed25519",v.from("06 03 2B 65 70".replace(/ /g,""),"hex")],["Ed448",v.from("06 03 2B 65 71".replace(/ /g,""),"hex")]]);var[D,ce]=process.versions.node.split(".").map(e=>parseInt(e,10)),ft=D>=16||D===15&&ce>=13,J=!("electron"in process.versions)&&(D>=17||D===16&&ce>=9),oo=D>=16||D===15&&ce>=9,no=D>=16||D===15&&ce>=12;var ao=(e,t)=>{if(!(t instanceof Uint8Array)){if(!_e(t))throw new TypeError(Pe(e,t,...l,"Uint8Array"));if(t.type!=="secret")throw new TypeError(`${l.join(" or ")} instances for symmetric algorithms must be of type "secret"`)}},so=(e,t,r)=>{if(!_e(t))throw new TypeError(Pe(e,t,...l));if(t.type==="secret")throw new TypeError(`${l.join(" or ")} instances for asymmetric algorithms must not be of type "secret"`);if(r==="sign"&&t.type==="public")throw new TypeError(`${l.join(" or ")} instances for asymmetric algorithm signing must be of type "private"`);if(r==="decrypt"&&t.type==="public")throw new TypeError(`${l.join(" or ")} instances for asymmetric algorithm decryption must be of type "private"`);if(t.algorithm&&r==="verify"&&t.type==="private")throw new TypeError(`${l.join(" or ")} instances for asymmetric algorithm verifying must be of type "public"`);if(t.algorithm&&r==="encrypt"&&t.type==="private")throw new TypeError(`${l.join(" or ")} instances for asymmetric algorithm encryption must be of type "public"`)},co=(e,t,r)=>{e.startsWith("HS")||e==="dir"||e.startsWith("PBES2")||/^A\d{3}(?:GCM)?KW$/.test(e)?ao(e,t):so(e,t,r)},X=co;function yo(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 d(`Extension Header Parameter "${s}" is not recognized`);if(n[s]===void 0)throw new e(`Extension Header Parameter "${s}" is missing`);if(a.get(s)&&o[s]===void 0)throw new e(`Extension Header Parameter "${s}" MUST be integrity protected`)}return new Set(o.crit)}var B=yo;var bo=Symbol();import*as Y from"crypto";import{promisify as Po}from"util";function de(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 d(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}import{constants as wt}from"crypto";var St={padding:wt.RSA_PKCS1_PSS_PADDING,saltLength:wt.RSA_PSS_SALTLEN_DIGEST},Co=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 q(t,e),t;case(J&&"PS256"):case(J&&"PS384"):case(J&&"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 q(t,e),{key:t,...St};case(!J&&"PS256"):case(!J&&"PS384"):case(!J&&"PS512"):if(t.asymmetricKeyType!=="rsa")throw new TypeError("Invalid key for this operation, its asymmetricKeyType must be rsa");return q(t,e),{key:t,...St};case"ES256":case"ES256K":case"ES384":case"ES512":{if(t.asymmetricKeyType!=="ec")throw new TypeError("Invalid key for this operation, its asymmetricKeyType must be ec");let r=ae(t),o=Co.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 d(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}import*as F from"crypto";import{promisify as Ao}from"util";function He(e){switch(e){case"HS256":return"sha256";case"HS384":return"sha384";case"HS512":return"sha512";default:throw new d(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}import{KeyObject as Et,createSecretKey as vo}from"crypto";function me(e,t,r){if(t instanceof Uint8Array){if(!e.startsWith("HS"))throw new TypeError(_(t,...l));return vo(t)}if(t instanceof Et)return t;if(C(t))return ct(t,e,r),Et.from(t);throw new TypeError(_(t,...l,"Uint8Array"))}var ke;F.sign.length>3?ke=Ao(F.sign):ke=F.sign;var xo=async(e,t,r)=>{let o=me(e,t,"sign");if(e.startsWith("HS")){let n=F.createHmac(He(e),o);return n.update(r),n.digest()}return ke(de(e),r,pe(e,o))},Oe=xo;var bt;Y.verify.length>4&&ft?bt=Po(Y.verify):bt=Y.verify;var Z=e=>Math.floor(e.getTime()/1e3);var Ko=/^(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)$/i,ue=e=>{let t=Ko.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 G=class{constructor(t){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 x("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");if(!L(this._protectedHeader,this._unprotectedHeader))throw new x("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let o={...this._protectedHeader,...this._unprotectedHeader},n=B(x,new Map([["b64",!0]]),r?.crit,this._protectedHeader,o),a=!0;if(n.has("b64")&&(a=this._protectedHeader.b64,typeof a!="boolean"))throw new x('The "b64" (base64url-encode payload) Header Parameter must be a boolean');let{alg:s}=o;if(typeof s!="string"||!s)throw new x('JWS "alg" (Algorithm) Header Parameter missing or invalid');X(s,t,"sign");let c=this._payload;a&&(c=A.encode(w(c)));let p;this._protectedHeader?p=A.encode(w(JSON.stringify(this._protectedHeader))):p=A.encode("");let f=H(p,A.encode("."),c),y=await Oe(s,t,f),T={signature:w(y),payload:""};return a&&(T.payload=b.decode(c)),this._unprotectedHeader&&(T.header=this._unprotectedHeader),this._protectedHeader&&(T.protected=b.decode(p)),T}};var Q=class{constructor(t){this._flattened=new G(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}`}};var z=class{constructor(t){if(!S(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:t}:this._payload={...this._payload,nbf:Z(new Date)+ue(t)},this}setExpirationTime(t){return typeof t=="number"?this._payload={...this._payload,exp:t}:this._payload={...this._payload,exp:Z(new Date)+ue(t)},this}setIssuedAt(t){return typeof t>"u"?this._payload={...this._payload,iat:Z(new Date)}:this._payload={...this._payload,iat:t},this}};var ee=class extends z{setProtectedHeader(t){return this._protectedHeader=t,this}async sign(t,r){var o;let n=new Q(A.encode(JSON.stringify(this._payload)));if(n.setProtectedHeader(this._protectedHeader),Array.isArray((o=this._protectedHeader)===null||o===void 0?void 0:o.crit)&&this._protectedHeader.crit.includes("b64")&&this._protectedHeader.b64===!1)throw new R("JWTs MUST NOT use unencoded payload");return n.sign(t,r)}};import{createSecretKey as sl,generateKeyPair as Do}from"crypto";import{promisify as Jo}from"util";var ul=Jo(Do);import{homedir as Fo}from"os";import{basename as Go,extname as zo,join as jo,resolve as Vo}from"path";import qo from"tar";function W(e){console.log(JSON.stringify(e,null,2))}async function Re(e,t,r){let o=t.source,n=De(o);if(n)try{console.log("Saving source code...");let a=await e.createAttachment(n,Go(o),Zo(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 Pt(e,t,r){let o=t.dist??t.source,n=De(o);if(n)try{console.log("Deploying bot...");let a=await e.post(e.fhirUrl("Bot",r.id,"$deploy"),{code:n});console.log("Deploy result: "+a.issue?.[0]?.details?.text)}catch(a){console.log("Deploy error: ",a)}}async function Me(e,t){if(t.length<4){console.log("Error: command needs to be npx medplum <new-bot-name> <project-id> <source-file> <dist-file>");return}let r=t[0],o=t[1],n=t[2],a=t[3];try{let s={name:r,description:""},c=await e.post("admin/projects/"+o+"/bot",s),p=await e.readResource("Bot",c.id),f={name:r,id:c.id,source:n,dist:a};await Re(e,f,p),console.log(`Success! Bot created: ${p.id}`),Xo(f)}catch(s){console.log("Error while creating new bot: "+s)}}function _t(e){let t=new RegExp("^"+Yo(e).replace(/\\\*/g,".*")+"$"),r=le()?.bots?.filter(o=>t.test(o.name));return r||[]}function le(e){let t=e?`medplum.${e}.config.json`:"medplum.config.json",r=De(t);if(r)return JSON.parse(r)}function De(e){let t=Vo(process.cwd(),e);return $o(t)?xt(t,"utf8"):(console.log("Error: File does not exist: "+t),"")}function Xo(e){let t=le();t?.bots?.push(e),Bo("medplum.config.json",JSON.stringify(t),()=>{console.log(`Bot added to config: ${e.id}`)})}function Yo(e){return e.replace(/[/\-\\^$*+?.()|[\]{}]/g,"\\$&")}function Kt(e){let o=0,n=0;return qo.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 Je(){return{extension:[{url:"http://hl7.org/fhir/StructureDefinition/data-absent-reason",valueCode:"unsupported"}]}}function Zo(e){let t=zo(e).toLowerCase();return[".cjs",".mjs",".js"].includes(t)?We.JAVASCRIPT:[".cts",".mts",".ts"].includes(t)?We.TYPESCRIPT:We.TEXT}function fe(e,t){let r=new E(e),o={name:e,...t};r.setObject("options",o),console.log(`${e} profile created`)}function he(e){return new E(e).getObject("options")}function Tt(e,t){return t==="default"?!0:!!e.getObject("options")}async function It(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=At(JSON.stringify(r)),s=At(JSON.stringify(n)),c=`${a}.${s}`,p=No("sha256",t.clientSecret).update(c).digest("base64url"),f=`${c}.${p}`,y=new URLSearchParams;y.set("grant_type","urn:ietf:params:oauth:grant-type:jwt-bearer"),y.set("client_id",t.clientId),y.set("assertion",f),y.set("scope",t.scope??"");let T=await e.post(t.tokenUrl,y.toString(),"application/x-www-form-urlencoded",{credentials:"include"});return(await JSON.parse(T)).access_token}async function Ht(e,t){let r=Fo(),o=jo(r,t.privateKeyPath),n=xt(o),a=Uo(n),s=await new ee({}).setProtectedHeader({alg:"RS384",typ:"JWT"}).setIssuer(t.clientId).setSubject(t.clientId).setAudience(`${t.baseUrl}${t.audience}`).setJti(Lo(16).toString("hex")).setIssuedAt().setExpirationTime("5m").sign(a),c=new URLSearchParams;c.append("grant_type","client_credentials"),c.append("client_assertion_type","urn:ietf:params:oauth:client-assertion-type:jwt-bearer"),c.append("client_assertion",s);let p=await e.post(t.tokenUrl,c.toString(),"application/x-www-form-urlencoded",{credentials:"include"});if(!p.access_token)throw new Error(`Failed to login: ${p}`);return p.access_token}var kt="medplum-cli",Ot="http://localhost:9615",Ue=m("login"),Le=m("whoami");Ue.action(async e=>{let t=e.profile??"default",r=new E(t);if(Tt(r,t)||(console.log("Creating new profile..."),fe(t,e)),e.authType==="basic"){console.log("Basic authentication does not require login");return}let o=he(t),n=await u(e);await nn(n,o)});Le.action(async e=>{let t=await u(e);cn(t)});async function nn(e,t){if(!t?.authType){await dn(e);return}if(t.authType==="jwt-bearer"){if(!t.clientId||!t.clientSecret)throw new Error("Missing values, make sure to add --client-id, and --client-secret for JWT Bearer login");console.log("Starting JWT login...");let r=await It(e,t);new E(t.name).setObject("activeLogin",{accessToken:r})}else if(t.authType==="jwt-assertion"){let r=await Ht(e,t);new E(t.name).setObject("activeLogin",{accessToken:r})}console.log("Login successful")}async function an(e){let t=rn(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:kt,redirectUri:Ot});o.writeHead(200,{"Content-Type":Ne.TEXT}),o.end(`Signed in as ${Qo(s)}. You may close this window.`)}catch(s){o.writeHead(400,{"Content-Type":Ne.TEXT}),o.end(`Error: ${en(s)}`)}finally{t.close()}else o.writeHead(404,{"Content-Type":Ne.TEXT}),o.end("Not found")}).listen(9615)}async function sn(e){let t=on(),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)}tn(r)}function cn(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 dn(e){await an(e);let t=new URL(e.getAuthorizeUrl());t.searchParams.set("client_id",kt),t.searchParams.set("redirect_uri",Ot),t.searchParams.set("scope","openid"),t.searchParams.set("response_type","code"),t.searchParams.set("prompt","login"),await sn(t.toString())}import{Command as si}from"commander";import{CloudFormationClient as pn,DescribeStackResourcesCommand as mn,DescribeStacksCommand as un,ListStacksCommand as ln}from"@aws-sdk/client-cloudformation";import{CloudFrontClient as fn}from"@aws-sdk/client-cloudfront";import{ECSClient as hn}from"@aws-sdk/client-ecs";import{S3Client as yn}from"@aws-sdk/client-s3";var $e=new pn({}),Wt=new fn({}),Rt=new hn({}),Mt=new yn({}),gn="medplum:environment";async function Be(){return(await $e.send(new ln({}))).StackSummaries?.filter(t=>t.StackName&&t.StackStatus!=="DELETE_COMPLETE")||[]}async function j(e){let t=await Be();for(let r of t){let o=r.StackName,n=await Fe(o);if(n?.tag===e)return n}}async function Fe(e){let t=new un({StackName:e}),o=(await $e.send(t))?.Stacks?.[0],n=o?.Tags?.find(c=>c.Key===gn);if(!n)return;let a=await $e.send(new mn({StackName:e}));if(!a.StackResources)return;let s={stack:o,tag:n.Value};for(let c of a.StackResources)c.ResourceType==="AWS::ECS::Cluster"?s.ecsCluster=c:c.ResourceType==="AWS::ECS::Service"?s.ecsService=c:c.ResourceType==="AWS::S3::Bucket"&&c.LogicalResourceId?.startsWith("FrontEndAppBucket")?s.appBucket=c:c.ResourceType==="AWS::S3::Bucket"&&c.LogicalResourceId?.startsWith("StorageStorageBucket")?s.storageBucket=c:c.ResourceType==="AWS::CloudFront::Distribution"&&c.LogicalResourceId?.startsWith("FrontEndAppDistribution")&&(s.appDistribution=c);return s}function ye(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: ${Ge(e.ecsService)}`),console.log(`App Bucket: ${e.appBucket?.PhysicalResourceId}`),console.log(`Storage Bucket: ${e.storageBucket?.PhysicalResourceId}`)}function Ge(e){return e?.PhysicalResourceId?.split("/")?.pop()||""}async function Dt(e){let t=await j(e);if(!t){console.log("Stack not found");return}ye(t)}import{ACMClient as Ut,ListCertificatesCommand as wn,RequestCertificateCommand as Sn}from"@aws-sdk/client-acm";import{CloudFrontClient as En,CreatePublicKeyCommand as bn}from"@aws-sdk/client-cloudfront";import{GetParameterCommand as Cn,PutParameterCommand as vn,SSMClient as An}from"@aws-sdk/client-ssm";import{GetCallerIdentityCommand as xn,STSClient as Pn}from"@aws-sdk/client-sts";import{generateKeyPairSync as _n,randomUUID as Jt}from"crypto";import{existsSync as Kn,writeFileSync as Tn}from"fs";import{resolve as In}from"path";import Hn from"readline";var kn=e=>`${e}DomainName`,Lt=e=>`${e}SslCertArn`,we;async function $t(){let e={apiPort:8103,region:"us-east-1"};we=Hn.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 On(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 ge("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 K("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 K("What is the config file name?",`medplum.${e.name}.config.json`);Kn(r)&&(i("Config file already exists."),await ge("Do you want to overwrite the config file?")),i('Using config file "'+r+'"...'),g(r,e),h("AWS REGION"),i("Most Medplum resources will be created in a single AWS region."),e.region=await K("Enter your AWS region:","us-east-1"),g(r,e),h("AWS ACCOUNT NUMBER"),i("Medplum Infrastructure will use your AWS account number to create AWS resources."),t&&i("Using the AWS CLI, your current account ID is: "+t),e.accountNumber=await K("What is your AWS account number?",t),g(r,e),h("STACK NAME"),i("Medplum will create a CloudFormation stack to manage AWS resources."),i("AWS CloudFormation stack names ");let o="Medplum"+e.name.charAt(0).toUpperCase()+e.name.slice(1);for(e.stackName=await K("Enter your CloudFormation stack name?",o),g(r,e),h("BASE DOMAIN NAME"),i("Please enter the base domain name for your Medplum deployment."),i(""),i("Medplum deploys multiple subdomains for various services."),i(""),i('For example, "api." for the REST API and "app." for the web application.'),i("The base domain name is the common suffix for all subdomains."),i(""),i('For example, if your base domain name is "example.com",'),i('then the REST API will be "api.example.com".'),i(""),i('The base domain should include the TLD (i.e., ".com", ".org", ".net").'),i(""),i("Note that you must own the base domain, and it must use Route53 DNS.");!e.domainName;)e.domainName=await K("Enter your base domain name:");g(r,e),h("SUPPORT EMAIL"),i("Medplum sends transactional emails to users."),i("For example, emails to new users or for password reset."),i("Medplum will use the support email address to send these emails."),i("Note that you must verify the support email address in SES.");let n=await K("Enter your support email address:");h("API DOMAIN NAME"),i("Medplum deploys a REST API for the backend services."),e.apiDomainName=await K("Enter your REST API domain name:","api."+e.domainName),e.baseUrl=`https://${e.apiDomainName}/`,g(r,e),h("APP DOMAIN NAME"),i("Medplum deploys a web application for the user interface."),e.appDomainName=await K("Enter your web application domain name:","app."+e.domainName),g(r,e),h("STORAGE DOMAIN NAME"),i("Medplum deploys a storage service for file uploads."),e.storageDomainName=await K("Enter your storage domain name:","storage."+e.domainName),g(r,e),h("STORAGE BUCKET"),i("Medplum uses an S3 bucket to store binary content such as file uploads."),i("Medplum will create a the S3 bucket as part of the CloudFormation stack."),e.storageBucketName=await K("Enter your storage bucket name:","medplum-"+e.name+"-storage"),g(r,e),h("MAX AVAILABILITY ZONES"),i("Medplum API servers can be deployed in multiple availability zones."),i("This provides redundancy and high availability."),i("However, it also increases the cost of the deployment."),i("If you want to use all availability zones, choose a large number such as 99."),i("If you want to restrict the number, for example to manage EIP limits,"),i("then choose a small number such as 1 or 2."),e.maxAzs=await te("Enter the maximum number of availability zones:",[1,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 je("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 te("Enter the number of database instances:",[1,2],1)):(i("Medplum will not create a new RDS database."),i("Please create a new RDS database and enter the database name, username, and password."),i('Set the AWS Secrets Manager secret ARN in the config file in the "rdsSecretsArn" setting.'),e.rdsSecretsArn="TODO"),g(r,e),h("SERVER INSTANCES"),i("Medplum uses AWS Fargate to run the API servers."),i("Medplum will create a new Fargate cluster as part of the CloudFormation stack."),i("Fargate will automatically scale the number of servers up and down."),i("If you need high availability, you can choose multiple instances."),e.desiredServerCount=await te("Enter the number of server instances:",[1,2,3,4,6,8],1),g(r,e),h("SERVER MEMORY"),i("You can choose the amount of memory for each server instance."),i("The default is 512 MB, which is sufficient for getting started."),i("Note that only certain CPU units are compatible with memory units."),i('Consult AWS Fargate "Task Definition Parameters" for more information.'),e.serverMemory=await te("Enter the server memory (MB):",[512,1024,2048,4096,8192,16384],512),g(r,e),h("SERVER CPU"),i("You can choose the amount of CPU for each server instance."),i("CPU is expressed as an integer using AWS CPU units"),i("The default is 256, which is sufficient for getting started."),i("Note that only certain CPU units are compatible with memory units."),i('Consult AWS Fargate "Task Definition Parameters" for more information.'),e.serverCpu=await te("Enter the server CPU:",[256,512,1024,2048,4096,8192,16384],256),g(r,e),h("SERVER IMAGE"),i("Medplum uses Docker images for the API servers."),i("You can choose the image to use for the servers."),i("Docker images can be loaded from either Docker Hub or AWS ECR."),i("The default is the latest Medplum release."),e.serverImage=await K("Enter the server image:","medplum/medplum-server:latest"),g(r,e),h("SIGNING KEY"),i("Medplum uses AWS CloudFront Presigned URLs for binary content such as file uploads.");let{keyId:a,privateKey:s,publicKey:c,passphrase:p}=await Dn(e.stackName+"SigningKey");e.signingKeyId=a,e.storagePublicKey=c,g(r,e),h("SSL CERTIFICATES"),i("Medplum will now check for existing SSL certificates for the subdomains.");let f=await Wn(e.region);i("Found "+f.length+" certificate(s).");for(let{region:T,certName:I}of[{region:e.region,certName:"api"},{region:"us-east-1",certName:"app"},{region:"us-east-1",certName:"storage"}]){i("");let lr=await Rn(e,f,T,I);e[Lt(I)]=lr,g(r,e)}h("AWS PARAMETER STORE"),i("Medplum uses AWS Parameter Store to store sensitive configuration values."),i("These values will be encrypted at rest."),i(`The values will be stored in the "/medplum/${e.name}" path.`);let y={port:e.apiPort,baseUrl:e.baseUrl,appBaseUrl:`https://${e.appDomainName}/`,storageBaseUrl:`https://${e.storageDomainName}/binary/`,binaryStorage:`s3:${e.storageBucketName}`,signingKeyId:e.signingKeyId,signingKey:s,signingKeyPassphrase:p,supportEmail:n};i(JSON.stringify({...y,signingKey:"****",signingKeyPassphrase:"****"},null,2)),await ge("Do you want to store these values in AWS Parameter Store?"),await Un(e.region,`/medplum/${e.name}/`,y),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(""),we.close()}function i(e){we.write(e+`
2
+ var ot=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,r)=>(typeof require<"u"?require:t)[r]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});import{MEDPLUM_VERSION as xi,normalizeErrorString as Pi}from"@medplum/core";import{Command as _i}from"commander";import Ki from"dotenv";import{ContentType as Ne,getDisplayString as Yo,normalizeErrorString as Zo}from"@medplum/core";import{exec as Qo}from"child_process";import{createServer as en}from"http";import{platform as tn}from"os";import{ClientStorage as hr}from"@medplum/core";import{existsSync as nt,mkdirSync as yr,readFileSync as gr,writeFileSync as wr}from"fs";import{homedir as Sr}from"os";import{resolve as it}from"path";var _=class extends hr{constructor(r){super();this.dirName=it(Sr(),".medplum"),this.fileName=it(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(nt(this.fileName))return JSON.parse(gr(this.fileName,"utf8"))}writeFile(r){nt(this.dirName)||yr(this.dirName),wr(this.fileName,JSON.stringify(r,null,2),"utf8")}};import{MedplumClient as Er}from"@medplum/core";async function u(e){let t=e.profile??"default",r=new _(t),o=r.getObject("options");if(t!=="default"&&!o)throw new Error(`Profile "${t}" does not exist`);let{baseUrl:n,fhirUrlPath:a,accessToken:s,tokenUrl:c,authorizeUrl:m,clientId:f,clientSecret:I}=br(e,r),H=e.fetch??fetch,K=new Er({fetch:H,baseUrl:n,tokenUrl:c,fhirUrlPath:a,authorizeUrl:m,storage:r,onUnauthenticated:Cr,verbose:e.verbose});return s&&K.setAccessToken(s),o?.authType==="client_credentials"?(K.setBasicAuth(f,I),await K.startClientLogin(f,I)):o?.authType==="basic"&&K.setBasicAuth(f,I),K}function br(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,m=e.clientId??r?.clientId??process.env.MEDPLUM_CLIENT_ID,f=e.clientSecret??r?.clientSecret??process.env.MEDPLUM_CLIENT_SECRET;return{baseUrl:o,fhirUrlPath:n,accessToken:a,tokenUrl:s,authorizeUrl:c,clientId:m,clientSecret:f}}function Cr(){console.log("Unauthenticated: run `npx medplum login` to sign in")}import{Command as vr,Option as Ar}from"commander";function p(e){return new vr(e).option("--client-id <clientId>","FHIR server client id").option("--client-secret <clientSecret>","FHIR server client secret").option("--base-url <baseUrl>","FHIR server base URL, must be absolute").option("--token-url <tokenUrl>","FHIR server token URL, absolute or relative to base URL").option("--authorize-url <authorizeUrl>","FHIR server authorize URL, absolute or relative to base URL").option("--fhir-url, --fhir-url-path <fhirUrlPath>","FHIR server URL, absolute or relative to base URL").option("--scope <scope>","JWT scope").option("--access-token <accessToken>","Access token for token exchange authentication").option("--callback-url <callbackUrl>","Callback URL for authorization code flow").option("--subject <subject>","Subject for JWT authentication").option("--audience <audience>","Audience for JWT authentication").option("--issuer <issuer>","Issuer for JWT authentication").option("--private-key-path <privateKeyPath>","Private key path for JWT assertion").option("--audience <audience>","Audience for JWT assertion").option("-p, --profile <profile>","Profile name").option("-v --verbose","Verbose output").addOption(new Ar("--auth-type <authType>","Type of authentication").choices(["basic","client-credentials","authorization-code","jwt-bearer","token-exchange","jwt-assertion"]))}import{ContentType as We,encodeBase64 as At}from"@medplum/core";import{createHmac as Uo,createPrivateKey as Lo,randomBytes as $o}from"crypto";import{existsSync as Bo,readFileSync as xt,writeFile as Fo}from"fs";import{Buffer as be}from"buffer";var C=new TextEncoder,S=new TextDecoder,Gi=2**32;function T(...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 g;be.isEncoding("base64url")?g=e=>be.from(e).toString("base64url"):g=e=>be.from(e).toString("base64").replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_");var U=class extends Error{static get code(){return"ERR_JOSE_GENERIC"}constructor(t){var r;super(t),this.code="ERR_JOSE_GENERIC",this.name=this.constructor.name,(r=Error.captureStackTrace)===null||r===void 0||r.call(Error,this,this.constructor)}};var d=class extends U{constructor(){super(...arguments),this.code="ERR_JOSE_NOT_SUPPORTED"}static get code(){return"ERR_JOSE_NOT_SUPPORTED"}};var v=class extends U{constructor(){super(...arguments),this.code="ERR_JWS_INVALID"}static get code(){return"ERR_JWS_INVALID"}},O=class extends U{constructor(){super(...arguments),this.code="ERR_JWT_INVALID"}static get code(){return"ERR_JWT_INVALID"}};import{KeyObject as _r}from"crypto";import*as ve from"util";var A=ve.types.isKeyObject?e=>ve.types.isKeyObject(e):e=>e!=null&&e instanceof _r;import*as st from"crypto";import*as Ae from"util";var Kr=st.webcrypto,oe=Kr,E=Ae.types.isCryptoKey?e=>Ae.types.isCryptoKey(e):e=>!1;function M(e,t="algorithm.name"){return new TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`)}function ne(e,t){return e.name===t}function xe(e){return parseInt(e.name.slice(4),10)}function Tr(e){switch(e){case"ES256":return"P-256";case"ES384":return"P-384";case"ES512":return"P-521";default:throw new Error("unreachable")}}function Ir(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 ct(e,t,...r){switch(t){case"HS256":case"HS384":case"HS512":{if(!ne(e.algorithm,"HMAC"))throw M("HMAC");let o=parseInt(t.slice(2),10);if(xe(e.algorithm.hash)!==o)throw M(`SHA-${o}`,"algorithm.hash");break}case"RS256":case"RS384":case"RS512":{if(!ne(e.algorithm,"RSASSA-PKCS1-v1_5"))throw M("RSASSA-PKCS1-v1_5");let o=parseInt(t.slice(2),10);if(xe(e.algorithm.hash)!==o)throw M(`SHA-${o}`,"algorithm.hash");break}case"PS256":case"PS384":case"PS512":{if(!ne(e.algorithm,"RSA-PSS"))throw M("RSA-PSS");let o=parseInt(t.slice(2),10);if(xe(e.algorithm.hash)!==o)throw M(`SHA-${o}`,"algorithm.hash");break}case"EdDSA":{if(e.algorithm.name!=="Ed25519"&&e.algorithm.name!=="Ed448")throw M("Ed25519 or Ed448");break}case"ES256":case"ES384":case"ES512":{if(!ne(e.algorithm,"ECDSA"))throw M("ECDSA");let o=Tr(t);if(e.algorithm.namedCurve!==o)throw M(o,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}Ir(e,r)}function dt(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)=>dt("Key must be ",e,...t);function Pe(e,t,...r){return dt(`Key for the ${e} algorithm must be `,t,...r)}var _e=e=>A(e)||E(e),l=["KeyObject"];(globalThis.CryptoKey||!(oe===null||oe===void 0)&&oe.CryptoKey)&&l.push("CryptoKey");import{promisify as mt}from"util";import{inflateRaw as Or,deflateRaw as kr}from"zlib";var Oa=mt(Or),ka=mt(kr);var Dr=(...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},L=Dr;function Jr(e){return typeof e=="object"&&e!==null}function w(e){if(!Jr(e)||Object.prototype.toString.call(e)!=="[object Object]")return!1;if(Object.getPrototypeOf(e)===null)return!0;let t=e;for(;Object.getPrototypeOf(t)!==null;)t=Object.getPrototypeOf(t);return Object.getPrototypeOf(e)===t}import{diffieHellman as ss,generateKeyPair as zr,KeyObject as cs}from"crypto";import{promisify as Vr}from"util";import{Buffer as ie}from"buffer";import{createPublicKey as Nr,KeyObject as Ur}from"crypto";var Lr=ie.from([42,134,72,206,61,3,1,7]),$r=ie.from([43,129,4,0,34]),Br=ie.from([43,129,4,0,35]),Fr=ie.from([43,129,4,0,10]),Ke=new WeakMap,Gr=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 d("Unsupported key curve for this operation")}},ut=(e,t)=>{var r;let o;if(E(e))o=Ur.from(e);else if(A(e))o=e;else throw new TypeError(x(e,...l));if(o.type==="secret")throw new TypeError('only "private" or "public" type keys can be used for this operation');switch(o.asymmetricKeyType){case"ed25519":case"ed448":return`Ed${o.asymmetricKeyType.slice(2)}`;case"x25519":case"x448":return`X${o.asymmetricKeyType.slice(1)}`;case"ec":{if(Ke.has(o))return Ke.get(o);let n=(r=o.asymmetricKeyDetails)===null||r===void 0?void 0:r.namedCurve;if(!n&&o.type==="private")n=ut(Nr(o),!0);else if(!n){let s=o.export({format:"der",type:"spki"}),c=s[1]<128?14:15,m=s[c],f=s.slice(c+1,c+1+m);if(f.equals(Lr))n="prime256v1";else if(f.equals($r))n="secp384r1";else if(f.equals(Br))n="secp521r1";else if(f.equals(Fr))n="secp256k1";else throw new d("Unsupported key curve for this operation")}if(t)return n;let a=Gr(n);return Ke.set(o,a),a}default:throw new TypeError("Invalid asymmetric key type for this operation")}};var ae=ut;var ws=Vr(zr);import{promisify as Xr}from"util";import{KeyObject as xs,pbkdf2 as Yr}from"crypto";var ks=Xr(Yr);var Te=new WeakMap,se=(e,t)=>{let r=e.readUInt8(1);if(!(r&128))return t===0?r:se(e.subarray(2+r),t-1);let o=r&127;r=0;for(let n=0;n<o;n++){r<<=8;let a=e.readUInt8(2+n);r|=a}return t===0?r:se(e.subarray(2+r),t-1)},Zr=(e,t)=>{let r=e.readUInt8(1);if(!(r&128))return se(e.subarray(2),t);let o=r&127;return se(e.subarray(2+o),t)},Qr=e=>{var t,r;if(Te.has(e))return Te.get(e);let o=(r=(t=e.asymmetricKeyDetails)===null||t===void 0?void 0:t.modulusLength)!==null&&r!==void 0?r:Zr(e.export({format:"der",type:"pkcs1"}),e.type==="private"?1:0)-1<<3;return Te.set(e,o),o};var q=(e,t)=>{if(Qr(e)<2048)throw new TypeError(`${t} requires key modulusLength to be 2048 bits or larger`)};import{Buffer as b}from"buffer";var eo=2,to=3,ro=4,oo=48,rc=b.from([0]),oc=b.from([eo]),nc=b.from([to]),ic=b.from([oo]),ac=b.from([ro]);var sc=new Map([["P-256",b.from("06 08 2A 86 48 CE 3D 03 01 07".replace(/ /g,""),"hex")],["secp256k1",b.from("06 05 2B 81 04 00 0A".replace(/ /g,""),"hex")],["P-384",b.from("06 05 2B 81 04 00 22".replace(/ /g,""),"hex")],["P-521",b.from("06 05 2B 81 04 00 23".replace(/ /g,""),"hex")],["ecPublicKey",b.from("06 07 2A 86 48 CE 3D 02 01".replace(/ /g,""),"hex")],["X25519",b.from("06 03 2B 65 6E".replace(/ /g,""),"hex")],["X448",b.from("06 03 2B 65 6F".replace(/ /g,""),"hex")],["Ed25519",b.from("06 03 2B 65 70".replace(/ /g,""),"hex")],["Ed448",b.from("06 03 2B 65 71".replace(/ /g,""),"hex")]]);var[D,ce]=process.versions.node.split(".").map(e=>parseInt(e,10)),ft=D>=16||D===15&&ce>=13,J=!("electron"in process.versions)&&(D>=17||D===16&&ce>=9),no=D>=16||D===15&&ce>=9,io=D>=16||D===15&&ce>=12;var so=(e,t)=>{if(!(t instanceof Uint8Array)){if(!_e(t))throw new TypeError(Pe(e,t,...l,"Uint8Array"));if(t.type!=="secret")throw new TypeError(`${l.join(" or ")} instances for symmetric algorithms must be of type "secret"`)}},co=(e,t,r)=>{if(!_e(t))throw new TypeError(Pe(e,t,...l));if(t.type==="secret")throw new TypeError(`${l.join(" or ")} instances for asymmetric algorithms must not be of type "secret"`);if(r==="sign"&&t.type==="public")throw new TypeError(`${l.join(" or ")} instances for asymmetric algorithm signing must be of type "private"`);if(r==="decrypt"&&t.type==="public")throw new TypeError(`${l.join(" or ")} instances for asymmetric algorithm decryption must be of type "private"`);if(t.algorithm&&r==="verify"&&t.type==="private")throw new TypeError(`${l.join(" or ")} instances for asymmetric algorithm verifying must be of type "public"`);if(t.algorithm&&r==="encrypt"&&t.type==="private")throw new TypeError(`${l.join(" or ")} instances for asymmetric algorithm encryption must be of type "public"`)},po=(e,t,r)=>{e.startsWith("HS")||e==="dir"||e.startsWith("PBES2")||/^A\d{3}(?:GCM)?KW$/.test(e)?so(e,t):co(e,t,r)},X=po;function go(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 d(`Extension Header Parameter "${s}" is not recognized`);if(n[s]===void 0)throw new e(`Extension Header Parameter "${s}" is missing`);if(a.get(s)&&o[s]===void 0)throw new e(`Extension Header Parameter "${s}" MUST be integrity protected`)}return new Set(o.crit)}var B=go;var Co=Symbol();import*as Y from"crypto";import{promisify as _o}from"util";function de(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 d(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}import{constants as wt}from"crypto";var St={padding:wt.RSA_PKCS1_PSS_PADDING,saltLength:wt.RSA_PSS_SALTLEN_DIGEST},vo=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 q(t,e),t;case(J&&"PS256"):case(J&&"PS384"):case(J&&"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 q(t,e),{key:t,...St};case(!J&&"PS256"):case(!J&&"PS384"):case(!J&&"PS512"):if(t.asymmetricKeyType!=="rsa")throw new TypeError("Invalid key for this operation, its asymmetricKeyType must be rsa");return q(t,e),{key:t,...St};case"ES256":case"ES256K":case"ES384":case"ES512":{if(t.asymmetricKeyType!=="ec")throw new TypeError("Invalid key for this operation, its asymmetricKeyType must be ec");let r=ae(t),o=vo.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 d(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}import*as F from"crypto";import{promisify as xo}from"util";function He(e){switch(e){case"HS256":return"sha256";case"HS384":return"sha384";case"HS512":return"sha512";default:throw new d(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}import{KeyObject as Et,createSecretKey as Ao}from"crypto";function me(e,t,r){if(t instanceof Uint8Array){if(!e.startsWith("HS"))throw new TypeError(x(t,...l));return Ao(t)}if(t instanceof Et)return t;if(E(t))return ct(t,e,r),Et.from(t);throw new TypeError(x(t,...l,"Uint8Array"))}var Re;F.sign.length>3?Re=xo(F.sign):Re=F.sign;var Po=async(e,t,r)=>{let o=me(e,t,"sign");if(e.startsWith("HS")){let n=F.createHmac(He(e),o);return n.update(r),n.digest()}return Re(de(e),r,pe(e,o))},Me=Po;var bt;Y.verify.length>4&&ft?bt=_o(Y.verify):bt=Y.verify;var Z=e=>Math.floor(e.getTime()/1e3);var To=/^(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)$/i,ue=e=>{let t=To.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 G=class{constructor(t){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 v("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");if(!L(this._protectedHeader,this._unprotectedHeader))throw new v("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let o={...this._protectedHeader,...this._unprotectedHeader},n=B(v,new Map([["b64",!0]]),r?.crit,this._protectedHeader,o),a=!0;if(n.has("b64")&&(a=this._protectedHeader.b64,typeof a!="boolean"))throw new v('The "b64" (base64url-encode payload) Header Parameter must be a boolean');let{alg:s}=o;if(typeof s!="string"||!s)throw new v('JWS "alg" (Algorithm) Header Parameter missing or invalid');X(s,t,"sign");let c=this._payload;a&&(c=C.encode(g(c)));let m;this._protectedHeader?m=C.encode(g(JSON.stringify(this._protectedHeader))):m=C.encode("");let f=T(m,C.encode("."),c),I=await Me(s,t,f),H={signature:g(I),payload:""};return a&&(H.payload=S.decode(c)),this._unprotectedHeader&&(H.header=this._unprotectedHeader),this._protectedHeader&&(H.protected=S.decode(m)),H}};var Q=class{constructor(t){this._flattened=new G(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}`}};var z=class{constructor(t){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:t}:this._payload={...this._payload,nbf:Z(new Date)+ue(t)},this}setExpirationTime(t){return typeof t=="number"?this._payload={...this._payload,exp:t}:this._payload={...this._payload,exp:Z(new Date)+ue(t)},this}setIssuedAt(t){return typeof t>"u"?this._payload={...this._payload,iat:Z(new Date)}:this._payload={...this._payload,iat:t},this}};var ee=class extends z{setProtectedHeader(t){return this._protectedHeader=t,this}async sign(t,r){var o;let n=new Q(C.encode(JSON.stringify(this._payload)));if(n.setProtectedHeader(this._protectedHeader),Array.isArray((o=this._protectedHeader)===null||o===void 0?void 0:o.crit)&&this._protectedHeader.crit.includes("b64")&&this._protectedHeader.b64===!1)throw new O("JWTs MUST NOT use unencoded payload");return n.sign(t,r)}};import{createSecretKey as il,generateKeyPair as Jo}from"crypto";import{promisify as No}from"util";var pl=No(Jo);import{basename as Go,extname as zo,resolve as Pt}from"path";import Vo from"tar";function W(e){console.log(JSON.stringify(e,null,2))}async function Oe(e,t,r){let o=t.source,n=De(o);if(n)try{console.log("Saving source code...");let a=await e.createAttachment(n,Go(o),Xo(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 _t(e,t,r){let o=t.dist??t.source,n=De(o);if(n)try{console.log("Deploying bot...");let a=await e.post(e.fhirUrl("Bot",r.id,"$deploy"),{code:n});console.log("Deploy result: "+a.issue?.[0]?.details?.text)}catch(a){console.log("Deploy error: ",a)}}async function ke(e,t){if(t.length<4){console.log("Error: command needs to be npx medplum <new-bot-name> <project-id> <source-file> <dist-file>");return}let r=t[0],o=t[1],n=t[2],a=t[3];try{let s={name:r,description:""},c=await e.post("admin/projects/"+o+"/bot",s),m=await e.readResource("Bot",c.id),f={name:r,id:c.id,source:n,dist:a};await Oe(e,f,m),console.log(`Success! Bot created: ${m.id}`),jo(f)}catch(s){console.log("Error while creating new bot: "+s)}}function Kt(e){let t=new RegExp("^"+qo(e).replace(/\\\*/g,".*")+"$"),r=le()?.bots?.filter(o=>t.test(o.name));return r||[]}function le(e){let t=e?`medplum.${e}.config.json`:"medplum.config.json",r=De(t);if(r)return JSON.parse(r)}function De(e){let t=Pt(process.cwd(),e);return Bo(t)?xt(t,"utf8"):(console.log("Error: File does not exist: "+t),"")}function jo(e){let t=le();t?.bots?.push(e),Fo("medplum.config.json",JSON.stringify(t),()=>{console.log(`Bot added to config: ${e.id}`)})}function qo(e){return e.replace(/[/\-\\^$*+?.()|[\]{}]/g,"\\$&")}function Tt(e){let o=0,n=0;return Vo.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 Je(){return{extension:[{url:"http://hl7.org/fhir/StructureDefinition/data-absent-reason",valueCode:"unsupported"}]}}function Xo(e){let t=zo(e).toLowerCase();return[".cjs",".mjs",".js"].includes(t)?We.JAVASCRIPT:[".cts",".mts",".ts"].includes(t)?We.TYPESCRIPT:We.TEXT}function fe(e,t){let r=new _(e),o={name:e,...t};r.setObject("options",o),console.log(`${e} profile created`)}function he(e){return new _(e).getObject("options")}function It(e,t){return t==="default"?!0:!!e.getObject("options")}async function Ht(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=At(JSON.stringify(r)),s=At(JSON.stringify(n)),c=`${a}.${s}`,m=Uo("sha256",t.clientSecret).update(c).digest("base64url"),f=`${c}.${m}`;await e.startJwtBearerLogin(t.clientId,f,t.scope??"")}async function Rt(e,t){let r=Lo(xt(Pt(t.privateKeyPath))),o=await new ee({}).setProtectedHeader({alg:"RS384",typ:"JWT"}).setIssuer(t.clientId).setSubject(t.clientId).setAudience(`${t.baseUrl}${t.audience}`).setJti($o(16).toString("hex")).setIssuedAt().setExpirationTime("5m").sign(r);await e.startJwtAssertionLogin(o)}var Mt="medplum-cli",Wt="http://localhost:9615",Ue=p("login"),Le=p("whoami");Ue.action(async e=>{let t=e.profile??"default",r=new _(t);if(It(r,t)||(console.log("Creating new profile..."),fe(t,e)),e.authType==="basic"){console.log("Basic authentication does not require login");return}let o=he(t),n=await u(e);await rn(n,o)});Le.action(async e=>{let t=await u(e);an(t)});async function rn(e,t){if(!t?.authType){await sn(e);return}if(t.authType==="jwt-bearer"){if(!t.clientId||!t.clientSecret)throw new Error("Missing values, make sure to add --client-id, and --client-secret for JWT Bearer login");console.log("Starting JWT login..."),await Ht(e,t)}else t.authType==="jwt-assertion"&&await Rt(e,t);console.log("Login successful")}async function on(e){let t=en(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:Mt,redirectUri:Wt});o.writeHead(200,{"Content-Type":Ne.TEXT}),o.end(`Signed in as ${Yo(s)}. You may close this window.`)}catch(s){o.writeHead(400,{"Content-Type":Ne.TEXT}),o.end(`Error: ${Zo(s)}`)}finally{t.close()}else o.writeHead(404,{"Content-Type":Ne.TEXT}),o.end("Not found")}).listen(9615)}async function nn(e){let t=tn(),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)}Qo(r)}function an(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 sn(e){await on(e);let t=new URL(e.getAuthorizeUrl());t.searchParams.set("client_id",Mt),t.searchParams.set("redirect_uri",Wt),t.searchParams.set("scope","openid"),t.searchParams.set("response_type","code"),t.searchParams.set("prompt","login"),await nn(t.toString())}import{Command as ii}from"commander";import{CloudFormationClient as cn,DescribeStackResourcesCommand as dn,DescribeStacksCommand as pn,ListStacksCommand as mn}from"@aws-sdk/client-cloudformation";import{CloudFrontClient as un}from"@aws-sdk/client-cloudfront";import{ECSClient as ln}from"@aws-sdk/client-ecs";import{S3Client as fn}from"@aws-sdk/client-s3";var $e=new cn({}),Ot=new un({}),kt=new ln({}),Dt=new fn({}),hn="medplum:environment";async function Be(){return(await $e.send(new mn({}))).StackSummaries?.filter(t=>t.StackName&&t.StackStatus!=="DELETE_COMPLETE")||[]}async function V(e){let t=await Be();for(let r of t){let o=r.StackName,n=await Fe(o);if(n?.tag===e)return n}}async function Fe(e){let t=new pn({StackName:e}),o=(await $e.send(t))?.Stacks?.[0],n=o?.Tags?.find(c=>c.Key===hn);if(!n)return;let a=await $e.send(new dn({StackName:e}));if(!a.StackResources)return;let s={stack:o,tag:n.Value};for(let c of a.StackResources)c.ResourceType==="AWS::ECS::Cluster"?s.ecsCluster=c:c.ResourceType==="AWS::ECS::Service"?s.ecsService=c:c.ResourceType==="AWS::S3::Bucket"&&c.LogicalResourceId?.startsWith("FrontEndAppBucket")?s.appBucket=c:c.ResourceType==="AWS::S3::Bucket"&&c.LogicalResourceId?.startsWith("StorageStorageBucket")?s.storageBucket=c:c.ResourceType==="AWS::CloudFront::Distribution"&&c.LogicalResourceId?.startsWith("FrontEndAppDistribution")&&(s.appDistribution=c);return s}function ye(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: ${Ge(e.ecsService)}`),console.log(`App Bucket: ${e.appBucket?.PhysicalResourceId}`),console.log(`Storage Bucket: ${e.storageBucket?.PhysicalResourceId}`)}function Ge(e){return e?.PhysicalResourceId?.split("/")?.pop()||""}async function Jt(e){let t=await V(e);if(!t){console.log("Stack not found");return}ye(t)}import{ACMClient as Lt,ListCertificatesCommand as yn,RequestCertificateCommand as gn}from"@aws-sdk/client-acm";import{CloudFrontClient as wn,CreatePublicKeyCommand as Sn}from"@aws-sdk/client-cloudfront";import{GetParameterCommand as En,PutParameterCommand as bn,SSMClient as Cn}from"@aws-sdk/client-ssm";import{GetCallerIdentityCommand as vn,STSClient as An}from"@aws-sdk/client-sts";import{generateKeyPairSync as xn,randomUUID as Nt}from"crypto";import{existsSync as Pn,writeFileSync as _n}from"fs";import{resolve as Kn}from"path";import Tn from"readline";var In=e=>`${e}DomainName`,$t=e=>`${e}SslCertArn`,we;async function Bt(){let e={apiPort:8103,region:"us-east-1"};we=Tn.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 Hn(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 ge("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 P("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 P("What is the config file name?",`medplum.${e.name}.config.json`);Pn(r)&&(i("Config file already exists."),await ge("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 P("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 P("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 P("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 P("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 P("Enter your support email address:");h("API DOMAIN NAME"),i("Medplum deploys a REST API for the backend services."),e.apiDomainName=await P("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 P("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 P("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 P("Enter your storage bucket name:","medplum-"+e.name+"-storage"),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 1 or 2."),e.maxAzs=await te("Enter the maximum number of availability zones:",[1,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 Ve("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 te("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 te("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 te("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 te("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 P("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{keyId:a,privateKey:s,publicKey:c,passphrase:m}=await On(e.stackName+"SigningKey");e.signingKeyId=a,e.storagePublicKey=c,y(r,e),h("SSL CERTIFICATES"),i("Medplum will now check for existing SSL certificates for the subdomains.");let f=await Rn(e.region);i("Found "+f.length+" certificate(s).");for(let{region:H,certName:K}of[{region:e.region,certName:"api"},{region:"us-east-1",certName:"app"},{region:"us-east-1",certName:"storage"}]){i("");let fr=await Mn(e,f,H,K);e[$t(K)]=fr,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 I={port:e.apiPort,baseUrl:e.baseUrl,appBaseUrl:`https://${e.appDomainName}/`,storageBaseUrl:`https://${e.storageDomainName}/binary/`,binaryStorage:`s3:${e.storageBucketName}`,signingKeyId:e.signingKeyId,signingKey:s,signingKeyPassphrase:m,supportEmail:n};i(JSON.stringify({...I,signingKey:"****",signingKeyPassphrase:"****"},null,2)),await ge("Do you want to store these values in AWS Parameter Store?"),await Jn(e.region,`/medplum/${e.name}/`,I),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(""),we.close()}function i(e){we.write(e+`
3
3
  `)}function h(e){i(`
4
4
  `+e+`
5
- `)}function K(e,t=""){return new Promise(r=>{we.question(e+(t?" ("+t+")":"")+" ",o=>{r(o||t.toString())})})}async function ze(e,t,r=""){let o=e+" ["+t.map(n=>n===r?"("+n+")":n).join("|")+"]";for(;;){let n=await K(o)||r;if(t.includes(n))return n;i("Please choose one of the following options: "+t.join(", "))}}async function te(e,t,r){return parseInt(await ze(e,t.map(o=>o.toString()),r.toString()),10)}async function je(e){return(await ze(e,["y","n"])).toLowerCase()==="y"}async function ge(e){if(!await je(e))throw i("Exiting..."),new Error("User cancelled")}function g(e,t){Tn(In(e),JSON.stringify(t,void 0,2),"utf-8")}async function On(e){try{let t=new Pn({region:e}),r=new xn({});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 Nt(e);if(e!=="us-east-1"){let r=await Nt("us-east-1");t.push(...r)}return t}async function Nt(e){try{let t=new Ut({region:e}),r=new wn({MaxItems:1e3});return(await t.send(r)).CertificateSummaryList}catch(t){return console.log("Warning: Unable to list certificates",t.message),[]}}async function Rn(e,t,r,o){let n=e[kn(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 je("Do you want to request a new certificate?"))return i(`Please add your certificate ARN to the config file in the "${Lt(o)}" setting.`),"TODO";let s=await Mn(r,n);return i("Certificate ARN: "+s),s}async function Mn(e,t){try{let r=await ze("Validate certificate using DNS or email validation?",["dns","email"],"dns"),o=new Ut({region:e}),n=new Sn({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 Dn(e){let t=Jt(),r=_n("rsa",{modulusLength:2048,publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs1",format:"pem",cipher:"aes-256-cbc",passphrase:t}});return{keyId:(await new En({}).send(new bn({PublicKeyConfig:{Name:e,CallerReference:Jt(),EncodedKey:r.publicKey}}))).PublicKey?.Id,publicKey:r.publicKey,privateKey:r.privateKey,passphrase:t}}async function Jn(e,t){let r=new Cn({Name:t,WithDecryption:!0});try{return(await e.send(r)).Parameter?.Value}catch(o){if(o.name==="ParameterNotFound")return;throw o}}async function Nn(e,t,r){let o=new vn({Name:t,Value:r,Type:"SecureString",Overwrite:!0});await e.send(o)}async function Un(e,t,r){let o=new An({region:e});for(let[n,a]of Object.entries(r)){let s=t+n,c=a.toString(),p=await Jn(o,s);p!==void 0&&p!==c&&(i(`Parameter "${s}" exists with different value.`),await ge(`Do you want to overwrite "${s}"?`)),await Nn(o,s,c)}}async function Bt(){let e=await Be();for(let t of e){let r=t.StackName,o=await Fe(r);o&&(ye(o),console.log(""))}}import{CreateInvalidationCommand as Ln}from"@aws-sdk/client-cloudfront";import{PutObjectCommand as $n}from"@aws-sdk/client-s3";import{ContentType as k}from"@medplum/core";import Bn from"fast-glob";import{createReadStream as Fn,mkdtempSync as Gn,readdirSync as zn,readFileSync as jn,rmSync as Vn,writeFileSync as qn}from"fs";import Ft from"node-fetch";import{tmpdir as Xn}from"os";import{join as Se,sep as Yn}from"path";import{pipeline as Zn}from"stream/promises";async function Gt(e,t){let r=le(e);if(!r){console.log("Config not found");return}let o=await j(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 ei("@medplum/app","latest");zt(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 ri(a,n.PhysicalResourceId,t),o.appDistribution?.PhysicalResourceId&&!t.dryrun&&await ii(o.appDistribution.PhysicalResourceId),console.log("Done")}async function Qn(e,t){let r=`https://registry.npmjs.org/${e}/${t}`;return(await Ft(r)).json()}async function ei(e,t){let o=(await Qn(e,t)).dist.tarball,n=Gn(Se(Xn(),"tarball-"));try{let a=await Ft(o),s=Kt(n);return await Zn(a.body,s),Se(n,"package","dist")}catch(a){throw Vn(n,{recursive:!0,force:!0}),a}}function zt(e,t){for(let r of zn(e,{withFileTypes:!0})){let o=Se(e,r.name);r.isDirectory()?zt(o,t):r.isFile()&&o.endsWith(".js")&&ti(o,t)}}function ti(e,t){let r=jn(e,"utf-8");for(let[o,n]of Object.entries(t))r=r.replaceAll(`__${o}__`,n);qn(e,r)}async function ri(e,t,r){let o=[["assets/**/*.css",k.CSS,!0],["assets/**/*.css.map",k.JSON,!0],["assets/**/*.js",k.JAVASCRIPT,!0],["assets/**/*.js.map",k.JSON,!0],["assets/**/*.txt",k.TEXT,!0],["assets/**/*.ico",k.FAVICON,!0],["img/**/*.png",k.PNG,!0],["img/**/*.svg",k.SVG,!0],["robots.txt",k.TEXT,!0],["index.html",k.HTML,!1]];for(let n of o)await oi({rootDir:e,bucketName:t,fileNamePattern:n[0],contentType:n[1],cached:n[2],dryrun:r.dryrun})}async function oi(e){let t=Bn.sync(e.fileNamePattern,{cwd:e.rootDir});for(let r of t)await ni(Se(e.rootDir,r),e)}async function ni(e,t){let r=Fn(e),o=e.substring(t.rootDir.length+1).split(Yn).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 Mt.send(new $n(n))}async function ii(e){let t=await Wt.send(new Ln({DistributionId:e,InvalidationBatch:{CallerReference:`invalidate-all-${Date.now()}`,Paths:{Quantity:1,Items:["/*"]}}}));console.log(`Created invalidation with ID: ${t.Invalidation?.Id}`)}import{UpdateServiceCommand as ai}from"@aws-sdk/client-ecs";async function jt(e){let t=await j(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=Ge(t.ecsService);if(!o){console.log("ECS Service not found");return}await Rt.send(new ai({cluster:r,service:o,forceNewDeployment:!0})),console.log(`Service "${o}" updated successfully.`)}var N=new si("aws").description("Commands to manage AWS resources");N.command("init").description("Initialize a new Medplum AWS CloudFormation stacks").action($t);N.command("list").description("List Medplum AWS CloudFormation stacks").action(Bt);N.command("describe").description("Describe a Medplum AWS CloudFormation stack by tag").argument("<tag>").action(Dt);N.command("update-server").alias("deploy-server").description("Update the server image").argument("<tag>").action(jt);N.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(Gt);import{Command as ci}from"commander";var Vt=m("save"),qt=m("deploy"),Xt=m("create"),Yt=new ci("bot").addCommand(Vt).addCommand(qt).addCommand(Xt),Ve=m("save-bot"),qe=m("deploy-bot"),Xe=m("create-bot");Vt.description("Saving the bot").argument("<botName>").action(async(e,t)=>{let r=await u(t);await Ee(r,e)});qt.description("Deploy the app to AWS").argument("<botName>").action(async(e,t)=>{let r=await u(t);await Ee(r,e,!0)});Xt.arguments("<botName> <projectId> <sourceFile> <distFile>").description("Creating a bot").action(async(e,t,r,o,n)=>{let a=await u(n);await Me(a,[e,t,r,o])});async function Ee(e,t,r=!1){let o=_t(t);for(let n of o){let a=await e.readResource("Bot",n.id);await Re(e,n,a),r&&await Pt(e,n,a)}console.log(`Number of bots deployed: ${o.length}`)}Ve.description("Saves the bot").argument("<botName>").action(async(e,t)=>{let r=await u(t);await Ee(r,e)});qe.description("Deploy the bot to AWS").argument("<botName>").action(async(e,t)=>{let r=await u(t);await Ee(r,e,!0)});Xe.arguments("<botName> <projectId> <sourceFile> <distFile>").description("Creates and saves the bot").action(async(e,t,r,o,n)=>{let a=await u(n);await Me(a,[e,t,r,o])});import{Command as di}from"commander";import{createReadStream as pi,writeFile as mi}from"fs";import{resolve as Qt}from"path";import{createInterface as ui}from"readline";var er=m("export"),tr=m("import"),rr=new di("bulk").addCommand(er).addCommand(tr);er.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 f=new URL(p),y=await a.download(p),T=`${c}_${f.pathname}`.replace(/[^a-zA-Z0-9]+/g,"_")+".ndjson",I=Qt(n??"",T);mi(`${I}`,await y.text(),()=>{console.log(`${I} is created`)})})});tr.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=Qt(n??process.cwd(),e),s=await u(t);await li(a,parseInt(r,10),s,o)});async function li(e,t,r,o){let n=[],a=pi(e),s=ui({input:a});for await(let c of s){let p=fi(c,o);n.push({resource:p,request:{method:"POST",url:p.resourceType}}),n.length%t===0&&(await Zt(n,r),n=[])}n.length>0&&await Zt(n,r)}async function Zt(e,t){(await t.executeBatch({resourceType:"Bundle",type:"transaction",entry:e})).entry?.forEach(o=>{W(o.response)})}function fi(e,t){let r=JSON.parse(e);return t?hi(r):r}function hi(e){return e.resourceType==="ExplanationOfBenefit"?yi(e):e}function yi(e){return e.provider||(e.provider=Je()),e.item?.forEach(t=>{t?.productOrService||(t.productOrService=Je())}),e}import{Command as gi,Option as wi}from"commander";var or=m("list"),nr=m("current"),ir=m("switch"),ar=m("invite"),sr=new gi("project").addCommand(or).addCommand(nr).addCommand(ir).addCommand(ar);or.description("List of current projects").action(async e=>{let t=await u(e);Si(t)});function Si(e){let r=e.getLogins().map(o=>`${o.project.display} (${o.project.reference})`).join(`
5
+ `)}function P(e,t=""){return new Promise(r=>{we.question(e+(t?" ("+t+")":"")+" ",o=>{r(o||t.toString())})})}async function ze(e,t,r=""){let o=e+" ["+t.map(n=>n===r?"("+n+")":n).join("|")+"]";for(;;){let n=await P(o)||r;if(t.includes(n))return n;i("Please choose one of the following options: "+t.join(", "))}}async function te(e,t,r){return parseInt(await ze(e,t.map(o=>o.toString()),r.toString()),10)}async function Ve(e){return(await ze(e,["y","n"])).toLowerCase()==="y"}async function ge(e){if(!await Ve(e))throw i("Exiting..."),new Error("User cancelled")}function y(e,t){_n(Kn(e),JSON.stringify(t,void 0,2),"utf-8")}async function Hn(e){try{let t=new An({region:e}),r=new vn({});return(await t.send(r)).Account}catch(t){console.log("Warning: Unable to get AWS account ID",t.message);return}}async function Rn(e){let t=await Ut(e);if(e!=="us-east-1"){let r=await Ut("us-east-1");t.push(...r)}return t}async function Ut(e){try{let t=new Lt({region:e}),r=new yn({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[In(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 Ve("Do you want to request a new certificate?"))return i(`Please add your certificate ARN to the config file in the "${$t(o)}" setting.`),"TODO";let s=await Wn(r,n);return i("Certificate ARN: "+s),s}async function Wn(e,t){try{let r=await ze("Validate certificate using DNS or email validation?",["dns","email"],"dns"),o=new Lt({region:e}),n=new gn({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 On(e){let t=Nt(),r=xn("rsa",{modulusLength:2048,publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs1",format:"pem",cipher:"aes-256-cbc",passphrase:t}});return{keyId:(await new wn({}).send(new Sn({PublicKeyConfig:{Name:e,CallerReference:Nt(),EncodedKey:r.publicKey}}))).PublicKey?.Id,publicKey:r.publicKey,privateKey:r.privateKey,passphrase:t}}async function kn(e,t){let r=new En({Name:t,WithDecryption:!0});try{return(await e.send(r)).Parameter?.Value}catch(o){if(o.name==="ParameterNotFound")return;throw o}}async function Dn(e,t,r){let o=new bn({Name:t,Value:r,Type:"SecureString",Overwrite:!0});await e.send(o)}async function Jn(e,t,r){let o=new Cn({region:e});for(let[n,a]of Object.entries(r)){let s=t+n,c=a.toString(),m=await kn(o,s);m!==void 0&&m!==c&&(i(`Parameter "${s}" exists with different value.`),await ge(`Do you want to overwrite "${s}"?`)),await Dn(o,s,c)}}async function Ft(){let e=await Be();for(let t of e){let r=t.StackName,o=await Fe(r);o&&(ye(o),console.log(""))}}import{CreateInvalidationCommand as Nn}from"@aws-sdk/client-cloudfront";import{PutObjectCommand as Un}from"@aws-sdk/client-s3";import{ContentType as R}from"@medplum/core";import Ln from"fast-glob";import{createReadStream as $n,mkdtempSync as Bn,readdirSync as Fn,readFileSync as Gn,rmSync as zn,writeFileSync as Vn}from"fs";import Gt from"node-fetch";import{tmpdir as jn}from"os";import{join as Se,sep as qn}from"path";import{pipeline as Xn}from"stream/promises";async function zt(e,t){let r=le(e);if(!r){console.log("Config not found");return}let o=await V(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 Zn("@medplum/app","latest");Vt(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 ei(a,n.PhysicalResourceId,t),o.appDistribution?.PhysicalResourceId&&!t.dryrun&&await oi(o.appDistribution.PhysicalResourceId),console.log("Done")}async function Yn(e,t){let r=`https://registry.npmjs.org/${e}/${t}`;return(await Gt(r)).json()}async function Zn(e,t){let o=(await Yn(e,t)).dist.tarball,n=Bn(Se(jn(),"tarball-"));try{let a=await Gt(o),s=Tt(n);return await Xn(a.body,s),Se(n,"package","dist")}catch(a){throw zn(n,{recursive:!0,force:!0}),a}}function Vt(e,t){for(let r of Fn(e,{withFileTypes:!0})){let o=Se(e,r.name);r.isDirectory()?Vt(o,t):r.isFile()&&o.endsWith(".js")&&Qn(o,t)}}function Qn(e,t){let r=Gn(e,"utf-8");for(let[o,n]of Object.entries(t))r=r.replaceAll(`__${o}__`,n);Vn(e,r)}async function ei(e,t,r){let o=[["assets/**/*.css",R.CSS,!0],["assets/**/*.css.map",R.JSON,!0],["assets/**/*.js",R.JAVASCRIPT,!0],["assets/**/*.js.map",R.JSON,!0],["assets/**/*.txt",R.TEXT,!0],["assets/**/*.ico",R.FAVICON,!0],["img/**/*.png",R.PNG,!0],["img/**/*.svg",R.SVG,!0],["robots.txt",R.TEXT,!0],["index.html",R.HTML,!1]];for(let n of o)await ti({rootDir:e,bucketName:t,fileNamePattern:n[0],contentType:n[1],cached:n[2],dryrun:r.dryrun})}async function ti(e){let t=Ln.sync(e.fileNamePattern,{cwd:e.rootDir});for(let r of t)await ri(Se(e.rootDir,r),e)}async function ri(e,t){let r=$n(e),o=e.substring(t.rootDir.length+1).split(qn).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 Dt.send(new Un(n))}async function oi(e){let t=await Ot.send(new Nn({DistributionId:e,InvalidationBatch:{CallerReference:`invalidate-all-${Date.now()}`,Paths:{Quantity:1,Items:["/*"]}}}));console.log(`Created invalidation with ID: ${t.Invalidation?.Id}`)}import{UpdateServiceCommand as ni}from"@aws-sdk/client-ecs";async function jt(e){let t=await V(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=Ge(t.ecsService);if(!o){console.log("ECS Service not found");return}await kt.send(new ni({cluster:r,service:o,forceNewDeployment:!0})),console.log(`Service "${o}" updated successfully.`)}var N=new ii("aws").description("Commands to manage AWS resources");N.command("init").description("Initialize a new Medplum AWS CloudFormation stacks").action(Bt);N.command("list").description("List Medplum AWS CloudFormation stacks").action(Ft);N.command("describe").description("Describe a Medplum AWS CloudFormation stack by tag").argument("<tag>").action(Jt);N.command("update-server").alias("deploy-server").description("Update the server image").argument("<tag>").action(jt);N.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(zt);import{Command as ai}from"commander";var qt=p("save"),Xt=p("deploy"),Yt=p("create"),Zt=new ai("bot").addCommand(qt).addCommand(Xt).addCommand(Yt),je=p("save-bot"),qe=p("deploy-bot"),Xe=p("create-bot");qt.description("Saving the bot").argument("<botName>").action(async(e,t)=>{let r=await u(t);await Ee(r,e)});Xt.description("Deploy the app to AWS").argument("<botName>").action(async(e,t)=>{let r=await u(t);await Ee(r,e,!0)});Yt.arguments("<botName> <projectId> <sourceFile> <distFile>").description("Creating a bot").action(async(e,t,r,o,n)=>{let a=await u(n);await ke(a,[e,t,r,o])});async function Ee(e,t,r=!1){let o=Kt(t);for(let n of o){let a=await e.readResource("Bot",n.id);await Oe(e,n,a),r&&await _t(e,n,a)}console.log(`Number of bots deployed: ${o.length}`)}je.description("Saves the bot").argument("<botName>").action(async(e,t)=>{let r=await u(t);await Ee(r,e)});qe.description("Deploy the bot to AWS").argument("<botName>").action(async(e,t)=>{let r=await u(t);await Ee(r,e,!0)});Xe.arguments("<botName> <projectId> <sourceFile> <distFile>").description("Creates and saves the bot").action(async(e,t,r,o,n)=>{let a=await u(n);await ke(a,[e,t,r,o])});import{Command as si}from"commander";import{createReadStream as ci,writeFile as di}from"fs";import{resolve as er}from"path";import{createInterface as pi}from"readline";var tr=p("export"),rr=p("import"),or=new si("bulk").addCommand(tr).addCommand(rr);tr.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:m})=>{let f=new URL(m),I=await a.download(m),H=`${c}_${f.pathname}`.replace(/[^a-zA-Z0-9]+/g,"_")+".ndjson",K=er(n??"",H);di(`${K}`,await I.text(),()=>{console.log(`${K} is created`)})})});rr.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=er(n??process.cwd(),e),s=await u(t);await mi(a,parseInt(r,10),s,o)});async function mi(e,t,r,o){let n=[],a=ci(e),s=pi({input:a});for await(let c of s){let m=ui(c,o);n.push({resource:m,request:{method:"POST",url:m.resourceType}}),n.length%t===0&&(await Qt(n,r),n=[])}n.length>0&&await Qt(n,r)}async function Qt(e,t){(await t.executeBatch({resourceType:"Bundle",type:"transaction",entry:e})).entry?.forEach(o=>{W(o.response)})}function ui(e,t){let r=JSON.parse(e);return t?li(r):r}function li(e){return e.resourceType==="ExplanationOfBenefit"?fi(e):e}function fi(e){return e.provider||(e.provider=Je()),e.item?.forEach(t=>{t?.productOrService||(t.productOrService=Je())}),e}import{Command as hi,Option as yi}from"commander";var nr=p("list"),ir=p("current"),ar=p("switch"),sr=p("invite"),cr=new hi("project").addCommand(nr).addCommand(ir).addCommand(ar).addCommand(sr);nr.description("List of current projects").action(async e=>{let t=await u(e);gi(t)});function gi(e){let r=e.getLogins().map(o=>`${o.project.display} (${o.project.reference})`).join(`
6
6
 
7
- `);console.log(r)}nr.description("Project you are currently on").action(async e=>{let r=(await u(e)).getActiveLogin();if(!r)throw new Error("Unauthenticated: run `npx medplum login` to login");console.log(`${r.project.display} (${r.project.reference})`)});ir.description("Switching to another project from the current one").argument("<projectId>").action(async(e,t)=>{let r=await u(t);await Ei(r,e)});ar.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 wi("-r, --role <role>","Role of user").choices(["Practitioner","Patient","RelatedPerson"]).default("Practitioner")).action(async(e,t,r,o)=>{let n=await u(o),a=n.getActiveLogin();if(!a)throw new Error("Unauthenticated: run `npx medplum login` to login");if(!a.project.reference)throw new Error("No current project to invite user to");let s=a.project.reference.split("/")[1],c={resourceType:o.role,firstName:e,lastName:t,email:r,sendEmail:!!o.sendEmail,admin:!!o.admin};await bi(s,c,n)});async function Ei(e,t){let o=e.getLogins().find(n=>n.project.reference?.includes(t));o?(await e.setActiveLogin(o),console.log(`Switched to project ${t}
8
- `)):console.log(`Error: project ${t} not found. Make sure you are added as a user to this project`)}async function bi(e,t,r){try{await r.invite(e,t),t.sendEmail&&console.log("Email sent"),console.log("See your users at https://app.medplum.com/admin/users")}catch(o){console.log("Error while sending invite "+o)}}import{convertToTransactionBundle as Ci}from"@medplum/core";var Ye=m("delete"),Ze=m("get"),Qe=m("patch"),et=m("post"),tt=m("put");Ye.argument("<url>","Resource/$id").action(async(e,t)=>{let r=await u(t);W(await r.delete(re(e,t)))});Ze.argument("<url>","Resource/$id").option("--as-transaction","Print out the bundle as a transaction type").action(async(e,t)=>{let o=await(await u(t)).get(re(e,t));t.asTransaction?W(Ci(o)):W(o)});Qe.arguments("<url> <body>").action(async(e,t,r)=>{let o=await u(r);W(await o.patch(re(e,r),rt(t)))});et.arguments("<url> <body>").action(async(e,t,r)=>{let o=await u(r);W(await o.post(re(e,r),rt(t)))});tt.arguments("<url> <body>").action(async(e,t,r)=>{let o=await u(r);W(await o.put(re(e,r),rt(t)))});function rt(e){if(e)try{return JSON.parse(e)}catch{return e}}function re(e,t){let r=["admin/","auth/","fhir/R4"],{fhirUrlPath:o}=t;return r.some(n=>e.startsWith(n))?e:o?`${o}/${e}`:"fhir/R4/"+e}import{Command as vi}from"commander";import{resolve as Ai}from"path";import{readdirSync as xi}from"fs";import{homedir as Pi}from"os";var cr=m("set"),dr=m("remove"),pr=m("list"),mr=m("describe"),ur=new vi("profile").addCommand(cr).addCommand(dr).addCommand(pr).addCommand(mr);cr.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)=>{fe(e,t)});dr.argument("<profileName>","Name of the profile").description("Remove a profile by name").action(async e=>{new E(e).setObject("options",void 0),console.log(`${e} profile removed`)});pr.description("List all profiles saved").action(async()=>{let e=Ai(Pi(),".medplum"),t=xi(e),r=[];t.forEach(o=>{let n=o.split(".")[0],s=new E(n).getObject("options");s&&r.push({profileName:n,profile:s})}),console.log(r)});mr.argument("<profileName>","Name of the profile").description("Describes a profile").action(async e=>{let t=he(e);console.log(t)});async function Hi(e){try{let t=new Ti("medplum").description("Command to access Medplum CLI");t.version(_i),t.addCommand(Ue),t.addCommand(Le),t.addCommand(Ze),t.addCommand(et),t.addCommand(Qe),t.addCommand(tt),t.addCommand(Ye),t.addCommand(sr),t.addCommand(rr),t.addCommand(Yt),t.addCommand(Ve),t.addCommand(qe),t.addCommand(Xe),t.addCommand(ur),t.addCommand(N),await t.parseAsync(e)}catch(t){console.error("Error: "+Ki(t))}}async function ki(){Ii.config(),await Hi(process.argv)}ot.main===module&&ki().catch(e=>console.error("Unhandled error:",e));export{Hi as main,ki as run};
7
+ `);console.log(r)}ir.description("Project you are currently on").action(async e=>{let r=(await u(e)).getActiveLogin();if(!r)throw new Error("Unauthenticated: run `npx medplum login` to login");console.log(`${r.project.display} (${r.project.reference})`)});ar.description("Switching to another project from the current one").argument("<projectId>").action(async(e,t)=>{let r=await u(t);await wi(r,e)});sr.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 yi("-r, --role <role>","Role of user").choices(["Practitioner","Patient","RelatedPerson"]).default("Practitioner")).action(async(e,t,r,o)=>{let n=await u(o),a=n.getActiveLogin();if(!a)throw new Error("Unauthenticated: run `npx medplum login` to login");if(!a.project.reference)throw new Error("No current project to invite user to");let s=a.project.reference.split("/")[1],c={resourceType:o.role,firstName:e,lastName:t,email:r,sendEmail:!!o.sendEmail,admin:!!o.admin};await Si(s,c,n)});async function wi(e,t){let o=e.getLogins().find(n=>n.project.reference?.includes(t));o?(await e.setActiveLogin(o),console.log(`Switched to project ${t}
8
+ `)):console.log(`Error: project ${t} not found. Make sure you are added as a user to this project`)}async function Si(e,t,r){try{await r.invite(e,t),t.sendEmail&&console.log("Email sent"),console.log("See your users at https://app.medplum.com/admin/users")}catch(o){console.log("Error while sending invite "+o)}}import{convertToTransactionBundle as Ei}from"@medplum/core";var Ye=p("delete"),Ze=p("get"),Qe=p("patch"),et=p("post"),tt=p("put");Ye.argument("<url>","Resource/$id").action(async(e,t)=>{let r=await u(t);W(await r.delete(re(r,e)))});Ze.argument("<url>","Resource/$id").option("--as-transaction","Print out the bundle as a transaction type").action(async(e,t)=>{let r=await u(t),o=await r.get(re(r,e));t.asTransaction?W(Ei(o)):W(o)});Qe.arguments("<url> <body>").action(async(e,t,r)=>{let o=await u(r);W(await o.patch(re(o,e),rt(t)))});et.arguments("<url> <body>").action(async(e,t,r)=>{let o=await u(r);W(await o.post(re(o,e),rt(t)))});tt.arguments("<url> <body>").action(async(e,t,r)=>{let o=await u(r);W(await o.put(re(o,e),rt(t)))});function rt(e){if(e)try{return JSON.parse(e)}catch{return e}}function re(e,t){return["admin/","auth/","fhir/R4"].some(o=>t.startsWith(o))?t:e.fhirUrl(t).toString()}import{Command as bi}from"commander";import{resolve as Ci}from"path";import{readdirSync as vi}from"fs";import{homedir as Ai}from"os";var dr=p("set"),pr=p("remove"),mr=p("list"),ur=p("describe"),lr=new bi("profile").addCommand(dr).addCommand(pr).addCommand(mr).addCommand(ur);dr.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)=>{fe(e,t)});pr.argument("<profileName>","Name of the profile").description("Remove a profile by name").action(async e=>{new _(e).setObject("options",void 0),console.log(`${e} profile removed`)});mr.description("List all profiles saved").action(async()=>{let e=Ci(Ai(),".medplum"),t=vi(e),r=[];t.forEach(o=>{let n=o.split(".")[0],s=new _(n).getObject("options");s&&r.push({profileName:n,profile:s})}),console.log(r)});ur.argument("<profileName>","Name of the profile").description("Describes a profile").action(async e=>{let t=he(e);console.log(t)});async function Ti(e){try{let t=new _i("medplum").description("Command to access Medplum CLI");t.version(xi),t.addCommand(Ue),t.addCommand(Le),t.addCommand(Ze),t.addCommand(et),t.addCommand(Qe),t.addCommand(tt),t.addCommand(Ye),t.addCommand(cr),t.addCommand(or),t.addCommand(Zt),t.addCommand(je),t.addCommand(qe),t.addCommand(Xe),t.addCommand(lr),t.addCommand(N),await t.parseAsync(e)}catch(t){console.error("Error: "+Pi(t))}}async function Ii(){Ki.config(),await Ti(process.argv)}ot.main===module&&Ii().catch(e=>console.error("Unhandled error:",e));export{Ti as main,Ii as run};
9
9
  //# sourceMappingURL=index.mjs.map