medplum 4.2.0 → 4.2.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/index.cjs +11 -11
- package/dist/cjs/index.cjs.map +3 -3
- package/dist/esm/index.mjs +8 -8
- package/dist/esm/index.mjs.map +3 -3
- package/package.json +3 -3
package/dist/esm/index.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var Q=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,r)=>(typeof require<"u"?require:t)[r]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var ho=(e,t)=>()=>(e&&(t=e(e=0)),t);var mo=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);import{MEDPLUM_VERSION as Vo,normalizeErrorString as et}from"@medplum/core";import{CommanderError as qt,Option as Xo}from"commander";import qo from"dotenv";import{ContentType as zt,isOk as zo,isUUID as Yo}from"@medplum/core";import{Option as dt}from"commander";import{MedplumClient as Zo}from"@medplum/core";import{ClientStorage as Qo}from"@medplum/core";import{existsSync as At,mkdirSync as ea,readFileSync as ta,writeFileSync as ra}from"node:fs";import{homedir as oa}from"node:os";import{resolve as $t}from"node:path";import{ContentType as Xe,encodeBase64 as Rt}from"@medplum/core";import{Command as sa}from"commander";import{Buffer as na}from"node:buffer";import*as Zt from"node:util";import*as er from"node:crypto";import*as tr from"node:util";import{KeyObject as wa}from"node:crypto";import{KeyObject as $a}from"node:crypto";import{constants as Lt,KeyObject as Ca}from"node:crypto";import*as xe from"node:crypto";import{promisify as Ma}from"node:util";import{KeyObject as Ct,createSecretKey as kt}from"node:crypto";import{createHmac as Ja,createPrivateKey as Va,randomBytes as Xa}from"node:crypto";import{existsSync as qa,readFileSync as nr,writeFileSync as cr}from"node:fs";import{basename as lr,extname as za,resolve as mt}from"node:path";import{isPromise as Ya}from"node:util/types";import{extract as Za}from"tar";import{ContentType as Te,getDisplayString as mi,MEDPLUM_CLI_CLIENT_ID as fi,normalizeErrorString as gi}from"@medplum/core";import{exec as yi}from"node:child_process";import{createServer as wi}from"node:http";import{platform as Ei}from"node:os";import{CloudFormationClient as Rr,DescribeStackResourcesCommand as Li,DescribeStacksCommand as Ci,paginateListStacks as ki}from"@aws-sdk/client-cloudformation";import{CloudFrontClient as Di,CreateInvalidationCommand as Mi}from"@aws-sdk/client-cloudfront";import{ECSClient as _i}from"@aws-sdk/client-ecs";import{S3Client as Ui}from"@aws-sdk/client-s3";import{GetParameterCommand as xi,PutParameterCommand as ji,SSMClient as Fi}from"@aws-sdk/client-ssm";import{GetCallerIdentityCommand as Wi,STSClient as Hi}from"@aws-sdk/client-sts";import{normalizeErrorString as Bi}from"@medplum/core";import Ki from"node-fetch";import{readdirSync as Gi}from"node:fs";import Ji from"node:readline";import{ACMClient as Mr,ListCertificatesCommand as es,RequestCertificateCommand as ts}from"@aws-sdk/client-acm";import{CloudFrontClient as rs,CreatePublicKeyCommand as os}from"@aws-sdk/client-cloudfront";import{GetCallerIdentityCommand as as,STSClient as is}from"@aws-sdk/client-sts";import{normalizeErrorString as ss}from"@medplum/core";import{generateKeyPairSync as ns,randomUUID as Ut}from"node:crypto";import{existsSync as cs}from"node:fs";import{PutObjectCommand as ys}from"@aws-sdk/client-s3";import{ContentType as z}from"@medplum/core";import ws from"fast-glob";import Ur from"node-fetch";import{createReadStream as Es,mkdtempSync as vs,readdirSync as Ss,readFileSync as Is,rmSync as bs,writeFileSync as As}from"node:fs";import{tmpdir as $s}from"node:os";import{join as Ce,sep as Rs}from"node:path";import{pipeline as Ts}from"node:stream/promises";import{GetBucketPolicyCommand as Ms,PutBucketPolicyCommand as _s}from"@aws-sdk/client-s3";import{spawnSync as Js}from"node:child_process";import{createReadStream as Ys,writeFile as Zs}from"node:fs";import{resolve as Gr}from"node:path";import{createInterface as Qs}from"node:readline";import{formatHl7DateTime as an,Hl7Message as sn}from"@medplum/core";import{connect as nn}from"node:net";import{Hl7Message as cn}from"@medplum/core";import Ht from"iconv-lite";import ln from"node:net";import{readFileSync as hn}from"node:fs";import{readdirSync as yn}from"node:fs";import{homedir as wn}from"node:os";import{resolve as En}from"node:path";import{Option as vn}from"commander";import{convertToTransactionBundle as An}from"@medplum/core";async function U(e,t=!0){let r=e.profile??"default",o=new Se(r),a=o.getObject("options");if(r!=="default"&&!a)throw new Error(`Profile "${r}" does not exist`);let{baseUrl:i,fhirUrlPath:n,accessToken:c,tokenUrl:s,authorizeUrl:f,clientId:l,clientSecret:u}=aa(e,o),h=e.fetch??fetch,d=new Zo({fetch:h,baseUrl:i,tokenUrl:s,fhirUrlPath:n,authorizeUrl:f,storage:o,onUnauthenticated:ia,verbose:e.verbose});return t&&(c?d.setAccessToken(c):l&&u&&(d.setBasicAuth(l,u),a?.authType!=="basic"&&await d.startClientLogin(l,u))),d}function aa(e,t){let r=t.getObject("options"),o=e.baseUrl??r?.baseUrl??process.env.MEDPLUM_BASE_URL??"https://api.medplum.com/",a=e.fhirUrlPath??r?.fhirUrlPath??process.env.MEDPLUM_FHIR_URL_PATH,i=e.accessToken??r?.accessToken??process.env.MEDPLUM_CLIENT_ACCESS_TOKEN,n=e.tokenUrl??r?.tokenUrl??process.env.MEDPLUM_TOKEN_URL,c=e.authorizeUrl??r?.authorizeUrl??process.env.MEDPLUM_AUTHORIZE_URL,s=e.clientId??r?.clientId??process.env.MEDPLUM_CLIENT_ID,f=e.clientSecret??r?.clientSecret??process.env.MEDPLUM_CLIENT_SECRET;return{baseUrl:o,fhirUrlPath:a,accessToken:i,tokenUrl:n,authorizeUrl:c,clientId:s,clientSecret:f}}function ia(){console.log("Unauthenticated: run `npx medplum login` to sign in")}function ca(...e){let t=e.reduce((a,{length:i})=>a+i,0),r=new Uint8Array(t),o=0;for(let a of e)r.set(a,o),o+=a.length;return r}function q(e,t="algorithm.name"){return new TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`)}function fe(e,t){return e.name===t}function ze(e){return parseInt(e.name.slice(4),10)}function da(e){switch(e){case"ES256":return"P-256";case"ES384":return"P-384";case"ES512":return"P-521";default:throw new Error("unreachable")}}function ha(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 ma(e,t,...r){switch(t){case"HS256":case"HS384":case"HS512":{if(!fe(e.algorithm,"HMAC"))throw q("HMAC");let o=parseInt(t.slice(2),10);if(ze(e.algorithm.hash)!==o)throw q(`SHA-${o}`,"algorithm.hash");break}case"RS256":case"RS384":case"RS512":{if(!fe(e.algorithm,"RSASSA-PKCS1-v1_5"))throw q("RSASSA-PKCS1-v1_5");let o=parseInt(t.slice(2),10);if(ze(e.algorithm.hash)!==o)throw q(`SHA-${o}`,"algorithm.hash");break}case"PS256":case"PS384":case"PS512":{if(!fe(e.algorithm,"RSA-PSS"))throw q("RSA-PSS");let o=parseInt(t.slice(2),10);if(ze(e.algorithm.hash)!==o)throw q(`SHA-${o}`,"algorithm.hash");break}case"EdDSA":{if(e.algorithm.name!=="Ed25519"&&e.algorithm.name!=="Ed448")throw q("Ed25519 or Ed448");break}case"Ed25519":{if(!fe(e.algorithm,"Ed25519"))throw q("Ed25519");break}case"ES256":case"ES384":case"ES512":{if(!fe(e.algorithm,"ECDSA"))throw q("ECDSA");let o=da(t);if(e.algorithm.namedCurve!==o)throw q(o,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}ha(e,r)}function rr(e,t,...r){if(r=r.filter(Boolean),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?.name&&(e+=` Received an instance of ${t.constructor.name}`),e}function or(e,t,...r){return rr(`Key for the ${e} algorithm must be `,t,...r)}function ya(e){return typeof e=="object"&&e!==null}function ir(e){if(!ya(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}function be(e){return ir(e)&&typeof e.kty=="string"}function Ea(e){return e.kty!=="oct"&&typeof e.d=="string"}function va(e){return e.kty!=="oct"&&typeof e.d>"u"}function Sa(e){return be(e)&&e.kty==="oct"&&typeof e.k=="string"}function sr(e,t,r,o){t.startsWith("HS")||t==="dir"||t.startsWith("PBES2")||/^A\d{3}(?:GCM)?KW$/.test(t)?Ra(t,r,o,e):Ta(t,r,o,e)}function Pa(e,t,r,o,a){if(a.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(n=>typeof n!="string"||n.length===0))throw new e('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');let i;r!==void 0?i=new Map([...Object.entries(r),...t.entries()]):i=t;for(let n of o.crit){if(!i.has(n))throw new ue(`Extension Header Parameter "${n}" is not recognized`);if(a[n]===void 0)throw new e(`Extension Header Parameter "${n}" is missing`);if(i.get(n)&&o[n]===void 0)throw new e(`Extension Header Parameter "${n}" MUST be integrity protected`)}return new Set(o.crit)}function La(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"Ed25519":case"EdDSA":return;default:throw new ue(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}function Da(e,t){let r,o,a;if(t instanceof Ca)r=t.asymmetricKeyType,o=t.asymmetricKeyDetails;else switch(a=!0,t.kty){case"RSA":r="rsa";break;case"EC":r="ec";break;case"OKP":{if(t.crv==="Ed25519"){r="ed25519";break}if(t.crv==="Ed448"){r="ed448";break}throw new TypeError("Invalid key for this operation, its crv must be Ed25519 or Ed448")}default:throw new TypeError("Invalid key for this operation, its kty must be RSA, OKP, or EC")}let i;switch(e){case"Ed25519":if(r!=="ed25519")throw new TypeError("Invalid key for this operation, its asymmetricKeyType must be ed25519");break;case"EdDSA":if(!["ed25519","ed448"].includes(r))throw new TypeError("Invalid key for this operation, its asymmetricKeyType must be ed25519 or ed448");break;case"RS256":case"RS384":case"RS512":if(r!=="rsa")throw new TypeError("Invalid key for this operation, its asymmetricKeyType must be rsa");Ot(t,e);break;case"PS256":case"PS384":case"PS512":if(r==="rsa-pss"){let{hashAlgorithm:n,mgf1HashAlgorithm:c,saltLength:s}=o,f=parseInt(e.slice(-3),10);if(n!==void 0&&(n!==`sha${f}`||c!==n))throw new TypeError(`Invalid key for this operation, its RSA-PSS parameters do not meet the requirements of "alg" ${e}`);if(s!==void 0&&s>f>>3)throw new TypeError(`Invalid key for this operation, its RSA-PSS parameter saltLength does not meet the requirements of "alg" ${e}`)}else if(r!=="rsa")throw new TypeError("Invalid key for this operation, its asymmetricKeyType must be rsa or rsa-pss");Ot(t,e),i={padding:Lt.RSA_PKCS1_PSS_PADDING,saltLength:Lt.RSA_PSS_SALTLEN_DIGEST};break;case"ES256":case"ES256K":case"ES384":case"ES512":{if(r!=="ec")throw new TypeError("Invalid key for this operation, its asymmetricKeyType must be ec");let n=Aa(t),c=ka.get(e);if(n!==c)throw new TypeError(`Invalid key curve for the algorithm, its curve must be ${c}, got ${n}`);i={dsaEncoding:"ieee-p1363"};break}default:throw new ue(`alg ${e} is not supported either by JOSE or your javascript runtime`)}return a?{format:"jwk",key:t,...i}:i?{...i,key:t}:t}function _a(e){switch(e){case"HS256":return"sha256";case"HS384":return"sha384";case"HS512":return"sha512";default:throw new ue(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}function Ua(e,t,r){if(t instanceof Uint8Array){if(!e.startsWith("HS"))throw new TypeError(tt(t,...ne));return kt(t)}if(t instanceof Ct)return t;if(ht(t))return ma(t,e,r),Ct.from(t);if(be(t))return e.startsWith("HS")?kt(Buffer.from(t.k,"base64url")):t;throw new TypeError(tt(t,...ne,"Uint8Array","JSON Web Key"))}function te(e,t){if(!Number.isFinite(t))throw new TypeError(`Invalid ${e} input`);return t}function re(e){console.log(JSON.stringify(e,null,2))}async function ur(e,t,r){let o=t.source,a=je(o);if(!a)return;console.log("Saving source code...");let i=await e.createAttachment({data:a,filename:lr(o),contentType:ai(o)});console.log("Updating bot...");let n=await e.updateResource({...r,sourceCode:i});console.log("Success! New bot version: "+n.meta?.versionId)}async function pr(e,t,r){let o=t.dist??t.source,a=je(o);if(!a)return;console.log("Deploying bot...");let i=await e.post(e.fhirUrl("Bot",r.id,"$deploy"),{code:a,filename:lr(o)});console.log("Deploy result: "+i.issue?.[0]?.details?.text)}async function dr(e,t,r,o,a,i,n){let c={name:t,description:"",runtimeVersion:i},s=await e.post("admin/projects/"+r+"/bot",c),f=await e.readResource("Bot",s.id),l={name:t,id:s.id,source:o,dist:a};await ur(e,l,f),await pr(e,l,f),console.log(`Success! Bot created: ${f.id}`),n&&ti(l)}function Qa(e){let t=new RegExp("^"+ri(e).replace(/\\\*/g,".*")+"$");return pe()?.bots?.filter(o=>t.test(o.name))||[]}function oe(e,t){if(t?.file)return t.file;let r=["medplum"];return e&&r.push(e),r.push("config"),t?.server&&r.push("server"),r.push("json"),r.join(".")}function H(e,t){cr(mt(e),JSON.stringify(t,void 0,2),"utf-8")}function pe(e,t){let r=oe(e,t),o=je(r);if(o)return JSON.parse(o)}function ei(e){let t=je(oe(e,{server:!0}));if(t)return JSON.parse(t)}function je(e){let t=mt(e);return qa(t)?nr(t,"utf8"):""}function ti(e){let t=pe()??{};t.bots||(t.bots=[]),t.bots.push(e),cr("medplum.config.json",JSON.stringify(t,null,2),"utf8"),console.log(`Bot added to config: ${e.id}`)}function ri(e){return e.replace(/[/\-\\^$*+?.()|[\]{}]/g,"\\$&")}function oi(e){let t=0,r=0;return Za({cwd:e,filter:(o,a)=>{if(t++,t>100)throw new Error("Tar extractor reached max number of files");if(r+=a.size,r>10485760)throw new Error("Tar extractor reached max size");return!0}})}function Dt(){return{url:"http://hl7.org/fhir/StructureDefinition/data-absent-reason",valueCode:"unsupported"}}function ai(e){let t=za(e).toLowerCase();return[".cjs",".mjs",".js"].includes(t)?Xe.JAVASCRIPT:[".cts",".mts",".ts"].includes(t)?Xe.TYPESCRIPT:Xe.TEXT}function hr(e,t){let r=new Se(e),o={name:e,...t};return r.setObject("options",o),o}function ii(e){return new Se(e).getObject("options")}async function si(e,t){let r={typ:"JWT",alg:"HS256"},o=Math.floor(Date.now()/1e3),a={aud:`${t.baseUrl}${t.audience}`,iss:t.issuer,sub:t.subject,nbf:o,iat:o,exp:o+604800},i=Rt(JSON.stringify(r)),n=Rt(JSON.stringify(a)),c=`${i}.${n}`,s=Ja("sha256",t.clientSecret).update(c).digest("base64url"),f=`${c}.${s}`;await e.startJwtBearerLogin(t.clientId,f,t.scope??"")}async function ni(e,t){let r=Va(nr(mt(t.privateKeyPath))),o=await new Ga({}).setProtectedHeader({alg:"RS384",typ:"JWT"}).setIssuer(t.clientId).setSubject(t.clientId).setAudience(`${t.baseUrl}${t.audience}`).setJti(Xa(16).toString("hex")).setIssuedAt().setExpirationTime("5m").sign(r);await e.startJwtAssertionLogin(o)}function N(e,t){t.configureHelp({showGlobalOptions:!0}),e.addCommand(t)}function ci(e,t){return async r=>{let o=e.registeredArguments.length,a=r.slice(0,o);a[o]=e.optsWithGlobals();try{let i=t(...a);Ya(i)&&await i}finally{e.resetOptionDefaults()}}}async function ft({operation:e,agentIds:t,options:r,parseSuccessfulResponse:o}){let a=hi(t,r),i=await U(r),n=a.type==="criteria"?a.criteria:`Agent?_id=${a.ids.join(",")}`,c=new URLSearchParams(n.split("?")[1]),s;try{let d=i.fhirUrl("Agent",e);d.search=c.toString(),s=await i.get(d,{cache:"reload"})}catch(d){throw new Error(`Operation '${e}' failed`,{cause:d})}if(r.output==="json"){console.info(JSON.stringify(s,null,2));return}let f=[],l=[];switch(s.resourceType){case"Bundle":{let d=li(s);for(let g of d)g.result.resourceType==="Parameters"||zo(g.result)?f.push(g):l.push(g);break}case"Parameters":case"OperationOutcome":{let d=await i.searchOne("Agent",c,{cache:"reload"});if(!d)throw new Error("Agent not found");s.resourceType==="Parameters"?f.push({agent:d,result:s}):l.push({agent:d,result:s});break}default:throw new Error(`Invalid result received for '${e}' operation: ${JSON.stringify(s)}`)}let u=[];for(let d of f){let g=o(d);u.push(g)}let h=[];for(let d of l){let g=d.result.issue?.[0],m={id:d.agent.id,name:d.agent.name,severity:g.severity,code:g.code,details:g.details?.text??"No details to show"};h.push(m)}console.info(`
|
|
2
|
+
var Q=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,r)=>(typeof require<"u"?require:t)[r]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var ho=(e,t)=>()=>(e&&(t=e(e=0)),t);var mo=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);import{MEDPLUM_VERSION as Vo,normalizeErrorString as et}from"@medplum/core";import{CommanderError as qt,Option as Xo}from"commander";import qo from"dotenv";import{ContentType as zt,isOk as zo,isUUID as Yo}from"@medplum/core";import{Option as dt}from"commander";import{MedplumClient as Zo}from"@medplum/core";import{ClientStorage as Qo}from"@medplum/core";import{existsSync as At,mkdirSync as ea,readFileSync as ta,writeFileSync as ra}from"node:fs";import{homedir as oa}from"node:os";import{resolve as $t}from"node:path";import{ContentType as Xe,encodeBase64 as Rt}from"@medplum/core";import{Command as sa}from"commander";import{Buffer as na}from"node:buffer";import*as Zt from"node:util";import*as er from"node:crypto";import*as tr from"node:util";import{KeyObject as wa}from"node:crypto";import{KeyObject as $a}from"node:crypto";import{constants as Lt,KeyObject as Ca}from"node:crypto";import*as xe from"node:crypto";import{promisify as Ma}from"node:util";import{KeyObject as Ct,createSecretKey as kt}from"node:crypto";import{createHmac as Ja,createPrivateKey as Va,randomBytes as Xa}from"node:crypto";import{existsSync as qa,readFileSync as nr,writeFileSync as cr}from"node:fs";import{basename as lr,extname as za,resolve as mt}from"node:path";import{isPromise as Ya}from"node:util/types";import{extract as Za}from"tar";import{ContentType as Te,getDisplayString as mi,MEDPLUM_CLI_CLIENT_ID as fi,normalizeErrorString as gi}from"@medplum/core";import{exec as yi}from"node:child_process";import{createServer as wi}from"node:http";import{platform as Ei}from"node:os";import{CloudFormationClient as Rr,DescribeStackResourcesCommand as Li,DescribeStacksCommand as Ci,paginateListStacks as ki}from"@aws-sdk/client-cloudformation";import{CloudFrontClient as Di,CreateInvalidationCommand as Mi}from"@aws-sdk/client-cloudfront";import{ECSClient as _i}from"@aws-sdk/client-ecs";import{S3Client as Ui}from"@aws-sdk/client-s3";import{GetParameterCommand as xi,PutParameterCommand as ji,SSMClient as Fi}from"@aws-sdk/client-ssm";import{GetCallerIdentityCommand as Wi,STSClient as Hi}from"@aws-sdk/client-sts";import{normalizeErrorString as Bi}from"@medplum/core";import Ki from"node-fetch";import{readdirSync as Gi}from"node:fs";import Ji from"node:readline";import{ACMClient as Mr,ListCertificatesCommand as es,RequestCertificateCommand as ts}from"@aws-sdk/client-acm";import{CloudFrontClient as rs,CreatePublicKeyCommand as os}from"@aws-sdk/client-cloudfront";import{GetCallerIdentityCommand as as,STSClient as is}from"@aws-sdk/client-sts";import{normalizeErrorString as ss}from"@medplum/core";import{generateKeyPairSync as ns,randomUUID as Ut}from"node:crypto";import{existsSync as cs}from"node:fs";import{PutObjectCommand as ys}from"@aws-sdk/client-s3";import{ContentType as z}from"@medplum/core";import ws from"fast-glob";import Ur from"node-fetch";import{createReadStream as Es,mkdtempSync as vs,readdirSync as Ss,readFileSync as Is,rmSync as bs,writeFileSync as As}from"node:fs";import{tmpdir as $s}from"node:os";import{join as Ce,sep as Rs}from"node:path";import{pipeline as Ts}from"node:stream/promises";import{GetBucketPolicyCommand as Ms,PutBucketPolicyCommand as _s}from"@aws-sdk/client-s3";import{spawnSync as Js}from"node:child_process";import{createReadStream as Ys,writeFile as Zs}from"node:fs";import{resolve as Gr}from"node:path";import{createInterface as Qs}from"node:readline";import{formatHl7DateTime as an,Hl7Message as sn}from"@medplum/core";import{connect as nn}from"node:net";import{Hl7Message as cn}from"@medplum/core";import Ht from"iconv-lite";import{sleep as ln}from"@medplum/core";import un from"node:net";import{readFileSync as mn}from"node:fs";import{readdirSync as wn}from"node:fs";import{homedir as En}from"node:os";import{resolve as vn}from"node:path";import{Option as Sn}from"commander";import{convertToTransactionBundle as $n}from"@medplum/core";async function U(e,t=!0){let r=e.profile??"default",o=new Se(r),a=o.getObject("options");if(r!=="default"&&!a)throw new Error(`Profile "${r}" does not exist`);let{baseUrl:i,fhirUrlPath:n,accessToken:c,tokenUrl:s,authorizeUrl:f,clientId:l,clientSecret:u}=aa(e,o),h=e.fetch??fetch,d=new Zo({fetch:h,baseUrl:i,tokenUrl:s,fhirUrlPath:n,authorizeUrl:f,storage:o,onUnauthenticated:ia,verbose:e.verbose});return t&&(c?d.setAccessToken(c):l&&u&&(d.setBasicAuth(l,u),a?.authType!=="basic"&&await d.startClientLogin(l,u))),d}function aa(e,t){let r=t.getObject("options"),o=e.baseUrl??r?.baseUrl??process.env.MEDPLUM_BASE_URL??"https://api.medplum.com/",a=e.fhirUrlPath??r?.fhirUrlPath??process.env.MEDPLUM_FHIR_URL_PATH,i=e.accessToken??r?.accessToken??process.env.MEDPLUM_CLIENT_ACCESS_TOKEN,n=e.tokenUrl??r?.tokenUrl??process.env.MEDPLUM_TOKEN_URL,c=e.authorizeUrl??r?.authorizeUrl??process.env.MEDPLUM_AUTHORIZE_URL,s=e.clientId??r?.clientId??process.env.MEDPLUM_CLIENT_ID,f=e.clientSecret??r?.clientSecret??process.env.MEDPLUM_CLIENT_SECRET;return{baseUrl:o,fhirUrlPath:a,accessToken:i,tokenUrl:n,authorizeUrl:c,clientId:s,clientSecret:f}}function ia(){console.log("Unauthenticated: run `npx medplum login` to sign in")}function ca(...e){let t=e.reduce((a,{length:i})=>a+i,0),r=new Uint8Array(t),o=0;for(let a of e)r.set(a,o),o+=a.length;return r}function q(e,t="algorithm.name"){return new TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`)}function fe(e,t){return e.name===t}function ze(e){return parseInt(e.name.slice(4),10)}function da(e){switch(e){case"ES256":return"P-256";case"ES384":return"P-384";case"ES512":return"P-521";default:throw new Error("unreachable")}}function ha(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 ma(e,t,...r){switch(t){case"HS256":case"HS384":case"HS512":{if(!fe(e.algorithm,"HMAC"))throw q("HMAC");let o=parseInt(t.slice(2),10);if(ze(e.algorithm.hash)!==o)throw q(`SHA-${o}`,"algorithm.hash");break}case"RS256":case"RS384":case"RS512":{if(!fe(e.algorithm,"RSASSA-PKCS1-v1_5"))throw q("RSASSA-PKCS1-v1_5");let o=parseInt(t.slice(2),10);if(ze(e.algorithm.hash)!==o)throw q(`SHA-${o}`,"algorithm.hash");break}case"PS256":case"PS384":case"PS512":{if(!fe(e.algorithm,"RSA-PSS"))throw q("RSA-PSS");let o=parseInt(t.slice(2),10);if(ze(e.algorithm.hash)!==o)throw q(`SHA-${o}`,"algorithm.hash");break}case"EdDSA":{if(e.algorithm.name!=="Ed25519"&&e.algorithm.name!=="Ed448")throw q("Ed25519 or Ed448");break}case"Ed25519":{if(!fe(e.algorithm,"Ed25519"))throw q("Ed25519");break}case"ES256":case"ES384":case"ES512":{if(!fe(e.algorithm,"ECDSA"))throw q("ECDSA");let o=da(t);if(e.algorithm.namedCurve!==o)throw q(o,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}ha(e,r)}function rr(e,t,...r){if(r=r.filter(Boolean),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?.name&&(e+=` Received an instance of ${t.constructor.name}`),e}function or(e,t,...r){return rr(`Key for the ${e} algorithm must be `,t,...r)}function ya(e){return typeof e=="object"&&e!==null}function ir(e){if(!ya(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}function be(e){return ir(e)&&typeof e.kty=="string"}function Ea(e){return e.kty!=="oct"&&typeof e.d=="string"}function va(e){return e.kty!=="oct"&&typeof e.d>"u"}function Sa(e){return be(e)&&e.kty==="oct"&&typeof e.k=="string"}function sr(e,t,r,o){t.startsWith("HS")||t==="dir"||t.startsWith("PBES2")||/^A\d{3}(?:GCM)?KW$/.test(t)?Ra(t,r,o,e):Ta(t,r,o,e)}function Pa(e,t,r,o,a){if(a.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(n=>typeof n!="string"||n.length===0))throw new e('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');let i;r!==void 0?i=new Map([...Object.entries(r),...t.entries()]):i=t;for(let n of o.crit){if(!i.has(n))throw new ue(`Extension Header Parameter "${n}" is not recognized`);if(a[n]===void 0)throw new e(`Extension Header Parameter "${n}" is missing`);if(i.get(n)&&o[n]===void 0)throw new e(`Extension Header Parameter "${n}" MUST be integrity protected`)}return new Set(o.crit)}function La(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"Ed25519":case"EdDSA":return;default:throw new ue(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}function Da(e,t){let r,o,a;if(t instanceof Ca)r=t.asymmetricKeyType,o=t.asymmetricKeyDetails;else switch(a=!0,t.kty){case"RSA":r="rsa";break;case"EC":r="ec";break;case"OKP":{if(t.crv==="Ed25519"){r="ed25519";break}if(t.crv==="Ed448"){r="ed448";break}throw new TypeError("Invalid key for this operation, its crv must be Ed25519 or Ed448")}default:throw new TypeError("Invalid key for this operation, its kty must be RSA, OKP, or EC")}let i;switch(e){case"Ed25519":if(r!=="ed25519")throw new TypeError("Invalid key for this operation, its asymmetricKeyType must be ed25519");break;case"EdDSA":if(!["ed25519","ed448"].includes(r))throw new TypeError("Invalid key for this operation, its asymmetricKeyType must be ed25519 or ed448");break;case"RS256":case"RS384":case"RS512":if(r!=="rsa")throw new TypeError("Invalid key for this operation, its asymmetricKeyType must be rsa");Ot(t,e);break;case"PS256":case"PS384":case"PS512":if(r==="rsa-pss"){let{hashAlgorithm:n,mgf1HashAlgorithm:c,saltLength:s}=o,f=parseInt(e.slice(-3),10);if(n!==void 0&&(n!==`sha${f}`||c!==n))throw new TypeError(`Invalid key for this operation, its RSA-PSS parameters do not meet the requirements of "alg" ${e}`);if(s!==void 0&&s>f>>3)throw new TypeError(`Invalid key for this operation, its RSA-PSS parameter saltLength does not meet the requirements of "alg" ${e}`)}else if(r!=="rsa")throw new TypeError("Invalid key for this operation, its asymmetricKeyType must be rsa or rsa-pss");Ot(t,e),i={padding:Lt.RSA_PKCS1_PSS_PADDING,saltLength:Lt.RSA_PSS_SALTLEN_DIGEST};break;case"ES256":case"ES256K":case"ES384":case"ES512":{if(r!=="ec")throw new TypeError("Invalid key for this operation, its asymmetricKeyType must be ec");let n=Aa(t),c=ka.get(e);if(n!==c)throw new TypeError(`Invalid key curve for the algorithm, its curve must be ${c}, got ${n}`);i={dsaEncoding:"ieee-p1363"};break}default:throw new ue(`alg ${e} is not supported either by JOSE or your javascript runtime`)}return a?{format:"jwk",key:t,...i}:i?{...i,key:t}:t}function _a(e){switch(e){case"HS256":return"sha256";case"HS384":return"sha384";case"HS512":return"sha512";default:throw new ue(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}function Ua(e,t,r){if(t instanceof Uint8Array){if(!e.startsWith("HS"))throw new TypeError(tt(t,...ne));return kt(t)}if(t instanceof Ct)return t;if(ht(t))return ma(t,e,r),Ct.from(t);if(be(t))return e.startsWith("HS")?kt(Buffer.from(t.k,"base64url")):t;throw new TypeError(tt(t,...ne,"Uint8Array","JSON Web Key"))}function te(e,t){if(!Number.isFinite(t))throw new TypeError(`Invalid ${e} input`);return t}function re(e){console.log(JSON.stringify(e,null,2))}async function ur(e,t,r){let o=t.source,a=je(o);if(!a)return;console.log("Saving source code...");let i=await e.createAttachment({data:a,filename:lr(o),contentType:ai(o)});console.log("Updating bot...");let n=await e.updateResource({...r,sourceCode:i});console.log("Success! New bot version: "+n.meta?.versionId)}async function pr(e,t,r){let o=t.dist??t.source,a=je(o);if(!a)return;console.log("Deploying bot...");let i=await e.post(e.fhirUrl("Bot",r.id,"$deploy"),{code:a,filename:lr(o)});console.log("Deploy result: "+i.issue?.[0]?.details?.text)}async function dr(e,t,r,o,a,i,n){let c={name:t,description:"",runtimeVersion:i},s=await e.post("admin/projects/"+r+"/bot",c),f=await e.readResource("Bot",s.id),l={name:t,id:s.id,source:o,dist:a};await ur(e,l,f),await pr(e,l,f),console.log(`Success! Bot created: ${f.id}`),n&&ti(l)}function Qa(e){let t=new RegExp("^"+ri(e).replace(/\\\*/g,".*")+"$");return pe()?.bots?.filter(o=>t.test(o.name))||[]}function oe(e,t){if(t?.file)return t.file;let r=["medplum"];return e&&r.push(e),r.push("config"),t?.server&&r.push("server"),r.push("json"),r.join(".")}function H(e,t){cr(mt(e),JSON.stringify(t,void 0,2),"utf-8")}function pe(e,t){let r=oe(e,t),o=je(r);if(o)return JSON.parse(o)}function ei(e){let t=je(oe(e,{server:!0}));if(t)return JSON.parse(t)}function je(e){let t=mt(e);return qa(t)?nr(t,"utf8"):""}function ti(e){let t=pe()??{};t.bots||(t.bots=[]),t.bots.push(e),cr("medplum.config.json",JSON.stringify(t,null,2),"utf8"),console.log(`Bot added to config: ${e.id}`)}function ri(e){return e.replace(/[/\-\\^$*+?.()|[\]{}]/g,"\\$&")}function oi(e){let t=0,r=0;return Za({cwd:e,filter:(o,a)=>{if(t++,t>100)throw new Error("Tar extractor reached max number of files");if(r+=a.size,r>10485760)throw new Error("Tar extractor reached max size");return!0}})}function Dt(){return{url:"http://hl7.org/fhir/StructureDefinition/data-absent-reason",valueCode:"unsupported"}}function ai(e){let t=za(e).toLowerCase();return[".cjs",".mjs",".js"].includes(t)?Xe.JAVASCRIPT:[".cts",".mts",".ts"].includes(t)?Xe.TYPESCRIPT:Xe.TEXT}function hr(e,t){let r=new Se(e),o={name:e,...t};return r.setObject("options",o),o}function ii(e){return new Se(e).getObject("options")}async function si(e,t){let r={typ:"JWT",alg:"HS256"},o=Math.floor(Date.now()/1e3),a={aud:`${t.baseUrl}${t.audience}`,iss:t.issuer,sub:t.subject,nbf:o,iat:o,exp:o+604800},i=Rt(JSON.stringify(r)),n=Rt(JSON.stringify(a)),c=`${i}.${n}`,s=Ja("sha256",t.clientSecret).update(c).digest("base64url"),f=`${c}.${s}`;await e.startJwtBearerLogin(t.clientId,f,t.scope??"")}async function ni(e,t){let r=Va(nr(mt(t.privateKeyPath))),o=await new Ga({}).setProtectedHeader({alg:"RS384",typ:"JWT"}).setIssuer(t.clientId).setSubject(t.clientId).setAudience(`${t.baseUrl}${t.audience}`).setJti(Xa(16).toString("hex")).setIssuedAt().setExpirationTime("5m").sign(r);await e.startJwtAssertionLogin(o)}function N(e,t){t.configureHelp({showGlobalOptions:!0}),e.addCommand(t)}function ci(e,t){return async r=>{let o=e.registeredArguments.length,a=r.slice(0,o);a[o]=e.optsWithGlobals();try{let i=t(...a);Ya(i)&&await i}finally{e.resetOptionDefaults()}}}async function ft({operation:e,agentIds:t,options:r,parseSuccessfulResponse:o}){let a=hi(t,r),i=await U(r),n=a.type==="criteria"?a.criteria:`Agent?_id=${a.ids.join(",")}`,c=new URLSearchParams(n.split("?")[1]),s;try{let d=i.fhirUrl("Agent",e);d.search=c.toString(),s=await i.get(d,{cache:"reload"})}catch(d){throw new Error(`Operation '${e}' failed`,{cause:d})}if(r.output==="json"){console.info(JSON.stringify(s,null,2));return}let f=[],l=[];switch(s.resourceType){case"Bundle":{let d=li(s);for(let g of d)g.result.resourceType==="Parameters"||zo(g.result)?f.push(g):l.push(g);break}case"Parameters":case"OperationOutcome":{let d=await i.searchOne("Agent",c,{cache:"reload"});if(!d)throw new Error("Agent not found");s.resourceType==="Parameters"?f.push({agent:d,result:s}):l.push({agent:d,result:s});break}default:throw new Error(`Invalid result received for '${e}' operation: ${JSON.stringify(s)}`)}let u=[];for(let d of f){let g=o(d);u.push(g)}let h=[];for(let d of l){let g=d.result.issue?.[0],m={id:d.agent.id,name:d.agent.name,severity:g.severity,code:g.code,details:g.details?.text??"No details to show"};h.push(m)}console.info(`
|
|
3
3
|
${u.length} successful response(s):
|
|
4
4
|
`),console.table(u.length?u:"No successful responses received"),console.info(),h.length&&(console.info(`${h.length} failed response(s):`),console.info(),console.table(h))}async function Er(e,t,r){if(!(t||r.criteria))throw new Error("This command requires either an [agentId] or a --criteria <criteria> flag");if(t&&r.criteria)throw new Error("Ambiguous arguments and options combination; [agentId] arg and --criteria <criteria> flag are mutually exclusive");let o;if(t)o=t;else{vr(r.criteria);let a=await e.search("Agent",`${r.criteria.split("?")[1]}&_count=2`);if(!a?.entry?.length)throw new Error("Could not find an agent matching the provided criteria");if(a.entry.length!==1)throw new Error("Found more than one agent matching this criteria. This operation requires the criteria to resolve to exactly one agent");o=a.entry[0].resource?.id}return{reference:`Agent/${o}`}}function li(e){let t=[];for(let r of e.entry??[]){if(!r.resource)throw new Error("No Parameter resource found in entry");t.push(ui(r.resource))}return t}function ui(e){let t=e.parameter?.find(o=>o.name==="agent")?.resource;if(!t)throw new Error("Agent bulk operation response missing 'agent'");if(t.resourceType!=="Agent")throw new Error(`Agent bulk operation returned 'agent' with type '${t.resourceType}'`);let r=e.parameter?.find(o=>o.name==="result")?.resource;if(!r)throw new Error("Agent bulk operation response missing result'");if(!(r.resourceType==="Parameters"||r.resourceType==="OperationOutcome"))throw new Error(`Agent bulk operation returned 'result' with type '${r.resourceType}'`);return{agent:t,result:r}}function pi(e,t){let r={},o=t.required,a=t.optional;for(let i of o){let n=e.parameter?.find(s=>s.name===i);if(!n)throw new Error(`Failed to find parameter '${i}'`);let c;for(let s in n)if(s.startsWith("value")){if(c)throw new Error(`Found multiple values for parameter '${i}'`);c=s}if(!c)throw new Error(`Failed to find a value for parameter '${i}'`);r[i]=n[c]}if(a?.length)for(let i of a){let n=e.parameter?.find(s=>s.name===i);if(!n)continue;let c=di(i,n);r[i]=c}return r}function di(e,t){let r;for(let o in t)if(o.startsWith("value")){if(r)throw new Error(`Found multiple values for parameter '${e}'`);r=o}if(!r)throw new Error(`Failed to find a value for parameter '${e}'`);return t[r]}function hi(e,t){if(!Array.isArray(e))throw new Error("Invalid agent IDs array");if(e.length){if(t.criteria)throw new Error("Ambiguous arguments and options combination; [agentIds...] arg and --criteria <criteria> flag are mutually exclusive");for(let r of e)if(!Yo(r))throw new Error(`Input '${r}' is not a valid agentId`);return{type:"ids",ids:e}}if(t.criteria)return vr(t.criteria),{type:"criteria",criteria:t.criteria};throw new Error("Either an [agentId...] arg or a --criteria <criteria> flag is required")}function vr(e){let t="Criteria must be formatted as a string containing the resource type (Agent) followed by a '?' and valid URL search query params, eg. `Agent?name=Test Agent`";if(typeof e!="string")throw new Error(t);let[r,o]=e.split("?");if(r!=="Agent"||!o)throw new Error(t);try{new URLSearchParams(o)}catch(a){throw new Error(t,{cause:a})}if(!o.includes("="))throw new Error(t,{cause:new Error("Query string lacks at least one `=`")})}async function vi(e,t){switch(t?.authType??"authorization-code"){case"authorization-code":await Ai(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 si(e,t);break;case"jwt-assertion":await ni(e,t);break}}async function Si(e){let t=wi(async(r,o)=>{let a=new URL(r.url,"http://localhost:9615"),i=a.searchParams.get("code");if(r.method==="OPTIONS"){o.writeHead(200,{Allow:"GET, POST","Content-Type":Te.TEXT}),o.end("OK");return}if(a.pathname==="/"&&i)try{let n=await e.processCode(i,{clientId:Sr,redirectUri:Ir});o.writeHead(200,{"Content-Type":Te.TEXT}),o.end(`Signed in as ${mi(n)}. You may close this window.`)}catch(n){o.writeHead(400,{"Content-Type":Te.TEXT}),o.end(`Error: ${gi(n)}`)}finally{t.close()}else o.writeHead(404,{"Content-Type":Te.TEXT}),o.end("Not found")}).listen(9615)}async function Ii(e){let t=Ei(),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)}return new Promise((o,a)=>{yi(r,(i,n,c)=>{if(i){a(i);return}if(c){a(new Error("Could not open browser: "+c));return}o()})})}function bi(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 Ai(e){await Si(e);let t=new URL(e.getAuthorizeUrl());t.searchParams.set("client_id",Sr),t.searchParams.set("redirect_uri",Ir),t.searchParams.set("scope","openid"),t.searchParams.set("response_type","code"),t.searchParams.set("prompt","login"),await Ii(t.toString())}function Tr(){Fe=Ji.createInterface({input:process.stdin,output:process.stdout})}function Nr(){Fe.close()}function p(e){Fe.write(e+`
|
|
5
5
|
`)}function j(e){p(`
|
|
@@ -11,15 +11,15 @@ Configuration values come from a file named **medplum.<tag>.config.server.json**
|
|
|
11
11
|
`+Ee.yellow("**Services must be restarted to apply changes.**"))).argument("<tag>","The Medplum stack tag").option("--file [file]",Mt("File to provide overrides for **apiPort**, **baseUrl**, **appDomainName** and **storageDomainName** values that appear in the config file.")).option("--dryrun","Displays the operations that would be performed using the specified command without actually running them.").option("--yes","Automatically confirm the update").action(Hs),N(e,new R("update-server").alias("deploy-server").description("Update the server image").argument("<tag>","The Medplum stack tag").option("--file [file]","Specifies the config file to use. If not specified, the file is based on the tag.").option("--to-version [version]","Specifies the version of the configuration to update. If not specified, the latest version is updated.").action(Vs)),e.command("update-app").alias("deploy-app").description("Update the app site").argument("<tag>","The Medplum stack tag").option("--file [file]","Specifies the config file to use. If not specified, the file is based on the tag.").option("--to-version [version]","Specifies the version of the configuration to update. If not specified, the latest version is updated.").option("--dryrun","Displays the operations that would be performed using the specified command without actually running them.").option("--tar-path [tarPath]","Specifies the path to the extracted tarball of the @medplum/app package.").action(Ns),e.command("update-bucket-policies").description("Update S3 bucket policies").argument("<tag>","The Medplum stack tag").option("--file [file]","Specifies the config file to use. If not specified, the file is based on the tag.").option("--dryrun","Displays the operations that would be performed using the specified command without actually running them.").action(Us),e}async function Be(e,t,r=!1){let o=Qa(t),a=[],i=[],n=0,c=0;for(let s of o)try{let f=await e.readResource("Bot",s.id);await ur(e,s,f),n++,r&&(await pr(e,s,f),c++)}catch(f){a.push(f),i.push(`${s.name} [${s.id}]`)}if(console.log(`Number of bots saved: ${n}`),console.log(`Number of bots deployed: ${c}`),console.log(`Number of errors: ${a.length}`),a.length)throw new Error(`${a.length} bot(s) had failures. Bots with failures:
|
|
12
12
|
|
|
13
13
|
${i.join(`
|
|
14
|
-
`)}`,{cause:a})}async function en(e,t,r,o){let a=[],i=Ys(e),n=Qs({input:i});for await(let c of n){let s=tn(c,o);a.push({resource:s,request:{method:"POST",url:s.resourceType}}),a.length%t===0&&(await Wt(a,r),a=[])}a.length>0&&await Wt(a,r)}async function Wt(e,t){(await t.executeBatch({resourceType:"Bundle",type:"transaction",entry:e})).entry?.forEach(r=>{re(r.response)})}function tn(e,t){let r=JSON.parse(e);return t?rn(r):r}function rn(e){return e.resourceType==="ExplanationOfBenefit"?on(e):e}function on(e){return e.provider||(e.provider=Dt()),e.item?.forEach(t=>{t?.productOrService||(t.productOrService=Dt())}),e}function
|
|
14
|
+
`)}`,{cause:a})}async function en(e,t,r,o){let a=[],i=Ys(e),n=Qs({input:i});for await(let c of n){let s=tn(c,o);a.push({resource:s,request:{method:"POST",url:s.resourceType}}),a.length%t===0&&(await Wt(a,r),a=[])}a.length>0&&await Wt(a,r)}async function Wt(e,t){(await t.executeBatch({resourceType:"Bundle",type:"transaction",entry:e})).entry?.forEach(r=>{re(r.response)})}function tn(e,t){let r=JSON.parse(e);return t?rn(r):r}function rn(e){return e.resourceType==="ExplanationOfBenefit"?on(e):e}function on(e){return e.provider||(e.provider=Dt()),e.item?.forEach(t=>{t?.productOrService||(t.productOrService=Dt())}),e}function yn(){let e=an(new Date),t=Date.now().toString();return`MSH|^~\\&|ADTSYS|HOSPITAL|RECEIVER|DEST|${e}||ADT^A01|${t}|P|2.5|
|
|
15
15
|
EVN|A01|${e}||
|
|
16
16
|
PID|1|12345|12345^^^HOSP^MR|123456|DOE^JOHN^MIDDLE^SUFFIX|19800101|M|||123 STREET^APT 4B^CITY^ST^12345-6789||555-555-5555||S|
|
|
17
|
-
PV1|1|I|2000^2012^01||||12345^DOCTOR^DOC||||||||||1234567^DOCTOR^DOC||AMB|||||||||||||||||||||||||202309280900|`}function
|
|
17
|
+
PV1|1|I|2000^2012^01||||12345^DOCTOR^DOC||||||||||1234567^DOCTOR^DOC||AMB|||||||||||||||||||||||||202309280900|`}function In(e){let t=e.getLogins().map(r=>`${r.project.display} (${r.project.reference})`).join(`
|
|
18
18
|
|
|
19
|
-
`);console.log(t)}async function
|
|
20
|
-
`)}async function
|
|
19
|
+
`);console.log(t)}async function bn(e,t){let r=e.getLogins().find(o=>o.project.reference?.includes(t));if(!r)throw new Error(`Project ${t} not found. Make sure you are added as a user to this project`);await e.setActiveLogin(r),console.log(`Switched to project ${t}
|
|
20
|
+
`)}async function An(e,t,r){await r.invite(e,t),t.sendEmail&&console.log("Email sent"),console.log("See your users at https://app.medplum.com/admin/users")}function It(e){if(e)try{return JSON.parse(e)}catch{return e}}function Re(e,t){return["admin/","auth/","fhir/R4"].some(r=>t.startsWith(r))?t:e.fhirUrl(t).toString()}async function Rn(e){let t=new R("medplum").description("Command to access Medplum CLI").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("-p, --profile <profile>","Profile name").option("-v --verbose","Verbose output").addOption(new Xo("--auth-type <authType>","Type of authentication").choices(["basic","client-credentials","authorization-code","jwt-bearer","token-exchange","jwt-assertion"])).on("option:verbose",()=>{process.env.VERBOSE="1"});t.exitOverride(),t.version(Vo),t.configureHelp({showGlobalOptions:!0}),N(t,br),N(t,Ar),N(t,$r),N(t,so),N(t,co),N(t,no),N(t,lo),N(t,io),N(t,$e),N(t,vt),N(t,He),N(t,de),N(t,Hr),N(t,Br),N(t,Kr),N(t,Ae),N(t,zs()),N(t,St);try{await t.parseAsync(e)}catch(r){Tn(r)}}function Tn(e){let t=1,r=!0;if(e instanceof qt&&(process.env.VERBOSE||(r=!1),t=e.exitCode),t!==0&&r){Ze(e,!!process.env.VERBOSE);let o=e.cause;if(process.env.VERBOSE)if(Array.isArray(o))for(let a of o)Ze(a,!0);else o instanceof Error&&Ze(o,!0)}process.exit(t)}function Ze(e,t=!1){if(t){console.error(e);return}e instanceof qt?process.stderr.write(`${et(e)}
|
|
21
21
|
`):process.stderr.write(`Error: ${et(e)}
|
|
22
|
-
`)}async function bt(){qo.config(),await $n(process.argv)}var fo,it,go,yo,wo,Eo,vo,So,A,Io,Bt,B,ke,De,ve,st,Kt,K,le,bo,Ao,$o,Ro,To,No,Po,Oo,V,Lo,Co,nt,ko,Do,Me,ct,Gt,Jt,lt,ut,Vt,Mo,_o,X,_e,Ue,Uo,xo,jo,Fo,Wo,pt,Ho,Bo,Ko,Go,Jo,Xt,Se,we,Tt,Bn,qe,Ie,ue,ie,Yt,Nt,Pt,la,Qt,ua,pa,ht,tt,ar,ne,fa,ga,Ia,ba,Aa,Ot,se,rt,Ra,Ta,Jn,Na,Oa,ka,xa,ja,Fa,ee,Wa,Ye,Ha,Ba,Ka,Ga,R,mr,fr,gr,yr,wr,de,Sr,Ir,br,Ar,$r,ge,$i,Ri,Ti,Ni,Pi,Ee,Mt,Oi,Fe,Le,Vi,fc,yt,Xi,ls,_r,at,jr,Fr,Wr,He,Hr,Br,Kr,Jr,Vr,vt,Xr,un,Oe,qr,zr,pn,dn,mn,fn,St,Yr,Zr,Qr,eo,Ae,to,ro,oo,ao,$e,io,so,no,co,lo,uo=ho(()=>{"use strict";fo=Object.create,it=Object.defineProperty,go=Object.getOwnPropertyDescriptor,yo=Object.getOwnPropertyNames,wo=Object.getPrototypeOf,Eo=Object.prototype.hasOwnProperty,vo=(e,t,r)=>t in e?it(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,So=(e=>typeof Q<"u"?Q:typeof Proxy<"u"?new Proxy(e,{get:(t,r)=>(typeof Q<"u"?Q:t)[r]}):e)(function(e){if(typeof Q<"u")return Q.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')}),A=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),Io=(e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let a of yo(t))!Eo.call(e,a)&&a!==r&&it(e,a,{get:()=>t[a],enumerable:!(o=go(t,a))||o.enumerable});return e},Bt=(e,t,r)=>(r=e!=null?fo(wo(e)):{},Io(t||!e||!e.__esModule?it(r,"default",{value:e,enumerable:!0}):r,e)),B=(e,t,r)=>vo(e,typeof t!="symbol"?t+"":t,r),ke=A((e,t)=>{"use strict";var r="2.0.0",o=Number.MAX_SAFE_INTEGER||9007199254740991,a=16,i=250,n=["major","premajor","minor","preminor","patch","prepatch","prerelease"];t.exports={MAX_LENGTH:256,MAX_SAFE_COMPONENT_LENGTH:a,MAX_SAFE_BUILD_LENGTH:i,MAX_SAFE_INTEGER:o,RELEASE_TYPES:n,SEMVER_SPEC_VERSION:r,FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2}}),De=A((e,t)=>{"use strict";var r=typeof process=="object"&&process.env&&process.env.NODE_DEBUG&&/\bsemver\b/i.test(process.env.NODE_DEBUG)?(...o)=>console.error("SEMVER",...o):()=>{};t.exports=r}),ve=A((e,t)=>{"use strict";var{MAX_SAFE_COMPONENT_LENGTH:r,MAX_SAFE_BUILD_LENGTH:o,MAX_LENGTH:a}=ke(),i=De();e=t.exports={};var n=e.re=[],c=e.safeRe=[],s=e.src=[],f=e.safeSrc=[],l=e.t={},u=0,h="[a-zA-Z0-9-]",d=[["\\s",1],["\\d",a],[h,o]],g=P=>{for(let[T,O]of d)P=P.split(`${T}*`).join(`${T}{0,${O}}`).split(`${T}+`).join(`${T}{1,${O}}`);return P},m=(P,T,O)=>{let x=g(T),F=u++;i(P,F,T),l[P]=F,s[F]=T,f[F]=x,n[F]=new RegExp(T,O?"g":void 0),c[F]=new RegExp(x,O?"g":void 0)};m("NUMERICIDENTIFIER","0|[1-9]\\d*"),m("NUMERICIDENTIFIERLOOSE","\\d+"),m("NONNUMERICIDENTIFIER",`\\d*[a-zA-Z-]${h}*`),m("MAINVERSION",`(${s[l.NUMERICIDENTIFIER]})\\.(${s[l.NUMERICIDENTIFIER]})\\.(${s[l.NUMERICIDENTIFIER]})`),m("MAINVERSIONLOOSE",`(${s[l.NUMERICIDENTIFIERLOOSE]})\\.(${s[l.NUMERICIDENTIFIERLOOSE]})\\.(${s[l.NUMERICIDENTIFIERLOOSE]})`),m("PRERELEASEIDENTIFIER",`(?:${s[l.NONNUMERICIDENTIFIER]}|${s[l.NUMERICIDENTIFIER]})`),m("PRERELEASEIDENTIFIERLOOSE",`(?:${s[l.NONNUMERICIDENTIFIER]}|${s[l.NUMERICIDENTIFIERLOOSE]})`),m("PRERELEASE",`(?:-(${s[l.PRERELEASEIDENTIFIER]}(?:\\.${s[l.PRERELEASEIDENTIFIER]})*))`),m("PRERELEASELOOSE",`(?:-?(${s[l.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${s[l.PRERELEASEIDENTIFIERLOOSE]})*))`),m("BUILDIDENTIFIER",`${h}+`),m("BUILD",`(?:\\+(${s[l.BUILDIDENTIFIER]}(?:\\.${s[l.BUILDIDENTIFIER]})*))`),m("FULLPLAIN",`v?${s[l.MAINVERSION]}${s[l.PRERELEASE]}?${s[l.BUILD]}?`),m("FULL",`^${s[l.FULLPLAIN]}$`),m("LOOSEPLAIN",`[v=\\s]*${s[l.MAINVERSIONLOOSE]}${s[l.PRERELEASELOOSE]}?${s[l.BUILD]}?`),m("LOOSE",`^${s[l.LOOSEPLAIN]}$`),m("GTLT","((?:<|>)?=?)"),m("XRANGEIDENTIFIERLOOSE",`${s[l.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`),m("XRANGEIDENTIFIER",`${s[l.NUMERICIDENTIFIER]}|x|X|\\*`),m("XRANGEPLAIN",`[v=\\s]*(${s[l.XRANGEIDENTIFIER]})(?:\\.(${s[l.XRANGEIDENTIFIER]})(?:\\.(${s[l.XRANGEIDENTIFIER]})(?:${s[l.PRERELEASE]})?${s[l.BUILD]}?)?)?`),m("XRANGEPLAINLOOSE",`[v=\\s]*(${s[l.XRANGEIDENTIFIERLOOSE]})(?:\\.(${s[l.XRANGEIDENTIFIERLOOSE]})(?:\\.(${s[l.XRANGEIDENTIFIERLOOSE]})(?:${s[l.PRERELEASELOOSE]})?${s[l.BUILD]}?)?)?`),m("XRANGE",`^${s[l.GTLT]}\\s*${s[l.XRANGEPLAIN]}$`),m("XRANGELOOSE",`^${s[l.GTLT]}\\s*${s[l.XRANGEPLAINLOOSE]}$`),m("COERCEPLAIN",`(^|[^\\d])(\\d{1,${r}})(?:\\.(\\d{1,${r}}))?(?:\\.(\\d{1,${r}}))?`),m("COERCE",`${s[l.COERCEPLAIN]}(?:$|[^\\d])`),m("COERCEFULL",s[l.COERCEPLAIN]+`(?:${s[l.PRERELEASE]})?(?:${s[l.BUILD]})?(?:$|[^\\d])`),m("COERCERTL",s[l.COERCE],!0),m("COERCERTLFULL",s[l.COERCEFULL],!0),m("LONETILDE","(?:~>?)"),m("TILDETRIM",`(\\s*)${s[l.LONETILDE]}\\s+`,!0),e.tildeTrimReplace="$1~",m("TILDE",`^${s[l.LONETILDE]}${s[l.XRANGEPLAIN]}$`),m("TILDELOOSE",`^${s[l.LONETILDE]}${s[l.XRANGEPLAINLOOSE]}$`),m("LONECARET","(?:\\^)"),m("CARETTRIM",`(\\s*)${s[l.LONECARET]}\\s+`,!0),e.caretTrimReplace="$1^",m("CARET",`^${s[l.LONECARET]}${s[l.XRANGEPLAIN]}$`),m("CARETLOOSE",`^${s[l.LONECARET]}${s[l.XRANGEPLAINLOOSE]}$`),m("COMPARATORLOOSE",`^${s[l.GTLT]}\\s*(${s[l.LOOSEPLAIN]})$|^$`),m("COMPARATOR",`^${s[l.GTLT]}\\s*(${s[l.FULLPLAIN]})$|^$`),m("COMPARATORTRIM",`(\\s*)${s[l.GTLT]}\\s*(${s[l.LOOSEPLAIN]}|${s[l.XRANGEPLAIN]})`,!0),e.comparatorTrimReplace="$1$2$3",m("HYPHENRANGE",`^\\s*(${s[l.XRANGEPLAIN]})\\s+-\\s+(${s[l.XRANGEPLAIN]})\\s*$`),m("HYPHENRANGELOOSE",`^\\s*(${s[l.XRANGEPLAINLOOSE]})\\s+-\\s+(${s[l.XRANGEPLAINLOOSE]})\\s*$`),m("STAR","(<|>)?=?\\s*\\*"),m("GTE0","^\\s*>=\\s*0\\.0\\.0\\s*$"),m("GTE0PRE","^\\s*>=\\s*0\\.0\\.0-0\\s*$")}),st=A((e,t)=>{"use strict";var r=Object.freeze({loose:!0}),o=Object.freeze({}),a=i=>i?typeof i!="object"?r:i:o;t.exports=a}),Kt=A((e,t)=>{"use strict";var r=/^[0-9]+$/,o=(i,n)=>{let c=r.test(i),s=r.test(n);return c&&s&&(i=+i,n=+n),i===n?0:c&&!s?-1:s&&!c?1:i<n?-1:1},a=(i,n)=>o(n,i);t.exports={compareIdentifiers:o,rcompareIdentifiers:a}}),K=A((e,t)=>{"use strict";var r=De(),{MAX_LENGTH:o,MAX_SAFE_INTEGER:a}=ke(),{safeRe:i,t:n}=ve(),c=st(),{compareIdentifiers:s}=Kt(),f=class Y{constructor(u,h){if(h=c(h),u instanceof Y){if(u.loose===!!h.loose&&u.includePrerelease===!!h.includePrerelease)return u;u=u.version}else if(typeof u!="string")throw new TypeError(`Invalid version. Must be a string. Got type "${typeof u}".`);if(u.length>o)throw new TypeError(`version is longer than ${o} characters`);r("SemVer",u,h),this.options=h,this.loose=!!h.loose,this.includePrerelease=!!h.includePrerelease;let d=u.trim().match(h.loose?i[n.LOOSE]:i[n.FULL]);if(!d)throw new TypeError(`Invalid Version: ${u}`);if(this.raw=u,this.major=+d[1],this.minor=+d[2],this.patch=+d[3],this.major>a||this.major<0)throw new TypeError("Invalid major version");if(this.minor>a||this.minor<0)throw new TypeError("Invalid minor version");if(this.patch>a||this.patch<0)throw new TypeError("Invalid patch version");d[4]?this.prerelease=d[4].split(".").map(g=>{if(/^[0-9]+$/.test(g)){let m=+g;if(m>=0&&m<a)return m}return g}):this.prerelease=[],this.build=d[5]?d[5].split("."):[],this.format()}format(){return this.version=`${this.major}.${this.minor}.${this.patch}`,this.prerelease.length&&(this.version+=`-${this.prerelease.join(".")}`),this.version}toString(){return this.version}compare(u){if(r("SemVer.compare",this.version,this.options,u),!(u instanceof Y)){if(typeof u=="string"&&u===this.version)return 0;u=new Y(u,this.options)}return u.version===this.version?0:this.compareMain(u)||this.comparePre(u)}compareMain(u){return u instanceof Y||(u=new Y(u,this.options)),s(this.major,u.major)||s(this.minor,u.minor)||s(this.patch,u.patch)}comparePre(u){if(u instanceof Y||(u=new Y(u,this.options)),this.prerelease.length&&!u.prerelease.length)return-1;if(!this.prerelease.length&&u.prerelease.length)return 1;if(!this.prerelease.length&&!u.prerelease.length)return 0;let h=0;do{let d=this.prerelease[h],g=u.prerelease[h];if(r("prerelease compare",h,d,g),d===void 0&&g===void 0)return 0;if(g===void 0)return 1;if(d===void 0)return-1;if(d!==g)return s(d,g)}while(++h)}compareBuild(u){u instanceof Y||(u=new Y(u,this.options));let h=0;do{let d=this.build[h],g=u.build[h];if(r("build compare",h,d,g),d===void 0&&g===void 0)return 0;if(g===void 0)return 1;if(d===void 0)return-1;if(d!==g)return s(d,g)}while(++h)}inc(u,h,d){if(u.startsWith("pre")){if(!h&&d===!1)throw new Error("invalid increment argument: identifier is empty");if(h){let g=`-${h}`.match(this.options.loose?i[n.PRERELEASELOOSE]:i[n.PRERELEASE]);if(!g||g[1]!==h)throw new Error(`invalid identifier: ${h}`)}}switch(u){case"premajor":this.prerelease.length=0,this.patch=0,this.minor=0,this.major++,this.inc("pre",h,d);break;case"preminor":this.prerelease.length=0,this.patch=0,this.minor++,this.inc("pre",h,d);break;case"prepatch":this.prerelease.length=0,this.inc("patch",h,d),this.inc("pre",h,d);break;case"prerelease":this.prerelease.length===0&&this.inc("patch",h,d),this.inc("pre",h,d);break;case"release":if(this.prerelease.length===0)throw new Error(`version ${this.raw} is not a prerelease`);this.prerelease.length=0;break;case"major":(this.minor!==0||this.patch!==0||this.prerelease.length===0)&&this.major++,this.minor=0,this.patch=0,this.prerelease=[];break;case"minor":(this.patch!==0||this.prerelease.length===0)&&this.minor++,this.patch=0,this.prerelease=[];break;case"patch":this.prerelease.length===0&&this.patch++,this.prerelease=[];break;case"pre":{let g=Number(d)?1:0;if(this.prerelease.length===0)this.prerelease=[g];else{let m=this.prerelease.length;for(;--m>=0;)typeof this.prerelease[m]=="number"&&(this.prerelease[m]++,m=-2);if(m===-1){if(h===this.prerelease.join(".")&&d===!1)throw new Error("invalid increment argument: identifier already exists");this.prerelease.push(g)}}if(h){let m=[h,g];d===!1&&(m=[h]),s(this.prerelease[0],h)===0?isNaN(this.prerelease[1])&&(this.prerelease=m):this.prerelease=m}break}default:throw new Error(`invalid increment argument: ${u}`)}return this.raw=this.format(),this.build.length&&(this.raw+=`+${this.build.join(".")}`),this}};t.exports=f}),le=A((e,t)=>{"use strict";var r=K(),o=(a,i,n=!1)=>{if(a instanceof r)return a;try{return new r(a,i)}catch(c){if(!n)return null;throw c}};t.exports=o}),bo=A((e,t)=>{"use strict";var r=le(),o=(a,i)=>{let n=r(a,i);return n?n.version:null};t.exports=o}),Ao=A((e,t)=>{"use strict";var r=le(),o=(a,i)=>{let n=r(a.trim().replace(/^[=v]+/,""),i);return n?n.version:null};t.exports=o}),$o=A((e,t)=>{"use strict";var r=K(),o=(a,i,n,c,s)=>{typeof n=="string"&&(s=c,c=n,n=void 0);try{return new r(a instanceof r?a.version:a,n).inc(i,c,s).version}catch{return null}};t.exports=o}),Ro=A((e,t)=>{"use strict";var r=le(),o=(a,i)=>{let n=r(a,null,!0),c=r(i,null,!0),s=n.compare(c);if(s===0)return null;let f=s>0,l=f?n:c,u=f?c:n,h=!!l.prerelease.length;if(u.prerelease.length&&!h){if(!u.patch&&!u.minor)return"major";if(u.compareMain(l)===0)return u.minor&&!u.patch?"minor":"patch"}let d=h?"pre":"";return n.major!==c.major?d+"major":n.minor!==c.minor?d+"minor":n.patch!==c.patch?d+"patch":"prerelease"};t.exports=o}),To=A((e,t)=>{"use strict";var r=K(),o=(a,i)=>new r(a,i).major;t.exports=o}),No=A((e,t)=>{"use strict";var r=K(),o=(a,i)=>new r(a,i).minor;t.exports=o}),Po=A((e,t)=>{"use strict";var r=K(),o=(a,i)=>new r(a,i).patch;t.exports=o}),Oo=A((e,t)=>{"use strict";var r=le(),o=(a,i)=>{let n=r(a,i);return n&&n.prerelease.length?n.prerelease:null};t.exports=o}),V=A((e,t)=>{"use strict";var r=K(),o=(a,i,n)=>new r(a,n).compare(new r(i,n));t.exports=o}),Lo=A((e,t)=>{"use strict";var r=V(),o=(a,i,n)=>r(i,a,n);t.exports=o}),Co=A((e,t)=>{"use strict";var r=V(),o=(a,i)=>r(a,i,!0);t.exports=o}),nt=A((e,t)=>{"use strict";var r=K(),o=(a,i,n)=>{let c=new r(a,n),s=new r(i,n);return c.compare(s)||c.compareBuild(s)};t.exports=o}),ko=A((e,t)=>{"use strict";var r=nt(),o=(a,i)=>a.sort((n,c)=>r(n,c,i));t.exports=o}),Do=A((e,t)=>{"use strict";var r=nt(),o=(a,i)=>a.sort((n,c)=>r(c,n,i));t.exports=o}),Me=A((e,t)=>{"use strict";var r=V(),o=(a,i,n)=>r(a,i,n)>0;t.exports=o}),ct=A((e,t)=>{"use strict";var r=V(),o=(a,i,n)=>r(a,i,n)<0;t.exports=o}),Gt=A((e,t)=>{"use strict";var r=V(),o=(a,i,n)=>r(a,i,n)===0;t.exports=o}),Jt=A((e,t)=>{"use strict";var r=V(),o=(a,i,n)=>r(a,i,n)!==0;t.exports=o}),lt=A((e,t)=>{"use strict";var r=V(),o=(a,i,n)=>r(a,i,n)>=0;t.exports=o}),ut=A((e,t)=>{"use strict";var r=V(),o=(a,i,n)=>r(a,i,n)<=0;t.exports=o}),Vt=A((e,t)=>{"use strict";var r=Gt(),o=Jt(),a=Me(),i=lt(),n=ct(),c=ut(),s=(f,l,u,h)=>{switch(l){case"===":return typeof f=="object"&&(f=f.version),typeof u=="object"&&(u=u.version),f===u;case"!==":return typeof f=="object"&&(f=f.version),typeof u=="object"&&(u=u.version),f!==u;case"":case"=":case"==":return r(f,u,h);case"!=":return o(f,u,h);case">":return a(f,u,h);case">=":return i(f,u,h);case"<":return n(f,u,h);case"<=":return c(f,u,h);default:throw new TypeError(`Invalid operator: ${l}`)}};t.exports=s}),Mo=A((e,t)=>{"use strict";var r=K(),o=le(),{safeRe:a,t:i}=ve(),n=(c,s)=>{if(c instanceof r)return c;if(typeof c=="number"&&(c=String(c)),typeof c!="string")return null;s=s||{};let f=null;if(!s.rtl)f=c.match(s.includePrerelease?a[i.COERCEFULL]:a[i.COERCE]);else{let m=s.includePrerelease?a[i.COERCERTLFULL]:a[i.COERCERTL],P;for(;(P=m.exec(c))&&(!f||f.index+f[0].length!==c.length);)(!f||P.index+P[0].length!==f.index+f[0].length)&&(f=P),m.lastIndex=P.index+P[1].length+P[2].length;m.lastIndex=-1}if(f===null)return null;let l=f[2],u=f[3]||"0",h=f[4]||"0",d=s.includePrerelease&&f[5]?`-${f[5]}`:"",g=s.includePrerelease&&f[6]?`+${f[6]}`:"";return o(`${l}.${u}.${h}${d}${g}`,s)};t.exports=n}),_o=A((e,t)=>{"use strict";var r=class{constructor(){this.max=1e3,this.map=new Map}get(o){let a=this.map.get(o);if(a!==void 0)return this.map.delete(o),this.map.set(o,a),a}delete(o){return this.map.delete(o)}set(o,a){if(!this.delete(o)&&a!==void 0){if(this.map.size>=this.max){let i=this.map.keys().next().value;this.delete(i)}this.map.set(o,a)}return this}};t.exports=r}),X=A((e,t)=>{"use strict";var r=/\s+/g,o=class Pe{constructor(y,S){if(S=n(S),y instanceof Pe)return y.loose===!!S.loose&&y.includePrerelease===!!S.includePrerelease?y:new Pe(y.raw,S);if(y instanceof c)return this.raw=y.value,this.set=[[y]],this.formatted=void 0,this;if(this.options=S,this.loose=!!S.loose,this.includePrerelease=!!S.includePrerelease,this.raw=y.trim().replace(r," "),this.set=this.raw.split("||").map(E=>this.parseRange(E.trim())).filter(E=>E.length),!this.set.length)throw new TypeError(`Invalid SemVer Range: ${this.raw}`);if(this.set.length>1){let E=this.set[0];if(this.set=this.set.filter(I=>!T(I[0])),this.set.length===0)this.set=[E];else if(this.set.length>1){for(let I of this.set)if(I.length===1&&O(I[0])){this.set=[I];break}}}this.formatted=void 0}get range(){if(this.formatted===void 0){this.formatted="";for(let y=0;y<this.set.length;y++){y>0&&(this.formatted+="||");let S=this.set[y];for(let E=0;E<S.length;E++)E>0&&(this.formatted+=" "),this.formatted+=S[E].toString().trim()}}return this.formatted}format(){return this.range}toString(){return this.range}parseRange(y){let S=((this.options.includePrerelease&&m)|(this.options.loose&&P))+":"+y,E=i.get(S);if(E)return E;let I=this.options.loose,v=I?l[u.HYPHENRANGELOOSE]:l[u.HYPHENRANGE];y=y.replace(v,Je(this.options.includePrerelease)),s("hyphen replace",y),y=y.replace(l[u.COMPARATORTRIM],h),s("comparator trim",y),y=y.replace(l[u.TILDETRIM],d),s("tilde trim",y),y=y.replace(l[u.CARETTRIM],g),s("caret trim",y);let b=y.split(" ").map(D=>F(D,this.options)).join(" ").split(/\s+/).map(D=>Ge(D,this.options));I&&(b=b.filter(D=>(s("loose invalid filter",D,this.options),!!D.match(l[u.COMPARATORLOOSE])))),s("range list",b);let C=new Map,L=b.map(D=>new c(D,this.options));for(let D of L){if(T(D))return[D];C.set(D.value,D)}C.size>1&&C.has("")&&C.delete("");let k=[...C.values()];return i.set(S,k),k}intersects(y,S){if(!(y instanceof Pe))throw new TypeError("a Range is required");return this.set.some(E=>x(E,S)&&y.set.some(I=>x(I,S)&&E.every(v=>I.every(b=>v.intersects(b,S)))))}test(y){if(!y)return!1;if(typeof y=="string")try{y=new f(y,this.options)}catch{return!1}for(let S=0;S<this.set.length;S++)if(Ve(this.set[S],y,this.options))return!0;return!1}};t.exports=o;var a=_o(),i=new a,n=st(),c=_e(),s=De(),f=K(),{safeRe:l,t:u,comparatorTrimReplace:h,tildeTrimReplace:d,caretTrimReplace:g}=ve(),{FLAG_INCLUDE_PRERELEASE:m,FLAG_LOOSE:P}=ke(),T=w=>w.value==="<0.0.0-0",O=w=>w.value==="",x=(w,y)=>{let S=!0,E=w.slice(),I=E.pop();for(;S&&E.length;)S=E.every(v=>I.intersects(v,y)),I=E.pop();return S},F=(w,y)=>(s("comp",w,y),w=_(w,y),s("caret",w),w=Z(w,y),s("tildes",w),w=$(w,y),s("xrange",w),w=Ke(w,y),s("stars",w),w),M=w=>!w||w.toLowerCase()==="x"||w==="*",Z=(w,y)=>w.trim().split(/\s+/).map(S=>G(S,y)).join(" "),G=(w,y)=>{let S=y.loose?l[u.TILDELOOSE]:l[u.TILDE];return w.replace(S,(E,I,v,b,C)=>{s("tilde",w,E,I,v,b,C);let L;return M(I)?L="":M(v)?L=`>=${I}.0.0 <${+I+1}.0.0-0`:M(b)?L=`>=${I}.${v}.0 <${I}.${+v+1}.0-0`:C?(s("replaceTilde pr",C),L=`>=${I}.${v}.${b}-${C} <${I}.${+v+1}.0-0`):L=`>=${I}.${v}.${b} <${I}.${+v+1}.0-0`,s("tilde return",L),L})},_=(w,y)=>w.trim().split(/\s+/).map(S=>W(S,y)).join(" "),W=(w,y)=>{s("caret",w,y);let S=y.loose?l[u.CARETLOOSE]:l[u.CARET],E=y.includePrerelease?"-0":"";return w.replace(S,(I,v,b,C,L)=>{s("caret",w,I,v,b,C,L);let k;return M(v)?k="":M(b)?k=`>=${v}.0.0${E} <${+v+1}.0.0-0`:M(C)?v==="0"?k=`>=${v}.${b}.0${E} <${v}.${+b+1}.0-0`:k=`>=${v}.${b}.0${E} <${+v+1}.0.0-0`:L?(s("replaceCaret pr",L),v==="0"?b==="0"?k=`>=${v}.${b}.${C}-${L} <${v}.${b}.${+C+1}-0`:k=`>=${v}.${b}.${C}-${L} <${v}.${+b+1}.0-0`:k=`>=${v}.${b}.${C}-${L} <${+v+1}.0.0-0`):(s("no pr"),v==="0"?b==="0"?k=`>=${v}.${b}.${C}${E} <${v}.${b}.${+C+1}-0`:k=`>=${v}.${b}.${C}${E} <${v}.${+b+1}.0-0`:k=`>=${v}.${b}.${C} <${+v+1}.0.0-0`),s("caret return",k),k})},$=(w,y)=>(s("replaceXRanges",w,y),w.split(/\s+/).map(S=>he(S,y)).join(" ")),he=(w,y)=>{w=w.trim();let S=y.loose?l[u.XRANGELOOSE]:l[u.XRANGE];return w.replace(S,(E,I,v,b,C,L)=>{s("xRange",w,E,I,v,b,C,L);let k=M(v),D=k||M(b),ae=D||M(C),me=ae;return I==="="&&me&&(I=""),L=y.includePrerelease?"-0":"",k?I===">"||I==="<"?E="<0.0.0-0":E="*":I&&me?(D&&(b=0),C=0,I===">"?(I=">=",D?(v=+v+1,b=0,C=0):(b=+b+1,C=0)):I==="<="&&(I="<",D?v=+v+1:b=+b+1),I==="<"&&(L="-0"),E=`${I+v}.${b}.${C}${L}`):D?E=`>=${v}.0.0${L} <${+v+1}.0.0-0`:ae&&(E=`>=${v}.${b}.0${L} <${v}.${+b+1}.0-0`),s("xRange return",E),E})},Ke=(w,y)=>(s("replaceStars",w,y),w.trim().replace(l[u.STAR],"")),Ge=(w,y)=>(s("replaceGTE0",w,y),w.trim().replace(l[y.includePrerelease?u.GTE0PRE:u.GTE0],"")),Je=w=>(y,S,E,I,v,b,C,L,k,D,ae,me)=>(M(E)?S="":M(I)?S=`>=${E}.0.0${w?"-0":""}`:M(v)?S=`>=${E}.${I}.0${w?"-0":""}`:b?S=`>=${S}`:S=`>=${S}${w?"-0":""}`,M(k)?L="":M(D)?L=`<${+k+1}.0.0-0`:M(ae)?L=`<${k}.${+D+1}.0-0`:me?L=`<=${k}.${D}.${ae}-${me}`:w?L=`<${k}.${D}.${+ae+1}-0`:L=`<=${L}`,`${S} ${L}`.trim()),Ve=(w,y,S)=>{for(let E=0;E<w.length;E++)if(!w[E].test(y))return!1;if(y.prerelease.length&&!S.includePrerelease){for(let E=0;E<w.length;E++)if(s(w[E].semver),w[E].semver!==c.ANY&&w[E].semver.prerelease.length>0){let I=w[E].semver;if(I.major===y.major&&I.minor===y.minor&&I.patch===y.patch)return!0}return!1}return!0}}),_e=A((e,t)=>{"use strict";var r=Symbol("SemVer ANY"),o=class Qe{static get ANY(){return r}constructor(h,d){if(d=a(d),h instanceof Qe){if(h.loose===!!d.loose)return h;h=h.value}h=h.trim().split(/\s+/).join(" "),s("comparator",h,d),this.options=d,this.loose=!!d.loose,this.parse(h),this.semver===r?this.value="":this.value=this.operator+this.semver.version,s("comp",this)}parse(h){let d=this.options.loose?i[n.COMPARATORLOOSE]:i[n.COMPARATOR],g=h.match(d);if(!g)throw new TypeError(`Invalid comparator: ${h}`);this.operator=g[1]!==void 0?g[1]:"",this.operator==="="&&(this.operator=""),g[2]?this.semver=new f(g[2],this.options.loose):this.semver=r}toString(){return this.value}test(h){if(s("Comparator.test",h,this.options.loose),this.semver===r||h===r)return!0;if(typeof h=="string")try{h=new f(h,this.options)}catch{return!1}return c(h,this.operator,this.semver,this.options)}intersects(h,d){if(!(h instanceof Qe))throw new TypeError("a Comparator is required");return this.operator===""?this.value===""?!0:new l(h.value,d).test(this.value):h.operator===""?h.value===""?!0:new l(this.value,d).test(h.semver):(d=a(d),d.includePrerelease&&(this.value==="<0.0.0-0"||h.value==="<0.0.0-0")||!d.includePrerelease&&(this.value.startsWith("<0.0.0")||h.value.startsWith("<0.0.0"))?!1:!!(this.operator.startsWith(">")&&h.operator.startsWith(">")||this.operator.startsWith("<")&&h.operator.startsWith("<")||this.semver.version===h.semver.version&&this.operator.includes("=")&&h.operator.includes("=")||c(this.semver,"<",h.semver,d)&&this.operator.startsWith(">")&&h.operator.startsWith("<")||c(this.semver,">",h.semver,d)&&this.operator.startsWith("<")&&h.operator.startsWith(">")))}};t.exports=o;var a=st(),{safeRe:i,t:n}=ve(),c=Vt(),s=De(),f=K(),l=X()}),Ue=A((e,t)=>{"use strict";var r=X(),o=(a,i,n)=>{try{i=new r(i,n)}catch{return!1}return i.test(a)};t.exports=o}),Uo=A((e,t)=>{"use strict";var r=X(),o=(a,i)=>new r(a,i).set.map(n=>n.map(c=>c.value).join(" ").trim().split(" "));t.exports=o}),xo=A((e,t)=>{"use strict";var r=K(),o=X(),a=(i,n,c)=>{let s=null,f=null,l=null;try{l=new o(n,c)}catch{return null}return i.forEach(u=>{l.test(u)&&(!s||f.compare(u)===-1)&&(s=u,f=new r(s,c))}),s};t.exports=a}),jo=A((e,t)=>{"use strict";var r=K(),o=X(),a=(i,n,c)=>{let s=null,f=null,l=null;try{l=new o(n,c)}catch{return null}return i.forEach(u=>{l.test(u)&&(!s||f.compare(u)===1)&&(s=u,f=new r(s,c))}),s};t.exports=a}),Fo=A((e,t)=>{"use strict";var r=K(),o=X(),a=Me(),i=(n,c)=>{n=new o(n,c);let s=new r("0.0.0");if(n.test(s)||(s=new r("0.0.0-0"),n.test(s)))return s;s=null;for(let f=0;f<n.set.length;++f){let l=n.set[f],u=null;l.forEach(h=>{let d=new r(h.semver.version);switch(h.operator){case">":d.prerelease.length===0?d.patch++:d.prerelease.push(0),d.raw=d.format();case"":case">=":(!u||a(d,u))&&(u=d);break;case"<":case"<=":break;default:throw new Error(`Unexpected operation: ${h.operator}`)}}),u&&(!s||a(s,u))&&(s=u)}return s&&n.test(s)?s:null};t.exports=i}),Wo=A((e,t)=>{"use strict";var r=X(),o=(a,i)=>{try{return new r(a,i).range||"*"}catch{return null}};t.exports=o}),pt=A((e,t)=>{"use strict";var r=K(),o=_e(),{ANY:a}=o,i=X(),n=Ue(),c=Me(),s=ct(),f=ut(),l=lt(),u=(h,d,g,m)=>{h=new r(h,m),d=new i(d,m);let P,T,O,x,F;switch(g){case">":P=c,T=f,O=s,x=">",F=">=";break;case"<":P=s,T=l,O=c,x="<",F="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if(n(h,d,m))return!1;for(let M=0;M<d.set.length;++M){let Z=d.set[M],G=null,_=null;if(Z.forEach(W=>{W.semver===a&&(W=new o(">=0.0.0")),G=G||W,_=_||W,P(W.semver,G.semver,m)?G=W:O(W.semver,_.semver,m)&&(_=W)}),G.operator===x||G.operator===F||(!_.operator||_.operator===x)&&T(h,_.semver)||_.operator===F&&O(h,_.semver))return!1}return!0};t.exports=u}),Ho=A((e,t)=>{"use strict";var r=pt(),o=(a,i,n)=>r(a,i,">",n);t.exports=o}),Bo=A((e,t)=>{"use strict";var r=pt(),o=(a,i,n)=>r(a,i,"<",n);t.exports=o}),Ko=A((e,t)=>{"use strict";var r=X(),o=(a,i,n)=>(a=new r(a,n),i=new r(i,n),a.intersects(i,n));t.exports=o}),Go=A((e,t)=>{"use strict";var r=Ue(),o=V();t.exports=(a,i,n)=>{let c=[],s=null,f=null,l=a.sort((g,m)=>o(g,m,n));for(let g of l)r(g,i,n)?(f=g,s||(s=g)):(f&&c.push([s,f]),f=null,s=null);s&&c.push([s,null]);let u=[];for(let[g,m]of c)g===m?u.push(g):!m&&g===l[0]?u.push("*"):m?g===l[0]?u.push(`<=${m}`):u.push(`${g} - ${m}`):u.push(`>=${g}`);let h=u.join(" || "),d=typeof i.raw=="string"?i.raw:String(i);return h.length<d.length?h:i}}),Jo=A((e,t)=>{"use strict";var r=X(),o=_e(),{ANY:a}=o,i=Ue(),n=V(),c=(d,g,m={})=>{if(d===g)return!0;d=new r(d,m),g=new r(g,m);let P=!1;e:for(let T of d.set){for(let O of g.set){let x=l(T,O,m);if(P=P||x!==null,x)continue e}if(P)return!1}return!0},s=[new o(">=0.0.0-0")],f=[new o(">=0.0.0")],l=(d,g,m)=>{if(d===g)return!0;if(d.length===1&&d[0].semver===a){if(g.length===1&&g[0].semver===a)return!0;m.includePrerelease?d=s:d=f}if(g.length===1&&g[0].semver===a){if(m.includePrerelease)return!0;g=f}let P=new Set,T,O;for(let $ of d)$.operator===">"||$.operator===">="?T=u(T,$,m):$.operator==="<"||$.operator==="<="?O=h(O,$,m):P.add($.semver);if(P.size>1)return null;let x;if(T&&O&&(x=n(T.semver,O.semver,m),x>0||x===0&&(T.operator!==">="||O.operator!=="<=")))return null;for(let $ of P){if(T&&!i($,String(T),m)||O&&!i($,String(O),m))return null;for(let he of g)if(!i($,String(he),m))return!1;return!0}let F,M,Z,G,_=O&&!m.includePrerelease&&O.semver.prerelease.length?O.semver:!1,W=T&&!m.includePrerelease&&T.semver.prerelease.length?T.semver:!1;_&&_.prerelease.length===1&&O.operator==="<"&&_.prerelease[0]===0&&(_=!1);for(let $ of g){if(G=G||$.operator===">"||$.operator===">=",Z=Z||$.operator==="<"||$.operator==="<=",T){if(W&&$.semver.prerelease&&$.semver.prerelease.length&&$.semver.major===W.major&&$.semver.minor===W.minor&&$.semver.patch===W.patch&&(W=!1),$.operator===">"||$.operator===">="){if(F=u(T,$,m),F===$&&F!==T)return!1}else if(T.operator===">="&&!i(T.semver,String($),m))return!1}if(O){if(_&&$.semver.prerelease&&$.semver.prerelease.length&&$.semver.major===_.major&&$.semver.minor===_.minor&&$.semver.patch===_.patch&&(_=!1),$.operator==="<"||$.operator==="<="){if(M=h(O,$,m),M===$&&M!==O)return!1}else if(O.operator==="<="&&!i(O.semver,String($),m))return!1}if(!$.operator&&(O||T)&&x!==0)return!1}return!(T&&Z&&!O&&x!==0||O&&G&&!T&&x!==0||W||_)},u=(d,g,m)=>{if(!d)return g;let P=n(d.semver,g.semver,m);return P>0?d:P<0||g.operator===">"&&d.operator===">="?g:d},h=(d,g,m)=>{if(!d)return g;let P=n(d.semver,g.semver,m);return P<0?d:P>0||g.operator==="<"&&d.operator==="<="?g:d};t.exports=c}),Xt=A((e,t)=>{"use strict";var r=ve(),o=ke(),a=K(),i=Kt(),n=le(),c=bo(),s=Ao(),f=$o(),l=Ro(),u=To(),h=No(),d=Po(),g=Oo(),m=V(),P=Lo(),T=Co(),O=nt(),x=ko(),F=Do(),M=Me(),Z=ct(),G=Gt(),_=Jt(),W=lt(),$=ut(),he=Vt(),Ke=Mo(),Ge=_e(),Je=X(),Ve=Ue(),w=Uo(),y=xo(),S=jo(),E=Fo(),I=Wo(),v=pt(),b=Ho(),C=Bo(),L=Ko(),k=Go(),D=Jo();t.exports={parse:n,valid:c,clean:s,inc:f,diff:l,major:u,minor:h,patch:d,prerelease:g,compare:m,rcompare:P,compareLoose:T,compareBuild:O,sort:x,rsort:F,gt:M,lt:Z,eq:G,neq:_,gte:W,lte:$,cmp:he,coerce:Ke,Comparator:Ge,Range:Je,satisfies:Ve,toComparators:w,maxSatisfying:y,minSatisfying:S,minVersion:E,validRange:I,outside:v,gtr:b,ltr:C,intersects:L,simplifyRange:k,subset:D,SemVer:a,re:r.re,src:r.src,tokens:r.t,SEMVER_SPEC_VERSION:o.SEMVER_SPEC_VERSION,RELEASE_TYPES:o.RELEASE_TYPES,compareIdentifiers:i.compareIdentifiers,rcompareIdentifiers:i.rcompareIdentifiers}}),Se=class extends Qo{constructor(e){super(),this.dirName=$t(oa(),".medplum"),this.fileName=$t(this.dirName,e+".json")}clear(){this.writeFile({})}getString(e){return this.readFile()?.[e]}setString(e,t){let r=this.readFile()??{};t?r[e]=t:delete r[e],this.writeFile(r)}getObject(e){let t=this.getString(e);return t?JSON.parse(t):void 0}setObject(e,t){this.setString(e,t?JSON.stringify(t):void 0)}readFile(){if(At(this.fileName))return JSON.parse(ta(this.fileName,"utf8"))}writeFile(e){At(this.dirName)||ea(this.dirName),ra(this.fileName,JSON.stringify(e,null,2),"utf8")}};we=new TextEncoder,Tt=new TextDecoder,Bn=2**32;qe=e=>na.from(e).toString("base64url"),Ie=class extends Error{constructor(e,t){super(e,t),B(this,"code","ERR_JOSE_GENERIC"),this.name=this.constructor.name,Error.captureStackTrace?.(this,this.constructor)}};B(Ie,"code","ERR_JOSE_GENERIC");ue=class extends Ie{constructor(){super(...arguments),B(this,"code","ERR_JOSE_NOT_SUPPORTED")}};B(ue,"code","ERR_JOSE_NOT_SUPPORTED");ie=class extends Ie{constructor(){super(...arguments),B(this,"code","ERR_JWS_INVALID")}};B(ie,"code","ERR_JWS_INVALID");Yt=class extends Ie{constructor(){super(...arguments),B(this,"code","ERR_JWT_INVALID")}};B(Yt,"code","ERR_JWT_INVALID");la=class extends(Pt=Ie,Nt=Symbol.asyncIterator,Pt){constructor(e="multiple matching keys found in the JSON Web Key Set",t){super(e,t),B(this,Nt),B(this,"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS")}};B(la,"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS");Qt=e=>Zt.types.isKeyObject(e),ua=er.webcrypto,pa=ua,ht=e=>tr.types.isCryptoKey(e);tt=(e,...t)=>rr("Key must be ",e,...t);ar=e=>Qt(e)||ht(e),ne=["KeyObject"];(globalThis.CryptoKey||pa?.CryptoKey)&&ne.push("CryptoKey");fa=(...e)=>{let t=e.filter(Boolean);if(t.length===0||t.length===1)return!0;let r;for(let o of t){let a=Object.keys(o);if(!r||r.size===0){r=new Set(a);continue}for(let i of a){if(r.has(i))return!1;r.add(i)}}return!0},ga=fa;Ia=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 ue("Unsupported key curve for this operation")}},ba=(e,t)=>{let r;if(ht(e))r=wa.from(e);else if(Qt(e))r=e;else{if(be(e))return e.crv;throw new TypeError(tt(e,...ne))}if(r.type==="secret")throw new TypeError('only "private" or "public" type keys can be used for this operation');switch(r.asymmetricKeyType){case"ed25519":case"ed448":return`Ed${r.asymmetricKeyType.slice(2)}`;case"x25519":case"x448":return`X${r.asymmetricKeyType.slice(1)}`;case"ec":{let o=r.asymmetricKeyDetails.namedCurve;return t?o:Ia(o)}default:throw new TypeError("Invalid asymmetric key type for this operation")}},Aa=ba,Ot=(e,t)=>{let r;try{e instanceof $a?r=e.asymmetricKeyDetails?.modulusLength:r=Buffer.from(e.n,"base64url").byteLength<<3}catch{}if(typeof r!="number"||r<2048)throw new TypeError(`${t} requires key modulusLength to be 2048 bits or larger`)},se=e=>e?.[Symbol.toStringTag],rt=(e,t,r)=>{if(t.use!==void 0&&t.use!=="sig")throw new TypeError("Invalid key for this operation, when present its use must be sig");if(t.key_ops!==void 0&&t.key_ops.includes?.(r)!==!0)throw new TypeError(`Invalid key for this operation, when present its key_ops must include ${r}`);if(t.alg!==void 0&&t.alg!==e)throw new TypeError(`Invalid key for this operation, when present its alg must be ${e}`);return!0},Ra=(e,t,r,o)=>{if(!(t instanceof Uint8Array)){if(o&&be(t)){if(Sa(t)&&rt(e,t,r))return;throw new TypeError('JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present')}if(!ar(t))throw new TypeError(or(e,t,...ne,"Uint8Array",o?"JSON Web Key":null));if(t.type!=="secret")throw new TypeError(`${se(t)} instances for symmetric algorithms must be of type "secret"`)}},Ta=(e,t,r,o)=>{if(o&&be(t))switch(r){case"sign":if(Ea(t)&&rt(e,t,r))return;throw new TypeError("JSON Web Key for this operation be a private JWK");case"verify":if(va(t)&&rt(e,t,r))return;throw new TypeError("JSON Web Key for this operation be a public JWK")}if(!ar(t))throw new TypeError(or(e,t,...ne,o?"JSON Web Key":null));if(t.type==="secret")throw new TypeError(`${se(t)} instances for asymmetric algorithms must not be of type "secret"`);if(r==="sign"&&t.type==="public")throw new TypeError(`${se(t)} instances for asymmetric algorithm signing must be of type "private"`);if(r==="decrypt"&&t.type==="public")throw new TypeError(`${se(t)} instances for asymmetric algorithm decryption must be of type "private"`);if(t.algorithm&&r==="verify"&&t.type==="private")throw new TypeError(`${se(t)} instances for asymmetric algorithm verifying must be of type "public"`);if(t.algorithm&&r==="encrypt"&&t.type==="private")throw new TypeError(`${se(t)} instances for asymmetric algorithm encryption must be of type "public"`)};Jn=sr.bind(void 0,!1),Na=sr.bind(void 0,!0);Oa=Pa;ka=new Map([["ES256","P-256"],["ES256K","secp256k1"],["ES384","P-384"],["ES512","P-521"]]);xa=Ma(xe.sign),ja=async(e,t,r)=>{let o=Ua(e,t,"sign");if(e.startsWith("HS")){let a=xe.createHmac(_a(e),o);return a.update(r),a.digest()}return xa(La(e),r,Da(e,o))},Fa=ja,ee=e=>Math.floor(e.getTime()/1e3),Wa=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i,Ye=e=>{let t=Wa.exec(e);if(!t||t[4]&&t[1])throw new TypeError("Invalid time period format");let r=parseFloat(t[2]),o=t[3].toLowerCase(),a;switch(o){case"sec":case"secs":case"second":case"seconds":case"s":a=Math.round(r);break;case"minute":case"minutes":case"min":case"mins":case"m":a=Math.round(r*60);break;case"hour":case"hours":case"hr":case"hrs":case"h":a=Math.round(r*3600);break;case"day":case"days":case"d":a=Math.round(r*86400);break;case"week":case"weeks":case"w":a=Math.round(r*604800);break;default:a=Math.round(r*31557600);break}return t[1]==="-"||t[4]==="ago"?-a:a},Ha=class{constructor(e){if(B(this,"_payload"),B(this,"_protectedHeader"),B(this,"_unprotectedHeader"),!(e instanceof Uint8Array))throw new TypeError("payload must be an instance of Uint8Array");this._payload=e}setProtectedHeader(e){if(this._protectedHeader)throw new TypeError("setProtectedHeader can only be called once");return this._protectedHeader=e,this}setUnprotectedHeader(e){if(this._unprotectedHeader)throw new TypeError("setUnprotectedHeader can only be called once");return this._unprotectedHeader=e,this}async sign(e,t){if(!this._protectedHeader&&!this._unprotectedHeader)throw new ie("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");if(!ga(this._protectedHeader,this._unprotectedHeader))throw new ie("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let r={...this._protectedHeader,...this._unprotectedHeader},o=Oa(ie,new Map([["b64",!0]]),t?.crit,this._protectedHeader,r),a=!0;if(o.has("b64")&&(a=this._protectedHeader.b64,typeof a!="boolean"))throw new ie('The "b64" (base64url-encode payload) Header Parameter must be a boolean');let{alg:i}=r;if(typeof i!="string"||!i)throw new ie('JWS "alg" (Algorithm) Header Parameter missing or invalid');Na(i,e,"sign");let n=this._payload;a&&(n=we.encode(qe(n)));let c;this._protectedHeader?c=we.encode(qe(JSON.stringify(this._protectedHeader))):c=we.encode("");let s=ca(c,we.encode("."),n),f=await Fa(i,e,s),l={signature:qe(f),payload:""};return a&&(l.payload=Tt.decode(n)),this._unprotectedHeader&&(l.header=this._unprotectedHeader),this._protectedHeader&&(l.protected=Tt.decode(c)),l}},Ba=class{constructor(e){B(this,"_flattened"),this._flattened=new Ha(e)}setProtectedHeader(e){return this._flattened.setProtectedHeader(e),this}async sign(e,t){let r=await this._flattened.sign(e,t);if(r.payload===void 0)throw new TypeError("use the flattened module for creating JWS with b64: false");return`${r.protected}.${r.payload}.${r.signature}`}};Ka=class{constructor(e={}){if(B(this,"_payload"),!ir(e))throw new TypeError("JWT Claims Set MUST be an object");this._payload=e}setIssuer(e){return this._payload={...this._payload,iss:e},this}setSubject(e){return this._payload={...this._payload,sub:e},this}setAudience(e){return this._payload={...this._payload,aud:e},this}setJti(e){return this._payload={...this._payload,jti:e},this}setNotBefore(e){return typeof e=="number"?this._payload={...this._payload,nbf:te("setNotBefore",e)}:e instanceof Date?this._payload={...this._payload,nbf:te("setNotBefore",ee(e))}:this._payload={...this._payload,nbf:ee(new Date)+Ye(e)},this}setExpirationTime(e){return typeof e=="number"?this._payload={...this._payload,exp:te("setExpirationTime",e)}:e instanceof Date?this._payload={...this._payload,exp:te("setExpirationTime",ee(e))}:this._payload={...this._payload,exp:ee(new Date)+Ye(e)},this}setIssuedAt(e){return typeof e>"u"?this._payload={...this._payload,iat:ee(new Date)}:e instanceof Date?this._payload={...this._payload,iat:te("setIssuedAt",ee(e))}:typeof e=="string"?this._payload={...this._payload,iat:te("setIssuedAt",ee(new Date)+Ye(e))}:this._payload={...this._payload,iat:te("setIssuedAt",e)},this}},Ga=class extends Ka{constructor(){super(...arguments),B(this,"_protectedHeader")}setProtectedHeader(e){return this._protectedHeader=e,this}async sign(e,t){let r=new Ba(we.encode(JSON.stringify(this._payload)));if(r.setProtectedHeader(this._protectedHeader),Array.isArray(this._protectedHeader?.crit)&&this._protectedHeader.crit.includes("b64")&&this._protectedHeader.b64===!1)throw new Yt("JWTs MUST NOT use unencoded payload");return r.sign(e,t)}};R=class extends sa{action(e){let t=ci(this,e);return super._actionHandler=t,this}resetOptionDefaults(){this._optionValues={};for(let e of this.options)e.defaultValue!==void 0&&(this._optionValues[e.attributeName()]=e.defaultValue)}};mr=new R("status").aliases(["info","list","ls"]),fr=new R("ping"),gr=new R("push"),yr=new R("reload-config"),wr=new R("upgrade"),de=new R("agent");N(de,mr);N(de,fr);N(de,gr);N(de,yr);N(de,wr);mr.description("Get the status of a specified agent").argument("[agentIds...]","The ID(s) of the agent(s) to get the status of").option("--criteria <criteria>","An optional FHIR search criteria to resolve the agent to get the status of. Mutually exclusive with [agentIds...] arg").addOption(new dt("--output <format>","An optional output format, defaults to table").choices(["table","json"]).default("table")).action(async(e,t)=>{await ft({operation:"$bulk-status",agentIds:e,options:t,parseSuccessfulResponse:r=>{let o=pi(r.result,{required:["status","version"],optional:["lastUpdated"]});return{id:r.agent.id,name:r.agent.name,enabledStatus:r.agent.status,version:o.version,connectionStatus:o.status,statusLastUpdated:o.lastUpdated??"N/A"}}})});fr.description("Ping a host from a specified agent").argument("<ipOrDomain>","The IPv4 address or domain name to ping").argument("[agentId]","Conditionally optional ID of the agent to ping from. Mutually exclusive with --criteria <criteria> option").option("--count <count>","An optional amount of pings to issue before returning results","1").option("--criteria <criteria>","An optional FHIR search criteria to resolve the agent to ping from. Mutually exclusive with [agentId] arg").action(async(e,t,r)=>{let o=await U(r),a=await Er(o,t,r),i=Number.parseInt(r.count,10);if(Number.isNaN(i))throw new Error("--count <count> must be an integer if specified");try{let n=await o.pushToAgent(a,e,`PING ${i}`,zt.PING,!0,{maxRetries:0});console.info(n)}catch(n){throw new Error("Unexpected response from agent while pinging",{cause:n})}});gr.description("Push a message to a target device via a specified agent").argument("<deviceId>","The ID of the device to push the message to").argument("<message>","The message to send to the destination device").argument("[agentId]","Conditionally optional ID of the agent to send the message from. Mutually exclusive with --criteria <criteria> option").option("--content-type <contentType>","The content type of the message",zt.HL7_V2).option("--no-wait","Tells the server not to wait for a response from the destination device").option("--criteria <criteria>","An optional FHIR search criteria to resolve the agent to ping from. Mutually exclusive with [agentId] arg").action(async(e,t,r,o)=>{let a=await U(o),i=await Er(a,r,o),n;try{n=await a.pushToAgent(i,{reference:`Device/${e}`},t,o.contentType,o.wait!==!1,{maxRetries:0})}catch(c){throw new Error("Unexpected response from agent while pushing message to agent",{cause:c})}console.info(n)});yr.description("Reload the config for the specified agent(s)").argument("[agentIds...]","The ID(s) of the agent(s) for which the config should be reloaded. Mutually exclusive with --criteria <criteria> flag").option("--criteria <criteria>","An optional FHIR search criteria to resolve the agent(s) for which to notify to reload their config. Mutually exclusive with [agentIds...] arg").addOption(new dt("--output <format>","An optional output format, defaults to table").choices(["table","json"]).default("table")).action(async(e,t)=>{await ft({operation:"$reload-config",agentIds:e,options:t,parseSuccessfulResponse:r=>({id:r.agent.id,name:r.agent.name})})});wr.description("Upgrade the version for the specified agent(s)").argument("[agentIds...]","The ID(s) of the agent(s) that should be upgraded. Mutually exclusive with --criteria <criteria> flag").option("--criteria <criteria>","An optional FHIR search criteria to resolve the agent(s) to upgrade. Mutually exclusive with [agentIds...] arg").option("--version <version>","An optional version to upgrade to. Defaults to the latest version if flag not included").addOption(new dt("--output <format>","An optional output format, defaults to table").choices(["table","json"]).default("table")).action(async(e,t)=>{await ft({operation:"$upgrade",agentIds:e,options:t,parseSuccessfulResponse:r=>({id:r.agent.id,name:r.agent.name,version:t.version??"latest"})})});Sr=fi,Ir="http://localhost:9615",br=new R("login"),Ar=new R("whoami"),$r=new R("token");br.action(async e=>{let t=e.profile??"default",r=hr(t,e),o=await U(e,!1);await vi(o,r)});Ar.action(async e=>{let t=await U(e);bi(t)});$r.action(async e=>{let t=await U(e);await t.getProfileAsync();let r=t.getAccessToken();if(!r)throw new Error("Not logged in");console.log(r)});ge="\x1B[0m",$i="\x1B[1m",Ri="\x1B[31m",Ti="\x1B[32m",Ni="\x1B[33m",Pi="\x1B[34m",Ee={red:e=>`${Ri}${e}${ge}`,green:e=>`${Ti}${e}${ge}`,yellow:e=>`${Ni}${e}${ge}`,blue:e=>`${Pi}${e}${ge}`,bold:e=>`${$i}${e}${ge}`},Mt=e=>e.replace(/\*\*(.*?)\*\*/g,(t,r)=>Ee.bold(r)),Oi=Bt(Xt());Le=new Rr({}),Vi=new Di({region:"us-east-1"}),fc=new _i({}),yt=new Ui({}),Xi="medplum:environment";ls=e=>`${e}DomainName`,_r=e=>`${e}SslCertArn`;at=Bt(Xt());jr=new R("save"),Fr=new R("deploy"),Wr=new R("create"),He=new R("bot");N(He,jr);N(He,Fr);N(He,Wr);Hr=new R("save-bot"),Br=new R("deploy-bot"),Kr=new R("create-bot");jr.description("Saving the bot").argument("<botName>").action(async(e,t)=>{let r=await U(t);await Be(r,e)});Fr.description("Deploy the app to AWS").argument("<botName>").action(async(e,t)=>{let r=await U(t);await Be(r,e,!0)});Wr.arguments("<botName> <projectId> <sourceFile> <distFile>").description("Creating a bot").option("--runtime-version <runtimeVersion>","Runtime version (awslambda, vmcontext)").option("--no-write-config","Do not write bot to config").action(async(e,t,r,o,a)=>{let i=await U(a);await dr(i,e,t,r,o,a.runtimeVersion,!!a.writeConfig)});Hr.description("Saves the bot").argument("<botName>").action(async(e,t)=>{let r=await U(t);await Be(r,e)});Br.description("Deploy the bot to AWS").argument("<botName>").action(async(e,t)=>{let r=await U(t);await Be(r,e,!0)});Kr.arguments("<botName> <projectId> <sourceFile> <distFile>").description("Creates and saves the bot").action(async(e,t,r,o,a)=>{let i=await U(a);await dr(i,e,t,r,o)});Jr=new R("export"),Vr=new R("import"),vt=new R("bulk");N(vt,Jr);N(vt,Vr);Jr.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:a}=e,i=await U(e);(await i.bulkExport(t,r,o,{pollStatusOnAccepted:!0})).output?.forEach(async({type:n,url:c})=>{let s=new URL(c),f=await i.download(c),l=`${n}_${s.pathname}`.replace(/[^a-zA-Z0-9]+/g,"_")+".ndjson",u=Gr(a??"",l);Zs(`${u}`,await f.text(),()=>{console.log(`${u} is created`)})})});Vr.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:a}=t,i=Gr(a??process.cwd(),e),n=await U(t);await en(i,Number.parseInt(r,10),n,o)});Xr=class extends EventTarget{addEventListener(e,t,r){super.addEventListener(e,t,r)}removeEventListener(e,t,r){super.removeEventListener(e,t,r)}},un=class extends Event{constructor(e,t){super("message"),this.connection=e,this.message=t}},Oe=class extends Event{constructor(e){super("error"),this.error=e}},qr=class extends Event{constructor(){super("close")}},zr=class extends Xr{constructor(e,t="utf-8",r=!1){super(),this.chunks=[],this.messageQueue=[],this.socket=e,this.encoding=t,this.enhancedMode=r,e.on("data",o=>{try{if(this.appendData(o),o.at(-2)===28&&o.at(-1)===13){let a=Buffer.concat(this.chunks),i=a.subarray(1,a.length-2),n=Ht.decode(i,this.encoding),c=cn.parse(n);this.dispatchEvent(new un(this,c)),this.resetBuffer()}}catch(a){this.dispatchEvent(new Oe(a))}}),e.on("error",o=>{this.resetBuffer(),this.dispatchEvent(new Oe(o))}),e.on("end",()=>{this.close()}),this.addEventListener("message",o=>{r&&this.send(o.message.buildAck({ackCode:"CA"}));let a=this.messageQueue.shift();if(!a){this.dispatchEvent(new Oe(new Error(`Received a message when no pending messages were in the queue. Message: ${o.message}`)));return}a.resolve?.(o.message)})}sendImpl(e,t){this.messageQueue.push(t);let r=e.toString(),o=Ht.encode(r,this.encoding),a=Buffer.alloc(o.length+3);a.writeInt8(11,0),o.copy(a,1),a.writeInt8(28,o.length+1),a.writeInt8(13,o.length+2),this.socket.write(a)}send(e){this.sendImpl(e,{message:e})}async sendAndWait(e){return new Promise((t,r)=>{let o={message:e,resolve:t,reject:r};this.sendImpl(e,o)})}close(){this.socket.end(),this.socket.destroy(),this.dispatchEvent(new qr)}appendData(e){this.chunks.push(e)}resetBuffer(){this.chunks=[]}},pn=class extends Xr{constructor(e){super(),this.options=e,this.host=this.options.host,this.port=this.options.port,this.encoding=this.options.encoding,this.keepAlive=this.options.keepAlive??!1,this.connectTimeout=this.options.connectTimeout??3e4}connect(){return this.connection?Promise.resolve(this.connection):(this.socket&&(this.socket.removeAllListeners(),this.socket.destroy(),this.socket=void 0),new Promise((e,t)=>{this.socket=nn({host:this.host,port:this.port,keepAlive:this.keepAlive}),this.connectTimeout>0&&(this.socket.setTimeout(this.connectTimeout),this.socket.on("timeout",()=>{let r=new Error(`Connection timeout after ${this.connectTimeout}ms`);this.socket&&(this.socket.destroy(),this.socket=void 0),t(r)})),this.socket.on("connect",()=>{if(!this.socket)return;let r;this.connection=r=new zr(this.socket,this.encoding),this.socket.setTimeout(0),r.addEventListener("close",()=>{this.socket=void 0,this.dispatchEvent(new qr)}),r.addEventListener("error",o=>{this.dispatchEvent(new Oe(o.error))}),e(this.connection)}),this.socket.on("error",r=>{this.socket&&(this.socket.destroy(),this.socket=void 0),t(r)})}))}async send(e){return(await this.connect()).send(e)}async sendAndWait(e){return(await this.connect()).sendAndWait(e)}close(){this.socket&&(this.socket.removeAllListeners(),this.socket.destroy(),this.socket=void 0),this.connection&&(this.connection.close(),delete this.connection)}},dn=class{constructor(e){this.handler=e}start(e,t,r=!1){let o=ln.createServer(a=>{let i=new zr(a,t,r);this.handler(i)});o.listen(e),this.server=o}async stop(){return new Promise((e,t)=>{if(!this.server){t(new Error("Stop was called but there is no server running"));return}this.server.close(r=>{if(r){t(r);return}e()}),this.server=void 0})}},mn=new R("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").option("--encoding <encoding>","The encoding to use").action(async(e,t,r,o)=>{if(o.generateExample?r=gn():o.file&&(r=hn(o.file,"utf8")),!r)throw new Error("Missing HL7 message body");let a=new pn({host:e,port:Number.parseInt(t,10),encoding:o.encoding});try{let i=await a.sendAndWait(sn.parse(r));console.log(i.toString().replaceAll("\r",`
|
|
23
|
-
`))}finally{a.close()}}),
|
|
24
|
-
`)),r.send(o.buildAck())})}).start(Number.parseInt(e,10),t.encoding),console.log("Listening on port "+e)}),St=new R("hl7");N(St,
|
|
22
|
+
`)}async function bt(){qo.config(),await Rn(process.argv)}var fo,it,go,yo,wo,Eo,vo,So,A,Io,Bt,B,ke,De,ve,st,Kt,K,le,bo,Ao,$o,Ro,To,No,Po,Oo,V,Lo,Co,nt,ko,Do,Me,ct,Gt,Jt,lt,ut,Vt,Mo,_o,X,_e,Ue,Uo,xo,jo,Fo,Wo,pt,Ho,Bo,Ko,Go,Jo,Xt,Se,we,Tt,Kn,qe,Ie,ue,ie,Yt,Nt,Pt,la,Qt,ua,pa,ht,tt,ar,ne,fa,ga,Ia,ba,Aa,Ot,se,rt,Ra,Ta,Vn,Na,Oa,ka,xa,ja,Fa,ee,Wa,Ye,Ha,Ba,Ka,Ga,R,mr,fr,gr,yr,wr,de,Sr,Ir,br,Ar,$r,ge,$i,Ri,Ti,Ni,Pi,Ee,Mt,Oi,Fe,Le,Vi,gc,yt,Xi,ls,_r,at,jr,Fr,Wr,He,Hr,Br,Kr,Jr,Vr,vt,Xr,pn,Oe,qr,zr,dn,hn,fn,gn,St,Yr,Zr,Qr,eo,Ae,to,ro,oo,ao,$e,io,so,no,co,lo,uo=ho(()=>{"use strict";fo=Object.create,it=Object.defineProperty,go=Object.getOwnPropertyDescriptor,yo=Object.getOwnPropertyNames,wo=Object.getPrototypeOf,Eo=Object.prototype.hasOwnProperty,vo=(e,t,r)=>t in e?it(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,So=(e=>typeof Q<"u"?Q:typeof Proxy<"u"?new Proxy(e,{get:(t,r)=>(typeof Q<"u"?Q:t)[r]}):e)(function(e){if(typeof Q<"u")return Q.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')}),A=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),Io=(e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let a of yo(t))!Eo.call(e,a)&&a!==r&&it(e,a,{get:()=>t[a],enumerable:!(o=go(t,a))||o.enumerable});return e},Bt=(e,t,r)=>(r=e!=null?fo(wo(e)):{},Io(t||!e||!e.__esModule?it(r,"default",{value:e,enumerable:!0}):r,e)),B=(e,t,r)=>vo(e,typeof t!="symbol"?t+"":t,r),ke=A((e,t)=>{"use strict";var r="2.0.0",o=Number.MAX_SAFE_INTEGER||9007199254740991,a=16,i=250,n=["major","premajor","minor","preminor","patch","prepatch","prerelease"];t.exports={MAX_LENGTH:256,MAX_SAFE_COMPONENT_LENGTH:a,MAX_SAFE_BUILD_LENGTH:i,MAX_SAFE_INTEGER:o,RELEASE_TYPES:n,SEMVER_SPEC_VERSION:r,FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2}}),De=A((e,t)=>{"use strict";var r=typeof process=="object"&&process.env&&process.env.NODE_DEBUG&&/\bsemver\b/i.test(process.env.NODE_DEBUG)?(...o)=>console.error("SEMVER",...o):()=>{};t.exports=r}),ve=A((e,t)=>{"use strict";var{MAX_SAFE_COMPONENT_LENGTH:r,MAX_SAFE_BUILD_LENGTH:o,MAX_LENGTH:a}=ke(),i=De();e=t.exports={};var n=e.re=[],c=e.safeRe=[],s=e.src=[],f=e.safeSrc=[],l=e.t={},u=0,h="[a-zA-Z0-9-]",d=[["\\s",1],["\\d",a],[h,o]],g=P=>{for(let[T,O]of d)P=P.split(`${T}*`).join(`${T}{0,${O}}`).split(`${T}+`).join(`${T}{1,${O}}`);return P},m=(P,T,O)=>{let x=g(T),F=u++;i(P,F,T),l[P]=F,s[F]=T,f[F]=x,n[F]=new RegExp(T,O?"g":void 0),c[F]=new RegExp(x,O?"g":void 0)};m("NUMERICIDENTIFIER","0|[1-9]\\d*"),m("NUMERICIDENTIFIERLOOSE","\\d+"),m("NONNUMERICIDENTIFIER",`\\d*[a-zA-Z-]${h}*`),m("MAINVERSION",`(${s[l.NUMERICIDENTIFIER]})\\.(${s[l.NUMERICIDENTIFIER]})\\.(${s[l.NUMERICIDENTIFIER]})`),m("MAINVERSIONLOOSE",`(${s[l.NUMERICIDENTIFIERLOOSE]})\\.(${s[l.NUMERICIDENTIFIERLOOSE]})\\.(${s[l.NUMERICIDENTIFIERLOOSE]})`),m("PRERELEASEIDENTIFIER",`(?:${s[l.NONNUMERICIDENTIFIER]}|${s[l.NUMERICIDENTIFIER]})`),m("PRERELEASEIDENTIFIERLOOSE",`(?:${s[l.NONNUMERICIDENTIFIER]}|${s[l.NUMERICIDENTIFIERLOOSE]})`),m("PRERELEASE",`(?:-(${s[l.PRERELEASEIDENTIFIER]}(?:\\.${s[l.PRERELEASEIDENTIFIER]})*))`),m("PRERELEASELOOSE",`(?:-?(${s[l.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${s[l.PRERELEASEIDENTIFIERLOOSE]})*))`),m("BUILDIDENTIFIER",`${h}+`),m("BUILD",`(?:\\+(${s[l.BUILDIDENTIFIER]}(?:\\.${s[l.BUILDIDENTIFIER]})*))`),m("FULLPLAIN",`v?${s[l.MAINVERSION]}${s[l.PRERELEASE]}?${s[l.BUILD]}?`),m("FULL",`^${s[l.FULLPLAIN]}$`),m("LOOSEPLAIN",`[v=\\s]*${s[l.MAINVERSIONLOOSE]}${s[l.PRERELEASELOOSE]}?${s[l.BUILD]}?`),m("LOOSE",`^${s[l.LOOSEPLAIN]}$`),m("GTLT","((?:<|>)?=?)"),m("XRANGEIDENTIFIERLOOSE",`${s[l.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`),m("XRANGEIDENTIFIER",`${s[l.NUMERICIDENTIFIER]}|x|X|\\*`),m("XRANGEPLAIN",`[v=\\s]*(${s[l.XRANGEIDENTIFIER]})(?:\\.(${s[l.XRANGEIDENTIFIER]})(?:\\.(${s[l.XRANGEIDENTIFIER]})(?:${s[l.PRERELEASE]})?${s[l.BUILD]}?)?)?`),m("XRANGEPLAINLOOSE",`[v=\\s]*(${s[l.XRANGEIDENTIFIERLOOSE]})(?:\\.(${s[l.XRANGEIDENTIFIERLOOSE]})(?:\\.(${s[l.XRANGEIDENTIFIERLOOSE]})(?:${s[l.PRERELEASELOOSE]})?${s[l.BUILD]}?)?)?`),m("XRANGE",`^${s[l.GTLT]}\\s*${s[l.XRANGEPLAIN]}$`),m("XRANGELOOSE",`^${s[l.GTLT]}\\s*${s[l.XRANGEPLAINLOOSE]}$`),m("COERCEPLAIN",`(^|[^\\d])(\\d{1,${r}})(?:\\.(\\d{1,${r}}))?(?:\\.(\\d{1,${r}}))?`),m("COERCE",`${s[l.COERCEPLAIN]}(?:$|[^\\d])`),m("COERCEFULL",s[l.COERCEPLAIN]+`(?:${s[l.PRERELEASE]})?(?:${s[l.BUILD]})?(?:$|[^\\d])`),m("COERCERTL",s[l.COERCE],!0),m("COERCERTLFULL",s[l.COERCEFULL],!0),m("LONETILDE","(?:~>?)"),m("TILDETRIM",`(\\s*)${s[l.LONETILDE]}\\s+`,!0),e.tildeTrimReplace="$1~",m("TILDE",`^${s[l.LONETILDE]}${s[l.XRANGEPLAIN]}$`),m("TILDELOOSE",`^${s[l.LONETILDE]}${s[l.XRANGEPLAINLOOSE]}$`),m("LONECARET","(?:\\^)"),m("CARETTRIM",`(\\s*)${s[l.LONECARET]}\\s+`,!0),e.caretTrimReplace="$1^",m("CARET",`^${s[l.LONECARET]}${s[l.XRANGEPLAIN]}$`),m("CARETLOOSE",`^${s[l.LONECARET]}${s[l.XRANGEPLAINLOOSE]}$`),m("COMPARATORLOOSE",`^${s[l.GTLT]}\\s*(${s[l.LOOSEPLAIN]})$|^$`),m("COMPARATOR",`^${s[l.GTLT]}\\s*(${s[l.FULLPLAIN]})$|^$`),m("COMPARATORTRIM",`(\\s*)${s[l.GTLT]}\\s*(${s[l.LOOSEPLAIN]}|${s[l.XRANGEPLAIN]})`,!0),e.comparatorTrimReplace="$1$2$3",m("HYPHENRANGE",`^\\s*(${s[l.XRANGEPLAIN]})\\s+-\\s+(${s[l.XRANGEPLAIN]})\\s*$`),m("HYPHENRANGELOOSE",`^\\s*(${s[l.XRANGEPLAINLOOSE]})\\s+-\\s+(${s[l.XRANGEPLAINLOOSE]})\\s*$`),m("STAR","(<|>)?=?\\s*\\*"),m("GTE0","^\\s*>=\\s*0\\.0\\.0\\s*$"),m("GTE0PRE","^\\s*>=\\s*0\\.0\\.0-0\\s*$")}),st=A((e,t)=>{"use strict";var r=Object.freeze({loose:!0}),o=Object.freeze({}),a=i=>i?typeof i!="object"?r:i:o;t.exports=a}),Kt=A((e,t)=>{"use strict";var r=/^[0-9]+$/,o=(i,n)=>{let c=r.test(i),s=r.test(n);return c&&s&&(i=+i,n=+n),i===n?0:c&&!s?-1:s&&!c?1:i<n?-1:1},a=(i,n)=>o(n,i);t.exports={compareIdentifiers:o,rcompareIdentifiers:a}}),K=A((e,t)=>{"use strict";var r=De(),{MAX_LENGTH:o,MAX_SAFE_INTEGER:a}=ke(),{safeRe:i,t:n}=ve(),c=st(),{compareIdentifiers:s}=Kt(),f=class Y{constructor(u,h){if(h=c(h),u instanceof Y){if(u.loose===!!h.loose&&u.includePrerelease===!!h.includePrerelease)return u;u=u.version}else if(typeof u!="string")throw new TypeError(`Invalid version. Must be a string. Got type "${typeof u}".`);if(u.length>o)throw new TypeError(`version is longer than ${o} characters`);r("SemVer",u,h),this.options=h,this.loose=!!h.loose,this.includePrerelease=!!h.includePrerelease;let d=u.trim().match(h.loose?i[n.LOOSE]:i[n.FULL]);if(!d)throw new TypeError(`Invalid Version: ${u}`);if(this.raw=u,this.major=+d[1],this.minor=+d[2],this.patch=+d[3],this.major>a||this.major<0)throw new TypeError("Invalid major version");if(this.minor>a||this.minor<0)throw new TypeError("Invalid minor version");if(this.patch>a||this.patch<0)throw new TypeError("Invalid patch version");d[4]?this.prerelease=d[4].split(".").map(g=>{if(/^[0-9]+$/.test(g)){let m=+g;if(m>=0&&m<a)return m}return g}):this.prerelease=[],this.build=d[5]?d[5].split("."):[],this.format()}format(){return this.version=`${this.major}.${this.minor}.${this.patch}`,this.prerelease.length&&(this.version+=`-${this.prerelease.join(".")}`),this.version}toString(){return this.version}compare(u){if(r("SemVer.compare",this.version,this.options,u),!(u instanceof Y)){if(typeof u=="string"&&u===this.version)return 0;u=new Y(u,this.options)}return u.version===this.version?0:this.compareMain(u)||this.comparePre(u)}compareMain(u){return u instanceof Y||(u=new Y(u,this.options)),s(this.major,u.major)||s(this.minor,u.minor)||s(this.patch,u.patch)}comparePre(u){if(u instanceof Y||(u=new Y(u,this.options)),this.prerelease.length&&!u.prerelease.length)return-1;if(!this.prerelease.length&&u.prerelease.length)return 1;if(!this.prerelease.length&&!u.prerelease.length)return 0;let h=0;do{let d=this.prerelease[h],g=u.prerelease[h];if(r("prerelease compare",h,d,g),d===void 0&&g===void 0)return 0;if(g===void 0)return 1;if(d===void 0)return-1;if(d!==g)return s(d,g)}while(++h)}compareBuild(u){u instanceof Y||(u=new Y(u,this.options));let h=0;do{let d=this.build[h],g=u.build[h];if(r("build compare",h,d,g),d===void 0&&g===void 0)return 0;if(g===void 0)return 1;if(d===void 0)return-1;if(d!==g)return s(d,g)}while(++h)}inc(u,h,d){if(u.startsWith("pre")){if(!h&&d===!1)throw new Error("invalid increment argument: identifier is empty");if(h){let g=`-${h}`.match(this.options.loose?i[n.PRERELEASELOOSE]:i[n.PRERELEASE]);if(!g||g[1]!==h)throw new Error(`invalid identifier: ${h}`)}}switch(u){case"premajor":this.prerelease.length=0,this.patch=0,this.minor=0,this.major++,this.inc("pre",h,d);break;case"preminor":this.prerelease.length=0,this.patch=0,this.minor++,this.inc("pre",h,d);break;case"prepatch":this.prerelease.length=0,this.inc("patch",h,d),this.inc("pre",h,d);break;case"prerelease":this.prerelease.length===0&&this.inc("patch",h,d),this.inc("pre",h,d);break;case"release":if(this.prerelease.length===0)throw new Error(`version ${this.raw} is not a prerelease`);this.prerelease.length=0;break;case"major":(this.minor!==0||this.patch!==0||this.prerelease.length===0)&&this.major++,this.minor=0,this.patch=0,this.prerelease=[];break;case"minor":(this.patch!==0||this.prerelease.length===0)&&this.minor++,this.patch=0,this.prerelease=[];break;case"patch":this.prerelease.length===0&&this.patch++,this.prerelease=[];break;case"pre":{let g=Number(d)?1:0;if(this.prerelease.length===0)this.prerelease=[g];else{let m=this.prerelease.length;for(;--m>=0;)typeof this.prerelease[m]=="number"&&(this.prerelease[m]++,m=-2);if(m===-1){if(h===this.prerelease.join(".")&&d===!1)throw new Error("invalid increment argument: identifier already exists");this.prerelease.push(g)}}if(h){let m=[h,g];d===!1&&(m=[h]),s(this.prerelease[0],h)===0?isNaN(this.prerelease[1])&&(this.prerelease=m):this.prerelease=m}break}default:throw new Error(`invalid increment argument: ${u}`)}return this.raw=this.format(),this.build.length&&(this.raw+=`+${this.build.join(".")}`),this}};t.exports=f}),le=A((e,t)=>{"use strict";var r=K(),o=(a,i,n=!1)=>{if(a instanceof r)return a;try{return new r(a,i)}catch(c){if(!n)return null;throw c}};t.exports=o}),bo=A((e,t)=>{"use strict";var r=le(),o=(a,i)=>{let n=r(a,i);return n?n.version:null};t.exports=o}),Ao=A((e,t)=>{"use strict";var r=le(),o=(a,i)=>{let n=r(a.trim().replace(/^[=v]+/,""),i);return n?n.version:null};t.exports=o}),$o=A((e,t)=>{"use strict";var r=K(),o=(a,i,n,c,s)=>{typeof n=="string"&&(s=c,c=n,n=void 0);try{return new r(a instanceof r?a.version:a,n).inc(i,c,s).version}catch{return null}};t.exports=o}),Ro=A((e,t)=>{"use strict";var r=le(),o=(a,i)=>{let n=r(a,null,!0),c=r(i,null,!0),s=n.compare(c);if(s===0)return null;let f=s>0,l=f?n:c,u=f?c:n,h=!!l.prerelease.length;if(u.prerelease.length&&!h){if(!u.patch&&!u.minor)return"major";if(u.compareMain(l)===0)return u.minor&&!u.patch?"minor":"patch"}let d=h?"pre":"";return n.major!==c.major?d+"major":n.minor!==c.minor?d+"minor":n.patch!==c.patch?d+"patch":"prerelease"};t.exports=o}),To=A((e,t)=>{"use strict";var r=K(),o=(a,i)=>new r(a,i).major;t.exports=o}),No=A((e,t)=>{"use strict";var r=K(),o=(a,i)=>new r(a,i).minor;t.exports=o}),Po=A((e,t)=>{"use strict";var r=K(),o=(a,i)=>new r(a,i).patch;t.exports=o}),Oo=A((e,t)=>{"use strict";var r=le(),o=(a,i)=>{let n=r(a,i);return n&&n.prerelease.length?n.prerelease:null};t.exports=o}),V=A((e,t)=>{"use strict";var r=K(),o=(a,i,n)=>new r(a,n).compare(new r(i,n));t.exports=o}),Lo=A((e,t)=>{"use strict";var r=V(),o=(a,i,n)=>r(i,a,n);t.exports=o}),Co=A((e,t)=>{"use strict";var r=V(),o=(a,i)=>r(a,i,!0);t.exports=o}),nt=A((e,t)=>{"use strict";var r=K(),o=(a,i,n)=>{let c=new r(a,n),s=new r(i,n);return c.compare(s)||c.compareBuild(s)};t.exports=o}),ko=A((e,t)=>{"use strict";var r=nt(),o=(a,i)=>a.sort((n,c)=>r(n,c,i));t.exports=o}),Do=A((e,t)=>{"use strict";var r=nt(),o=(a,i)=>a.sort((n,c)=>r(c,n,i));t.exports=o}),Me=A((e,t)=>{"use strict";var r=V(),o=(a,i,n)=>r(a,i,n)>0;t.exports=o}),ct=A((e,t)=>{"use strict";var r=V(),o=(a,i,n)=>r(a,i,n)<0;t.exports=o}),Gt=A((e,t)=>{"use strict";var r=V(),o=(a,i,n)=>r(a,i,n)===0;t.exports=o}),Jt=A((e,t)=>{"use strict";var r=V(),o=(a,i,n)=>r(a,i,n)!==0;t.exports=o}),lt=A((e,t)=>{"use strict";var r=V(),o=(a,i,n)=>r(a,i,n)>=0;t.exports=o}),ut=A((e,t)=>{"use strict";var r=V(),o=(a,i,n)=>r(a,i,n)<=0;t.exports=o}),Vt=A((e,t)=>{"use strict";var r=Gt(),o=Jt(),a=Me(),i=lt(),n=ct(),c=ut(),s=(f,l,u,h)=>{switch(l){case"===":return typeof f=="object"&&(f=f.version),typeof u=="object"&&(u=u.version),f===u;case"!==":return typeof f=="object"&&(f=f.version),typeof u=="object"&&(u=u.version),f!==u;case"":case"=":case"==":return r(f,u,h);case"!=":return o(f,u,h);case">":return a(f,u,h);case">=":return i(f,u,h);case"<":return n(f,u,h);case"<=":return c(f,u,h);default:throw new TypeError(`Invalid operator: ${l}`)}};t.exports=s}),Mo=A((e,t)=>{"use strict";var r=K(),o=le(),{safeRe:a,t:i}=ve(),n=(c,s)=>{if(c instanceof r)return c;if(typeof c=="number"&&(c=String(c)),typeof c!="string")return null;s=s||{};let f=null;if(!s.rtl)f=c.match(s.includePrerelease?a[i.COERCEFULL]:a[i.COERCE]);else{let m=s.includePrerelease?a[i.COERCERTLFULL]:a[i.COERCERTL],P;for(;(P=m.exec(c))&&(!f||f.index+f[0].length!==c.length);)(!f||P.index+P[0].length!==f.index+f[0].length)&&(f=P),m.lastIndex=P.index+P[1].length+P[2].length;m.lastIndex=-1}if(f===null)return null;let l=f[2],u=f[3]||"0",h=f[4]||"0",d=s.includePrerelease&&f[5]?`-${f[5]}`:"",g=s.includePrerelease&&f[6]?`+${f[6]}`:"";return o(`${l}.${u}.${h}${d}${g}`,s)};t.exports=n}),_o=A((e,t)=>{"use strict";var r=class{constructor(){this.max=1e3,this.map=new Map}get(o){let a=this.map.get(o);if(a!==void 0)return this.map.delete(o),this.map.set(o,a),a}delete(o){return this.map.delete(o)}set(o,a){if(!this.delete(o)&&a!==void 0){if(this.map.size>=this.max){let i=this.map.keys().next().value;this.delete(i)}this.map.set(o,a)}return this}};t.exports=r}),X=A((e,t)=>{"use strict";var r=/\s+/g,o=class Pe{constructor(y,S){if(S=n(S),y instanceof Pe)return y.loose===!!S.loose&&y.includePrerelease===!!S.includePrerelease?y:new Pe(y.raw,S);if(y instanceof c)return this.raw=y.value,this.set=[[y]],this.formatted=void 0,this;if(this.options=S,this.loose=!!S.loose,this.includePrerelease=!!S.includePrerelease,this.raw=y.trim().replace(r," "),this.set=this.raw.split("||").map(E=>this.parseRange(E.trim())).filter(E=>E.length),!this.set.length)throw new TypeError(`Invalid SemVer Range: ${this.raw}`);if(this.set.length>1){let E=this.set[0];if(this.set=this.set.filter(I=>!T(I[0])),this.set.length===0)this.set=[E];else if(this.set.length>1){for(let I of this.set)if(I.length===1&&O(I[0])){this.set=[I];break}}}this.formatted=void 0}get range(){if(this.formatted===void 0){this.formatted="";for(let y=0;y<this.set.length;y++){y>0&&(this.formatted+="||");let S=this.set[y];for(let E=0;E<S.length;E++)E>0&&(this.formatted+=" "),this.formatted+=S[E].toString().trim()}}return this.formatted}format(){return this.range}toString(){return this.range}parseRange(y){let S=((this.options.includePrerelease&&m)|(this.options.loose&&P))+":"+y,E=i.get(S);if(E)return E;let I=this.options.loose,v=I?l[u.HYPHENRANGELOOSE]:l[u.HYPHENRANGE];y=y.replace(v,Je(this.options.includePrerelease)),s("hyphen replace",y),y=y.replace(l[u.COMPARATORTRIM],h),s("comparator trim",y),y=y.replace(l[u.TILDETRIM],d),s("tilde trim",y),y=y.replace(l[u.CARETTRIM],g),s("caret trim",y);let b=y.split(" ").map(D=>F(D,this.options)).join(" ").split(/\s+/).map(D=>Ge(D,this.options));I&&(b=b.filter(D=>(s("loose invalid filter",D,this.options),!!D.match(l[u.COMPARATORLOOSE])))),s("range list",b);let C=new Map,L=b.map(D=>new c(D,this.options));for(let D of L){if(T(D))return[D];C.set(D.value,D)}C.size>1&&C.has("")&&C.delete("");let k=[...C.values()];return i.set(S,k),k}intersects(y,S){if(!(y instanceof Pe))throw new TypeError("a Range is required");return this.set.some(E=>x(E,S)&&y.set.some(I=>x(I,S)&&E.every(v=>I.every(b=>v.intersects(b,S)))))}test(y){if(!y)return!1;if(typeof y=="string")try{y=new f(y,this.options)}catch{return!1}for(let S=0;S<this.set.length;S++)if(Ve(this.set[S],y,this.options))return!0;return!1}};t.exports=o;var a=_o(),i=new a,n=st(),c=_e(),s=De(),f=K(),{safeRe:l,t:u,comparatorTrimReplace:h,tildeTrimReplace:d,caretTrimReplace:g}=ve(),{FLAG_INCLUDE_PRERELEASE:m,FLAG_LOOSE:P}=ke(),T=w=>w.value==="<0.0.0-0",O=w=>w.value==="",x=(w,y)=>{let S=!0,E=w.slice(),I=E.pop();for(;S&&E.length;)S=E.every(v=>I.intersects(v,y)),I=E.pop();return S},F=(w,y)=>(s("comp",w,y),w=_(w,y),s("caret",w),w=Z(w,y),s("tildes",w),w=$(w,y),s("xrange",w),w=Ke(w,y),s("stars",w),w),M=w=>!w||w.toLowerCase()==="x"||w==="*",Z=(w,y)=>w.trim().split(/\s+/).map(S=>G(S,y)).join(" "),G=(w,y)=>{let S=y.loose?l[u.TILDELOOSE]:l[u.TILDE];return w.replace(S,(E,I,v,b,C)=>{s("tilde",w,E,I,v,b,C);let L;return M(I)?L="":M(v)?L=`>=${I}.0.0 <${+I+1}.0.0-0`:M(b)?L=`>=${I}.${v}.0 <${I}.${+v+1}.0-0`:C?(s("replaceTilde pr",C),L=`>=${I}.${v}.${b}-${C} <${I}.${+v+1}.0-0`):L=`>=${I}.${v}.${b} <${I}.${+v+1}.0-0`,s("tilde return",L),L})},_=(w,y)=>w.trim().split(/\s+/).map(S=>W(S,y)).join(" "),W=(w,y)=>{s("caret",w,y);let S=y.loose?l[u.CARETLOOSE]:l[u.CARET],E=y.includePrerelease?"-0":"";return w.replace(S,(I,v,b,C,L)=>{s("caret",w,I,v,b,C,L);let k;return M(v)?k="":M(b)?k=`>=${v}.0.0${E} <${+v+1}.0.0-0`:M(C)?v==="0"?k=`>=${v}.${b}.0${E} <${v}.${+b+1}.0-0`:k=`>=${v}.${b}.0${E} <${+v+1}.0.0-0`:L?(s("replaceCaret pr",L),v==="0"?b==="0"?k=`>=${v}.${b}.${C}-${L} <${v}.${b}.${+C+1}-0`:k=`>=${v}.${b}.${C}-${L} <${v}.${+b+1}.0-0`:k=`>=${v}.${b}.${C}-${L} <${+v+1}.0.0-0`):(s("no pr"),v==="0"?b==="0"?k=`>=${v}.${b}.${C}${E} <${v}.${b}.${+C+1}-0`:k=`>=${v}.${b}.${C}${E} <${v}.${+b+1}.0-0`:k=`>=${v}.${b}.${C} <${+v+1}.0.0-0`),s("caret return",k),k})},$=(w,y)=>(s("replaceXRanges",w,y),w.split(/\s+/).map(S=>he(S,y)).join(" ")),he=(w,y)=>{w=w.trim();let S=y.loose?l[u.XRANGELOOSE]:l[u.XRANGE];return w.replace(S,(E,I,v,b,C,L)=>{s("xRange",w,E,I,v,b,C,L);let k=M(v),D=k||M(b),ae=D||M(C),me=ae;return I==="="&&me&&(I=""),L=y.includePrerelease?"-0":"",k?I===">"||I==="<"?E="<0.0.0-0":E="*":I&&me?(D&&(b=0),C=0,I===">"?(I=">=",D?(v=+v+1,b=0,C=0):(b=+b+1,C=0)):I==="<="&&(I="<",D?v=+v+1:b=+b+1),I==="<"&&(L="-0"),E=`${I+v}.${b}.${C}${L}`):D?E=`>=${v}.0.0${L} <${+v+1}.0.0-0`:ae&&(E=`>=${v}.${b}.0${L} <${v}.${+b+1}.0-0`),s("xRange return",E),E})},Ke=(w,y)=>(s("replaceStars",w,y),w.trim().replace(l[u.STAR],"")),Ge=(w,y)=>(s("replaceGTE0",w,y),w.trim().replace(l[y.includePrerelease?u.GTE0PRE:u.GTE0],"")),Je=w=>(y,S,E,I,v,b,C,L,k,D,ae,me)=>(M(E)?S="":M(I)?S=`>=${E}.0.0${w?"-0":""}`:M(v)?S=`>=${E}.${I}.0${w?"-0":""}`:b?S=`>=${S}`:S=`>=${S}${w?"-0":""}`,M(k)?L="":M(D)?L=`<${+k+1}.0.0-0`:M(ae)?L=`<${k}.${+D+1}.0-0`:me?L=`<=${k}.${D}.${ae}-${me}`:w?L=`<${k}.${D}.${+ae+1}-0`:L=`<=${L}`,`${S} ${L}`.trim()),Ve=(w,y,S)=>{for(let E=0;E<w.length;E++)if(!w[E].test(y))return!1;if(y.prerelease.length&&!S.includePrerelease){for(let E=0;E<w.length;E++)if(s(w[E].semver),w[E].semver!==c.ANY&&w[E].semver.prerelease.length>0){let I=w[E].semver;if(I.major===y.major&&I.minor===y.minor&&I.patch===y.patch)return!0}return!1}return!0}}),_e=A((e,t)=>{"use strict";var r=Symbol("SemVer ANY"),o=class Qe{static get ANY(){return r}constructor(h,d){if(d=a(d),h instanceof Qe){if(h.loose===!!d.loose)return h;h=h.value}h=h.trim().split(/\s+/).join(" "),s("comparator",h,d),this.options=d,this.loose=!!d.loose,this.parse(h),this.semver===r?this.value="":this.value=this.operator+this.semver.version,s("comp",this)}parse(h){let d=this.options.loose?i[n.COMPARATORLOOSE]:i[n.COMPARATOR],g=h.match(d);if(!g)throw new TypeError(`Invalid comparator: ${h}`);this.operator=g[1]!==void 0?g[1]:"",this.operator==="="&&(this.operator=""),g[2]?this.semver=new f(g[2],this.options.loose):this.semver=r}toString(){return this.value}test(h){if(s("Comparator.test",h,this.options.loose),this.semver===r||h===r)return!0;if(typeof h=="string")try{h=new f(h,this.options)}catch{return!1}return c(h,this.operator,this.semver,this.options)}intersects(h,d){if(!(h instanceof Qe))throw new TypeError("a Comparator is required");return this.operator===""?this.value===""?!0:new l(h.value,d).test(this.value):h.operator===""?h.value===""?!0:new l(this.value,d).test(h.semver):(d=a(d),d.includePrerelease&&(this.value==="<0.0.0-0"||h.value==="<0.0.0-0")||!d.includePrerelease&&(this.value.startsWith("<0.0.0")||h.value.startsWith("<0.0.0"))?!1:!!(this.operator.startsWith(">")&&h.operator.startsWith(">")||this.operator.startsWith("<")&&h.operator.startsWith("<")||this.semver.version===h.semver.version&&this.operator.includes("=")&&h.operator.includes("=")||c(this.semver,"<",h.semver,d)&&this.operator.startsWith(">")&&h.operator.startsWith("<")||c(this.semver,">",h.semver,d)&&this.operator.startsWith("<")&&h.operator.startsWith(">")))}};t.exports=o;var a=st(),{safeRe:i,t:n}=ve(),c=Vt(),s=De(),f=K(),l=X()}),Ue=A((e,t)=>{"use strict";var r=X(),o=(a,i,n)=>{try{i=new r(i,n)}catch{return!1}return i.test(a)};t.exports=o}),Uo=A((e,t)=>{"use strict";var r=X(),o=(a,i)=>new r(a,i).set.map(n=>n.map(c=>c.value).join(" ").trim().split(" "));t.exports=o}),xo=A((e,t)=>{"use strict";var r=K(),o=X(),a=(i,n,c)=>{let s=null,f=null,l=null;try{l=new o(n,c)}catch{return null}return i.forEach(u=>{l.test(u)&&(!s||f.compare(u)===-1)&&(s=u,f=new r(s,c))}),s};t.exports=a}),jo=A((e,t)=>{"use strict";var r=K(),o=X(),a=(i,n,c)=>{let s=null,f=null,l=null;try{l=new o(n,c)}catch{return null}return i.forEach(u=>{l.test(u)&&(!s||f.compare(u)===1)&&(s=u,f=new r(s,c))}),s};t.exports=a}),Fo=A((e,t)=>{"use strict";var r=K(),o=X(),a=Me(),i=(n,c)=>{n=new o(n,c);let s=new r("0.0.0");if(n.test(s)||(s=new r("0.0.0-0"),n.test(s)))return s;s=null;for(let f=0;f<n.set.length;++f){let l=n.set[f],u=null;l.forEach(h=>{let d=new r(h.semver.version);switch(h.operator){case">":d.prerelease.length===0?d.patch++:d.prerelease.push(0),d.raw=d.format();case"":case">=":(!u||a(d,u))&&(u=d);break;case"<":case"<=":break;default:throw new Error(`Unexpected operation: ${h.operator}`)}}),u&&(!s||a(s,u))&&(s=u)}return s&&n.test(s)?s:null};t.exports=i}),Wo=A((e,t)=>{"use strict";var r=X(),o=(a,i)=>{try{return new r(a,i).range||"*"}catch{return null}};t.exports=o}),pt=A((e,t)=>{"use strict";var r=K(),o=_e(),{ANY:a}=o,i=X(),n=Ue(),c=Me(),s=ct(),f=ut(),l=lt(),u=(h,d,g,m)=>{h=new r(h,m),d=new i(d,m);let P,T,O,x,F;switch(g){case">":P=c,T=f,O=s,x=">",F=">=";break;case"<":P=s,T=l,O=c,x="<",F="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if(n(h,d,m))return!1;for(let M=0;M<d.set.length;++M){let Z=d.set[M],G=null,_=null;if(Z.forEach(W=>{W.semver===a&&(W=new o(">=0.0.0")),G=G||W,_=_||W,P(W.semver,G.semver,m)?G=W:O(W.semver,_.semver,m)&&(_=W)}),G.operator===x||G.operator===F||(!_.operator||_.operator===x)&&T(h,_.semver)||_.operator===F&&O(h,_.semver))return!1}return!0};t.exports=u}),Ho=A((e,t)=>{"use strict";var r=pt(),o=(a,i,n)=>r(a,i,">",n);t.exports=o}),Bo=A((e,t)=>{"use strict";var r=pt(),o=(a,i,n)=>r(a,i,"<",n);t.exports=o}),Ko=A((e,t)=>{"use strict";var r=X(),o=(a,i,n)=>(a=new r(a,n),i=new r(i,n),a.intersects(i,n));t.exports=o}),Go=A((e,t)=>{"use strict";var r=Ue(),o=V();t.exports=(a,i,n)=>{let c=[],s=null,f=null,l=a.sort((g,m)=>o(g,m,n));for(let g of l)r(g,i,n)?(f=g,s||(s=g)):(f&&c.push([s,f]),f=null,s=null);s&&c.push([s,null]);let u=[];for(let[g,m]of c)g===m?u.push(g):!m&&g===l[0]?u.push("*"):m?g===l[0]?u.push(`<=${m}`):u.push(`${g} - ${m}`):u.push(`>=${g}`);let h=u.join(" || "),d=typeof i.raw=="string"?i.raw:String(i);return h.length<d.length?h:i}}),Jo=A((e,t)=>{"use strict";var r=X(),o=_e(),{ANY:a}=o,i=Ue(),n=V(),c=(d,g,m={})=>{if(d===g)return!0;d=new r(d,m),g=new r(g,m);let P=!1;e:for(let T of d.set){for(let O of g.set){let x=l(T,O,m);if(P=P||x!==null,x)continue e}if(P)return!1}return!0},s=[new o(">=0.0.0-0")],f=[new o(">=0.0.0")],l=(d,g,m)=>{if(d===g)return!0;if(d.length===1&&d[0].semver===a){if(g.length===1&&g[0].semver===a)return!0;m.includePrerelease?d=s:d=f}if(g.length===1&&g[0].semver===a){if(m.includePrerelease)return!0;g=f}let P=new Set,T,O;for(let $ of d)$.operator===">"||$.operator===">="?T=u(T,$,m):$.operator==="<"||$.operator==="<="?O=h(O,$,m):P.add($.semver);if(P.size>1)return null;let x;if(T&&O&&(x=n(T.semver,O.semver,m),x>0||x===0&&(T.operator!==">="||O.operator!=="<=")))return null;for(let $ of P){if(T&&!i($,String(T),m)||O&&!i($,String(O),m))return null;for(let he of g)if(!i($,String(he),m))return!1;return!0}let F,M,Z,G,_=O&&!m.includePrerelease&&O.semver.prerelease.length?O.semver:!1,W=T&&!m.includePrerelease&&T.semver.prerelease.length?T.semver:!1;_&&_.prerelease.length===1&&O.operator==="<"&&_.prerelease[0]===0&&(_=!1);for(let $ of g){if(G=G||$.operator===">"||$.operator===">=",Z=Z||$.operator==="<"||$.operator==="<=",T){if(W&&$.semver.prerelease&&$.semver.prerelease.length&&$.semver.major===W.major&&$.semver.minor===W.minor&&$.semver.patch===W.patch&&(W=!1),$.operator===">"||$.operator===">="){if(F=u(T,$,m),F===$&&F!==T)return!1}else if(T.operator===">="&&!i(T.semver,String($),m))return!1}if(O){if(_&&$.semver.prerelease&&$.semver.prerelease.length&&$.semver.major===_.major&&$.semver.minor===_.minor&&$.semver.patch===_.patch&&(_=!1),$.operator==="<"||$.operator==="<="){if(M=h(O,$,m),M===$&&M!==O)return!1}else if(O.operator==="<="&&!i(O.semver,String($),m))return!1}if(!$.operator&&(O||T)&&x!==0)return!1}return!(T&&Z&&!O&&x!==0||O&&G&&!T&&x!==0||W||_)},u=(d,g,m)=>{if(!d)return g;let P=n(d.semver,g.semver,m);return P>0?d:P<0||g.operator===">"&&d.operator===">="?g:d},h=(d,g,m)=>{if(!d)return g;let P=n(d.semver,g.semver,m);return P<0?d:P>0||g.operator==="<"&&d.operator==="<="?g:d};t.exports=c}),Xt=A((e,t)=>{"use strict";var r=ve(),o=ke(),a=K(),i=Kt(),n=le(),c=bo(),s=Ao(),f=$o(),l=Ro(),u=To(),h=No(),d=Po(),g=Oo(),m=V(),P=Lo(),T=Co(),O=nt(),x=ko(),F=Do(),M=Me(),Z=ct(),G=Gt(),_=Jt(),W=lt(),$=ut(),he=Vt(),Ke=Mo(),Ge=_e(),Je=X(),Ve=Ue(),w=Uo(),y=xo(),S=jo(),E=Fo(),I=Wo(),v=pt(),b=Ho(),C=Bo(),L=Ko(),k=Go(),D=Jo();t.exports={parse:n,valid:c,clean:s,inc:f,diff:l,major:u,minor:h,patch:d,prerelease:g,compare:m,rcompare:P,compareLoose:T,compareBuild:O,sort:x,rsort:F,gt:M,lt:Z,eq:G,neq:_,gte:W,lte:$,cmp:he,coerce:Ke,Comparator:Ge,Range:Je,satisfies:Ve,toComparators:w,maxSatisfying:y,minSatisfying:S,minVersion:E,validRange:I,outside:v,gtr:b,ltr:C,intersects:L,simplifyRange:k,subset:D,SemVer:a,re:r.re,src:r.src,tokens:r.t,SEMVER_SPEC_VERSION:o.SEMVER_SPEC_VERSION,RELEASE_TYPES:o.RELEASE_TYPES,compareIdentifiers:i.compareIdentifiers,rcompareIdentifiers:i.rcompareIdentifiers}}),Se=class extends Qo{constructor(e){super(),this.dirName=$t(oa(),".medplum"),this.fileName=$t(this.dirName,e+".json")}clear(){this.writeFile({})}getString(e){return this.readFile()?.[e]}setString(e,t){let r=this.readFile()??{};t?r[e]=t:delete r[e],this.writeFile(r)}getObject(e){let t=this.getString(e);return t?JSON.parse(t):void 0}setObject(e,t){this.setString(e,t?JSON.stringify(t):void 0)}readFile(){if(At(this.fileName))return JSON.parse(ta(this.fileName,"utf8"))}writeFile(e){At(this.dirName)||ea(this.dirName),ra(this.fileName,JSON.stringify(e,null,2),"utf8")}};we=new TextEncoder,Tt=new TextDecoder,Kn=2**32;qe=e=>na.from(e).toString("base64url"),Ie=class extends Error{constructor(e,t){super(e,t),B(this,"code","ERR_JOSE_GENERIC"),this.name=this.constructor.name,Error.captureStackTrace?.(this,this.constructor)}};B(Ie,"code","ERR_JOSE_GENERIC");ue=class extends Ie{constructor(){super(...arguments),B(this,"code","ERR_JOSE_NOT_SUPPORTED")}};B(ue,"code","ERR_JOSE_NOT_SUPPORTED");ie=class extends Ie{constructor(){super(...arguments),B(this,"code","ERR_JWS_INVALID")}};B(ie,"code","ERR_JWS_INVALID");Yt=class extends Ie{constructor(){super(...arguments),B(this,"code","ERR_JWT_INVALID")}};B(Yt,"code","ERR_JWT_INVALID");la=class extends(Pt=Ie,Nt=Symbol.asyncIterator,Pt){constructor(e="multiple matching keys found in the JSON Web Key Set",t){super(e,t),B(this,Nt),B(this,"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS")}};B(la,"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS");Qt=e=>Zt.types.isKeyObject(e),ua=er.webcrypto,pa=ua,ht=e=>tr.types.isCryptoKey(e);tt=(e,...t)=>rr("Key must be ",e,...t);ar=e=>Qt(e)||ht(e),ne=["KeyObject"];(globalThis.CryptoKey||pa?.CryptoKey)&&ne.push("CryptoKey");fa=(...e)=>{let t=e.filter(Boolean);if(t.length===0||t.length===1)return!0;let r;for(let o of t){let a=Object.keys(o);if(!r||r.size===0){r=new Set(a);continue}for(let i of a){if(r.has(i))return!1;r.add(i)}}return!0},ga=fa;Ia=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 ue("Unsupported key curve for this operation")}},ba=(e,t)=>{let r;if(ht(e))r=wa.from(e);else if(Qt(e))r=e;else{if(be(e))return e.crv;throw new TypeError(tt(e,...ne))}if(r.type==="secret")throw new TypeError('only "private" or "public" type keys can be used for this operation');switch(r.asymmetricKeyType){case"ed25519":case"ed448":return`Ed${r.asymmetricKeyType.slice(2)}`;case"x25519":case"x448":return`X${r.asymmetricKeyType.slice(1)}`;case"ec":{let o=r.asymmetricKeyDetails.namedCurve;return t?o:Ia(o)}default:throw new TypeError("Invalid asymmetric key type for this operation")}},Aa=ba,Ot=(e,t)=>{let r;try{e instanceof $a?r=e.asymmetricKeyDetails?.modulusLength:r=Buffer.from(e.n,"base64url").byteLength<<3}catch{}if(typeof r!="number"||r<2048)throw new TypeError(`${t} requires key modulusLength to be 2048 bits or larger`)},se=e=>e?.[Symbol.toStringTag],rt=(e,t,r)=>{if(t.use!==void 0&&t.use!=="sig")throw new TypeError("Invalid key for this operation, when present its use must be sig");if(t.key_ops!==void 0&&t.key_ops.includes?.(r)!==!0)throw new TypeError(`Invalid key for this operation, when present its key_ops must include ${r}`);if(t.alg!==void 0&&t.alg!==e)throw new TypeError(`Invalid key for this operation, when present its alg must be ${e}`);return!0},Ra=(e,t,r,o)=>{if(!(t instanceof Uint8Array)){if(o&&be(t)){if(Sa(t)&&rt(e,t,r))return;throw new TypeError('JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present')}if(!ar(t))throw new TypeError(or(e,t,...ne,"Uint8Array",o?"JSON Web Key":null));if(t.type!=="secret")throw new TypeError(`${se(t)} instances for symmetric algorithms must be of type "secret"`)}},Ta=(e,t,r,o)=>{if(o&&be(t))switch(r){case"sign":if(Ea(t)&&rt(e,t,r))return;throw new TypeError("JSON Web Key for this operation be a private JWK");case"verify":if(va(t)&&rt(e,t,r))return;throw new TypeError("JSON Web Key for this operation be a public JWK")}if(!ar(t))throw new TypeError(or(e,t,...ne,o?"JSON Web Key":null));if(t.type==="secret")throw new TypeError(`${se(t)} instances for asymmetric algorithms must not be of type "secret"`);if(r==="sign"&&t.type==="public")throw new TypeError(`${se(t)} instances for asymmetric algorithm signing must be of type "private"`);if(r==="decrypt"&&t.type==="public")throw new TypeError(`${se(t)} instances for asymmetric algorithm decryption must be of type "private"`);if(t.algorithm&&r==="verify"&&t.type==="private")throw new TypeError(`${se(t)} instances for asymmetric algorithm verifying must be of type "public"`);if(t.algorithm&&r==="encrypt"&&t.type==="private")throw new TypeError(`${se(t)} instances for asymmetric algorithm encryption must be of type "public"`)};Vn=sr.bind(void 0,!1),Na=sr.bind(void 0,!0);Oa=Pa;ka=new Map([["ES256","P-256"],["ES256K","secp256k1"],["ES384","P-384"],["ES512","P-521"]]);xa=Ma(xe.sign),ja=async(e,t,r)=>{let o=Ua(e,t,"sign");if(e.startsWith("HS")){let a=xe.createHmac(_a(e),o);return a.update(r),a.digest()}return xa(La(e),r,Da(e,o))},Fa=ja,ee=e=>Math.floor(e.getTime()/1e3),Wa=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i,Ye=e=>{let t=Wa.exec(e);if(!t||t[4]&&t[1])throw new TypeError("Invalid time period format");let r=parseFloat(t[2]),o=t[3].toLowerCase(),a;switch(o){case"sec":case"secs":case"second":case"seconds":case"s":a=Math.round(r);break;case"minute":case"minutes":case"min":case"mins":case"m":a=Math.round(r*60);break;case"hour":case"hours":case"hr":case"hrs":case"h":a=Math.round(r*3600);break;case"day":case"days":case"d":a=Math.round(r*86400);break;case"week":case"weeks":case"w":a=Math.round(r*604800);break;default:a=Math.round(r*31557600);break}return t[1]==="-"||t[4]==="ago"?-a:a},Ha=class{constructor(e){if(B(this,"_payload"),B(this,"_protectedHeader"),B(this,"_unprotectedHeader"),!(e instanceof Uint8Array))throw new TypeError("payload must be an instance of Uint8Array");this._payload=e}setProtectedHeader(e){if(this._protectedHeader)throw new TypeError("setProtectedHeader can only be called once");return this._protectedHeader=e,this}setUnprotectedHeader(e){if(this._unprotectedHeader)throw new TypeError("setUnprotectedHeader can only be called once");return this._unprotectedHeader=e,this}async sign(e,t){if(!this._protectedHeader&&!this._unprotectedHeader)throw new ie("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");if(!ga(this._protectedHeader,this._unprotectedHeader))throw new ie("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let r={...this._protectedHeader,...this._unprotectedHeader},o=Oa(ie,new Map([["b64",!0]]),t?.crit,this._protectedHeader,r),a=!0;if(o.has("b64")&&(a=this._protectedHeader.b64,typeof a!="boolean"))throw new ie('The "b64" (base64url-encode payload) Header Parameter must be a boolean');let{alg:i}=r;if(typeof i!="string"||!i)throw new ie('JWS "alg" (Algorithm) Header Parameter missing or invalid');Na(i,e,"sign");let n=this._payload;a&&(n=we.encode(qe(n)));let c;this._protectedHeader?c=we.encode(qe(JSON.stringify(this._protectedHeader))):c=we.encode("");let s=ca(c,we.encode("."),n),f=await Fa(i,e,s),l={signature:qe(f),payload:""};return a&&(l.payload=Tt.decode(n)),this._unprotectedHeader&&(l.header=this._unprotectedHeader),this._protectedHeader&&(l.protected=Tt.decode(c)),l}},Ba=class{constructor(e){B(this,"_flattened"),this._flattened=new Ha(e)}setProtectedHeader(e){return this._flattened.setProtectedHeader(e),this}async sign(e,t){let r=await this._flattened.sign(e,t);if(r.payload===void 0)throw new TypeError("use the flattened module for creating JWS with b64: false");return`${r.protected}.${r.payload}.${r.signature}`}};Ka=class{constructor(e={}){if(B(this,"_payload"),!ir(e))throw new TypeError("JWT Claims Set MUST be an object");this._payload=e}setIssuer(e){return this._payload={...this._payload,iss:e},this}setSubject(e){return this._payload={...this._payload,sub:e},this}setAudience(e){return this._payload={...this._payload,aud:e},this}setJti(e){return this._payload={...this._payload,jti:e},this}setNotBefore(e){return typeof e=="number"?this._payload={...this._payload,nbf:te("setNotBefore",e)}:e instanceof Date?this._payload={...this._payload,nbf:te("setNotBefore",ee(e))}:this._payload={...this._payload,nbf:ee(new Date)+Ye(e)},this}setExpirationTime(e){return typeof e=="number"?this._payload={...this._payload,exp:te("setExpirationTime",e)}:e instanceof Date?this._payload={...this._payload,exp:te("setExpirationTime",ee(e))}:this._payload={...this._payload,exp:ee(new Date)+Ye(e)},this}setIssuedAt(e){return typeof e>"u"?this._payload={...this._payload,iat:ee(new Date)}:e instanceof Date?this._payload={...this._payload,iat:te("setIssuedAt",ee(e))}:typeof e=="string"?this._payload={...this._payload,iat:te("setIssuedAt",ee(new Date)+Ye(e))}:this._payload={...this._payload,iat:te("setIssuedAt",e)},this}},Ga=class extends Ka{constructor(){super(...arguments),B(this,"_protectedHeader")}setProtectedHeader(e){return this._protectedHeader=e,this}async sign(e,t){let r=new Ba(we.encode(JSON.stringify(this._payload)));if(r.setProtectedHeader(this._protectedHeader),Array.isArray(this._protectedHeader?.crit)&&this._protectedHeader.crit.includes("b64")&&this._protectedHeader.b64===!1)throw new Yt("JWTs MUST NOT use unencoded payload");return r.sign(e,t)}};R=class extends sa{action(e){let t=ci(this,e);return super._actionHandler=t,this}resetOptionDefaults(){this._optionValues={};for(let e of this.options)e.defaultValue!==void 0&&(this._optionValues[e.attributeName()]=e.defaultValue)}};mr=new R("status").aliases(["info","list","ls"]),fr=new R("ping"),gr=new R("push"),yr=new R("reload-config"),wr=new R("upgrade"),de=new R("agent");N(de,mr);N(de,fr);N(de,gr);N(de,yr);N(de,wr);mr.description("Get the status of a specified agent").argument("[agentIds...]","The ID(s) of the agent(s) to get the status of").option("--criteria <criteria>","An optional FHIR search criteria to resolve the agent to get the status of. Mutually exclusive with [agentIds...] arg").addOption(new dt("--output <format>","An optional output format, defaults to table").choices(["table","json"]).default("table")).action(async(e,t)=>{await ft({operation:"$bulk-status",agentIds:e,options:t,parseSuccessfulResponse:r=>{let o=pi(r.result,{required:["status","version"],optional:["lastUpdated"]});return{id:r.agent.id,name:r.agent.name,enabledStatus:r.agent.status,version:o.version,connectionStatus:o.status,statusLastUpdated:o.lastUpdated??"N/A"}}})});fr.description("Ping a host from a specified agent").argument("<ipOrDomain>","The IPv4 address or domain name to ping").argument("[agentId]","Conditionally optional ID of the agent to ping from. Mutually exclusive with --criteria <criteria> option").option("--count <count>","An optional amount of pings to issue before returning results","1").option("--criteria <criteria>","An optional FHIR search criteria to resolve the agent to ping from. Mutually exclusive with [agentId] arg").action(async(e,t,r)=>{let o=await U(r),a=await Er(o,t,r),i=Number.parseInt(r.count,10);if(Number.isNaN(i))throw new Error("--count <count> must be an integer if specified");try{let n=await o.pushToAgent(a,e,`PING ${i}`,zt.PING,!0,{maxRetries:0});console.info(n)}catch(n){throw new Error("Unexpected response from agent while pinging",{cause:n})}});gr.description("Push a message to a target device via a specified agent").argument("<deviceId>","The ID of the device to push the message to").argument("<message>","The message to send to the destination device").argument("[agentId]","Conditionally optional ID of the agent to send the message from. Mutually exclusive with --criteria <criteria> option").option("--content-type <contentType>","The content type of the message",zt.HL7_V2).option("--no-wait","Tells the server not to wait for a response from the destination device").option("--criteria <criteria>","An optional FHIR search criteria to resolve the agent to ping from. Mutually exclusive with [agentId] arg").action(async(e,t,r,o)=>{let a=await U(o),i=await Er(a,r,o),n;try{n=await a.pushToAgent(i,{reference:`Device/${e}`},t,o.contentType,o.wait!==!1,{maxRetries:0})}catch(c){throw new Error("Unexpected response from agent while pushing message to agent",{cause:c})}console.info(n)});yr.description("Reload the config for the specified agent(s)").argument("[agentIds...]","The ID(s) of the agent(s) for which the config should be reloaded. Mutually exclusive with --criteria <criteria> flag").option("--criteria <criteria>","An optional FHIR search criteria to resolve the agent(s) for which to notify to reload their config. Mutually exclusive with [agentIds...] arg").addOption(new dt("--output <format>","An optional output format, defaults to table").choices(["table","json"]).default("table")).action(async(e,t)=>{await ft({operation:"$reload-config",agentIds:e,options:t,parseSuccessfulResponse:r=>({id:r.agent.id,name:r.agent.name})})});wr.description("Upgrade the version for the specified agent(s)").argument("[agentIds...]","The ID(s) of the agent(s) that should be upgraded. Mutually exclusive with --criteria <criteria> flag").option("--criteria <criteria>","An optional FHIR search criteria to resolve the agent(s) to upgrade. Mutually exclusive with [agentIds...] arg").option("--version <version>","An optional version to upgrade to. Defaults to the latest version if flag not included").addOption(new dt("--output <format>","An optional output format, defaults to table").choices(["table","json"]).default("table")).action(async(e,t)=>{await ft({operation:"$upgrade",agentIds:e,options:t,parseSuccessfulResponse:r=>({id:r.agent.id,name:r.agent.name,version:t.version??"latest"})})});Sr=fi,Ir="http://localhost:9615",br=new R("login"),Ar=new R("whoami"),$r=new R("token");br.action(async e=>{let t=e.profile??"default",r=hr(t,e),o=await U(e,!1);await vi(o,r)});Ar.action(async e=>{let t=await U(e);bi(t)});$r.action(async e=>{let t=await U(e);await t.getProfileAsync();let r=t.getAccessToken();if(!r)throw new Error("Not logged in");console.log(r)});ge="\x1B[0m",$i="\x1B[1m",Ri="\x1B[31m",Ti="\x1B[32m",Ni="\x1B[33m",Pi="\x1B[34m",Ee={red:e=>`${Ri}${e}${ge}`,green:e=>`${Ti}${e}${ge}`,yellow:e=>`${Ni}${e}${ge}`,blue:e=>`${Pi}${e}${ge}`,bold:e=>`${$i}${e}${ge}`},Mt=e=>e.replace(/\*\*(.*?)\*\*/g,(t,r)=>Ee.bold(r)),Oi=Bt(Xt());Le=new Rr({}),Vi=new Di({region:"us-east-1"}),gc=new _i({}),yt=new Ui({}),Xi="medplum:environment";ls=e=>`${e}DomainName`,_r=e=>`${e}SslCertArn`;at=Bt(Xt());jr=new R("save"),Fr=new R("deploy"),Wr=new R("create"),He=new R("bot");N(He,jr);N(He,Fr);N(He,Wr);Hr=new R("save-bot"),Br=new R("deploy-bot"),Kr=new R("create-bot");jr.description("Saving the bot").argument("<botName>").action(async(e,t)=>{let r=await U(t);await Be(r,e)});Fr.description("Deploy the app to AWS").argument("<botName>").action(async(e,t)=>{let r=await U(t);await Be(r,e,!0)});Wr.arguments("<botName> <projectId> <sourceFile> <distFile>").description("Creating a bot").option("--runtime-version <runtimeVersion>","Runtime version (awslambda, vmcontext)").option("--no-write-config","Do not write bot to config").action(async(e,t,r,o,a)=>{let i=await U(a);await dr(i,e,t,r,o,a.runtimeVersion,!!a.writeConfig)});Hr.description("Saves the bot").argument("<botName>").action(async(e,t)=>{let r=await U(t);await Be(r,e)});Br.description("Deploy the bot to AWS").argument("<botName>").action(async(e,t)=>{let r=await U(t);await Be(r,e,!0)});Kr.arguments("<botName> <projectId> <sourceFile> <distFile>").description("Creates and saves the bot").action(async(e,t,r,o,a)=>{let i=await U(a);await dr(i,e,t,r,o)});Jr=new R("export"),Vr=new R("import"),vt=new R("bulk");N(vt,Jr);N(vt,Vr);Jr.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:a}=e,i=await U(e);(await i.bulkExport(t,r,o,{pollStatusOnAccepted:!0})).output?.forEach(async({type:n,url:c})=>{let s=new URL(c),f=await i.download(c),l=`${n}_${s.pathname}`.replace(/[^a-zA-Z0-9]+/g,"_")+".ndjson",u=Gr(a??"",l);Zs(`${u}`,await f.text(),()=>{console.log(`${u} is created`)})})});Vr.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:a}=t,i=Gr(a??process.cwd(),e),n=await U(t);await en(i,Number.parseInt(r,10),n,o)});Xr=class extends EventTarget{addEventListener(e,t,r){super.addEventListener(e,t,r)}removeEventListener(e,t,r){super.removeEventListener(e,t,r)}},pn=class extends Event{constructor(e,t){super("message"),this.connection=e,this.message=t}},Oe=class extends Event{constructor(e){super("error"),this.error=e}},qr=class extends Event{constructor(){super("close")}},zr=class extends Xr{constructor(e,t="utf-8",r=!1){super(),this.chunks=[],this.messageQueue=[],this.socket=e,this.encoding=t,this.enhancedMode=r,e.on("data",o=>{try{if(this.appendData(o),o.at(-2)===28&&o.at(-1)===13){let a=Buffer.concat(this.chunks),i=a.subarray(1,a.length-2),n=Ht.decode(i,this.encoding),c=cn.parse(n);this.dispatchEvent(new pn(this,c)),this.resetBuffer()}}catch(a){this.dispatchEvent(new Oe(a))}}),e.on("error",o=>{this.resetBuffer(),this.dispatchEvent(new Oe(o))}),e.on("end",()=>{this.close()}),this.addEventListener("message",o=>{r&&this.send(o.message.buildAck({ackCode:"CA"}));let a=this.messageQueue.shift();if(!a){this.dispatchEvent(new Oe(new Error(`Received a message when no pending messages were in the queue. Message: ${o.message}`)));return}a.resolve?.(o.message)})}sendImpl(e,t){this.messageQueue.push(t);let r=e.toString(),o=Ht.encode(r,this.encoding),a=Buffer.alloc(o.length+3);a.writeInt8(11,0),o.copy(a,1),a.writeInt8(28,o.length+1),a.writeInt8(13,o.length+2),this.socket.write(a)}send(e){this.sendImpl(e,{message:e})}async sendAndWait(e){return new Promise((t,r)=>{let o={message:e,resolve:t,reject:r};this.sendImpl(e,o)})}close(){this.socket.end(),this.socket.destroy(),this.dispatchEvent(new qr)}appendData(e){this.chunks.push(e)}resetBuffer(){this.chunks=[]}},dn=class extends Xr{constructor(e){super(),this.options=e,this.host=this.options.host,this.port=this.options.port,this.encoding=this.options.encoding,this.keepAlive=this.options.keepAlive??!1,this.connectTimeout=this.options.connectTimeout??3e4}connect(){return this.connection?Promise.resolve(this.connection):(this.socket&&(this.socket.removeAllListeners(),this.socket.destroy(),this.socket=void 0),new Promise((e,t)=>{this.socket=nn({host:this.host,port:this.port,keepAlive:this.keepAlive}),this.connectTimeout>0&&(this.socket.setTimeout(this.connectTimeout),this.socket.on("timeout",()=>{let r=new Error(`Connection timeout after ${this.connectTimeout}ms`);this.socket&&(this.socket.destroy(),this.socket=void 0),t(r)})),this.socket.on("connect",()=>{if(!this.socket)return;let r;this.connection=r=new zr(this.socket,this.encoding),this.socket.setTimeout(0),r.addEventListener("close",()=>{this.socket=void 0,this.dispatchEvent(new qr)}),r.addEventListener("error",o=>{this.dispatchEvent(new Oe(o.error))}),e(this.connection)}),this.socket.on("error",r=>{this.socket&&(this.socket.destroy(),this.socket=void 0),t(r)})}))}async send(e){return(await this.connect()).send(e)}async sendAndWait(e){return(await this.connect()).sendAndWait(e)}close(){this.socket&&(this.socket.removeAllListeners(),this.socket.destroy(),this.socket=void 0),this.connection&&(this.connection.close(),delete this.connection)}},hn=class{constructor(e){this.handler=e}start(e,t,r=!1){let o=un.createServer(i=>{let n=new zr(i,t,r);this.handler(n)}),a=async i=>{i?.code==="EADDRINUSE"&&(await ln(50),o.close(),o.listen(e))};o.on("error",a),o.once("listening",()=>{o.off("error",a)}),o.listen(e),this.server=o}async stop(){return new Promise((e,t)=>{if(!this.server){t(new Error("Stop was called but there is no server running"));return}this.server.close(r=>{if(r){t(r);return}e()}),this.server=void 0})}},fn=new R("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").option("--encoding <encoding>","The encoding to use").action(async(e,t,r,o)=>{if(o.generateExample?r=yn():o.file&&(r=mn(o.file,"utf8")),!r)throw new Error("Missing HL7 message body");let a=new dn({host:e,port:Number.parseInt(t,10),encoding:o.encoding});try{let i=await a.sendAndWait(sn.parse(r));console.log(i.toString().replaceAll("\r",`
|
|
23
|
+
`))}finally{a.close()}}),gn=new R("listen").description("Starts an HL7 v2 MLLP server").argument("<port>").option("--encoding <encoding>","The encoding to use").action(async(e,t)=>{new hn(r=>{r.addEventListener("message",({message:o})=>{console.log(o.toString().replaceAll("\r",`
|
|
24
|
+
`)),r.send(o.buildAck())})}).start(Number.parseInt(e,10),t.encoding),console.log("Listening on port "+e)}),St=new R("hl7");N(St,fn);N(St,gn);Yr=new R("set"),Zr=new R("remove"),Qr=new R("list"),eo=new R("describe"),Ae=new R("profile");N(Ae,Yr);N(Ae,Zr);N(Ae,Qr);N(Ae,eo);Yr.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)=>{hr(e,t)});Zr.argument("<profileName>","Name of the profile").description("Remove a profile by name").action(async e=>{new Se(e).setObject("options",void 0),console.log(`${e} profile removed`)});Qr.description("List all profiles saved").action(async()=>{let e=vn(En(),".medplum"),t=wn(e),r=[];t.forEach(o=>{let a=o.split(".")[0],i=new Se(a).getObject("options");i&&r.push({profileName:a,profile:i})}),console.log(r)});eo.argument("<profileName>","Name of the profile").description("Describes a profile").action(async e=>{let t=ii(e);console.log(t)});to=new R("list"),ro=new R("current"),oo=new R("switch"),ao=new R("invite"),$e=new R("project");N($e,to);N($e,ro);N($e,oo);N($e,ao);to.description("List of current projects").action(async e=>{let t=await U(e);In(t)});ro.description("Project you are currently on").action(async e=>{let t=(await U(e)).getActiveLogin();if(!t)throw new Error("Unauthenticated: run `npx medplum login` to login");console.log(`${t.project.display} (${t.project.reference})`)});oo.description("Switching to another project from the current one").argument("<projectId>").action(async(e,t)=>{let r=await U(t);await bn(r,e)});ao.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 Sn("-r, --role <role>","Role of user").choices(["Practitioner","Patient","RelatedPerson"]).default("Practitioner")).action(async(e,t,r,o)=>{let a=await U(o),i=a.getActiveLogin();if(!i)throw new Error("Unauthenticated: run `npx medplum login` to login");if(!i?.project?.reference)throw new Error("No current project to invite user to");let n=i.project.reference.split("/")[1],c={resourceType:o.role,firstName:e,lastName:t,email:r,sendEmail:!!o.sendEmail,admin:!!o.admin};await An(n,c,a)});io=new R("delete"),so=new R("get"),no=new R("patch"),co=new R("post"),lo=new R("put");io.argument("<url>","Resource/$id").action(async(e,t)=>{let r=await U(t);re(await r.delete(Re(r,e)))});so.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?re($n(o)):re(o)});no.arguments("<url> <body>").action(async(e,t,r)=>{let o=await U(r);re(await o.patch(Re(o,e),It(t)))});co.arguments("<url> <body>").option("--prefer-async",'Sets the Prefer header to "respond-async"').action(async(e,t,r)=>{let o=await U(r),a=r.preferAsync?{Prefer:"respond-async"}:void 0;re(await o.post(Re(o,e),It(t),void 0,{headers:a}))});lo.arguments("<url> <body>").action(async(e,t,r)=>{let o=await U(r);re(await o.put(Re(o,e),It(t)))});So.main===module&&bt().catch(e=>{console.error("Unhandled error:",et(e)),process.exit(1)})});import{normalizeErrorString as Nn}from"@medplum/core";var Pn=mo((yl,po)=>{uo();Q.main===po&&bt().catch(e=>{console.error("Unhandled error:",Nn(e)),process.exit(1)})});export default Pn();
|
|
25
25
|
//# sourceMappingURL=index.mjs.map
|