@medplum/cli 2.1.6 → 2.1.7

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.
@@ -2,7 +2,7 @@
2
2
  var at=(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 ea,normalizeErrorString as ta}from"@medplum/core";import{Command as ra}from"commander";import oa from"dotenv";import{ContentType as Be,getDisplayString as dn,normalizeErrorString as pn}from"@medplum/core";import{exec as mn}from"child_process";import{createServer as ln}from"http";import{platform as un}from"os";import{MedplumClient as kr}from"@medplum/core";import{ClientStorage as Ir}from"@medplum/core";import{existsSync as st,mkdirSync as Tr,readFileSync as _r,writeFileSync as Kr}from"fs";import{homedir as Hr}from"os";import{resolve as ct}from"path";var K=class extends Ir{constructor(r){super();this.dirName=ct(Hr(),".medplum"),this.fileName=ct(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(st(this.fileName))return JSON.parse(_r(this.fileName,"utf8"))}writeFile(r){st(this.dirName)||Tr(this.dirName),Kr(this.fileName,JSON.stringify(r,null,2),"utf8")}};async function l(e,t=!0){let r=e.profile??"default",o=new K(r),n=o.getObject("options");if(r!=="default"&&!n)throw new Error(`Profile "${r}" does not exist`);let{baseUrl:a,fhirUrlPath:s,accessToken:c,tokenUrl:p,authorizeUrl:h,clientId:_,clientSecret:I}=Rr(e,o),U=e.fetch??fetch,L=new kr({fetch:U,baseUrl:a,tokenUrl:p,fhirUrlPath:s,authorizeUrl:h,storage:o,onUnauthenticated:Or,verbose:e.verbose});return t&&(c?L.setAccessToken(c):_&&I&&(L.setBasicAuth(_,I),n?.authType!=="basic"&&await L.startClientLogin(_,I))),L}function Rr(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,h=e.clientSecret??r?.clientSecret??process.env.MEDPLUM_CLIENT_SECRET;return{baseUrl:o,fhirUrlPath:n,accessToken:a,tokenUrl:s,authorizeUrl:c,clientId:p,clientSecret:h}}function Or(){console.log("Unauthenticated: run `npx medplum login` to sign in")}import{Command as Mr,Option as Dr}from"commander";function d(e){return new Mr(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 Dr("--auth-type <authType>","Type of authentication").choices(["basic","client-credentials","authorization-code","jwt-bearer","token-exchange","jwt-assertion"]))}import{ContentType as We,encodeBase64 as It}from"@medplum/core";import{createHmac as Zo,createPrivateKey as Qo,randomBytes as en}from"crypto";import{existsSync as tn,readFileSync as Tt,writeFileSync as rn}from"fs";import{Buffer as Ae}from"buffer";var v=new TextEncoder,S=new TextDecoder,ba=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;Ae.isEncoding("base64url")?g=e=>Ae.from(e).toString("base64url"):g=e=>Ae.from(e).toString("base64").replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_");var $=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 m=class extends ${constructor(){super(...arguments),this.code="ERR_JOSE_NOT_SUPPORTED"}static get code(){return"ERR_JOSE_NOT_SUPPORTED"}};var C=class extends ${constructor(){super(...arguments),this.code="ERR_JWS_INVALID"}static get code(){return"ERR_JWS_INVALID"}},O=class extends ${constructor(){super(...arguments),this.code="ERR_JWT_INVALID"}static get code(){return"ERR_JWT_INVALID"}};import{KeyObject as Ur}from"crypto";import*as xe from"util";var A=xe.types.isKeyObject?e=>xe.types.isKeyObject(e):e=>e!=null&&e instanceof Ur;import*as pt from"crypto";import*as Ie from"util";var Nr=pt.webcrypto,ae=Nr,b=Ie.types.isCryptoKey?e=>Ie.types.isCryptoKey(e):e=>!1;function k(e,t="algorithm.name"){return new TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`)}function se(e,t){return e.name===t}function Te(e){return parseInt(e.name.slice(4),10)}function Lr(e){switch(e){case"ES256":return"P-256";case"ES384":return"P-384";case"ES512":return"P-521";default:throw new Error("unreachable")}}function $r(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 mt(e,t,...r){switch(t){case"HS256":case"HS384":case"HS512":{if(!se(e.algorithm,"HMAC"))throw k("HMAC");let o=parseInt(t.slice(2),10);if(Te(e.algorithm.hash)!==o)throw k(`SHA-${o}`,"algorithm.hash");break}case"RS256":case"RS384":case"RS512":{if(!se(e.algorithm,"RSASSA-PKCS1-v1_5"))throw k("RSASSA-PKCS1-v1_5");let o=parseInt(t.slice(2),10);if(Te(e.algorithm.hash)!==o)throw k(`SHA-${o}`,"algorithm.hash");break}case"PS256":case"PS384":case"PS512":{if(!se(e.algorithm,"RSA-PSS"))throw k("RSA-PSS");let o=parseInt(t.slice(2),10);if(Te(e.algorithm.hash)!==o)throw k(`SHA-${o}`,"algorithm.hash");break}case"EdDSA":{if(e.algorithm.name!=="Ed25519"&&e.algorithm.name!=="Ed448")throw k("Ed25519 or Ed448");break}case"ES256":case"ES384":case"ES512":{if(!se(e.algorithm,"ECDSA"))throw k("ECDSA");let o=Lr(t);if(e.algorithm.namedCurve!==o)throw k(o,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}$r(e,r)}function lt(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 P=(e,...t)=>lt("Key must be ",e,...t);function _e(e,t,...r){return lt(`Key for the ${e} algorithm must be `,t,...r)}var Ke=e=>A(e)||b(e),u=["KeyObject"];(globalThis.CryptoKey||!(ae===null||ae===void 0)&&ae.CryptoKey)&&u.push("CryptoKey");import{promisify as ft}from"util";import{inflateRaw as Vr,deflateRaw as jr}from"zlib";var ps=ft(Vr),ms=ft(jr);var qr=(...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},B=qr;function Xr(e){return typeof e=="object"&&e!==null}function w(e){if(!Xr(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 no,KeyObject as Ws}from"crypto";import{promisify as io}from"util";import{Buffer as ce}from"buffer";import{createPublicKey as Yr,KeyObject as Zr}from"crypto";var Qr=ce.from([42,134,72,206,61,3,1,7]),eo=ce.from([43,129,4,0,34]),to=ce.from([43,129,4,0,35]),ro=ce.from([43,129,4,0,10]),He=new WeakMap,oo=e=>{switch(e){case"prime256v1":return"P-256";case"secp384r1":return"P-384";case"secp521r1":return"P-521";case"secp256k1":return"secp256k1";default:throw new m("Unsupported key curve for this operation")}},ht=(e,t)=>{var r;let o;if(b(e))o=Zr.from(e);else if(A(e))o=e;else throw new TypeError(P(e,...u));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(He.has(o))return He.get(o);let n=(r=o.asymmetricKeyDetails)===null||r===void 0?void 0:r.namedCurve;if(!n&&o.type==="private")n=ht(Yr(o),!0);else if(!n){let s=o.export({format:"der",type:"spki"}),c=s[1]<128?14:15,p=s[c],h=s.slice(c+1,c+1+p);if(h.equals(Qr))n="prime256v1";else if(h.equals(eo))n="secp384r1";else if(h.equals(to))n="secp521r1";else if(h.equals(ro))n="secp256k1";else throw new m("Unsupported key curve for this operation")}if(t)return n;let a=oo(n);return He.set(o,a),a}default:throw new TypeError("Invalid asymmetric key type for this operation")}};var de=ht;var Vs=io(no);import{promisify as co}from"util";import{KeyObject as ec,pbkdf2 as po}from"crypto";var mc=co(po);var ke=new WeakMap,pe=(e,t)=>{let r=e.readUInt8(1);if(!(r&128))return t===0?r:pe(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:pe(e.subarray(2+r),t-1)},mo=(e,t)=>{let r=e.readUInt8(1);if(!(r&128))return pe(e.subarray(2),t);let o=r&127;return pe(e.subarray(2+o),t)},lo=e=>{var t,r;if(ke.has(e))return ke.get(e);let o=(r=(t=e.asymmetricKeyDetails)===null||t===void 0?void 0:t.modulusLength)!==null&&r!==void 0?r:mo(e.export({format:"der",type:"pkcs1"}),e.type==="private"?1:0)-1<<3;return ke.set(e,o),o};var Y=(e,t)=>{if(lo(e)<2048)throw new TypeError(`${t} requires key modulusLength to be 2048 bits or larger`)};import{Buffer as E}from"buffer";var uo=2,fo=3,ho=4,yo=48,Hc=E.from([0]),kc=E.from([uo]),Rc=E.from([fo]),Oc=E.from([yo]),Mc=E.from([ho]);var Dc=new Map([["P-256",E.from("06 08 2A 86 48 CE 3D 03 01 07".replace(/ /g,""),"hex")],["secp256k1",E.from("06 05 2B 81 04 00 0A".replace(/ /g,""),"hex")],["P-384",E.from("06 05 2B 81 04 00 22".replace(/ /g,""),"hex")],["P-521",E.from("06 05 2B 81 04 00 23".replace(/ /g,""),"hex")],["ecPublicKey",E.from("06 07 2A 86 48 CE 3D 02 01".replace(/ /g,""),"hex")],["X25519",E.from("06 03 2B 65 6E".replace(/ /g,""),"hex")],["X448",E.from("06 03 2B 65 6F".replace(/ /g,""),"hex")],["Ed25519",E.from("06 03 2B 65 70".replace(/ /g,""),"hex")],["Ed448",E.from("06 03 2B 65 71".replace(/ /g,""),"hex")]]);var[D,me]=process.versions.node.split(".").map(e=>parseInt(e,10)),gt=D>=16||D===15&&me>=13,N=!("electron"in process.versions)&&(D>=17||D===16&&me>=9),go=D>=16||D===15&&me>=9,wo=D>=16||D===15&&me>=12;var bo=(e,t)=>{if(!(t instanceof Uint8Array)){if(!Ke(t))throw new TypeError(_e(e,t,...u,"Uint8Array"));if(t.type!=="secret")throw new TypeError(`${u.join(" or ")} instances for symmetric algorithms must be of type "secret"`)}},Eo=(e,t,r)=>{if(!Ke(t))throw new TypeError(_e(e,t,...u));if(t.type==="secret")throw new TypeError(`${u.join(" or ")} instances for asymmetric algorithms must not be of type "secret"`);if(r==="sign"&&t.type==="public")throw new TypeError(`${u.join(" or ")} instances for asymmetric algorithm signing must be of type "private"`);if(r==="decrypt"&&t.type==="public")throw new TypeError(`${u.join(" or ")} instances for asymmetric algorithm decryption must be of type "private"`);if(t.algorithm&&r==="verify"&&t.type==="private")throw new TypeError(`${u.join(" or ")} instances for asymmetric algorithm verifying must be of type "public"`);if(t.algorithm&&r==="encrypt"&&t.type==="private")throw new TypeError(`${u.join(" or ")} instances for asymmetric algorithm encryption must be of type "public"`)},vo=(e,t,r)=>{e.startsWith("HS")||e==="dir"||e.startsWith("PBES2")||/^A\d{3}(?:GCM)?KW$/.test(e)?bo(e,t):Eo(e,t,r)},Z=vo;function _o(e,t,r,o,n){if(n.crit!==void 0&&o.crit===void 0)throw new e('"crit" (Critical) Header Parameter MUST be integrity protected');if(!o||o.crit===void 0)return new Set;if(!Array.isArray(o.crit)||o.crit.length===0||o.crit.some(s=>typeof s!="string"||s.length===0))throw new e('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');let a;r!==void 0?a=new Map([...Object.entries(r),...t.entries()]):a=t;for(let s of o.crit){if(!a.has(s))throw new m(`Extension Header Parameter "${s}" is not recognized`);if(n[s]===void 0)throw new e(`Extension Header Parameter "${s}" is missing`);if(a.get(s)&&o[s]===void 0)throw new e(`Extension Header Parameter "${s}" MUST be integrity protected`)}return new Set(o.crit)}var G=_o;var Oo=Symbol();import*as Q from"crypto";import{promisify as Uo}from"util";function le(e){switch(e){case"PS256":case"RS256":case"ES256":case"ES256K":return"sha256";case"PS384":case"RS384":case"ES384":return"sha384";case"PS512":case"RS512":case"ES512":return"sha512";case"EdDSA":return;default:throw new m(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}import{constants as Et}from"crypto";var vt={padding:Et.RSA_PKCS1_PSS_PADDING,saltLength:Et.RSA_PSS_SALTLEN_DIGEST},Mo=new Map([["ES256","P-256"],["ES256K","secp256k1"],["ES384","P-384"],["ES512","P-521"]]);function ue(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 Y(t,e),t;case(N&&"PS256"):case(N&&"PS384"):case(N&&"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 Y(t,e),{key:t,...vt};case(!N&&"PS256"):case(!N&&"PS384"):case(!N&&"PS512"):if(t.asymmetricKeyType!=="rsa")throw new TypeError("Invalid key for this operation, its asymmetricKeyType must be rsa");return Y(t,e),{key:t,...vt};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=de(t),o=Mo.get(e);if(r!==o)throw new TypeError(`Invalid key curve for the algorithm, its curve must be ${o}, got ${r}`);return{dsaEncoding:"ieee-p1363",key:t}}default:throw new m(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}import*as z from"crypto";import{promisify as Wo}from"util";function Oe(e){switch(e){case"HS256":return"sha256";case"HS384":return"sha384";case"HS512":return"sha512";default:throw new m(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}import{KeyObject as Ct,createSecretKey as Do}from"crypto";function fe(e,t,r){if(t instanceof Uint8Array){if(!e.startsWith("HS"))throw new TypeError(P(t,...u));return Do(t)}if(t instanceof Ct)return t;if(b(t))return mt(t,e,r),Ct.from(t);throw new TypeError(P(t,...u,"Uint8Array"))}var Me;z.sign.length>3?Me=Wo(z.sign):Me=z.sign;var Jo=async(e,t,r)=>{let o=fe(e,t,"sign");if(e.startsWith("HS")){let n=z.createHmac(Oe(e),o);return n.update(r),n.digest()}return Me(le(e),r,ue(e,o))},De=Jo;var At;Q.verify.length>4&&gt?At=Uo(Q.verify):At=Q.verify;var ee=e=>Math.floor(e.getTime()/1e3);var Lo=/^(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)$/i,he=e=>{let t=Lo.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 V=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 C("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");if(!B(this._protectedHeader,this._unprotectedHeader))throw new C("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let o={...this._protectedHeader,...this._unprotectedHeader},n=G(C,new Map([["b64",!0]]),r?.crit,this._protectedHeader,o),a=!0;if(n.has("b64")&&(a=this._protectedHeader.b64,typeof a!="boolean"))throw new C('The "b64" (base64url-encode payload) Header Parameter must be a boolean');let{alg:s}=o;if(typeof s!="string"||!s)throw new C('JWS "alg" (Algorithm) Header Parameter missing or invalid');Z(s,t,"sign");let c=this._payload;a&&(c=v.encode(g(c)));let p;this._protectedHeader?p=v.encode(g(JSON.stringify(this._protectedHeader))):p=v.encode("");let h=T(p,v.encode("."),c),_=await De(s,t,h),I={signature:g(_),payload:""};return a&&(I.payload=S.decode(c)),this._unprotectedHeader&&(I.header=this._unprotectedHeader),this._protectedHeader&&(I.protected=S.decode(p)),I}};var te=class{constructor(t){this._flattened=new V(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 j=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:ee(new Date)+he(t)},this}setExpirationTime(t){return typeof t=="number"?this._payload={...this._payload,exp:t}:this._payload={...this._payload,exp:ee(new Date)+he(t)},this}setIssuedAt(t){return typeof t>"u"?this._payload={...this._payload,iat:ee(new Date)}:this._payload={...this._payload,iat:t},this}};var re=class extends j{setProtectedHeader(t){return this._protectedHeader=t,this}async sign(t,r){var o;let n=new te(v.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 Ou,generateKeyPair as Xo}from"crypto";import{promisify as Yo}from"util";var Uu=Yo(Xo);import{basename as _t,extname as on,resolve as Kt}from"path";import nn from"tar";function R(e){console.log(JSON.stringify(e,null,2))}async function Je(e,t,r){let o=t.source,n=Le(o);if(n)try{console.log("Saving source code...");let a=await e.createAttachment(n,_t(o),cn(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 Ue(e,t,r){let o=t.dist??t.source,n=Le(o);if(n)try{console.log("Deploying bot...");let a=await e.post(e.fhirUrl("Bot",r.id,"$deploy"),{code:n,filename:_t(o)});console.log("Deploy result: "+a.issue?.[0]?.details?.text)}catch(a){console.log("Deploy error: ",a)}}async function Ne(e,t,r,o,n,a){try{let s={name:t,description:"",runtimeVersion:a},c=await e.post("admin/projects/"+r+"/bot",s),p=await e.readResource("Bot",c.id),h={name:t,id:c.id,source:o,dist:n};await Je(e,h,p),await Ue(e,h,p),console.log(`Success! Bot created: ${p.id}`),an(h)}catch(s){console.log("Error while creating new bot: "+s)}}function Ht(e){let t=new RegExp("^"+sn(e).replace(/\\\*/g,".*")+"$"),r=q()?.bots?.filter(o=>t.test(o.name));return r||[]}function q(e){let t=e?`medplum.${e}.config.json`:"medplum.config.json",r=Le(t);if(r)return JSON.parse(r)}function Le(e){let t=Kt(process.cwd(),e);return tn(t)?Tt(t,"utf8"):""}function an(e){let t=q()??{};t.bots||(t.bots=[]),t.bots.push(e),rn("medplum.config.json",JSON.stringify(t,null,2),"utf8"),console.log(`Bot added to config: ${e.id}`)}function sn(e){return e.replace(/[/\-\\^$*+?.()|[\]{}]/g,"\\$&")}function kt(e){let o=0,n=0;return nn.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 $e(){return{extension:[{url:"http://hl7.org/fhir/StructureDefinition/data-absent-reason",valueCode:"unsupported"}]}}function cn(e){let t=on(e).toLowerCase();return[".cjs",".mjs",".js"].includes(t)?We.JAVASCRIPT:[".cts",".mts",".ts"].includes(t)?We.TYPESCRIPT:We.TEXT}function ye(e,t){let r=new K(e),o={name:e,...t};return r.setObject("options",o),console.log(`${e} profile created`),o}function Rt(e){return new K(e).getObject("options")}async function Ot(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=It(JSON.stringify(r)),s=It(JSON.stringify(n)),c=`${a}.${s}`,p=Zo("sha256",t.clientSecret).update(c).digest("base64url"),h=`${c}.${p}`;await e.startJwtBearerLogin(t.clientId,h,t.scope??"")}async function Mt(e,t){let r=Qo(Tt(Kt(t.privateKeyPath))),o=await new re({}).setProtectedHeader({alg:"RS384",typ:"JWT"}).setIssuer(t.clientId).setSubject(t.clientId).setAudience(`${t.baseUrl}${t.audience}`).setJti(en(16).toString("hex")).setIssuedAt().setExpirationTime("5m").sign(r);await e.startJwtAssertionLogin(o)}var Dt="medplum-cli",Wt="http://localhost:9615",Fe=d("login"),Ge=d("whoami");Fe.action(async e=>{let t=e.profile??"default",r=ye(t,e),o=await l(e,!1);await fn(o,r)});Ge.action(async e=>{let t=await l(e);gn(t)});async function fn(e,t){switch(t?.authType??"authorization-code"){case"authorization-code":await wn(e);break;case"basic":e.setBasicAuth(t.clientId,t.clientSecret);break;case"client-credentials":e.setBasicAuth(t.clientId,t.clientSecret),await e.startClientLogin(t.clientId,t.clientSecret);break;case"jwt-bearer":await Ot(e,t);break;case"jwt-assertion":await Mt(e,t);break}console.log("Login successful")}async function hn(e){let t=ln(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:Dt,redirectUri:Wt});o.writeHead(200,{"Content-Type":Be.TEXT}),o.end(`Signed in as ${dn(s)}. You may close this window.`)}catch(s){o.writeHead(400,{"Content-Type":Be.TEXT}),o.end(`Error: ${pn(s)}`)}finally{t.close()}else o.writeHead(404,{"Content-Type":Be.TEXT}),o.end("Not found")}).listen(9615)}async function yn(e){let t=un(),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)}mn(r)}function gn(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 wn(e){await hn(e);let t=new URL(e.getAuthorizeUrl());t.searchParams.set("client_id",Dt),t.searchParams.set("redirect_uri",Wt),t.searchParams.set("scope","openid"),t.searchParams.set("response_type","code"),t.searchParams.set("prompt","login"),await yn(t.toString())}import{Command as vi}from"commander";import{CloudFormationClient as Ut,DescribeStackResourcesCommand as Sn,DescribeStacksCommand as bn,ListStacksCommand as En}from"@aws-sdk/client-cloudformation";import{CloudFrontClient as vn,CreateInvalidationCommand as Cn}from"@aws-sdk/client-cloudfront";import{ECSClient as An}from"@aws-sdk/client-ecs";import{S3Client as Pn}from"@aws-sdk/client-s3";var ge=new Ut({}),xn=new vn({region:"us-east-1"}),Nt=new An({}),oe=new Pn({}),In="medplum:environment";async function ze(){return(await ge.send(new En({}))).StackSummaries?.filter(t=>t.StackName&&t.StackStatus!=="DELETE_COMPLETE")||[]}async function W(e){let t=await ze();for(let r of t){let o=r.StackName,n=await Ve(o);if(n?.tag===e)return n}}async function Ve(e){let t={};return await Jt(ge,e,t),ge.config.region!=="us-east-1"&&await Jt(new Ut({region:"us-east-1"}),e+"-us-east-1",t),t}async function Jt(e,t,r){let o=new bn({StackName:t}),a=(await e.send(o))?.Stacks?.[0],s=a?.Tags?.find(p=>p.Key===In);if(!s)return;let c=await e.send(new Sn({StackName:t}));if(c.StackResources){e===ge&&(r.stack=a,r.tag=s.Value);for(let p of c.StackResources)Tn(p,r)}}function Tn(e,t){e.ResourceType==="AWS::ECS::Cluster"?t.ecsCluster=e:e.ResourceType==="AWS::ECS::Service"?t.ecsService=e:e.ResourceType==="AWS::S3::Bucket"&&e.LogicalResourceId?.startsWith("FrontEndAppBucket")?t.appBucket=e:e.ResourceType==="AWS::CloudFront::Distribution"&&e.LogicalResourceId?.startsWith("FrontEndAppDistribution")?t.appDistribution=e:e.ResourceType==="AWS::CloudFront::CloudFrontOriginAccessIdentity"&&e.LogicalResourceId?.startsWith("FrontEndOriginAccessIdentity")?t.appOriginAccessIdentity=e:e.ResourceType==="AWS::S3::Bucket"&&e.LogicalResourceId?.startsWith("StorageStorageBucket")?t.storageBucket=e:e.ResourceType==="AWS::CloudFront::Distribution"&&e.LogicalResourceId?.startsWith("StorageStorageDistribution")?t.storageDistribution=e:e.ResourceType==="AWS::CloudFront::CloudFrontOriginAccessIdentity"&&e.LogicalResourceId?.startsWith("StorageOriginAccessIdentity")&&(t.storageOriginAccessIdentity=e)}function we(e){console.log(`Medplum Tag: ${e.tag}`),console.log(`Stack Name: ${e.stack?.StackName}`),console.log(`Stack ID: ${e.stack?.StackId}`),console.log(`Status: ${e.stack?.StackStatus}`),console.log(`ECS Cluster: ${e.ecsCluster?.PhysicalResourceId}`),console.log(`ECS Service: ${je(e.ecsService)}`),console.log(`App Bucket: ${e.appBucket?.PhysicalResourceId}`),console.log(`App Distribution: ${e.appDistribution?.PhysicalResourceId}`),console.log(`App OAI: ${e.appOriginAccessIdentity?.PhysicalResourceId}`),console.log(`Storage Bucket: ${e.storageBucket?.PhysicalResourceId}`),console.log(`Storage Distribution: ${e.storageDistribution?.PhysicalResourceId}`),console.log(`Storage OAI: ${e.storageOriginAccessIdentity?.PhysicalResourceId}`)}function je(e){return e?.PhysicalResourceId?.split("/")?.pop()||""}async function Se(e){let t=await xn.send(new Cn({DistributionId:e,InvalidationBatch:{CallerReference:`invalidate-all-${Date.now()}`,Paths:{Quantity:1,Items:["/*"]}}}));console.log(`Created invalidation with ID: ${t.Invalidation?.Id}`)}async function Lt(e){let t=await W(e);if(!t){console.log("Stack not found");return}we(t)}import{ACMClient as Ft,ListCertificatesCommand as _n,RequestCertificateCommand as Kn}from"@aws-sdk/client-acm";import{CloudFrontClient as Hn,CreatePublicKeyCommand as kn}from"@aws-sdk/client-cloudfront";import{GetParameterCommand as Rn,PutParameterCommand as On,SSMClient as Mn}from"@aws-sdk/client-ssm";import{GetCallerIdentityCommand as Dn,STSClient as Wn}from"@aws-sdk/client-sts";import{generateKeyPairSync as Jn,randomUUID as $t}from"crypto";import{existsSync as Un,writeFileSync as Nn}from"fs";import{resolve as Ln}from"path";import $n from"readline";var Bn=e=>`${e}DomainName`,Gt=e=>`${e}SslCertArn`,Ee;async function zt(){let e={apiPort:8103,region:"us-east-1"};Ee=$n.createInterface({input:process.stdin,output:process.stdout}),f("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 Fn(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 be("Do you want to continue without AWS credentials?")),f("ENVIRONMENT NAME"),i('Medplum deployments have a short environment name such as "prod", "staging", "alice", or "demo".'),i("The environment name is used in multiple places:"),i(" 1. As part of config file names (i.e., medplum.demo.config.json)"),i(" 2. As the base of CloudFormation stack names (i.e., MedplumDemo)"),i(" 3. AWS Parameter Store keys (i.e., /medplum/demo/...)"),e.name=await x("What is your environment name?","demo"),i('Using environment name "'+e.name+'"...'),f("CONFIG FILE"),i("Medplum Infrastructure will create a config file in the current directory.");let r=await x("What is the config file name?",`medplum.${e.name}.config.json`);Un(r)&&(i("Config file already exists."),await be("Do you want to overwrite the config file?")),i('Using config file "'+r+'"...'),y(r,e),f("AWS REGION"),i("Most Medplum resources will be created in a single AWS region."),e.region=await x("Enter your AWS region:","us-east-1"),y(r,e),f("AWS ACCOUNT NUMBER"),i("Medplum Infrastructure will use your AWS account number to create AWS resources."),t&&i("Using the AWS CLI, your current account ID is: "+t),e.accountNumber=await x("What is your AWS account number?",t),y(r,e),f("STACK NAME"),i("Medplum will create a CloudFormation stack to manage AWS resources."),i("AWS CloudFormation stack names ");let o="Medplum"+e.name.charAt(0).toUpperCase()+e.name.slice(1);for(e.stackName=await x("Enter your CloudFormation stack name?",o),y(r,e),f("BASE DOMAIN NAME"),i("Please enter the base domain name for your Medplum deployment."),i(""),i("Medplum deploys multiple subdomains for various services."),i(""),i('For example, "api." for the REST API and "app." for the web application.'),i("The base domain name is the common suffix for all subdomains."),i(""),i('For example, if your base domain name is "example.com",'),i('then the REST API will be "api.example.com".'),i(""),i('The base domain should include the TLD (i.e., ".com", ".org", ".net").'),i(""),i("Note that you must own the base domain, and it must use Route53 DNS.");!e.domainName;)e.domainName=await x("Enter your base domain name:");y(r,e),f("SUPPORT EMAIL"),i("Medplum sends transactional emails to users."),i("For example, emails to new users or for password reset."),i("Medplum will use the support email address to send these emails."),i("Note that you must verify the support email address in SES.");let n=await x("Enter your support email address:");f("API DOMAIN NAME"),i("Medplum deploys a REST API for the backend services."),e.apiDomainName=await x("Enter your REST API domain name:","api."+e.domainName),e.baseUrl=`https://${e.apiDomainName}/`,y(r,e),f("APP DOMAIN NAME"),i("Medplum deploys a web application for the user interface."),e.appDomainName=await x("Enter your web application domain name:","app."+e.domainName),y(r,e),f("STORAGE DOMAIN NAME"),i("Medplum deploys a storage service for file uploads."),e.storageDomainName=await x("Enter your storage domain name:","storage."+e.domainName),y(r,e),f("STORAGE BUCKET"),i("Medplum uses an S3 bucket to store binary content such as file uploads."),i("Medplum will create a the S3 bucket as part of the CloudFormation stack."),e.storageBucketName=await x("Enter your storage bucket name:","medplum-"+e.name+"-storage"),y(r,e),f("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 ne("Enter the maximum number of availability zones:",[1,2,3,99],2),f("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 Xe("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 ne("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),f("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 ne("Enter the number of server instances:",[1,2,3,4,6,8],1),y(r,e),f("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 ne("Enter the server memory (MB):",[512,1024,2048,4096,8192,16384],512),y(r,e),f("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 ne("Enter the server CPU:",[256,512,1024,2048,4096,8192,16384],256),y(r,e),f("SERVER IMAGE"),i("Medplum uses Docker images for the API servers."),i("You can choose the image to use for the servers."),i("Docker images can be loaded from either Docker Hub or AWS ECR."),i("The default is the latest Medplum release."),e.serverImage=await x("Enter the server image:","medplum/medplum-server:latest"),y(r,e),f("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 jn(e.stackName+"SigningKey");e.signingKeyId=a,e.storagePublicKey=c,y(r,e),f("SSL CERTIFICATES"),i("Medplum will now check for existing SSL certificates for the subdomains.");let h=await Gn(e.region);i("Found "+h.length+" certificate(s).");for(let{region:I,certName:U}of[{region:e.region,certName:"api"},{region:"us-east-1",certName:"app"},{region:"us-east-1",certName:"storage"}]){i("");let L=await zn(e,h,I,U);e[Gt(U)]=L,y(r,e)}f("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 _={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({..._,signingKey:"****",signingKeyPassphrase:"****"},null,2)),await be("Do you want to store these values in AWS Parameter Store?"),await Yn(e.region,`/medplum/${e.name}/`,_),f("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(""),Ee.close()}function i(e){Ee.write(e+`
3
3
  `)}function f(e){i(`
4
4
  `+e+`
5
- `)}function x(e,t=""){return new Promise(r=>{Ee.question(e+(t?" ("+t+")":"")+" ",o=>{r(o||t.toString())})})}async function qe(e,t,r=""){let o=e+" ["+t.map(n=>n===r?"("+n+")":n).join("|")+"]";for(;;){let n=await x(o)||r;if(t.includes(n))return n;i("Please choose one of the following options: "+t.join(", "))}}async function ne(e,t,r){return parseInt(await qe(e,t.map(o=>o.toString()),r.toString()),10)}async function Xe(e){return(await qe(e,["y","n"])).toLowerCase()==="y"}async function be(e){if(!await Xe(e))throw i("Exiting..."),new Error("User cancelled")}function y(e,t){Nn(Ln(e),JSON.stringify(t,void 0,2),"utf-8")}async function Fn(e){try{let t=new Wn({region:e}),r=new Dn({});return(await t.send(r)).Account}catch(t){console.log("Warning: Unable to get AWS account ID",t.message);return}}async function Gn(e){let t=await Bt(e);if(e!=="us-east-1"){let r=await Bt("us-east-1");t.push(...r)}return t}async function Bt(e){try{let t=new Ft({region:e}),r=new _n({MaxItems:1e3});return(await t.send(r)).CertificateSummaryList}catch(t){return console.log("Warning: Unable to list certificates",t.message),[]}}async function zn(e,t,r,o){let n=e[Bn(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 Xe("Do you want to request a new certificate?"))return i(`Please add your certificate ARN to the config file in the "${Gt(o)}" setting.`),"TODO";let s=await Vn(r,n);return i("Certificate ARN: "+s),s}async function Vn(e,t){try{let r=await qe("Validate certificate using DNS or email validation?",["dns","email"],"dns"),o=new Ft({region:e}),n=new Kn({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 jn(e){let t=$t(),r=Jn("rsa",{modulusLength:2048,publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs1",format:"pem",cipher:"aes-256-cbc",passphrase:t}});return{keyId:(await new Hn({}).send(new kn({PublicKeyConfig:{Name:e,CallerReference:$t(),EncodedKey:r.publicKey}}))).PublicKey?.Id,publicKey:r.publicKey,privateKey:r.privateKey,passphrase:t}}async function qn(e,t){let r=new Rn({Name:t,WithDecryption:!0});try{return(await e.send(r)).Parameter?.Value}catch(o){if(o.name==="ParameterNotFound")return;throw o}}async function Xn(e,t,r){let o=new On({Name:t,Value:r,Type:"SecureString",Overwrite:!0});await e.send(o)}async function Yn(e,t,r){let o=new Mn({region:e});for(let[n,a]of Object.entries(r)){let s=t+n,c=a.toString(),p=await qn(o,s);p!==void 0&&p!==c&&(i(`Parameter "${s}" exists with different value.`),await be(`Do you want to overwrite "${s}"?`)),await Xn(o,s,c)}}async function Vt(){let e=await ze();for(let t of e){let r=t.StackName,o=await Ve(r);o&&(we(o),console.log(""))}}import{PutObjectCommand as Zn}from"@aws-sdk/client-s3";import{ContentType as H}from"@medplum/core";import Qn from"fast-glob";import{createReadStream as ei,mkdtempSync as ti,readdirSync as ri,readFileSync as oi,rmSync as ni,writeFileSync as ii}from"fs";import jt from"node-fetch";import{tmpdir as ai}from"os";import{join as ve,sep as si}from"path";import{pipeline as ci}from"stream/promises";async function qt(e,t){let r=q(e);if(!r){console.log("Config not found");return}let o=await W(e);if(!o){console.log("Stack not found");return}let n=o.appBucket;if(!n){console.log("App bucket not found");return}let a=await pi("@medplum/app","latest");Xt(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 li(a,n.PhysicalResourceId,t),o.appDistribution?.PhysicalResourceId&&!t.dryrun&&await Se(o.appDistribution.PhysicalResourceId),console.log("Done")}async function di(e,t){let r=`https://registry.npmjs.org/${e}/${t}`;return(await jt(r)).json()}async function pi(e,t){let o=(await di(e,t)).dist.tarball,n=ti(ve(ai(),"tarball-"));try{let a=await jt(o),s=kt(n);return await ci(a.body,s),ve(n,"package","dist")}catch(a){throw ni(n,{recursive:!0,force:!0}),a}}function Xt(e,t){for(let r of ri(e,{withFileTypes:!0})){let o=ve(e,r.name);r.isDirectory()?Xt(o,t):r.isFile()&&o.endsWith(".js")&&mi(o,t)}}function mi(e,t){let r=oi(e,"utf-8");for(let[o,n]of Object.entries(t))r=r.replaceAll(`__${o}__`,n);ii(e,r)}async function li(e,t,r){let o=[["assets/**/*.css",H.CSS,!0],["assets/**/*.css.map",H.JSON,!0],["assets/**/*.js",H.JAVASCRIPT,!0],["assets/**/*.js.map",H.JSON,!0],["assets/**/*.txt",H.TEXT,!0],["assets/**/*.ico",H.FAVICON,!0],["img/**/*.png",H.PNG,!0],["img/**/*.svg",H.SVG,!0],["robots.txt",H.TEXT,!0],["index.html",H.HTML,!1]];for(let n of o)await ui({rootDir:e,bucketName:t,fileNamePattern:n[0],contentType:n[1],cached:n[2],dryrun:r.dryrun})}async function ui(e){let t=Qn.sync(e.fileNamePattern,{cwd:e.rootDir});for(let r of t)await fi(ve(e.rootDir,r),e)}async function fi(e,t){let r=ei(e),o=e.substring(t.rootDir.length+1).split(si).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 oe.send(new Zn(n))}import{GetBucketPolicyCommand as hi,PutBucketPolicyCommand as yi}from"@aws-sdk/client-s3";async function Zt(e,t){if(!q(e)){console.log("Config not found");return}let o=await W(e);if(!o){console.log("Stack not found");return}await Yt("App",o.appBucket,o.appDistribution,o.appOriginAccessIdentity,t),await Yt("Storage",o.storageBucket,o.storageDistribution,o.storageOriginAccessIdentity,t),console.log("Done")}async function Yt(e,t,r,o,n){if(!t?.PhysicalResourceId){console.log(`${e} bucket not found`);return}if(!r?.PhysicalResourceId){console.log(`${e} distribution not found`);return}if(!o?.PhysicalResourceId){console.log(`${e} OAI not found`);return}let a=t.PhysicalResourceId,s=o.PhysicalResourceId,c=await gi(a);if(Si(c,a,s)){console.log(`${e} bucket already has policy statement`);return}bi(c,a,s),console.log(`${e} bucket policy:`),console.log(JSON.stringify(c,void 0,2)),n.dryrun?console.log("Dry run - skipping updates"):(console.log("Updating bucket policy..."),await wi(a,c),console.log("Bucket policy updated"),console.log("Creating CloudFront invalidation..."),await Se(r.PhysicalResourceId),console.log("CloudFront invalidation created"),console.log(`${e} bucket policy updated`))}async function gi(e){let t=await oe.send(new hi({Bucket:e}));return JSON.parse(t.Policy??"{}")}async function wi(e,t){await oe.send(new yi({Bucket:e,Policy:JSON.stringify(t)}))}function Si(e,t,r){return!!e?.Statement?.some(o=>o?.Effect==="Allow"&&o?.Principal?.AWS===`arn:aws:iam::cloudfront:user/CloudFront Origin Access Identity ${r}`&&Array.isArray(o?.Action)&&o?.Action?.includes("s3:GetObject*")&&o?.Action?.includes("s3:GetBucket*")&&o?.Action?.includes("s3:List*")&&Array.isArray(o?.Resource)&&o?.Resource?.includes(`arn:aws:s3:::${t}`)&&o?.Resource?.includes(`arn:aws:s3:::${t}/*`))}function bi(e,t,r){e.Version||(e.Version="2012-10-17"),e.Statement||(e.Statement=[]),e.Statement.push({Effect:"Allow",Principal:{AWS:`arn:aws:iam::cloudfront:user/CloudFront Origin Access Identity ${r}`},Action:["s3:GetObject*","s3:GetBucket*","s3:List*"],Resource:[`arn:aws:s3:::${t}`,`arn:aws:s3:::${t}/*`]})}import{UpdateServiceCommand as Ei}from"@aws-sdk/client-ecs";async function Qt(e){let t=await W(e);if(!t){console.log("Stack not found");return}let r=t.ecsCluster?.PhysicalResourceId;if(!r){console.log("ECS Cluster not found");return}let o=je(t.ecsService);if(!o){console.log("ECS Service not found");return}await Nt.send(new Ei({cluster:r,service:o,forceNewDeployment:!0})),console.log(`Service "${o}" updated successfully.`)}var J=new vi("aws").description("Commands to manage AWS resources");J.command("init").description("Initialize a new Medplum AWS CloudFormation stacks").action(zt);J.command("list").description("List Medplum AWS CloudFormation stacks").action(Vt);J.command("describe").description("Describe a Medplum AWS CloudFormation stack by tag").argument("<tag>").action(Lt);J.command("update-server").alias("deploy-server").description("Update the server image").argument("<tag>").action(Qt);J.command("update-app").alias("deploy-app").description("Update the app site").argument("<tag>").option("--dryrun","Displays the operations that would be performed using the specified command without actually running them.").action(qt);J.command("update-bucket-policies").description("Update S3 bucket policies").argument("<tag>").option("--dryrun","Displays the operations that would be performed using the specified command without actually running them.").action(Zt);import{Command as Ci}from"commander";var er=d("save"),tr=d("deploy"),rr=d("create"),or=new Ci("bot").addCommand(er).addCommand(tr).addCommand(rr),Ye=d("save-bot"),Ze=d("deploy-bot"),Qe=d("create-bot");er.description("Saving the bot").argument("<botName>").action(async(e,t)=>{let r=await l(t);await Ce(r,e)});tr.description("Deploy the app to AWS").argument("<botName>").action(async(e,t)=>{let r=await l(t);await Ce(r,e,!0)});rr.arguments("<botName> <projectId> <sourceFile> <distFile>").description("Creating a bot").option("--runtime-version <runtimeVersion>","Runtime version (awslambda, vmcontext)").action(async(e,t,r,o,n)=>{let a=await l(n);await Ne(a,e,t,r,o,n.runtimeVersion)});async function Ce(e,t,r=!1){let o=Ht(t);for(let n of o){let a=await e.readResource("Bot",n.id);await Je(e,n,a),r&&await Ue(e,n,a)}console.log(`Number of bots deployed: ${o.length}`)}Ye.description("Saves the bot").argument("<botName>").action(async(e,t)=>{let r=await l(t);await Ce(r,e)});Ze.description("Deploy the bot to AWS").argument("<botName>").action(async(e,t)=>{let r=await l(t);await Ce(r,e,!0)});Qe.arguments("<botName> <projectId> <sourceFile> <distFile>").description("Creates and saves the bot").action(async(e,t,r,o,n)=>{let a=await l(n);await Ne(a,e,t,r,o)});import{Command as Ai}from"commander";import{createReadStream as Pi,writeFile as xi}from"fs";import{resolve as ir}from"path";import{createInterface as Ii}from"readline";var ar=d("export"),sr=d("import"),cr=new Ai("bulk").addCommand(ar).addCommand(sr);ar.option("-e, --export-level <exportLevel>",'Optional export level. Defaults to system level export. "Group/:id" - Group of Patients, "Patient" - All Patients.').option("-t, --types <types>","optional resource types to export").option("-s, --since <since>","optional Resources will be included in the response if their state has changed after the supplied time (e.g. if Resource.meta.lastUpdated is later than the supplied _since time).").option("-d, --target-directory <targetDirectory>","optional target directory to save files from the bulk export operations.").action(async e=>{let{exportLevel:t,types:r,since:o,targetDirectory:n}=e,a=await l(e);(await a.bulkExport(t,r,o)).output?.forEach(async({type:c,url:p})=>{let h=new URL(p),_=await a.download(p),I=`${c}_${h.pathname}`.replace(/[^a-zA-Z0-9]+/g,"_")+".ndjson",U=ir(n??"",I);xi(`${U}`,await _.text(),()=>{console.log(`${U} is created`)})})});sr.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=ir(n??process.cwd(),e),s=await l(t);await Ti(a,parseInt(r,10),s,o)});async function Ti(e,t,r,o){let n=[],a=Pi(e),s=Ii({input:a});for await(let c of s){let p=_i(c,o);n.push({resource:p,request:{method:"POST",url:p.resourceType}}),n.length%t===0&&(await nr(n,r),n=[])}n.length>0&&await nr(n,r)}async function nr(e,t){(await t.executeBatch({resourceType:"Bundle",type:"transaction",entry:e})).entry?.forEach(o=>{R(o.response)})}function _i(e,t){let r=JSON.parse(e);return t?Ki(r):r}function Ki(e){return e.resourceType==="ExplanationOfBenefit"?Hi(e):e}function Hi(e){return e.provider||(e.provider=$e()),e.item?.forEach(t=>{t?.productOrService||(t.productOrService=$e())}),e}import{formatHl7DateTime as Wi,Hl7Message as Ji}from"@medplum/core";import{connect as ki}from"net";import{Hl7Message as Ri}from"@medplum/core";import Di from"net";var lr=class extends EventTarget{addEventListener(e,t,r){super.addEventListener(e,t,r)}removeEventListener(e,t,r){super.removeEventListener(e,t,r)}},Oi=String.fromCharCode(11),dr=String.fromCharCode(28),pr=String.fromCharCode(13),Mi=class extends Event{constructor(e,t){super("message"),this.connection=e,this.message=t}},mr=class extends Event{constructor(e){super("error"),this.error=e}},ur=class extends lr{constructor(e,t){super(),this.socket=e,this.encoding=t;let r="";e.on("data",o=>{try{if(r+=o.toString(),r.endsWith(dr+pr)){let n=Ri.parse(r.substring(1,r.length-2));this.dispatchEvent(new Mi(this,n)),r=""}}catch(n){this.dispatchEvent(new mr(n))}}).setEncoding(t??"utf-8"),e.on("error",o=>{r="",this.dispatchEvent(new mr(o))})}send(e){this.socket.write(Oi+e.toString()+dr+pr)}async sendAndWait(e){let t=new Promise(r=>{function o(n){n.target.removeEventListener("message",o),r(n.message)}this.addEventListener("message",o)});return this.send(e),t}close(){this.socket.end(),this.socket.destroy()}},fr=class extends lr{constructor(e){super(),this.options=e,this.host=this.options.host,this.port=this.options.port}connect(){return this.connection?Promise.resolve(this.connection):new Promise(e=>{let t=ki({host:this.host,port:this.port},()=>{this.connection=new ur(t),e(this.connection)})})}async send(e){return(await this.connect()).send(e)}async sendAndWait(e){return(await this.connect()).sendAndWait(e)}close(){this.connection&&(this.connection.close(),delete this.connection)}},hr=class{constructor(e){this.handler=e}start(e,t){let r=Di.createServer(o=>{let n=new ur(o,t);this.handler(n)});r.listen(e),this.server=r}stop(){this.server&&(this.server.close(),this.server=void 0)}};import{Command as Ui}from"commander";import{readFileSync as Ni}from"fs";var Li=d("send").description("Send an HL7 v2 message via MLLP").argument("<host>","The destination host name or IP address").argument("<port>","The destination port number").argument("[body]","Optional HL7 message body").option("--generate-example","Generate a sample HL7 message").option("--file <file>","Read the HL7 message from a file").action(async(e,t,r,o)=>{if(o.generate?r=Bi():o.file&&(r=Ni(o.file,"utf8")),!r)throw new Error("Missing HL7 message body");let n=new fr({host:e,port:parseInt(t,10)});try{let a=await n.sendAndWait(Ji.parse(r));console.log(a.toString().replaceAll("\r",`
5
+ `)}function x(e,t=""){return new Promise(r=>{Ee.question(e+(t?" ("+t+")":"")+" ",o=>{r(o||t.toString())})})}async function qe(e,t,r=""){let o=e+" ["+t.map(n=>n===r?"("+n+")":n).join("|")+"]";for(;;){let n=await x(o)||r;if(t.includes(n))return n;i("Please choose one of the following options: "+t.join(", "))}}async function ne(e,t,r){return parseInt(await qe(e,t.map(o=>o.toString()),r.toString()),10)}async function Xe(e){return(await qe(e,["y","n"])).toLowerCase()==="y"}async function be(e){if(!await Xe(e))throw i("Exiting..."),new Error("User cancelled")}function y(e,t){Nn(Ln(e),JSON.stringify(t,void 0,2),"utf-8")}async function Fn(e){try{let t=new Wn({region:e}),r=new Dn({});return(await t.send(r)).Account}catch(t){console.log("Warning: Unable to get AWS account ID",t.message);return}}async function Gn(e){let t=await Bt(e);if(e!=="us-east-1"){let r=await Bt("us-east-1");t.push(...r)}return t}async function Bt(e){try{let t=new Ft({region:e}),r=new _n({MaxItems:1e3});return(await t.send(r)).CertificateSummaryList}catch(t){return console.log("Warning: Unable to list certificates",t.message),[]}}async function zn(e,t,r,o){let n=e[Bn(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 Xe("Do you want to request a new certificate?"))return i(`Please add your certificate ARN to the config file in the "${Gt(o)}" setting.`),"TODO";let s=await Vn(r,n);return i("Certificate ARN: "+s),s}async function Vn(e,t){try{let r=await qe("Validate certificate using DNS or email validation?",["dns","email"],"dns"),o=new Ft({region:e}),n=new Kn({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 jn(e){let t=$t(),r=Jn("rsa",{modulusLength:2048,publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs1",format:"pem",cipher:"aes-256-cbc",passphrase:t}});return{keyId:(await new Hn({}).send(new kn({PublicKeyConfig:{Name:e,CallerReference:$t(),EncodedKey:r.publicKey}}))).PublicKey?.Id,publicKey:r.publicKey,privateKey:r.privateKey,passphrase:t}}async function qn(e,t){let r=new Rn({Name:t,WithDecryption:!0});try{return(await e.send(r)).Parameter?.Value}catch(o){if(o.name==="ParameterNotFound")return;throw o}}async function Xn(e,t,r){let o=new On({Name:t,Value:r,Type:"SecureString",Overwrite:!0});await e.send(o)}async function Yn(e,t,r){let o=new Mn({region:e});for(let[n,a]of Object.entries(r)){let s=t+n,c=a.toString(),p=await qn(o,s);p!==void 0&&p!==c&&(i(`Parameter "${s}" exists with different value.`),await be(`Do you want to overwrite "${s}"?`)),await Xn(o,s,c)}}async function Vt(){let e=await ze();for(let t of e){let r=t.StackName,o=await Ve(r);o&&(we(o),console.log(""))}}import{PutObjectCommand as Zn}from"@aws-sdk/client-s3";import{ContentType as H}from"@medplum/core";import Qn from"fast-glob";import{createReadStream as ei,mkdtempSync as ti,readdirSync as ri,readFileSync as oi,rmSync as ni,writeFileSync as ii}from"fs";import jt from"node-fetch";import{tmpdir as ai}from"os";import{join as ve,sep as si}from"path";import{pipeline as ci}from"stream/promises";async function qt(e,t){let r=q(e);if(!r){console.log("Config not found");return}let o=await W(e);if(!o){console.log("Stack not found");return}let n=o.appBucket;if(!n){console.log("App bucket not found");return}let a=await pi("@medplum/app","latest");Xt(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 li(a,n.PhysicalResourceId,t),o.appDistribution?.PhysicalResourceId&&!t.dryrun&&await Se(o.appDistribution.PhysicalResourceId),console.log("Done")}async function di(e,t){let r=`https://registry.npmjs.org/${e}/${t}`;return(await jt(r)).json()}async function pi(e,t){let o=(await di(e,t)).dist.tarball,n=ti(ve(ai(),"tarball-"));try{let a=await jt(o),s=kt(n);return await ci(a.body,s),ve(n,"package","dist")}catch(a){throw ni(n,{recursive:!0,force:!0}),a}}function Xt(e,t){for(let r of ri(e,{withFileTypes:!0})){let o=ve(e,r.name);r.isDirectory()?Xt(o,t):r.isFile()&&o.endsWith(".js")&&mi(o,t)}}function mi(e,t){let r=oi(e,"utf-8");for(let[o,n]of Object.entries(t))r=r.replaceAll(`__${o}__`,n);ii(e,r)}async function li(e,t,r){let o=[["assets/**/*.css",H.CSS,!0],["assets/**/*.css.map",H.JSON,!0],["assets/**/*.js",H.JAVASCRIPT,!0],["assets/**/*.js.map",H.JSON,!0],["assets/**/*.txt",H.TEXT,!0],["assets/**/*.ico",H.FAVICON,!0],["img/**/*.png",H.PNG,!0],["img/**/*.svg",H.SVG,!0],["robots.txt",H.TEXT,!0],["index.html",H.HTML,!1]];for(let n of o)await ui({rootDir:e,bucketName:t,fileNamePattern:n[0],contentType:n[1],cached:n[2],dryrun:r.dryrun})}async function ui(e){let t=Qn.sync(e.fileNamePattern,{cwd:e.rootDir});for(let r of t)await fi(ve(e.rootDir,r),e)}async function fi(e,t){let r=ei(e),o=e.substring(t.rootDir.length+1).split(si).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 oe.send(new Zn(n))}import{GetBucketPolicyCommand as hi,PutBucketPolicyCommand as yi}from"@aws-sdk/client-s3";async function Zt(e,t){if(!q(e)){console.log("Config not found");return}let o=await W(e);if(!o){console.log("Stack not found");return}await Yt("App",o.appBucket,o.appDistribution,o.appOriginAccessIdentity,t),await Yt("Storage",o.storageBucket,o.storageDistribution,o.storageOriginAccessIdentity,t),console.log("Done")}async function Yt(e,t,r,o,n){if(!t?.PhysicalResourceId){console.log(`${e} bucket not found`);return}if(!r?.PhysicalResourceId){console.log(`${e} distribution not found`);return}if(!o?.PhysicalResourceId){console.log(`${e} OAI not found`);return}let a=t.PhysicalResourceId,s=o.PhysicalResourceId,c=await gi(a);if(Si(c,a,s)){console.log(`${e} bucket already has policy statement`);return}bi(c,a,s),console.log(`${e} bucket policy:`),console.log(JSON.stringify(c,void 0,2)),n.dryrun?console.log("Dry run - skipping updates"):(console.log("Updating bucket policy..."),await wi(a,c),console.log("Bucket policy updated"),console.log("Creating CloudFront invalidation..."),await Se(r.PhysicalResourceId),console.log("CloudFront invalidation created"),console.log(`${e} bucket policy updated`))}async function gi(e){let t=await oe.send(new hi({Bucket:e}));return JSON.parse(t.Policy??"{}")}async function wi(e,t){await oe.send(new yi({Bucket:e,Policy:JSON.stringify(t)}))}function Si(e,t,r){return!!e?.Statement?.some(o=>o?.Effect==="Allow"&&o?.Principal?.AWS===`arn:aws:iam::cloudfront:user/CloudFront Origin Access Identity ${r}`&&Array.isArray(o?.Action)&&o?.Action?.includes("s3:GetObject*")&&o?.Action?.includes("s3:GetBucket*")&&o?.Action?.includes("s3:List*")&&Array.isArray(o?.Resource)&&o?.Resource?.includes(`arn:aws:s3:::${t}`)&&o?.Resource?.includes(`arn:aws:s3:::${t}/*`))}function bi(e,t,r){e.Version||(e.Version="2012-10-17"),e.Statement||(e.Statement=[]),e.Statement.push({Effect:"Allow",Principal:{AWS:`arn:aws:iam::cloudfront:user/CloudFront Origin Access Identity ${r}`},Action:["s3:GetObject*","s3:GetBucket*","s3:List*"],Resource:[`arn:aws:s3:::${t}`,`arn:aws:s3:::${t}/*`]})}import{UpdateServiceCommand as Ei}from"@aws-sdk/client-ecs";async function Qt(e){let t=await W(e);if(!t){console.log("Stack not found");return}let r=t.ecsCluster?.PhysicalResourceId;if(!r){console.log("ECS Cluster not found");return}let o=je(t.ecsService);if(!o){console.log("ECS Service not found");return}await Nt.send(new Ei({cluster:r,service:o,forceNewDeployment:!0})),console.log(`Service "${o}" updated successfully.`)}var J=new vi("aws").description("Commands to manage AWS resources");J.command("init").description("Initialize a new Medplum AWS CloudFormation stacks").action(zt);J.command("list").description("List Medplum AWS CloudFormation stacks").action(Vt);J.command("describe").description("Describe a Medplum AWS CloudFormation stack by tag").argument("<tag>").action(Lt);J.command("update-server").alias("deploy-server").description("Update the server image").argument("<tag>").action(Qt);J.command("update-app").alias("deploy-app").description("Update the app site").argument("<tag>").option("--dryrun","Displays the operations that would be performed using the specified command without actually running them.").action(qt);J.command("update-bucket-policies").description("Update S3 bucket policies").argument("<tag>").option("--dryrun","Displays the operations that would be performed using the specified command without actually running them.").action(Zt);import{Command as Ci}from"commander";var er=d("save"),tr=d("deploy"),rr=d("create"),or=new Ci("bot").addCommand(er).addCommand(tr).addCommand(rr),Ye=d("save-bot"),Ze=d("deploy-bot"),Qe=d("create-bot");er.description("Saving the bot").argument("<botName>").action(async(e,t)=>{let r=await l(t);await Ce(r,e)});tr.description("Deploy the app to AWS").argument("<botName>").action(async(e,t)=>{let r=await l(t);await Ce(r,e,!0)});rr.arguments("<botName> <projectId> <sourceFile> <distFile>").description("Creating a bot").option("--runtime-version <runtimeVersion>","Runtime version (awslambda, vmcontext)").action(async(e,t,r,o,n)=>{let a=await l(n);await Ne(a,e,t,r,o,n.runtimeVersion)});async function Ce(e,t,r=!1){let o=Ht(t);for(let n of o){let a=await e.readResource("Bot",n.id);await Je(e,n,a),r&&await Ue(e,n,a)}console.log(`Number of bots deployed: ${o.length}`)}Ye.description("Saves the bot").argument("<botName>").action(async(e,t)=>{let r=await l(t);await Ce(r,e)});Ze.description("Deploy the bot to AWS").argument("<botName>").action(async(e,t)=>{let r=await l(t);await Ce(r,e,!0)});Qe.arguments("<botName> <projectId> <sourceFile> <distFile>").description("Creates and saves the bot").action(async(e,t,r,o,n)=>{let a=await l(n);await Ne(a,e,t,r,o)});import{Command as Ai}from"commander";import{createReadStream as Pi,writeFile as xi}from"fs";import{resolve as ir}from"path";import{createInterface as Ii}from"readline";var ar=d("export"),sr=d("import"),cr=new Ai("bulk").addCommand(ar).addCommand(sr);ar.option("-e, --export-level <exportLevel>",'Optional export level. Defaults to system level export. "Group/:id" - Group of Patients, "Patient" - All Patients.').option("-t, --types <types>","optional resource types to export").option("-s, --since <since>","optional Resources will be included in the response if their state has changed after the supplied time (e.g. if Resource.meta.lastUpdated is later than the supplied _since time).").option("-d, --target-directory <targetDirectory>","optional target directory to save files from the bulk export operations.").action(async e=>{let{exportLevel:t,types:r,since:o,targetDirectory:n}=e,a=await l(e);(await a.bulkExport(t,r,o)).output?.forEach(async({type:c,url:p})=>{let h=new URL(p),_=await a.download(p),I=`${c}_${h.pathname}`.replace(/[^a-zA-Z0-9]+/g,"_")+".ndjson",U=ir(n??"",I);xi(`${U}`,await _.text(),()=>{console.log(`${U} is created`)})})});sr.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=ir(n??process.cwd(),e),s=await l(t);await Ti(a,parseInt(r,10),s,o)});async function Ti(e,t,r,o){let n=[],a=Pi(e),s=Ii({input:a});for await(let c of s){let p=_i(c,o);n.push({resource:p,request:{method:"POST",url:p.resourceType}}),n.length%t===0&&(await nr(n,r),n=[])}n.length>0&&await nr(n,r)}async function nr(e,t){(await t.executeBatch({resourceType:"Bundle",type:"transaction",entry:e})).entry?.forEach(o=>{R(o.response)})}function _i(e,t){let r=JSON.parse(e);return t?Ki(r):r}function Ki(e){return e.resourceType==="ExplanationOfBenefit"?Hi(e):e}function Hi(e){return e.provider||(e.provider=$e()),e.item?.forEach(t=>{t?.productOrService||(t.productOrService=$e())}),e}import{formatHl7DateTime as Wi,Hl7Message as Ji}from"@medplum/core";import{connect as ki}from"net";import{Hl7Message as Ri}from"@medplum/core";import Di from"net";var lr=class extends EventTarget{addEventListener(e,t,r){super.addEventListener(e,t,r)}removeEventListener(e,t,r){super.removeEventListener(e,t,r)}},Oi=String.fromCharCode(11),dr=String.fromCharCode(28),pr=String.fromCharCode(13),Mi=class extends Event{constructor(e,t){super("message"),this.connection=e,this.message=t}},mr=class extends Event{constructor(e){super("error"),this.error=e}},ur=class extends lr{constructor(e,t){super(),this.socket=e,this.encoding=t;let r="";e.on("data",o=>{try{if(r+=o.toString(),r.endsWith(dr+pr)){let n=Ri.parse(r.substring(1,r.length-2));this.dispatchEvent(new Mi(this,n)),r=""}}catch(n){this.dispatchEvent(new mr(n))}}).setEncoding(t??"utf-8"),e.on("error",o=>{r="",this.dispatchEvent(new mr(o))})}send(e){this.socket.write(Oi+e.toString()+dr+pr)}async sendAndWait(e){let t=new Promise(r=>{function o(n){n.target.removeEventListener("message",o),r(n.message)}this.addEventListener("message",o)});return this.send(e),t}close(){this.socket.end(),this.socket.destroy()}},fr=class extends lr{constructor(e){super(),this.options=e,this.host=this.options.host,this.port=this.options.port}connect(){return this.connection?Promise.resolve(this.connection):new Promise(e=>{let t=ki({host:this.host,port:this.port},()=>{this.connection=new ur(t),e(this.connection)})})}async send(e){return(await this.connect()).send(e)}async sendAndWait(e){return(await this.connect()).sendAndWait(e)}close(){this.connection&&(this.connection.close(),delete this.connection)}},hr=class{constructor(e){this.handler=e}start(e,t){let r=Di.createServer(o=>{let n=new ur(o,t);this.handler(n)});r.listen(e),this.server=r}stop(){this.server&&(this.server.close(),this.server=void 0)}};import{Command as Ui}from"commander";import{readFileSync as Ni}from"fs";var Li=d("send").description("Send an HL7 v2 message via MLLP").argument("<host>","The destination host name or IP address").argument("<port>","The destination port number").argument("[body]","Optional HL7 message body").option("--generate-example","Generate a sample HL7 message").option("--file <file>","Read the HL7 message from a file").action(async(e,t,r,o)=>{if(o.generateExample?r=Bi():o.file&&(r=Ni(o.file,"utf8")),!r)throw new Error("Missing HL7 message body");let n=new fr({host:e,port:parseInt(t,10)});try{let a=await n.sendAndWait(Ji.parse(r));console.log(a.toString().replaceAll("\r",`
6
6
  `))}finally{n.close()}}),$i=d("listen").description("Starts an HL7 v2 MLLP server").argument("<port>").action(async e=>{new hr(r=>{r.addEventListener("message",({message:o})=>{console.log(o.toString().replaceAll("\r",`
7
7
  `)),r.send(o.buildAck())})}).start(parseInt(e,10)),console.log("Listening on port "+e)}),yr=new Ui("hl7").addCommand(Li).addCommand($i);function Bi(){let e=Wi(new Date),t=Date.now().toString();return`MSH|^~\\&|ADTSYS|HOSPITAL|RECEIVER|DEST|${e}||ADT^A01|${t}|P|2.5|
8
8
  EVN|A01|${e}||