medplum 5.0.12 → 5.0.13
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 +2 -2
- 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
|
-
import{MEDPLUM_VERSION as Jo,normalizeErrorString as rt}from"@medplum/core";import{CommanderError as Zt,Option as Vo}from"commander";import Xo from"dotenv";import{ContentType as er,EMPTY as zo,isOk as qo,isUUID as Yo}from"@medplum/core";import{Option as ft}from"commander";import{MedplumClient as Qo}from"@medplum/core";import{ClientStorage as Zo}from"@medplum/core";import{existsSync as Rt,mkdirSync as es,readFileSync as ts,writeFileSync as rs}from"node:fs";import{homedir as os}from"node:os";import{resolve as Tt}from"node:path";import{ContentType as qe,encodeBase64 as Pt,OAuthSigningAlgorithm as tr}from"@medplum/core";import{Command as as}from"commander";import{Buffer as ns}from"node:buffer";import*as or from"node:util";import*as ir from"node:crypto";import*as ar from"node:util";import{KeyObject as ys}from"node:crypto";import{KeyObject as $s}from"node:crypto";import{constants as kt,KeyObject as Cs}from"node:crypto";import*as Fe from"node:crypto";import{promisify as Ds}from"node:util";import{KeyObject as Mt,createSecretKey as Dt}from"node:crypto";import{createHmac as Js,createPrivateKey as Vs,randomBytes as Xs}from"node:crypto";import{existsSync as zs,readFileSync as dr,writeFileSync as hr}from"node:fs";import{basename as mr,extname as qs,resolve as wt}from"node:path";import{isPromise as Ys}from"node:util/types";import{extract as Qs}from"tar";import{ContentType as Ne,getDisplayString as mi,MEDPLUM_CLI_CLIENT_ID as fi,normalizeErrorString as gi}from"@medplum/core";import{exec as wi}from"node:child_process";import{createServer as yi}from"node:http";import{platform as Ei}from"node:os";import{CloudFormationClient as Lr,DescribeStackResourcesCommand as Li,DescribeStacksCommand as Ci,paginateListStacks as ki}from"@aws-sdk/client-cloudformation";import{CloudFrontClient as Mi,CreateInvalidationCommand as Di}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{EMPTY as Bi,normalizeErrorString as Ki}from"@medplum/core";import Gi from"node-fetch";import{readdirSync as Ji}from"node:fs";import Vi from"node:readline";import{ACMClient as Fr,ListCertificatesCommand as ta,RequestCertificateCommand as ra}from"@aws-sdk/client-acm";import{CloudFrontClient as oa,CreatePublicKeyCommand as sa}from"@aws-sdk/client-cloudfront";import{GetCallerIdentityCommand as ia,STSClient as aa}from"@aws-sdk/client-sts";import{normalizeErrorString as na}from"@medplum/core";import{generateKeyPairSync as ca,randomUUID as jt}from"node:crypto";import{existsSync as la}from"node:fs";import{PutObjectCommand as ya}from"@aws-sdk/client-s3";import{ContentType as Y}from"@medplum/core";import Ea from"fast-glob";import Hr from"node-fetch";import{createReadStream as va,mkdtempSync as Sa,readdirSync as ba,readFileSync as Ia,rmSync as Aa,writeFileSync as $a}from"node:fs";import{tmpdir as Ra}from"node:os";import{join as Me,sep as Ta}from"node:path";import{pipeline as Pa}from"node:stream/promises";import{GetBucketPolicyCommand as _a,PutBucketPolicyCommand as Ua}from"@aws-sdk/client-s3";import{spawnSync as Va}from"node:child_process";import{EMPTY as Qa}from"@medplum/core";import{createReadStream as Za,writeFile as en}from"node:fs";import{resolve as qr}from"node:path";import{createInterface as tn}from"node:readline";import{formatHl7DateTime as nn,Hl7Message as cn}from"@medplum/core";import Le from"node:assert";import{connect as ln}from"node:net";import{Hl7Message as un,OperationOutcomeError as Ee,sleep as pn,validationError as dn}from"@medplum/core";import Kt from"iconv-lite";import{sleep as hn}from"@medplum/core";import mn from"node:net";import{readFileSync as In}from"node:fs";import{readdirSync as Tn}from"node:fs";import{homedir as Pn}from"node:os";import{resolve as Nn}from"node:path";import{Option as On}from"commander";import{convertToTransactionBundle as Mn}from"@medplum/core";var fo=Object.create,ct=Object.defineProperty,go=Object.getOwnPropertyDescriptor,wo=Object.getOwnPropertyNames,yo=Object.getPrototypeOf,Eo=Object.prototype.hasOwnProperty,vo=(e,t,r)=>t in e?ct(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,A=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),So=(e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of wo(t))!Eo.call(e,s)&&s!==r&&ct(e,s,{get:()=>t[s],enumerable:!(o=go(t,s))||o.enumerable});return e},Vt=(e,t,r)=>(r=e!=null?fo(yo(e)):{},So(t||!e||!e.__esModule?ct(r,"default",{value:e,enumerable:!0}):r,e)),B=(e,t,r)=>vo(e,typeof t!="symbol"?t+"":t,r),De=A((e,t)=>{"use strict";var r="2.0.0",o=Number.MAX_SAFE_INTEGER||9007199254740991,s=16,i=250,a=["major","premajor","minor","preminor","patch","prepatch","prerelease"];t.exports={MAX_LENGTH:256,MAX_SAFE_COMPONENT_LENGTH:s,MAX_SAFE_BUILD_LENGTH:i,MAX_SAFE_INTEGER:o,RELEASE_TYPES:a,SEMVER_SPEC_VERSION:r,FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2}}),_e=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}),be=A((e,t)=>{"use strict";var{MAX_SAFE_COMPONENT_LENGTH:r,MAX_SAFE_BUILD_LENGTH:o,MAX_LENGTH:s}=De(),i=_e();e=t.exports={};var a=e.re=[],c=e.safeRe=[],n=e.src=[],f=e.safeSrc=[],l=e.t={},u=0,d="[a-zA-Z0-9-]",m=[["\\s",1],["\\d",s],[d,o]],g=N=>{for(let[T,O]of m)N=N.split(`${T}*`).join(`${T}{0,${O}}`).split(`${T}+`).join(`${T}{1,${O}}`);return N},h=(N,T,O)=>{let j=g(T),W=u++;i(N,W,T),l[N]=W,n[W]=T,f[W]=j,a[W]=new RegExp(T,O?"g":void 0),c[W]=new RegExp(j,O?"g":void 0)};h("NUMERICIDENTIFIER","0|[1-9]\\d*"),h("NUMERICIDENTIFIERLOOSE","\\d+"),h("NONNUMERICIDENTIFIER",`\\d*[a-zA-Z-]${d}*`),h("MAINVERSION",`(${n[l.NUMERICIDENTIFIER]})\\.(${n[l.NUMERICIDENTIFIER]})\\.(${n[l.NUMERICIDENTIFIER]})`),h("MAINVERSIONLOOSE",`(${n[l.NUMERICIDENTIFIERLOOSE]})\\.(${n[l.NUMERICIDENTIFIERLOOSE]})\\.(${n[l.NUMERICIDENTIFIERLOOSE]})`),h("PRERELEASEIDENTIFIER",`(?:${n[l.NONNUMERICIDENTIFIER]}|${n[l.NUMERICIDENTIFIER]})`),h("PRERELEASEIDENTIFIERLOOSE",`(?:${n[l.NONNUMERICIDENTIFIER]}|${n[l.NUMERICIDENTIFIERLOOSE]})`),h("PRERELEASE",`(?:-(${n[l.PRERELEASEIDENTIFIER]}(?:\\.${n[l.PRERELEASEIDENTIFIER]})*))`),h("PRERELEASELOOSE",`(?:-?(${n[l.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${n[l.PRERELEASEIDENTIFIERLOOSE]})*))`),h("BUILDIDENTIFIER",`${d}+`),h("BUILD",`(?:\\+(${n[l.BUILDIDENTIFIER]}(?:\\.${n[l.BUILDIDENTIFIER]})*))`),h("FULLPLAIN",`v?${n[l.MAINVERSION]}${n[l.PRERELEASE]}?${n[l.BUILD]}?`),h("FULL",`^${n[l.FULLPLAIN]}$`),h("LOOSEPLAIN",`[v=\\s]*${n[l.MAINVERSIONLOOSE]}${n[l.PRERELEASELOOSE]}?${n[l.BUILD]}?`),h("LOOSE",`^${n[l.LOOSEPLAIN]}$`),h("GTLT","((?:<|>)?=?)"),h("XRANGEIDENTIFIERLOOSE",`${n[l.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`),h("XRANGEIDENTIFIER",`${n[l.NUMERICIDENTIFIER]}|x|X|\\*`),h("XRANGEPLAIN",`[v=\\s]*(${n[l.XRANGEIDENTIFIER]})(?:\\.(${n[l.XRANGEIDENTIFIER]})(?:\\.(${n[l.XRANGEIDENTIFIER]})(?:${n[l.PRERELEASE]})?${n[l.BUILD]}?)?)?`),h("XRANGEPLAINLOOSE",`[v=\\s]*(${n[l.XRANGEIDENTIFIERLOOSE]})(?:\\.(${n[l.XRANGEIDENTIFIERLOOSE]})(?:\\.(${n[l.XRANGEIDENTIFIERLOOSE]})(?:${n[l.PRERELEASELOOSE]})?${n[l.BUILD]}?)?)?`),h("XRANGE",`^${n[l.GTLT]}\\s*${n[l.XRANGEPLAIN]}$`),h("XRANGELOOSE",`^${n[l.GTLT]}\\s*${n[l.XRANGEPLAINLOOSE]}$`),h("COERCEPLAIN",`(^|[^\\d])(\\d{1,${r}})(?:\\.(\\d{1,${r}}))?(?:\\.(\\d{1,${r}}))?`),h("COERCE",`${n[l.COERCEPLAIN]}(?:$|[^\\d])`),h("COERCEFULL",n[l.COERCEPLAIN]+`(?:${n[l.PRERELEASE]})?(?:${n[l.BUILD]})?(?:$|[^\\d])`),h("COERCERTL",n[l.COERCE],!0),h("COERCERTLFULL",n[l.COERCEFULL],!0),h("LONETILDE","(?:~>?)"),h("TILDETRIM",`(\\s*)${n[l.LONETILDE]}\\s+`,!0),e.tildeTrimReplace="$1~",h("TILDE",`^${n[l.LONETILDE]}${n[l.XRANGEPLAIN]}$`),h("TILDELOOSE",`^${n[l.LONETILDE]}${n[l.XRANGEPLAINLOOSE]}$`),h("LONECARET","(?:\\^)"),h("CARETTRIM",`(\\s*)${n[l.LONECARET]}\\s+`,!0),e.caretTrimReplace="$1^",h("CARET",`^${n[l.LONECARET]}${n[l.XRANGEPLAIN]}$`),h("CARETLOOSE",`^${n[l.LONECARET]}${n[l.XRANGEPLAINLOOSE]}$`),h("COMPARATORLOOSE",`^${n[l.GTLT]}\\s*(${n[l.LOOSEPLAIN]})$|^$`),h("COMPARATOR",`^${n[l.GTLT]}\\s*(${n[l.FULLPLAIN]})$|^$`),h("COMPARATORTRIM",`(\\s*)${n[l.GTLT]}\\s*(${n[l.LOOSEPLAIN]}|${n[l.XRANGEPLAIN]})`,!0),e.comparatorTrimReplace="$1$2$3",h("HYPHENRANGE",`^\\s*(${n[l.XRANGEPLAIN]})\\s+-\\s+(${n[l.XRANGEPLAIN]})\\s*$`),h("HYPHENRANGELOOSE",`^\\s*(${n[l.XRANGEPLAINLOOSE]})\\s+-\\s+(${n[l.XRANGEPLAINLOOSE]})\\s*$`),h("STAR","(<|>)?=?\\s*\\*"),h("GTE0","^\\s*>=\\s*0\\.0\\.0\\s*$"),h("GTE0PRE","^\\s*>=\\s*0\\.0\\.0-0\\s*$")}),lt=A((e,t)=>{"use strict";var r=Object.freeze({loose:!0}),o=Object.freeze({}),s=i=>i?typeof i!="object"?r:i:o;t.exports=s}),Xt=A((e,t)=>{"use strict";var r=/^[0-9]+$/,o=(i,a)=>{if(typeof i=="number"&&typeof a=="number")return i===a?0:i<a?-1:1;let c=r.test(i),n=r.test(a);return c&&n&&(i=+i,a=+a),i===a?0:c&&!n?-1:n&&!c?1:i<a?-1:1},s=(i,a)=>o(a,i);t.exports={compareIdentifiers:o,rcompareIdentifiers:s}}),G=A((e,t)=>{"use strict";var r=_e(),{MAX_LENGTH:o,MAX_SAFE_INTEGER:s}=De(),{safeRe:i,t:a}=be(),c=lt(),{compareIdentifiers:n}=Xt(),f=class Q{constructor(u,d){if(d=c(d),u instanceof Q){if(u.loose===!!d.loose&&u.includePrerelease===!!d.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,d),this.options=d,this.loose=!!d.loose,this.includePrerelease=!!d.includePrerelease;let m=u.trim().match(d.loose?i[a.LOOSE]:i[a.FULL]);if(!m)throw new TypeError(`Invalid Version: ${u}`);if(this.raw=u,this.major=+m[1],this.minor=+m[2],this.patch=+m[3],this.major>s||this.major<0)throw new TypeError("Invalid major version");if(this.minor>s||this.minor<0)throw new TypeError("Invalid minor version");if(this.patch>s||this.patch<0)throw new TypeError("Invalid patch version");m[4]?this.prerelease=m[4].split(".").map(g=>{if(/^[0-9]+$/.test(g)){let h=+g;if(h>=0&&h<s)return h}return g}):this.prerelease=[],this.build=m[5]?m[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 Q)){if(typeof u=="string"&&u===this.version)return 0;u=new Q(u,this.options)}return u.version===this.version?0:this.compareMain(u)||this.comparePre(u)}compareMain(u){return u instanceof Q||(u=new Q(u,this.options)),this.major<u.major?-1:this.major>u.major?1:this.minor<u.minor?-1:this.minor>u.minor?1:this.patch<u.patch?-1:this.patch>u.patch?1:0}comparePre(u){if(u instanceof Q||(u=new Q(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 d=0;do{let m=this.prerelease[d],g=u.prerelease[d];if(r("prerelease compare",d,m,g),m===void 0&&g===void 0)return 0;if(g===void 0)return 1;if(m===void 0)return-1;if(m!==g)return n(m,g)}while(++d)}compareBuild(u){u instanceof Q||(u=new Q(u,this.options));let d=0;do{let m=this.build[d],g=u.build[d];if(r("build compare",d,m,g),m===void 0&&g===void 0)return 0;if(g===void 0)return 1;if(m===void 0)return-1;if(m!==g)return n(m,g)}while(++d)}inc(u,d,m){if(u.startsWith("pre")){if(!d&&m===!1)throw new Error("invalid increment argument: identifier is empty");if(d){let g=`-${d}`.match(this.options.loose?i[a.PRERELEASELOOSE]:i[a.PRERELEASE]);if(!g||g[1]!==d)throw new Error(`invalid identifier: ${d}`)}}switch(u){case"premajor":this.prerelease.length=0,this.patch=0,this.minor=0,this.major++,this.inc("pre",d,m);break;case"preminor":this.prerelease.length=0,this.patch=0,this.minor++,this.inc("pre",d,m);break;case"prepatch":this.prerelease.length=0,this.inc("patch",d,m),this.inc("pre",d,m);break;case"prerelease":this.prerelease.length===0&&this.inc("patch",d,m),this.inc("pre",d,m);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(m)?1:0;if(this.prerelease.length===0)this.prerelease=[g];else{let h=this.prerelease.length;for(;--h>=0;)typeof this.prerelease[h]=="number"&&(this.prerelease[h]++,h=-2);if(h===-1){if(d===this.prerelease.join(".")&&m===!1)throw new Error("invalid increment argument: identifier already exists");this.prerelease.push(g)}}if(d){let h=[d,g];m===!1&&(h=[d]),n(this.prerelease[0],d)===0?isNaN(this.prerelease[1])&&(this.prerelease=h):this.prerelease=h}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}),ue=A((e,t)=>{"use strict";var r=G(),o=(s,i,a=!1)=>{if(s instanceof r)return s;try{return new r(s,i)}catch(c){if(!a)return null;throw c}};t.exports=o}),bo=A((e,t)=>{"use strict";var r=ue(),o=(s,i)=>{let a=r(s,i);return a?a.version:null};t.exports=o}),Io=A((e,t)=>{"use strict";var r=ue(),o=(s,i)=>{let a=r(s.trim().replace(/^[=v]+/,""),i);return a?a.version:null};t.exports=o}),Ao=A((e,t)=>{"use strict";var r=G(),o=(s,i,a,c,n)=>{typeof a=="string"&&(n=c,c=a,a=void 0);try{return new r(s instanceof r?s.version:s,a).inc(i,c,n).version}catch{return null}};t.exports=o}),$o=A((e,t)=>{"use strict";var r=ue(),o=(s,i)=>{let a=r(s,null,!0),c=r(i,null,!0),n=a.compare(c);if(n===0)return null;let f=n>0,l=f?a:c,u=f?c:a,d=!!l.prerelease.length;if(u.prerelease.length&&!d){if(!u.patch&&!u.minor)return"major";if(u.compareMain(l)===0)return u.minor&&!u.patch?"minor":"patch"}let m=d?"pre":"";return a.major!==c.major?m+"major":a.minor!==c.minor?m+"minor":a.patch!==c.patch?m+"patch":"prerelease"};t.exports=o}),Ro=A((e,t)=>{"use strict";var r=G(),o=(s,i)=>new r(s,i).major;t.exports=o}),To=A((e,t)=>{"use strict";var r=G(),o=(s,i)=>new r(s,i).minor;t.exports=o}),Po=A((e,t)=>{"use strict";var r=G(),o=(s,i)=>new r(s,i).patch;t.exports=o}),No=A((e,t)=>{"use strict";var r=ue(),o=(s,i)=>{let a=r(s,i);return a&&a.prerelease.length?a.prerelease:null};t.exports=o}),X=A((e,t)=>{"use strict";var r=G(),o=(s,i,a)=>new r(s,a).compare(new r(i,a));t.exports=o}),Oo=A((e,t)=>{"use strict";var r=X(),o=(s,i,a)=>r(i,s,a);t.exports=o}),Lo=A((e,t)=>{"use strict";var r=X(),o=(s,i)=>r(s,i,!0);t.exports=o}),ut=A((e,t)=>{"use strict";var r=G(),o=(s,i,a)=>{let c=new r(s,a),n=new r(i,a);return c.compare(n)||c.compareBuild(n)};t.exports=o}),Co=A((e,t)=>{"use strict";var r=ut(),o=(s,i)=>s.sort((a,c)=>r(a,c,i));t.exports=o}),ko=A((e,t)=>{"use strict";var r=ut(),o=(s,i)=>s.sort((a,c)=>r(c,a,i));t.exports=o}),Ue=A((e,t)=>{"use strict";var r=X(),o=(s,i,a)=>r(s,i,a)>0;t.exports=o}),pt=A((e,t)=>{"use strict";var r=X(),o=(s,i,a)=>r(s,i,a)<0;t.exports=o}),zt=A((e,t)=>{"use strict";var r=X(),o=(s,i,a)=>r(s,i,a)===0;t.exports=o}),qt=A((e,t)=>{"use strict";var r=X(),o=(s,i,a)=>r(s,i,a)!==0;t.exports=o}),dt=A((e,t)=>{"use strict";var r=X(),o=(s,i,a)=>r(s,i,a)>=0;t.exports=o}),ht=A((e,t)=>{"use strict";var r=X(),o=(s,i,a)=>r(s,i,a)<=0;t.exports=o}),Yt=A((e,t)=>{"use strict";var r=zt(),o=qt(),s=Ue(),i=dt(),a=pt(),c=ht(),n=(f,l,u,d)=>{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,d);case"!=":return o(f,u,d);case">":return s(f,u,d);case">=":return i(f,u,d);case"<":return a(f,u,d);case"<=":return c(f,u,d);default:throw new TypeError(`Invalid operator: ${l}`)}};t.exports=n}),Mo=A((e,t)=>{"use strict";var r=G(),o=ue(),{safeRe:s,t:i}=be(),a=(c,n)=>{if(c instanceof r)return c;if(typeof c=="number"&&(c=String(c)),typeof c!="string")return null;n=n||{};let f=null;if(!n.rtl)f=c.match(n.includePrerelease?s[i.COERCEFULL]:s[i.COERCE]);else{let h=n.includePrerelease?s[i.COERCERTLFULL]:s[i.COERCERTL],N;for(;(N=h.exec(c))&&(!f||f.index+f[0].length!==c.length);)(!f||N.index+N[0].length!==f.index+f[0].length)&&(f=N),h.lastIndex=N.index+N[1].length+N[2].length;h.lastIndex=-1}if(f===null)return null;let l=f[2],u=f[3]||"0",d=f[4]||"0",m=n.includePrerelease&&f[5]?`-${f[5]}`:"",g=n.includePrerelease&&f[6]?`+${f[6]}`:"";return o(`${l}.${u}.${d}${m}${g}`,n)};t.exports=a}),Do=A((e,t)=>{"use strict";var r=class{constructor(){this.max=1e3,this.map=new Map}get(o){let s=this.map.get(o);if(s!==void 0)return this.map.delete(o),this.map.set(o,s),s}delete(o){return this.map.delete(o)}set(o,s){if(!this.delete(o)&&s!==void 0){if(this.map.size>=this.max){let i=this.map.keys().next().value;this.delete(i)}this.map.set(o,s)}return this}};t.exports=r}),z=A((e,t)=>{"use strict";var r=/\s+/g,o=class Ce{constructor(w,S){if(S=a(S),w instanceof Ce)return w.loose===!!S.loose&&w.includePrerelease===!!S.includePrerelease?w:new Ce(w.raw,S);if(w instanceof c)return this.raw=w.value,this.set=[[w]],this.formatted=void 0,this;if(this.options=S,this.loose=!!S.loose,this.includePrerelease=!!S.includePrerelease,this.raw=w.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(b=>!T(b[0])),this.set.length===0)this.set=[E];else if(this.set.length>1){for(let b of this.set)if(b.length===1&&O(b[0])){this.set=[b];break}}}this.formatted=void 0}get range(){if(this.formatted===void 0){this.formatted="";for(let w=0;w<this.set.length;w++){w>0&&(this.formatted+="||");let S=this.set[w];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(w){let S=((this.options.includePrerelease&&h)|(this.options.loose&&N))+":"+w,E=i.get(S);if(E)return E;let b=this.options.loose,v=b?l[u.HYPHENRANGELOOSE]:l[u.HYPHENRANGE];w=w.replace(v,Xe(this.options.includePrerelease)),n("hyphen replace",w),w=w.replace(l[u.COMPARATORTRIM],d),n("comparator trim",w),w=w.replace(l[u.TILDETRIM],m),n("tilde trim",w),w=w.replace(l[u.CARETTRIM],g),n("caret trim",w);let I=w.split(" ").map(D=>W(D,this.options)).join(" ").split(/\s+/).map(D=>Ve(D,this.options));b&&(I=I.filter(D=>(n("loose invalid filter",D,this.options),!!D.match(l[u.COMPARATORLOOSE])))),n("range list",I);let C=new Map,L=I.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 M=[...C.values()];return i.set(S,M),M}intersects(w,S){if(!(w instanceof Ce))throw new TypeError("a Range is required");return this.set.some(E=>j(E,S)&&w.set.some(b=>j(b,S)&&E.every(v=>b.every(I=>v.intersects(I,S)))))}test(w){if(!w)return!1;if(typeof w=="string")try{w=new f(w,this.options)}catch{return!1}for(let S=0;S<this.set.length;S++)if(ze(this.set[S],w,this.options))return!0;return!1}};t.exports=o;var s=Do(),i=new s,a=lt(),c=xe(),n=_e(),f=G(),{safeRe:l,t:u,comparatorTrimReplace:d,tildeTrimReplace:m,caretTrimReplace:g}=be(),{FLAG_INCLUDE_PRERELEASE:h,FLAG_LOOSE:N}=De(),T=y=>y.value==="<0.0.0-0",O=y=>y.value==="",j=(y,w)=>{let S=!0,E=y.slice(),b=E.pop();for(;S&&E.length;)S=E.every(v=>b.intersects(v,w)),b=E.pop();return S},W=(y,w)=>(y=y.replace(l[u.BUILD],""),n("comp",y,w),y=U(y,w),n("caret",y),y=Z(y,w),n("tildes",y),y=$(y,w),n("xrange",y),y=Je(y,w),n("stars",y),y),_=y=>!y||y.toLowerCase()==="x"||y==="*",Z=(y,w)=>y.trim().split(/\s+/).map(S=>J(S,w)).join(" "),J=(y,w)=>{let S=w.loose?l[u.TILDELOOSE]:l[u.TILDE];return y.replace(S,(E,b,v,I,C)=>{n("tilde",y,E,b,v,I,C);let L;return _(b)?L="":_(v)?L=`>=${b}.0.0 <${+b+1}.0.0-0`:_(I)?L=`>=${b}.${v}.0 <${b}.${+v+1}.0-0`:C?(n("replaceTilde pr",C),L=`>=${b}.${v}.${I}-${C} <${b}.${+v+1}.0-0`):L=`>=${b}.${v}.${I} <${b}.${+v+1}.0-0`,n("tilde return",L),L})},U=(y,w)=>y.trim().split(/\s+/).map(S=>H(S,w)).join(" "),H=(y,w)=>{n("caret",y,w);let S=w.loose?l[u.CARETLOOSE]:l[u.CARET],E=w.includePrerelease?"-0":"";return y.replace(S,(b,v,I,C,L)=>{n("caret",y,b,v,I,C,L);let M;return _(v)?M="":_(I)?M=`>=${v}.0.0${E} <${+v+1}.0.0-0`:_(C)?v==="0"?M=`>=${v}.${I}.0${E} <${v}.${+I+1}.0-0`:M=`>=${v}.${I}.0${E} <${+v+1}.0.0-0`:L?(n("replaceCaret pr",L),v==="0"?I==="0"?M=`>=${v}.${I}.${C}-${L} <${v}.${I}.${+C+1}-0`:M=`>=${v}.${I}.${C}-${L} <${v}.${+I+1}.0-0`:M=`>=${v}.${I}.${C}-${L} <${+v+1}.0.0-0`):(n("no pr"),v==="0"?I==="0"?M=`>=${v}.${I}.${C}${E} <${v}.${I}.${+C+1}-0`:M=`>=${v}.${I}.${C}${E} <${v}.${+I+1}.0-0`:M=`>=${v}.${I}.${C} <${+v+1}.0.0-0`),n("caret return",M),M})},$=(y,w)=>(n("replaceXRanges",y,w),y.split(/\s+/).map(S=>me(S,w)).join(" ")),me=(y,w)=>{y=y.trim();let S=w.loose?l[u.XRANGELOOSE]:l[u.XRANGE];return y.replace(S,(E,b,v,I,C,L)=>{n("xRange",y,E,b,v,I,C,L);let M=_(v),D=M||_(I),se=D||_(C),fe=se;return b==="="&&fe&&(b=""),L=w.includePrerelease?"-0":"",M?b===">"||b==="<"?E="<0.0.0-0":E="*":b&&fe?(D&&(I=0),C=0,b===">"?(b=">=",D?(v=+v+1,I=0,C=0):(I=+I+1,C=0)):b==="<="&&(b="<",D?v=+v+1:I=+I+1),b==="<"&&(L="-0"),E=`${b+v}.${I}.${C}${L}`):D?E=`>=${v}.0.0${L} <${+v+1}.0.0-0`:se&&(E=`>=${v}.${I}.0${L} <${v}.${+I+1}.0-0`),n("xRange return",E),E})},Je=(y,w)=>(n("replaceStars",y,w),y.trim().replace(l[u.STAR],"")),Ve=(y,w)=>(n("replaceGTE0",y,w),y.trim().replace(l[w.includePrerelease?u.GTE0PRE:u.GTE0],"")),Xe=y=>(w,S,E,b,v,I,C,L,M,D,se,fe)=>(_(E)?S="":_(b)?S=`>=${E}.0.0${y?"-0":""}`:_(v)?S=`>=${E}.${b}.0${y?"-0":""}`:I?S=`>=${S}`:S=`>=${S}${y?"-0":""}`,_(M)?L="":_(D)?L=`<${+M+1}.0.0-0`:_(se)?L=`<${M}.${+D+1}.0-0`:fe?L=`<=${M}.${D}.${se}-${fe}`:y?L=`<${M}.${D}.${+se+1}-0`:L=`<=${L}`,`${S} ${L}`.trim()),ze=(y,w,S)=>{for(let E=0;E<y.length;E++)if(!y[E].test(w))return!1;if(w.prerelease.length&&!S.includePrerelease){for(let E=0;E<y.length;E++)if(n(y[E].semver),y[E].semver!==c.ANY&&y[E].semver.prerelease.length>0){let b=y[E].semver;if(b.major===w.major&&b.minor===w.minor&&b.patch===w.patch)return!0}return!1}return!0}}),xe=A((e,t)=>{"use strict";var r=Symbol("SemVer ANY"),o=class tt{static get ANY(){return r}constructor(d,m){if(m=s(m),d instanceof tt){if(d.loose===!!m.loose)return d;d=d.value}d=d.trim().split(/\s+/).join(" "),n("comparator",d,m),this.options=m,this.loose=!!m.loose,this.parse(d),this.semver===r?this.value="":this.value=this.operator+this.semver.version,n("comp",this)}parse(d){let m=this.options.loose?i[a.COMPARATORLOOSE]:i[a.COMPARATOR],g=d.match(m);if(!g)throw new TypeError(`Invalid comparator: ${d}`);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(d){if(n("Comparator.test",d,this.options.loose),this.semver===r||d===r)return!0;if(typeof d=="string")try{d=new f(d,this.options)}catch{return!1}return c(d,this.operator,this.semver,this.options)}intersects(d,m){if(!(d instanceof tt))throw new TypeError("a Comparator is required");return this.operator===""?this.value===""?!0:new l(d.value,m).test(this.value):d.operator===""?d.value===""?!0:new l(this.value,m).test(d.semver):(m=s(m),m.includePrerelease&&(this.value==="<0.0.0-0"||d.value==="<0.0.0-0")||!m.includePrerelease&&(this.value.startsWith("<0.0.0")||d.value.startsWith("<0.0.0"))?!1:!!(this.operator.startsWith(">")&&d.operator.startsWith(">")||this.operator.startsWith("<")&&d.operator.startsWith("<")||this.semver.version===d.semver.version&&this.operator.includes("=")&&d.operator.includes("=")||c(this.semver,"<",d.semver,m)&&this.operator.startsWith(">")&&d.operator.startsWith("<")||c(this.semver,">",d.semver,m)&&this.operator.startsWith("<")&&d.operator.startsWith(">")))}};t.exports=o;var s=lt(),{safeRe:i,t:a}=be(),c=Yt(),n=_e(),f=G(),l=z()}),je=A((e,t)=>{"use strict";var r=z(),o=(s,i,a)=>{try{i=new r(i,a)}catch{return!1}return i.test(s)};t.exports=o}),_o=A((e,t)=>{"use strict";var r=z(),o=(s,i)=>new r(s,i).set.map(a=>a.map(c=>c.value).join(" ").trim().split(" "));t.exports=o}),Uo=A((e,t)=>{"use strict";var r=G(),o=z(),s=(i,a,c)=>{let n=null,f=null,l=null;try{l=new o(a,c)}catch{return null}return i.forEach(u=>{l.test(u)&&(!n||f.compare(u)===-1)&&(n=u,f=new r(n,c))}),n};t.exports=s}),xo=A((e,t)=>{"use strict";var r=G(),o=z(),s=(i,a,c)=>{let n=null,f=null,l=null;try{l=new o(a,c)}catch{return null}return i.forEach(u=>{l.test(u)&&(!n||f.compare(u)===1)&&(n=u,f=new r(n,c))}),n};t.exports=s}),jo=A((e,t)=>{"use strict";var r=G(),o=z(),s=Ue(),i=(a,c)=>{a=new o(a,c);let n=new r("0.0.0");if(a.test(n)||(n=new r("0.0.0-0"),a.test(n)))return n;n=null;for(let f=0;f<a.set.length;++f){let l=a.set[f],u=null;l.forEach(d=>{let m=new r(d.semver.version);switch(d.operator){case">":m.prerelease.length===0?m.patch++:m.prerelease.push(0),m.raw=m.format();case"":case">=":(!u||s(m,u))&&(u=m);break;case"<":case"<=":break;default:throw new Error(`Unexpected operation: ${d.operator}`)}}),u&&(!n||s(n,u))&&(n=u)}return n&&a.test(n)?n:null};t.exports=i}),Fo=A((e,t)=>{"use strict";var r=z(),o=(s,i)=>{try{return new r(s,i).range||"*"}catch{return null}};t.exports=o}),mt=A((e,t)=>{"use strict";var r=G(),o=xe(),{ANY:s}=o,i=z(),a=je(),c=Ue(),n=pt(),f=ht(),l=dt(),u=(d,m,g,h)=>{d=new r(d,h),m=new i(m,h);let N,T,O,j,W;switch(g){case">":N=c,T=f,O=n,j=">",W=">=";break;case"<":N=n,T=l,O=c,j="<",W="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if(a(d,m,h))return!1;for(let _=0;_<m.set.length;++_){let Z=m.set[_],J=null,U=null;if(Z.forEach(H=>{H.semver===s&&(H=new o(">=0.0.0")),J=J||H,U=U||H,N(H.semver,J.semver,h)?J=H:O(H.semver,U.semver,h)&&(U=H)}),J.operator===j||J.operator===W||(!U.operator||U.operator===j)&&T(d,U.semver)||U.operator===W&&O(d,U.semver))return!1}return!0};t.exports=u}),Wo=A((e,t)=>{"use strict";var r=mt(),o=(s,i,a)=>r(s,i,">",a);t.exports=o}),Ho=A((e,t)=>{"use strict";var r=mt(),o=(s,i,a)=>r(s,i,"<",a);t.exports=o}),Bo=A((e,t)=>{"use strict";var r=z(),o=(s,i,a)=>(s=new r(s,a),i=new r(i,a),s.intersects(i,a));t.exports=o}),Ko=A((e,t)=>{"use strict";var r=je(),o=X();t.exports=(s,i,a)=>{let c=[],n=null,f=null,l=s.sort((g,h)=>o(g,h,a));for(let g of l)r(g,i,a)?(f=g,n||(n=g)):(f&&c.push([n,f]),f=null,n=null);n&&c.push([n,null]);let u=[];for(let[g,h]of c)g===h?u.push(g):!h&&g===l[0]?u.push("*"):h?g===l[0]?u.push(`<=${h}`):u.push(`${g} - ${h}`):u.push(`>=${g}`);let d=u.join(" || "),m=typeof i.raw=="string"?i.raw:String(i);return d.length<m.length?d:i}}),Go=A((e,t)=>{"use strict";var r=z(),o=xe(),{ANY:s}=o,i=je(),a=X(),c=(m,g,h={})=>{if(m===g)return!0;m=new r(m,h),g=new r(g,h);let N=!1;e:for(let T of m.set){for(let O of g.set){let j=l(T,O,h);if(N=N||j!==null,j)continue e}if(N)return!1}return!0},n=[new o(">=0.0.0-0")],f=[new o(">=0.0.0")],l=(m,g,h)=>{if(m===g)return!0;if(m.length===1&&m[0].semver===s){if(g.length===1&&g[0].semver===s)return!0;h.includePrerelease?m=n:m=f}if(g.length===1&&g[0].semver===s){if(h.includePrerelease)return!0;g=f}let N=new Set,T,O;for(let $ of m)$.operator===">"||$.operator===">="?T=u(T,$,h):$.operator==="<"||$.operator==="<="?O=d(O,$,h):N.add($.semver);if(N.size>1)return null;let j;if(T&&O&&(j=a(T.semver,O.semver,h),j>0||j===0&&(T.operator!==">="||O.operator!=="<=")))return null;for(let $ of N){if(T&&!i($,String(T),h)||O&&!i($,String(O),h))return null;for(let me of g)if(!i($,String(me),h))return!1;return!0}let W,_,Z,J,U=O&&!h.includePrerelease&&O.semver.prerelease.length?O.semver:!1,H=T&&!h.includePrerelease&&T.semver.prerelease.length?T.semver:!1;U&&U.prerelease.length===1&&O.operator==="<"&&U.prerelease[0]===0&&(U=!1);for(let $ of g){if(J=J||$.operator===">"||$.operator===">=",Z=Z||$.operator==="<"||$.operator==="<=",T){if(H&&$.semver.prerelease&&$.semver.prerelease.length&&$.semver.major===H.major&&$.semver.minor===H.minor&&$.semver.patch===H.patch&&(H=!1),$.operator===">"||$.operator===">="){if(W=u(T,$,h),W===$&&W!==T)return!1}else if(T.operator===">="&&!i(T.semver,String($),h))return!1}if(O){if(U&&$.semver.prerelease&&$.semver.prerelease.length&&$.semver.major===U.major&&$.semver.minor===U.minor&&$.semver.patch===U.patch&&(U=!1),$.operator==="<"||$.operator==="<="){if(_=d(O,$,h),_===$&&_!==O)return!1}else if(O.operator==="<="&&!i(O.semver,String($),h))return!1}if(!$.operator&&(O||T)&&j!==0)return!1}return!(T&&Z&&!O&&j!==0||O&&J&&!T&&j!==0||H||U)},u=(m,g,h)=>{if(!m)return g;let N=a(m.semver,g.semver,h);return N>0?m:N<0||g.operator===">"&&m.operator===">="?g:m},d=(m,g,h)=>{if(!m)return g;let N=a(m.semver,g.semver,h);return N<0?m:N>0||g.operator==="<"&&m.operator==="<="?g:m};t.exports=c}),Qt=A((e,t)=>{"use strict";var r=be(),o=De(),s=G(),i=Xt(),a=ue(),c=bo(),n=Io(),f=Ao(),l=$o(),u=Ro(),d=To(),m=Po(),g=No(),h=X(),N=Oo(),T=Lo(),O=ut(),j=Co(),W=ko(),_=Ue(),Z=pt(),J=zt(),U=qt(),H=dt(),$=ht(),me=Yt(),Je=Mo(),Ve=xe(),Xe=z(),ze=je(),y=_o(),w=Uo(),S=xo(),E=jo(),b=Fo(),v=mt(),I=Wo(),C=Ho(),L=Bo(),M=Ko(),D=Go();t.exports={parse:a,valid:c,clean:n,inc:f,diff:l,major:u,minor:d,patch:m,prerelease:g,compare:h,rcompare:N,compareLoose:T,compareBuild:O,sort:j,rsort:W,gt:_,lt:Z,eq:J,neq:U,gte:H,lte:$,cmp:me,coerce:Je,Comparator:Ve,Range:Xe,satisfies:ze,toComparators:y,maxSatisfying:w,minSatisfying:S,minVersion:E,validRange:b,outside:v,gtr:I,ltr:C,intersects:L,simplifyRange:M,subset:D,SemVer:s,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}}),Ie=class extends Zo{constructor(e){super(),B(this,"dirName"),B(this,"fileName"),this.dirName=Tt(os(),".medplum"),this.fileName=Tt(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(Rt(this.fileName))return JSON.parse(ts(this.fileName,"utf8"))}writeFile(e){Rt(this.dirName)||es(this.dirName),rs(this.fileName,JSON.stringify(e,null,2),"utf8")}};async function x(e,t=!0){let r=e.profile??"default",o=new Ie(r),s=o.getObject("options");if(r!=="default"&&!s)throw new Error(`Profile "${r}" does not exist`);let{baseUrl:i,fhirUrlPath:a,accessToken:c,tokenUrl:n,authorizeUrl:f,clientId:l,clientSecret:u}=ss(e,o),d=e.fetch??fetch,m=new Qo({fetch:d,baseUrl:i,tokenUrl:n,fhirUrlPath:a,authorizeUrl:f,storage:o,onUnauthenticated:is,verbose:e.verbose});return t&&(c?m.setAccessToken(c):l&&u&&(m.setBasicAuth(l,u),s?.authType!=="basic"&&await m.startClientLogin(l,u))),m}function ss(e,t){let r=t.getObject("options"),o=e.baseUrl??r?.baseUrl??process.env.MEDPLUM_BASE_URL??"https://api.medplum.com/",s=e.fhirUrlPath??r?.fhirUrlPath??process.env.MEDPLUM_FHIR_URL_PATH,i=e.accessToken??r?.accessToken??process.env.MEDPLUM_CLIENT_ACCESS_TOKEN,a=e.tokenUrl??r?.tokenUrl??process.env.MEDPLUM_TOKEN_URL,c=e.authorizeUrl??r?.authorizeUrl??process.env.MEDPLUM_AUTHORIZE_URL,n=e.clientId??r?.clientId??process.env.MEDPLUM_CLIENT_ID,f=e.clientSecret??r?.clientSecret??process.env.MEDPLUM_CLIENT_SECRET;return{baseUrl:o,fhirUrlPath:s,accessToken:i,tokenUrl:a,authorizeUrl:c,clientId:n,clientSecret:f}}function is(){console.log("Unauthenticated: run `npx medplum login` to sign in")}var ve=new TextEncoder,Nt=new TextDecoder,Yn=2**32;function cs(...e){let t=e.reduce((s,{length:i})=>s+i,0),r=new Uint8Array(t),o=0;for(let s of e)r.set(s,o),o+=s.length;return r}var Ye=e=>ns.from(e).toString("base64url"),Ae=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(Ae,"code","ERR_JOSE_GENERIC");var pe=class extends Ae{constructor(){super(...arguments),B(this,"code","ERR_JOSE_NOT_SUPPORTED")}};B(pe,"code","ERR_JOSE_NOT_SUPPORTED");var ie=class extends Ae{constructor(){super(...arguments),B(this,"code","ERR_JWS_INVALID")}};B(ie,"code","ERR_JWS_INVALID");var rr=class extends Ae{constructor(){super(...arguments),B(this,"code","ERR_JWT_INVALID")}};B(rr,"code","ERR_JWT_INVALID");var Ot,Lt,ls=class extends(Lt=Ae,Ot=Symbol.asyncIterator,Lt){constructor(e="multiple matching keys found in the JSON Web Key Set",t){super(e,t),B(this,Ot),B(this,"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS")}};B(ls,"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS");var sr=e=>or.types.isKeyObject(e),us=ir.webcrypto,ps=us,gt=e=>ar.types.isCryptoKey(e);function q(e,t="algorithm.name"){return new TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`)}function ge(e,t){return e.name===t}function Qe(e){return parseInt(e.name.slice(4),10)}function ds(e){switch(e){case"ES256":return"P-256";case"ES384":return"P-384";case"ES512":return"P-521";default:throw new Error("unreachable")}}function hs(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 ms(e,t,...r){switch(t){case"HS256":case"HS384":case"HS512":{if(!ge(e.algorithm,"HMAC"))throw q("HMAC");let o=parseInt(t.slice(2),10);if(Qe(e.algorithm.hash)!==o)throw q(`SHA-${o}`,"algorithm.hash");break}case"RS256":case"RS384":case"RS512":{if(!ge(e.algorithm,"RSASSA-PKCS1-v1_5"))throw q("RSASSA-PKCS1-v1_5");let o=parseInt(t.slice(2),10);if(Qe(e.algorithm.hash)!==o)throw q(`SHA-${o}`,"algorithm.hash");break}case"PS256":case"PS384":case"PS512":{if(!ge(e.algorithm,"RSA-PSS"))throw q("RSA-PSS");let o=parseInt(t.slice(2),10);if(Qe(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(!ge(e.algorithm,"Ed25519"))throw q("Ed25519");break}case"ES256":case"ES384":case"ES512":{if(!ge(e.algorithm,"ECDSA"))throw q("ECDSA");let o=ds(t);if(e.algorithm.namedCurve!==o)throw q(o,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}hs(e,r)}function nr(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}var ot=(e,...t)=>nr("Key must be ",e,...t);function cr(e,t,...r){return nr(`Key for the ${e} algorithm must be `,t,...r)}var lr=e=>sr(e)||gt(e),ce=["KeyObject"];(globalThis.CryptoKey||ps?.CryptoKey)&&ce.push("CryptoKey");var fs=(...e)=>{let t=e.filter(Boolean);if(t.length===0||t.length===1)return!0;let r;for(let o of t){let s=Object.keys(o);if(!r||r.size===0){r=new Set(s);continue}for(let i of s){if(r.has(i))return!1;r.add(i)}}return!0},gs=fs;function ws(e){return typeof e=="object"&&e!==null}function ur(e){if(!ws(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 $e(e){return ur(e)&&typeof e.kty=="string"}function Es(e){return e.kty!=="oct"&&typeof e.d=="string"}function vs(e){return e.kty!=="oct"&&typeof e.d>"u"}function Ss(e){return $e(e)&&e.kty==="oct"&&typeof e.k=="string"}var bs=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 pe("Unsupported key curve for this operation")}},Is=(e,t)=>{let r;if(gt(e))r=ys.from(e);else if(sr(e))r=e;else{if($e(e))return e.crv;throw new TypeError(ot(e,...ce))}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:bs(o)}default:throw new TypeError("Invalid asymmetric key type for this operation")}},As=Is,Ct=(e,t)=>{let r;try{e instanceof $s?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`)},ae=e=>e?.[Symbol.toStringTag],st=(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},Rs=(e,t,r,o)=>{if(!(t instanceof Uint8Array)){if(o&&$e(t)){if(Ss(t)&&st(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(!lr(t))throw new TypeError(cr(e,t,...ce,"Uint8Array",o?"JSON Web Key":null));if(t.type!=="secret")throw new TypeError(`${ae(t)} instances for symmetric algorithms must be of type "secret"`)}},Ts=(e,t,r,o)=>{if(o&&$e(t))switch(r){case"sign":if(Es(t)&&st(e,t,r))return;throw new TypeError("JSON Web Key for this operation be a private JWK");case"verify":if(vs(t)&&st(e,t,r))return;throw new TypeError("JSON Web Key for this operation be a public JWK")}if(!lr(t))throw new TypeError(cr(e,t,...ce,o?"JSON Web Key":null));if(t.type==="secret")throw new TypeError(`${ae(t)} instances for asymmetric algorithms must not be of type "secret"`);if(r==="sign"&&t.type==="public")throw new TypeError(`${ae(t)} instances for asymmetric algorithm signing must be of type "private"`);if(r==="decrypt"&&t.type==="public")throw new TypeError(`${ae(t)} instances for asymmetric algorithm decryption must be of type "private"`);if(t.algorithm&&r==="verify"&&t.type==="private")throw new TypeError(`${ae(t)} instances for asymmetric algorithm verifying must be of type "public"`);if(t.algorithm&&r==="encrypt"&&t.type==="private")throw new TypeError(`${ae(t)} instances for asymmetric algorithm encryption must be of type "public"`)};function pr(e,t,r,o){t.startsWith("HS")||t==="dir"||t.startsWith("PBES2")||/^A\d{3}(?:GCM)?KW$/.test(t)?Rs(t,r,o,e):Ts(t,r,o,e)}var ec=pr.bind(void 0,!1),Ps=pr.bind(void 0,!0);function Ns(e,t,r,o,s){if(s.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(a=>typeof a!="string"||a.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 a of o.crit){if(!i.has(a))throw new pe(`Extension Header Parameter "${a}" is not recognized`);if(s[a]===void 0)throw new e(`Extension Header Parameter "${a}" is missing`);if(i.get(a)&&o[a]===void 0)throw new e(`Extension Header Parameter "${a}" MUST be integrity protected`)}return new Set(o.crit)}var Os=Ns;function Ls(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 pe(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}var ks=new Map([["ES256","P-256"],["ES256K","secp256k1"],["ES384","P-384"],["ES512","P-521"]]);function Ms(e,t){let r,o,s;if(t instanceof Cs)r=t.asymmetricKeyType,o=t.asymmetricKeyDetails;else switch(s=!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");Ct(t,e);break;case"PS256":case"PS384":case"PS512":if(r==="rsa-pss"){let{hashAlgorithm:a,mgf1HashAlgorithm:c,saltLength:n}=o,f=parseInt(e.slice(-3),10);if(a!==void 0&&(a!==`sha${f}`||c!==a))throw new TypeError(`Invalid key for this operation, its RSA-PSS parameters do not meet the requirements of "alg" ${e}`);if(n!==void 0&&n>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");Ct(t,e),i={padding:kt.RSA_PKCS1_PSS_PADDING,saltLength:kt.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 a=As(t),c=ks.get(e);if(a!==c)throw new TypeError(`Invalid key curve for the algorithm, its curve must be ${c}, got ${a}`);i={dsaEncoding:"ieee-p1363"};break}default:throw new pe(`alg ${e} is not supported either by JOSE or your javascript runtime`)}return s?{format:"jwk",key:t,...i}:i?{...i,key:t}:t}function _s(e){switch(e){case"HS256":return"sha256";case"HS384":return"sha384";case"HS512":return"sha512";default:throw new pe(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}function Us(e,t,r){if(t instanceof Uint8Array){if(!e.startsWith("HS"))throw new TypeError(ot(t,...ce));return Dt(t)}if(t instanceof Mt)return t;if(gt(t))return ms(t,e,r),Mt.from(t);if($e(t))return e.startsWith("HS")?Dt(Buffer.from(t.k,"base64url")):t;throw new TypeError(ot(t,...ce,"Uint8Array","JSON Web Key"))}var xs=Ds(Fe.sign),js=async(e,t,r)=>{let o=Us(e,t,"sign");if(e.startsWith("HS")){let s=Fe.createHmac(_s(e),o);return s.update(r),s.digest()}return xs(Ls(e),r,Ms(e,o))},Fs=js,ee=e=>Math.floor(e.getTime()/1e3),Ws=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i,Ze=e=>{let t=Ws.exec(e);if(!t||t[4]&&t[1])throw new TypeError("Invalid time period format");let r=parseFloat(t[2]),o=t[3].toLowerCase(),s;switch(o){case"sec":case"secs":case"second":case"seconds":case"s":s=Math.round(r);break;case"minute":case"minutes":case"min":case"mins":case"m":s=Math.round(r*60);break;case"hour":case"hours":case"hr":case"hrs":case"h":s=Math.round(r*3600);break;case"day":case"days":case"d":s=Math.round(r*86400);break;case"week":case"weeks":case"w":s=Math.round(r*604800);break;default:s=Math.round(r*31557600);break}return t[1]==="-"||t[4]==="ago"?-s:s},Hs=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(!gs(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=Os(ie,new Map([["b64",!0]]),t?.crit,this._protectedHeader,r),s=!0;if(o.has("b64")&&(s=this._protectedHeader.b64,typeof s!="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');Ps(i,e,"sign");let a=this._payload;s&&(a=ve.encode(Ye(a)));let c;this._protectedHeader?c=ve.encode(Ye(JSON.stringify(this._protectedHeader))):c=ve.encode("");let n=cs(c,ve.encode("."),a),f=await Fs(i,e,n),l={signature:Ye(f),payload:""};return s&&(l.payload=Nt.decode(a)),this._unprotectedHeader&&(l.header=this._unprotectedHeader),this._protectedHeader&&(l.protected=Nt.decode(c)),l}},Bs=class{constructor(e){B(this,"_flattened"),this._flattened=new Hs(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}`}};function te(e,t){if(!Number.isFinite(t))throw new TypeError(`Invalid ${e} input`);return t}var Ks=class{constructor(e={}){if(B(this,"_payload"),!ur(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)+Ze(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)+Ze(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)+Ze(e))}:this._payload={...this._payload,iat:te("setIssuedAt",e)},this}},Gs=class extends Ks{constructor(){super(...arguments),B(this,"_protectedHeader")}setProtectedHeader(e){return this._protectedHeader=e,this}async sign(e,t){let r=new Bs(ve.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 rr("JWTs MUST NOT use unencoded payload");return r.sign(e,t)}};function re(e){console.log(JSON.stringify(e,null,2))}async function fr(e,t,r){let o=t.source,s=We(o);if(!s)return;console.log("Saving source code...");let i=await e.createAttachment({data:s,filename:mr(o),contentType:si(o)});console.log("Updating bot...");let a=await e.updateResource({...r,sourceCode:i});console.log("Success! New bot version: "+a.meta?.versionId)}async function gr(e,t,r){let o=t.dist??t.source,s=We(o);if(!s)return;console.log("Deploying bot...");let i=await e.post(e.fhirUrl("Bot",r.id,"$deploy"),{code:s,filename:mr(o)});console.log("Deploy result: "+i.issue?.[0]?.details?.text)}async function wr(e,t,r,o,s,i,a){let c={name:t,description:"",runtimeVersion:i},n=await e.post("admin/projects/"+r+"/bot",c),f=await e.readResource("Bot",n.id),l={name:t,id:n.id,source:o,dist:s};await fr(e,l,f),await gr(e,l,f),console.log(`Success! Bot created: ${f.id}`),a&&ti(l)}function Zs(e){let t=new RegExp("^"+ri(e).replaceAll(String.raw`\*`,".*")+"$");return de()?.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 K(e,t){hr(wt(e),JSON.stringify(t,void 0,2),"utf-8")}function de(e,t){let r=oe(e,t),o=We(r);if(o)return JSON.parse(o)}function ei(e){let t=We(oe(e,{server:!0}));if(t)return JSON.parse(t)}function We(e){let t=wt(e);return zs(t)?dr(t,"utf8"):""}function ti(e){let t=de()??{};t.bots||(t.bots=[]),t.bots.push(e),hr("medplum.config.json",JSON.stringify(t,null,2),"utf8"),console.log(`Bot added to config: ${e.id}`)}function ri(e){return e.replaceAll(/[/\-\\^$*+?.()|[\]{}]/g,"\\$&")}function oi(e){let t=0,r=0;return Qs({cwd:e,filter:(o,s)=>{if(t++,t>100)throw new Error("Tar extractor reached max number of files");if(r+=s.size,r>10485760)throw new Error("Tar extractor reached max size");return!0}})}function _t(){return{url:"http://hl7.org/fhir/StructureDefinition/data-absent-reason",valueCode:"unsupported"}}function si(e){let t=qs(e).toLowerCase();return[".cjs",".mjs",".js"].includes(t)?qe.JAVASCRIPT:[".cts",".mts",".ts"].includes(t)?qe.TYPESCRIPT:qe.TEXT}function yr(e,t){let r=new Ie(e),o={name:e,...t};return r.setObject("options",o),o}function ii(e){return new Ie(e).getObject("options")}async function ai(e,t){let r={typ:"JWT",alg:tr.HS256},o=Math.floor(Date.now()/1e3),s={aud:`${t.baseUrl}${t.audience}`,iss:t.issuer,sub:t.subject,nbf:o,iat:o,exp:o+604800},i=Pt(JSON.stringify(r)),a=Pt(JSON.stringify(s)),c=`${i}.${a}`,n=Js("sha256",t.clientSecret).update(c).digest("base64url"),f=`${c}.${n}`;await e.startJwtBearerLogin(t.clientId,f,t.scope??"")}async function ni(e,t){let r=Vs(dr(wt(t.privateKeyPath))),o=await new Gs({}).setProtectedHeader({typ:"JWT",alg:tr.RS384}).setIssuer(t.clientId).setSubject(t.clientId).setAudience(`${t.baseUrl}${t.audience}`).setJti(Xs(16).toString("hex")).setIssuedAt().setExpirationTime("5m").sign(r);await e.startJwtAssertionLogin(o)}function P(e,t){t.configureHelp({showGlobalOptions:!0}),e.addCommand(t)}var R=class extends as{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)}};function ci(e,t){return async r=>{let o=e.registeredArguments.length,s=r.slice(0,o);s[o]=e.optsWithGlobals();try{let i=t(...s);Ys(i)&&await i}finally{e.resetOptionDefaults()}}}var Er=new R("status").aliases(["info","list","ls"]),vr=new R("ping"),Sr=new R("push"),br=new R("reload-config"),Ir=new R("upgrade"),he=new R("agent");P(he,Er);P(he,vr);P(he,Sr);P(he,br);P(he,Ir);Er.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 ft("--output <format>","An optional output format, defaults to table").choices(["table","json"]).default("table")).action(async(e,t)=>{await yt({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"}}})});vr.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 x(r),s=await Ar(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 a=await o.pushToAgent(s,e,`PING ${i}`,er.PING,!0,{maxRetries:0});console.info(a)}catch(a){throw new Error("Unexpected response from agent while pinging",{cause:a})}});Sr.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",er.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 s=await x(o),i=await Ar(s,r,o),a;try{a=await s.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(a)});br.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 ft("--output <format>","An optional output format, defaults to table").choices(["table","json"]).default("table")).action(async(e,t)=>{await yt({operation:"$reload-config",agentIds:e,options:t,parseSuccessfulResponse:r=>({id:r.agent.id,name:r.agent.name})})});Ir.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("--agentVersion <version>","An optional agent version to upgrade to. Defaults to the latest version if flag not included").option("--force","Forces an upgrade when a pending upgrade is in an inconsistent state. Use with caution.").addOption(new ft("--output <format>","An optional output format, defaults to table").choices(["table","json"]).default("table")).action(async(e,t)=>{let r={};t.agentVersion&&(r.version=t.agentVersion),t.force&&(r.force=!0),await yt({operation:"$upgrade",agentIds:e,options:t,params:r,parseSuccessfulResponse:o=>({id:o.agent.id,name:o.agent.name,version:t.agentVersion??"latest"})})});async function yt({operation:e,agentIds:t,options:r,params:o={},parseSuccessfulResponse:s}){let i=hi(t,r),a=await x(r),c=i.type==="criteria"?i.criteria:`Agent?_id=${i.ids.join(",")}`,n=new URLSearchParams(c.split("?")[1]);for(let[g,h]of Object.entries(o))n.append(g,h.toString());let f;try{let g=a.fhirUrl("Agent",e);g.search=n.toString(),f=await a.get(g,{cache:"reload"})}catch(g){throw new Error(`Operation '${e}' failed`,{cause:g})}if(r.output==="json"){console.info(JSON.stringify(f,null,2));return}let l=[],u=[];switch(f.resourceType){case"Bundle":{let g=li(f);for(let h of g)h.result.resourceType==="Parameters"||qo(h.result)?l.push(h):u.push(h);break}case"Parameters":case"OperationOutcome":{let g=await a.searchOne("Agent",n,{cache:"reload"});if(!g)throw new Error("Agent not found");f.resourceType==="Parameters"?l.push({agent:g,result:f}):u.push({agent:g,result:f});break}default:throw new Error(`Invalid result received for '${e}' operation: ${JSON.stringify(f)}`)}let d=[];for(let g of l){let h=s(g);d.push(h)}let m=[];for(let g of u){let h=g.result.issue?.[0],N={id:g.agent.id,name:g.agent.name,severity:h.severity,code:h.code,details:h.details?.text??"No details to show"};m.push(N)}console.info(`
|
|
2
|
+
import{MEDPLUM_VERSION as Jo,normalizeErrorString as rt}from"@medplum/core";import{CommanderError as Zt,Option as Vo}from"commander";import Xo from"dotenv";import{ContentType as er,EMPTY as zo,isOk as qo,isUUID as Yo}from"@medplum/core";import{Option as ft}from"commander";import{MedplumClient as Qo}from"@medplum/core";import{ClientStorage as Zo}from"@medplum/core";import{existsSync as Rt,mkdirSync as es,readFileSync as ts,writeFileSync as rs}from"node:fs";import{homedir as os}from"node:os";import{resolve as Tt}from"node:path";import{ContentType as qe,encodeBase64 as Pt,OAuthSigningAlgorithm as tr}from"@medplum/core";import{Command as as}from"commander";import{Buffer as ns}from"node:buffer";import*as or from"node:util";import*as ir from"node:crypto";import*as ar from"node:util";import{KeyObject as ys}from"node:crypto";import{KeyObject as $s}from"node:crypto";import{constants as kt,KeyObject as Cs}from"node:crypto";import*as Fe from"node:crypto";import{promisify as Ds}from"node:util";import{KeyObject as Mt,createSecretKey as Dt}from"node:crypto";import{createHmac as Js,createPrivateKey as Vs,randomBytes as Xs}from"node:crypto";import{existsSync as zs,readFileSync as dr,writeFileSync as hr}from"node:fs";import{basename as mr,extname as qs,resolve as wt}from"node:path";import{isPromise as Ys}from"node:util/types";import{extract as Qs}from"tar";import{ContentType as Ne,getDisplayString as mi,MEDPLUM_CLI_CLIENT_ID as fi,normalizeErrorString as gi}from"@medplum/core";import{exec as wi}from"node:child_process";import{createServer as yi}from"node:http";import{platform as Ei}from"node:os";import{CloudFormationClient as Lr,DescribeStackResourcesCommand as Li,DescribeStacksCommand as Ci,paginateListStacks as ki}from"@aws-sdk/client-cloudformation";import{CloudFrontClient as Mi,CreateInvalidationCommand as Di}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{EMPTY as Bi,normalizeErrorString as Ki}from"@medplum/core";import Gi from"node-fetch";import{readdirSync as Ji}from"node:fs";import Vi from"node:readline";import{ACMClient as Fr,ListCertificatesCommand as ta,RequestCertificateCommand as ra}from"@aws-sdk/client-acm";import{CloudFrontClient as oa,CreatePublicKeyCommand as sa}from"@aws-sdk/client-cloudfront";import{GetCallerIdentityCommand as ia,STSClient as aa}from"@aws-sdk/client-sts";import{normalizeErrorString as na}from"@medplum/core";import{generateKeyPairSync as ca,randomUUID as jt}from"node:crypto";import{existsSync as la}from"node:fs";import{PutObjectCommand as ya}from"@aws-sdk/client-s3";import{ContentType as Y}from"@medplum/core";import Ea from"fast-glob";import Hr from"node-fetch";import{createReadStream as va,mkdtempSync as Sa,readdirSync as ba,readFileSync as Ia,rmSync as Aa,writeFileSync as $a}from"node:fs";import{tmpdir as Ra}from"node:os";import{join as Me,sep as Ta}from"node:path";import{pipeline as Pa}from"node:stream/promises";import{GetBucketPolicyCommand as _a,PutBucketPolicyCommand as Ua}from"@aws-sdk/client-s3";import{spawnSync as Va}from"node:child_process";import{EMPTY as Qa}from"@medplum/core";import{createReadStream as Za,writeFile as en}from"node:fs";import{resolve as qr}from"node:path";import{createInterface as tn}from"node:readline";import{formatHl7DateTime as nn,Hl7Message as cn}from"@medplum/core";import Le from"node:assert";import{connect as ln}from"node:net";import{Hl7Message as un,OperationOutcomeError as Ee,ReturnAckCategory as Kt,sleep as pn,validationError as dn}from"@medplum/core";import Gt from"iconv-lite";import"@medplum/core";import{sleep as hn}from"@medplum/core";import mn from"node:net";import{readFileSync as In}from"node:fs";import{readdirSync as Tn}from"node:fs";import{homedir as Pn}from"node:os";import{resolve as Nn}from"node:path";import{Option as On}from"commander";import{convertToTransactionBundle as Mn}from"@medplum/core";var fo=Object.create,ct=Object.defineProperty,go=Object.getOwnPropertyDescriptor,wo=Object.getOwnPropertyNames,yo=Object.getPrototypeOf,Eo=Object.prototype.hasOwnProperty,vo=(e,t,r)=>t in e?ct(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,A=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),So=(e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of wo(t))!Eo.call(e,s)&&s!==r&&ct(e,s,{get:()=>t[s],enumerable:!(o=go(t,s))||o.enumerable});return e},Vt=(e,t,r)=>(r=e!=null?fo(yo(e)):{},So(t||!e||!e.__esModule?ct(r,"default",{value:e,enumerable:!0}):r,e)),B=(e,t,r)=>vo(e,typeof t!="symbol"?t+"":t,r),De=A((e,t)=>{"use strict";var r="2.0.0",o=Number.MAX_SAFE_INTEGER||9007199254740991,s=16,i=250,a=["major","premajor","minor","preminor","patch","prepatch","prerelease"];t.exports={MAX_LENGTH:256,MAX_SAFE_COMPONENT_LENGTH:s,MAX_SAFE_BUILD_LENGTH:i,MAX_SAFE_INTEGER:o,RELEASE_TYPES:a,SEMVER_SPEC_VERSION:r,FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2}}),_e=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}),be=A((e,t)=>{"use strict";var{MAX_SAFE_COMPONENT_LENGTH:r,MAX_SAFE_BUILD_LENGTH:o,MAX_LENGTH:s}=De(),i=_e();e=t.exports={};var a=e.re=[],c=e.safeRe=[],n=e.src=[],f=e.safeSrc=[],l=e.t={},u=0,d="[a-zA-Z0-9-]",m=[["\\s",1],["\\d",s],[d,o]],g=N=>{for(let[T,O]of m)N=N.split(`${T}*`).join(`${T}{0,${O}}`).split(`${T}+`).join(`${T}{1,${O}}`);return N},h=(N,T,O)=>{let j=g(T),W=u++;i(N,W,T),l[N]=W,n[W]=T,f[W]=j,a[W]=new RegExp(T,O?"g":void 0),c[W]=new RegExp(j,O?"g":void 0)};h("NUMERICIDENTIFIER","0|[1-9]\\d*"),h("NUMERICIDENTIFIERLOOSE","\\d+"),h("NONNUMERICIDENTIFIER",`\\d*[a-zA-Z-]${d}*`),h("MAINVERSION",`(${n[l.NUMERICIDENTIFIER]})\\.(${n[l.NUMERICIDENTIFIER]})\\.(${n[l.NUMERICIDENTIFIER]})`),h("MAINVERSIONLOOSE",`(${n[l.NUMERICIDENTIFIERLOOSE]})\\.(${n[l.NUMERICIDENTIFIERLOOSE]})\\.(${n[l.NUMERICIDENTIFIERLOOSE]})`),h("PRERELEASEIDENTIFIER",`(?:${n[l.NONNUMERICIDENTIFIER]}|${n[l.NUMERICIDENTIFIER]})`),h("PRERELEASEIDENTIFIERLOOSE",`(?:${n[l.NONNUMERICIDENTIFIER]}|${n[l.NUMERICIDENTIFIERLOOSE]})`),h("PRERELEASE",`(?:-(${n[l.PRERELEASEIDENTIFIER]}(?:\\.${n[l.PRERELEASEIDENTIFIER]})*))`),h("PRERELEASELOOSE",`(?:-?(${n[l.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${n[l.PRERELEASEIDENTIFIERLOOSE]})*))`),h("BUILDIDENTIFIER",`${d}+`),h("BUILD",`(?:\\+(${n[l.BUILDIDENTIFIER]}(?:\\.${n[l.BUILDIDENTIFIER]})*))`),h("FULLPLAIN",`v?${n[l.MAINVERSION]}${n[l.PRERELEASE]}?${n[l.BUILD]}?`),h("FULL",`^${n[l.FULLPLAIN]}$`),h("LOOSEPLAIN",`[v=\\s]*${n[l.MAINVERSIONLOOSE]}${n[l.PRERELEASELOOSE]}?${n[l.BUILD]}?`),h("LOOSE",`^${n[l.LOOSEPLAIN]}$`),h("GTLT","((?:<|>)?=?)"),h("XRANGEIDENTIFIERLOOSE",`${n[l.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`),h("XRANGEIDENTIFIER",`${n[l.NUMERICIDENTIFIER]}|x|X|\\*`),h("XRANGEPLAIN",`[v=\\s]*(${n[l.XRANGEIDENTIFIER]})(?:\\.(${n[l.XRANGEIDENTIFIER]})(?:\\.(${n[l.XRANGEIDENTIFIER]})(?:${n[l.PRERELEASE]})?${n[l.BUILD]}?)?)?`),h("XRANGEPLAINLOOSE",`[v=\\s]*(${n[l.XRANGEIDENTIFIERLOOSE]})(?:\\.(${n[l.XRANGEIDENTIFIERLOOSE]})(?:\\.(${n[l.XRANGEIDENTIFIERLOOSE]})(?:${n[l.PRERELEASELOOSE]})?${n[l.BUILD]}?)?)?`),h("XRANGE",`^${n[l.GTLT]}\\s*${n[l.XRANGEPLAIN]}$`),h("XRANGELOOSE",`^${n[l.GTLT]}\\s*${n[l.XRANGEPLAINLOOSE]}$`),h("COERCEPLAIN",`(^|[^\\d])(\\d{1,${r}})(?:\\.(\\d{1,${r}}))?(?:\\.(\\d{1,${r}}))?`),h("COERCE",`${n[l.COERCEPLAIN]}(?:$|[^\\d])`),h("COERCEFULL",n[l.COERCEPLAIN]+`(?:${n[l.PRERELEASE]})?(?:${n[l.BUILD]})?(?:$|[^\\d])`),h("COERCERTL",n[l.COERCE],!0),h("COERCERTLFULL",n[l.COERCEFULL],!0),h("LONETILDE","(?:~>?)"),h("TILDETRIM",`(\\s*)${n[l.LONETILDE]}\\s+`,!0),e.tildeTrimReplace="$1~",h("TILDE",`^${n[l.LONETILDE]}${n[l.XRANGEPLAIN]}$`),h("TILDELOOSE",`^${n[l.LONETILDE]}${n[l.XRANGEPLAINLOOSE]}$`),h("LONECARET","(?:\\^)"),h("CARETTRIM",`(\\s*)${n[l.LONECARET]}\\s+`,!0),e.caretTrimReplace="$1^",h("CARET",`^${n[l.LONECARET]}${n[l.XRANGEPLAIN]}$`),h("CARETLOOSE",`^${n[l.LONECARET]}${n[l.XRANGEPLAINLOOSE]}$`),h("COMPARATORLOOSE",`^${n[l.GTLT]}\\s*(${n[l.LOOSEPLAIN]})$|^$`),h("COMPARATOR",`^${n[l.GTLT]}\\s*(${n[l.FULLPLAIN]})$|^$`),h("COMPARATORTRIM",`(\\s*)${n[l.GTLT]}\\s*(${n[l.LOOSEPLAIN]}|${n[l.XRANGEPLAIN]})`,!0),e.comparatorTrimReplace="$1$2$3",h("HYPHENRANGE",`^\\s*(${n[l.XRANGEPLAIN]})\\s+-\\s+(${n[l.XRANGEPLAIN]})\\s*$`),h("HYPHENRANGELOOSE",`^\\s*(${n[l.XRANGEPLAINLOOSE]})\\s+-\\s+(${n[l.XRANGEPLAINLOOSE]})\\s*$`),h("STAR","(<|>)?=?\\s*\\*"),h("GTE0","^\\s*>=\\s*0\\.0\\.0\\s*$"),h("GTE0PRE","^\\s*>=\\s*0\\.0\\.0-0\\s*$")}),lt=A((e,t)=>{"use strict";var r=Object.freeze({loose:!0}),o=Object.freeze({}),s=i=>i?typeof i!="object"?r:i:o;t.exports=s}),Xt=A((e,t)=>{"use strict";var r=/^[0-9]+$/,o=(i,a)=>{if(typeof i=="number"&&typeof a=="number")return i===a?0:i<a?-1:1;let c=r.test(i),n=r.test(a);return c&&n&&(i=+i,a=+a),i===a?0:c&&!n?-1:n&&!c?1:i<a?-1:1},s=(i,a)=>o(a,i);t.exports={compareIdentifiers:o,rcompareIdentifiers:s}}),G=A((e,t)=>{"use strict";var r=_e(),{MAX_LENGTH:o,MAX_SAFE_INTEGER:s}=De(),{safeRe:i,t:a}=be(),c=lt(),{compareIdentifiers:n}=Xt(),f=class Q{constructor(u,d){if(d=c(d),u instanceof Q){if(u.loose===!!d.loose&&u.includePrerelease===!!d.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,d),this.options=d,this.loose=!!d.loose,this.includePrerelease=!!d.includePrerelease;let m=u.trim().match(d.loose?i[a.LOOSE]:i[a.FULL]);if(!m)throw new TypeError(`Invalid Version: ${u}`);if(this.raw=u,this.major=+m[1],this.minor=+m[2],this.patch=+m[3],this.major>s||this.major<0)throw new TypeError("Invalid major version");if(this.minor>s||this.minor<0)throw new TypeError("Invalid minor version");if(this.patch>s||this.patch<0)throw new TypeError("Invalid patch version");m[4]?this.prerelease=m[4].split(".").map(g=>{if(/^[0-9]+$/.test(g)){let h=+g;if(h>=0&&h<s)return h}return g}):this.prerelease=[],this.build=m[5]?m[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 Q)){if(typeof u=="string"&&u===this.version)return 0;u=new Q(u,this.options)}return u.version===this.version?0:this.compareMain(u)||this.comparePre(u)}compareMain(u){return u instanceof Q||(u=new Q(u,this.options)),this.major<u.major?-1:this.major>u.major?1:this.minor<u.minor?-1:this.minor>u.minor?1:this.patch<u.patch?-1:this.patch>u.patch?1:0}comparePre(u){if(u instanceof Q||(u=new Q(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 d=0;do{let m=this.prerelease[d],g=u.prerelease[d];if(r("prerelease compare",d,m,g),m===void 0&&g===void 0)return 0;if(g===void 0)return 1;if(m===void 0)return-1;if(m!==g)return n(m,g)}while(++d)}compareBuild(u){u instanceof Q||(u=new Q(u,this.options));let d=0;do{let m=this.build[d],g=u.build[d];if(r("build compare",d,m,g),m===void 0&&g===void 0)return 0;if(g===void 0)return 1;if(m===void 0)return-1;if(m!==g)return n(m,g)}while(++d)}inc(u,d,m){if(u.startsWith("pre")){if(!d&&m===!1)throw new Error("invalid increment argument: identifier is empty");if(d){let g=`-${d}`.match(this.options.loose?i[a.PRERELEASELOOSE]:i[a.PRERELEASE]);if(!g||g[1]!==d)throw new Error(`invalid identifier: ${d}`)}}switch(u){case"premajor":this.prerelease.length=0,this.patch=0,this.minor=0,this.major++,this.inc("pre",d,m);break;case"preminor":this.prerelease.length=0,this.patch=0,this.minor++,this.inc("pre",d,m);break;case"prepatch":this.prerelease.length=0,this.inc("patch",d,m),this.inc("pre",d,m);break;case"prerelease":this.prerelease.length===0&&this.inc("patch",d,m),this.inc("pre",d,m);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(m)?1:0;if(this.prerelease.length===0)this.prerelease=[g];else{let h=this.prerelease.length;for(;--h>=0;)typeof this.prerelease[h]=="number"&&(this.prerelease[h]++,h=-2);if(h===-1){if(d===this.prerelease.join(".")&&m===!1)throw new Error("invalid increment argument: identifier already exists");this.prerelease.push(g)}}if(d){let h=[d,g];m===!1&&(h=[d]),n(this.prerelease[0],d)===0?isNaN(this.prerelease[1])&&(this.prerelease=h):this.prerelease=h}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}),ue=A((e,t)=>{"use strict";var r=G(),o=(s,i,a=!1)=>{if(s instanceof r)return s;try{return new r(s,i)}catch(c){if(!a)return null;throw c}};t.exports=o}),bo=A((e,t)=>{"use strict";var r=ue(),o=(s,i)=>{let a=r(s,i);return a?a.version:null};t.exports=o}),Io=A((e,t)=>{"use strict";var r=ue(),o=(s,i)=>{let a=r(s.trim().replace(/^[=v]+/,""),i);return a?a.version:null};t.exports=o}),Ao=A((e,t)=>{"use strict";var r=G(),o=(s,i,a,c,n)=>{typeof a=="string"&&(n=c,c=a,a=void 0);try{return new r(s instanceof r?s.version:s,a).inc(i,c,n).version}catch{return null}};t.exports=o}),$o=A((e,t)=>{"use strict";var r=ue(),o=(s,i)=>{let a=r(s,null,!0),c=r(i,null,!0),n=a.compare(c);if(n===0)return null;let f=n>0,l=f?a:c,u=f?c:a,d=!!l.prerelease.length;if(u.prerelease.length&&!d){if(!u.patch&&!u.minor)return"major";if(u.compareMain(l)===0)return u.minor&&!u.patch?"minor":"patch"}let m=d?"pre":"";return a.major!==c.major?m+"major":a.minor!==c.minor?m+"minor":a.patch!==c.patch?m+"patch":"prerelease"};t.exports=o}),Ro=A((e,t)=>{"use strict";var r=G(),o=(s,i)=>new r(s,i).major;t.exports=o}),To=A((e,t)=>{"use strict";var r=G(),o=(s,i)=>new r(s,i).minor;t.exports=o}),Po=A((e,t)=>{"use strict";var r=G(),o=(s,i)=>new r(s,i).patch;t.exports=o}),No=A((e,t)=>{"use strict";var r=ue(),o=(s,i)=>{let a=r(s,i);return a&&a.prerelease.length?a.prerelease:null};t.exports=o}),X=A((e,t)=>{"use strict";var r=G(),o=(s,i,a)=>new r(s,a).compare(new r(i,a));t.exports=o}),Oo=A((e,t)=>{"use strict";var r=X(),o=(s,i,a)=>r(i,s,a);t.exports=o}),Lo=A((e,t)=>{"use strict";var r=X(),o=(s,i)=>r(s,i,!0);t.exports=o}),ut=A((e,t)=>{"use strict";var r=G(),o=(s,i,a)=>{let c=new r(s,a),n=new r(i,a);return c.compare(n)||c.compareBuild(n)};t.exports=o}),Co=A((e,t)=>{"use strict";var r=ut(),o=(s,i)=>s.sort((a,c)=>r(a,c,i));t.exports=o}),ko=A((e,t)=>{"use strict";var r=ut(),o=(s,i)=>s.sort((a,c)=>r(c,a,i));t.exports=o}),Ue=A((e,t)=>{"use strict";var r=X(),o=(s,i,a)=>r(s,i,a)>0;t.exports=o}),pt=A((e,t)=>{"use strict";var r=X(),o=(s,i,a)=>r(s,i,a)<0;t.exports=o}),zt=A((e,t)=>{"use strict";var r=X(),o=(s,i,a)=>r(s,i,a)===0;t.exports=o}),qt=A((e,t)=>{"use strict";var r=X(),o=(s,i,a)=>r(s,i,a)!==0;t.exports=o}),dt=A((e,t)=>{"use strict";var r=X(),o=(s,i,a)=>r(s,i,a)>=0;t.exports=o}),ht=A((e,t)=>{"use strict";var r=X(),o=(s,i,a)=>r(s,i,a)<=0;t.exports=o}),Yt=A((e,t)=>{"use strict";var r=zt(),o=qt(),s=Ue(),i=dt(),a=pt(),c=ht(),n=(f,l,u,d)=>{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,d);case"!=":return o(f,u,d);case">":return s(f,u,d);case">=":return i(f,u,d);case"<":return a(f,u,d);case"<=":return c(f,u,d);default:throw new TypeError(`Invalid operator: ${l}`)}};t.exports=n}),Mo=A((e,t)=>{"use strict";var r=G(),o=ue(),{safeRe:s,t:i}=be(),a=(c,n)=>{if(c instanceof r)return c;if(typeof c=="number"&&(c=String(c)),typeof c!="string")return null;n=n||{};let f=null;if(!n.rtl)f=c.match(n.includePrerelease?s[i.COERCEFULL]:s[i.COERCE]);else{let h=n.includePrerelease?s[i.COERCERTLFULL]:s[i.COERCERTL],N;for(;(N=h.exec(c))&&(!f||f.index+f[0].length!==c.length);)(!f||N.index+N[0].length!==f.index+f[0].length)&&(f=N),h.lastIndex=N.index+N[1].length+N[2].length;h.lastIndex=-1}if(f===null)return null;let l=f[2],u=f[3]||"0",d=f[4]||"0",m=n.includePrerelease&&f[5]?`-${f[5]}`:"",g=n.includePrerelease&&f[6]?`+${f[6]}`:"";return o(`${l}.${u}.${d}${m}${g}`,n)};t.exports=a}),Do=A((e,t)=>{"use strict";var r=class{constructor(){this.max=1e3,this.map=new Map}get(o){let s=this.map.get(o);if(s!==void 0)return this.map.delete(o),this.map.set(o,s),s}delete(o){return this.map.delete(o)}set(o,s){if(!this.delete(o)&&s!==void 0){if(this.map.size>=this.max){let i=this.map.keys().next().value;this.delete(i)}this.map.set(o,s)}return this}};t.exports=r}),z=A((e,t)=>{"use strict";var r=/\s+/g,o=class Ce{constructor(w,S){if(S=a(S),w instanceof Ce)return w.loose===!!S.loose&&w.includePrerelease===!!S.includePrerelease?w:new Ce(w.raw,S);if(w instanceof c)return this.raw=w.value,this.set=[[w]],this.formatted=void 0,this;if(this.options=S,this.loose=!!S.loose,this.includePrerelease=!!S.includePrerelease,this.raw=w.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(b=>!T(b[0])),this.set.length===0)this.set=[E];else if(this.set.length>1){for(let b of this.set)if(b.length===1&&O(b[0])){this.set=[b];break}}}this.formatted=void 0}get range(){if(this.formatted===void 0){this.formatted="";for(let w=0;w<this.set.length;w++){w>0&&(this.formatted+="||");let S=this.set[w];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(w){let S=((this.options.includePrerelease&&h)|(this.options.loose&&N))+":"+w,E=i.get(S);if(E)return E;let b=this.options.loose,v=b?l[u.HYPHENRANGELOOSE]:l[u.HYPHENRANGE];w=w.replace(v,Xe(this.options.includePrerelease)),n("hyphen replace",w),w=w.replace(l[u.COMPARATORTRIM],d),n("comparator trim",w),w=w.replace(l[u.TILDETRIM],m),n("tilde trim",w),w=w.replace(l[u.CARETTRIM],g),n("caret trim",w);let I=w.split(" ").map(D=>W(D,this.options)).join(" ").split(/\s+/).map(D=>Ve(D,this.options));b&&(I=I.filter(D=>(n("loose invalid filter",D,this.options),!!D.match(l[u.COMPARATORLOOSE])))),n("range list",I);let C=new Map,L=I.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 M=[...C.values()];return i.set(S,M),M}intersects(w,S){if(!(w instanceof Ce))throw new TypeError("a Range is required");return this.set.some(E=>j(E,S)&&w.set.some(b=>j(b,S)&&E.every(v=>b.every(I=>v.intersects(I,S)))))}test(w){if(!w)return!1;if(typeof w=="string")try{w=new f(w,this.options)}catch{return!1}for(let S=0;S<this.set.length;S++)if(ze(this.set[S],w,this.options))return!0;return!1}};t.exports=o;var s=Do(),i=new s,a=lt(),c=xe(),n=_e(),f=G(),{safeRe:l,t:u,comparatorTrimReplace:d,tildeTrimReplace:m,caretTrimReplace:g}=be(),{FLAG_INCLUDE_PRERELEASE:h,FLAG_LOOSE:N}=De(),T=y=>y.value==="<0.0.0-0",O=y=>y.value==="",j=(y,w)=>{let S=!0,E=y.slice(),b=E.pop();for(;S&&E.length;)S=E.every(v=>b.intersects(v,w)),b=E.pop();return S},W=(y,w)=>(y=y.replace(l[u.BUILD],""),n("comp",y,w),y=U(y,w),n("caret",y),y=Z(y,w),n("tildes",y),y=$(y,w),n("xrange",y),y=Je(y,w),n("stars",y),y),_=y=>!y||y.toLowerCase()==="x"||y==="*",Z=(y,w)=>y.trim().split(/\s+/).map(S=>J(S,w)).join(" "),J=(y,w)=>{let S=w.loose?l[u.TILDELOOSE]:l[u.TILDE];return y.replace(S,(E,b,v,I,C)=>{n("tilde",y,E,b,v,I,C);let L;return _(b)?L="":_(v)?L=`>=${b}.0.0 <${+b+1}.0.0-0`:_(I)?L=`>=${b}.${v}.0 <${b}.${+v+1}.0-0`:C?(n("replaceTilde pr",C),L=`>=${b}.${v}.${I}-${C} <${b}.${+v+1}.0-0`):L=`>=${b}.${v}.${I} <${b}.${+v+1}.0-0`,n("tilde return",L),L})},U=(y,w)=>y.trim().split(/\s+/).map(S=>H(S,w)).join(" "),H=(y,w)=>{n("caret",y,w);let S=w.loose?l[u.CARETLOOSE]:l[u.CARET],E=w.includePrerelease?"-0":"";return y.replace(S,(b,v,I,C,L)=>{n("caret",y,b,v,I,C,L);let M;return _(v)?M="":_(I)?M=`>=${v}.0.0${E} <${+v+1}.0.0-0`:_(C)?v==="0"?M=`>=${v}.${I}.0${E} <${v}.${+I+1}.0-0`:M=`>=${v}.${I}.0${E} <${+v+1}.0.0-0`:L?(n("replaceCaret pr",L),v==="0"?I==="0"?M=`>=${v}.${I}.${C}-${L} <${v}.${I}.${+C+1}-0`:M=`>=${v}.${I}.${C}-${L} <${v}.${+I+1}.0-0`:M=`>=${v}.${I}.${C}-${L} <${+v+1}.0.0-0`):(n("no pr"),v==="0"?I==="0"?M=`>=${v}.${I}.${C}${E} <${v}.${I}.${+C+1}-0`:M=`>=${v}.${I}.${C}${E} <${v}.${+I+1}.0-0`:M=`>=${v}.${I}.${C} <${+v+1}.0.0-0`),n("caret return",M),M})},$=(y,w)=>(n("replaceXRanges",y,w),y.split(/\s+/).map(S=>me(S,w)).join(" ")),me=(y,w)=>{y=y.trim();let S=w.loose?l[u.XRANGELOOSE]:l[u.XRANGE];return y.replace(S,(E,b,v,I,C,L)=>{n("xRange",y,E,b,v,I,C,L);let M=_(v),D=M||_(I),se=D||_(C),fe=se;return b==="="&&fe&&(b=""),L=w.includePrerelease?"-0":"",M?b===">"||b==="<"?E="<0.0.0-0":E="*":b&&fe?(D&&(I=0),C=0,b===">"?(b=">=",D?(v=+v+1,I=0,C=0):(I=+I+1,C=0)):b==="<="&&(b="<",D?v=+v+1:I=+I+1),b==="<"&&(L="-0"),E=`${b+v}.${I}.${C}${L}`):D?E=`>=${v}.0.0${L} <${+v+1}.0.0-0`:se&&(E=`>=${v}.${I}.0${L} <${v}.${+I+1}.0-0`),n("xRange return",E),E})},Je=(y,w)=>(n("replaceStars",y,w),y.trim().replace(l[u.STAR],"")),Ve=(y,w)=>(n("replaceGTE0",y,w),y.trim().replace(l[w.includePrerelease?u.GTE0PRE:u.GTE0],"")),Xe=y=>(w,S,E,b,v,I,C,L,M,D,se,fe)=>(_(E)?S="":_(b)?S=`>=${E}.0.0${y?"-0":""}`:_(v)?S=`>=${E}.${b}.0${y?"-0":""}`:I?S=`>=${S}`:S=`>=${S}${y?"-0":""}`,_(M)?L="":_(D)?L=`<${+M+1}.0.0-0`:_(se)?L=`<${M}.${+D+1}.0-0`:fe?L=`<=${M}.${D}.${se}-${fe}`:y?L=`<${M}.${D}.${+se+1}-0`:L=`<=${L}`,`${S} ${L}`.trim()),ze=(y,w,S)=>{for(let E=0;E<y.length;E++)if(!y[E].test(w))return!1;if(w.prerelease.length&&!S.includePrerelease){for(let E=0;E<y.length;E++)if(n(y[E].semver),y[E].semver!==c.ANY&&y[E].semver.prerelease.length>0){let b=y[E].semver;if(b.major===w.major&&b.minor===w.minor&&b.patch===w.patch)return!0}return!1}return!0}}),xe=A((e,t)=>{"use strict";var r=Symbol("SemVer ANY"),o=class tt{static get ANY(){return r}constructor(d,m){if(m=s(m),d instanceof tt){if(d.loose===!!m.loose)return d;d=d.value}d=d.trim().split(/\s+/).join(" "),n("comparator",d,m),this.options=m,this.loose=!!m.loose,this.parse(d),this.semver===r?this.value="":this.value=this.operator+this.semver.version,n("comp",this)}parse(d){let m=this.options.loose?i[a.COMPARATORLOOSE]:i[a.COMPARATOR],g=d.match(m);if(!g)throw new TypeError(`Invalid comparator: ${d}`);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(d){if(n("Comparator.test",d,this.options.loose),this.semver===r||d===r)return!0;if(typeof d=="string")try{d=new f(d,this.options)}catch{return!1}return c(d,this.operator,this.semver,this.options)}intersects(d,m){if(!(d instanceof tt))throw new TypeError("a Comparator is required");return this.operator===""?this.value===""?!0:new l(d.value,m).test(this.value):d.operator===""?d.value===""?!0:new l(this.value,m).test(d.semver):(m=s(m),m.includePrerelease&&(this.value==="<0.0.0-0"||d.value==="<0.0.0-0")||!m.includePrerelease&&(this.value.startsWith("<0.0.0")||d.value.startsWith("<0.0.0"))?!1:!!(this.operator.startsWith(">")&&d.operator.startsWith(">")||this.operator.startsWith("<")&&d.operator.startsWith("<")||this.semver.version===d.semver.version&&this.operator.includes("=")&&d.operator.includes("=")||c(this.semver,"<",d.semver,m)&&this.operator.startsWith(">")&&d.operator.startsWith("<")||c(this.semver,">",d.semver,m)&&this.operator.startsWith("<")&&d.operator.startsWith(">")))}};t.exports=o;var s=lt(),{safeRe:i,t:a}=be(),c=Yt(),n=_e(),f=G(),l=z()}),je=A((e,t)=>{"use strict";var r=z(),o=(s,i,a)=>{try{i=new r(i,a)}catch{return!1}return i.test(s)};t.exports=o}),_o=A((e,t)=>{"use strict";var r=z(),o=(s,i)=>new r(s,i).set.map(a=>a.map(c=>c.value).join(" ").trim().split(" "));t.exports=o}),Uo=A((e,t)=>{"use strict";var r=G(),o=z(),s=(i,a,c)=>{let n=null,f=null,l=null;try{l=new o(a,c)}catch{return null}return i.forEach(u=>{l.test(u)&&(!n||f.compare(u)===-1)&&(n=u,f=new r(n,c))}),n};t.exports=s}),xo=A((e,t)=>{"use strict";var r=G(),o=z(),s=(i,a,c)=>{let n=null,f=null,l=null;try{l=new o(a,c)}catch{return null}return i.forEach(u=>{l.test(u)&&(!n||f.compare(u)===1)&&(n=u,f=new r(n,c))}),n};t.exports=s}),jo=A((e,t)=>{"use strict";var r=G(),o=z(),s=Ue(),i=(a,c)=>{a=new o(a,c);let n=new r("0.0.0");if(a.test(n)||(n=new r("0.0.0-0"),a.test(n)))return n;n=null;for(let f=0;f<a.set.length;++f){let l=a.set[f],u=null;l.forEach(d=>{let m=new r(d.semver.version);switch(d.operator){case">":m.prerelease.length===0?m.patch++:m.prerelease.push(0),m.raw=m.format();case"":case">=":(!u||s(m,u))&&(u=m);break;case"<":case"<=":break;default:throw new Error(`Unexpected operation: ${d.operator}`)}}),u&&(!n||s(n,u))&&(n=u)}return n&&a.test(n)?n:null};t.exports=i}),Fo=A((e,t)=>{"use strict";var r=z(),o=(s,i)=>{try{return new r(s,i).range||"*"}catch{return null}};t.exports=o}),mt=A((e,t)=>{"use strict";var r=G(),o=xe(),{ANY:s}=o,i=z(),a=je(),c=Ue(),n=pt(),f=ht(),l=dt(),u=(d,m,g,h)=>{d=new r(d,h),m=new i(m,h);let N,T,O,j,W;switch(g){case">":N=c,T=f,O=n,j=">",W=">=";break;case"<":N=n,T=l,O=c,j="<",W="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if(a(d,m,h))return!1;for(let _=0;_<m.set.length;++_){let Z=m.set[_],J=null,U=null;if(Z.forEach(H=>{H.semver===s&&(H=new o(">=0.0.0")),J=J||H,U=U||H,N(H.semver,J.semver,h)?J=H:O(H.semver,U.semver,h)&&(U=H)}),J.operator===j||J.operator===W||(!U.operator||U.operator===j)&&T(d,U.semver)||U.operator===W&&O(d,U.semver))return!1}return!0};t.exports=u}),Wo=A((e,t)=>{"use strict";var r=mt(),o=(s,i,a)=>r(s,i,">",a);t.exports=o}),Ho=A((e,t)=>{"use strict";var r=mt(),o=(s,i,a)=>r(s,i,"<",a);t.exports=o}),Bo=A((e,t)=>{"use strict";var r=z(),o=(s,i,a)=>(s=new r(s,a),i=new r(i,a),s.intersects(i,a));t.exports=o}),Ko=A((e,t)=>{"use strict";var r=je(),o=X();t.exports=(s,i,a)=>{let c=[],n=null,f=null,l=s.sort((g,h)=>o(g,h,a));for(let g of l)r(g,i,a)?(f=g,n||(n=g)):(f&&c.push([n,f]),f=null,n=null);n&&c.push([n,null]);let u=[];for(let[g,h]of c)g===h?u.push(g):!h&&g===l[0]?u.push("*"):h?g===l[0]?u.push(`<=${h}`):u.push(`${g} - ${h}`):u.push(`>=${g}`);let d=u.join(" || "),m=typeof i.raw=="string"?i.raw:String(i);return d.length<m.length?d:i}}),Go=A((e,t)=>{"use strict";var r=z(),o=xe(),{ANY:s}=o,i=je(),a=X(),c=(m,g,h={})=>{if(m===g)return!0;m=new r(m,h),g=new r(g,h);let N=!1;e:for(let T of m.set){for(let O of g.set){let j=l(T,O,h);if(N=N||j!==null,j)continue e}if(N)return!1}return!0},n=[new o(">=0.0.0-0")],f=[new o(">=0.0.0")],l=(m,g,h)=>{if(m===g)return!0;if(m.length===1&&m[0].semver===s){if(g.length===1&&g[0].semver===s)return!0;h.includePrerelease?m=n:m=f}if(g.length===1&&g[0].semver===s){if(h.includePrerelease)return!0;g=f}let N=new Set,T,O;for(let $ of m)$.operator===">"||$.operator===">="?T=u(T,$,h):$.operator==="<"||$.operator==="<="?O=d(O,$,h):N.add($.semver);if(N.size>1)return null;let j;if(T&&O&&(j=a(T.semver,O.semver,h),j>0||j===0&&(T.operator!==">="||O.operator!=="<=")))return null;for(let $ of N){if(T&&!i($,String(T),h)||O&&!i($,String(O),h))return null;for(let me of g)if(!i($,String(me),h))return!1;return!0}let W,_,Z,J,U=O&&!h.includePrerelease&&O.semver.prerelease.length?O.semver:!1,H=T&&!h.includePrerelease&&T.semver.prerelease.length?T.semver:!1;U&&U.prerelease.length===1&&O.operator==="<"&&U.prerelease[0]===0&&(U=!1);for(let $ of g){if(J=J||$.operator===">"||$.operator===">=",Z=Z||$.operator==="<"||$.operator==="<=",T){if(H&&$.semver.prerelease&&$.semver.prerelease.length&&$.semver.major===H.major&&$.semver.minor===H.minor&&$.semver.patch===H.patch&&(H=!1),$.operator===">"||$.operator===">="){if(W=u(T,$,h),W===$&&W!==T)return!1}else if(T.operator===">="&&!i(T.semver,String($),h))return!1}if(O){if(U&&$.semver.prerelease&&$.semver.prerelease.length&&$.semver.major===U.major&&$.semver.minor===U.minor&&$.semver.patch===U.patch&&(U=!1),$.operator==="<"||$.operator==="<="){if(_=d(O,$,h),_===$&&_!==O)return!1}else if(O.operator==="<="&&!i(O.semver,String($),h))return!1}if(!$.operator&&(O||T)&&j!==0)return!1}return!(T&&Z&&!O&&j!==0||O&&J&&!T&&j!==0||H||U)},u=(m,g,h)=>{if(!m)return g;let N=a(m.semver,g.semver,h);return N>0?m:N<0||g.operator===">"&&m.operator===">="?g:m},d=(m,g,h)=>{if(!m)return g;let N=a(m.semver,g.semver,h);return N<0?m:N>0||g.operator==="<"&&m.operator==="<="?g:m};t.exports=c}),Qt=A((e,t)=>{"use strict";var r=be(),o=De(),s=G(),i=Xt(),a=ue(),c=bo(),n=Io(),f=Ao(),l=$o(),u=Ro(),d=To(),m=Po(),g=No(),h=X(),N=Oo(),T=Lo(),O=ut(),j=Co(),W=ko(),_=Ue(),Z=pt(),J=zt(),U=qt(),H=dt(),$=ht(),me=Yt(),Je=Mo(),Ve=xe(),Xe=z(),ze=je(),y=_o(),w=Uo(),S=xo(),E=jo(),b=Fo(),v=mt(),I=Wo(),C=Ho(),L=Bo(),M=Ko(),D=Go();t.exports={parse:a,valid:c,clean:n,inc:f,diff:l,major:u,minor:d,patch:m,prerelease:g,compare:h,rcompare:N,compareLoose:T,compareBuild:O,sort:j,rsort:W,gt:_,lt:Z,eq:J,neq:U,gte:H,lte:$,cmp:me,coerce:Je,Comparator:Ve,Range:Xe,satisfies:ze,toComparators:y,maxSatisfying:w,minSatisfying:S,minVersion:E,validRange:b,outside:v,gtr:I,ltr:C,intersects:L,simplifyRange:M,subset:D,SemVer:s,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}}),Ie=class extends Zo{constructor(e){super(),B(this,"dirName"),B(this,"fileName"),this.dirName=Tt(os(),".medplum"),this.fileName=Tt(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(Rt(this.fileName))return JSON.parse(ts(this.fileName,"utf8"))}writeFile(e){Rt(this.dirName)||es(this.dirName),rs(this.fileName,JSON.stringify(e,null,2),"utf8")}};async function x(e,t=!0){let r=e.profile??"default",o=new Ie(r),s=o.getObject("options");if(r!=="default"&&!s)throw new Error(`Profile "${r}" does not exist`);let{baseUrl:i,fhirUrlPath:a,accessToken:c,tokenUrl:n,authorizeUrl:f,clientId:l,clientSecret:u}=ss(e,o),d=e.fetch??fetch,m=new Qo({fetch:d,baseUrl:i,tokenUrl:n,fhirUrlPath:a,authorizeUrl:f,storage:o,onUnauthenticated:is,verbose:e.verbose});return t&&(c?m.setAccessToken(c):l&&u&&(m.setBasicAuth(l,u),s?.authType!=="basic"&&await m.startClientLogin(l,u))),m}function ss(e,t){let r=t.getObject("options"),o=e.baseUrl??r?.baseUrl??process.env.MEDPLUM_BASE_URL??"https://api.medplum.com/",s=e.fhirUrlPath??r?.fhirUrlPath??process.env.MEDPLUM_FHIR_URL_PATH,i=e.accessToken??r?.accessToken??process.env.MEDPLUM_CLIENT_ACCESS_TOKEN,a=e.tokenUrl??r?.tokenUrl??process.env.MEDPLUM_TOKEN_URL,c=e.authorizeUrl??r?.authorizeUrl??process.env.MEDPLUM_AUTHORIZE_URL,n=e.clientId??r?.clientId??process.env.MEDPLUM_CLIENT_ID,f=e.clientSecret??r?.clientSecret??process.env.MEDPLUM_CLIENT_SECRET;return{baseUrl:o,fhirUrlPath:s,accessToken:i,tokenUrl:a,authorizeUrl:c,clientId:n,clientSecret:f}}function is(){console.log("Unauthenticated: run `npx medplum login` to sign in")}var ve=new TextEncoder,Nt=new TextDecoder,Yn=2**32;function cs(...e){let t=e.reduce((s,{length:i})=>s+i,0),r=new Uint8Array(t),o=0;for(let s of e)r.set(s,o),o+=s.length;return r}var Ye=e=>ns.from(e).toString("base64url"),Ae=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(Ae,"code","ERR_JOSE_GENERIC");var pe=class extends Ae{constructor(){super(...arguments),B(this,"code","ERR_JOSE_NOT_SUPPORTED")}};B(pe,"code","ERR_JOSE_NOT_SUPPORTED");var ie=class extends Ae{constructor(){super(...arguments),B(this,"code","ERR_JWS_INVALID")}};B(ie,"code","ERR_JWS_INVALID");var rr=class extends Ae{constructor(){super(...arguments),B(this,"code","ERR_JWT_INVALID")}};B(rr,"code","ERR_JWT_INVALID");var Ot,Lt,ls=class extends(Lt=Ae,Ot=Symbol.asyncIterator,Lt){constructor(e="multiple matching keys found in the JSON Web Key Set",t){super(e,t),B(this,Ot),B(this,"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS")}};B(ls,"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS");var sr=e=>or.types.isKeyObject(e),us=ir.webcrypto,ps=us,gt=e=>ar.types.isCryptoKey(e);function q(e,t="algorithm.name"){return new TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`)}function ge(e,t){return e.name===t}function Qe(e){return parseInt(e.name.slice(4),10)}function ds(e){switch(e){case"ES256":return"P-256";case"ES384":return"P-384";case"ES512":return"P-521";default:throw new Error("unreachable")}}function hs(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 ms(e,t,...r){switch(t){case"HS256":case"HS384":case"HS512":{if(!ge(e.algorithm,"HMAC"))throw q("HMAC");let o=parseInt(t.slice(2),10);if(Qe(e.algorithm.hash)!==o)throw q(`SHA-${o}`,"algorithm.hash");break}case"RS256":case"RS384":case"RS512":{if(!ge(e.algorithm,"RSASSA-PKCS1-v1_5"))throw q("RSASSA-PKCS1-v1_5");let o=parseInt(t.slice(2),10);if(Qe(e.algorithm.hash)!==o)throw q(`SHA-${o}`,"algorithm.hash");break}case"PS256":case"PS384":case"PS512":{if(!ge(e.algorithm,"RSA-PSS"))throw q("RSA-PSS");let o=parseInt(t.slice(2),10);if(Qe(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(!ge(e.algorithm,"Ed25519"))throw q("Ed25519");break}case"ES256":case"ES384":case"ES512":{if(!ge(e.algorithm,"ECDSA"))throw q("ECDSA");let o=ds(t);if(e.algorithm.namedCurve!==o)throw q(o,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}hs(e,r)}function nr(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}var ot=(e,...t)=>nr("Key must be ",e,...t);function cr(e,t,...r){return nr(`Key for the ${e} algorithm must be `,t,...r)}var lr=e=>sr(e)||gt(e),ce=["KeyObject"];(globalThis.CryptoKey||ps?.CryptoKey)&&ce.push("CryptoKey");var fs=(...e)=>{let t=e.filter(Boolean);if(t.length===0||t.length===1)return!0;let r;for(let o of t){let s=Object.keys(o);if(!r||r.size===0){r=new Set(s);continue}for(let i of s){if(r.has(i))return!1;r.add(i)}}return!0},gs=fs;function ws(e){return typeof e=="object"&&e!==null}function ur(e){if(!ws(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 $e(e){return ur(e)&&typeof e.kty=="string"}function Es(e){return e.kty!=="oct"&&typeof e.d=="string"}function vs(e){return e.kty!=="oct"&&typeof e.d>"u"}function Ss(e){return $e(e)&&e.kty==="oct"&&typeof e.k=="string"}var bs=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 pe("Unsupported key curve for this operation")}},Is=(e,t)=>{let r;if(gt(e))r=ys.from(e);else if(sr(e))r=e;else{if($e(e))return e.crv;throw new TypeError(ot(e,...ce))}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:bs(o)}default:throw new TypeError("Invalid asymmetric key type for this operation")}},As=Is,Ct=(e,t)=>{let r;try{e instanceof $s?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`)},ae=e=>e?.[Symbol.toStringTag],st=(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},Rs=(e,t,r,o)=>{if(!(t instanceof Uint8Array)){if(o&&$e(t)){if(Ss(t)&&st(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(!lr(t))throw new TypeError(cr(e,t,...ce,"Uint8Array",o?"JSON Web Key":null));if(t.type!=="secret")throw new TypeError(`${ae(t)} instances for symmetric algorithms must be of type "secret"`)}},Ts=(e,t,r,o)=>{if(o&&$e(t))switch(r){case"sign":if(Es(t)&&st(e,t,r))return;throw new TypeError("JSON Web Key for this operation be a private JWK");case"verify":if(vs(t)&&st(e,t,r))return;throw new TypeError("JSON Web Key for this operation be a public JWK")}if(!lr(t))throw new TypeError(cr(e,t,...ce,o?"JSON Web Key":null));if(t.type==="secret")throw new TypeError(`${ae(t)} instances for asymmetric algorithms must not be of type "secret"`);if(r==="sign"&&t.type==="public")throw new TypeError(`${ae(t)} instances for asymmetric algorithm signing must be of type "private"`);if(r==="decrypt"&&t.type==="public")throw new TypeError(`${ae(t)} instances for asymmetric algorithm decryption must be of type "private"`);if(t.algorithm&&r==="verify"&&t.type==="private")throw new TypeError(`${ae(t)} instances for asymmetric algorithm verifying must be of type "public"`);if(t.algorithm&&r==="encrypt"&&t.type==="private")throw new TypeError(`${ae(t)} instances for asymmetric algorithm encryption must be of type "public"`)};function pr(e,t,r,o){t.startsWith("HS")||t==="dir"||t.startsWith("PBES2")||/^A\d{3}(?:GCM)?KW$/.test(t)?Rs(t,r,o,e):Ts(t,r,o,e)}var ec=pr.bind(void 0,!1),Ps=pr.bind(void 0,!0);function Ns(e,t,r,o,s){if(s.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(a=>typeof a!="string"||a.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 a of o.crit){if(!i.has(a))throw new pe(`Extension Header Parameter "${a}" is not recognized`);if(s[a]===void 0)throw new e(`Extension Header Parameter "${a}" is missing`);if(i.get(a)&&o[a]===void 0)throw new e(`Extension Header Parameter "${a}" MUST be integrity protected`)}return new Set(o.crit)}var Os=Ns;function Ls(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 pe(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}var ks=new Map([["ES256","P-256"],["ES256K","secp256k1"],["ES384","P-384"],["ES512","P-521"]]);function Ms(e,t){let r,o,s;if(t instanceof Cs)r=t.asymmetricKeyType,o=t.asymmetricKeyDetails;else switch(s=!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");Ct(t,e);break;case"PS256":case"PS384":case"PS512":if(r==="rsa-pss"){let{hashAlgorithm:a,mgf1HashAlgorithm:c,saltLength:n}=o,f=parseInt(e.slice(-3),10);if(a!==void 0&&(a!==`sha${f}`||c!==a))throw new TypeError(`Invalid key for this operation, its RSA-PSS parameters do not meet the requirements of "alg" ${e}`);if(n!==void 0&&n>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");Ct(t,e),i={padding:kt.RSA_PKCS1_PSS_PADDING,saltLength:kt.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 a=As(t),c=ks.get(e);if(a!==c)throw new TypeError(`Invalid key curve for the algorithm, its curve must be ${c}, got ${a}`);i={dsaEncoding:"ieee-p1363"};break}default:throw new pe(`alg ${e} is not supported either by JOSE or your javascript runtime`)}return s?{format:"jwk",key:t,...i}:i?{...i,key:t}:t}function _s(e){switch(e){case"HS256":return"sha256";case"HS384":return"sha384";case"HS512":return"sha512";default:throw new pe(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}function Us(e,t,r){if(t instanceof Uint8Array){if(!e.startsWith("HS"))throw new TypeError(ot(t,...ce));return Dt(t)}if(t instanceof Mt)return t;if(gt(t))return ms(t,e,r),Mt.from(t);if($e(t))return e.startsWith("HS")?Dt(Buffer.from(t.k,"base64url")):t;throw new TypeError(ot(t,...ce,"Uint8Array","JSON Web Key"))}var xs=Ds(Fe.sign),js=async(e,t,r)=>{let o=Us(e,t,"sign");if(e.startsWith("HS")){let s=Fe.createHmac(_s(e),o);return s.update(r),s.digest()}return xs(Ls(e),r,Ms(e,o))},Fs=js,ee=e=>Math.floor(e.getTime()/1e3),Ws=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i,Ze=e=>{let t=Ws.exec(e);if(!t||t[4]&&t[1])throw new TypeError("Invalid time period format");let r=parseFloat(t[2]),o=t[3].toLowerCase(),s;switch(o){case"sec":case"secs":case"second":case"seconds":case"s":s=Math.round(r);break;case"minute":case"minutes":case"min":case"mins":case"m":s=Math.round(r*60);break;case"hour":case"hours":case"hr":case"hrs":case"h":s=Math.round(r*3600);break;case"day":case"days":case"d":s=Math.round(r*86400);break;case"week":case"weeks":case"w":s=Math.round(r*604800);break;default:s=Math.round(r*31557600);break}return t[1]==="-"||t[4]==="ago"?-s:s},Hs=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(!gs(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=Os(ie,new Map([["b64",!0]]),t?.crit,this._protectedHeader,r),s=!0;if(o.has("b64")&&(s=this._protectedHeader.b64,typeof s!="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');Ps(i,e,"sign");let a=this._payload;s&&(a=ve.encode(Ye(a)));let c;this._protectedHeader?c=ve.encode(Ye(JSON.stringify(this._protectedHeader))):c=ve.encode("");let n=cs(c,ve.encode("."),a),f=await Fs(i,e,n),l={signature:Ye(f),payload:""};return s&&(l.payload=Nt.decode(a)),this._unprotectedHeader&&(l.header=this._unprotectedHeader),this._protectedHeader&&(l.protected=Nt.decode(c)),l}},Bs=class{constructor(e){B(this,"_flattened"),this._flattened=new Hs(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}`}};function te(e,t){if(!Number.isFinite(t))throw new TypeError(`Invalid ${e} input`);return t}var Ks=class{constructor(e={}){if(B(this,"_payload"),!ur(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)+Ze(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)+Ze(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)+Ze(e))}:this._payload={...this._payload,iat:te("setIssuedAt",e)},this}},Gs=class extends Ks{constructor(){super(...arguments),B(this,"_protectedHeader")}setProtectedHeader(e){return this._protectedHeader=e,this}async sign(e,t){let r=new Bs(ve.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 rr("JWTs MUST NOT use unencoded payload");return r.sign(e,t)}};function re(e){console.log(JSON.stringify(e,null,2))}async function fr(e,t,r){let o=t.source,s=We(o);if(!s)return;console.log("Saving source code...");let i=await e.createAttachment({data:s,filename:mr(o),contentType:si(o)});console.log("Updating bot...");let a=await e.updateResource({...r,sourceCode:i});console.log("Success! New bot version: "+a.meta?.versionId)}async function gr(e,t,r){let o=t.dist??t.source,s=We(o);if(!s)return;console.log("Deploying bot...");let i=await e.post(e.fhirUrl("Bot",r.id,"$deploy"),{code:s,filename:mr(o)});console.log("Deploy result: "+i.issue?.[0]?.details?.text)}async function wr(e,t,r,o,s,i,a){let c={name:t,description:"",runtimeVersion:i},n=await e.post("admin/projects/"+r+"/bot",c),f=await e.readResource("Bot",n.id),l={name:t,id:n.id,source:o,dist:s};await fr(e,l,f),await gr(e,l,f),console.log(`Success! Bot created: ${f.id}`),a&&ti(l)}function Zs(e){let t=new RegExp("^"+ri(e).replaceAll(String.raw`\*`,".*")+"$");return de()?.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 K(e,t){hr(wt(e),JSON.stringify(t,void 0,2),"utf-8")}function de(e,t){let r=oe(e,t),o=We(r);if(o)return JSON.parse(o)}function ei(e){let t=We(oe(e,{server:!0}));if(t)return JSON.parse(t)}function We(e){let t=wt(e);return zs(t)?dr(t,"utf8"):""}function ti(e){let t=de()??{};t.bots||(t.bots=[]),t.bots.push(e),hr("medplum.config.json",JSON.stringify(t,null,2),"utf8"),console.log(`Bot added to config: ${e.id}`)}function ri(e){return e.replaceAll(/[/\-\\^$*+?.()|[\]{}]/g,"\\$&")}function oi(e){let t=0,r=0;return Qs({cwd:e,filter:(o,s)=>{if(t++,t>100)throw new Error("Tar extractor reached max number of files");if(r+=s.size,r>10485760)throw new Error("Tar extractor reached max size");return!0}})}function _t(){return{url:"http://hl7.org/fhir/StructureDefinition/data-absent-reason",valueCode:"unsupported"}}function si(e){let t=qs(e).toLowerCase();return[".cjs",".mjs",".js"].includes(t)?qe.JAVASCRIPT:[".cts",".mts",".ts"].includes(t)?qe.TYPESCRIPT:qe.TEXT}function yr(e,t){let r=new Ie(e),o={name:e,...t};return r.setObject("options",o),o}function ii(e){return new Ie(e).getObject("options")}async function ai(e,t){let r={typ:"JWT",alg:tr.HS256},o=Math.floor(Date.now()/1e3),s={aud:`${t.baseUrl}${t.audience}`,iss:t.issuer,sub:t.subject,nbf:o,iat:o,exp:o+604800},i=Pt(JSON.stringify(r)),a=Pt(JSON.stringify(s)),c=`${i}.${a}`,n=Js("sha256",t.clientSecret).update(c).digest("base64url"),f=`${c}.${n}`;await e.startJwtBearerLogin(t.clientId,f,t.scope??"")}async function ni(e,t){let r=Vs(dr(wt(t.privateKeyPath))),o=await new Gs({}).setProtectedHeader({typ:"JWT",alg:tr.RS384}).setIssuer(t.clientId).setSubject(t.clientId).setAudience(`${t.baseUrl}${t.audience}`).setJti(Xs(16).toString("hex")).setIssuedAt().setExpirationTime("5m").sign(r);await e.startJwtAssertionLogin(o)}function P(e,t){t.configureHelp({showGlobalOptions:!0}),e.addCommand(t)}var R=class extends as{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)}};function ci(e,t){return async r=>{let o=e.registeredArguments.length,s=r.slice(0,o);s[o]=e.optsWithGlobals();try{let i=t(...s);Ys(i)&&await i}finally{e.resetOptionDefaults()}}}var Er=new R("status").aliases(["info","list","ls"]),vr=new R("ping"),Sr=new R("push"),br=new R("reload-config"),Ir=new R("upgrade"),he=new R("agent");P(he,Er);P(he,vr);P(he,Sr);P(he,br);P(he,Ir);Er.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 ft("--output <format>","An optional output format, defaults to table").choices(["table","json"]).default("table")).action(async(e,t)=>{await yt({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"}}})});vr.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 x(r),s=await Ar(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 a=await o.pushToAgent(s,e,`PING ${i}`,er.PING,!0,{maxRetries:0});console.info(a)}catch(a){throw new Error("Unexpected response from agent while pinging",{cause:a})}});Sr.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",er.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 s=await x(o),i=await Ar(s,r,o),a;try{a=await s.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(a)});br.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 ft("--output <format>","An optional output format, defaults to table").choices(["table","json"]).default("table")).action(async(e,t)=>{await yt({operation:"$reload-config",agentIds:e,options:t,parseSuccessfulResponse:r=>({id:r.agent.id,name:r.agent.name})})});Ir.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("--agentVersion <version>","An optional agent version to upgrade to. Defaults to the latest version if flag not included").option("--force","Forces an upgrade when a pending upgrade is in an inconsistent state. Use with caution.").addOption(new ft("--output <format>","An optional output format, defaults to table").choices(["table","json"]).default("table")).action(async(e,t)=>{let r={};t.agentVersion&&(r.version=t.agentVersion),t.force&&(r.force=!0),await yt({operation:"$upgrade",agentIds:e,options:t,params:r,parseSuccessfulResponse:o=>({id:o.agent.id,name:o.agent.name,version:t.agentVersion??"latest"})})});async function yt({operation:e,agentIds:t,options:r,params:o={},parseSuccessfulResponse:s}){let i=hi(t,r),a=await x(r),c=i.type==="criteria"?i.criteria:`Agent?_id=${i.ids.join(",")}`,n=new URLSearchParams(c.split("?")[1]);for(let[g,h]of Object.entries(o))n.append(g,h.toString());let f;try{let g=a.fhirUrl("Agent",e);g.search=n.toString(),f=await a.get(g,{cache:"reload"})}catch(g){throw new Error(`Operation '${e}' failed`,{cause:g})}if(r.output==="json"){console.info(JSON.stringify(f,null,2));return}let l=[],u=[];switch(f.resourceType){case"Bundle":{let g=li(f);for(let h of g)h.result.resourceType==="Parameters"||qo(h.result)?l.push(h):u.push(h);break}case"Parameters":case"OperationOutcome":{let g=await a.searchOne("Agent",n,{cache:"reload"});if(!g)throw new Error("Agent not found");f.resourceType==="Parameters"?l.push({agent:g,result:f}):u.push({agent:g,result:f});break}default:throw new Error(`Invalid result received for '${e}' operation: ${JSON.stringify(f)}`)}let d=[];for(let g of l){let h=s(g);d.push(h)}let m=[];for(let g of u){let h=g.result.issue?.[0],N={id:g.agent.id,name:g.agent.name,severity:h.severity,code:h.code,details:h.details?.text??"No details to show"};m.push(N)}console.info(`
|
|
3
3
|
${d.length} successful response(s):
|
|
4
4
|
`),console.table(d.length?d:"No successful responses received"),console.info(),m.length&&(console.info(`${m.length} failed response(s):`),console.info(),console.table(m))}async function Ar(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{$r(r.criteria);let s=await e.search("Agent",`${r.criteria.split("?")[1]}&_count=2`);if(!s?.entry?.length)throw new Error("Could not find an agent matching the provided criteria");if(s.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=s.entry[0].resource?.id}return{reference:`Agent/${o}`}}function li(e){let t=[];for(let r of e.entry??zo){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,s=t.optional;for(let i of o){let a=e.parameter?.find(n=>n.name===i);if(!a)throw new Error(`Failed to find parameter '${i}'`);let c;for(let n in a)if(n.startsWith("value")){if(c)throw new Error(`Found multiple values for parameter '${i}'`);c=n}if(!c)throw new Error(`Failed to find a value for parameter '${i}'`);r[i]=a[c]}if(s?.length)for(let i of s){let a=e.parameter?.find(n=>n.name===i);if(!a)continue;let c=di(i,a);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 $r(t.criteria),{type:"criteria",criteria:t.criteria};throw new Error("Either an [agentId...] arg or a --criteria <criteria> flag is required")}function $r(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(s){throw new Error(t,{cause:s})}if(!o.includes("="))throw new Error(t,{cause:new Error("Query string lacks at least one `=`")})}var Rr=fi,Tr="http://localhost:9615",Pr=new R("login"),Nr=new R("whoami"),Or=new R("token");Pr.action(async e=>{let t=e.profile??"default",r=yr(t,e),o=await x(e,!1);await vi(o,r)});Nr.action(async e=>{let t=await x(e);Ii(t)});Or.action(async e=>{let t=await x(e);await t.getProfileAsync();let r=t.getAccessToken();if(!r)throw new Error("Not logged in");console.log(r)});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 ai(e,t);break;case"jwt-assertion":await ni(e,t);break}}async function Si(e){let t=yi(async(r,o)=>{let s=new URL(r.url,"http://localhost:9615"),i=s.searchParams.get("code");if(r.method==="OPTIONS"){o.writeHead(200,{Allow:"GET, POST","Content-Type":Ne.TEXT}),o.end("OK");return}if(s.pathname==="/"&&i)try{let a=await e.processCode(i,{clientId:Rr,redirectUri:Tr});o.writeHead(200,{"Content-Type":Ne.TEXT}),o.end(`Signed in as ${mi(a)}. You may close this window.`)}catch(a){o.writeHead(400,{"Content-Type":Ne.TEXT}),o.end(`Error: ${gi(a)}`)}finally{t.close(),process.exit(0)}else o.writeHead(404,{"Content-Type":Ne.TEXT}),o.end("Not found")}).listen(9615)}async function bi(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,s)=>{wi(r,(i,a,c)=>{if(i){s(i);return}if(c){s(new Error("Could not open browser: "+c));return}o()})})}function Ii(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",Rr),t.searchParams.set("redirect_uri",Tr),t.searchParams.set("scope","openid"),t.searchParams.set("response_type","code"),t.searchParams.set("prompt","login"),await bi(t.toString())}var we="\x1B[0m",$i="\x1B[1m",Ri="\x1B[31m",Ti="\x1B[32m",Pi="\x1B[33m",Ni="\x1B[34m",Se={red:e=>`${Ri}${e}${we}`,green:e=>`${Ti}${e}${we}`,yellow:e=>`${Pi}${e}${we}`,blue:e=>`${Ni}${e}${we}`,bold:e=>`${$i}${e}${we}`},Ut=e=>e.replaceAll(/\*\*(.*?)\*\*/g,(t,r)=>Se.bold(r)),Oi=Vt(Qt(),1),He;function Cr(){He=Vi.createInterface({input:process.stdin,output:process.stdout})}function kr(){He.close()}function p(e){He.write(e+`
|
|
5
5
|
`)}function F(e){p(`
|
|
@@ -11,7 +11,7 @@ Configuration values come from a file named **medplum.<tag>.config.server.json**
|
|
|
11
11
|
`+Se.yellow("**Services must be restarted to apply changes.**"))).argument("<tag>","The Medplum stack tag").option("--file [file]",Ut("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(Ba),P(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(Xa)),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(Na),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(xa),e}var Kr=new R("save"),Gr=new R("deploy"),Jr=new R("create"),Ke=new R("bot");P(Ke,Kr);P(Ke,Gr);P(Ke,Jr);var Vr=new R("save-bot"),Xr=new R("deploy-bot"),zr=new R("create-bot");Kr.description("Saving the bot").argument("<botName>").action(async(e,t)=>{let r=await x(t);await Ge(r,e)});Gr.description("Deploy the app to AWS").argument("<botName>").action(async(e,t)=>{let r=await x(t);await Ge(r,e,!0)});Jr.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,s)=>{let i=await x(s);await wr(i,e,t,r,o,s.runtimeVersion,!!s.writeConfig)});async function Ge(e,t,r=!1){let o=Zs(t),s=[],i=[],a=0,c=0;for(let n of o)try{let f=await e.readResource("Bot",n.id);await fr(e,n,f),a++,r&&(await gr(e,n,f),c++)}catch(f){s.push(f),i.push(`${n.name} [${n.id}]`)}if(console.log(`Number of bots saved: ${a}`),console.log(`Number of bots deployed: ${c}`),console.log(`Number of errors: ${s.length}`),s.length)throw new Error(`${s.length} bot(s) had failures. Bots with failures:
|
|
12
12
|
|
|
13
13
|
${i.join(`
|
|
14
|
-
`)}`,{cause:s})}Vr.description("Saves the bot").argument("<botName>").action(async(e,t)=>{let r=await x(t);await Ge(r,e)});Xr.description("Deploy the bot to AWS").argument("<botName>").action(async(e,t)=>{let r=await x(t);await Ge(r,e,!0)});zr.arguments("<botName> <projectId> <sourceFile> <distFile>").description("Creates and saves the bot").action(async(e,t,r,o,s)=>{let i=await x(s);await wr(i,e,t,r,o)});var Yr=new R("export"),Qr=new R("import"),It=new R("bulk");P(It,Yr);P(It,Qr);Yr.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:s}=e,i=await x(e);(await i.bulkExport(t,r,o,{pollStatusOnAccepted:!0})).output?.forEach(async({type:a,url:c})=>{let n=new URL(c),f=await i.download(c),l=`${a}_${n.pathname}`.replaceAll(/[^a-zA-Z0-9]+/g,"_")+".ndjson",u=qr(s??"",l);en(`${u}`,await f.text(),()=>{console.log(`${u} is created`)})})});Qr.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:s}=t,i=qr(s??process.cwd(),e),a=await x(t);await rn(i,Number.parseInt(r,10),a,o)});async function rn(e,t,r,o){let s=[],i=Za(e),a=tn({input:i});for await(let c of a){let n=on(c,o);s.push({resource:n,request:{method:"POST",url:n.resourceType}}),s.length%t===0&&(await Bt(s,r),s=[])}s.length>0&&await Bt(s,r)}async function Bt(e,t){let r=await t.executeBatch({resourceType:"Bundle",type:"transaction",entry:e});for(let o of r.entry??Qa)re(o.response)}function on(e,t){let r=JSON.parse(e);return t?sn(r):r}function sn(e){return e.resourceType==="ExplanationOfBenefit"?an(e):e}function an(e){return e.provider||(e.provider=_t()),e.item?.forEach(t=>{t?.productOrService||(t.productOrService=_t())}),e}var fn=Object.defineProperty,gn=(e,t,r)=>t in e?fn(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,k=(e,t,r)=>gn(e,typeof t!="symbol"?t+"":t,r),Zr=class extends EventTarget{addEventListener(e,t,r){super.addEventListener(e,t,r)}removeEventListener(e,t,r){super.removeEventListener(e,t,r)}},wn=class extends Event{constructor(e,t){super("message"),k(this,"connection"),k(this,"message"),this.connection=e,this.message=t}},yn=class extends Event{constructor(e,t){super("enhancedAckSent"),k(this,"connection"),k(this,"message"),this.connection=e,this.message=t}},ne=class extends Event{constructor(e){super("error"),k(this,"error"),this.error=e}},nt=class extends Event{constructor(){super("close")}},Gt={FIRST:"first",APPLICATION:"application"},Jt="utf-8",En=60*1e3,eo=class extends Zr{constructor(e,t=Jt,r,o={}){super(),k(this,"socket"),k(this,"encoding"),k(this,"enhancedMode"),k(this,"messagesPerMin"),k(this,"chunks",[]),k(this,"pendingMessages",new Map),k(this,"responseQueue",[]),k(this,"lastMessageDispatchedTime",0),k(this,"responseQueueProcessing",!1),this.socket=e,this.encoding=t,this.enhancedMode=r,this.messagesPerMin=o.messagesPerMin,e.on("data",s=>{try{this.appendData(s);let i=this.parseMessages();for(let a of i)this.responseQueue.push(new wn(this,a));this.processResponseQueue().catch(a=>{this.dispatchEvent(new ne(a))})}catch(i){this.dispatchEvent(new ne(i))}}),e.on("error",s=>{this.resetBuffer(),this.dispatchEvent(new ne(s))}),e.on("close",()=>{this.dispatchEvent(new nt)}),this.addEventListener("message",s=>{let i;this.enhancedMode==="standard"?i=s.message.buildAck({ackCode:"CA"}):this.enhancedMode==="aaMode"&&(i=s.message.buildAck({ackCode:"AA"})),i&&(this.send(i),this.dispatchEvent(new yn(this,i)));let a=s.message.getSegment("MSA")?.getField(2)?.toString();if(!a)return;let c=this.pendingMessages.get(a);if(!c){this.dispatchEvent(new ne(new Ee({resourceType:"OperationOutcome",issue:[{severity:"warning",code:"not-found",details:{text:"Response received for unknown message control ID"},diagnostics:`Received ACK for message control ID '${a}' but there was no pending message with this control ID`}]})));return}let n=s.message.getSegment("MSA")?.getField(1)?.toString()?.toUpperCase();n&&(c.returnAck===Gt.APPLICATION&&n==="CA"||(c.resolve(s.message),this.pendingMessages.delete(a)))})}isClosed(){return this.socket.closed}sendImpl(e){let t=e.toString(),r=Kt.encode(t,this.encoding),o=Buffer.alloc(r.length+3);o.writeInt8(11,0),r.copy(o,1),o.writeInt8(28,r.length+1),o.writeInt8(13,r.length+2),this.socket.write(o)}async processResponseQueue(){if(!this.responseQueueProcessing){for(this.responseQueueProcessing=!0;this.responseQueue.length;){if(this.messagesPerMin){let t=En/this.messagesPerMin,r=Date.now()-this.lastMessageDispatchedTime;t>r&&await pn(t-r)}let e=this.responseQueue.shift();e&&this.dispatchEvent(e),this.lastMessageDispatchedTime=Date.now()}this.responseQueueProcessing=!1}}parseMessages(){let e=[],t=Buffer.concat(this.chunks);if(this.resetBuffer(),t.length===0)return e;let r=0;for(;r<t.length;){for(;t[r]!==11&&r<t.length;)r++;let o=-1;for(let c=r+1;c<t.length-1;c++)if(t[c]===28&&t[c+1]===13){o=c+1;break}if(o===-1)break;let s=t.subarray(r,o+1).subarray(1,-2),i=Kt.decode(s,this.encoding),a=un.parse(i);e.push(a),r=o+1}return this.chunks=r<t.length?[t.subarray(r)]:[],e}send(e){this.sendImpl(e)}async sendAndWait(e,t){return new Promise((r,o)=>{let s=e.getSegment("MSH")?.getField(10)?.toString();if(!s){o(new Ee(dn("Required field missing: MSH.10")));return}let i;t?.timeoutMs&&(i=setTimeout(()=>{this.pendingMessages.delete(s),o(new Ee({resourceType:"OperationOutcome",issue:[{severity:"error",code:"timeout",details:{text:"Client timeout"},diagnostics:`Request timed out after waiting ${t.timeoutMs} milliseconds for response`}]}))},t.timeoutMs)),this.pendingMessages.set(s,{message:e,resolve:r,reject:o,returnAck:t?.returnAck??Gt.APPLICATION,timer:i}),this.sendImpl(e)})}async close(){if(!this.isClosed()){if(this.socket.end(),this.socket.destroy(),this.pendingMessages.size){for(let e of this.pendingMessages.values())e.timer&&clearTimeout(e.timer),e.reject(new Ee({resourceType:"OperationOutcome",issue:[{severity:"warning",code:"incomplete",details:{text:"Message was still pending when connection closed"}}]}));this.dispatchEvent(new ne(new Ee({resourceType:"OperationOutcome",issue:[{severity:"warning",code:"incomplete",details:{text:"Messages were still pending when connection closed"},diagnostics:`Hl7Connection closed while ${this.pendingMessages.size} messages were pending`}]}))),this.pendingMessages.clear()}await new Promise(e=>{this.socket.once("close",e)})}}appendData(e){this.chunks.push(e)}resetBuffer(){this.chunks=[]}setEncoding(e){this.encoding=e??Jt}getEncoding(){return this.encoding}setEnhancedMode(e){this.enhancedMode=e}getEnhancedMode(){return this.enhancedMode}setMessagesPerMin(e){this.messagesPerMin=e}getMessagesPerMin(){return this.messagesPerMin}getPendingMessageCount(){return this.pendingMessages.size}},vn=class extends Zr{constructor(e){super(),k(this,"options"),k(this,"host"),k(this,"port"),k(this,"encoding"),k(this,"connection"),k(this,"keepAlive"),k(this,"socket"),k(this,"connectTimeout"),k(this,"deferredConnectionPromise"),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(){if(this.deferredConnectionPromise)return this.deferredConnectionPromise.promise;let e=this.deferredConnectionPromise=this.createDeferredConnectionPromise();return this.socket=ln({host:this.host,port:this.port,keepAlive:this.keepAlive}),this.connectTimeout>0&&(this.socket.setTimeout(this.connectTimeout),this.registerSocketTimeoutListener(e)),this.registerSocketConnectListener(e),this.registerSocketErrorListener(e),this.registerSocketCloseListener(e),e.promise}registerSocketTimeoutListener(e){Le(this.socket);let t=this.socket,r=()=>{this.cleanupSocket(t);let o=new Error(`Connection timeout after ${this.connectTimeout}ms`);this.rejectDeferredPromise(e,o)};t.on("timeout",r)}registerSocketConnectListener(e){Le(this.socket);let t=this.socket,r=()=>{if(t!==this.socket){this.cleanupSocket(t);return}let o;this.connection=o=new eo(t,this.encoding),t.setTimeout(0),this.registerHl7ConnectionListeners(o),e.resolve(o)};t.on("connect",r)}registerSocketErrorListener(e){Le(this.socket);let t=this.socket,r=o=>{this.cleanupSocket(t),o.constructor.name==="AggregateError"?this.rejectDeferredPromise(e,o.errors[0]):this.rejectDeferredPromise(e,o)};t.on("error",r)}registerSocketCloseListener(e){Le(this.socket);let t=this.socket,r=()=>{this.cleanupSocket(t),this.rejectDeferredPromise(e,new Error("Socket closed before connection finished"))};t.on("close",r)}registerHl7ConnectionListeners(e){e.addEventListener("close",()=>{this.socket=void 0,this.connection=void 0,this.deferredConnectionPromise=void 0,this.dispatchEvent(new nt)}),e.addEventListener("error",t=>{this.dispatchEvent(new ne(t.error))})}createDeferredConnectionPromise(){let e,t;return{promise:new Promise((r,o)=>{e=r,t=o}),resolve:e,reject:t}}rejectDeferredPromise(e,t){e.reject(t),this.deferredConnectionPromise===e&&(this.deferredConnectionPromise=void 0)}cleanupSocket(e){e.destroyed||e.destroy(),e===this.socket&&(this.socket=void 0)}async send(e){return(await this.connect()).send(e)}async sendAndWait(e,t){return(await this.connect()).sendAndWait(e,t)}async close(){if(this.deferredConnectionPromise&&this.rejectDeferredPromise(this.deferredConnectionPromise,new Error("Client closed while connecting")),this.connection){let e=this.connection;delete this.connection,await e.close()}else this.dispatchEvent(new nt);this.socket&&(this.socket.removeAllListeners(),this.socket.destroy(),this.socket=void 0)}},Sn=1e4,bn=class{constructor(e){k(this,"handler"),k(this,"server"),k(this,"encoding"),k(this,"enhancedMode"),k(this,"messagesPerMin"),k(this,"connections",new Set),this.handler=e}async start(e,t,r,o){t&&this.setEncoding(t),r!==void 0&&this.setEnhancedMode(r),o?.messagesPerMin!==void 0&&this.setMessagesPerMin(o.messagesPerMin);let s=mn.createServer(i=>{let a=new eo(i,this.encoding,this.enhancedMode,{messagesPerMin:this.messagesPerMin});this.handler(a),this.connections.add(a),a.addEventListener("close",()=>{this.connections.delete(a)})});await new Promise(i=>{let a=n=>{s.listen(n,i)},c=async n=>{n?.code==="EADDRINUSE"&&(await hn(50),s.close(),a(e))};s.on("error",c),s.once("listening",()=>{s.off("error",c)}),a(e),this.server=s})}async stop(e){return new Promise((t,r)=>{if(!this.server){r(new Error("Stop was called but there is no server running"));return}let o;e?.forceDrainTimeoutMs!==-1&&(o=setTimeout(()=>{for(let s of this.connections)s.close().catch(console.error)},e?.forceDrainTimeoutMs??Sn)),this.server.close(s=>{if(s){r(s);return}o&&clearTimeout(o),this.connections.clear(),this.server=void 0,t()})})}setEnhancedMode(e){this.enhancedMode=e}getEnhancedMode(){return this.enhancedMode}setEncoding(e){this.encoding=e}getEncoding(){return this.encoding}setMessagesPerMin(e){this.messagesPerMin=e}getMessagesPerMin(){return this.messagesPerMin}},An=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=Rn():o.file&&(r=In(o.file,"utf8")),!r)throw new Error("Missing HL7 message body");let s=new vn({host:e,port:Number.parseInt(t,10),encoding:o.encoding});try{let i=await s.sendAndWait(cn.parse(r));console.log(i.toString().replaceAll("\r",`
|
|
14
|
+
`)}`,{cause:s})}Vr.description("Saves the bot").argument("<botName>").action(async(e,t)=>{let r=await x(t);await Ge(r,e)});Xr.description("Deploy the bot to AWS").argument("<botName>").action(async(e,t)=>{let r=await x(t);await Ge(r,e,!0)});zr.arguments("<botName> <projectId> <sourceFile> <distFile>").description("Creates and saves the bot").action(async(e,t,r,o,s)=>{let i=await x(s);await wr(i,e,t,r,o)});var Yr=new R("export"),Qr=new R("import"),It=new R("bulk");P(It,Yr);P(It,Qr);Yr.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:s}=e,i=await x(e);(await i.bulkExport(t,r,o,{pollStatusOnAccepted:!0})).output?.forEach(async({type:a,url:c})=>{let n=new URL(c),f=await i.download(c),l=`${a}_${n.pathname}`.replaceAll(/[^a-zA-Z0-9]+/g,"_")+".ndjson",u=qr(s??"",l);en(`${u}`,await f.text(),()=>{console.log(`${u} is created`)})})});Qr.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:s}=t,i=qr(s??process.cwd(),e),a=await x(t);await rn(i,Number.parseInt(r,10),a,o)});async function rn(e,t,r,o){let s=[],i=Za(e),a=tn({input:i});for await(let c of a){let n=on(c,o);s.push({resource:n,request:{method:"POST",url:n.resourceType}}),s.length%t===0&&(await Bt(s,r),s=[])}s.length>0&&await Bt(s,r)}async function Bt(e,t){let r=await t.executeBatch({resourceType:"Bundle",type:"transaction",entry:e});for(let o of r.entry??Qa)re(o.response)}function on(e,t){let r=JSON.parse(e);return t?sn(r):r}function sn(e){return e.resourceType==="ExplanationOfBenefit"?an(e):e}function an(e){return e.provider||(e.provider=_t()),e.item?.forEach(t=>{t?.productOrService||(t.productOrService=_t())}),e}var fn=Object.defineProperty,gn=(e,t,r)=>t in e?fn(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,k=(e,t,r)=>gn(e,typeof t!="symbol"?t+"":t,r),Zr=class extends EventTarget{addEventListener(e,t,r){super.addEventListener(e,t,r)}removeEventListener(e,t,r){super.removeEventListener(e,t,r)}},wn=class extends Event{constructor(e,t){super("message"),k(this,"connection"),k(this,"message"),this.connection=e,this.message=t}},yn=class extends Event{constructor(e,t){super("enhancedAckSent"),k(this,"connection"),k(this,"message"),this.connection=e,this.message=t}},ne=class extends Event{constructor(e){super("error"),k(this,"error"),this.error=e}},nt=class extends Event{constructor(){super("close")}},Jt="utf-8",En=60*1e3,eo=class extends Zr{constructor(e,t=Jt,r,o={}){super(),k(this,"socket"),k(this,"encoding"),k(this,"enhancedMode"),k(this,"messagesPerMin"),k(this,"chunks",[]),k(this,"pendingMessages",new Map),k(this,"responseQueue",[]),k(this,"lastMessageDispatchedTime",0),k(this,"responseQueueProcessing",!1),this.socket=e,this.encoding=t,this.enhancedMode=r,this.messagesPerMin=o.messagesPerMin,e.on("data",s=>{try{this.appendData(s);let i=this.parseMessages();for(let a of i)this.responseQueue.push(new wn(this,a));this.processResponseQueue().catch(a=>{this.dispatchEvent(new ne(a))})}catch(i){this.dispatchEvent(new ne(i))}}),e.on("error",s=>{this.resetBuffer(),this.dispatchEvent(new ne(s))}),e.on("close",()=>{this.dispatchEvent(new nt)}),this.addEventListener("message",s=>{let i;this.enhancedMode==="standard"?i=s.message.buildAck({ackCode:"CA"}):this.enhancedMode==="aaMode"&&(i=s.message.buildAck({ackCode:"AA"})),i&&(this.send(i),this.dispatchEvent(new yn(this,i)));let a=s.message.getSegment("MSA")?.getField(2)?.toString();if(!a)return;let c=this.pendingMessages.get(a);if(!c){this.dispatchEvent(new ne(new Ee({resourceType:"OperationOutcome",issue:[{severity:"warning",code:"not-found",details:{text:"Response received for unknown message control ID"},diagnostics:`Received ACK for message control ID '${a}' but there was no pending message with this control ID`}]})));return}let n=s.message.getSegment("MSA")?.getField(1)?.toString()?.toUpperCase();n&&(c.returnAck===Kt.APPLICATION&&n==="CA"||(c.resolve(s.message),this.pendingMessages.delete(a)))})}isClosed(){return this.socket.closed}sendImpl(e){let t=e.toString(),r=Gt.encode(t,this.encoding),o=Buffer.alloc(r.length+3);o.writeInt8(11,0),r.copy(o,1),o.writeInt8(28,r.length+1),o.writeInt8(13,r.length+2),this.socket.write(o)}async processResponseQueue(){if(!this.responseQueueProcessing){for(this.responseQueueProcessing=!0;this.responseQueue.length;){if(this.messagesPerMin){let t=En/this.messagesPerMin,r=Date.now()-this.lastMessageDispatchedTime;t>r&&await pn(t-r)}let e=this.responseQueue.shift();e&&this.dispatchEvent(e),this.lastMessageDispatchedTime=Date.now()}this.responseQueueProcessing=!1}}parseMessages(){let e=[],t=Buffer.concat(this.chunks);if(this.resetBuffer(),t.length===0)return e;let r=0;for(;r<t.length;){for(;t[r]!==11&&r<t.length;)r++;let o=-1;for(let c=r+1;c<t.length-1;c++)if(t[c]===28&&t[c+1]===13){o=c+1;break}if(o===-1)break;let s=t.subarray(r,o+1).subarray(1,-2),i=Gt.decode(s,this.encoding),a=un.parse(i);e.push(a),r=o+1}return this.chunks=r<t.length?[t.subarray(r)]:[],e}send(e){this.sendImpl(e)}async sendAndWait(e,t){return new Promise((r,o)=>{let s=e.getSegment("MSH")?.getField(10)?.toString();if(!s){o(new Ee(dn("Required field missing: MSH.10")));return}let i;t?.timeoutMs&&(i=setTimeout(()=>{this.pendingMessages.delete(s),o(new Ee({resourceType:"OperationOutcome",issue:[{severity:"error",code:"timeout",details:{text:"Client timeout"},diagnostics:`Request timed out after waiting ${t.timeoutMs} milliseconds for response`}]}))},t.timeoutMs)),this.pendingMessages.set(s,{message:e,resolve:r,reject:o,returnAck:t?.returnAck??Kt.APPLICATION,timer:i}),this.sendImpl(e)})}async close(){if(!this.isClosed()){if(this.socket.end(),this.socket.destroy(),this.pendingMessages.size){for(let e of this.pendingMessages.values())e.timer&&clearTimeout(e.timer),e.reject(new Ee({resourceType:"OperationOutcome",issue:[{severity:"warning",code:"incomplete",details:{text:"Message was still pending when connection closed"}}]}));this.dispatchEvent(new ne(new Ee({resourceType:"OperationOutcome",issue:[{severity:"warning",code:"incomplete",details:{text:"Messages were still pending when connection closed"},diagnostics:`Hl7Connection closed while ${this.pendingMessages.size} messages were pending`}]}))),this.pendingMessages.clear()}await new Promise(e=>{this.socket.once("close",e)})}}appendData(e){this.chunks.push(e)}resetBuffer(){this.chunks=[]}setEncoding(e){this.encoding=e??Jt}getEncoding(){return this.encoding}setEnhancedMode(e){this.enhancedMode=e}getEnhancedMode(){return this.enhancedMode}setMessagesPerMin(e){this.messagesPerMin=e}getMessagesPerMin(){return this.messagesPerMin}getPendingMessageCount(){return this.pendingMessages.size}},vn=class extends Zr{constructor(e){super(),k(this,"options"),k(this,"host"),k(this,"port"),k(this,"encoding"),k(this,"connection"),k(this,"keepAlive"),k(this,"socket"),k(this,"connectTimeout"),k(this,"deferredConnectionPromise"),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(){if(this.deferredConnectionPromise)return this.deferredConnectionPromise.promise;let e=this.deferredConnectionPromise=this.createDeferredConnectionPromise();return this.socket=ln({host:this.host,port:this.port,keepAlive:this.keepAlive}),this.connectTimeout>0&&(this.socket.setTimeout(this.connectTimeout),this.registerSocketTimeoutListener(e)),this.registerSocketConnectListener(e),this.registerSocketErrorListener(e),this.registerSocketCloseListener(e),e.promise}registerSocketTimeoutListener(e){Le(this.socket);let t=this.socket,r=()=>{this.cleanupSocket(t);let o=new Error(`Connection timeout after ${this.connectTimeout}ms`);this.rejectDeferredPromise(e,o)};t.on("timeout",r)}registerSocketConnectListener(e){Le(this.socket);let t=this.socket,r=()=>{if(t!==this.socket){this.cleanupSocket(t);return}let o;this.connection=o=new eo(t,this.encoding),t.setTimeout(0),this.registerHl7ConnectionListeners(o),e.resolve(o)};t.on("connect",r)}registerSocketErrorListener(e){Le(this.socket);let t=this.socket,r=o=>{this.cleanupSocket(t),o.constructor.name==="AggregateError"?this.rejectDeferredPromise(e,o.errors[0]):this.rejectDeferredPromise(e,o)};t.on("error",r)}registerSocketCloseListener(e){Le(this.socket);let t=this.socket,r=()=>{this.cleanupSocket(t),this.rejectDeferredPromise(e,new Error("Socket closed before connection finished"))};t.on("close",r)}registerHl7ConnectionListeners(e){e.addEventListener("close",()=>{this.socket=void 0,this.connection=void 0,this.deferredConnectionPromise=void 0,this.dispatchEvent(new nt)}),e.addEventListener("error",t=>{this.dispatchEvent(new ne(t.error))})}createDeferredConnectionPromise(){let e,t;return{promise:new Promise((r,o)=>{e=r,t=o}),resolve:e,reject:t}}rejectDeferredPromise(e,t){e.reject(t),this.deferredConnectionPromise===e&&(this.deferredConnectionPromise=void 0)}cleanupSocket(e){e.destroyed||e.destroy(),e===this.socket&&(this.socket=void 0)}async send(e){return(await this.connect()).send(e)}async sendAndWait(e,t){return(await this.connect()).sendAndWait(e,t)}async close(){if(this.deferredConnectionPromise&&this.rejectDeferredPromise(this.deferredConnectionPromise,new Error("Client closed while connecting")),this.connection){let e=this.connection;delete this.connection,await e.close()}else this.dispatchEvent(new nt);this.socket&&(this.socket.removeAllListeners(),this.socket.destroy(),this.socket=void 0)}},Sn=1e4,bn=class{constructor(e){k(this,"handler"),k(this,"server"),k(this,"encoding"),k(this,"enhancedMode"),k(this,"messagesPerMin"),k(this,"connections",new Set),this.handler=e}async start(e,t,r,o){t&&this.setEncoding(t),r!==void 0&&this.setEnhancedMode(r),o?.messagesPerMin!==void 0&&this.setMessagesPerMin(o.messagesPerMin);let s=mn.createServer(i=>{let a=new eo(i,this.encoding,this.enhancedMode,{messagesPerMin:this.messagesPerMin});this.handler(a),this.connections.add(a),a.addEventListener("close",()=>{this.connections.delete(a)})});await new Promise(i=>{let a=n=>{s.listen(n,i)},c=async n=>{n?.code==="EADDRINUSE"&&(await hn(50),s.close(),a(e))};s.on("error",c),s.once("listening",()=>{s.off("error",c)}),a(e),this.server=s})}async stop(e){return new Promise((t,r)=>{if(!this.server){r(new Error("Stop was called but there is no server running"));return}let o;e?.forceDrainTimeoutMs!==-1&&(o=setTimeout(()=>{for(let s of this.connections)s.close().catch(console.error)},e?.forceDrainTimeoutMs??Sn)),this.server.close(s=>{if(s){r(s);return}o&&clearTimeout(o),this.connections.clear(),this.server=void 0,t()})})}setEnhancedMode(e){this.enhancedMode=e}getEnhancedMode(){return this.enhancedMode}setEncoding(e){this.encoding=e}getEncoding(){return this.encoding}setMessagesPerMin(e){this.messagesPerMin=e}getMessagesPerMin(){return this.messagesPerMin}},An=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=Rn():o.file&&(r=In(o.file,"utf8")),!r)throw new Error("Missing HL7 message body");let s=new vn({host:e,port:Number.parseInt(t,10),encoding:o.encoding});try{let i=await s.sendAndWait(cn.parse(r));console.log(i.toString().replaceAll("\r",`
|
|
15
15
|
`))}finally{await s.close()}}),$n=new R("listen").description("Starts an HL7 v2 MLLP server").argument("<port>").option("--encoding <encoding>","The encoding to use").action(async(e,t)=>{await new bn(r=>{r.addEventListener("message",({message:o})=>{console.log(o.toString().replaceAll("\r",`
|
|
16
16
|
`)),r.send(o.buildAck())})}).start(Number.parseInt(e,10),t.encoding),console.log("Listening on port "+e)}),At=new R("hl7");P(At,An);P(At,$n);function Rn(){let e=nn(new Date),t=Date.now().toString();return`MSH|^~\\&|ADTSYS|HOSPITAL|RECEIVER|DEST|${e}||ADT^A01|${t}|P|2.5|
|
|
17
17
|
EVN|A01|${e}||
|