medplum 5.1.8 → 5.1.9
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 +1 -1
- package/dist/cjs/index.cjs.map +2 -2
- package/dist/esm/index.mjs +1 -1
- package/dist/esm/index.mjs.map +2 -2
- package/package.json +3 -3
package/dist/cjs/index.cjs
CHANGED
|
@@ -11,7 +11,7 @@ Configuration values come from a file named **medplum.<tag>.config.server.json**
|
|
|
11
11
|
`+_e.yellow("**Services must be restarted to apply changes.**"))).argument("<tag>","The Medplum stack tag").option("--file [file]",ir("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(Ta),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(Ca)),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(fa),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(Ia),e}var Rs=new R("save"),Ts=new R("deploy"),Ps=new R("create"),ht=new R("bot");P(ht,Rs);P(ht,Ts);P(ht,Ps);var Ns=new R("save-bot"),Os=new R("deploy-bot"),Cs=new R("create-bot");Rs.description("Saving the bot").argument("<botName>").action(async(e,t)=>{let r=await x(t);await mt(r,e)});Ts.description("Deploy the app to AWS").argument("<botName>").action(async(e,t)=>{let r=await x(t);await mt(r,e,!0)});Ps.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,s,o)=>{let i=await x(o);await Wr(i,e,t,r,s,o.runtimeVersion,!!o.writeConfig)});async function mt(e,t,r=!1){let s=Pi(t),o=[],i=[],a=0,c=0;for(let n of s)try{let f=await e.readResource("Bot",n.id);await jr(e,n,f),a++,r&&(await Fr(e,n,f),c++)}catch(f){o.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: ${o.length}`),o.length)throw new Error(`${o.length} bot(s) had failures. Bots with failures:
|
|
12
12
|
|
|
13
13
|
${i.join(`
|
|
14
|
-
`)}`,{cause:o})}Ns.description("Saves the bot").argument("<botName>").action(async(e,t)=>{let r=await x(t);await mt(r,e)});Os.description("Deploy the bot to AWS").argument("<botName>").action(async(e,t)=>{let r=await x(t);await mt(r,e,!0)});Cs.arguments("<botName> <projectId> <sourceFile> <distFile>").description("Creates and saves the bot").action(async(e,t,r,s,o)=>{let i=await x(o);await Wr(i,e,t,r,s)});var Ds=new R("export"),Us=new R("import"),qt=new R("bulk");P(qt,Ds);P(qt,Us);Ds.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:s,targetDirectory:o}=e,i=await x(e),a=await i.bulkExport(t,r,s,{pollStatusOnAccepted:!0});for(let{type:c,url:n}of a.output??Xt.EMPTY){let f=new URL(n),l=`${c}_${f.pathname}`.replaceAll(/[^a-zA-Z0-9]+/g,"_")+".ndjson",u=(0,zt.resolve)(o??"",l),d=await i.downloadResponse(n);if(!d.ok)throw new Error(`Download failed: ${d.status} ${d.statusText}`);if(!d.body)throw new Error("Download response missing body");let m=ks.Readable.fromWeb(d.body);await(0,Ms.pipeline)(m,(0,ft.createWriteStream)(u)),console.log(`${u} is created`)}});Us.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:s,targetDirectory:o}=t,i=(0,zt.resolve)(o??process.cwd(),e),a=await x(t);await Da(i,Number.parseInt(r,10),a,s)});async function Da(e,t,r,s){let o=[],i=(0,ft.createReadStream)(e),a=(0,Ls.createInterface)({input:i});for await(let c of a){let n=Ua(c,s);o.push({resource:n,request:{method:"POST",url:n.resourceType}}),o.length%t===0&&(await ur(o,r),o=[])}o.length>0&&await ur(o,r)}async function ur(e,t){let r=await t.executeBatch({resourceType:"Bundle",type:"transaction",entry:e});for(let s of r.entry??Xt.EMPTY)de(s.response)}function Ua(e,t){let r=JSON.parse(e);return t?_a(r):r}function _a(e){return e.resourceType==="ExplanationOfBenefit"?xa(e):e}function xa(e){return e.provider||(e.provider=or()),e.item?.forEach(t=>{t?.productOrService||(t.productOrService=or())}),e}var ja=Object.defineProperty,Fa=(e,t,r)=>t in e?ja(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,L=(e,t,r)=>Fa(e,typeof t!="symbol"?t+"":t,r),Fs=class extends EventTarget{addEventListener(e,t,r){super.addEventListener(e,t,r)}removeEventListener(e,t,r){super.removeEventListener(e,t,r)}},Wa=class extends Event{constructor(e,t){super("message"),L(this,"connection"),L(this,"message"),this.connection=e,this.message=t}},Ha=class extends Event{constructor(e,t){super("enhancedAckSent"),L(this,"connection"),L(this,"message"),this.connection=e,this.message=t}},Ue=class extends Event{constructor(e){super("error"),L(this,"error"),this.error=e}},Lt=class extends Event{constructor(e){super("warning"),L(this,"error"),this.error=e}},kt=class extends Event{constructor(){super("close")}},pr="utf-8",Ba=5e3,Ka=60*1e3,Ws=class extends Fs{constructor(e,t=pr,r,s={}){super(),L(this,"socket"),L(this,"encoding"),L(this,"enhancedMode"),L(this,"messagesPerMin"),L(this,"gracefulCloseTimeoutMs"),L(this,"chunks",[]),L(this,"pendingMessages",new Map),L(this,"responseQueue",[]),L(this,"lastMessageDispatchedTime",0),L(this,"responseQueueProcessing",!1),L(this,"closing",!1),this.socket=e,this.encoding=t,this.enhancedMode=r,this.messagesPerMin=s.messagesPerMin,this.gracefulCloseTimeoutMs=s.gracefulCloseTimeoutMs??Ba,e.on("data",o=>{if(this.closing){this.dispatchEvent(new Lt(new G.OperationOutcomeError({resourceType:"OperationOutcome",issue:[{severity:"warning",code:"transient",details:{text:"Data received after close was initiated"}}]})));return}try{this.appendData(o);let i=this.parseMessages();for(let a of i)this.responseQueue.push(new Wa(this,a));this.processResponseQueue().catch(a=>{this.dispatchEvent(new Ue(a))})}catch(i){this.dispatchEvent(new Ue(i))}}),e.on("error",o=>{this.resetBuffer(),this.dispatchEvent(new Ue(o))}),e.on("close",()=>{this.drainPendingMessages(),this.dispatchEvent(new kt)}),this.addEventListener("message",o=>{let i;this.enhancedMode==="standard"?i=o.message.buildAck({ackCode:"CA"}):this.enhancedMode==="aaMode"&&(i=o.message.buildAck({ackCode:"AA"})),i&&(this.send(i),this.dispatchEvent(new Ha(this,i)));let a=o.message.getSegment("MSA")?.getField(2)?.toString();if(!a)return;let c=this.pendingMessages.get(a);if(!c){this.dispatchEvent(new Lt(new G.OperationOutcomeError({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=o.message.getSegment("MSA")?.getField(1)?.toString()?.toUpperCase();n&&(c.returnAck===G.ReturnAckCategory.APPLICATION&&n==="CA"||(c.resolve(o.message),this.pendingMessages.delete(a)))})}isClosed(){return this.socket.closed}sendImpl(e){let t=e.toString(),r=Ct.default.encode(t,this.encoding),s=Buffer.alloc(r.length+3);s.writeInt8(11,0),r.copy(s,1),s.writeInt8(28,r.length+1),s.writeInt8(13,r.length+2),this.socket.write(s)}async processResponseQueue(){if(!this.responseQueueProcessing){for(this.responseQueueProcessing=!0;this.responseQueue.length;){if(this.messagesPerMin){let t=Ka/this.messagesPerMin,r=Date.now()-this.lastMessageDispatchedTime;t>r&&await(0,G.sleep)(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 s=-1;for(let c=r+1;c<t.length-1;c++)if(t[c]===28&&t[c+1]===13){s=c+1;break}if(s===-1)break;let o=t.subarray(r,s+1).subarray(1,-2),i=Ct.default.decode(o,this.encoding),a=G.Hl7Message.parse(i);e.push(a),r=s+1}return this.chunks=r<t.length?[t.subarray(r)]:[],e}send(e){this.sendImpl(e)}async sendAndWait(e,t){return new Promise((r,s)=>{let o=e.getSegment("MSH")?.getField(10)?.toString();if(!o){s(new G.OperationOutcomeError((0,G.validationError)("Required field missing: MSH.10")));return}let i;t?.timeoutMs&&(i=setTimeout(()=>{this.pendingMessages.delete(o),s(new G.OperationOutcomeError({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(o,{message:e,resolve:r,reject:s,returnAck:t?.returnAck??G.ReturnAckCategory.APPLICATION,timer:i}),this.sendImpl(e)})}async close(){this.isClosed()||(this.closing=!0,this.socket.end(),this.drainPendingMessages(),await new Promise(e=>{let t=setTimeout(()=>{this.socket.destroy()},this.gracefulCloseTimeoutMs);this.socket.once("close",()=>{clearTimeout(t),e()})}))}drainPendingMessages(){if(!this.pendingMessages.size)return;let e=this.pendingMessages.size;for(let t of this.pendingMessages.values())t.timer&&clearTimeout(t.timer),t.reject(new G.OperationOutcomeError({resourceType:"OperationOutcome",issue:[{severity:"warning",code:"incomplete",details:{text:"Message was still pending when connection closed"}}]}));this.dispatchEvent(new Ue(new G.OperationOutcomeError({resourceType:"OperationOutcome",issue:[{severity:"warning",code:"incomplete",details:{text:"Messages were still pending when connection closed"},diagnostics:`Hl7Connection closed while ${e} messages were pending`}]}))),this.pendingMessages.clear()}appendData(e){this.chunks.push(e)}resetBuffer(){this.chunks=[]}setEncoding(e){this.encoding=e??pr}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}},Ga=class extends Fs{constructor(e){super(),L(this,"options"),L(this,"host"),L(this,"port"),L(this,"encoding"),L(this,"connection"),L(this,"keepAlive"),L(this,"socket"),L(this,"connectTimeout"),L(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=(0,_s.connect)({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){(0,De.default)(this.socket);let t=this.socket,r=()=>{this.cleanupSocket(t);let s=new Error(`Connection timeout after ${this.connectTimeout}ms`);this.rejectDeferredPromise(e,s)};t.on("timeout",r)}registerSocketConnectListener(e){(0,De.default)(this.socket);let t=this.socket,r=()=>{if(t!==this.socket){this.cleanupSocket(t);return}let s;this.connection=s=new Ws(t,this.encoding),t.setTimeout(0),this.registerHl7ConnectionListeners(s),e.resolve(s)};t.on("connect",r)}registerSocketErrorListener(e){(0,De.default)(this.socket);let t=this.socket,r=s=>{this.cleanupSocket(t),s.constructor.name==="AggregateError"?this.rejectDeferredPromise(e,s.errors[0]):this.rejectDeferredPromise(e,s)};t.on("error",r)}registerSocketCloseListener(e){(0,De.default)(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 kt)}),e.addEventListener("error",t=>{this.dispatchEvent(new Ue(t.error))}),e.addEventListener("warning",t=>{this.dispatchEvent(new Lt(t.error))})}createDeferredConnectionPromise(){let e,t;return{promise:new Promise((r,s)=>{e=r,t=s}),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 kt);this.socket&&(this.socket.removeAllListeners(),this.socket.destroy(),this.socket=void 0)}},Ja=1e4,Va=class{constructor(e){L(this,"handler"),L(this,"server"),L(this,"encoding"),L(this,"enhancedMode"),L(this,"messagesPerMin"),L(this,"connections",new Set),this.handler=e}async start(e,t,r,s){t&&this.setEncoding(t),r!==void 0&&this.setEnhancedMode(r),s?.messagesPerMin!==void 0&&this.setMessagesPerMin(s.messagesPerMin);let o=js.default.createServer(i=>{let a=new Ws(i,this.encoding,this.enhancedMode,{messagesPerMin:this.messagesPerMin});this.handler(a),this.connections.add(a),a.addEventListener("close",()=>{this.connections.delete(a)})});return new Promise((i,a)=>{let c=f=>{o.listen(f,()=>{let l=o.address().port;i(l)})},n=f=>{f?.code==="EADDRINUSE"?o.close(()=>(0,xs.sleep)(50).then(()=>c(e))):a(f)};o.on("error",n),o.once("listening",()=>{o.off("error",n)}),c(e),this.server=o})}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 s;e?.forceDrainTimeoutMs!==-1&&(s=setTimeout(()=>{for(let o of this.connections)o.close().catch(console.error)},e?.forceDrainTimeoutMs??Ja)),this.server.close(o=>{if(o){r(o);return}s&&clearTimeout(s),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}},Xa=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,s)=>{if(s.generateExample?r=qa():s.file&&(r=(0,Hs.readFileSync)(s.file,"utf8")),!r)throw new Error("Missing HL7 message body");let o=new Ga({host:e,port:Number.parseInt(t,10),encoding:s.encoding});try{let i=await o.sendAndWait(gt.Hl7Message.parse(r));console.log(i.toString().replaceAll("\r",`
|
|
14
|
+
`)}`,{cause:o})}Ns.description("Saves the bot").argument("<botName>").action(async(e,t)=>{let r=await x(t);await mt(r,e)});Os.description("Deploy the bot to AWS").argument("<botName>").action(async(e,t)=>{let r=await x(t);await mt(r,e,!0)});Cs.arguments("<botName> <projectId> <sourceFile> <distFile>").description("Creates and saves the bot").action(async(e,t,r,s,o)=>{let i=await x(o);await Wr(i,e,t,r,s)});var Ds=new R("export"),Us=new R("import"),qt=new R("bulk");P(qt,Ds);P(qt,Us);Ds.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:s,targetDirectory:o}=e,i=await x(e),a=await i.bulkExport(t,r,s,{pollStatusOnAccepted:!0});for(let{type:c,url:n}of a.output??Xt.EMPTY){let f=new URL(n),l=`${c}_${f.pathname}`.replaceAll(/[^a-zA-Z0-9]+/g,"_")+".ndjson",u=(0,zt.resolve)(o??"",l),d=await i.downloadResponse(n);if(!d.ok)throw new Error(`Download failed: ${d.status} ${d.statusText}`);if(!d.body)throw new Error("Download response missing body");let m=ks.Readable.fromWeb(d.body);await(0,Ms.pipeline)(m,(0,ft.createWriteStream)(u)),console.log(`${u} is created`)}});Us.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:s,targetDirectory:o}=t,i=(0,zt.resolve)(o??process.cwd(),e),a=await x(t);await Da(i,Number.parseInt(r,10),a,s)});async function Da(e,t,r,s){let o=[],i=(0,ft.createReadStream)(e),a=(0,Ls.createInterface)({input:i});for await(let c of a){let n=Ua(c,s);o.push({resource:n,request:{method:"POST",url:n.resourceType}}),o.length%t===0&&(await ur(o,r),o=[])}o.length>0&&await ur(o,r)}async function ur(e,t){let r=await t.executeBatch({resourceType:"Bundle",type:"transaction",entry:e});for(let s of r.entry??Xt.EMPTY)de(s.response)}function Ua(e,t){let r=JSON.parse(e);return t?_a(r):r}function _a(e){return e.resourceType==="ExplanationOfBenefit"?xa(e):e}function xa(e){return e.provider||(e.provider=or()),e.item?.forEach(t=>{t?.productOrService||(t.productOrService=or())}),e}var ja=Object.defineProperty,Fa=(e,t,r)=>t in e?ja(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,L=(e,t,r)=>Fa(e,typeof t!="symbol"?t+"":t,r),Fs=class extends EventTarget{addEventListener(e,t,r){super.addEventListener(e,t,r)}removeEventListener(e,t,r){super.removeEventListener(e,t,r)}},Wa=class extends Event{constructor(e,t){super("message"),L(this,"connection"),L(this,"message"),this.connection=e,this.message=t}},Ha=class extends Event{constructor(e,t){super("enhancedAckSent"),L(this,"connection"),L(this,"message"),this.connection=e,this.message=t}},Ue=class extends Event{constructor(e){super("error"),L(this,"error"),this.error=e}},Lt=class extends Event{constructor(e){super("warning"),L(this,"error"),this.error=e}},kt=class extends Event{constructor(){super("close")}},pr="utf-8",Ba=5e3,Ka=60*1e3,Ws=class extends Fs{constructor(e,t=pr,r,s={}){super(),L(this,"socket"),L(this,"encoding"),L(this,"enhancedMode"),L(this,"messagesPerMin"),L(this,"gracefulCloseTimeoutMs"),L(this,"chunks",[]),L(this,"pendingMessages",new Map),L(this,"responseQueue",[]),L(this,"lastMessageDispatchedTime",0),L(this,"responseQueueProcessing",!1),L(this,"closing",!1),this.socket=e,this.encoding=t,this.enhancedMode=r,this.messagesPerMin=s.messagesPerMin,this.gracefulCloseTimeoutMs=s.gracefulCloseTimeoutMs??Ba,e.on("data",o=>{if(this.closing){this.dispatchEvent(new Lt(new G.OperationOutcomeError({resourceType:"OperationOutcome",issue:[{severity:"warning",code:"transient",details:{text:"Data received after close was initiated"}}]})));return}try{this.appendData(o);let i=this.parseMessages();for(let a of i)this.responseQueue.push(new Wa(this,a));this.processResponseQueue().catch(a=>{this.dispatchEvent(new Ue(a))})}catch(i){this.dispatchEvent(new Ue(i))}}),e.on("error",o=>{this.resetBuffer(),this.dispatchEvent(new Ue(o))}),e.on("close",()=>{this.drainPendingMessages(),this.dispatchEvent(new kt)}),this.addEventListener("message",o=>{let i;this.enhancedMode==="standard"?i=o.message.buildAck({ackCode:"CA"}):this.enhancedMode==="aaMode"&&(i=o.message.buildAck({ackCode:"AA"})),i&&(this.send(i),this.dispatchEvent(new Ha(this,i)));let a=o.message.getSegment("MSA")?.getField(2)?.toString();if(!a)return;let c=this.getPendingMessage(a);if(!c){this.dispatchEvent(new Lt(new G.OperationOutcomeError({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=o.message.getSegment("MSA")?.getField(1)?.toString()?.toUpperCase();n&&(c.returnAck===G.ReturnAckCategory.APPLICATION&&n==="CA"||(c.timer&&clearTimeout(c.timer),c.resolve(o.message),this.deletePendingMessage(a)))})}isClosed(){return this.socket.closed}sendImpl(e){let t=e.toString(),r=Ct.default.encode(t,this.encoding),s=Buffer.alloc(r.length+3);s.writeInt8(11,0),r.copy(s,1),s.writeInt8(28,r.length+1),s.writeInt8(13,r.length+2),this.socket.write(s)}async processResponseQueue(){if(!this.responseQueueProcessing){for(this.responseQueueProcessing=!0;this.responseQueue.length;){if(this.messagesPerMin){let t=Ka/this.messagesPerMin,r=Date.now()-this.lastMessageDispatchedTime;t>r&&await(0,G.sleep)(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 s=-1;for(let c=r+1;c<t.length-1;c++)if(t[c]===28&&t[c+1]===13){s=c+1;break}if(s===-1)break;let o=t.subarray(r,s+1).subarray(1,-2),i=Ct.default.decode(o,this.encoding),a=G.Hl7Message.parse(i);e.push(a),r=s+1}return this.chunks=r<t.length?[t.subarray(r)]:[],e}send(e){this.sendImpl(e)}async sendAndWait(e,t){return new Promise((r,s)=>{let o=e.getSegment("MSH")?.getField(10)?.toString();if(!o){s(new G.OperationOutcomeError((0,G.validationError)("Required field missing: MSH.10")));return}let i;t?.timeoutMs&&(i=setTimeout(()=>{this.deletePendingMessage(o),s(new G.OperationOutcomeError({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.setPendingMessage(o,{message:e,resolve:r,reject:s,returnAck:t?.returnAck??G.ReturnAckCategory.APPLICATION,timer:i}),this.sendImpl(e)})}async close(){this.isClosed()||(this.closing=!0,this.socket.end(),this.drainPendingMessages(),await new Promise(e=>{let t=setTimeout(()=>{this.socket.destroy()},this.gracefulCloseTimeoutMs);this.socket.once("close",()=>{clearTimeout(t),e()})}))}drainPendingMessages(){if(!this.pendingMessages.size)return;let e=this.pendingMessages.size;for(let t of this.pendingMessages.values())t.timer&&clearTimeout(t.timer),t.reject(new G.OperationOutcomeError({resourceType:"OperationOutcome",issue:[{severity:"warning",code:"incomplete",details:{text:"Message was still pending when connection closed"}}]}));this.dispatchEvent(new Ue(new G.OperationOutcomeError({resourceType:"OperationOutcome",issue:[{severity:"warning",code:"incomplete",details:{text:"Messages were still pending when connection closed"},diagnostics:`Hl7Connection closed while ${e} messages were pending`}]}))),this.pendingMessages.clear()}appendData(e){this.chunks.push(e)}resetBuffer(){this.chunks=[]}setEncoding(e){this.encoding=e??pr}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}getPendingMessage(e){return this.pendingMessages.get(e)}setPendingMessage(e,t){this.pendingMessages.set(e,t)}deletePendingMessage(e){this.pendingMessages.delete(e)}},Ga=class extends Fs{constructor(e){super(),L(this,"options"),L(this,"host"),L(this,"port"),L(this,"encoding"),L(this,"connection"),L(this,"keepAlive"),L(this,"socket"),L(this,"connectTimeout"),L(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=(0,_s.connect)({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){(0,De.default)(this.socket);let t=this.socket,r=()=>{this.cleanupSocket(t);let s=new Error(`Connection timeout after ${this.connectTimeout}ms`);this.rejectDeferredPromise(e,s)};t.on("timeout",r)}registerSocketConnectListener(e){(0,De.default)(this.socket);let t=this.socket,r=()=>{if(t!==this.socket){this.cleanupSocket(t);return}let s;this.connection=s=this.createConnection(t,this.encoding),t.setTimeout(0),this.registerHl7ConnectionListeners(s),e.resolve(s)};t.on("connect",r)}registerSocketErrorListener(e){(0,De.default)(this.socket);let t=this.socket,r=s=>{this.cleanupSocket(t),s.constructor.name==="AggregateError"?this.rejectDeferredPromise(e,s.errors[0]):this.rejectDeferredPromise(e,s)};t.on("error",r)}registerSocketCloseListener(e){(0,De.default)(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 kt)}),e.addEventListener("error",t=>{this.dispatchEvent(new Ue(t.error))}),e.addEventListener("warning",t=>{this.dispatchEvent(new Lt(t.error))})}createDeferredConnectionPromise(){let e,t;return{promise:new Promise((r,s)=>{e=r,t=s}),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)}createConnection(e,t,r,s){return new Ws(e,t,r,s)}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 kt);this.socket&&(this.socket.removeAllListeners(),this.socket.destroy(),this.socket=void 0)}},Ja=1e4,Va=class{constructor(e){L(this,"handler"),L(this,"server"),L(this,"encoding"),L(this,"enhancedMode"),L(this,"messagesPerMin"),L(this,"connections",new Set),this.handler=e}async start(e,t,r,s){t&&this.setEncoding(t),r!==void 0&&this.setEnhancedMode(r),s?.messagesPerMin!==void 0&&this.setMessagesPerMin(s.messagesPerMin);let o=js.default.createServer(i=>{let a=new Ws(i,this.encoding,this.enhancedMode,{messagesPerMin:this.messagesPerMin});this.handler(a),this.connections.add(a),a.addEventListener("close",()=>{this.connections.delete(a)})});return new Promise((i,a)=>{let c=f=>{o.listen(f,()=>{let l=o.address().port;i(l)})},n=f=>{f?.code==="EADDRINUSE"?o.close(()=>(0,xs.sleep)(50).then(()=>c(e))):a(f)};o.on("error",n),o.once("listening",()=>{o.off("error",n)}),c(e),this.server=o})}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 s;e?.forceDrainTimeoutMs!==-1&&(s=setTimeout(()=>{for(let o of this.connections)o.close().catch(console.error)},e?.forceDrainTimeoutMs??Ja)),this.server.close(o=>{if(o){r(o);return}s&&clearTimeout(s),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}},Xa=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,s)=>{if(s.generateExample?r=qa():s.file&&(r=(0,Hs.readFileSync)(s.file,"utf8")),!r)throw new Error("Missing HL7 message body");let o=new Ga({host:e,port:Number.parseInt(t,10),encoding:s.encoding});try{let i=await o.sendAndWait(gt.Hl7Message.parse(r));console.log(i.toString().replaceAll("\r",`
|
|
15
15
|
`))}finally{await o.close()}}),za=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 Va(r=>{r.addEventListener("message",({message:s})=>{console.log(s.toString().replaceAll("\r",`
|
|
16
16
|
`)),r.send(s.buildAck())})}).start(Number.parseInt(e,10),t.encoding),console.log("Listening on port "+e)}),Yt=new R("hl7");P(Yt,Xa);P(Yt,za);function qa(){let e=(0,gt.formatHl7DateTime)(new Date),t=Date.now().toString();return`MSH|^~\\&|ADTSYS|HOSPITAL|RECEIVER|DEST|${e}||ADT^A01|${t}|P|2.5|
|
|
17
17
|
EVN|A01|${e}||
|