ocpp-ws-io 2.2.0 → 2.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- 'use strict';var events=require('events'),os=require('os'),ne=require('ws'),voltlogIo=require('voltlog-io'),wt=require('ajv'),_t=require('ajv-formats'),crypto=require('crypto'),qt=require('http'),https=require('https'),tls=require('tls'),net=require('net'),path=require('path'),worker_threads=require('worker_threads');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var ne__default=/*#__PURE__*/_interopDefault(ne);var wt__default=/*#__PURE__*/_interopDefault(wt);var _t__default=/*#__PURE__*/_interopDefault(_t);var qt__default=/*#__PURE__*/_interopDefault(qt);var rt=(s=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(s,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):s)(function(s){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+s+'" is not supported')});var ye=class{_channels=new Map;async publish(e,t){let i=this._channels.get(e);if(i)for(let n of i)try{n(t);}catch{}}async publishBatch(e){for(let t of e)await this.publish(t.channel,t.data);}async subscribe(e,t){this._channels.has(e)||this._channels.set(e,new Set),this._channels.get(e)?.add(t);}async unsubscribe(e){this._channels.delete(e);}async disconnect(){this._channels.clear(),this._presence.clear();}_presence=new Map;async setPresence(e,t,i){this._presence.set(e,t);}async getPresence(e){return this._presence.get(e)||null}async getPresenceBatch(e){return e.map(t=>this._presence.get(t)||null)}async removePresence(e){this._presence.delete(e);}async setPresenceBatch(e){for(let{identity:t,nodeId:i}of e)this._presence.set(t,i);}};function at(s){return s}var Te=class{_cluster;_subscriber;_handlers=new Map;constructor(e){try{let{createRequire:t}=rt("module"),n=t(__filename)("ioredis"),r=e.redisOptions??{};e.natMap&&(r.natMap=e.natMap),this._cluster=new n.Cluster(e.nodes.map(a=>({host:a.host,port:a.port})),{redisOptions:r}),this._subscriber=new n.Cluster(e.nodes.map(a=>({host:a.host,port:a.port})),{redisOptions:r}),this._subscriber.on("message",(a,o)=>{let d=this._handlers.get(a);d&&d(o);});}catch{throw new Error("ClusterDriver requires 'ioredis' as a peer dependency. Install it with: npm i ioredis")}}async publish(e,t){await this._cluster.publish(e,t);}async subscribe(e,t){this._handlers.set(e,t),await this._subscriber.subscribe(e);}async unsubscribe(e){await this._subscriber.unsubscribe(e),this._handlers.delete(e);}async set(e,t,i){i?await this._cluster.set(e,t,"EX",i):await this._cluster.set(e,t);}async get(e){return await this._cluster.get(e)||null}async mget(e){if(e.length===0)return [];try{return await this._cluster.mget(...e)}catch{return await Promise.all(e.map(t=>this.get(t)))}}async del(e){await this._cluster.del(e);}async xadd(e,t,i){let n=[];i&&n.push("MAXLEN","~",i.toString()),n.push("*");for(let[r,a]of Object.entries(t))n.push(r,a);return await this._cluster.xadd(e,...n)}async xaddBatch(e,t){if(e.length===0)return;let i=this._cluster.pipeline();for(let n of e){let r=[];t&&r.push("MAXLEN","~",t.toString()),r.push("*");for(let[a,o]of Object.entries(n.args))r.push(a,o);i.xadd(n.stream,...r);}await i.exec();}async xread(e,t,i){let n=[];t&&n.push("COUNT",t),typeof i=="number"&&n.push("BLOCK",i),n.push("STREAMS");for(let a of e)n.push(a.key);for(let a of e)n.push(a.id);let r=await this._cluster.xread(...n);return r?r.map(([a,o])=>({stream:a,messages:o.map(([d,p])=>{let c={};for(let l=0;l<p.length;l+=2)c[p[l]]=p[l+1];return {id:d,data:c}})})):null}async xlen(e){return await this._cluster.xlen(e)}async disconnect(){this._handlers.clear(),await Promise.allSettled([this._cluster.quit(),this._subscriber.quit()]);}async setPresenceBatch(e){if(e.length===0)return;let t=this._cluster.pipeline();for(let{key:i,value:n,ttlSeconds:r}of e)t.set(i,n,"EX",r);await t.exec();}async expire(e,t){await this._cluster.expire(e,t);}onError(e){return this._cluster.on("error",e),()=>this._cluster.removeListener("error",e)}onReconnect(e){return this._cluster.on("reconnecting",e),()=>this._cluster.removeListener("reconnecting",e)}};var ve=class{constructor(e,t,i){this.pub=e;this.sub=t;this.blocking=i;this.sub.on&&this.sub.on("message",(n,r)=>{let a=this._handlers.get(n);a&&a(r);});}_handlers=new Map;async publish(e,t){await this.pub.publish(e,t);}async subscribe(e,t){this._handlers.set(e,t),await this.sub.subscribe(e);}async unsubscribe(e){await this.sub.unsubscribe(e),this._handlers.delete(e);}async set(e,t,i){i?await this.pub.set(e,t,"EX",i):await this.pub.set(e,t);}async get(e){return await this.pub.get(e)||null}async mget(e){return e.length===0?[]:await this.pub.mget(...e)}async del(e){await this.pub.del(e);}async xadd(e,t,i){let n=[];i&&n.push("MAXLEN","~",i.toString()),n.push("*");for(let[r,a]of Object.entries(t))n.push(r,a);return await this.pub.xadd(e,...n)}async xaddBatch(e,t){if(e.length===0)return;let i=this.pub.pipeline();for(let n of e){let r=[];t&&r.push("MAXLEN","~",t.toString()),r.push("*");for(let[a,o]of Object.entries(n.args))r.push(a,o);i.xadd(n.stream,...r);}await i.exec();}async xread(e,t,i){let n=[];t&&n.push("COUNT",t),typeof i=="number"&&n.push("BLOCK",i),n.push("STREAMS"),e.forEach(o=>{n.push(o.key);}),e.forEach(o=>{n.push(o.id);});let a=await(i&&this.blocking?this.blocking:this.pub).xread(...n);return a?a.map(([o,d])=>({stream:o,messages:d.map(([p,c])=>{let l={};for(let m=0;m<c.length;m+=2)l[c[m]]=c[m+1];return {id:p,data:l}})})):null}async xlen(e){return await this.pub.xlen(e)}async disconnect(){this._handlers.clear();let e=async t=>{t.quit?await t.quit():t.disconnect&&await t.disconnect();};await Promise.all([e(this.pub),e(this.sub)]);}async setPresenceBatch(e){if(e.length===0)return;let t=this.pub.pipeline();for(let{key:i,value:n,ttlSeconds:r}of e)t.set(i,n,"EX",r);await t.exec();}async expire(e,t){await this.pub.expire(e,t);}onError(e){return this.pub.on("error",e),()=>this.pub.removeListener("error",e)}onReconnect(e){return this.pub.on("connect",e),()=>this.pub.removeListener("connect",e)}},Ce=class{constructor(e,t,i){this.pub=e;this.sub=t;this.blocking=i;}async publish(e,t){await this.pub.publish(e,t);}async subscribe(e,t){await this.sub.subscribe(e,t);}async unsubscribe(e){await this.sub.unsubscribe(e);}async set(e,t,i){i?await this.pub.set(e,t,{EX:i}):await this.pub.set(e,t);}async get(e){return await this.pub.get(e)||null}async mget(e){return e.length===0?[]:await this.pub.mGet(e)}async del(e){await this.pub.del(e);}async xadd(e,t,i){return await this.pub.xAdd(e,"*",t,{TRIM:i?{strategy:"MAXLEN",strategyModifier:"~",threshold:i}:void 0})}async xaddBatch(e,t){if(e.length===0)return;let i=this.pub.multi();for(let n of e)i.xAdd(n.stream,"*",n.args,{TRIM:t?{strategy:"MAXLEN",strategyModifier:"~",threshold:t}:void 0});await i.exec();}async xread(e,t,i){let n={};t&&(n.COUNT=t),typeof i=="number"&&(n.BLOCK=i);let r=e.map(d=>({key:d.key,id:d.id})),o=await(i&&this.blocking?this.blocking:this.pub).xRead(r,n);return !o||o.length===0?null:o.map(d=>({stream:d.name,messages:d.messages.map(p=>({id:p.id,data:p.message}))}))}async xlen(e){return await this.pub.xLen(e)}async disconnect(){await Promise.all([this.pub.disconnect(),this.sub.disconnect()]);}async setPresenceBatch(e){if(e.length===0)return;let t=this.pub.multi();for(let{key:i,value:n,ttlSeconds:r}of e)t.set(i,n,{EX:r});await t.exec();}async expire(e,t){await this.pub.expire(e,t);}onError(e){return this.pub.on("error",e),()=>this.pub.removeListener("error",e)}onReconnect(e){return this.pub.on("connect",e),()=>this.pub.removeListener("connect",e)}};function Ne(s,e,t){return e.isOpen!==void 0&&typeof e.subscribe=="function"?new Ce(s,e,t):new ve(s,e,t)}var be=class{_driver;_prefix;_streamMaxLen;_streamTtlSeconds;_presenceTtlSeconds;_handlers=new Map;_streamOffsets=new Map;_streams=new Set;_polling=false;_closed=false;_sequenceCounters=new Map;_unsubError;_unsubReconnect;_presenceCache=new Map;_driverPool;_nextPoolIndex;constructor(e){this._prefix=e.prefix??"ocpp-ws-io:",this._streamMaxLen=e.streamMaxLen??1e3,this._streamTtlSeconds=e.streamTtlSeconds??300,this._presenceTtlSeconds=e.presenceTtlSeconds??300,this._driver=Ne(e.pubClient,e.subClient,e.blockingClient);let t=e.poolSize??1;if(this._driverPool=[this._driver],this._nextPoolIndex=0,t>1&&e.driverFactory)for(let i=1;i<t;i++)this._driverPool.push(e.driverFactory());this._driver.onError&&(this._unsubError=this._driver.onError(i=>{console.error("[RedisAdapter] Redis error:",i.message);})),this._driver.onReconnect&&(this._unsubReconnect=this._driver.onReconnect(()=>{this._rehydratePresence().catch(()=>{});}));}_getPoolDriver(){if(this._driverPool.length===1)return this._driver;let e=this._driverPool[this._nextPoolIndex];return this._nextPoolIndex=(this._nextPoolIndex+1)%this._driverPool.length,e}async publish(e,t){let i=this._prefix+e,n=t;if(n&&typeof n=="object"&&e.startsWith("ocpp:node:")){let a=(this._sequenceCounters.get(e)??0)+1;this._sequenceCounters.set(e,a),n.__seq=a;}let r=JSON.stringify(t);if(e.startsWith("ocpp:node:")){let a=this._getPoolDriver();await a.xadd(i,{message:r},this._streamMaxLen),await a.expire(i,this._streamTtlSeconds).catch(()=>{});}else await this._getPoolDriver().publish(i,r);}async publishBatch(e){let t=[],i=[];for(let r of e){let a=this._prefix+r.channel,o=JSON.stringify(r.data);r.channel.startsWith("ocpp:node:")?t.push({stream:a,args:{message:o}}):i.push({channel:a,message:o});}let n=[];t.length>0&&n.push(this._getPoolDriver().xaddBatch(t,this._streamMaxLen)),i.length>0&&n.push(Promise.all(i.map(r=>this._getPoolDriver().publish(r.channel,r.message))).then(()=>{})),await Promise.all(n);}async subscribe(e,t){if(!this._handlers.has(e)){this._handlers.set(e,new Set);let i=this._prefix+e;e.startsWith("ocpp:node:")?this._streams.has(i)||(this._streams.add(i),this._streamOffsets.set(i,"0"),this._ensurePolling()):await this._driver.subscribe(i,n=>{this._handleMessage(e,n);});}this._handlers.get(e)?.add(t);}async unsubscribe(e){let t=this._prefix+e;this._streams.has(t)?(this._streams.delete(t),this._streamOffsets.delete(t)):await this._driver.unsubscribe(t),this._handlers.delete(e);}async disconnect(){this._closed=true,this._handlers.clear(),this._streams.clear(),this._presenceCache.clear(),this._sequenceCounters.clear(),this._unsubError&&this._unsubError(),this._unsubReconnect&&this._unsubReconnect(),await Promise.allSettled(this._driverPool.map(e=>e.disconnect()));}_handleMessage(e,t){let i=this._handlers.get(e);if(!i)return;let n;try{n=JSON.parse(t);}catch{n=t;}for(let r of i)try{r(n);}catch{}}_ensurePolling(){this._polling||this._closed||(this._polling=true,this._pollLoop().catch(()=>{this._polling=false;}));}async _pollLoop(){for(;!this._closed;){if(this._streams.size===0){await new Promise(t=>setTimeout(t,1e3));continue}let e=Array.from(this._streams).map(t=>({key:t,id:this._streamOffsets.get(t)||"$"}));try{let t=await this._driver.xread(e,void 0,1e3);if(t)for(let i of t){let n=i.stream.replace(this._prefix,"");for(let r of i.messages){this._streamOffsets.set(i.stream,r.id);let a=r.data.message;a&&this._handleMessage(n,a);}}}catch{await new Promise(i=>setTimeout(i,1e3));}}this._polling=false;}async setPresence(e,t,i){let n=`${this._prefix}presence:${e}`;this._presenceCache.set(e,{nodeId:t,ttl:i}),await this._driver.set(n,t,i);}async getPresence(e){let t=`${this._prefix}presence:${e}`;return await this._driver.get(t)}async getPresenceBatch(e){if(e.length===0)return [];let t=e.map(i=>`${this._prefix}presence:${i}`);return this._driver.mget?await this._driver.mget(t):await Promise.all(t.map(i=>this._driver.get(i)))}async removePresence(e){let t=`${this._prefix}presence:${e}`;await this._driver.del(t);}async metrics(){let e=0,t={};for(let i of this._streams)try{let n=await this._driver.xlen(i);e+=n,t[i]=n;}catch{t[i]=-1;}return {pendingMessages:e,activeStreams:this._streams.size,streamDetails:t}}async setPresenceBatch(e){if(e.length===0)return;let t=e.map(({identity:i,nodeId:n,ttl:r})=>{let a=`${this._prefix}presence:${i}`,o=r??this._presenceTtlSeconds;return this._presenceCache.set(i,{nodeId:n,ttl:o}),{key:a,value:n,ttlSeconds:o}});await this._driver.setPresenceBatch(t);}async _rehydratePresence(){if(this._presenceCache.size===0)return;let e=Array.from(this._presenceCache.entries()).map(([t,{nodeId:i,ttl:n}])=>({key:`${this._prefix}presence:${t}`,value:i,ttlSeconds:n}));await this._driver.setPresenceBatch(e);}};var W=class extends events.EventEmitter{_cpuThreshold;_memThreshold;_cooldownMs;_sampleInterval;_timer=null;_lastOverloadTime=0;_multiplier=1;_prevCpuUsage=null;_prevTimestamp=0;constructor(e={}){super(),this._cpuThreshold=e.cpuThresholdPercent??70,this._memThreshold=e.memThresholdPercent??85,this._cooldownMs=e.cooldownMs??1e4,this._sampleInterval=e.sampleIntervalMs??2e3;}get multiplier(){return this._multiplier}start(){this._timer||(this._prevCpuUsage=process.cpuUsage(),this._prevTimestamp=Date.now(),this._timer=setInterval(()=>this._sample(),this._sampleInterval),this._timer.unref&&this._timer.unref());}stop(){this._timer&&(clearInterval(this._timer),this._timer=null),this._multiplier=1;}_sample(){let e=Date.now(),t=process.cpuUsage(this._prevCpuUsage??void 0),i=e-this._prevTimestamp,n=(t.user+t.system)/1e3/i/os.cpus().length*100;this._prevCpuUsage=process.cpuUsage(),this._prevTimestamp=e;let r=os.totalmem(),a=os.freemem(),o=(r-a)/r*100,d=n>this._cpuThreshold,p=o>this._memThreshold,c=this._multiplier;d||p?(this._lastOverloadTime=e,this._multiplier=Math.max(.25,this._multiplier*.5)):e-this._lastOverloadTime>this._cooldownMs&&(this._multiplier=Math.min(1,this._multiplier+.1)),this._multiplier!==c&&this.emit("adapted",{multiplier:this._multiplier,cpuPercent:Math.round(n*100)/100,memPercent:Math.round(o*100)/100});}on(e,t){return super.on(e,t)}emit(e,t){return super.emit(e,t)}};var k=class extends Error{constructor(e="Operation timed out"){super(e),this.name="TimeoutError";}},H=class extends Error{statusCode;headers;constructor(e,t,i={}){super(e),this.name="UnexpectedHttpResponse",this.statusCode=t,this.headers=i;}},Pe=class extends Error{constructor(e="WebSocket upgrade failed"){super(e),this.name="WebsocketUpgradeError";}},v=class extends Error{rpcErrorCode="GenericError";rpcErrorMessage="";details;constructor(e,t={}){super(e),this.name="RPCGenericError",this.details=t;}},j=class extends v{rpcErrorCode="NotImplemented";rpcErrorMessage="Requested method is not known";constructor(e,t={}){super(e,t),this.name="RPCNotImplementedError";}},z=class extends v{rpcErrorCode="NotSupported";rpcErrorMessage="Requested method is recognised but not supported";constructor(e,t={}){super(e,t),this.name="RPCNotSupportedError";}},B=class extends v{rpcErrorCode="InternalError";rpcErrorMessage="An internal error occurred and the receiver was not able to process the requested action successfully";constructor(e,t={}){super(e,t),this.name="RPCInternalError";}},G=class extends v{rpcErrorCode="ProtocolError";rpcErrorMessage="Payload for action is incomplete";constructor(e,t={}){super(e,t),this.name="RPCProtocolError";}},J=class extends v{rpcErrorCode="SecurityError";rpcErrorMessage="During the processing of action a security issue occurred preventing receiver from completing the action successfully";constructor(e,t={}){super(e,t),this.name="RPCSecurityError";}},K=class extends v{rpcErrorCode="FormationViolation";rpcErrorMessage="Payload for action is syntactically incorrect or not conform the PDU structure for action";constructor(e,t={}){super(e,t),this.name="RPCFormationViolationError";}},X=class extends v{rpcErrorCode="FormatViolation";rpcErrorMessage="Payload is syntactically correct but at least one field contains an invalid value";constructor(e,t={}){super(e,t),this.name="RPCFormatViolationError";}},Q=class extends v{rpcErrorCode="PropertyConstraintViolation";rpcErrorMessage="Payload is syntactically correct but at least one of the fields violates data type constraints";constructor(e,t={}){super(e,t),this.name="RPCPropertyConstraintViolationError";}},Y=class extends v{rpcErrorCode="OccurrenceConstraintViolation";rpcErrorMessage="Payload for action is syntactically correct but at least one of the fields violates occurrence constraints";constructor(e,t={}){super(e,t),this.name="RPCOccurrenceConstraintViolationError";}},Z=class extends v{rpcErrorCode="TypeConstraintViolation";rpcErrorMessage="Payload for action is syntactically correct but at least one of the fields violates type constraints";constructor(e,t={}){super(e,t),this.name="RPCTypeConstraintViolationError";}},_=class extends v{rpcErrorCode="MessageTypeNotSupported";rpcErrorMessage="A message with a Message Type Number received that is not supported by this implementation";constructor(e,t={}){super(e,t),this.name="RPCMessageTypeNotSupportedError";}},ee=class extends v{rpcErrorCode="RpcFrameworkError";rpcErrorMessage="Content of the call is not a valid RPC request";constructor(e,t={}){super(e,t),this.name="RPCFrameworkError";}};function lt(s){return s}function ut(s){return s}function mt(s){return s}function ht(s){return s}function ft(...s){return async e=>{let t=false,i=false,n=o=>{t=true,e.accept(o);},r=(o,d)=>(i=true,e.reject(o,d)),a={...e,accept:n,reject:r};try{for(let o of s){if(e.signal.aborted||t||i)break;let d=o(a);if(d instanceof Promise&&await d,t||i)break}!t&&!i&&r(401,"Unauthorized (All composeAuth handlers passed without accepting)");}catch{i||r(500,"Internal Server Error during auth compose execution");}}}function Se(s,e,t={}){let i=typeof t=="object"?t:{},{exchangeLog:n=false,prettify:r=false}=i;return async(a,o)=>{let d=Date.now(),p=a.method,c=n?"info":"debug";switch(a.type){case "incoming_call":n&&r?s[c]?.(`\u26A1 ${e} \u2190 ${p} [IN]`,{messageId:a.messageId,method:a.method,protocol:a.protocol,payload:a.params,direction:"IN"}):s[c]?.("CALL \u2190",{messageId:a.messageId,method:a.method,protocol:a.protocol,payload:a.params,direction:"IN"});break;case "outgoing_call":n&&r?s[c]?.(`\u26A1 ${e} \u2192 ${p} [OUT]`,{method:a.method,params:a.params,direction:"OUT"}):s[c]?.("CALL \u2192",{method:a.method,params:a.params,direction:"OUT"});break}try{let l=await o(),m=Date.now()-d;switch(a.type){case "incoming_call":l!=null&&(n&&r?s[c]?.(`\u2705 ${e} \u2192 ${p} [RES]`,{messageId:a.messageId,method:a.method,durationMs:m,params:l,direction:"OUT"}):s[c]?.("CALLRESULT \u2192",{messageId:a.messageId,method:a.method,durationMs:m,params:l,direction:"OUT"}));break;case "outgoing_call":n&&r?s[c]?.(`\u2705 ${e} \u2190 ${p} [RES]`,{messageId:a.messageId,method:a.method,durationMs:m,payload:l,direction:"IN"}):s[c]?.("CALLRESULT \u2190",{messageId:a.messageId,method:a.method,durationMs:m,payload:l,direction:"IN"});break}return l}catch(l){let m=l.message,h=Date.now()-d;throw a.type==="incoming_call"?n&&r?s.error?.(`\u{1F6A8} ${e} \u2192 ${p} [ERR]`,{messageId:a.messageId,method:a.method,durationMs:h,error:m,direction:"OUT"}):s.error?.("CALLERROR \u2192",{messageId:a.messageId,method:a.method,durationMs:h,error:m,direction:"OUT"}):a.type==="outgoing_call"&&(n&&r?s.warn?.(`\u{1F6A8} ${e} \u2190 ${p} [ERR]`,{messageId:a.messageId,method:a.method,durationMs:h,error:m,direction:"IN"}):s.warn?.("CALLERROR \u2190",{messageId:a.messageId,method:a.method,durationMs:h,error:m,direction:"IN"})),l}}}function vt(s){return s.showMetadata===false||s.showSourceMeta===false||s.prettifySource===true||s.prettifyMetadata===true}function Ct(s){let e=s.showMetadata??true,t=s.showSourceMeta??true,i=s.prettifySource??false,n=s.prettifyMetadata??false,r="\x1B[2;37m",a="\x1B[0m",o="\x1B[36m";return (d,p)=>{if(!t)d.context=void 0;else if(i&&d.context){let l=[];d.context.component&&l.push(String(d.context.component)),d.context.identity&&l.push(String(d.context.identity)),l.length>0&&(d.message=`${r}[${l.join("/")}]${a} ${d.message}`,d.context=void 0);}let c=d.meta;if(!e)d.meta={};else if(n&&c&&Object.keys(c).length>0){let l=Object.entries(c).filter(([,m])=>m!=null).map(([m,h])=>{let E=typeof h=="object"?JSON.stringify(h):String(h);return typeof h=="string"?E=`${r}${E}${a}`:E=`${r}${E}${a}`,`${o}${m}${a}=${E}`}).join(" ");l&&(d.message=`${d.message} ${l}`),d.meta={};}p(d);}}function de(s,e){if(s===false||s?.enabled===false)return null;if(s?.logger)return e&&s.logger.child?s.logger.child(e):s.logger;let t=s?.level??"INFO",n=s?.prettify??false?[voltlogIo.prettyTransport({level:t})]:[voltlogIo.consoleTransport({level:t})];if(s?.handler){let o=s.handler;n.push({name:"customHandler",write:d=>o(d)});}let r=[];s&&vt(s)&&r.push(Ct(s));let a=voltlogIo.createLogger({level:t,transports:n,middleware:r.length>0?r:void 0});return e&&Object.keys(e).length>0?a.child(e):a}var pe=class{_stack=[];use(e){this._stack.push(e);}async execute(e,t){let i=-1,n=async r=>{if(r<=i)throw new Error("next() called multiple times");i=r;let a=this._stack[r];if(r===this._stack.length)return t(e);if(a)return a(e,()=>n(r+1))};return n(0)}};var ce=class{_concurrency;_running=0;_queue=[];constructor(e=1){this._concurrency=Math.max(1,e);}get concurrency(){return this._concurrency}get pending(){return this._queue.length}get running(){return this._running}get size(){return this._running+this._queue.length}setConcurrency(e){this._concurrency=Math.max(1,e),this._drain();}push(e){return new Promise((t,i)=>{this._queue.push({fn:e,resolve:t,reject:i}),this._drain();})}_drain(){for(;this._running<this._concurrency&&this._queue.length>0;){let e=this._queue.shift();this._running++,e?.fn().then(e.resolve).catch(e.reject).finally(()=>{this._running--,this._drain();});}}};var ke=[{$id:"urn:Authorize.req",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{idTag:{type:"string",maxLength:20}},required:["idTag"],type:"object"},{$id:"urn:Authorize.conf",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{idTagInfo:{type:"object",properties:{expiryDate:{type:"string",format:"date-time"},parentIdTag:{type:"string",maxLength:20},status:{type:"string",enum:["Accepted","Blocked","Expired","Invalid","ConcurrentTx"]}},additionalProperties:false,required:["status"]}},required:["idTagInfo"],type:"object"},{$id:"urn:BootNotification.req",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{chargePointVendor:{type:"string",maxLength:20},chargePointModel:{type:"string",maxLength:20},chargePointSerialNumber:{type:"string",maxLength:25},chargeBoxSerialNumber:{type:"string",maxLength:25},firmwareVersion:{type:"string",maxLength:50},iccid:{type:"string",maxLength:20},imsi:{type:"string",maxLength:20},meterType:{type:"string",maxLength:25},meterSerialNumber:{type:"string",maxLength:25}},required:["chargePointVendor","chargePointModel"],type:"object"},{$id:"urn:BootNotification.conf",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{status:{type:"string",enum:["Accepted","Pending","Rejected"]},currentTime:{type:"string",format:"date-time"},interval:{type:"integer"}},required:["status","currentTime","interval"],type:"object"},{$id:"urn:CancelReservation.req",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{reservationId:{type:"integer"}},required:["reservationId"],type:"object"},{$id:"urn:CancelReservation.conf",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{status:{type:"string",enum:["Accepted","Rejected"]}},required:["status"],type:"object"},{$id:"urn:CertificateSigned.req",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{certificateChain:{type:"string",maxLength:1e4}},required:["certificateChain"],type:"object"},{$id:"urn:CertificateSigned.conf",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,definitions:{CertificateSignedStatusEnumType:{type:"string",enum:["Accepted","Rejected"]}},properties:{status:{$ref:"#/definitions/CertificateSignedStatusEnumType"}},required:["status"],type:"object"},{$id:"urn:ChangeAvailability.req",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{connectorId:{type:"integer"},type:{type:"string",enum:["Inoperative","Operative"]}},required:["connectorId","type"],type:"object"},{$id:"urn:ChangeAvailability.conf",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{status:{type:"string",enum:["Accepted","Rejected","Scheduled"]}},required:["status"],type:"object"},{$id:"urn:ChangeConfiguration.req",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{key:{type:"string",maxLength:50},value:{type:"string",maxLength:500}},required:["key","value"],type:"object"},{$id:"urn:ChangeConfiguration.conf",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{status:{type:"string",enum:["Accepted","Rejected","RebootRequired","NotSupported"]}},required:["status"],type:"object"},{$id:"urn:ClearCache.req",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{},type:"object"},{$id:"urn:ClearCache.conf",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{status:{type:"string",enum:["Accepted","Rejected"]}},required:["status"],type:"object"},{$id:"urn:ClearChargingProfile.req",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{id:{type:"integer"},connectorId:{type:"integer"},chargingProfilePurpose:{type:"string",enum:["ChargePointMaxProfile","TxDefaultProfile","TxProfile"]},stackLevel:{type:"integer"}},type:"object"},{$id:"urn:ClearChargingProfile.conf",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{status:{type:"string",enum:["Accepted","Unknown"]}},required:["status"],type:"object"},{$id:"urn:DataTransfer.req",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{vendorId:{type:"string",maxLength:255},messageId:{type:"string",maxLength:50},data:{type:"string"}},required:["vendorId"],type:"object"},{$id:"urn:DataTransfer.conf",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{status:{type:"string",enum:["Accepted","Rejected","UnknownMessageId","UnknownVendorId"]},data:{type:"string"}},required:["status"],type:"object"},{$id:"urn:DeleteCertificate.req",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,definitions:{HashAlgorithmEnumType:{type:"string",enum:["SHA256","SHA384","SHA512"]},CertificateHashDataType:{type:"object",additionalProperties:false,properties:{hashAlgorithm:{$ref:"#/definitions/HashAlgorithmEnumType"},issuerNameHash:{type:"string",maxLength:128},issuerKeyHash:{type:"string",maxLength:128},serialNumber:{type:"string",maxLength:40}},required:["hashAlgorithm","issuerNameHash","issuerKeyHash","serialNumber"]}},properties:{certificateHashData:{$ref:"#/definitions/CertificateHashDataType"}},required:["certificateHashData"],type:"object"},{$id:"urn:DeleteCertificate.conf",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,definitions:{DeleteCertificateStatusEnumType:{type:"string",enum:["Accepted","Failed","NotFound"]}},properties:{status:{$ref:"#/definitions/DeleteCertificateStatusEnumType"}},required:["status"],type:"object"},{$id:"urn:DiagnosticsStatusNotification.req",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{status:{type:"string",enum:["Idle","Uploaded","UploadFailed","Uploading"]}},required:["status"],type:"object"},{$id:"urn:DiagnosticsStatusNotification.conf",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{},type:"object"},{$id:"urn:ExtendedTriggerMessage.req",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,definitions:{MessageTriggerEnumType:{type:"string",enum:["BootNotification","LogStatusNotification","FirmwareStatusNotification","Heartbeat","MeterValues","SignChargePointCertificate","StatusNotification"]}},properties:{requestedMessage:{$ref:"#/definitions/MessageTriggerEnumType"},connectorId:{type:"integer"}},required:["requestedMessage"],type:"object"},{$id:"urn:ExtendedTriggerMessage.conf",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,definitions:{TriggerMessageStatusEnumType:{type:"string",enum:["Accepted","Rejected","NotImplemented"]}},properties:{status:{$ref:"#/definitions/TriggerMessageStatusEnumType"}},required:["status"],type:"object"},{$id:"urn:FirmwareStatusNotification.req",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{status:{type:"string",enum:["Downloaded","DownloadFailed","Downloading","Idle","InstallationFailed","Installing","Installed"]}},required:["status"],type:"object"},{$id:"urn:FirmwareStatusNotification.conf",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{},type:"object"},{$id:"urn:GetCompositeSchedule.req",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{connectorId:{type:"integer"},duration:{type:"integer"},chargingRateUnit:{type:"string",enum:["A","W"]}},required:["connectorId","duration"],type:"object"},{$id:"urn:GetCompositeSchedule.conf",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{status:{type:"string",enum:["Accepted","Rejected"]},connectorId:{type:"integer"},scheduleStart:{type:"string",format:"date-time"},chargingSchedule:{type:"object",properties:{duration:{type:"integer"},startSchedule:{type:"string",format:"date-time"},chargingRateUnit:{type:"string",enum:["A","W"]},chargingSchedulePeriod:{type:"array",items:{type:"object",properties:{startPeriod:{type:"integer"},limit:{type:"number",multipleOf:.1},numberPhases:{type:"integer"}},additionalProperties:false,required:["startPeriod","limit"]}},minChargingRate:{type:"number",multipleOf:.1}},additionalProperties:false,required:["chargingRateUnit","chargingSchedulePeriod"]}},required:["status"],type:"object"},{$id:"urn:GetConfiguration.req",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{key:{type:"array",items:{type:"string",maxLength:50}}},type:"object"},{$id:"urn:GetConfiguration.conf",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{configurationKey:{type:"array",items:{type:"object",properties:{key:{type:"string",maxLength:50},readonly:{type:"boolean"},value:{type:"string",maxLength:500}},additionalProperties:false,required:["key","readonly"]}},unknownKey:{type:"array",items:{type:"string",maxLength:50}}},type:"object"},{$id:"urn:GetDiagnostics.req",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{location:{type:"string",format:"uri"},retries:{type:"integer"},retryInterval:{type:"integer"},startTime:{type:"string",format:"date-time"},stopTime:{type:"string",format:"date-time"}},required:["location"],type:"object"},{$id:"urn:GetDiagnostics.conf",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{fileName:{type:"string",maxLength:255}},type:"object"},{$id:"urn:GetInstalledCertificateIds.req",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,definitions:{CertificateUseEnumType:{type:"string",enum:["CentralSystemRootCertificate","ManufacturerRootCertificate"]}},properties:{certificateType:{$ref:"#/definitions/CertificateUseEnumType"}},required:["certificateType"],type:"object"},{$id:"urn:GetInstalledCertificateIds.conf",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,definitions:{GetInstalledCertificateStatusEnumType:{type:"string",enum:["Accepted","NotFound"]},HashAlgorithmEnumType:{type:"string",enum:["SHA256","SHA384","SHA512"]},CertificateHashDataType:{type:"object",additionalProperties:false,properties:{hashAlgorithm:{$ref:"#/definitions/HashAlgorithmEnumType"},issuerNameHash:{type:"string",maxLength:128},issuerKeyHash:{type:"string",maxLength:128},serialNumber:{type:"string",maxLength:40}},required:["hashAlgorithm","issuerNameHash","issuerKeyHash","serialNumber"]}},properties:{certificateHashData:{type:"array",items:{$ref:"#/definitions/CertificateHashDataType"},minItems:1},status:{$ref:"#/definitions/GetInstalledCertificateStatusEnumType"}},required:["status"],type:"object"},{$id:"urn:GetLocalListVersion.req",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{},type:"object"},{$id:"urn:GetLocalListVersion.conf",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{listVersion:{type:"integer"}},required:["listVersion"],type:"object"},{$id:"urn:GetLog.req",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,definitions:{LogEnumType:{type:"string",enum:["DiagnosticsLog","SecurityLog"]},LogParametersType:{type:"object",additionalProperties:false,properties:{remoteLocation:{type:"string",maxLength:512},oldestTimestamp:{type:"string",format:"date-time"},latestTimestamp:{type:"string",format:"date-time"}},required:["remoteLocation"]}},properties:{log:{$ref:"#/definitions/LogParametersType"},logType:{$ref:"#/definitions/LogEnumType"},requestId:{type:"integer"},retries:{type:"integer"},retryInterval:{type:"integer"}},required:["logType","requestId","log"],type:"object"},{$id:"urn:GetLog.conf",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,definitions:{LogStatusEnumType:{type:"string",enum:["Accepted","Rejected","AcceptedCanceled"]}},properties:{status:{$ref:"#/definitions/LogStatusEnumType"},filename:{type:"string",maxLength:255}},required:["status"],type:"object"},{$id:"urn:Heartbeat.req",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{},type:"object"},{$id:"urn:Heartbeat.conf",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{currentTime:{type:"string",format:"date-time"}},required:["currentTime"],type:"object"},{$id:"urn:InstallCertificate.req",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,definitions:{CertificateUseEnumType:{type:"string",enum:["CentralSystemRootCertificate","ManufacturerRootCertificate"]}},properties:{certificateType:{$ref:"#/definitions/CertificateUseEnumType"},certificate:{type:"string",maxLength:5500}},required:["certificateType","certificate"],type:"object"},{$id:"urn:InstallCertificate.conf",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,definitions:{InstallCertificateStatusEnumType:{type:"string",enum:["Accepted","Failed","Rejected"]}},properties:{status:{$ref:"#/definitions/InstallCertificateStatusEnumType"}},required:["status"],type:"object"},{$id:"urn:LogStatusNotification.req",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,definitions:{UploadLogStatusEnumType:{type:"string",enum:["BadMessage","Idle","NotSupportedOperation","PermissionDenied","Uploaded","UploadFailure","Uploading"]}},properties:{status:{$ref:"#/definitions/UploadLogStatusEnumType"},requestId:{type:"integer"}},required:["status"],type:"object"},{$id:"urn:LogStatusNotification.conf",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,type:"object"},{$id:"urn:MeterValues.req",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{connectorId:{type:"integer"},transactionId:{type:"integer"},meterValue:{type:"array",items:{type:"object",properties:{timestamp:{type:"string",format:"date-time"},sampledValue:{type:"array",items:{type:"object",properties:{value:{type:"string"},context:{type:"string",enum:["Interruption.Begin","Interruption.End","Sample.Clock","Sample.Periodic","Transaction.Begin","Transaction.End","Trigger","Other"]},format:{type:"string",enum:["Raw","SignedData"]},measurand:{type:"string",enum:["Energy.Active.Export.Register","Energy.Active.Import.Register","Energy.Reactive.Export.Register","Energy.Reactive.Import.Register","Energy.Active.Export.Interval","Energy.Active.Import.Interval","Energy.Reactive.Export.Interval","Energy.Reactive.Import.Interval","Power.Active.Export","Power.Active.Import","Power.Offered","Power.Reactive.Export","Power.Reactive.Import","Power.Factor","Current.Import","Current.Export","Current.Offered","Voltage","Frequency","Temperature","SoC","RPM"]},phase:{type:"string",enum:["L1","L2","L3","N","L1-N","L2-N","L3-N","L1-L2","L2-L3","L3-L1"]},location:{type:"string",enum:["Cable","EV","Inlet","Outlet","Body"]},unit:{type:"string",enum:["Wh","kWh","varh","kvarh","W","kW","VA","kVA","var","kvar","A","V","K","Celcius","Celsius","Fahrenheit","Percent"]}},additionalProperties:false,required:["value"]}}},additionalProperties:false,required:["timestamp","sampledValue"]}}},required:["connectorId","meterValue"],type:"object"},{$id:"urn:MeterValues.conf",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{},type:"object"},{$id:"urn:RemoteStartTransaction.req",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{connectorId:{type:"integer"},idTag:{type:"string",maxLength:20},chargingProfile:{type:"object",properties:{chargingProfileId:{type:"integer"},transactionId:{type:"integer"},stackLevel:{type:"integer"},chargingProfilePurpose:{type:"string",enum:["ChargePointMaxProfile","TxDefaultProfile","TxProfile"]},chargingProfileKind:{type:"string",enum:["Absolute","Recurring","Relative"]},recurrencyKind:{type:"string",enum:["Daily","Weekly"]},validFrom:{type:"string",format:"date-time"},validTo:{type:"string",format:"date-time"},chargingSchedule:{type:"object",properties:{duration:{type:"integer"},startSchedule:{type:"string",format:"date-time"},chargingRateUnit:{type:"string",enum:["A","W"]},chargingSchedulePeriod:{type:"array",items:{type:"object",properties:{startPeriod:{type:"integer"},limit:{type:"number",multipleOf:.1},numberPhases:{type:"integer"}},additionalProperties:false,required:["startPeriod","limit"]}},minChargingRate:{type:"number",multipleOf:.1}},additionalProperties:false,required:["chargingRateUnit","chargingSchedulePeriod"]}},additionalProperties:false,required:["chargingProfileId","stackLevel","chargingProfilePurpose","chargingProfileKind","chargingSchedule"]}},required:["idTag"],type:"object"},{$id:"urn:RemoteStartTransaction.conf",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{status:{type:"string",enum:["Accepted","Rejected"]}},required:["status"],type:"object"},{$id:"urn:RemoteStopTransaction.req",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{transactionId:{type:"integer"}},required:["transactionId"],type:"object"},{$id:"urn:RemoteStopTransaction.conf",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{status:{type:"string",enum:["Accepted","Rejected"]}},required:["status"],type:"object"},{$id:"urn:ReserveNow.req",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{connectorId:{type:"integer"},expiryDate:{type:"string",format:"date-time"},idTag:{type:"string",maxLength:20},parentIdTag:{type:"string",maxLength:20},reservationId:{type:"integer"}},required:["connectorId","expiryDate","idTag","reservationId"],type:"object"},{$id:"urn:ReserveNow.conf",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{status:{type:"string",enum:["Accepted","Faulted","Occupied","Rejected","Unavailable"]}},required:["status"],type:"object"},{$id:"urn:Reset.req",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{type:{type:"string",enum:["Hard","Soft"]}},required:["type"],type:"object"},{$id:"urn:Reset.conf",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{status:{type:"string",enum:["Accepted","Rejected"]}},required:["status"],type:"object"},{$id:"urn:SecurityEventNotification.req",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{type:{type:"string",maxLength:50},timestamp:{type:"string",format:"date-time"},techInfo:{type:"string",maxLength:255}},required:["type","timestamp"],type:"object"},{$id:"urn:SecurityEventNotification.conf",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,type:"object"},{$id:"urn:SendLocalList.req",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{listVersion:{type:"integer"},localAuthorizationList:{type:"array",items:{type:"object",properties:{idTag:{type:"string",maxLength:20},idTagInfo:{type:"object",properties:{expiryDate:{type:"string",format:"date-time"},parentIdTag:{type:"string",maxLength:20},status:{type:"string",enum:["Accepted","Blocked","Expired","Invalid","ConcurrentTx"]}},additionalProperties:false,required:["status"]}},additionalProperties:false,required:["idTag"]}},updateType:{type:"string",enum:["Differential","Full"]}},required:["listVersion","updateType"],type:"object"},{$id:"urn:SendLocalList.conf",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{status:{type:"string",enum:["Accepted","Failed","NotSupported","VersionMismatch"]}},required:["status"],type:"object"},{$id:"urn:SetChargingProfile.req",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{connectorId:{type:"integer"},csChargingProfiles:{type:"object",properties:{chargingProfileId:{type:"integer"},transactionId:{type:"integer"},stackLevel:{type:"integer"},chargingProfilePurpose:{type:"string",enum:["ChargePointMaxProfile","TxDefaultProfile","TxProfile"]},chargingProfileKind:{type:"string",enum:["Absolute","Recurring","Relative"]},recurrencyKind:{type:"string",enum:["Daily","Weekly"]},validFrom:{type:"string",format:"date-time"},validTo:{type:"string",format:"date-time"},chargingSchedule:{type:"object",properties:{duration:{type:"integer"},startSchedule:{type:"string",format:"date-time"},chargingRateUnit:{type:"string",enum:["A","W"]},chargingSchedulePeriod:{type:"array",items:{type:"object",properties:{startPeriod:{type:"integer"},limit:{type:"number",multipleOf:.1},numberPhases:{type:"integer"}},additionalProperties:false,required:["startPeriod","limit"]}},minChargingRate:{type:"number",multipleOf:.1}},additionalProperties:false,required:["chargingRateUnit","chargingSchedulePeriod"]}},additionalProperties:false,required:["chargingProfileId","stackLevel","chargingProfilePurpose","chargingProfileKind","chargingSchedule"]}},required:["connectorId","csChargingProfiles"],type:"object"},{$id:"urn:SetChargingProfile.conf",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{status:{type:"string",enum:["Accepted","Rejected","NotSupported"]}},required:["status"],type:"object"},{$id:"urn:SignCertificate.req",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{csr:{type:"string",maxLength:5500}},required:["csr"],type:"object"},{$id:"urn:SignCertificate.conf",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,definitions:{GenericStatusEnumType:{type:"string",enum:["Accepted","Rejected"]}},properties:{status:{$ref:"#/definitions/GenericStatusEnumType"}},required:["status"],type:"object"},{$id:"urn:SignedFirmwareStatusNotification.req",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,definitions:{FirmwareStatusEnumType:{type:"string",enum:["Downloaded","DownloadFailed","Downloading","DownloadScheduled","DownloadPaused","Idle","InstallationFailed","Installing","Installed","InstallRebooting","InstallScheduled","InstallVerificationFailed","InvalidSignature","SignatureVerified"]}},properties:{status:{$ref:"#/definitions/FirmwareStatusEnumType"},requestId:{type:"integer"}},required:["status"],type:"object"},{$id:"urn:SignedFirmwareStatusNotification.conf",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,type:"object"},{$id:"urn:SignedUpdateFirmware.req",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,definitions:{FirmwareType:{type:"object",additionalProperties:false,properties:{location:{type:"string",maxLength:512},retrieveDateTime:{type:"string",format:"date-time"},installDateTime:{type:"string",format:"date-time"},signingCertificate:{type:"string",maxLength:5500},signature:{type:"string",maxLength:800}},required:["location","retrieveDateTime","signingCertificate","signature"]}},properties:{retries:{type:"integer"},retryInterval:{type:"integer"},requestId:{type:"integer"},firmware:{$ref:"#/definitions/FirmwareType"}},required:["requestId","firmware"],type:"object"},{$id:"urn:SignedUpdateFirmware.conf",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,definitions:{UpdateFirmwareStatusEnumType:{type:"string",enum:["Accepted","Rejected","AcceptedCanceled","InvalidCertificate","RevokedCertificate"]}},properties:{status:{$ref:"#/definitions/UpdateFirmwareStatusEnumType"}},required:["status"],type:"object"},{$id:"urn:StartTransaction.req",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{connectorId:{type:"integer"},idTag:{type:"string",maxLength:20},meterStart:{type:"integer"},reservationId:{type:"integer"},timestamp:{type:"string",format:"date-time"}},required:["connectorId","idTag","meterStart","timestamp"],type:"object"},{$id:"urn:StartTransaction.conf",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{idTagInfo:{type:"object",properties:{expiryDate:{type:"string",format:"date-time"},parentIdTag:{type:"string",maxLength:20},status:{type:"string",enum:["Accepted","Blocked","Expired","Invalid","ConcurrentTx"]}},additionalProperties:false,required:["status"]},transactionId:{type:"integer"}},required:["idTagInfo","transactionId"],type:"object"},{$id:"urn:StatusNotification.req",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{connectorId:{type:"integer"},errorCode:{type:"string",enum:["ConnectorLockFailure","EVCommunicationError","GroundFailure","HighTemperature","InternalError","LocalListConflict","NoError","OtherError","OverCurrentFailure","PowerMeterFailure","PowerSwitchFailure","ReaderFailure","ResetFailure","UnderVoltage","OverVoltage","WeakSignal"]},info:{type:"string",maxLength:50},status:{type:"string",enum:["Available","Preparing","Charging","SuspendedEVSE","SuspendedEV","Finishing","Reserved","Unavailable","Faulted"]},timestamp:{type:"string",format:"date-time"},vendorId:{type:"string",maxLength:255},vendorErrorCode:{type:"string",maxLength:50}},required:["connectorId","errorCode","status"],type:"object"},{$id:"urn:StatusNotification.conf",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{},type:"object"},{$id:"urn:StopTransaction.req",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{idTag:{type:"string",maxLength:20},meterStop:{type:"integer"},timestamp:{type:"string",format:"date-time"},transactionId:{type:"integer"},reason:{type:"string",enum:["EmergencyStop","EVDisconnected","HardReset","Local","Other","PowerLoss","Reboot","Remote","SoftReset","UnlockCommand","DeAuthorized"]},transactionData:{type:"array",items:{type:"object",properties:{timestamp:{type:"string",format:"date-time"},sampledValue:{type:"array",items:{type:"object",properties:{value:{type:"string"},context:{type:"string",enum:["Interruption.Begin","Interruption.End","Sample.Clock","Sample.Periodic","Transaction.Begin","Transaction.End","Trigger","Other"]},format:{type:"string",enum:["Raw","SignedData"]},measurand:{type:"string",enum:["Energy.Active.Export.Register","Energy.Active.Import.Register","Energy.Reactive.Export.Register","Energy.Reactive.Import.Register","Energy.Active.Export.Interval","Energy.Active.Import.Interval","Energy.Reactive.Export.Interval","Energy.Reactive.Import.Interval","Power.Active.Export","Power.Active.Import","Power.Offered","Power.Reactive.Export","Power.Reactive.Import","Power.Factor","Current.Import","Current.Export","Current.Offered","Voltage","Frequency","Temperature","SoC","RPM"]},phase:{type:"string",enum:["L1","L2","L3","N","L1-N","L2-N","L3-N","L1-L2","L2-L3","L3-L1"]},location:{type:"string",enum:["Cable","EV","Inlet","Outlet","Body"]},unit:{type:"string",enum:["Wh","kWh","varh","kvarh","W","kW","VA","kVA","var","kvar","A","V","K","Celcius","Celsius","Fahrenheit","Percent"]}},additionalProperties:false,required:["value"]}}},additionalProperties:false,required:["timestamp","sampledValue"]}}},required:["transactionId","timestamp","meterStop"],type:"object"},{$id:"urn:StopTransaction.conf",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{idTagInfo:{type:"object",properties:{expiryDate:{type:"string",format:"date-time"},parentIdTag:{type:"string",maxLength:20},status:{type:"string",enum:["Accepted","Blocked","Expired","Invalid","ConcurrentTx"]}},additionalProperties:false,required:["status"]}},type:"object"},{$id:"urn:TriggerMessage.req",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{requestedMessage:{type:"string",enum:["BootNotification","DiagnosticsStatusNotification","FirmwareStatusNotification","Heartbeat","MeterValues","StatusNotification"]},connectorId:{type:"integer"}},required:["requestedMessage"],type:"object"},{$id:"urn:TriggerMessage.conf",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{status:{type:"string",enum:["Accepted","Rejected","NotImplemented"]}},required:["status"],type:"object"},{$id:"urn:UnlockConnector.req",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{connectorId:{type:"integer"}},required:["connectorId"],type:"object"},{$id:"urn:UnlockConnector.conf",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{status:{type:"string",enum:["Unlocked","UnlockFailed","NotSupported"]}},required:["status"],type:"object"},{$id:"urn:UpdateFirmware.req",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{location:{type:"string",format:"uri"},retries:{type:"integer"},retrieveDate:{type:"string",format:"date-time"},retryInterval:{type:"integer"}},required:["location","retrieveDate"],type:"object"},{$id:"urn:UpdateFirmware.conf",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{},type:"object"}];var Fe=[{$id:"urn:Authorize.req",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,definitions:{CustomDataType:{description:"This class does not get 'AdditionalProperties = false' in the schema generation, so it can be extended with arbitrary JSON properties to allow adding custom data.",type:"object",properties:{vendorId:{type:"string",maxLength:255}},required:["vendorId"]},HashAlgorithmEnumType:{description:`Used algorithms for the hashes provided.\r
1
+ 'use strict';var events=require('events'),os=require('os'),ae=require('ws'),voltlogIo=require('voltlog-io'),wt=require('ajv'),_t=require('ajv-formats'),crypto=require('crypto'),qt=require('http'),https=require('https'),tls=require('tls'),net=require('net'),path=require('path'),worker_threads=require('worker_threads');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var ae__default=/*#__PURE__*/_interopDefault(ae);var wt__default=/*#__PURE__*/_interopDefault(wt);var _t__default=/*#__PURE__*/_interopDefault(_t);var qt__default=/*#__PURE__*/_interopDefault(qt);var rt=(s=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(s,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):s)(function(s){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+s+'" is not supported')});var Ce=class{_channels=new Map;async publish(e,t){let n=this._channels.get(e);if(n)for(let i of n)try{i(t);}catch{}}async publishBatch(e){for(let t of e)await this.publish(t.channel,t.data);}async subscribe(e,t){this._channels.has(e)||this._channels.set(e,new Set),this._channels.get(e)?.add(t);}async unsubscribe(e){this._channels.delete(e);}async disconnect(){this._channels.clear(),this._presence.clear();}_presence=new Map;async setPresence(e,t,n){this._presence.set(e,t);}async getPresence(e){return this._presence.get(e)||null}async getPresenceBatch(e){return e.map(t=>this._presence.get(t)||null)}async removePresence(e){this._presence.delete(e);}async setPresenceBatch(e){for(let{identity:t,nodeId:n}of e)this._presence.set(t,n);}};function at(s){return s}var be=class{_cluster;_subscriber;_handlers=new Map;constructor(e){try{let{createRequire:t}=rt("module"),i=t(__filename)("ioredis"),r=e.redisOptions??{};e.natMap&&(r.natMap=e.natMap),this._cluster=new i.Cluster(e.nodes.map(a=>({host:a.host,port:a.port})),{redisOptions:r}),this._subscriber=new i.Cluster(e.nodes.map(a=>({host:a.host,port:a.port})),{redisOptions:r}),this._subscriber.on("message",(a,o)=>{let d=this._handlers.get(a);d&&d(o);});}catch{throw new Error("ClusterDriver requires 'ioredis' as a peer dependency. Install it with: npm i ioredis")}}async publish(e,t){await this._cluster.publish(e,t);}async subscribe(e,t){this._handlers.set(e,t),await this._subscriber.subscribe(e);}async unsubscribe(e){await this._subscriber.unsubscribe(e),this._handlers.delete(e);}async set(e,t,n){n?await this._cluster.set(e,t,"EX",n):await this._cluster.set(e,t);}async get(e){return await this._cluster.get(e)||null}async mget(e){if(e.length===0)return [];try{return await this._cluster.mget(...e)}catch{return await Promise.all(e.map(t=>this.get(t)))}}async del(e){await this._cluster.del(e);}async xadd(e,t,n){let i=[];n&&i.push("MAXLEN","~",n.toString()),i.push("*");for(let[r,a]of Object.entries(t))i.push(r,a);return await this._cluster.xadd(e,...i)}async xaddBatch(e,t){if(e.length===0)return;let n=this._cluster.pipeline();for(let i of e){let r=[];t&&r.push("MAXLEN","~",t.toString()),r.push("*");for(let[a,o]of Object.entries(i.args))r.push(a,o);n.xadd(i.stream,...r);}await n.exec();}async xread(e,t,n){let i=[];t&&i.push("COUNT",t),typeof n=="number"&&i.push("BLOCK",n),i.push("STREAMS");for(let a of e)i.push(a.key);for(let a of e)i.push(a.id);let r=await this._cluster.xread(...i);return r?r.map(([a,o])=>({stream:a,messages:o.map(([d,p])=>{let c={};for(let l=0;l<p.length;l+=2)c[p[l]]=p[l+1];return {id:d,data:c}})})):null}async xlen(e){return await this._cluster.xlen(e)}async disconnect(){this._handlers.clear(),await Promise.allSettled([this._cluster.quit(),this._subscriber.quit()]);}async setPresenceBatch(e){if(e.length===0)return;let t=this._cluster.pipeline();for(let{key:n,value:i,ttlSeconds:r}of e)t.set(n,i,"EX",r);await t.exec();}async expire(e,t){await this._cluster.expire(e,t);}onError(e){return this._cluster.on("error",e),()=>this._cluster.removeListener("error",e)}onReconnect(e){return this._cluster.on("reconnecting",e),()=>this._cluster.removeListener("reconnecting",e)}};var Pe=class{constructor(e,t,n){this.pub=e;this.sub=t;this.blocking=n;this.sub.on&&this.sub.on("message",(i,r)=>{let a=this._handlers.get(i);a&&a(r);});}pub;sub;blocking;_handlers=new Map;async publish(e,t){await this.pub.publish(e,t);}async subscribe(e,t){this._handlers.set(e,t),await this.sub.subscribe(e);}async unsubscribe(e){await this.sub.unsubscribe(e),this._handlers.delete(e);}async set(e,t,n){n?await this.pub.set(e,t,"EX",n):await this.pub.set(e,t);}async get(e){return await this.pub.get(e)||null}async mget(e){return e.length===0?[]:await this.pub.mget(...e)}async del(e){await this.pub.del(e);}async xadd(e,t,n){let i=[];n&&i.push("MAXLEN","~",n.toString()),i.push("*");for(let[r,a]of Object.entries(t))i.push(r,a);return await this.pub.xadd(e,...i)}async xaddBatch(e,t){if(e.length===0)return;let n=this.pub.pipeline();for(let i of e){let r=[];t&&r.push("MAXLEN","~",t.toString()),r.push("*");for(let[a,o]of Object.entries(i.args))r.push(a,o);n.xadd(i.stream,...r);}await n.exec();}async xread(e,t,n){let i=[];t&&i.push("COUNT",t),typeof n=="number"&&i.push("BLOCK",n),i.push("STREAMS"),e.forEach(o=>{i.push(o.key);}),e.forEach(o=>{i.push(o.id);});let a=await(n&&this.blocking?this.blocking:this.pub).xread(...i);return a?a.map(([o,d])=>({stream:o,messages:d.map(([p,c])=>{let l={};for(let u=0;u<c.length;u+=2)l[c[u]]=c[u+1];return {id:p,data:l}})})):null}async xlen(e){return await this.pub.xlen(e)}async disconnect(){this._handlers.clear();let e=async t=>{t.quit?await t.quit():t.disconnect&&await t.disconnect();};await Promise.all([e(this.pub),e(this.sub)]);}async setPresenceBatch(e){if(e.length===0)return;let t=this.pub.pipeline();for(let{key:n,value:i,ttlSeconds:r}of e)t.set(n,i,"EX",r);await t.exec();}async expire(e,t){await this.pub.expire(e,t);}onError(e){return this.pub.on("error",e),()=>this.pub.removeListener("error",e)}onReconnect(e){return this.pub.on("connect",e),()=>this.pub.removeListener("connect",e)}},Se=class{constructor(e,t,n){this.pub=e;this.sub=t;this.blocking=n;}pub;sub;blocking;async publish(e,t){await this.pub.publish(e,t);}async subscribe(e,t){await this.sub.subscribe(e,t);}async unsubscribe(e){await this.sub.unsubscribe(e);}async set(e,t,n){n?await this.pub.set(e,t,{EX:n}):await this.pub.set(e,t);}async get(e){return await this.pub.get(e)||null}async mget(e){return e.length===0?[]:await this.pub.mGet(e)}async del(e){await this.pub.del(e);}async xadd(e,t,n){return await this.pub.xAdd(e,"*",t,{TRIM:n?{strategy:"MAXLEN",strategyModifier:"~",threshold:n}:void 0})}async xaddBatch(e,t){if(e.length===0)return;let n=this.pub.multi();for(let i of e)n.xAdd(i.stream,"*",i.args,{TRIM:t?{strategy:"MAXLEN",strategyModifier:"~",threshold:t}:void 0});await n.exec();}async xread(e,t,n){let i={};t&&(i.COUNT=t),typeof n=="number"&&(i.BLOCK=n);let r=e.map(d=>({key:d.key,id:d.id})),o=await(n&&this.blocking?this.blocking:this.pub).xRead(r,i);return !o||o.length===0?null:o.map(d=>({stream:d.name,messages:d.messages.map(p=>({id:p.id,data:p.message}))}))}async xlen(e){return await this.pub.xLen(e)}async disconnect(){await Promise.all([this.pub.disconnect(),this.sub.disconnect()]);}async setPresenceBatch(e){if(e.length===0)return;let t=this.pub.multi();for(let{key:n,value:i,ttlSeconds:r}of e)t.set(n,i,{EX:r});await t.exec();}async expire(e,t){await this.pub.expire(e,t);}onError(e){return this.pub.on("error",e),()=>this.pub.removeListener("error",e)}onReconnect(e){return this.pub.on("connect",e),()=>this.pub.removeListener("connect",e)}};function Fe(s,e,t){return e.isOpen!==void 0&&typeof e.subscribe=="function"?new Se(s,e,t):new Pe(s,e,t)}var Ie=class{_driver;_prefix;_streamMaxLen;_streamTtlSeconds;_presenceTtlSeconds;_handlers=new Map;_streamOffsets=new Map;_streams=new Set;_polling=false;_closed=false;_sequenceCounters=new Map;_unsubError;_unsubReconnect;_presenceCache=new Map;_driverPool;_nextPoolIndex;constructor(e){this._prefix=e.prefix??"ocpp-ws-io:",this._streamMaxLen=e.streamMaxLen??1e3,this._streamTtlSeconds=e.streamTtlSeconds??300,this._presenceTtlSeconds=e.presenceTtlSeconds??300,this._driver=Fe(e.pubClient,e.subClient,e.blockingClient);let t=e.poolSize??1;if(this._driverPool=[this._driver],this._nextPoolIndex=0,t>1&&e.driverFactory)for(let n=1;n<t;n++)this._driverPool.push(e.driverFactory());this._driver.onError&&(this._unsubError=this._driver.onError(n=>{console.error("[RedisAdapter] Redis error:",n.message);})),this._driver.onReconnect&&(this._unsubReconnect=this._driver.onReconnect(()=>{this._rehydratePresence().catch(()=>{});}));}_getPoolDriver(){if(this._driverPool.length===1)return this._driver;let e=this._driverPool[this._nextPoolIndex];return this._nextPoolIndex=(this._nextPoolIndex+1)%this._driverPool.length,e}async publish(e,t){let n=this._prefix+e,i=t;if(i&&typeof i=="object"&&e.startsWith("ocpp:node:")){let a=(this._sequenceCounters.get(e)??0)+1;this._sequenceCounters.set(e,a),i.__seq=a;}let r=JSON.stringify(t);if(e.startsWith("ocpp:node:")){let a=this._getPoolDriver();await a.xadd(n,{message:r},this._streamMaxLen),await a.expire(n,this._streamTtlSeconds).catch(()=>{});}else await this._getPoolDriver().publish(n,r);}async publishBatch(e){let t=[],n=[];for(let r of e){let a=this._prefix+r.channel,o=JSON.stringify(r.data);r.channel.startsWith("ocpp:node:")?t.push({stream:a,args:{message:o}}):n.push({channel:a,message:o});}let i=[];t.length>0&&i.push(this._getPoolDriver().xaddBatch(t,this._streamMaxLen)),n.length>0&&i.push(Promise.all(n.map(r=>this._getPoolDriver().publish(r.channel,r.message))).then(()=>{})),await Promise.all(i);}async subscribe(e,t){if(!this._handlers.has(e)){this._handlers.set(e,new Set);let n=this._prefix+e;e.startsWith("ocpp:node:")?this._streams.has(n)||(this._streams.add(n),this._streamOffsets.set(n,"0"),this._ensurePolling()):await this._driver.subscribe(n,i=>{this._handleMessage(e,i);});}this._handlers.get(e)?.add(t);}async unsubscribe(e){let t=this._prefix+e;this._streams.has(t)?(this._streams.delete(t),this._streamOffsets.delete(t)):await this._driver.unsubscribe(t),this._handlers.delete(e);}async disconnect(){this._closed=true,this._handlers.clear(),this._streams.clear(),this._presenceCache.clear(),this._sequenceCounters.clear(),this._unsubError&&this._unsubError(),this._unsubReconnect&&this._unsubReconnect(),await Promise.allSettled(this._driverPool.map(e=>e.disconnect()));}_handleMessage(e,t){let n=this._handlers.get(e);if(!n)return;let i;try{i=JSON.parse(t);}catch{i=t;}for(let r of n)try{r(i);}catch{}}_ensurePolling(){this._polling||this._closed||(this._polling=true,this._pollLoop().catch(()=>{this._polling=false;}));}async _pollLoop(){for(;!this._closed;){if(this._streams.size===0){await new Promise(t=>setTimeout(t,1e3));continue}let e=Array.from(this._streams).map(t=>({key:t,id:this._streamOffsets.get(t)||"$"}));try{let t=await this._driver.xread(e,void 0,1e3);if(t)for(let n of t){let i=n.stream.replace(this._prefix,"");for(let r of n.messages){this._streamOffsets.set(n.stream,r.id);let a=r.data.message;a&&this._handleMessage(i,a);}}}catch{await new Promise(n=>setTimeout(n,1e3));}}this._polling=false;}async setPresence(e,t,n){let i=`${this._prefix}presence:${e}`;this._presenceCache.set(e,{nodeId:t,ttl:n}),await this._driver.set(i,t,n);}async getPresence(e){let t=`${this._prefix}presence:${e}`;return await this._driver.get(t)}async getPresenceBatch(e){if(e.length===0)return [];let t=e.map(n=>`${this._prefix}presence:${n}`);return this._driver.mget?await this._driver.mget(t):await Promise.all(t.map(n=>this._driver.get(n)))}async removePresence(e){let t=`${this._prefix}presence:${e}`;await this._driver.del(t);}async metrics(){let e=0,t={};for(let n of this._streams)try{let i=await this._driver.xlen(n);e+=i,t[n]=i;}catch{t[n]=-1;}return {pendingMessages:e,activeStreams:this._streams.size,streamDetails:t}}async setPresenceBatch(e){if(e.length===0)return;let t=e.map(({identity:n,nodeId:i,ttl:r})=>{let a=`${this._prefix}presence:${n}`,o=r??this._presenceTtlSeconds;return this._presenceCache.set(n,{nodeId:i,ttl:o}),{key:a,value:i,ttlSeconds:o}});await this._driver.setPresenceBatch(t);}async _rehydratePresence(){if(this._presenceCache.size===0)return;let e=Array.from(this._presenceCache.entries()).map(([t,{nodeId:n,ttl:i}])=>({key:`${this._prefix}presence:${t}`,value:n,ttlSeconds:i}));await this._driver.setPresenceBatch(e);}};var z=class extends events.EventEmitter{_cpuThreshold;_memThreshold;_cooldownMs;_sampleInterval;_timer=null;_lastOverloadTime=0;_multiplier=1;_prevCpuUsage=null;_prevTimestamp=0;constructor(e={}){super(),this._cpuThreshold=e.cpuThresholdPercent??70,this._memThreshold=e.memThresholdPercent??85,this._cooldownMs=e.cooldownMs??1e4,this._sampleInterval=e.sampleIntervalMs??2e3;}get multiplier(){return this._multiplier}start(){this._timer||(this._prevCpuUsage=process.cpuUsage(),this._prevTimestamp=Date.now(),this._timer=setInterval(()=>this._sample(),this._sampleInterval),this._timer.unref&&this._timer.unref());}stop(){this._timer&&(clearInterval(this._timer),this._timer=null),this._multiplier=1;}_sample(){let e=Date.now(),t=process.cpuUsage(this._prevCpuUsage??void 0),n=e-this._prevTimestamp,i=(t.user+t.system)/1e3/n/os.cpus().length*100;this._prevCpuUsage=process.cpuUsage(),this._prevTimestamp=e;let r=os.totalmem(),a=os.freemem(),o=(r-a)/r*100,d=i>this._cpuThreshold,p=o>this._memThreshold,c=this._multiplier;d||p?(this._lastOverloadTime=e,this._multiplier=Math.max(.25,this._multiplier*.5)):e-this._lastOverloadTime>this._cooldownMs&&(this._multiplier=Math.min(1,this._multiplier+.1)),this._multiplier!==c&&this.emit("adapted",{multiplier:this._multiplier,cpuPercent:Math.round(i*100)/100,memPercent:Math.round(o*100)/100});}on(e,t){return super.on(e,t)}emit(e,t){return super.emit(e,t)}};var k=class extends Error{constructor(e="Operation timed out"){super(e),this.name="TimeoutError";}},B=class extends Error{statusCode;headers;constructor(e,t,n={}){super(e),this.name="UnexpectedHttpResponse",this.statusCode=t,this.headers=n;}},Ee=class extends Error{constructor(e="WebSocket upgrade failed"){super(e),this.name="WebsocketUpgradeError";}},P=class extends Error{rpcErrorCode="GenericError";rpcErrorMessage="";details;constructor(e,t={}){super(e),this.name="RPCGenericError",this.details=t;}},R=class extends P{rpcErrorCode="NotImplemented";rpcErrorMessage="Requested method is not known";constructor(e,t={}){super(e,t),this.name="RPCNotImplementedError";}},G=class extends P{rpcErrorCode="NotSupported";rpcErrorMessage="Requested method is recognised but not supported";constructor(e,t={}){super(e,t),this.name="RPCNotSupportedError";}},J=class extends P{rpcErrorCode="InternalError";rpcErrorMessage="An internal error occurred and the receiver was not able to process the requested action successfully";constructor(e,t={}){super(e,t),this.name="RPCInternalError";}},K=class extends P{rpcErrorCode="ProtocolError";rpcErrorMessage="Payload for action is incomplete";constructor(e,t={}){super(e,t),this.name="RPCProtocolError";}},X=class extends P{rpcErrorCode="SecurityError";rpcErrorMessage="During the processing of action a security issue occurred preventing receiver from completing the action successfully";constructor(e,t={}){super(e,t),this.name="RPCSecurityError";}},Q=class extends P{rpcErrorCode="FormationViolation";rpcErrorMessage="Payload for action is syntactically incorrect or not conform the PDU structure for action";constructor(e,t={}){super(e,t),this.name="RPCFormationViolationError";}},Y=class extends P{rpcErrorCode="FormatViolation";rpcErrorMessage="Payload is syntactically correct but at least one field contains an invalid value";constructor(e,t={}){super(e,t),this.name="RPCFormatViolationError";}},Z=class extends P{rpcErrorCode="PropertyConstraintViolation";rpcErrorMessage="Payload is syntactically correct but at least one of the fields violates data type constraints";constructor(e,t={}){super(e,t),this.name="RPCPropertyConstraintViolationError";}},ee=class extends P{rpcErrorCode="OccurrenceConstraintViolation";rpcErrorMessage="Payload for action is syntactically correct but at least one of the fields violates occurrence constraints";constructor(e,t={}){super(e,t),this.name="RPCOccurrenceConstraintViolationError";}},te=class extends P{rpcErrorCode="TypeConstraintViolation";rpcErrorMessage="Payload for action is syntactically correct but at least one of the fields violates type constraints";constructor(e,t={}){super(e,t),this.name="RPCTypeConstraintViolationError";}},L=class extends P{rpcErrorCode="MessageTypeNotSupported";rpcErrorMessage="A message with a Message Type Number received that is not supported by this implementation";constructor(e,t={}){super(e,t),this.name="RPCMessageTypeNotSupportedError";}},ie=class extends P{rpcErrorCode="RpcFrameworkError";rpcErrorMessage="Content of the call is not a valid RPC request";constructor(e,t={}){super(e,t),this.name="RPCFrameworkError";}};function lt(s){return s}function ut(s){return s}function mt(s){return s}function ht(s){return s}function ft(...s){return async e=>{let t=false,n=false,i=o=>{t=true,e.accept(o);},r=(o,d)=>(n=true,e.reject(o,d)),a={...e,accept:i,reject:r};try{for(let o of s){if(e.signal.aborted||t||n)break;let d=o(a);if(d instanceof Promise&&await d,t||n)break}!t&&!n&&r(401,"Unauthorized (All composeAuth handlers passed without accepting)");}catch{n||r(500,"Internal Server Error during auth compose execution");}}}function xe(s,e,t={}){let n=typeof t=="object"?t:{},{exchangeLog:i=false,prettify:r=false}=n;return async(a,o)=>{let d=Date.now(),p=a.method,c=i?"info":"debug";switch(a.type){case "incoming_call":i&&r?s[c]?.(`\u26A1 ${e} \u2190 ${p} [IN]`,{messageId:a.messageId,method:a.method,protocol:a.protocol,payload:a.params,direction:"IN"}):s[c]?.("CALL \u2190",{messageId:a.messageId,method:a.method,protocol:a.protocol,payload:a.params,direction:"IN"});break;case "outgoing_call":i&&r?s[c]?.(`\u26A1 ${e} \u2192 ${p} [OUT]`,{method:a.method,params:a.params,direction:"OUT"}):s[c]?.("CALL \u2192",{method:a.method,params:a.params,direction:"OUT"});break}try{let l=await o(),u=Date.now()-d;switch(a.type){case "incoming_call":l!=null&&(i&&r?s[c]?.(`\u2705 ${e} \u2192 ${p} [RES]`,{messageId:a.messageId,method:a.method,durationMs:u,params:l,direction:"OUT"}):s[c]?.("CALLRESULT \u2192",{messageId:a.messageId,method:a.method,durationMs:u,params:l,direction:"OUT"}));break;case "outgoing_call":i&&r?s[c]?.(`\u2705 ${e} \u2190 ${p} [RES]`,{messageId:a.messageId,method:a.method,durationMs:u,payload:l,direction:"IN"}):s[c]?.("CALLRESULT \u2190",{messageId:a.messageId,method:a.method,durationMs:u,payload:l,direction:"IN"});break}return l}catch(l){let u=l.message,f=Date.now()-d;throw a.type==="incoming_call"?i&&r?s.error?.(`\u{1F6A8} ${e} \u2192 ${p} [ERR]`,{messageId:a.messageId,method:a.method,durationMs:f,error:u,direction:"OUT"}):s.error?.("CALLERROR \u2192",{messageId:a.messageId,method:a.method,durationMs:f,error:u,direction:"OUT"}):a.type==="outgoing_call"&&(i&&r?s.warn?.(`\u{1F6A8} ${e} \u2190 ${p} [ERR]`,{messageId:a.messageId,method:a.method,durationMs:f,error:u,direction:"IN"}):s.warn?.("CALLERROR \u2190",{messageId:a.messageId,method:a.method,durationMs:f,error:u,direction:"IN"})),l}}}function vt(s){return s.showMetadata===false||s.showSourceMeta===false||s.prettifySource===true||s.prettifyMetadata===true}function Ct(s){let e=s.showMetadata??true,t=s.showSourceMeta??true,n=s.prettifySource??false,i=s.prettifyMetadata??false,r="\x1B[2;37m",a="\x1B[0m",o="\x1B[36m";return (d,p)=>{if(!t)d.context=void 0;else if(n&&d.context){let l=[];d.context.component&&l.push(String(d.context.component)),d.context.identity&&l.push(String(d.context.identity)),l.length>0&&(d.message=`${r}[${l.join("/")}]${a} ${d.message}`,d.context=void 0);}let c=d.meta;if(!e)d.meta={};else if(i&&c&&Object.keys(c).length>0){let l=Object.entries(c).filter(([,u])=>u!=null).map(([u,f])=>{let S=typeof f=="object"?JSON.stringify(f):String(f);return typeof f=="string"?S=`${r}${S}${a}`:S=`${r}${S}${a}`,`${o}${u}${a}=${S}`}).join(" ");l&&(d.message=`${d.message} ${l}`),d.meta={};}p(d);}}function ce(s,e){if(s===false||s?.enabled===false)return null;if(s?.logger)return e&&s.logger.child?s.logger.child(e):s.logger;let t=s?.level??"INFO",i=s?.prettify??false?[voltlogIo.prettyTransport({level:t})]:[voltlogIo.consoleTransport({level:t})];if(s?.handler){let o=s.handler;i.push({name:"customHandler",write:d=>o(d)});}let r=[];s&&vt(s)&&r.push(Ct(s));let a=voltlogIo.createLogger({level:t,transports:i,middleware:r.length>0?r:void 0});return e&&Object.keys(e).length>0?a.child(e):a}var le=class{_stack=[];use(e){this._stack.push(e);}async execute(e,t){let n=-1,i=async r=>{if(r<=n)throw new Error("next() called multiple times");n=r;let a=this._stack[r];if(r===this._stack.length)return t(e);if(a)return a(e,()=>i(r+1))};return i(0)}};var ue=class{_concurrency;_running=0;_queue=[];constructor(e=1){this._concurrency=Math.max(1,e);}get concurrency(){return this._concurrency}get pending(){return this._queue.length}get running(){return this._running}get size(){return this._running+this._queue.length}setConcurrency(e){this._concurrency=Math.max(1,e),this._drain();}push(e){return new Promise((t,n)=>{this._queue.push({fn:e,resolve:t,reject:n}),this._drain();})}_drain(){for(;this._running<this._concurrency&&this._queue.length>0;){let e=this._queue.shift();this._running++,e?.fn().then(e.resolve).catch(e.reject).finally(()=>{this._running--,this._drain();});}}};var Ue=[{$id:"urn:Authorize.req",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{idTag:{type:"string",maxLength:20}},required:["idTag"],type:"object"},{$id:"urn:Authorize.conf",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{idTagInfo:{type:"object",properties:{expiryDate:{type:"string",format:"date-time"},parentIdTag:{type:"string",maxLength:20},status:{type:"string",enum:["Accepted","Blocked","Expired","Invalid","ConcurrentTx"]}},additionalProperties:false,required:["status"]}},required:["idTagInfo"],type:"object"},{$id:"urn:BootNotification.req",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{chargePointVendor:{type:"string",maxLength:20},chargePointModel:{type:"string",maxLength:20},chargePointSerialNumber:{type:"string",maxLength:25},chargeBoxSerialNumber:{type:"string",maxLength:25},firmwareVersion:{type:"string",maxLength:50},iccid:{type:"string",maxLength:20},imsi:{type:"string",maxLength:20},meterType:{type:"string",maxLength:25},meterSerialNumber:{type:"string",maxLength:25}},required:["chargePointVendor","chargePointModel"],type:"object"},{$id:"urn:BootNotification.conf",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{status:{type:"string",enum:["Accepted","Pending","Rejected"]},currentTime:{type:"string",format:"date-time"},interval:{type:"integer"}},required:["status","currentTime","interval"],type:"object"},{$id:"urn:CancelReservation.req",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{reservationId:{type:"integer"}},required:["reservationId"],type:"object"},{$id:"urn:CancelReservation.conf",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{status:{type:"string",enum:["Accepted","Rejected"]}},required:["status"],type:"object"},{$id:"urn:CertificateSigned.req",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{certificateChain:{type:"string",maxLength:1e4}},required:["certificateChain"],type:"object"},{$id:"urn:CertificateSigned.conf",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,definitions:{CertificateSignedStatusEnumType:{type:"string",enum:["Accepted","Rejected"]}},properties:{status:{$ref:"#/definitions/CertificateSignedStatusEnumType"}},required:["status"],type:"object"},{$id:"urn:ChangeAvailability.req",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{connectorId:{type:"integer"},type:{type:"string",enum:["Inoperative","Operative"]}},required:["connectorId","type"],type:"object"},{$id:"urn:ChangeAvailability.conf",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{status:{type:"string",enum:["Accepted","Rejected","Scheduled"]}},required:["status"],type:"object"},{$id:"urn:ChangeConfiguration.req",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{key:{type:"string",maxLength:50},value:{type:"string",maxLength:500}},required:["key","value"],type:"object"},{$id:"urn:ChangeConfiguration.conf",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{status:{type:"string",enum:["Accepted","Rejected","RebootRequired","NotSupported"]}},required:["status"],type:"object"},{$id:"urn:ClearCache.req",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{},type:"object"},{$id:"urn:ClearCache.conf",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{status:{type:"string",enum:["Accepted","Rejected"]}},required:["status"],type:"object"},{$id:"urn:ClearChargingProfile.req",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{id:{type:"integer"},connectorId:{type:"integer"},chargingProfilePurpose:{type:"string",enum:["ChargePointMaxProfile","TxDefaultProfile","TxProfile"]},stackLevel:{type:"integer"}},type:"object"},{$id:"urn:ClearChargingProfile.conf",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{status:{type:"string",enum:["Accepted","Unknown"]}},required:["status"],type:"object"},{$id:"urn:DataTransfer.req",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{vendorId:{type:"string",maxLength:255},messageId:{type:"string",maxLength:50},data:{type:"string"}},required:["vendorId"],type:"object"},{$id:"urn:DataTransfer.conf",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{status:{type:"string",enum:["Accepted","Rejected","UnknownMessageId","UnknownVendorId"]},data:{type:"string"}},required:["status"],type:"object"},{$id:"urn:DeleteCertificate.req",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,definitions:{HashAlgorithmEnumType:{type:"string",enum:["SHA256","SHA384","SHA512"]},CertificateHashDataType:{type:"object",additionalProperties:false,properties:{hashAlgorithm:{$ref:"#/definitions/HashAlgorithmEnumType"},issuerNameHash:{type:"string",maxLength:128},issuerKeyHash:{type:"string",maxLength:128},serialNumber:{type:"string",maxLength:40}},required:["hashAlgorithm","issuerNameHash","issuerKeyHash","serialNumber"]}},properties:{certificateHashData:{$ref:"#/definitions/CertificateHashDataType"}},required:["certificateHashData"],type:"object"},{$id:"urn:DeleteCertificate.conf",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,definitions:{DeleteCertificateStatusEnumType:{type:"string",enum:["Accepted","Failed","NotFound"]}},properties:{status:{$ref:"#/definitions/DeleteCertificateStatusEnumType"}},required:["status"],type:"object"},{$id:"urn:DiagnosticsStatusNotification.req",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{status:{type:"string",enum:["Idle","Uploaded","UploadFailed","Uploading"]}},required:["status"],type:"object"},{$id:"urn:DiagnosticsStatusNotification.conf",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{},type:"object"},{$id:"urn:ExtendedTriggerMessage.req",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,definitions:{MessageTriggerEnumType:{type:"string",enum:["BootNotification","LogStatusNotification","FirmwareStatusNotification","Heartbeat","MeterValues","SignChargePointCertificate","StatusNotification"]}},properties:{requestedMessage:{$ref:"#/definitions/MessageTriggerEnumType"},connectorId:{type:"integer"}},required:["requestedMessage"],type:"object"},{$id:"urn:ExtendedTriggerMessage.conf",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,definitions:{TriggerMessageStatusEnumType:{type:"string",enum:["Accepted","Rejected","NotImplemented"]}},properties:{status:{$ref:"#/definitions/TriggerMessageStatusEnumType"}},required:["status"],type:"object"},{$id:"urn:FirmwareStatusNotification.req",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{status:{type:"string",enum:["Downloaded","DownloadFailed","Downloading","Idle","InstallationFailed","Installing","Installed"]}},required:["status"],type:"object"},{$id:"urn:FirmwareStatusNotification.conf",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{},type:"object"},{$id:"urn:GetCompositeSchedule.req",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{connectorId:{type:"integer"},duration:{type:"integer"},chargingRateUnit:{type:"string",enum:["A","W"]}},required:["connectorId","duration"],type:"object"},{$id:"urn:GetCompositeSchedule.conf",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{status:{type:"string",enum:["Accepted","Rejected"]},connectorId:{type:"integer"},scheduleStart:{type:"string",format:"date-time"},chargingSchedule:{type:"object",properties:{duration:{type:"integer"},startSchedule:{type:"string",format:"date-time"},chargingRateUnit:{type:"string",enum:["A","W"]},chargingSchedulePeriod:{type:"array",items:{type:"object",properties:{startPeriod:{type:"integer"},limit:{type:"number",multipleOf:.1},numberPhases:{type:"integer"}},additionalProperties:false,required:["startPeriod","limit"]}},minChargingRate:{type:"number",multipleOf:.1}},additionalProperties:false,required:["chargingRateUnit","chargingSchedulePeriod"]}},required:["status"],type:"object"},{$id:"urn:GetConfiguration.req",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{key:{type:"array",items:{type:"string",maxLength:50}}},type:"object"},{$id:"urn:GetConfiguration.conf",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{configurationKey:{type:"array",items:{type:"object",properties:{key:{type:"string",maxLength:50},readonly:{type:"boolean"},value:{type:"string",maxLength:500}},additionalProperties:false,required:["key","readonly"]}},unknownKey:{type:"array",items:{type:"string",maxLength:50}}},type:"object"},{$id:"urn:GetDiagnostics.req",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{location:{type:"string",format:"uri"},retries:{type:"integer"},retryInterval:{type:"integer"},startTime:{type:"string",format:"date-time"},stopTime:{type:"string",format:"date-time"}},required:["location"],type:"object"},{$id:"urn:GetDiagnostics.conf",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{fileName:{type:"string",maxLength:255}},type:"object"},{$id:"urn:GetInstalledCertificateIds.req",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,definitions:{CertificateUseEnumType:{type:"string",enum:["CentralSystemRootCertificate","ManufacturerRootCertificate"]}},properties:{certificateType:{$ref:"#/definitions/CertificateUseEnumType"}},required:["certificateType"],type:"object"},{$id:"urn:GetInstalledCertificateIds.conf",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,definitions:{GetInstalledCertificateStatusEnumType:{type:"string",enum:["Accepted","NotFound"]},HashAlgorithmEnumType:{type:"string",enum:["SHA256","SHA384","SHA512"]},CertificateHashDataType:{type:"object",additionalProperties:false,properties:{hashAlgorithm:{$ref:"#/definitions/HashAlgorithmEnumType"},issuerNameHash:{type:"string",maxLength:128},issuerKeyHash:{type:"string",maxLength:128},serialNumber:{type:"string",maxLength:40}},required:["hashAlgorithm","issuerNameHash","issuerKeyHash","serialNumber"]}},properties:{certificateHashData:{type:"array",items:{$ref:"#/definitions/CertificateHashDataType"},minItems:1},status:{$ref:"#/definitions/GetInstalledCertificateStatusEnumType"}},required:["status"],type:"object"},{$id:"urn:GetLocalListVersion.req",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{},type:"object"},{$id:"urn:GetLocalListVersion.conf",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{listVersion:{type:"integer"}},required:["listVersion"],type:"object"},{$id:"urn:GetLog.req",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,definitions:{LogEnumType:{type:"string",enum:["DiagnosticsLog","SecurityLog"]},LogParametersType:{type:"object",additionalProperties:false,properties:{remoteLocation:{type:"string",maxLength:512},oldestTimestamp:{type:"string",format:"date-time"},latestTimestamp:{type:"string",format:"date-time"}},required:["remoteLocation"]}},properties:{log:{$ref:"#/definitions/LogParametersType"},logType:{$ref:"#/definitions/LogEnumType"},requestId:{type:"integer"},retries:{type:"integer"},retryInterval:{type:"integer"}},required:["logType","requestId","log"],type:"object"},{$id:"urn:GetLog.conf",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,definitions:{LogStatusEnumType:{type:"string",enum:["Accepted","Rejected","AcceptedCanceled"]}},properties:{status:{$ref:"#/definitions/LogStatusEnumType"},filename:{type:"string",maxLength:255}},required:["status"],type:"object"},{$id:"urn:Heartbeat.req",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{},type:"object"},{$id:"urn:Heartbeat.conf",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{currentTime:{type:"string",format:"date-time"}},required:["currentTime"],type:"object"},{$id:"urn:InstallCertificate.req",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,definitions:{CertificateUseEnumType:{type:"string",enum:["CentralSystemRootCertificate","ManufacturerRootCertificate"]}},properties:{certificateType:{$ref:"#/definitions/CertificateUseEnumType"},certificate:{type:"string",maxLength:5500}},required:["certificateType","certificate"],type:"object"},{$id:"urn:InstallCertificate.conf",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,definitions:{InstallCertificateStatusEnumType:{type:"string",enum:["Accepted","Failed","Rejected"]}},properties:{status:{$ref:"#/definitions/InstallCertificateStatusEnumType"}},required:["status"],type:"object"},{$id:"urn:LogStatusNotification.req",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,definitions:{UploadLogStatusEnumType:{type:"string",enum:["BadMessage","Idle","NotSupportedOperation","PermissionDenied","Uploaded","UploadFailure","Uploading"]}},properties:{status:{$ref:"#/definitions/UploadLogStatusEnumType"},requestId:{type:"integer"}},required:["status"],type:"object"},{$id:"urn:LogStatusNotification.conf",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,type:"object"},{$id:"urn:MeterValues.req",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{connectorId:{type:"integer"},transactionId:{type:"integer"},meterValue:{type:"array",items:{type:"object",properties:{timestamp:{type:"string",format:"date-time"},sampledValue:{type:"array",items:{type:"object",properties:{value:{type:"string"},context:{type:"string",enum:["Interruption.Begin","Interruption.End","Sample.Clock","Sample.Periodic","Transaction.Begin","Transaction.End","Trigger","Other"]},format:{type:"string",enum:["Raw","SignedData"]},measurand:{type:"string",enum:["Energy.Active.Export.Register","Energy.Active.Import.Register","Energy.Reactive.Export.Register","Energy.Reactive.Import.Register","Energy.Active.Export.Interval","Energy.Active.Import.Interval","Energy.Reactive.Export.Interval","Energy.Reactive.Import.Interval","Power.Active.Export","Power.Active.Import","Power.Offered","Power.Reactive.Export","Power.Reactive.Import","Power.Factor","Current.Import","Current.Export","Current.Offered","Voltage","Frequency","Temperature","SoC","RPM"]},phase:{type:"string",enum:["L1","L2","L3","N","L1-N","L2-N","L3-N","L1-L2","L2-L3","L3-L1"]},location:{type:"string",enum:["Cable","EV","Inlet","Outlet","Body"]},unit:{type:"string",enum:["Wh","kWh","varh","kvarh","W","kW","VA","kVA","var","kvar","A","V","K","Celcius","Celsius","Fahrenheit","Percent"]}},additionalProperties:false,required:["value"]}}},additionalProperties:false,required:["timestamp","sampledValue"]}}},required:["connectorId","meterValue"],type:"object"},{$id:"urn:MeterValues.conf",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{},type:"object"},{$id:"urn:RemoteStartTransaction.req",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{connectorId:{type:"integer"},idTag:{type:"string",maxLength:20},chargingProfile:{type:"object",properties:{chargingProfileId:{type:"integer"},transactionId:{type:"integer"},stackLevel:{type:"integer"},chargingProfilePurpose:{type:"string",enum:["ChargePointMaxProfile","TxDefaultProfile","TxProfile"]},chargingProfileKind:{type:"string",enum:["Absolute","Recurring","Relative"]},recurrencyKind:{type:"string",enum:["Daily","Weekly"]},validFrom:{type:"string",format:"date-time"},validTo:{type:"string",format:"date-time"},chargingSchedule:{type:"object",properties:{duration:{type:"integer"},startSchedule:{type:"string",format:"date-time"},chargingRateUnit:{type:"string",enum:["A","W"]},chargingSchedulePeriod:{type:"array",items:{type:"object",properties:{startPeriod:{type:"integer"},limit:{type:"number",multipleOf:.1},numberPhases:{type:"integer"}},additionalProperties:false,required:["startPeriod","limit"]}},minChargingRate:{type:"number",multipleOf:.1}},additionalProperties:false,required:["chargingRateUnit","chargingSchedulePeriod"]}},additionalProperties:false,required:["chargingProfileId","stackLevel","chargingProfilePurpose","chargingProfileKind","chargingSchedule"]}},required:["idTag"],type:"object"},{$id:"urn:RemoteStartTransaction.conf",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{status:{type:"string",enum:["Accepted","Rejected"]}},required:["status"],type:"object"},{$id:"urn:RemoteStopTransaction.req",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{transactionId:{type:"integer"}},required:["transactionId"],type:"object"},{$id:"urn:RemoteStopTransaction.conf",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{status:{type:"string",enum:["Accepted","Rejected"]}},required:["status"],type:"object"},{$id:"urn:ReserveNow.req",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{connectorId:{type:"integer"},expiryDate:{type:"string",format:"date-time"},idTag:{type:"string",maxLength:20},parentIdTag:{type:"string",maxLength:20},reservationId:{type:"integer"}},required:["connectorId","expiryDate","idTag","reservationId"],type:"object"},{$id:"urn:ReserveNow.conf",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{status:{type:"string",enum:["Accepted","Faulted","Occupied","Rejected","Unavailable"]}},required:["status"],type:"object"},{$id:"urn:Reset.req",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{type:{type:"string",enum:["Hard","Soft"]}},required:["type"],type:"object"},{$id:"urn:Reset.conf",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{status:{type:"string",enum:["Accepted","Rejected"]}},required:["status"],type:"object"},{$id:"urn:SecurityEventNotification.req",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{type:{type:"string",maxLength:50},timestamp:{type:"string",format:"date-time"},techInfo:{type:"string",maxLength:255}},required:["type","timestamp"],type:"object"},{$id:"urn:SecurityEventNotification.conf",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,type:"object"},{$id:"urn:SendLocalList.req",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{listVersion:{type:"integer"},localAuthorizationList:{type:"array",items:{type:"object",properties:{idTag:{type:"string",maxLength:20},idTagInfo:{type:"object",properties:{expiryDate:{type:"string",format:"date-time"},parentIdTag:{type:"string",maxLength:20},status:{type:"string",enum:["Accepted","Blocked","Expired","Invalid","ConcurrentTx"]}},additionalProperties:false,required:["status"]}},additionalProperties:false,required:["idTag"]}},updateType:{type:"string",enum:["Differential","Full"]}},required:["listVersion","updateType"],type:"object"},{$id:"urn:SendLocalList.conf",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{status:{type:"string",enum:["Accepted","Failed","NotSupported","VersionMismatch"]}},required:["status"],type:"object"},{$id:"urn:SetChargingProfile.req",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{connectorId:{type:"integer"},csChargingProfiles:{type:"object",properties:{chargingProfileId:{type:"integer"},transactionId:{type:"integer"},stackLevel:{type:"integer"},chargingProfilePurpose:{type:"string",enum:["ChargePointMaxProfile","TxDefaultProfile","TxProfile"]},chargingProfileKind:{type:"string",enum:["Absolute","Recurring","Relative"]},recurrencyKind:{type:"string",enum:["Daily","Weekly"]},validFrom:{type:"string",format:"date-time"},validTo:{type:"string",format:"date-time"},chargingSchedule:{type:"object",properties:{duration:{type:"integer"},startSchedule:{type:"string",format:"date-time"},chargingRateUnit:{type:"string",enum:["A","W"]},chargingSchedulePeriod:{type:"array",items:{type:"object",properties:{startPeriod:{type:"integer"},limit:{type:"number",multipleOf:.1},numberPhases:{type:"integer"}},additionalProperties:false,required:["startPeriod","limit"]}},minChargingRate:{type:"number",multipleOf:.1}},additionalProperties:false,required:["chargingRateUnit","chargingSchedulePeriod"]}},additionalProperties:false,required:["chargingProfileId","stackLevel","chargingProfilePurpose","chargingProfileKind","chargingSchedule"]}},required:["connectorId","csChargingProfiles"],type:"object"},{$id:"urn:SetChargingProfile.conf",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{status:{type:"string",enum:["Accepted","Rejected","NotSupported"]}},required:["status"],type:"object"},{$id:"urn:SignCertificate.req",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{csr:{type:"string",maxLength:5500}},required:["csr"],type:"object"},{$id:"urn:SignCertificate.conf",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,definitions:{GenericStatusEnumType:{type:"string",enum:["Accepted","Rejected"]}},properties:{status:{$ref:"#/definitions/GenericStatusEnumType"}},required:["status"],type:"object"},{$id:"urn:SignedFirmwareStatusNotification.req",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,definitions:{FirmwareStatusEnumType:{type:"string",enum:["Downloaded","DownloadFailed","Downloading","DownloadScheduled","DownloadPaused","Idle","InstallationFailed","Installing","Installed","InstallRebooting","InstallScheduled","InstallVerificationFailed","InvalidSignature","SignatureVerified"]}},properties:{status:{$ref:"#/definitions/FirmwareStatusEnumType"},requestId:{type:"integer"}},required:["status"],type:"object"},{$id:"urn:SignedFirmwareStatusNotification.conf",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,type:"object"},{$id:"urn:SignedUpdateFirmware.req",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,definitions:{FirmwareType:{type:"object",additionalProperties:false,properties:{location:{type:"string",maxLength:512},retrieveDateTime:{type:"string",format:"date-time"},installDateTime:{type:"string",format:"date-time"},signingCertificate:{type:"string",maxLength:5500},signature:{type:"string",maxLength:800}},required:["location","retrieveDateTime","signingCertificate","signature"]}},properties:{retries:{type:"integer"},retryInterval:{type:"integer"},requestId:{type:"integer"},firmware:{$ref:"#/definitions/FirmwareType"}},required:["requestId","firmware"],type:"object"},{$id:"urn:SignedUpdateFirmware.conf",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,definitions:{UpdateFirmwareStatusEnumType:{type:"string",enum:["Accepted","Rejected","AcceptedCanceled","InvalidCertificate","RevokedCertificate"]}},properties:{status:{$ref:"#/definitions/UpdateFirmwareStatusEnumType"}},required:["status"],type:"object"},{$id:"urn:StartTransaction.req",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{connectorId:{type:"integer"},idTag:{type:"string",maxLength:20},meterStart:{type:"integer"},reservationId:{type:"integer"},timestamp:{type:"string",format:"date-time"}},required:["connectorId","idTag","meterStart","timestamp"],type:"object"},{$id:"urn:StartTransaction.conf",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{idTagInfo:{type:"object",properties:{expiryDate:{type:"string",format:"date-time"},parentIdTag:{type:"string",maxLength:20},status:{type:"string",enum:["Accepted","Blocked","Expired","Invalid","ConcurrentTx"]}},additionalProperties:false,required:["status"]},transactionId:{type:"integer"}},required:["idTagInfo","transactionId"],type:"object"},{$id:"urn:StatusNotification.req",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{connectorId:{type:"integer"},errorCode:{type:"string",enum:["ConnectorLockFailure","EVCommunicationError","GroundFailure","HighTemperature","InternalError","LocalListConflict","NoError","OtherError","OverCurrentFailure","PowerMeterFailure","PowerSwitchFailure","ReaderFailure","ResetFailure","UnderVoltage","OverVoltage","WeakSignal"]},info:{type:"string",maxLength:50},status:{type:"string",enum:["Available","Preparing","Charging","SuspendedEVSE","SuspendedEV","Finishing","Reserved","Unavailable","Faulted"]},timestamp:{type:"string",format:"date-time"},vendorId:{type:"string",maxLength:255},vendorErrorCode:{type:"string",maxLength:50}},required:["connectorId","errorCode","status"],type:"object"},{$id:"urn:StatusNotification.conf",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{},type:"object"},{$id:"urn:StopTransaction.req",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{idTag:{type:"string",maxLength:20},meterStop:{type:"integer"},timestamp:{type:"string",format:"date-time"},transactionId:{type:"integer"},reason:{type:"string",enum:["EmergencyStop","EVDisconnected","HardReset","Local","Other","PowerLoss","Reboot","Remote","SoftReset","UnlockCommand","DeAuthorized"]},transactionData:{type:"array",items:{type:"object",properties:{timestamp:{type:"string",format:"date-time"},sampledValue:{type:"array",items:{type:"object",properties:{value:{type:"string"},context:{type:"string",enum:["Interruption.Begin","Interruption.End","Sample.Clock","Sample.Periodic","Transaction.Begin","Transaction.End","Trigger","Other"]},format:{type:"string",enum:["Raw","SignedData"]},measurand:{type:"string",enum:["Energy.Active.Export.Register","Energy.Active.Import.Register","Energy.Reactive.Export.Register","Energy.Reactive.Import.Register","Energy.Active.Export.Interval","Energy.Active.Import.Interval","Energy.Reactive.Export.Interval","Energy.Reactive.Import.Interval","Power.Active.Export","Power.Active.Import","Power.Offered","Power.Reactive.Export","Power.Reactive.Import","Power.Factor","Current.Import","Current.Export","Current.Offered","Voltage","Frequency","Temperature","SoC","RPM"]},phase:{type:"string",enum:["L1","L2","L3","N","L1-N","L2-N","L3-N","L1-L2","L2-L3","L3-L1"]},location:{type:"string",enum:["Cable","EV","Inlet","Outlet","Body"]},unit:{type:"string",enum:["Wh","kWh","varh","kvarh","W","kW","VA","kVA","var","kvar","A","V","K","Celcius","Celsius","Fahrenheit","Percent"]}},additionalProperties:false,required:["value"]}}},additionalProperties:false,required:["timestamp","sampledValue"]}}},required:["transactionId","timestamp","meterStop"],type:"object"},{$id:"urn:StopTransaction.conf",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{idTagInfo:{type:"object",properties:{expiryDate:{type:"string",format:"date-time"},parentIdTag:{type:"string",maxLength:20},status:{type:"string",enum:["Accepted","Blocked","Expired","Invalid","ConcurrentTx"]}},additionalProperties:false,required:["status"]}},type:"object"},{$id:"urn:TriggerMessage.req",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{requestedMessage:{type:"string",enum:["BootNotification","DiagnosticsStatusNotification","FirmwareStatusNotification","Heartbeat","MeterValues","StatusNotification"]},connectorId:{type:"integer"}},required:["requestedMessage"],type:"object"},{$id:"urn:TriggerMessage.conf",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{status:{type:"string",enum:["Accepted","Rejected","NotImplemented"]}},required:["status"],type:"object"},{$id:"urn:UnlockConnector.req",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{connectorId:{type:"integer"}},required:["connectorId"],type:"object"},{$id:"urn:UnlockConnector.conf",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{status:{type:"string",enum:["Unlocked","UnlockFailed","NotSupported"]}},required:["status"],type:"object"},{$id:"urn:UpdateFirmware.req",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{location:{type:"string",format:"uri"},retries:{type:"integer"},retrieveDate:{type:"string",format:"date-time"},retryInterval:{type:"integer"}},required:["location","retrieveDate"],type:"object"},{$id:"urn:UpdateFirmware.conf",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{},type:"object"}];var We=[{$id:"urn:Authorize.req",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,definitions:{CustomDataType:{description:"This class does not get 'AdditionalProperties = false' in the schema generation, so it can be extended with arbitrary JSON properties to allow adding custom data.",type:"object",properties:{vendorId:{type:"string",maxLength:255}},required:["vendorId"]},HashAlgorithmEnumType:{description:`Used algorithms for the hashes provided.\r
2
2
  `,type:"string",enum:["SHA256","SHA384","SHA512"]},IdTokenEnumType:{description:`Enumeration of possible idToken types.\r
3
3
  `,type:"string",enum:["Central","eMAID","ISO14443","ISO15693","KeyCode","Local","MacAddress","NoAuthorization"]},AdditionalInfoType:{description:`Contains a case insensitive identifier to use for the authorization and the type of authorization to support multiple forms of identifiers.\r
4
4
  `,type:"object",additionalProperties:false,properties:{customData:{$ref:"#/definitions/CustomDataType"},additionalIdToken:{description:`This field specifies the additional IdToken.\r
@@ -1716,7 +1716,7 @@ Base64 encoded firmware signature.\r
1716
1716
  `,type:"string",enum:["Accepted","Rejected","AcceptedCanceled","InvalidCertificate","RevokedCertificate"]},StatusInfoType:{description:`Element providing more information about the status.\r
1717
1717
  `,type:"object",additionalProperties:false,properties:{customData:{$ref:"#/definitions/CustomDataType"},reasonCode:{description:`A predefined code for the reason why the status is returned in this response. The string is case-insensitive.\r
1718
1718
  `,type:"string",maxLength:20},additionalInfo:{description:`Additional text to provide detailed information.\r
1719
- `,type:"string",maxLength:512}},required:["reasonCode"]}},properties:{customData:{$ref:"#/definitions/CustomDataType"},status:{$ref:"#/definitions/UpdateFirmwareStatusEnumType"},statusInfo:{$ref:"#/definitions/StatusInfoType"}},required:["status"],type:"object"}];var Ue=[{$schema:"http://json-schema.org/draft-07/schema",$id:"urn:AdjustPeriodicEventStreamRequest",comment:"OCPP 2.1 Edition 1 (c) OCA, Creative Commons Attribution-NoDerivatives 4.0 International Public License",definitions:{PeriodicEventStreamParamsType:{javaType:"PeriodicEventStreamParams",type:"object",additionalProperties:false,properties:{interval:{description:`Time in seconds after which stream data is sent.\r
1719
+ `,type:"string",maxLength:512}},required:["reasonCode"]}},properties:{customData:{$ref:"#/definitions/CustomDataType"},status:{$ref:"#/definitions/UpdateFirmwareStatusEnumType"},statusInfo:{$ref:"#/definitions/StatusInfoType"}},required:["status"],type:"object"}];var He=[{$schema:"http://json-schema.org/draft-07/schema",$id:"urn:AdjustPeriodicEventStreamRequest",comment:"OCPP 2.1 Edition 1 (c) OCA, Creative Commons Attribution-NoDerivatives 4.0 International Public License",definitions:{PeriodicEventStreamParamsType:{javaType:"PeriodicEventStreamParams",type:"object",additionalProperties:false,properties:{interval:{description:`Time in seconds after which stream data is sent.\r
1720
1720
  `,type:"integer",minimum:0},values:{description:`Number of items to be sent together in stream.\r
1721
1721
  `,type:"integer",minimum:0},customData:{$ref:"#/definitions/CustomDataType"}}},CustomDataType:{description:"This class does not get 'AdditionalProperties = false' in the schema generation, so it can be extended with arbitrary JSON properties to allow adding custom data.",javaType:"CustomData",type:"object",properties:{vendorId:{type:"string",maxLength:255}},required:["vendorId"]}},type:"object",additionalProperties:false,properties:{id:{type:"integer",minimum:0},params:{$ref:"#/definitions/PeriodicEventStreamParamsType"},customData:{$ref:"#/definitions/CustomDataType"}},required:["id","params"]},{$schema:"http://json-schema.org/draft-07/schema",$id:"urn:AdjustPeriodicEventStreamResponse",comment:"OCPP 2.1 Edition 1 (c) OCA, Creative Commons Attribution-NoDerivatives 4.0 International Public License",definitions:{GenericStatusEnumType:{description:`Status of operation.\r
1722
1722
  `,javaType:"GenericStatusEnum",type:"string",additionalProperties:false,enum:["Accepted","Rejected"]},StatusInfoType:{description:`Element providing more information about the status.\r
@@ -4817,10 +4817,10 @@ False to request stopping priority charging.\r
4817
4817
  \r
4818
4818
  `,type:"string",maxLength:20},evseId:{description:`EVSE id for which check was requested. \r
4819
4819
  \r
4820
- `,type:"integer",minimum:0},status:{$ref:"#/definitions/GenericStatusEnumType"},customData:{$ref:"#/definitions/CustomDataType"}},required:["vatNumber","status"]}];function le(){return crypto.randomUUID()}function R(s,e,t={}){switch(s){case "GenericError":return new v(e,t);case "RpcFrameworkError":return new ee(e,t);case "MessageTypeNotSupported":return new _(e,t);case "NotImplemented":return new j(e,t);case "NotSupported":return new z(e,t);case "InternalError":return new B(e,t);case "ProtocolError":return new G(e,t);case "SecurityError":return new J(e,t);case "FormatViolation":return new X(e,t);case "FormationViolation":return new K(e,t);case "PropertyConstraintViolation":return new Q(e,t);case "OccurrenceConstraintViolation":return new Y(e,t);case "TypeConstraintViolation":return new Z(e,t);default:return new v(e,t)}}var Et=["name","message","stack","code","rpcErrorCode","rpcErrorMessage","details"];function Ie(s){let e={};for(let t of Et){let i=s[t];if(i!==void 0){if(typeof i=="function"||typeof i=="symbol")continue;if(typeof i=="object"&&i!==null)try{JSON.stringify(i),e[t]=i;}catch{}else e[t]=i;}}return e.name||(e.name=s.name),e.message||(e.message=s.message),e}var xt="ocpp-ws-io",Dt="1.0.1";function Ee(){return `${xt}/${Dt}`}var q={debug:()=>{},info:()=>{},warn:()=>{},error:()=>{},child:()=>q};var Lt=new Set(["type"]),$t=new Set(["maximum","minimum","maxLength","minLength","pattern","format","anyOf","oneOf","not","if"]),At=new Set(["required","maxItems","minItems","maxProperties","minProperties","additionalProperties","additionalItems","exclusiveMaximum","exclusiveMinimum","multipleOf"]),jt=new Set(["enum","const"]);function Rt(s){return Lt.has(s)?"TypeConstraintViolation":At.has(s)?"OccurrenceConstraintViolation":jt.has(s)?"PropertyConstraintViolation":($t.has(s),"FormatViolation")}var ue=class{subprotocol;_ajv;constructor(e,t){this.subprotocol=e,this._ajv=new wt__default.default({allErrors:true,strict:false,multipleOfPrecision:4}),_t__default.default(this._ajv);for(let i of t){let n={...i};typeof n.$id=="string"&&n.$id.startsWith("urn:")&&(n.$id=n.$id.replace("urn:","urn/")),this._ajv.addSchema(n);}}_normalizeSchemaId(e){return e.startsWith("urn:")?e.replace("urn:","urn/"):e}validate(e,t){let i=this._normalizeSchemaId(e),n=this._ajv.getSchema(i);if(!n)return;if(!n(t)&&n.errors&&n.errors.length>0){let a=n.errors[0],o=Rt(a.keyword),d=this._ajv.errorsText(n.errors);throw R(o,d)}}hasSchema(e){return !!this._ajv.getSchema(this._normalizeSchemaId(e))}},We=new Map;function te(s,e){let t=We.get(s);if(t)return t;let i=new ue(s,e);return We.set(s,i),i}var me=null;function xe(){return me||(me=[te("ocpp1.6",ke),te("ocpp2.0.1",Fe),te("ocpp2.1",Ue)],me)}var ie={CONNECTING:0,OPEN:1,CLOSING:2,CLOSED:3},he=(n=>(n[n.NONE=0]="NONE",n[n.BASIC_AUTH=1]="BASIC_AUTH",n[n.TLS_BASIC_AUTH=2]="TLS_BASIC_AUTH",n[n.TLS_CLIENT_CERT=3]="TLS_CLIENT_CERT",n))(he||{}),I={CALL:2,CALLRESULT:3,CALLERROR:4},De=Symbol("NOREPLY");function He(s){if(s>=65&&s<=90||s>=97&&s<=122||s>=48&&s<=57)return true;switch(s){case 33:case 35:case 36:case 37:case 38:case 39:case 42:case 43:case 45:case 46:case 94:case 95:case 96:case 124:case 126:return true}return false}function ze(s){if(s.length===0)throw new SyntaxError("Unexpected end of input");let e=new Set,t=0;for(;t<s.length;){for(;t<s.length&&(s.charCodeAt(t)===32||s.charCodeAt(t)===9);)t++;let i=t;for(;t<s.length&&He(s.charCodeAt(t));)t++;if(t===i)throw new SyntaxError(`Unexpected character at index ${t}`);let n=s.substring(i,t);if(e.has(n))throw new SyntaxError(`The "${n}" subprotocol is duplicated`);for(e.add(n);t<s.length&&(s.charCodeAt(t)===32||s.charCodeAt(t)===9);)t++;if(t>=s.length)break;if(s.charCodeAt(t)!==44)throw new SyntaxError(`Unexpected character at index ${t}`);t++;let r=t;for(;r<s.length&&(s.charCodeAt(r)===32||s.charCodeAt(r)===9);)r++;if(r>=s.length||!He(s.charCodeAt(r)))throw new SyntaxError("Unexpected end of input")}if(e.size===0)throw new SyntaxError("Unexpected end of input");return e}var Mt=new Set([1004,1005,1006]);function Be(s){return s>=1e3&&s<=1014&&!Mt.has(s)||s>=3e3&&s<=4999}var Ot=/^ *[Bb][Aa][Ss][Ii][Cc] +([A-Za-z0-9._~+/-]+=*) *$/;function Ge(s,e){if(!s)return;let t=Ot.exec(s);if(t?.[1])try{let i=Buffer.from(t[1],"base64"),n=Buffer.from(`${e}:`);if(i.length>n.length&&i.subarray(0,n.length).equals(n))return i.subarray(n.length);let r=i.indexOf(58);if(r!==-1&&i.subarray(0,r).toString("utf8")===e)return i.subarray(r+1)}catch{}}function w(s,e,t,i){if(!s.writable)return;let n=qt__default.default.STATUS_CODES[e]??"Unknown",r=t??n,o={Connection:"close","Content-Type":"text/plain; charset=utf-8","Content-Length":Buffer.byteLength(r,"utf8"),...i},d=Object.entries(o).map(([p,c])=>`${p}: ${c}`).join(`\r
4821
- `);s.end(`HTTP/1.1 ${e} ${n}\r
4820
+ `,type:"integer",minimum:0},status:{$ref:"#/definitions/GenericStatusEnumType"},customData:{$ref:"#/definitions/CustomDataType"}},required:["vatNumber","status"]}];function me(){return crypto.randomUUID()}function q(s,e,t={}){switch(s){case "GenericError":return new P(e,t);case "RpcFrameworkError":return new ie(e,t);case "MessageTypeNotSupported":return new L(e,t);case "NotImplemented":return new R(e,t);case "NotSupported":return new G(e,t);case "InternalError":return new J(e,t);case "ProtocolError":return new K(e,t);case "SecurityError":return new X(e,t);case "FormatViolation":return new Y(e,t);case "FormationViolation":return new Q(e,t);case "PropertyConstraintViolation":return new Z(e,t);case "OccurrenceConstraintViolation":return new ee(e,t);case "TypeConstraintViolation":return new te(e,t);default:return new P(e,t)}}var Et=["name","message","stack","code","rpcErrorCode","rpcErrorMessage","details"];function De(s){let e={};for(let t of Et){let n=s[t];if(n!==void 0){if(typeof n=="function"||typeof n=="symbol")continue;if(typeof n=="object"&&n!==null)try{JSON.stringify(n),e[t]=n;}catch{}else e[t]=n;}}return e.name||(e.name=s.name),e.message||(e.message=s.message),e}var xt="ocpp-ws-io",Dt="1.0.1";function we(){return `${xt}/${Dt}`}var M={debug:()=>{},info:()=>{},warn:()=>{},error:()=>{},child:()=>M};var Lt=new Set(["type"]),$t=new Set(["maximum","minimum","maxLength","minLength","pattern","format","anyOf","oneOf","not","if"]),At=new Set(["required","maxItems","minItems","maxProperties","minProperties","additionalProperties","additionalItems","exclusiveMaximum","exclusiveMinimum","multipleOf"]),jt=new Set(["enum","const"]);function Rt(s){return Lt.has(s)?"TypeConstraintViolation":At.has(s)?"OccurrenceConstraintViolation":jt.has(s)?"PropertyConstraintViolation":($t.has(s),"FormatViolation")}var he=class{subprotocol;_ajv;constructor(e,t){this.subprotocol=e,this._ajv=new wt__default.default({allErrors:true,strict:false,multipleOfPrecision:4}),_t__default.default(this._ajv);for(let n of t){let i={...n};typeof i.$id=="string"&&i.$id.startsWith("urn:")&&(i.$id=i.$id.replace("urn:","urn/")),this._ajv.addSchema(i);}}_normalizeSchemaId(e){return e.startsWith("urn:")?e.replace("urn:","urn/"):e}validate(e,t){let n=this._normalizeSchemaId(e),i=this._ajv.getSchema(n);if(!i)return;if(!i(t)&&i.errors&&i.errors.length>0){let a=i.errors[0],o=Rt(a.keyword),d=this._ajv.errorsText(i.errors);throw q(o,d)}}hasSchema(e){return !!this._ajv.getSchema(this._normalizeSchemaId(e))}},ze=new Map;function ne(s,e){let t=ze.get(s);if(t)return t;let n=new he(s,e);return ze.set(s,n),n}var fe=null;function _e(){return fe||(fe=[ne("ocpp1.6",Ue),ne("ocpp2.0.1",We),ne("ocpp2.1",He)],fe)}var re={CONNECTING:0,OPEN:1,CLOSING:2,CLOSED:3},ge=(i=>(i[i.NONE=0]="NONE",i[i.BASIC_AUTH=1]="BASIC_AUTH",i[i.TLS_BASIC_AUTH=2]="TLS_BASIC_AUTH",i[i.TLS_CLIENT_CERT=3]="TLS_CLIENT_CERT",i))(ge||{}),x={CALL:2,CALLRESULT:3,CALLERROR:4},Le=Symbol("NOREPLY");function Be(s){if(s>=65&&s<=90||s>=97&&s<=122||s>=48&&s<=57)return true;switch(s){case 33:case 35:case 36:case 37:case 38:case 39:case 42:case 43:case 45:case 46:case 94:case 95:case 96:case 124:case 126:return true}return false}function Ge(s){if(s.length===0)throw new SyntaxError("Unexpected end of input");let e=new Set,t=0;for(;t<s.length;){for(;t<s.length&&(s.charCodeAt(t)===32||s.charCodeAt(t)===9);)t++;let n=t;for(;t<s.length&&Be(s.charCodeAt(t));)t++;if(t===n)throw new SyntaxError(`Unexpected character at index ${t}`);let i=s.substring(n,t);if(e.has(i))throw new SyntaxError(`The "${i}" subprotocol is duplicated`);for(e.add(i);t<s.length&&(s.charCodeAt(t)===32||s.charCodeAt(t)===9);)t++;if(t>=s.length)break;if(s.charCodeAt(t)!==44)throw new SyntaxError(`Unexpected character at index ${t}`);t++;let r=t;for(;r<s.length&&(s.charCodeAt(r)===32||s.charCodeAt(r)===9);)r++;if(r>=s.length||!Be(s.charCodeAt(r)))throw new SyntaxError("Unexpected end of input")}if(e.size===0)throw new SyntaxError("Unexpected end of input");return e}var Mt=new Set([1004,1005,1006]);function Je(s){return s>=1e3&&s<=1014&&!Mt.has(s)||s>=3e3&&s<=4999}var Ot=/^ *[Bb][Aa][Ss][Ii][Cc] +([A-Za-z0-9._~+/-]+=*) *$/;function Ke(s,e){if(!s)return;let t=Ot.exec(s);if(t?.[1])try{let n=Buffer.from(t[1],"base64"),i=Buffer.from(`${e}:`);if(n.length>i.length&&n.subarray(0,i.length).equals(i))return n.subarray(i.length);let r=n.indexOf(58);if(r!==-1&&n.subarray(0,r).toString("utf8")===e)return n.subarray(r+1)}catch{}}function _(s,e,t,n){if(!s.writable)return;let i=qt__default.default.STATUS_CODES[e]??"Unknown",r=t??i,o={Connection:"close","Content-Type":"text/plain; charset=utf-8","Content-Length":Buffer.byteLength(r,"utf8"),...n},d=Object.entries(o).map(([p,c])=>`${p}: ${c}`).join(`\r
4821
+ `);s.end(`HTTP/1.1 ${e} ${i}\r
4822
4822
  ${d}\r
4823
4823
  \r
4824
- ${r}`);}var {CONNECTING:F,OPEN:M,CLOSING:we,CLOSED:D}=ie,re=class s extends events.EventEmitter{static CONNECTING=F;static OPEN=M;static CLOSING=we;static CLOSED=D;_options;_state=D;_ws=null;_protocol;_identity;_handlers=new Map;_wildcardHandler=null;_pendingCalls=new Map;_pendingResponses=new Set;_callQueue;_pingTimer=null;_pongTimer=null;_closePromise=null;_reconnectAttempt=0;_reconnectTimer=null;_badMessageCount=0;_lastActivity=0;_outboundBuffer=[];_offlineQueue=[];_middleware;_validators=[];_strictProtocols=null;_handshake=null;_logger=q;_exchangeLog=false;_prettify=false;constructor(e){if(super(),this.setMaxListeners(0),!e.identity)throw new Error("identity is required");this._identity=e.identity,this._options={reconnect:true,maxReconnects:1/0,backoffMin:1e3,backoffMax:3e4,callTimeoutMs:3e4,pingIntervalMs:3e4,deferPingsOnActivity:false,callConcurrency:1,maxBadMessages:1/0,respondWithDetailedErrors:false,securityProfile:0,...e},this._callQueue=new ce(this._options.callConcurrency),this._middleware=new pe;let t=this._options.logging,i=de(t,{component:"OCPPClient",identity:this._identity});this._logger=i||q,t&&typeof t=="object"&&(this._exchangeLog=t.exchangeLog??false,this._prettify=t.prettify??false),this._options.logging&&this.use(Se(this._logger,this._identity,this._options.logging)),this._options.strictMode&&this._setupValidators();}_logExchange(e,t,i,n){if(!this._logger)return;let r=e==="OUT"?"\u2192":"\u2190",a=t==="CALLERROR"?"warn":this._exchangeLog?"info":"debug";if(this._exchangeLog&&this._prettify){let o=t==="CALLERROR"?"\u{1F6A8}":t==="CALLRESULT"?"\u2705":"\u26A1",d=i??t,p=`${o} ${this._identity} ${r} ${d} [${e}]`;this._logger?.[a]?.(p,{...n,direction:e});}else this._exchangeLog?this._logger?.[a]?.(`${t} ${r}`,{...n,direction:e}):this._logger?.[a]?.(`${t} ${r}`,n);}get log(){return this._logger||q}get identity(){return this._options.identity}get endpoint(){return this._options.endpoint}get options(){return this._options}get protocol(){return this._protocol}get state(){return this._state}get securityProfile(){return this._options.securityProfile??0}async connect(){if(this._state!==D)throw new Error(`Cannot connect: client is in state ${this._state}`);return this._state=F,this._reconnectAttempt=0,this._connectInternal()}async _connectInternal(){return new Promise((e,t)=>{let i=this._buildEndpoint(),n=this._buildWsOptions();this._logger?.debug?.("Connecting",{url:i}),this.emit("connecting",{url:i});let r=new ne__default.default(i,this._options.protocols??[],n);this._ws=r;let a=()=>{if(p(),this._state=M,this._protocol=r.protocol,this._badMessageCount=0,r.protocol&&this._reconnectAttempt===0&&(this._options.protocols=[r.protocol]),this._attachWebsocket(r),this._startPing(),this._flushOfflineQueue(),this._outboundBuffer.length>0){let m=this._outboundBuffer;this._outboundBuffer=[];for(let h of m)this._ws?.send(h);}this._logger?.info?.("Connected",{protocol:r.protocol});let l={response:r._req?.res};this.emit("open",l),e(l);},o=c=>{p(),this._state=D,this._logger?.error?.("Connection error",{error:c.message}),this.emit("error",c),t(c);},d=(c,l)=>{p(),this._state=D;let m=new H(`Unexpected HTTP response: ${l.statusCode}`,l.statusCode??0,l.headers);this._logger?.error?.("Unexpected HTTP response",{statusCode:l.statusCode}),this.emit("error",m),t(m);},p=()=>{r.removeListener("open",a),r.removeListener("error",o),r.removeListener("unexpected-response",d);};r.on("open",a),r.on("error",o),r.on("unexpected-response",d);})}async close(e={}){let{code:t=1e3,reason:i="",awaitPending:n=true,force:r=false}=e;return this._closePromise?this._closePromise:this._state===D?{code:1e3,reason:""}:(this._reconnectTimer&&(clearTimeout(this._reconnectTimer),this._reconnectTimer=null),this._closePromise=this._closeInternal(t,i,n,r),this._closePromise)}async _closeInternal(e,t,i,n){if(this._state=we,this._stopPing(),!n&&i){let r=Array.from(this._pendingCalls.values()).map(a=>new Promise(o=>{let d=a.resolve,p=a.reject;a.resolve=c=>{d(c),o();},a.reject=c=>{p(c),o();};}));r.length>0&&await Promise.allSettled(r);}return new Promise(r=>{if(!this._ws||this._ws.readyState===ne__default.default.CLOSED){this._state=D,this._cleanup();let o={code:e,reason:t};this.emit("close",o),r(o);return}let a=(o,d)=>{this._ws?.removeListener("close",a),this._state=D,this._cleanup();let p={code:o,reason:d.toString()};this.emit("close",p),r(p);};this._ws.on("close",a),n?this._ws.terminate():this._ws.close(Be(e)?e:1e3,t);})}handle(...e){if(e.length===1&&typeof e[0]=="function"){if(this._wildcardHandler)throw new Error("Wildcard handler is already registered.");this._wildcardHandler=e[0];}else if(e.length===2&&typeof e[0]=="string"&&typeof e[1]=="function"){if(this._handlers.has(e[0]))throw new Error(`Handler for '${e[0]}' is already registered.`);this._handlers.set(e[0],e[1]);}else if(e.length===3&&typeof e[0]=="string"&&typeof e[1]=="string"&&typeof e[2]=="function"){let t=`${e[0]}:${e[1]}`;if(this._handlers.has(t))throw new Error(`Handler for '${e[1]}' (protocol: ${e[0]}) is already registered.`);this._handlers.set(t,e[2]);}else throw new Error("Invalid arguments: provide (version, method, handler), (method, handler), or (wildcardHandler)")}removeHandler(e,t){e&&t?this._handlers.delete(`${e}:${t}`):e?this._handlers.delete(e):this._wildcardHandler=null;}removeAllHandlers(){this._handlers.clear(),this._wildcardHandler=null;}use(e){this._middleware.use(e);}async call(...e){let t,i,n;if(e.length>=3&&typeof e[0]=="string"&&typeof e[1]=="string"?(t=e[1],i=e[2]??{},n=e[3]??{}):(t=e[0],i=e[1]??{},n=e[2]??{}),this._state!==M){if(this._options.offlineQueue&&(this._state===D||this._state===F))return new Promise((a,o)=>{let d=this._options.offlineQueueMaxSize??100;this._offlineQueue.length>=d&&(this._offlineQueue.shift(),this._logger?.warn?.("Offline queue full \u2014 dropping oldest message",{method:t,queueSize:this._offlineQueue.length})),this._offlineQueue.push({method:t,params:i,options:n,resolve:a,reject:o}),this._logger?.debug?.("Call queued offline",{method:t,queueSize:this._offlineQueue.length});});throw new Error(`Cannot call: client is in state ${this._state}`)}let r=n.retries??0;return r>0?this._callWithRetry(t,i,n,r):this._callQueue.push(()=>this._sendCall(t,i,n))}async safeCall(...e){try{return await this.call(...e)}catch(t){if(t.name!=="TimeoutError"){let i={method:e.find(n=>typeof n=="string"&&!n.startsWith("ocpp")),error:t};this._logger?.warn?this._logger.warn("SafeCall failed",i):console.warn("SafeCall failed",i);}return}}async _sendCall(e,t,i){let n=i.idempotencyKey??le(),r=i.timeoutMs??this._options.callTimeoutMs,a={type:"outgoing_call",messageId:n,method:e,params:t,options:i},o;return await this._middleware.execute(a,async d=>{let p=d;this._options.strictMode&&this._protocol&&this._validateOutbound(p.method,p.params,"req");let c=[I.CALL,n,p.method,p.params],l=JSON.stringify(c);return o=await new Promise((m,h)=>{let E=setTimeout(()=>{this._pendingCalls.delete(n),h(new k(`Call to "${p.method}" timed out after ${r}ms`));},r),f=()=>{clearTimeout(E),this._pendingCalls.delete(n),h(new Error("Aborted"));};i.signal&&i.signal.addEventListener("abort",f),this._pendingCalls.set(n,{resolve:m,reject:h,timeoutHandle:E,abortHandler:i.signal?()=>i.signal?.removeEventListener("abort",f):void 0,method:p.method,sentAt:Date.now()}),this._ws?.readyState===ne__default.default.OPEN?this._safeSend(this._ws,l,A=>{A&&(clearTimeout(E),this._pendingCalls.delete(n),h(A));}):this._state===F?(this._logger?.debug?.("Buffering call",{method:p.method}),this._outboundBuffer.push(l)):(clearTimeout(E),this._pendingCalls.delete(n),h(new Error(`WebSocket is not open (state: ${this._state})`)));}),o}),o}sendRaw(e){if(this._state===M&&this._ws)this._ws.send(e);else if(this._state===F)this._outboundBuffer.push(e);else throw new Error("Cannot send: client is not connected")}reconfigure(e){Object.assign(this._options,e),e.callConcurrency!==void 0&&this._callQueue.setConcurrency(e.callConcurrency),(e.strictMode!==void 0||e.strictModeValidators!==void 0)&&this._setupValidators(),e.pingIntervalMs!==void 0&&(this._stopPing(),this._state===M&&this._startPing());}_attachWebsocket(e){e.on("message",t=>this._onMessage(t)),e.on("close",(t,i)=>this._onClose(t,i)),e.on("error",t=>this.emit("error",t)),e.on("ping",()=>{this._recordActivity(),this.emit("ping");}),e.on("pong",()=>{this._pongTimer&&(clearTimeout(this._pongTimer),this._pongTimer=null),this._recordActivity(),this.emit("pong");});}_buildMessageEventContext(e,t){return {...e,timestamp:new Date().toISOString(),latencyMs:t}}_emitMessageEvent(e,t,i,n){let r=this._buildMessageEventContext(i,n),a={message:e,direction:t,ctx:r};this.emit("message",a);}_onMessage(e,t){this._recordActivity();let i;try{if(t!==void 0?i=t:i=JSON.parse(e),!Array.isArray(i))throw new Error("Message is not an array")}catch(d){this._onBadMessage(typeof e=="string"?e:e.toString(),d);return}let n=i[0],r=i[1];if(typeof r!="string"){this._onBadMessage(typeof e=="string"?e:e.toString(),new _(`Invalid MessageId type: ${typeof r} (expected string)`));return}if(n===I.CALL&&i.length<4||n===I.CALLRESULT&&i.length<3||n===I.CALLERROR&&i.length<5){this._onBadMessage(JSON.stringify(i),new _(`Missing payload elements for message type ${n}`));return}let a=n===I.CALLERROR?4:n===I.CALL?3:2,o=i[a];if(typeof o!="object"||o===null||Array.isArray(o)){this._onBadMessage(JSON.stringify(i),new _(`Payload must be a JSON object, got ${o===null?"null":Array.isArray(o)?"array":typeof o}`));return}switch(n){case I.CALL:this._handleIncomingCall(i);break;case I.CALLRESULT:this._handleCallResult(i);break;case I.CALLERROR:this._handleCallError(i);break;default:this._onBadMessage(JSON.stringify(i),new _(`Unknown message type: ${n}`));}}async _handleIncomingCall(e){let[,t,i,n]=e,r={type:"incoming_call",messageId:t,method:i,params:n,protocol:this._protocol};try{await this._middleware.execute(r,async a=>{let o=a,d=[I.CALL,o.messageId,o.method,o.params];if(this._emitMessageEvent(d,"IN",o),this.emit("call",d),this._state===M)try{if(this._pendingResponses.has(o.messageId))throw R("RpcFrameworkError",`Already processing call with ID: ${o.messageId}`);let p=(this._protocol?this._handlers.get(`${this._protocol}:${o.method}`):void 0)??this._handlers.get(o.method);if(!p&&!this._wildcardHandler)throw new j(`Method "${o.method}" not implemented`);this._options.strictMode&&this._protocol&&this._validateInbound(o.method,o.params,"req"),this._pendingResponses.add(o.messageId);let c=new AbortController,l={messageId:o.messageId,method:o.method,protocol:this._protocol,params:o.params,signal:c.signal},m;if(p?m=await p(l):this._wildcardHandler&&(m=await this._wildcardHandler(o.method,l)),this._pendingResponses.delete(o.messageId),m===De)return;this._options.strictMode&&this._protocol&&this._validateOutbound(o.method,m,"conf");let h=[I.CALLRESULT,o.messageId,m];return this._ws?.send(JSON.stringify(h)),this.emit("callResult",h),m}catch(p){this._pendingResponses.delete(o.messageId);let c=p instanceof v||p.rpcErrorCode?p:R("InternalError",p.message),l=this._options.respondWithDetailedErrors?Ie(p):{},m=[I.CALLERROR,o.messageId,c.rpcErrorCode,c.rpcErrorMessage||p.message||"",l];throw this._ws?.send(JSON.stringify(m)),this.emit("callError",m),p}});}catch{}}async _handleCallResult(e){let[,t,i]=e;if(!this._pendingCalls.has(t)){this._logger?.warn?.("Received CallResult for unknown messageId",{messageId:t});return}let n=this._pendingCalls.get(t),r={type:"incoming_result",messageId:t,payload:i,method:n.method};await this._middleware.execute(r,async a=>{let o=a,d=this._pendingCalls.get(o.messageId);if(!d)return;let p=Date.now()-d.sentAt;this._emitMessageEvent(e,"IN",o,p),this.emit("callResult",e),clearTimeout(d.timeoutHandle),d.abortHandler,this._pendingCalls.delete(o.messageId),d.resolve(o.payload);});}async _handleCallError(e){let[,t]=e,i=this._pendingCalls.get(t);if(!i){this._logger?.warn?.("Received CallError for unknown messageId",{messageId:t});return}let n={type:"incoming_error",messageId:t,error:e,method:i.method};await this._middleware.execute(n,async r=>{let a=r,o=this._pendingCalls.get(a.messageId);if(!o)return;let d=Date.now()-o.sentAt;this._emitMessageEvent(e,"IN",a,d),this.emit("callError",e);let[,,p,c,l]=a.error;clearTimeout(o.timeoutHandle),this._pendingCalls.delete(a.messageId);let m=R(p,c,l);o.reject(m);});}_onBadMessage(e,t){this._badMessageCount++,this._logger?.warn?.("Bad message",{error:t.message,count:this._badMessageCount}),this.emit("badMessage",{message:e,error:t});let i=e.match(/^\s*\[\s*2\s*,\s*"([^"]+)"/);if(i?.[1]&&this._ws){let n=[I.CALLERROR,i[1],"FormatViolation",t.message||"Invalid message format",{}];this._ws.send(JSON.stringify(n)),this.emit("callError",n);}this._badMessageCount>=this._options.maxBadMessages&&this.close({code:1002,reason:"Too many bad messages"}).catch(()=>{});}_rejectPendingCalls(e){for(let[,t]of this._pendingCalls)clearTimeout(t.timeoutHandle),t.reject(new Error(e));this._pendingCalls.clear(),this._pendingResponses.clear();}_onClose(e,t){this._stopPing();let i=t.toString();this._rejectPendingCalls(`Connection closed (${e}: ${i})`),this._state!==we?(this._logger?.info?.("Disconnected",{code:e,reason:i}),this.emit("disconnect",{code:e,reason:i}),this._options.reconnect&&this._reconnectAttempt<this._options.maxReconnects?this._scheduleReconnect():(this._state=D,this.emit("close",{code:e,reason:i}))):this._state=D;}static _INTOLERABLE_ERRORS=new Set(["Maximum redirects exceeded","Server sent no subprotocol","Server sent an invalid subprotocol","Server sent a subprotocol but none was requested","Invalid Sec-WebSocket-Accept header"]);_scheduleReconnect(){this._reconnectAttempt++,this._state=F;let e=this._options.backoffMin,t=this._options.backoffMax,i=Math.min(t,e*2**(this._reconnectAttempt-1)*(.5+Math.random()*.5));this._logger?.warn?.("Reconnecting",{attempt:this._reconnectAttempt,delayMs:Math.round(i)}),this.emit("reconnect",{attempt:this._reconnectAttempt,delay:i}),this._reconnectTimer=setTimeout(async()=>{this._reconnectTimer=null;try{await this._connectInternal();}catch(n){let r=n instanceof Error?n.message:"";if(s._INTOLERABLE_ERRORS.has(r)){this._logger?.error?.("Intolerable error \u2014 stopping reconnection",{error:r}),this._state=D,this.emit("close",{code:1001,reason:r});return}this._reconnectAttempt<this._options.maxReconnects&&this._options.reconnect?this._scheduleReconnect():(this._state=D,this.emit("close",{code:1001,reason:"Max reconnection attempts exhausted"}));}},i);}_flushOfflineQueue(){if(this._offlineQueue.length===0)return;let e=this._offlineQueue.splice(0,this._offlineQueue.length);this._logger?.info?.("Flushing offline queue",{count:e.length});for(let t of e)this._callQueue.push(()=>this._sendCall(t.method,t.params,t.options)).then(t.resolve).catch(t.reject);}async _callWithRetry(e,t,i,n){let r=i.retryDelayMs??1e3,a=i.retryMaxDelayMs??3e4;for(let o=0;o<=n;o++)try{return await this._callQueue.push(()=>this._sendCall(e,t,i))}catch(d){if(o===n||!(d instanceof k))throw d;let p=Math.min(a,r*2**o),c=Math.random()*p;this._logger?.warn?.("Call retry",{method:e,attempt:o+1,maxRetries:n,delayMs:Math.round(c)}),await new Promise(l=>setTimeout(l,c));}throw new Error("Retry exhausted")}static _BACKPRESSURE_THRESHOLD=512*1024;_safeSend(e,t,i){if(!e||e.readyState!==ne__default.default.OPEN){i?.(new Error("WebSocket is not open"));return}if(e.bufferedAmount>s._BACKPRESSURE_THRESHOLD){this._logger?.warn?.("Backpressure \u2014 pausing send",{identity:this._identity,bufferedAmount:e.bufferedAmount,threshold:s._BACKPRESSURE_THRESHOLD}),this.emit("backpressure",{identity:this._identity,bufferedAmount:e.bufferedAmount});let n=0,r=setInterval(()=>{if(n+=50,!e||e.readyState!==ne__default.default.OPEN){clearInterval(r),i?.(new Error("WebSocket closed during backpressure wait"));return}(e.bufferedAmount<=s._BACKPRESSURE_THRESHOLD||n>=1e4)&&(clearInterval(r),e.send(t,i));},50);}else e.send(t,i);}_startPing(){if(this._options.pingIntervalMs<=0)return;let e=this._options.pongTimeoutMs??this._options.pingIntervalMs+5e3,t=()=>{if(this._state!==M||!this._ws)return;if(this._options.deferPingsOnActivity){let r=Date.now()-this._lastActivity;if(r<this._options.pingIntervalMs){this._pingTimer=setTimeout(t,this._options.pingIntervalMs-r);return}}this._ws.ping(),e>0&&(this._pongTimer=setTimeout(()=>{this._logger?.warn?.("Pong timeout \u2014 terminating dead connection",{identity:this._identity,timeoutMs:e}),this._ws?.terminate();},e));let n=this._options.pingIntervalMs*(.75+Math.random()*.5);this._pingTimer=setTimeout(t,n);},i=this._options.pingIntervalMs*(.75+Math.random()*.5);this._pingTimer=setTimeout(t,i);}_stopPing(){this._pingTimer&&(clearTimeout(this._pingTimer),this._pingTimer=null);}_recordActivity(){this._lastActivity=Date.now();}_setupValidators(){this._options.strictModeValidators?this._validators=this._options.strictModeValidators:this._validators=xe(),Array.isArray(this._options.strictMode)?this._strictProtocols=this._options.strictMode:this._strictProtocols=null;}_validateOutbound(e,t,i){let n=this._findValidator();if(!n||this._options.strictModeMethods&&!this._options.strictModeMethods.includes(e))return;let r=`urn:${e}.${i}`;try{n.validate(r,t);}catch(a){throw this.emit("strictValidationFailure",{message:t,error:a}),a}}_validateInbound(e,t,i){let n=this._findValidator();if(!n||this._options.strictModeMethods&&!this._options.strictModeMethods.includes(e))return;let r=`urn:${e}.${i}`;try{n.validate(r,t);}catch(a){throw this.emit("strictValidationFailure",{message:t,error:a}),a}}_findValidator(){return !this._protocol||this._strictProtocols&&!this._strictProtocols.includes(this._protocol)?null:this._validators.find(e=>e.subprotocol===this._protocol)??null}_buildEndpoint(){let e=this._options.endpoint;if(e.endsWith("/")||(e+="/"),e+=encodeURIComponent(this._identity),this._options.query){let t=new URLSearchParams(this._options.query);e+=(e.includes("?")?"&":"?")+t.toString();}return e}_buildWsOptions(){let e={headers:{...this._options.headers,"User-Agent":Ee()}},t=this._options.securityProfile??0;if((t===1||t===2)&&this._options.password){let n=Buffer.from(`${this._identity}:${this._options.password.toString()}`).toString("base64");e?.headers&&(e.headers.Authorization=`Basic ${n}`);}if(t===2||t===3){let n=this._options.tls??{};n.ca&&(e.ca=n.ca),n.rejectUnauthorized!==void 0&&(e.rejectUnauthorized=n.rejectUnauthorized),t===3&&(n.cert&&(e.cert=n.cert),n.key&&(e.key=n.key),n.passphrase&&(e.passphrase=n.passphrase));}let i=this._options.compression;return i&&(e.perMessageDeflate=i===true?{zlibDeflateOptions:{level:6,memLevel:8},zlibInflateOptions:{},clientNoContextTakeover:true,serverNoContextTakeover:true}:{zlibDeflateOptions:{level:i.level??6,memLevel:i.memLevel??8},zlibInflateOptions:{},clientNoContextTakeover:i.clientNoContextTakeover??true,serverNoContextTakeover:i.serverNoContextTakeover??true}),e}_cleanup(){this._stopPing(),this._pongTimer&&(clearTimeout(this._pongTimer),this._pongTimer=null),this._reconnectTimer&&(clearTimeout(this._reconnectTimer),this._reconnectTimer=null),this._closePromise=null,this._ws=null;}};var ae=class extends Map{_maxSize;constructor(e){if(super(),e<1)throw new RangeError("LRUMap maxSize must be >= 1");this._maxSize=e;}get maxSize(){return this._maxSize}set(e,t){if(this.has(e)&&this.delete(e),super.set(e,t),this.size>this._maxSize){let i=this.keys().next().value;i!==void 0&&this.delete(i);}return this}get(e){if(!this.has(e))return;let t=super.get(e);return this.delete(e),super.set(e,t),t}};async function Je(s,e){let t=-1,i=async(n,r)=>{if(r&&(e.state={...e.state||{},...r||{}}),n<=t)throw new Error("next() called multiple times in middleware");t=n;let a=s[n];n!==s.length&&a&&(e.next=i.bind(null,n+1),await a(e));};await i(0);}var $=class extends events.EventEmitter{patterns;middlewares;authCallback=null;_routeCORS;_routeConfig;_regexPatterns=[];constructor(e,t){super(),this.patterns=[],this.middlewares=t??[],e?.length&&this.route(...e);}route(...e){this.patterns.push(...e);for(let t of e)typeof t!="string"&&this._regexPatterns.push({regex:t,paramNames:[]});return this}use(...e){return this.middlewares.push(...e),this}cors(e){return this._routeCORS=e,this}config(e){return this._routeConfig=e,this}auth(e){return this.authCallback=e,this}handle(...e){return this.on("client",t=>{let i=e[e.length-1],n=[...e];typeof i=="function"&&(n[n.length-1]=(...r)=>{let a=r.length-1,o=r[a];return o&&typeof o=="object"&&Object.defineProperty(o,"client",{value:t,enumerable:true,configurable:true}),i(...r)}),t.handle(...n);}),this}};function kt(...s){return new $(s)}function Xe(s){return s.split(".").reduce((e,t)=>(e<<8)+parseInt(t,10),0)>>>0}function Qe(s,e){let t=s;t.startsWith("::ffff:")&&(t=t.substring(7));for(let i of e){if(i===t)return true;if(i.includes("/")){let n=i.split("/"),r=n[0],a=n[1];if(!r||!a)continue;let o=parseInt(a,10);if(net.isIPv4(t)&&net.isIPv4(r)){let d=Xe(t),p=Xe(r),c=o===0?0:-1<<32-o>>>0;if((d&c)===(p&c))return true}}}return false}function _e(s,e){if(e.allowedIPs&&e.allowedIPs.length>0){let t=s.socket.remoteAddress;if(!t||!Qe(t,e.allowedIPs))return {allowed:false,reason:"IP address not allowed"}}if(e.allowedSchemes&&e.allowedSchemes.length>0){let t=s.socket instanceof tls.TLSSocket?"wss":"ws",i=s.headers["x-forwarded-proto"];if(typeof i=="string"&&(t=i==="https"||i==="wss"?"wss":"ws"),!e.allowedSchemes.includes(t))return {allowed:false,reason:"Protocol scheme not allowed"}}if(e.allowedOrigins&&e.allowedOrigins.length>0){let t=s.headers.origin;if(typeof t=="string"&&!e.allowedOrigins.includes(t))return {allowed:false,reason:"Origin not allowed"}}return {allowed:true}}var U=class{children=new Map;paramChild=null;paramName="";wildcardChild=null;routers=[]};function Ye(s){return s.replace(/\/+/g,"/").replace(/^\/|\/$/g,"").split("/").filter(Boolean)}var fe=class{root=new U;_frozen=false;_size=0;get size(){return this._size}insert(e,t){this._frozen&&(this._frozen=false);let i=Ye(e),n=this.root;for(let r of i)if(r==="*"){n.wildcardChild||(n.wildcardChild=new U),n=n.wildcardChild;break}else if(r.startsWith(":")){let a=r.slice(1);if(!n.paramChild)n.paramChild=new U,n.paramChild.paramName=a;else if(n.paramChild.paramName!==a)throw new Error(`Route conflict: param ":${a}" conflicts with existing ":${n.paramChild.paramName}" at the same position in pattern "${e}"`);n=n.paramChild;}else {let a=r.toLowerCase(),o=n.children.get(a);o||(o=new U,n.children.set(a,o)),n=o;}n.routers.push(t),this._size++;}match(e){let t=Ye(e),i=[];if(this._matchRecursive(this.root,t,0,{},i),i.length===0)return null;let n=i[0].params,r=[];for(let a of i)r.push(...a.routers);return {routers:r,params:n}}_matchRecursive(e,t,i,n,r){if(i===t.length){e.routers.length>0&&r.push({routers:[...e.routers],params:{...n}});return}let a=t[i],o=a.toLowerCase(),d=e.children.get(o);if(d&&this._matchRecursive(d,t,i+1,n,r),e.paramChild){let p={...n};p[e.paramChild.paramName]=decodeURIComponent(a),this._matchRecursive(e.paramChild,t,i+1,p,r);}e.wildcardChild&&e.wildcardChild.routers.length>0&&r.push({routers:[...e.wildcardChild.routers],params:{...n}});}freeze(){this._frozen||(this._freezeNode(this.root),this._frozen=true);}_freezeNode(e){Object.freeze(e.routers),e.paramChild&&this._freezeNode(e.paramChild),e.wildcardChild&&this._freezeNode(e.wildcardChild);for(let t of e.children.values())this._freezeNode(t);}get frozen(){return this._frozen}};var oe=class extends re{_serverSession;_serverHandshake;constructor(e,t){super(e),this._serverSession=t.session,this._serverHandshake=t.handshake,this._adaptiveMultiplier=t.adaptiveMultiplier??null,this._workerPool=t.workerPool??null,this._state=ie.OPEN,this._identity=this._options.identity,this._ws=t.ws,this._protocol=t.protocol??t.ws.protocol,this._attachServerWebsocket(t.ws),this._startPing();}_rateLimits={};_adaptiveMultiplier=null;_workerPool=null;_checkRateLimit(e){let t=this._options.rateLimit;if(!t)return true;let i=Date.now(),n=(r,a,o)=>{let d=this._rateLimits[r];if(!d)d={tokens:a,lastRefill:i},this._rateLimits[r]=d;else {let p=i-d.lastRefill,c=this._adaptiveMultiplier?.()??1,l=a/o*c,m=p*l;m>0&&(d.tokens=Math.min(a,d.tokens+m),d.lastRefill=i);}return d.tokens>=1?(d.tokens-=1,true):false};if(!n("global",t.limit,t.windowMs))return false;if(e&&t.methods?.[e]){let r=t.methods[e];if(!n(`method:${e}`,r.limit,r.windowMs))return false}return true}_attachServerWebsocket(e){e.on("message",t=>{this._recordActivity();let i=this._options.rateLimit;if(i){let n,r;if(i.methods)try{r=JSON.parse(t),Array.isArray(r)&&r[0]===2&&(n=r[2]);}catch{}if(!this._checkRateLimit(n)){this._handleRateLimitExceeded(r||t.toString());return}if(r!==void 0){this._onMessage(t,r);return}}if(this._workerPool){let n=t;this._workerPool.parse(n).then(r=>{this._onMessage(t,r.message);}).catch(()=>{this._onMessage(t);});return}this._onMessage(t);}),e.on("close",(t,i)=>this._onClose(t,i)),e.on("error",t=>{this.listenerCount("error")>0?this.emit("error",t):this._logger?.debug?.("WebSocket error (unhandled by client listener)",{error:t.message});}),e.on("ping",()=>{this._recordActivity(),this.emit("ping");}),e.on("pong",()=>{this._pongTimer&&(clearTimeout(this._pongTimer),this._pongTimer=null),this._recordActivity(),this.emit("pong");});}_handleRateLimitExceeded(e){let i=this._options.rateLimit.onLimitExceeded||"ignore";if(i==="disconnect")this._logger?.warn?.("Rate limit exceeded \u2014 disconnecting client",{identity:this.identity}),this._ws?.terminate();else if(typeof i=="function")try{let n=i(this,e);n instanceof Promise&&n.catch(r=>{this._logger?.error?.("Error in custom onLimitExceeded handler",{identity:this.identity,error:r});});}catch(n){this._logger?.error?.("Error in custom onLimitExceeded handler",{identity:this.identity,error:n});}else this._logger?.debug?.("Rate limit exceeded \u2014 ignoring message",{identity:this.identity});}get session(){return this._serverSession}get handshake(){return this._serverHandshake}async connect(){throw new Error("Cannot connect from server client \u2014 connection is managed by the server")}close(e={}){return super.close(e)}};var Le=class{_workers=[];_nextWorker=0;_taskId=0;_pending=new Map;_maxQueueSize;_terminated=false;constructor(e={}){let t=e.poolSize??Math.max(2,os.cpus().length-2);this._maxQueueSize=e.maxQueueSize??1e4;let i=path.resolve(__dirname,"parse-worker.js");for(let n=0;n<t;n++){let r=new worker_threads.Worker(i);r.on("message",a=>{let o=this._pending.get(a.id);o&&(this._pending.delete(a.id),a.error?o.reject(new Error(a.error)):o.resolve({message:a.message,validationError:a.validationError}));}),r.on("error",a=>{console.error(`[WorkerPool] Worker ${n} error:`,a.message);}),this._workers.push(r);}}get size(){return this._workers.length}get pendingTasks(){return this._pending.size}parse(e,t){return this._terminated?Promise.reject(new Error("WorkerPool has been shut down")):this._pending.size>=this._maxQueueSize?Promise.reject(new Error(`WorkerPool queue full (${this._maxQueueSize} pending tasks)`)):new Promise((i,n)=>{let r=this._taskId++;this._pending.set(r,{resolve:i,reject:n});let a=this._workers[this._nextWorker%this._workers.length];this._nextWorker=(this._nextWorker+1)%this._workers.length,a.postMessage({id:r,buffer:e,schemaInfo:t});})}async shutdown(){if(this._terminated)return;this._terminated=true;for(let[t,i]of this._pending)i.reject(new Error("WorkerPool shutting down")),this._pending.delete(t);let e=this._workers.map(async t=>{try{await Promise.race([t.terminate(),new Promise(i=>setTimeout(i,5e3))]);}catch{}});await Promise.allSettled(e),this._workers=[];}};function Ze(s={}){try{return new Le(s)}catch{return null}}var Ae=class extends events.EventEmitter{_options;_trie=new fe;_globalMiddlewareRouters=[];_regexRouters=[];_clients=new Set;_clientsByIdentity=new Map;_httpServers=new Set;_wss=null;_state="OPEN";_adapter=null;_httpServerAbortControllers=new Set;_logger=null;_globalCORS;_connectionBuckets=new Map;_adaptiveLimiter=null;_plugins=[];_workerPool=null;_nodeId=le();_sessions;_gcInterval=null;_sessionTimeoutMs;constructor(e={}){if(super(),this.setMaxListeners(0),e.strictMode&&!e.protocols?.length)throw new Error("strictMode requires protocols to be specified (e.g. protocols: ['ocpp1.6'])");this._options={securityProfile:0,callTimeoutMs:3e4,pingIntervalMs:3e4,deferPingsOnActivity:false,callConcurrency:1,maxBadMessages:1/0,respondWithDetailedErrors:false,handshakeTimeoutMs:3e4,sessionTtlMs:7200*1e3,...e},this._sessionTimeoutMs=this._options.sessionTtlMs;let t=this._options.maxSessions??5e4;this._sessions=new ae(t),this._wss=new ne.WebSocketServer({noServer:true,maxPayload:this._options.maxPayloadBytes??65536,perMessageDeflate:this._buildCompressionConfig()}),this._gcInterval=setInterval(()=>{let r=Date.now();for(let[a,o]of this._sessions.entries())r-o.lastActive>this._sessionTimeoutMs&&this._sessions.delete(a);},60*1e3).unref(),this._logger=de(this._options.logging,{component:"OCPPServer"});let i=this._options.rateLimit;i?.adaptive&&(this._adaptiveLimiter=new W({cpuThresholdPercent:i.cpuThresholdPercent,memThresholdPercent:i.memThresholdPercent,cooldownMs:i.cooldownMs}),this._adaptiveLimiter.on("adapted",r=>{this._logger?.info?.("Adaptive rate limit adjusted",r),this.emit("rateLimit:adapted",r);}),this._adaptiveLimiter.start());let n=this._options.workerThreads;if(n){let r=typeof n=="object"?n:{};this._workerPool=Ze(r),this._workerPool&&this._logger?.info?.("Worker thread pool initialized",{poolSize:this._workerPool.size});}}get log(){return this._logger||q}get clients(){return this._clients}get state(){return this._state}stats(){let e=0;if(this._wss)for(let t of this._wss.clients)e+=t.bufferedAmount;return {connectedClients:this._clients.size,activeSessions:this._sessions.size,uptimeSeconds:process.uptime(),pid:process.pid,memoryUsage:process.memoryUsage(),cpuUsage:process.cpuUsage(),webSockets:this._wss?{total:this._wss.clients.size,bufferedAmount:e}:void 0}}async adapterMetrics(){if(!this._adapter?.metrics)return null;try{return await this._adapter.metrics()}catch(e){return this._logger?.warn?.("Failed to fetch adapter metrics",{error:e}),null}}getLocalClient(e){return this._clientsByIdentity.get(e)}hasLocalClient(e){return this.getLocalClient(e)!==void 0}async isClientConnected(e){if(this.hasLocalClient(e))return true;if(this._adapter?.getPresence){let t=await this._adapter.getPresence(e);return t!=null}return false}cors(e){return this._globalCORS=e,this}route(...e){let t=new $;return t.route(...e),this._registerRouter(t),t}attachRouters(...e){for(let t of e)this._registerRouter(t);return this}plugin(...e){for(let t of e)if(this._plugins.push(t),this._logger?.info?.("Plugin registered",{name:t.name}),t.onInit){let i=t.onInit(this);i instanceof Promise&&i.catch(n=>{this._logger?.error?.("Plugin onInit error",{name:t.name,error:n.message});});}return this}use(...e){let t=new $;return t.use(...e),this._registerRouter(t),t}auth(e){let t=new $;return t.auth(e),this._registerRouter(t),t}_registerRouter(e){let t=e.patterns.filter(n=>typeof n=="string"),i=e._regexPatterns.length>0;if(t.length===0&&!i)this._globalMiddlewareRouters.push(e);else {for(let n of t)this._trie.insert(n,e);i&&this._regexRouters.push(e);}}async listen(e=0,t,i){let n;if(i?.server)n=i.server;else {let a=this._options.securityProfile??0;if(a===2||a===3){let o=this._options.tls??{},d={};o.cert&&(d.cert=o.cert),o.key&&(d.key=o.key),o.ca&&(d.ca=o.ca),o.passphrase&&(d.passphrase=o.passphrase),a===3&&(d.requestCert=true,d.rejectUnauthorized=o.rejectUnauthorized??true),n=https.createServer(d);}else n=qt.createServer();}this._state==="CLOSED"&&(this._state="OPEN");let r=(a,o,d)=>{this._handleUpgrade(a,o,d).catch(p=>{o.destroyed||o.destroy(),this._logger?.error?.("Upgrade error",{error:p.message}),this.emit("upgradeError",{error:p,socket:o});});};if(n.on("upgrade",r),this._httpServers.add(n),this._options.healthEndpoint&&n.on("request",(a,o)=>{let d=a.url??"";if(d==="/health"){let p=this.stats(),c=JSON.stringify({status:this._state==="OPEN"?"ok":"degraded",state:this._state,connectedClients:p.connectedClients,activeSessions:p.activeSessions,uptimeSeconds:Math.round(p.uptimeSeconds),pid:p.pid});o.writeHead(200,{"Content-Type":"application/json","Cache-Control":"no-cache"}),o.end(c);return}if(d==="/metrics"){let p=this.stats(),c=["# HELP ocpp_connected_clients Number of currently connected OCPP clients","# TYPE ocpp_connected_clients gauge",`ocpp_connected_clients ${p.connectedClients}`,"","# HELP ocpp_active_sessions Number of active in-memory sessions","# TYPE ocpp_active_sessions gauge",`ocpp_active_sessions ${p.activeSessions}`,"","# HELP ocpp_uptime_seconds Process uptime in seconds","# TYPE ocpp_uptime_seconds gauge",`ocpp_uptime_seconds ${Math.round(p.uptimeSeconds)}`,"","# HELP ocpp_memory_rss_bytes Resident set size in bytes","# TYPE ocpp_memory_rss_bytes gauge",`ocpp_memory_rss_bytes ${p.memoryUsage.rss}`,"","# HELP ocpp_memory_heap_used_bytes V8 heap used in bytes","# TYPE ocpp_memory_heap_used_bytes gauge",`ocpp_memory_heap_used_bytes ${p.memoryUsage.heapUsed}`,"","# HELP ocpp_memory_heap_total_bytes V8 heap total in bytes","# TYPE ocpp_memory_heap_total_bytes gauge",`ocpp_memory_heap_total_bytes ${p.memoryUsage.heapTotal}`,"","# HELP ocpp_ws_buffered_bytes Total buffered WebSocket bytes","# TYPE ocpp_ws_buffered_bytes gauge",`ocpp_ws_buffered_bytes ${p.webSockets?.bufferedAmount??0}`,""];o.writeHead(200,{"Content-Type":"text/plain; version=0.0.4; charset=utf-8","Cache-Control":"no-cache"}),o.end(c.join(`
4825
- `));return}o.writeHead(404,{"Content-Type":"text/plain"}),o.end("Not Found");}),i?.signal){let a=new AbortController;this._httpServerAbortControllers.add(a),i.signal.addEventListener("abort",()=>{a.abort(),n.close(),this._httpServers.delete(n);},{once:true});}return i?.server||await new Promise((a,o)=>{n.on("error",o),n.listen(e,t,()=>{n.removeListener("error",o);let d=n.address();this._logger?.info?.("Server listening",{port:typeof d=="object"?d?.port:e,host:t??"0.0.0.0"}),a();});}),n}updateTLS(e){let t=this._options.securityProfile??0;if(t!==2&&t!==3)throw new Error("updateTLS() requires a TLS Security Profile (TLS_BASIC_AUTH or TLS_CLIENT_CERT)");this._options.tls={...this._options.tls,...e};let i={};e.cert&&(i.cert=e.cert),e.key&&(i.key=e.key),e.ca&&(i.ca=e.ca),e.passphrase&&(i.passphrase=e.passphrase);let n=0;for(let r of this._httpServers)"setSecureContext"in r&&typeof r.setSecureContext=="function"&&(r.setSecureContext(i),n++);this._logger?.info?.(`TLS context hot-reloaded across ${n} active server(s)`);}get handleUpgrade(){return (e,t,i)=>this._handleUpgrade(e,t,i).catch(n=>{t.destroyed||t.destroy(),this._logger?.error?.("Upgrade error",{error:n.message}),this.emit("upgradeError",{error:n,socket:t});})}async _handleUpgrade(e,t,i){if(this._state!=="OPEN"){w(t,503,"Server is shutting down");return}let n=this._options.connectionRateLimit;if(n){let u=e.socket.remoteAddress??"unknown",C=Date.now(),y=this._connectionBuckets.get(u);if(!y)y={tokens:n.limit,lastRefill:C},this._connectionBuckets.set(u,y);else {let T=C-y.lastRefill,P=n.limit/n.windowMs;y.tokens=Math.min(n.limit,y.tokens+T*P),y.lastRefill=C;}if(y.tokens<1){this._logger?.warn?.("Connection rate limit exceeded",{ip:u}),this.emit("securityEvent",{type:"CONNECTION_RATE_LIMIT",ip:u,timestamp:new Date().toISOString(),details:{tokensRemaining:y.tokens}}),w(t,429,"Too Many Requests");return}y.tokens-=1;}if(t.readyState!=="open"){this._logger?.debug?.("Socket not open at upgrade start"),t.destroyed||t.destroy();return}if(e.headers.upgrade?.toLowerCase()!=="websocket"){w(t,400,"Invalid upgrade request");return}if(this._globalCORS){let{allowed:u,reason:C}=_e(e,this._globalCORS);if(!u){this._logger?.warn?.("CORS rejected connection",{reason:C,ip:e.socket.remoteAddress}),w(t,403,"Forbidden");return}}let r=new URL(e.url??"/",`http://${e.headers.host??"localhost"}`),a,o=[],d=[],p={},c=r.pathname,l=false,m=this._trie.size>0||this._regexRouters.length>0,h;!this._trie.frozen&&this._trie.size>0&&this._trie.freeze();for(let u of this._globalMiddlewareRouters)d.push(u),u.middlewares.length>0&&o.push(...u.middlewares),u.authCallback&&!a&&(a=u.authCallback);let E=this._trie.match(c);if(E){Object.assign(p,E.params);for(let u of E.routers)d.push(u),l=true,u._routeConfig&&(h=Object.assign(h||{},u._routeConfig)),u.middlewares.length>0&&o.push(...u.middlewares),u.authCallback&&!a&&(a=u.authCallback);}for(let u of this._regexRouters)for(let C of u._regexPatterns){let y=C.regex.exec(c);if(y){if(d.push(u),l=true,y.groups)for(let[T,P]of Object.entries(y.groups))p[T]=decodeURIComponent(P??"");u._routeConfig&&(h=Object.assign(h||{},u._routeConfig)),u.middlewares.length>0&&o.push(...u.middlewares),u.authCallback&&!a&&(a=u.authCallback);break}}let f=p.identity;if(!f){let u=c.split("/").filter(Boolean);f=decodeURIComponent(u[u.length-1]??"");}if(!f){w(t,400,"Missing identity in URL path");return}for(let u of d)if(u._routeCORS){let{allowed:C,reason:y}=_e(e,u._routeCORS);if(!C){this._logger?.warn?.("Route CORS rejected connection",{reason:y,ip:e.socket.remoteAddress}),w(t,403,"Forbidden");return}}"setKeepAlive"in t&&t.setKeepAlive(true);let A=new Set,je=e.headers["sec-websocket-protocol"];if(je)try{A=ze(je);}catch{w(t,400,"Invalid Sec-WebSocket-Protocol header");return}let Re=h?.protocols??this._options.protocols??[],O;if(Re.length>0){if(A.size===0){w(t,400,"Missing subprotocol");return}if(O=Re.find(u=>A.has(u)),!O){w(t,400,"No matching subprotocol");return}}let et=Ge(e.headers.authorization??"",f),qe,Me=this._options.securityProfile??0;Me===3&&"getPeerCertificate"in t&&(qe=t.getPeerCertificate());let se={identity:f,remoteAddress:e.socket.remoteAddress??"",headers:e.headers,protocols:A,pathname:c,params:p,query:r.searchParams,request:e,password:et,clientCertificate:qe,securityProfile:Me},ge,Oe;if(a||o.length>0){let u=new AbortController,C=()=>{u.abort(new Error("Socket closed during handshake"));};t.on("close",C),t.on("error",C),t.on("end",C);let y=this._options.handshakeTimeoutMs??3e4,T;y>0&&(T=setTimeout(()=>{u.abort(new Error("Handshake timeout"));},y));try{ge={handshake:se,state:{},reject:(S=401,x="Unauthorized")=>{throw {code:S,message:x,_isMiddlewareReject:!0}},next:async S=>{}};let P=[...o],b=!1;if(P.push(async S=>{b=!0,a?Oe=await new Promise((x,L)=>{let V=!1,tt=N=>{V||(V=!0,N?.protocol&&(O=N.protocol),x(N));},it=(N=401,Ve="Unauthorized")=>{throw V||(V=!0,L({code:N,message:Ve})),{code:N,message:Ve,_isMiddlewareReject:!0}};if(u.signal.aborted){L(u.signal.reason);return}u.signal.addEventListener("abort",()=>{V||(V=!0,L(u.signal.reason));},{once:!0}),this._logger?.debug?.("Executing auth callback",{identity:f,pathname:c});let nt={handshake:se,state:S.state,reject:it,signal:u.signal,accept:tt};a(nt);}):O=se.protocols.values().next().value??void 0;}),await Je(P,ge),!b)throw {code:500,message:"Middleware chain halted unexpectedly without rejecting",_isMiddlewareReject:!0}}catch(P){if(u.signal.aborted){let L=P instanceof Error?P.message:"Unknown abort";this._logger?.warn?.("Handshake aborted",{identity:f,reason:L}),this.emit("securityEvent",{type:"UPGRADE_ABORTED",identity:f,ip:e.socket.remoteAddress,timestamp:new Date().toISOString(),details:{reason:L}}),this.emit("upgradeAborted",{identity:f,reason:L,socket:t,request:e}),t.destroyed||t.destroy();return}let b=P,S=typeof b?.code=="number"?b.code:401,x=typeof b?.message=="string"?b.message:"Unauthorized";this._logger?.warn?.("Auth rejected",{identity:f,code:S}),this.emit("securityEvent",{type:"AUTH_FAILED",identity:f,ip:e.socket.remoteAddress,timestamp:new Date().toISOString(),details:{code:S,message:x}}),w(t,S,x);return}finally{T&&clearTimeout(T),t.removeListener("close",C),t.removeListener("error",C),t.removeListener("end",C);}}else if(m&&!l){this._logger?.warn?.("Connection rejected: No matching route found",{pathname:c}),w(t,404,"Endpoint Not Found");return}if(t.readyState!=="open"){this._logger?.debug?.("Socket closed before upgrade completion",{identity:f}),t.destroyed||t.destroy();return}this._wss||(this._wss=new ne.WebSocketServer({noServer:true,maxPayload:this._options.maxPayloadBytes??65536})),this._wss.handleUpgrade(e,t,i,u=>{let C={identity:f,endpoint:"",callTimeoutMs:h?.callTimeoutMs??this._options.callTimeoutMs,pingIntervalMs:h?.pingIntervalMs??this._options.pingIntervalMs,deferPingsOnActivity:h?.deferPingsOnActivity??this._options.deferPingsOnActivity,callConcurrency:h?.callConcurrency??this._options.callConcurrency,maxBadMessages:this._options.maxBadMessages,respondWithDetailedErrors:this._options.respondWithDetailedErrors,strictMode:h?.strictMode??this._options.strictMode,strictModeMethods:h?.strictModeMethods??this._options.strictModeMethods,strictModeValidators:this._options.strictModeValidators,rateLimit:h?.rateLimit??this._options.rateLimit,reconnect:false,logging:this._options.logging},y={...ge?.state||{},...this._sessions.get(f)?.data||{},...Oe?.session||{}},T=new oe(C,{ws:u,handshake:se,session:y,protocol:O,adaptiveMultiplier:this._adaptiveLimiter?()=>this._adaptiveLimiter.multiplier:void 0,workerPool:this._workerPool??void 0});this._updateSessionActivity(f,T.session);let P=this._clientsByIdentity.get(f);P&&P!==T&&(this._logger?.warn?.("Evicting stale connection for identity",{identity:f,reason:"Duplicate identity replaced by new connection"}),P.close({code:4e3,reason:"Evicted by new connection",force:true}).catch(()=>{}),this._clients.delete(P)),this._clients.add(T),this._clientsByIdentity.set(f,T),this._adapter?.setPresence&&this._adapter.setPresence(f,this._nodeId,300).catch(b=>{this._logger?.error?.("Error setting presence",{identity:f,error:b});}),this._logger?.info?.("Client connected",{identity:f,remoteAddress:e.socket.remoteAddress,protocol:O}),T.on("close",({code:b,reason:S})=>{this._clients.delete(T),this._clientsByIdentity.get(f)===T&&this._clientsByIdentity.delete(f),this?._adapter?.removePresence&&this._adapter.removePresence(f).catch(x=>{this._logger?.error?.("Error removing presence",{identity:f,error:x});});for(let x of this._plugins)try{x.onDisconnect?.(T,b,S);}catch(L){this._logger?.error?.("Plugin onDisconnect error",{name:x.name,error:L.message});}this._logger?.info?.("Client disconnected",{identity:f});});for(let b of this._plugins)try{let S=b.onConnection?.(T);S instanceof Promise&&S.catch(x=>{this._logger?.error?.("Plugin onConnection error",{name:b.name,error:x.message});});}catch(S){this._logger?.error?.("Plugin onConnection error",{name:b.name,error:S.message});}this.emit("client",T);for(let b of d)b.emit("client",T);T.on("message",()=>{this._updateSessionActivity(f,T.session);});});}_updateSessionActivity(e,t){this._sessions.set(e,{data:t,lastActive:Date.now()});}async close(e={}){if(this._state!=="OPEN")return;if(this._state="CLOSING",this.emit("closing"),this._logger?.info?.("Server closing",{clientCount:this._clients.size}),this._gcInterval&&(clearInterval(this._gcInterval),this._gcInterval=null),!e.force){let r=Array.from(this._clients).map(async a=>{let o=a._ws;o&&o.bufferedAmount>0&&(this._logger?.debug?.("Waiting for client buffer to drain",{identity:a.identity,bufferedAmount:o.bufferedAmount}),await new Promise(d=>{let p=0,c=setInterval(()=>{p+=50,(!o||o.bufferedAmount===0||p>=5e3)&&(clearInterval(c),d());},50);}));});await Promise.allSettled(r);}let t=Array.from(this._clients).map(n=>n.close(e).catch(()=>{}));await Promise.allSettled(t);for(let n of this._httpServerAbortControllers)n.abort();this._httpServerAbortControllers.clear(),this._wss&&(this._wss.close(),this._wss=new ne.WebSocketServer({noServer:true}));let i=Array.from(this._httpServers).map(n=>new Promise(r=>{n.close(()=>r());}));await Promise.allSettled(i),this._httpServers.clear(),this._adaptiveLimiter&&this._adaptiveLimiter.stop();for(let n of this._plugins)try{let r=n.onClose?.();r instanceof Promise&&await r;}catch(r){this._logger?.error?.("Plugin onClose error",{name:n.name,error:r.message});}this._adapter&&await this._adapter.disconnect(),this._state="CLOSED",this.emit("close");}reconfigure(e){Object.assign(this._options,e);}async sendToClient(...e){let t,i,n,r;e.length>=4&&typeof e[0]=="string"&&typeof e[1]=="string"&&typeof e[2]=="string"?(t=e[0],i=e[2],n=e[3],r=e[4]):(t=e[0],i=e[1],n=e[2],r=e[3]);for(let a of this._clients)if(a.identity===t)return await a.call(i,n,r);if(this._adapter?.getPresence){let a=await this._adapter.getPresence(t);if(a){await this._adapter.publish(`ocpp:node:${a}`,{source:this._nodeId,target:t,method:i,params:n,options:r});return}}throw new Error(`Client ${t} not found`)}async safeSendToClient(...e){try{return await this.sendToClient(...e)}catch(t){this._logger&&typeof this._logger.warn=="function"&&t.name!=="TimeoutError"&&this._logger.warn("SafeSendToClient failed",{identity:e[0],method:e.length>=4&&typeof e[1]=="string"&&typeof e[2]=="string"?e[2]:e.length>=3&&typeof e[1]=="string"?e[1]:"unknown",error:t});return}}async sendBatch(e,t){if(t.length===0)return [];let i=this._clientsByIdentity.get(e);if(!i)return this._logger?.warn?.("sendBatch: client not found locally",{identity:e}),t.map(()=>{});let n=i.options.callConcurrency??1;t.length>n&&i.reconfigure({callConcurrency:t.length});try{return (await Promise.allSettled(t.map(a=>i.call(a.method,a.params,a.options??{})))).map(a=>{if(a.status==="fulfilled")return a.value;this._logger?.warn?.("sendBatch: individual call failed",{identity:e,error:a.reason?.message});})}finally{t.length>n&&i.reconfigure({callConcurrency:n});}}async setAdapter(e){this._adapter=e,await this._adapter.subscribe("ocpp:broadcast",t=>this._onBroadcast(t)),await this._adapter.subscribe(`ocpp:node:${this._nodeId}`,t=>{this._onUnicast(t);});}_onBroadcast(e){try{if(!e||typeof e!="object")return;let t=e;if(t.source===this._nodeId)return;for(let i of this._clients)i.call(t.method,t.params).catch(()=>{});}catch(t){this._logger?.error?.("Error processing broadcast message",{error:t.message});}}_onUnicast(e){try{if(!e||typeof e!="object")return;let t=e;for(let i of this._clients)if(i.identity===t.target){i.call(t.method,t.params,t.options).catch(n=>{n.name!=="TimeoutError"&&this._logger?.error?.("Error delivering unicast to client",{identity:t.target,error:n});});return}this._logger?.warn?.("Received unicast for unknown client",{target:t.target}),this._adapter?.removePresence&&this._adapter.removePresence(t.target).catch(()=>{});}catch(t){this._logger?.error?.("Error processing unicast",{error:t.message});}}async publish(e,t){this._adapter&&await this._adapter.publish(e,t);}async broadcast(e,t){let i=Array.from(this._clients).map(r=>r.call(e,t).catch(()=>{})),n=this._adapter?this._adapter.publish("ocpp:broadcast",{source:this._nodeId,method:e,params:t}):Promise.resolve();await Promise.all([Promise.all(i),n]);}async broadcastBatch(e,t,i,n){let r=new Set,a=[];for(let d of e){let p=this._clientsByIdentity.get(d);p&&(r.add(d),a.push(p.call(t,i,n).catch(()=>{})));}let o=e.filter(d=>!r.has(d));if(o.length>0&&this._adapter){let d=[];this._adapter.getPresenceBatch?d=await this._adapter.getPresenceBatch(o):this._adapter.getPresence&&(d=await Promise.all(o.map(c=>this._adapter.getPresence(c))));let p=[];for(let c=0;c<o.length;c++){let l=d[c];l&&p.push({channel:`ocpp:node:${l}`,data:{source:this._nodeId,target:o[c],method:t,params:i,options:n}});}p.length>0&&(this._adapter.publishBatch?await this._adapter.publishBatch(p):await Promise.all(p.map(c=>this._adapter.publish(c.channel,c.data))));}await Promise.all(a);}_buildCompressionConfig(){let e=this._options.compression;return e?e===true?{threshold:1024,zlibDeflateOptions:{level:6,memLevel:8},zlibInflateOptions:{},serverNoContextTakeover:true,clientNoContextTakeover:true}:{threshold:e.threshold??1024,zlibDeflateOptions:{level:e.level??6,memLevel:e.memLevel??8},zlibInflateOptions:{},serverNoContextTakeover:e.serverNoContextTakeover??true,clientNoContextTakeover:e.clientNoContextTakeover??true}:false}};
4826
- exports.AdaptiveLimiter=W;exports.ClusterDriver=Te;exports.ConnectionState=ie;exports.InMemoryAdapter=ye;exports.LRUMap=ae;exports.MessageType=I;exports.MiddlewareStack=pe;exports.NOREPLY=De;exports.OCPPClient=re;exports.OCPPRouter=$;exports.OCPPServer=Ae;exports.OCPPServerClient=oe;exports.RPCFormatViolationError=X;exports.RPCFormationViolationError=K;exports.RPCFrameworkError=ee;exports.RPCGenericError=v;exports.RPCInternalError=B;exports.RPCMessageTypeNotSupportedError=_;exports.RPCNotImplementedError=j;exports.RPCNotSupportedError=z;exports.RPCOccurrenceConstraintViolationError=Y;exports.RPCPropertyConstraintViolationError=Q;exports.RPCProtocolError=G;exports.RPCSecurityError=J;exports.RPCTypeConstraintViolationError=Z;exports.RedisAdapter=be;exports.SecurityProfile=he;exports.TimeoutError=k;exports.UnexpectedHttpResponse=H;exports.Validator=ue;exports.WebsocketUpgradeError=Pe;exports.combineAuth=ft;exports.createLoggingMiddleware=Se;exports.createPlugin=ut;exports.createRPCError=R;exports.createRouter=kt;exports.createValidator=te;exports.defineAdapter=at;exports.defineAuth=ht;exports.defineMiddleware=lt;exports.defineRpcMiddleware=mt;exports.getErrorPlainObject=Ie;exports.getPackageIdent=Ee;exports.getStandardValidators=xe;
4824
+ ${r}`);}var {CONNECTING:F,OPEN:O,CLOSING:$e,CLOSED:w}=re,oe=class s extends events.EventEmitter{static CONNECTING=F;static OPEN=O;static CLOSING=$e;static CLOSED=w;_options;_state=w;_ws=null;_protocol;_identity;_handlers=new Map;_wildcardHandler=null;_pendingCalls=new Map;_pendingResponses=new Set;_callQueue;_pingTimer=null;_pongTimer=null;_closePromise=null;_reconnectAttempt=0;_reconnectTimer=null;_badMessageCount=0;_lastActivity=0;_outboundBuffer=[];_offlineQueue=[];_middleware;_validators=[];_strictProtocols=null;_handshake=null;_logger=M;_exchangeLog=false;_prettify=false;constructor(e){if(super(),this.setMaxListeners(0),!e.identity)throw new Error("identity is required");this._identity=e.identity,this._options={reconnect:true,maxReconnects:1/0,backoffMin:1e3,backoffMax:3e4,callTimeoutMs:3e4,pingIntervalMs:3e4,deferPingsOnActivity:false,callConcurrency:1,maxBadMessages:1/0,respondWithDetailedErrors:false,securityProfile:0,...e},this._callQueue=new ue(this._options.callConcurrency),this._middleware=new le;let t=this._options.logging,n=ce(t,{component:"OCPPClient",identity:this._identity});this._logger=n||M,t&&typeof t=="object"&&(this._exchangeLog=t.exchangeLog??false,this._prettify=t.prettify??false),this._options.logging&&this.use(xe(this._logger,this._identity,this._options.logging)),this._options.strictMode&&this._setupValidators();}_logExchange(e,t,n,i){if(!this._logger)return;let r=e==="OUT"?"\u2192":"\u2190",a=t==="CALLERROR"?"warn":this._exchangeLog?"info":"debug";if(this._exchangeLog&&this._prettify){let o=t==="CALLERROR"?"\u{1F6A8}":t==="CALLRESULT"?"\u2705":"\u26A1",d=n??t,p=`${o} ${this._identity} ${r} ${d} [${e}]`;this._logger?.[a]?.(p,{...i,direction:e});}else this._exchangeLog?this._logger?.[a]?.(`${t} ${r}`,{...i,direction:e}):this._logger?.[a]?.(`${t} ${r}`,i);}get log(){return this._logger||M}get identity(){return this._options.identity}get endpoint(){return this._options.endpoint}get options(){return this._options}get protocol(){return this._protocol}get state(){return this._state}get securityProfile(){return this._options.securityProfile??0}async connect(){if(this._state!==w)throw new Error(`Cannot connect: client is in state ${this._state}`);return this._state=F,this._reconnectAttempt=0,this._connectInternal()}async _connectInternal(){return new Promise((e,t)=>{let n=this._buildEndpoint(),i=this._buildWsOptions();this._logger?.debug?.("Connecting",{url:n}),this.emit("connecting",{url:n});let r=new ae__default.default(n,this._options.protocols??[],i);this._ws=r;let a=()=>{if(p(),this._state=O,this._protocol=r.protocol,this._badMessageCount=0,r.protocol&&this._reconnectAttempt===0&&(this._options.protocols=[r.protocol]),this._attachWebsocket(r),this._startPing(),this._flushOfflineQueue(),this._outboundBuffer.length>0){let u=this._outboundBuffer;this._outboundBuffer=[];for(let f of u)this._ws?.send(f);}this._logger?.info?.("Connected",{protocol:r.protocol});let l={response:r._req?.res};this.emit("open",l),e(l);},o=c=>{p(),this._state=w,this._logger?.error?.("Connection error",{error:c.message}),this.emit("error",c),t(c);},d=(c,l)=>{p(),this._state=w;let u=new B(`Unexpected HTTP response: ${l.statusCode}`,l.statusCode??0,l.headers);this._logger?.error?.("Unexpected HTTP response",{statusCode:l.statusCode}),this.emit("error",u),t(u);},p=()=>{r.removeListener("open",a),r.removeListener("error",o),r.removeListener("unexpected-response",d);};r.on("open",a),r.on("error",o),r.on("unexpected-response",d);})}async close(e={}){let{code:t=1e3,reason:n="",awaitPending:i=true,force:r=false}=e;return this._closePromise?this._closePromise:this._state===w?{code:1e3,reason:""}:(this._reconnectTimer&&(clearTimeout(this._reconnectTimer),this._reconnectTimer=null),this._closePromise=this._closeInternal(t,n,i,r),this._closePromise)}async _closeInternal(e,t,n,i){if(this._state=$e,this._stopPing(),!i&&n){let r=Array.from(this._pendingCalls.values()).map(a=>new Promise(o=>{let d=a.resolve,p=a.reject;a.resolve=c=>{d(c),o();},a.reject=c=>{p(c),o();};}));r.length>0&&await Promise.allSettled(r);}return new Promise(r=>{if(!this._ws||this._ws.readyState===ae__default.default.CLOSED){this._state=w,this._cleanup();let o={code:e,reason:t};this.emit("close",o),r(o);return}let a=(o,d)=>{this._ws?.removeListener("close",a),this._state=w,this._cleanup();let p={code:o,reason:d.toString()};this.emit("close",p),r(p);};this._ws.on("close",a),i?this._ws.terminate():this._ws.close(Je(e)?e:1e3,t);})}handle(...e){if(e.length===1&&typeof e[0]=="function"){if(this._wildcardHandler)throw new Error("Wildcard handler is already registered.");this._wildcardHandler=e[0];}else if(e.length===2&&typeof e[0]=="string"&&typeof e[1]=="function"){if(this._handlers.has(e[0]))throw new Error(`Handler for '${e[0]}' is already registered.`);this._handlers.set(e[0],e[1]);}else if(e.length===3&&typeof e[0]=="string"&&typeof e[1]=="string"&&typeof e[2]=="function"){let t=`${e[0]}:${e[1]}`;if(this._handlers.has(t))throw new Error(`Handler for '${e[1]}' (protocol: ${e[0]}) is already registered.`);this._handlers.set(t,e[2]);}else throw new Error("Invalid arguments: provide (version, method, handler), (method, handler), or (wildcardHandler)")}removeHandler(e,t){e&&t?this._handlers.delete(`${e}:${t}`):e?this._handlers.delete(e):this._wildcardHandler=null;}removeAllHandlers(){this._handlers.clear(),this._wildcardHandler=null;}use(e){this._middleware.use(e);}async call(...e){let t,n,i;if(e.length>=3&&typeof e[0]=="string"&&typeof e[1]=="string"?(t=e[1],n=e[2]??{},i=e[3]??{}):(t=e[0],n=e[1]??{},i=e[2]??{}),this._state!==O){if(this._options.offlineQueue&&(this._state===w||this._state===F))return new Promise((a,o)=>{let d=this._options.offlineQueueMaxSize??100;this._offlineQueue.length>=d&&(this._offlineQueue.shift(),this._logger?.warn?.("Offline queue full \u2014 dropping oldest message",{method:t,queueSize:this._offlineQueue.length})),this._offlineQueue.push({method:t,params:n,options:i,resolve:a,reject:o}),this._logger?.debug?.("Call queued offline",{method:t,queueSize:this._offlineQueue.length});});throw new Error(`Cannot call: client is in state ${this._state}`)}let r=i.retries??0;return r>0?this._callWithRetry(t,n,i,r):this._callQueue.push(()=>this._sendCall(t,n,i))}async safeCall(...e){try{return await this.call(...e)}catch(t){if(t.name!=="TimeoutError"){let n={method:e.find(i=>typeof i=="string"&&!i.startsWith("ocpp")),error:t};this._logger?.warn?this._logger.warn("SafeCall failed",n):console.warn("SafeCall failed",n);}return}}async _sendCall(e,t,n){let i=n.idempotencyKey??me(),r=n.timeoutMs??this._options.callTimeoutMs,a={type:"outgoing_call",messageId:i,method:e,params:t,options:n},o;return await this._middleware.execute(a,async d=>{let p=d;this._options.strictMode&&this._protocol&&this._validateOutbound(p.method,p.params,"req");let c=[x.CALL,i,p.method,p.params],l=this._invokeBeforeSend(c);if(l instanceof Promise){if(await l===false)return}else if(l===false)return;let u=JSON.stringify(c);return o=await new Promise((f,S)=>{let y=setTimeout(()=>{this._pendingCalls.delete(i),S(new k(`Call to "${p.method}" timed out after ${r}ms`));},r),j=()=>{clearTimeout(y),this._pendingCalls.delete(i),S(new Error("Aborted"));};n.signal&&n.signal.addEventListener("abort",j),this._pendingCalls.set(i,{resolve:f,reject:S,timeoutHandle:y,abortHandler:n.signal?()=>n.signal?.removeEventListener("abort",j):void 0,method:p.method,sentAt:Date.now()}),this._ws?.readyState===ae__default.default.OPEN?this._safeSend(this._ws,u,W=>{W?(clearTimeout(y),this._pendingCalls.delete(i),S(W)):this._emitMessageEvent(c,"OUT",{type:"outgoing_call",messageId:i,method:p.method,params:p.params,options:n});}):this._state===F?(this._logger?.debug?.("Buffering call",{method:p.method}),this._outboundBuffer.push(u)):(clearTimeout(y),this._pendingCalls.delete(i),S(new Error(`WebSocket is not open (state: ${this._state})`)));}),o}),o}sendRaw(e){if(this._state===O&&this._ws)this._ws.send(e);else if(this._state===F)this._outboundBuffer.push(e);else throw new Error("Cannot send: client is not connected")}reconfigure(e){Object.assign(this._options,e),e.callConcurrency!==void 0&&this._callQueue.setConcurrency(e.callConcurrency),(e.strictMode!==void 0||e.strictModeValidators!==void 0)&&this._setupValidators(),e.pingIntervalMs!==void 0&&(this._stopPing(),this._state===O&&this._startPing());}_attachWebsocket(e){e.on("message",t=>this._onMessage(t)),e.on("close",(t,n)=>this._onClose(t,n)),e.on("error",t=>this.emit("error",t)),e.on("ping",()=>{this._recordActivity(),this.emit("ping");}),e.on("pong",()=>{this._pongTimer&&(clearTimeout(this._pongTimer),this._pongTimer=null),this._recordActivity(),this.emit("pong");});}_buildMessageEventContext(e,t){return {...e,timestamp:new Date().toISOString(),latencyMs:t}}_emitMessageEvent(e,t,n,i){let r=this._buildMessageEventContext(n,i),a={message:e,direction:t,ctx:r};this.emit("message",a);}_onMessage(e,t){this._recordActivity();let n;try{if(t!==void 0?n=t:n=JSON.parse(e),!Array.isArray(n))throw new Error("Message is not an array")}catch(d){this._onBadMessage(typeof e=="string"?e:e.toString(),d);return}let i=n[0],r=n[1];if(typeof r!="string"){this._onBadMessage(typeof e=="string"?e:e.toString(),new L(`Invalid MessageId type: ${typeof r} (expected string)`));return}if(i===x.CALL&&n.length<4||i===x.CALLRESULT&&n.length<3||i===x.CALLERROR&&n.length<5){this._onBadMessage(JSON.stringify(n),new L(`Missing payload elements for message type ${i}`));return}let a=i===x.CALLERROR?4:i===x.CALL?3:2,o=n[a];if(typeof o!="object"||o===null||Array.isArray(o)){this._onBadMessage(JSON.stringify(n),new L(`Payload must be a JSON object, got ${o===null?"null":Array.isArray(o)?"array":typeof o}`));return}switch(i){case x.CALL:this._handleIncomingCall(n);break;case x.CALLRESULT:this._handleCallResult(n);break;case x.CALLERROR:this._handleCallError(n);break;default:this._onBadMessage(JSON.stringify(n),new L(`Unknown message type: ${i}`));}}async _handleIncomingCall(e){let[,t,n,i]=e,r={type:"incoming_call",messageId:t,method:n,params:i,protocol:this._protocol};try{await this._middleware.execute(r,async a=>{let o=a,d=[x.CALL,o.messageId,o.method,o.params];if(this._emitMessageEvent(d,"IN",o),this.emit("call",d),this._state===O)try{if(this._pendingResponses.has(o.messageId))throw q("RpcFrameworkError",`Already processing call with ID: ${o.messageId}`);let p=(this._protocol?this._handlers.get(`${this._protocol}:${o.method}`):void 0)??this._handlers.get(o.method);if(!p&&!this._wildcardHandler)throw new R(`Method "${o.method}" not implemented`);this._options.strictMode&&this._protocol&&this._validateInbound(o.method,o.params,"req"),this._pendingResponses.add(o.messageId);let c=new AbortController,l={messageId:o.messageId,method:o.method,protocol:this._protocol,params:o.params,signal:c.signal},u;if(p?u=await p(l):this._wildcardHandler&&(u=await this._wildcardHandler(o.method,l)),this._pendingResponses.delete(o.messageId),u===Le)return;this._options.strictMode&&this._protocol&&this._validateOutbound(o.method,u,"conf");let f=[x.CALLRESULT,o.messageId,u],S=this._invokeBeforeSend(f);if(S instanceof Promise){if(await S===!1)return u}else if(S===!1)return u;return this._ws?.send(JSON.stringify(f)),this._emitMessageEvent(f,"OUT",{type:"outgoing_result",messageId:o.messageId,method:o.method,payload:u}),this.emit("callResult",f),u}catch(p){this._pendingResponses.delete(o.messageId);let c=p instanceof P||p.rpcErrorCode?p:q("InternalError",p.message),l=this._options.respondWithDetailedErrors?De(p):{},u=[x.CALLERROR,o.messageId,c.rpcErrorCode,c.rpcErrorMessage||p.message||"",l],f=this._invokeBeforeSend(u);if(f instanceof Promise){if(await f===!1)throw p}else if(f===!1)throw p;throw this._ws?.send(JSON.stringify(u)),this._emitMessageEvent(u,"OUT",{type:"outgoing_error",messageId:o.messageId,method:o.method,errorCode:c.rpcErrorCode,errorDescription:c.rpcErrorMessage||p.message||""}),this.emit("callError",u),this.emit("handlerError",{method:o.method,error:p}),p}});}catch{}}async _handleCallResult(e){let[,t,n]=e;if(!this._pendingCalls.has(t)){this._logger?.warn?.("Received CallResult for unknown messageId",{messageId:t});return}let i=this._pendingCalls.get(t),r={type:"incoming_result",messageId:t,payload:n,method:i.method};await this._middleware.execute(r,async a=>{let o=a,d=this._pendingCalls.get(o.messageId);if(!d)return;let p=Date.now()-d.sentAt;this._emitMessageEvent(e,"IN",o,p),this.emit("callResult",e),clearTimeout(d.timeoutHandle),d.abortHandler,this._pendingCalls.delete(o.messageId),d.resolve(o.payload);});}async _handleCallError(e){let[,t]=e,n=this._pendingCalls.get(t);if(!n){this._logger?.warn?.("Received CallError for unknown messageId",{messageId:t});return}let i={type:"incoming_error",messageId:t,error:e,method:n.method};await this._middleware.execute(i,async r=>{let a=r,o=this._pendingCalls.get(a.messageId);if(!o)return;let d=Date.now()-o.sentAt;this._emitMessageEvent(e,"IN",a,d),this.emit("callError",e);let[,,p,c,l]=a.error;clearTimeout(o.timeoutHandle),this._pendingCalls.delete(a.messageId);let u=q(p,c,l);o.reject(u);});}_onBadMessage(e,t){this._badMessageCount++,this._logger?.warn?.("Bad message",{error:t.message,count:this._badMessageCount}),this.emit("badMessage",{message:e,error:t});let n=e.match(/^\s*\[\s*2\s*,\s*"([^"]+)"/);if(n?.[1]&&this._ws){let i=[x.CALLERROR,n[1],"FormatViolation",t.message||"Invalid message format",{}],r=this._invokeBeforeSend(i);r instanceof Promise?r.then(a=>{a!==false&&(this._ws?.send(JSON.stringify(i)),this.emit("callError",i));}).catch(()=>{}):r!==false&&(this._ws.send(JSON.stringify(i)),this.emit("callError",i));}this._badMessageCount>=this._options.maxBadMessages&&this.close({code:1002,reason:"Too many bad messages"}).catch(()=>{});}_rejectPendingCalls(e){for(let[,t]of this._pendingCalls)clearTimeout(t.timeoutHandle),t.reject(new Error(e));this._pendingCalls.clear(),this._pendingResponses.clear();}_onClose(e,t){this._stopPing();let n=t.toString();this._rejectPendingCalls(`Connection closed (${e}: ${n})`),this._state!==$e?(this._logger?.info?.("Disconnected",{code:e,reason:n}),this.emit("disconnect",{code:e,reason:n}),this._options.reconnect&&this._reconnectAttempt<this._options.maxReconnects?this._scheduleReconnect():(this._state=w,this.emit("close",{code:e,reason:n}))):this._state=w;}static _INTOLERABLE_ERRORS=new Set(["Maximum redirects exceeded","Server sent no subprotocol","Server sent an invalid subprotocol","Server sent a subprotocol but none was requested","Invalid Sec-WebSocket-Accept header"]);_scheduleReconnect(){this._reconnectAttempt++,this._state=F;let e=this._options.backoffMin,t=this._options.backoffMax,n=Math.min(t,e*2**(this._reconnectAttempt-1)*(.5+Math.random()*.5));this._logger?.warn?.("Reconnecting",{attempt:this._reconnectAttempt,delayMs:Math.round(n)}),this.emit("reconnect",{attempt:this._reconnectAttempt,delay:n}),this._reconnectTimer=setTimeout(async()=>{this._reconnectTimer=null;try{await this._connectInternal();}catch(i){let r=i instanceof Error?i.message:"";if(s._INTOLERABLE_ERRORS.has(r)){this._logger?.error?.("Intolerable error \u2014 stopping reconnection",{error:r}),this._state=w,this.emit("close",{code:1001,reason:r});return}this._reconnectAttempt<this._options.maxReconnects&&this._options.reconnect?this._scheduleReconnect():(this._state=w,this.emit("close",{code:1001,reason:"Max reconnection attempts exhausted"}));}},n);}_flushOfflineQueue(){if(this._offlineQueue.length===0)return;let e=this._offlineQueue.splice(0,this._offlineQueue.length);this._logger?.info?.("Flushing offline queue",{count:e.length});for(let t of e)this._callQueue.push(()=>this._sendCall(t.method,t.params,t.options)).then(t.resolve).catch(t.reject);}async _callWithRetry(e,t,n,i){let r=n.retryDelayMs??1e3,a=n.retryMaxDelayMs??3e4;for(let o=0;o<=i;o++)try{return await this._callQueue.push(()=>this._sendCall(e,t,n))}catch(d){if(o===i||!(d instanceof k))throw d;let p=Math.min(a,r*2**o),c=Math.random()*p;this._logger?.warn?.("Call retry",{method:e,attempt:o+1,maxRetries:i,delayMs:Math.round(c)}),await new Promise(l=>setTimeout(l,c));}throw new Error("Retry exhausted")}static _BACKPRESSURE_THRESHOLD=512*1024;_invokeBeforeSend(e){return true}_safeSend(e,t,n){if(!e||e.readyState!==ae__default.default.OPEN){n?.(new Error("WebSocket is not open"));return}if(e.bufferedAmount>s._BACKPRESSURE_THRESHOLD){this._logger?.warn?.("Backpressure \u2014 pausing send",{identity:this._identity,bufferedAmount:e.bufferedAmount,threshold:s._BACKPRESSURE_THRESHOLD}),this.emit("backpressure",{identity:this._identity,bufferedAmount:e.bufferedAmount});let i=0,r=setInterval(()=>{if(i+=50,!e||e.readyState!==ae__default.default.OPEN){clearInterval(r),n?.(new Error("WebSocket closed during backpressure wait"));return}(e.bufferedAmount<=s._BACKPRESSURE_THRESHOLD||i>=1e4)&&(clearInterval(r),e.send(t,n));},50);}else e.send(t,n);}_startPing(){if(this._options.pingIntervalMs<=0)return;let e=this._options.pongTimeoutMs??this._options.pingIntervalMs+5e3,t=()=>{if(this._state!==O||!this._ws)return;if(this._options.deferPingsOnActivity){let r=Date.now()-this._lastActivity;if(r<this._options.pingIntervalMs){this._pingTimer=setTimeout(t,this._options.pingIntervalMs-r);return}}this._ws.ping(),e>0&&(this._pongTimer=setTimeout(()=>{this._logger?.warn?.("Pong timeout \u2014 terminating dead connection",{identity:this._identity,timeoutMs:e}),this.emit("pongTimeout",{identity:this._identity}),this._ws?.terminate();},e));let i=this._options.pingIntervalMs*(.75+Math.random()*.5);this._pingTimer=setTimeout(t,i);},n=this._options.pingIntervalMs*(.75+Math.random()*.5);this._pingTimer=setTimeout(t,n);}_stopPing(){this._pingTimer&&(clearTimeout(this._pingTimer),this._pingTimer=null);}_recordActivity(){this._lastActivity=Date.now();}_setupValidators(){this._options.strictModeValidators?this._validators=this._options.strictModeValidators:this._validators=_e(),Array.isArray(this._options.strictMode)?this._strictProtocols=this._options.strictMode:this._strictProtocols=null;}_validateOutbound(e,t,n){let i=this._findValidator();if(!i||this._options.strictModeMethods&&!this._options.strictModeMethods.includes(e))return;let r=`urn:${e}.${n}`;try{i.validate(r,t);}catch(a){throw this.emit("strictValidationFailure",{message:t,error:a}),a}}_validateInbound(e,t,n){let i=this._findValidator();if(!i||this._options.strictModeMethods&&!this._options.strictModeMethods.includes(e))return;let r=`urn:${e}.${n}`;try{i.validate(r,t);}catch(a){throw this.emit("strictValidationFailure",{message:t,error:a}),a}}_findValidator(){return !this._protocol||this._strictProtocols&&!this._strictProtocols.includes(this._protocol)?null:this._validators.find(e=>e.subprotocol===this._protocol)??null}_buildEndpoint(){let e=this._options.endpoint;if(e.endsWith("/")||(e+="/"),e+=encodeURIComponent(this._identity),this._options.query){let t=new URLSearchParams(this._options.query);e+=(e.includes("?")?"&":"?")+t.toString();}return e}_buildWsOptions(){let e={headers:{...this._options.headers,"User-Agent":we()}},t=this._options.securityProfile??0;if((t===1||t===2)&&this._options.password){let i=Buffer.from(`${this._identity}:${this._options.password.toString()}`).toString("base64");e?.headers&&(e.headers.Authorization=`Basic ${i}`);}if(t===2||t===3){let i=this._options.tls??{};i.ca&&(e.ca=i.ca),i.rejectUnauthorized!==void 0&&(e.rejectUnauthorized=i.rejectUnauthorized),t===3&&(i.cert&&(e.cert=i.cert),i.key&&(e.key=i.key),i.passphrase&&(e.passphrase=i.passphrase));}let n=this._options.compression;return n&&(e.perMessageDeflate=n===true?{zlibDeflateOptions:{level:6,memLevel:8},zlibInflateOptions:{},clientNoContextTakeover:true,serverNoContextTakeover:true}:{zlibDeflateOptions:{level:n.level??6,memLevel:n.memLevel??8},zlibInflateOptions:{},clientNoContextTakeover:n.clientNoContextTakeover??true,serverNoContextTakeover:n.serverNoContextTakeover??true}),e}_cleanup(){this._stopPing(),this._pongTimer&&(clearTimeout(this._pongTimer),this._pongTimer=null),this._reconnectTimer&&(clearTimeout(this._reconnectTimer),this._reconnectTimer=null),this._closePromise=null,this._ws=null;}};var se=class extends Map{_maxSize;constructor(e){if(super(),e<1)throw new RangeError("LRUMap maxSize must be >= 1");this._maxSize=e;}get maxSize(){return this._maxSize}set(e,t){if(this.has(e)&&this.delete(e),super.set(e,t),this.size>this._maxSize){let n=this.keys().next().value;n!==void 0&&this.delete(n);}return this}get(e){if(!this.has(e))return;let t=super.get(e);return this.delete(e),super.set(e,t),t}};async function Xe(s,e){let t=-1,n=async(i,r)=>{if(r&&(e.state={...e.state||{},...r||{}}),i<=t)throw new Error("next() called multiple times in middleware");t=i;let a=s[i];i!==s.length&&a&&(e.next=n.bind(null,i+1),await a(e));};await n(0);}var A=class extends events.EventEmitter{patterns;middlewares;authCallback=null;_routeCORS;_routeConfig;_regexPatterns=[];constructor(e,t){super(),this.patterns=[],this.middlewares=t??[],e?.length&&this.route(...e);}route(...e){this.patterns.push(...e);for(let t of e)typeof t!="string"&&this._regexPatterns.push({regex:t,paramNames:[]});return this}use(...e){return this.middlewares.push(...e),this}cors(e){return this._routeCORS=e,this}config(e){return this._routeConfig=e,this}auth(e){return this.authCallback=e,this}handle(...e){return this.on("client",t=>{let n=e[e.length-1],i=[...e];typeof n=="function"&&(i[i.length-1]=(...r)=>{let a=r.length-1,o=r[a];return o&&typeof o=="object"&&Object.defineProperty(o,"client",{value:t,enumerable:true,configurable:true}),n(...r)}),t.handle(...i);}),this}};function kt(...s){return new A(s)}function Ye(s){return s.split(".").reduce((e,t)=>(e<<8)+parseInt(t,10),0)>>>0}function Ze(s,e){let t=s;t.startsWith("::ffff:")&&(t=t.substring(7));for(let n of e){if(n===t)return true;if(n.includes("/")){let i=n.split("/"),r=i[0],a=i[1];if(!r||!a)continue;let o=parseInt(a,10);if(net.isIPv4(t)&&net.isIPv4(r)){let d=Ye(t),p=Ye(r),c=o===0?0:-1<<32-o>>>0;if((d&c)===(p&c))return true}}}return false}function Ae(s,e){if(e.allowedIPs&&e.allowedIPs.length>0){let t=s.socket.remoteAddress;if(!t||!Ze(t,e.allowedIPs))return {allowed:false,reason:"IP address not allowed"}}if(e.allowedSchemes&&e.allowedSchemes.length>0){let t=s.socket instanceof tls.TLSSocket?"wss":"ws",n=s.headers["x-forwarded-proto"];if(typeof n=="string"&&(t=n==="https"||n==="wss"?"wss":"ws"),!e.allowedSchemes.includes(t))return {allowed:false,reason:"Protocol scheme not allowed"}}if(e.allowedOrigins&&e.allowedOrigins.length>0){let t=s.headers.origin;if(typeof t=="string"&&!e.allowedOrigins.includes(t))return {allowed:false,reason:"Origin not allowed"}}return {allowed:true}}var U=class{children=new Map;paramChild=null;paramName="";wildcardChild=null;routers=[]};function et(s){return s.replace(/\/+/g,"/").replace(/^\/|\/$/g,"").split("/").filter(Boolean)}var ye=class{root=new U;_frozen=false;_size=0;get size(){return this._size}insert(e,t){this._frozen&&(this._frozen=false);let n=et(e),i=this.root;for(let r of n)if(r==="*"){i.wildcardChild||(i.wildcardChild=new U),i=i.wildcardChild;break}else if(r.startsWith(":")){let a=r.slice(1);if(!i.paramChild)i.paramChild=new U,i.paramChild.paramName=a;else if(i.paramChild.paramName!==a)throw new Error(`Route conflict: param ":${a}" conflicts with existing ":${i.paramChild.paramName}" at the same position in pattern "${e}"`);i=i.paramChild;}else {let a=r.toLowerCase(),o=i.children.get(a);o||(o=new U,i.children.set(a,o)),i=o;}i.routers.push(t),this._size++;}match(e){let t=et(e),n=[];if(this._matchRecursive(this.root,t,0,{},n),n.length===0)return null;let i=n[0].params,r=[];for(let a of n)r.push(...a.routers);return {routers:r,params:i}}_matchRecursive(e,t,n,i,r){if(n===t.length){e.routers.length>0&&r.push({routers:[...e.routers],params:{...i}});return}let a=t[n],o=a.toLowerCase(),d=e.children.get(o);if(d&&this._matchRecursive(d,t,n+1,i,r),e.paramChild){let p={...i};p[e.paramChild.paramName]=decodeURIComponent(a),this._matchRecursive(e.paramChild,t,n+1,p,r);}e.wildcardChild&&e.wildcardChild.routers.length>0&&r.push({routers:[...e.wildcardChild.routers],params:{...i}});}freeze(){this._frozen||(this._freezeNode(this.root),this._frozen=true);}_freezeNode(e){Object.freeze(e.routers),e.paramChild&&this._freezeNode(e.paramChild),e.wildcardChild&&this._freezeNode(e.wildcardChild);for(let t of e.children.values())this._freezeNode(t);}get frozen(){return this._frozen}};var de=class extends oe{_serverSession;_serverHandshake;_serverPlugins;constructor(e,t){super(e),this._serverSession=t.session,this._serverHandshake=t.handshake,this._adaptiveMultiplier=t.adaptiveMultiplier??null,this._workerPool=t.workerPool??null,this._serverPlugins=t.plugins??[],this._state=re.OPEN,this._identity=this._options.identity,this._ws=t.ws,this._protocol=t.protocol??t.ws.protocol,this._attachServerWebsocket(t.ws),this._startPing();}_rateLimits={};_adaptiveMultiplier=null;_workerPool=null;_checkRateLimit(e){let t=this._options.rateLimit;if(!t)return true;let n=Date.now(),i=(r,a,o)=>{let d=this._rateLimits[r];if(!d)d={tokens:a,lastRefill:n},this._rateLimits[r]=d;else {let p=n-d.lastRefill,c=this._adaptiveMultiplier?.()??1,l=a/o*c,u=p*l;u>0&&(d.tokens=Math.min(a,d.tokens+u),d.lastRefill=n);}return d.tokens>=1?(d.tokens-=1,true):false};if(!i("global",t.limit,t.windowMs))return false;if(e&&t.methods?.[e]){let r=t.methods[e];if(!i(`method:${e}`,r.limit,r.windowMs))return false}return true}_invokeBeforeSend(e){if(this._serverPlugins.length===0)return true;let t=[];for(let n of this._serverPlugins)if(n.onBeforeSend)try{let i=n.onBeforeSend(this,e);if(i instanceof Promise)t.push(i.then(r=>r!==!1).catch(()=>!0));else if(i===!1)return !1}catch{}return t.length>0?Promise.all(t).then(n=>n.every(i=>i===true)):true}_attachServerWebsocket(e){e.on("message",async t=>{this._recordActivity();for(let i of this._serverPlugins)if(i.onBeforeReceive)try{let r=i.onBeforeReceive(this,t);if(r instanceof Promise){if(await r===!1)return}else if(r===!1)return}catch{}let n=this._options.rateLimit;if(n){let i,r;if(n.methods)try{r=JSON.parse(t),Array.isArray(r)&&r[0]===2&&(i=r[2]);}catch{}if(!this._checkRateLimit(i)){this._handleRateLimitExceeded(r||t.toString());return}if(r!==void 0){this._onMessage(t,r);return}}if(this._workerPool){let i=t;this._workerPool.parse(i).then(r=>{this._onMessage(t,r.message);}).catch(()=>{this._onMessage(t);});return}this._onMessage(t);}),e.on("close",(t,n)=>this._onClose(t,n)),e.on("error",t=>{this.listenerCount("error")>0?this.emit("error",t):this._logger?.debug?.("WebSocket error (unhandled by client listener)",{error:t.message});}),e.on("ping",()=>{this._recordActivity(),this.emit("ping");}),e.on("pong",()=>{this._pongTimer&&(clearTimeout(this._pongTimer),this._pongTimer=null),this._recordActivity(),this.emit("pong");});}_handleRateLimitExceeded(e){let n=this._options.rateLimit.onLimitExceeded||"ignore";if(this.emit("rateLimitExceeded",{rawData:e}),n==="disconnect")this._logger?.warn?.("Rate limit exceeded \u2014 disconnecting client",{identity:this.identity}),this._ws?.terminate();else if(typeof n=="function")try{let i=n(this,e);i instanceof Promise&&i.catch(r=>{this._logger?.error?.("Error in custom onLimitExceeded handler",{identity:this.identity,error:r});});}catch(i){this._logger?.error?.("Error in custom onLimitExceeded handler",{identity:this.identity,error:i});}else this._logger?.debug?.("Rate limit exceeded \u2014 ignoring message",{identity:this.identity});}get session(){return this._serverSession}get handshake(){return this._serverHandshake}async connect(){throw new Error("Cannot connect from server client \u2014 connection is managed by the server")}close(e={}){return super.close(e)}};var je=class{_workers=[];_nextWorker=0;_taskId=0;_pending=new Map;_maxQueueSize;_terminated=false;constructor(e={}){let t=e.poolSize??Math.max(2,os.cpus().length-2);this._maxQueueSize=e.maxQueueSize??1e4;let n=path.resolve(__dirname,"parse-worker.js");for(let i=0;i<t;i++){let r=new worker_threads.Worker(n);r.on("message",a=>{let o=this._pending.get(a.id);o&&(this._pending.delete(a.id),a.error?o.reject(new Error(a.error)):o.resolve({message:a.message,validationError:a.validationError}));}),r.on("error",a=>{console.error(`[WorkerPool] Worker ${i} error:`,a.message);}),this._workers.push(r);}}get size(){return this._workers.length}get pendingTasks(){return this._pending.size}parse(e,t){return this._terminated?Promise.reject(new Error("WorkerPool has been shut down")):this._pending.size>=this._maxQueueSize?Promise.reject(new Error(`WorkerPool queue full (${this._maxQueueSize} pending tasks)`)):new Promise((n,i)=>{let r=this._taskId++;this._pending.set(r,{resolve:n,reject:i});let a=this._workers[this._nextWorker%this._workers.length];this._nextWorker=(this._nextWorker+1)%this._workers.length,a.postMessage({id:r,buffer:e,schemaInfo:t});})}async shutdown(){if(this._terminated)return;this._terminated=true;for(let[t,n]of this._pending)n.reject(new Error("WorkerPool shutting down")),this._pending.delete(t);let e=this._workers.map(async t=>{try{await Promise.race([t.terminate(),new Promise(n=>setTimeout(n,5e3))]);}catch{}});await Promise.allSettled(e),this._workers=[];}};function tt(s={}){try{return new je(s)}catch{return null}}var qe=class extends events.EventEmitter{_options;_trie=new ye;_globalMiddlewareRouters=[];_regexRouters=[];_clients=new Set;_clientsByIdentity=new Map;_httpServers=new Set;_wss=null;_state="OPEN";_adapter=null;_httpServerAbortControllers=new Set;_logger=null;_globalCORS;_connectionBuckets=new Map;_adaptiveLimiter=null;_plugins=[];_workerPool=null;_telemetryInterval=null;_nodeId=me();_sessions;_gcInterval=null;_sessionTimeoutMs;constructor(e={}){if(super(),this.setMaxListeners(0),e.strictMode&&!e.protocols?.length)throw new Error("strictMode requires protocols to be specified (e.g. protocols: ['ocpp1.6'])");this._options={securityProfile:0,callTimeoutMs:3e4,pingIntervalMs:3e4,deferPingsOnActivity:false,callConcurrency:1,maxBadMessages:1/0,respondWithDetailedErrors:false,handshakeTimeoutMs:3e4,sessionTtlMs:7200*1e3,...e},this._sessionTimeoutMs=this._options.sessionTtlMs;let t=this._options.maxSessions??5e4;this._sessions=new se(t),this._wss=new ae.WebSocketServer({noServer:true,maxPayload:this._options.maxPayloadBytes??65536,perMessageDeflate:this._buildCompressionConfig()}),this._gcInterval=setInterval(()=>{let r=Date.now();for(let[a,o]of this._sessions.entries())r-o.lastActive>this._sessionTimeoutMs&&this._sessions.delete(a);},60*1e3).unref(),this._logger=ce(this._options.logging,{component:"OCPPServer"});let n=this._options.rateLimit;n?.adaptive&&(this._adaptiveLimiter=new z({cpuThresholdPercent:n.cpuThresholdPercent,memThresholdPercent:n.memThresholdPercent,cooldownMs:n.cooldownMs}),this._adaptiveLimiter.on("adapted",r=>{this._logger?.info?.("Adaptive rate limit adjusted",r),this.emit("rateLimit:adapted",r);}),this._adaptiveLimiter.start());let i=this._options.workerThreads;if(i){let r=typeof i=="object"?i:{};this._workerPool=tt(r),this._workerPool&&this._logger?.info?.("Worker thread pool initialized",{poolSize:this._workerPool.size});}}get log(){return this._logger||M}get clients(){return this._clients}get state(){return this._state}stats(){let e=0;if(this._wss)for(let t of this._wss.clients)e+=t.bufferedAmount;return {connectedClients:this._clients.size,activeSessions:this._sessions.size,uptimeSeconds:process.uptime(),pid:process.pid,memoryUsage:process.memoryUsage(),cpuUsage:process.cpuUsage(),webSockets:this._wss?{total:this._wss.clients.size,bufferedAmount:e}:void 0}}async adapterMetrics(){if(!this._adapter?.metrics)return null;try{return await this._adapter.metrics()}catch(e){return this._logger?.warn?.("Failed to fetch adapter metrics",{error:e}),null}}getLocalClient(e){return this._clientsByIdentity.get(e)}hasLocalClient(e){return this.getLocalClient(e)!==void 0}async isClientConnected(e){if(this.hasLocalClient(e))return true;if(this._adapter?.getPresence){let t=await this._adapter.getPresence(e);return t!=null}return false}cors(e){return this._globalCORS=e,this}route(...e){let t=new A;return t.route(...e),this._registerRouter(t),t}attachRouters(...e){for(let t of e)this._registerRouter(t);return this}plugin(...e){for(let t of e)if(this._plugins.push(t),this._logger?.info?.("Plugin registered",{name:t.name}),t.onInit){let n=t.onInit(this);n instanceof Promise&&n.catch(i=>{this._logger?.error?.("Plugin onInit error",{name:t.name,error:i.message});});}return this._startTelemetryPush(),this}_startTelemetryPush(){if(this._telemetryInterval)return;let e=this._options.telemetry?.pushIntervalMs;!e||e<=0||this._plugins.some(t=>t.onTelemetry)&&(this._telemetryInterval=setInterval(async()=>{try{let t=this.stats(),n=this._adapter?await this.adapterMetrics().catch(()=>null):null;for(let i of this._plugins)try{await i.onTelemetry?.(t,n??void 0);}catch{}}catch{}},e),this._telemetryInterval.unref());}use(...e){let t=new A;return t.use(...e),this._registerRouter(t),t}auth(e){let t=new A;return t.auth(e),this._registerRouter(t),t}_registerRouter(e){let t=e.patterns.filter(i=>typeof i=="string"),n=e._regexPatterns.length>0;if(t.length===0&&!n)this._globalMiddlewareRouters.push(e);else {for(let i of t)this._trie.insert(i,e);n&&this._regexRouters.push(e);}}async listen(e=0,t,n){let i;if(n?.server)i=n.server;else {let a=this._options.securityProfile??0;if(a===2||a===3){let o=this._options.tls??{},d={};o.cert&&(d.cert=o.cert),o.key&&(d.key=o.key),o.ca&&(d.ca=o.ca),o.passphrase&&(d.passphrase=o.passphrase),a===3&&(d.requestCert=true,d.rejectUnauthorized=o.rejectUnauthorized??true),i=https.createServer(d);}else i=qt.createServer();}this._state==="CLOSED"&&(this._state="OPEN");let r=(a,o,d)=>{this._handleUpgrade(a,o,d).catch(p=>{o.destroyed||o.destroy(),this._logger?.error?.("Upgrade error",{error:p.message}),this.emit("upgradeError",{error:p,socket:o});});};if(i.on("upgrade",r),this._httpServers.add(i),this._options.healthEndpoint&&i.on("request",async(a,o)=>{let d=a.url??"";if(d==="/health"){let p=this.stats(),c=JSON.stringify({status:this._state==="OPEN"?"ok":"degraded",state:this._state,connectedClients:p.connectedClients,activeSessions:p.activeSessions,uptimeSeconds:Math.round(p.uptimeSeconds),pid:p.pid});o.writeHead(200,{"Content-Type":"application/json","Cache-Control":"no-cache"}),o.end(c);return}if(d==="/metrics"){let p=this.stats(),c=["# HELP ocpp_connected_clients Number of currently connected OCPP clients","# TYPE ocpp_connected_clients gauge",`ocpp_connected_clients ${p.connectedClients}`,"","# HELP ocpp_active_sessions Number of active in-memory sessions","# TYPE ocpp_active_sessions gauge",`ocpp_active_sessions ${p.activeSessions}`,"","# HELP ocpp_uptime_seconds Process uptime in seconds","# TYPE ocpp_uptime_seconds gauge",`ocpp_uptime_seconds ${Math.round(p.uptimeSeconds)}`,"","# HELP ocpp_memory_rss_bytes Resident set size in bytes","# TYPE ocpp_memory_rss_bytes gauge",`ocpp_memory_rss_bytes ${p.memoryUsage.rss}`,"","# HELP ocpp_memory_heap_used_bytes V8 heap used in bytes","# TYPE ocpp_memory_heap_used_bytes gauge",`ocpp_memory_heap_used_bytes ${p.memoryUsage.heapUsed}`,"","# HELP ocpp_memory_heap_total_bytes V8 heap total in bytes","# TYPE ocpp_memory_heap_total_bytes gauge",`ocpp_memory_heap_total_bytes ${p.memoryUsage.heapTotal}`,"","# HELP ocpp_ws_buffered_bytes Total buffered WebSocket bytes","# TYPE ocpp_ws_buffered_bytes gauge",`ocpp_ws_buffered_bytes ${p.webSockets?.bufferedAmount??0}`,""];o.writeHead(200,{"Content-Type":"text/plain; version=0.0.4; charset=utf-8","Cache-Control":"no-cache"});for(let l of this._plugins)if(l.getCustomMetrics)try{let u=await l.getCustomMetrics();u?.length&&(c.push(""),c.push(...u));}catch(u){this._logger?.error?.("Plugin getCustomMetrics error",{name:l.name,error:u.message});}o.end(c.join(`
4825
+ `));return}o.writeHead(404,{"Content-Type":"text/plain"}),o.end("Not Found");}),n?.signal){let a=new AbortController;this._httpServerAbortControllers.add(a),n.signal.addEventListener("abort",()=>{a.abort(),i.close(),this._httpServers.delete(i);},{once:true});}return n?.server||await new Promise((a,o)=>{i.on("error",o),i.listen(e,t,()=>{i.removeListener("error",o);let d=i.address();this._logger?.info?.("Server listening",{port:typeof d=="object"?d?.port:e,host:t??"0.0.0.0"}),a();});}),i}updateTLS(e){let t=this._options.securityProfile??0;if(t!==2&&t!==3)throw new Error("updateTLS() requires a TLS Security Profile (TLS_BASIC_AUTH or TLS_CLIENT_CERT)");this._options.tls={...this._options.tls,...e};let n={};e.cert&&(n.cert=e.cert),e.key&&(n.key=e.key),e.ca&&(n.ca=e.ca),e.passphrase&&(n.passphrase=e.passphrase);let i=0;for(let r of this._httpServers)"setSecureContext"in r&&typeof r.setSecureContext=="function"&&(r.setSecureContext(n),i++);this._logger?.info?.(`TLS context hot-reloaded across ${i} active server(s)`);for(let r of this._plugins)try{r.onTLSUpdate?.(e);}catch(a){this._logger?.error?.("Plugin onTLSUpdate error",{name:r.name,error:a.message});}}get handleUpgrade(){return (e,t,n)=>this._handleUpgrade(e,t,n).catch(i=>{t.destroyed||t.destroy(),this._logger?.error?.("Upgrade error",{error:i.message}),this.emit("upgradeError",{error:i,socket:t});})}async _handleUpgrade(e,t,n){if(this._state!=="OPEN"){_(t,503,"Server is shutting down");return}let i=this._options.connectionRateLimit;if(i){let m=e.socket.remoteAddress??"unknown",I=Date.now(),C=this._connectionBuckets.get(m);if(!C)C={tokens:i.limit,lastRefill:I},this._connectionBuckets.set(m,C);else {let h=I-C.lastRefill,E=i.limit/i.windowMs;C.tokens=Math.min(i.limit,C.tokens+h*E),C.lastRefill=I;}if(C.tokens<1){this._logger?.warn?.("Connection rate limit exceeded",{ip:m});let h={type:"CONNECTION_RATE_LIMIT",ip:m,timestamp:new Date().toISOString(),details:{tokensRemaining:C.tokens}};this.emit("securityEvent",h);for(let E of this._plugins)try{E.onSecurityEvent?.(h);}catch{}_(t,429,"Too Many Requests");return}C.tokens-=1;}if(t.readyState!=="open"){this._logger?.debug?.("Socket not open at upgrade start"),t.destroyed||t.destroy();return}if(e.headers.upgrade?.toLowerCase()!=="websocket"){_(t,400,"Invalid upgrade request");return}if(this._globalCORS){let{allowed:m,reason:I}=Ae(e,this._globalCORS);if(!m){this._logger?.warn?.("CORS rejected connection",{reason:I,ip:e.socket.remoteAddress}),_(t,403,"Forbidden");return}}let r=new URL(e.url??"/",`http://${e.headers.host??"localhost"}`),a,o=[],d=[],p={},c=r.pathname,l=false,u=this._trie.size>0||this._regexRouters.length>0,f;!this._trie.frozen&&this._trie.size>0&&this._trie.freeze();for(let m of this._globalMiddlewareRouters)d.push(m),m.middlewares.length>0&&o.push(...m.middlewares),m.authCallback&&!a&&(a=m.authCallback);let S=this._trie.match(c);if(S){Object.assign(p,S.params);for(let m of S.routers)d.push(m),l=true,m._routeConfig&&(f=Object.assign(f||{},m._routeConfig)),m.middlewares.length>0&&o.push(...m.middlewares),m.authCallback&&!a&&(a=m.authCallback);}for(let m of this._regexRouters)for(let I of m._regexPatterns){let C=I.regex.exec(c);if(C){if(d.push(m),l=true,C.groups)for(let[h,E]of Object.entries(C.groups))p[h]=decodeURIComponent(E??"");m._routeConfig&&(f=Object.assign(f||{},m._routeConfig)),m.middlewares.length>0&&o.push(...m.middlewares),m.authCallback&&!a&&(a=m.authCallback);break}}let y=p.identity;if(!y){let m=c.split("/").filter(Boolean);y=decodeURIComponent(m[m.length-1]??"");}if(!y){_(t,400,"Missing identity in URL path");return}for(let m of d)if(m._routeCORS){let{allowed:I,reason:C}=Ae(e,m._routeCORS);if(!I){this._logger?.warn?.("Route CORS rejected connection",{reason:C,ip:e.socket.remoteAddress}),_(t,403,"Forbidden");return}}"setKeepAlive"in t&&t.setKeepAlive(true);let j=new Set,W=e.headers["sec-websocket-protocol"];if(W)try{j=Ge(W);}catch{_(t,400,"Invalid Sec-WebSocket-Protocol header");return}let Me=f?.protocols??this._options.protocols??[],V;if(Me.length>0){if(j.size===0){_(t,400,"Missing subprotocol");return}if(V=Me.find(m=>j.has(m)),!V){_(t,400,"No matching subprotocol");return}}let it=Ke(e.headers.authorization??"",y),Oe,Ve=this._options.securityProfile??0;Ve===3&&"getPeerCertificate"in t&&(Oe=t.getPeerCertificate());let H={identity:y,remoteAddress:e.socket.remoteAddress??"",headers:e.headers,protocols:j,pathname:c,params:p,query:r.searchParams,request:e,password:it,clientCertificate:Oe,securityProfile:Ve},Te,Ne;if(a||o.length>0){let m=new AbortController,I=()=>{m.abort(new Error("Socket closed during handshake"));};t.on("close",I),t.on("error",I),t.on("end",I);let C=this._options.handshakeTimeoutMs??3e4,h;C>0&&(h=setTimeout(()=>{m.abort(new Error("Handshake timeout"));},C));try{Te={handshake:H,state:{},reject:(T=401,b="Unauthorized")=>{throw {code:T,message:b,_isMiddlewareReject:!0}},next:async T=>{}};let E=[...o],g=!1;if(E.push(async T=>{g=!0,a?Ne=await new Promise((b,$)=>{let D=!1,pe=N=>{D||(D=!0,N?.protocol&&(V=N.protocol),b(N));},ve=(N=401,ke="Unauthorized")=>{throw D||(D=!0,$({code:N,message:ke})),{code:N,message:ke,_isMiddlewareReject:!0}};if(m.signal.aborted){$(m.signal.reason);return}m.signal.addEventListener("abort",()=>{D||(D=!0,$(m.signal.reason));},{once:!0}),this._logger?.debug?.("Executing auth callback",{identity:y,pathname:c});let nt={handshake:H,state:T.state,reject:ve,signal:m.signal,accept:pe};a(nt);}):V=H.protocols.values().next().value??void 0;}),await Xe(E,Te),!g)throw {code:500,message:"Middleware chain halted unexpectedly without rejecting",_isMiddlewareReject:!0}}catch(E){if(m.signal.aborted){let D=E instanceof Error?E.message:"Unknown abort";this._logger?.warn?.("Handshake aborted",{identity:y,reason:D});let pe={type:"UPGRADE_ABORTED",identity:y,ip:e.socket.remoteAddress,timestamp:new Date().toISOString(),details:{reason:D}};this.emit("securityEvent",pe);for(let ve of this._plugins)try{ve.onSecurityEvent?.(pe);}catch{}this.emit("upgradeAborted",{identity:y,reason:D,socket:t,request:e}),t.destroyed||t.destroy();return}let g=E,T=typeof g?.code=="number"?g.code:401,b=typeof g?.message=="string"?g.message:"Unauthorized";this._logger?.warn?.("Auth rejected",{identity:y,code:T});let $={type:"AUTH_FAILED",identity:y,ip:e.socket.remoteAddress,timestamp:new Date().toISOString(),details:{code:T,message:b}};this.emit("securityEvent",$);for(let D of this._plugins){try{D.onSecurityEvent?.($);}catch{}try{D.onAuthFailed?.(H,T,b);}catch{}}_(t,T,b);return}finally{h&&clearTimeout(h),t.removeListener("close",I),t.removeListener("error",I),t.removeListener("end",I);}}else if(u&&!l){this._logger?.warn?.("Connection rejected: No matching route found",{pathname:c}),_(t,404,"Endpoint Not Found");return}if(t.readyState!=="open"){this._logger?.debug?.("Socket closed before upgrade completion",{identity:y}),t.destroyed||t.destroy();return}this._wss||(this._wss=new ae.WebSocketServer({noServer:true,maxPayload:this._options.maxPayloadBytes??65536})),this._wss.handleUpgrade(e,t,n,m=>{let I={identity:y,endpoint:"",callTimeoutMs:f?.callTimeoutMs??this._options.callTimeoutMs,pingIntervalMs:f?.pingIntervalMs??this._options.pingIntervalMs,deferPingsOnActivity:f?.deferPingsOnActivity??this._options.deferPingsOnActivity,callConcurrency:f?.callConcurrency??this._options.callConcurrency,maxBadMessages:this._options.maxBadMessages,respondWithDetailedErrors:this._options.respondWithDetailedErrors,strictMode:f?.strictMode??this._options.strictMode,strictModeMethods:f?.strictModeMethods??this._options.strictModeMethods,strictModeValidators:this._options.strictModeValidators,rateLimit:f?.rateLimit??this._options.rateLimit,reconnect:false,logging:this._options.logging},C={...Te?.state||{},...this._sessions.get(y)?.data||{},...Ne?.session||{}},h=new de(I,{ws:m,handshake:H,session:C,protocol:V,adaptiveMultiplier:this._adaptiveLimiter?()=>this._adaptiveLimiter.multiplier:void 0,workerPool:this._workerPool??void 0,plugins:this._plugins});this._updateSessionActivity(y,h.session);let E=this._clientsByIdentity.get(y);if(E&&E!==h){this._logger?.warn?.("Evicting stale connection for identity",{identity:y,reason:"Duplicate identity replaced by new connection"});for(let g of this._plugins)try{g.onEviction?.(E,h);}catch{}E.close({code:4e3,reason:"Evicted by new connection",force:true}).catch(()=>{}),this._clients.delete(E);}this._clients.add(h),this._clientsByIdentity.set(y,h),this._adapter?.setPresence&&this._adapter.setPresence(y,this._nodeId,300).catch(g=>{this._logger?.error?.("Error setting presence",{identity:y,error:g});}),this._logger?.info?.("Client connected",{identity:y,remoteAddress:e.socket.remoteAddress,protocol:V}),h.on("close",({code:g,reason:T})=>{this._clients.delete(h),this._clientsByIdentity.get(y)===h&&this._clientsByIdentity.delete(y),this?._adapter?.removePresence&&this._adapter.removePresence(y).catch(b=>{this._logger?.error?.("Error removing presence",{identity:y,error:b});});for(let b of this._plugins)try{b.onDisconnect?.(h,g,T);}catch($){this._logger?.error?.("Plugin onDisconnect error",{name:b.name,error:$.message});}this._logger?.info?.("Client disconnected",{identity:y});});for(let g of this._plugins)try{let T=g.onConnection?.(h);T instanceof Promise&&T.catch(b=>{this._logger?.error?.("Plugin onConnection error",{name:g.name,error:b.message});});}catch(T){this._logger?.error?.("Plugin onConnection error",{name:g.name,error:T.message});}h.on("message",g=>{for(let T of this._plugins)try{T.onMessage?.(h,g);}catch{}}),h.on("error",g=>{for(let T of this._plugins)try{T.onError?.(h,g);}catch{}}),h.on("badMessage",({message:g,error:T})=>{for(let b of this._plugins)try{b.onBadMessage?.(h,g,T);}catch{}}),h.on("strictValidationFailure",({message:g,error:T})=>{for(let b of this._plugins)try{b.onValidationFailure?.(h,g,T);}catch{}}),h.on("backpressure",g=>{for(let T of this._plugins)try{T.onBackpressure?.(h,g.bufferedAmount);}catch{}}),h.on("pongTimeout",()=>{for(let g of this._plugins)try{g.onPongTimeout?.(h);}catch{}}),h.on("handlerError",({method:g,error:T})=>{for(let b of this._plugins)try{b.onHandlerError?.(h,g,T);}catch{}}),h.on("rateLimitExceeded",g=>{for(let T of this._plugins)try{T.onRateLimitExceeded?.(h,g.rawData);}catch{}}),this.emit("client",h);for(let g of d)g.emit("client",h);h.on("message",()=>{this._updateSessionActivity(y,h.session);});});}_updateSessionActivity(e,t){this._sessions.set(e,{data:t,lastActive:Date.now()});}async close(e={}){if(this._state!=="OPEN")return;this._state="CLOSING",this.emit("closing"),this._logger?.info?.("Server closing",{clientCount:this._clients.size});for(let i of this._plugins)try{let r=i.onClosing?.();r instanceof Promise&&await r;}catch(r){this._logger?.error?.("Plugin onClosing error",{name:i.name,error:r.message});}if(this._gcInterval&&(clearInterval(this._gcInterval),this._gcInterval=null),this._telemetryInterval&&(clearInterval(this._telemetryInterval),this._telemetryInterval=null),!e.force){let r=Array.from(this._clients).map(async a=>{let o=a._ws;o&&o.bufferedAmount>0&&(this._logger?.debug?.("Waiting for client buffer to drain",{identity:a.identity,bufferedAmount:o.bufferedAmount}),await new Promise(d=>{let p=0,c=setInterval(()=>{p+=50,(!o||o.bufferedAmount===0||p>=5e3)&&(clearInterval(c),d());},50);}));});await Promise.allSettled(r);}let t=Array.from(this._clients).map(i=>i.close(e).catch(()=>{}));await Promise.allSettled(t);for(let i of this._httpServerAbortControllers)i.abort();this._httpServerAbortControllers.clear(),this._wss&&(this._wss.close(),this._wss=new ae.WebSocketServer({noServer:true}));let n=Array.from(this._httpServers).map(i=>new Promise(r=>{i.close(()=>r());}));await Promise.allSettled(n),this._httpServers.clear(),this._adaptiveLimiter&&this._adaptiveLimiter.stop();for(let i of this._plugins)try{let r=i.onClose?.();r instanceof Promise&&await r;}catch(r){this._logger?.error?.("Plugin onClose error",{name:i.name,error:r.message});}this._adapter&&await this._adapter.disconnect(),this._state="CLOSED",this.emit("close");}reconfigure(e){let t={...this._options};Object.assign(this._options,e);for(let n of this._plugins)try{n.onReconfigure?.(e,t);}catch(i){this._logger?.error?.("Plugin onReconfigure error",{name:n.name,error:i.message});}}async sendToClient(...e){let t,n,i,r;e.length>=4&&typeof e[0]=="string"&&typeof e[1]=="string"&&typeof e[2]=="string"?(t=e[0],n=e[2],i=e[3],r=e[4]):(t=e[0],n=e[1],i=e[2],r=e[3]);for(let a of this._clients)if(a.identity===t)return await a.call(n,i,r);if(this._adapter?.getPresence){let a=await this._adapter.getPresence(t);if(a){await this._adapter.publish(`ocpp:node:${a}`,{source:this._nodeId,target:t,method:n,params:i,options:r});return}}throw new Error(`Client ${t} not found`)}async safeSendToClient(...e){try{return await this.sendToClient(...e)}catch(t){this._logger&&typeof this._logger.warn=="function"&&t.name!=="TimeoutError"&&this._logger.warn("SafeSendToClient failed",{identity:e[0],method:e.length>=4&&typeof e[1]=="string"&&typeof e[2]=="string"?e[2]:e.length>=3&&typeof e[1]=="string"?e[1]:"unknown",error:t});return}}async sendBatch(e,t){if(t.length===0)return [];let n=this._clientsByIdentity.get(e);if(!n)return this._logger?.warn?.("sendBatch: client not found locally",{identity:e}),t.map(()=>{});let i=n.options.callConcurrency??1;t.length>i&&n.reconfigure({callConcurrency:t.length});try{return (await Promise.allSettled(t.map(a=>n.call(a.method,a.params,a.options??{})))).map(a=>{if(a.status==="fulfilled")return a.value;this._logger?.warn?.("sendBatch: individual call failed",{identity:e,error:a.reason?.message});})}finally{t.length>i&&n.reconfigure({callConcurrency:i});}}async setAdapter(e){this._adapter=e,await this._adapter.subscribe("ocpp:broadcast",t=>this._onBroadcast(t)),await this._adapter.subscribe(`ocpp:node:${this._nodeId}`,t=>{this._onUnicast(t);});}_onBroadcast(e){try{if(!e||typeof e!="object")return;let t=e;if(t.source===this._nodeId)return;for(let n of this._clients)n.call(t.method,t.params).catch(()=>{});}catch(t){this._logger?.error?.("Error processing broadcast message",{error:t.message});}}_onUnicast(e){try{if(!e||typeof e!="object")return;let t=e;for(let n of this._clients)if(n.identity===t.target){n.call(t.method,t.params,t.options).catch(i=>{i.name!=="TimeoutError"&&this._logger?.error?.("Error delivering unicast to client",{identity:t.target,error:i});});return}this._logger?.warn?.("Received unicast for unknown client",{target:t.target}),this._adapter?.removePresence&&this._adapter.removePresence(t.target).catch(()=>{});}catch(t){this._logger?.error?.("Error processing unicast",{error:t.message});}}async publish(e,t){this._adapter&&await this._adapter.publish(e,t);}async broadcast(e,t){let n=Array.from(this._clients).map(r=>r.call(e,t).catch(()=>{})),i=this._adapter?this._adapter.publish("ocpp:broadcast",{source:this._nodeId,method:e,params:t}):Promise.resolve();await Promise.all([Promise.all(n),i]);}async broadcastBatch(e,t,n,i){let r=new Set,a=[];for(let d of e){let p=this._clientsByIdentity.get(d);p&&(r.add(d),a.push(p.call(t,n,i).catch(()=>{})));}let o=e.filter(d=>!r.has(d));if(o.length>0&&this._adapter){let d=[];this._adapter.getPresenceBatch?d=await this._adapter.getPresenceBatch(o):this._adapter.getPresence&&(d=await Promise.all(o.map(c=>this._adapter.getPresence(c))));let p=[];for(let c=0;c<o.length;c++){let l=d[c];l&&p.push({channel:`ocpp:node:${l}`,data:{source:this._nodeId,target:o[c],method:t,params:n,options:i}});}p.length>0&&(this._adapter.publishBatch?await this._adapter.publishBatch(p):await Promise.all(p.map(c=>this._adapter.publish(c.channel,c.data))));}await Promise.all(a);}_buildCompressionConfig(){let e=this._options.compression;return e?e===true?{threshold:1024,zlibDeflateOptions:{level:6,memLevel:8},zlibInflateOptions:{},serverNoContextTakeover:true,clientNoContextTakeover:true}:{threshold:e.threshold??1024,zlibDeflateOptions:{level:e.level??6,memLevel:e.memLevel??8},zlibInflateOptions:{},serverNoContextTakeover:e.serverNoContextTakeover??true,clientNoContextTakeover:e.clientNoContextTakeover??true}:false}};
4826
+ exports.AdaptiveLimiter=z;exports.ClusterDriver=be;exports.ConnectionState=re;exports.InMemoryAdapter=Ce;exports.LRUMap=se;exports.MessageType=x;exports.MiddlewareStack=le;exports.NOREPLY=Le;exports.OCPPClient=oe;exports.OCPPRouter=A;exports.OCPPServer=qe;exports.OCPPServerClient=de;exports.RPCFormatViolationError=Y;exports.RPCFormationViolationError=Q;exports.RPCFrameworkError=ie;exports.RPCGenericError=P;exports.RPCInternalError=J;exports.RPCMessageTypeNotSupportedError=L;exports.RPCNotImplementedError=R;exports.RPCNotSupportedError=G;exports.RPCOccurrenceConstraintViolationError=ee;exports.RPCPropertyConstraintViolationError=Z;exports.RPCProtocolError=K;exports.RPCSecurityError=X;exports.RPCTypeConstraintViolationError=te;exports.RedisAdapter=Ie;exports.SecurityProfile=ge;exports.TimeoutError=k;exports.UnexpectedHttpResponse=B;exports.Validator=he;exports.WebsocketUpgradeError=Ee;exports.combineAuth=ft;exports.createLoggingMiddleware=xe;exports.createPlugin=ut;exports.createRPCError=q;exports.createRouter=kt;exports.createValidator=ne;exports.defineAdapter=at;exports.defineAuth=ht;exports.defineMiddleware=lt;exports.defineRpcMiddleware=mt;exports.getErrorPlainObject=De;exports.getPackageIdent=we;exports.getStandardValidators=_e;