ocpp-ws-io 2.2.2-beta.1 → 2.2.4
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/README.md +1 -1
- package/dist/adapters/redis.d.mts +2 -2
- package/dist/adapters/redis.d.ts +2 -2
- package/dist/browser.js +1 -1
- package/dist/browser.mjs +1 -1
- package/dist/{context-Cy7YIKyU.d.mts → context-BVYqFvfw.d.mts} +1 -1
- package/dist/{context-DcTIzhq-.d.ts → context-B_y56LLS.d.ts} +1 -1
- package/dist/express.d.mts +1 -1
- package/dist/express.d.ts +1 -1
- package/dist/fastify.d.mts +2 -2
- package/dist/fastify.d.ts +2 -2
- package/dist/hono.d.mts +2 -2
- package/dist/hono.d.ts +2 -2
- package/dist/{index-B9rTwvbn.d.mts → index-Dr8uXTWu.d.mts} +1 -1
- package/dist/{index-D5pJ3wS4.d.ts → index-DrWsObRI.d.ts} +1 -1
- package/dist/index.d.mts +4 -4
- package/dist/index.d.ts +4 -4
- package/dist/index.js +7 -7
- package/dist/index.mjs +7 -7
- package/dist/nestjs.d.mts +1 -1
- package/dist/nestjs.d.ts +1 -1
- package/dist/nestjs.js +8 -8
- package/dist/nestjs.mjs +8 -8
- package/dist/plugins.d.mts +32 -6
- package/dist/plugins.d.ts +32 -6
- package/dist/plugins.js +1 -1
- package/dist/plugins.mjs +1 -1
- package/dist/{types-xFfIgIuS.d.mts → types-BsoUgWtt.d.mts} +29 -2
- package/dist/{types-xFfIgIuS.d.ts → types-BsoUgWtt.d.ts} +29 -2
- package/package.json +2 -2
package/dist/nestjs.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
'use strict';var common=require('@nestjs/common'),core=require('@nestjs/core'),events=require('events'),Kt=require('http'),https=require('https'),ie=require('ws'),os=require('os'),tls=require('tls'),net=require('net'),voltlogIo=require('voltlog-io'),Ut=require('ajv'),Wt=require('ajv-formats'),crypto=require('crypto'),path=require('path'),worker_threads=require('worker_threads');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var Kt__default=/*#__PURE__*/_interopDefault(Kt);var ie__default=/*#__PURE__*/_interopDefault(ie);var Ut__default=/*#__PURE__*/_interopDefault(Ut);var Wt__default=/*#__PURE__*/_interopDefault(Wt);var k=(o,e,t,n)=>{for(var i=e,r=o.length-1,a;r>=0;r--)(a=o[r])&&(i=(a(i))||i);return i},B=(o,e)=>(t,n)=>e(t,n,o);var Z="ocpp:gateway",se="ocpp:message_event",de="ocpp:wildcard_event",pe="ocpp:auth",ce="ocpp:connection_middleware",le="ocpp:rpc_middleware",ue="ocpp:cors",ee="ocpp:params_args",F="OCPP_SERVER_OPTIONS",q="OCPP_SERVER_INSTANCE";var Ti=o=>common.SetMetadata(Z,typeof o=="string"?{path:o}:o||{}),vi=o=>common.SetMetadata(ue,o),Ci=(...o)=>common.SetMetadata(le,o);var Ei=(o,e)=>common.SetMetadata(se,{action:o,protocol:e}),Di=()=>common.SetMetadata(de,true),xi=()=>common.SetMetadata(pe,true),wi=()=>common.SetMetadata(ce,true);var Fe=(c=>(c[c.CLIENT=0]="CLIENT",c[c.MESSAGE=1]="MESSAGE",c[c.PARAMS=2]="PARAMS",c[c.CONTEXT=3]="CONTEXT",c[c.IDENTITY=4]="IDENTITY",c[c.PATH=5]="PATH",c[c.SESSION=6]="SESSION",c[c.PATH_PARAMS=7]="PATH_PARAMS",c[c.PROTOCOL=8]="PROTOCOL",c[c.MESSAGE_ID=9]="MESSAGE_ID",c[c.HANDSHAKE=10]="HANDSHAKE",c))(Fe||{});function j(o,e){return ()=>(t,n,i)=>{let r=Reflect.getMetadata(ee,t.constructor,n)||{},a={type:o,data:e};Reflect.defineMetadata(ee,{...r,[i]:a},t.constructor,n);}}var qi=j(0),Oi=j(1),Mi=j(2),Vi=j(3),Ni=j(4),ki=j(5),Fi=j(6),Ui=o=>j(7,o)(),Wi=j(8),Hi=j(9),zi=j(10);exports.OcppExplorer=class O{constructor(e,t,n,i){this.discoveryService=e;this.metadataScanner=t;this.server=n;this.service=i;}discoveryService;metadataScanner;server;service;logger=new common.Logger(exports.OcppExplorer.name);onModuleInit(){this.explore();}explore(){this.discoveryService.getProviders().filter(n=>n.metatype&&Reflect.hasMetadata(Z,n.metatype)).forEach(n=>{let{instance:i,metatype:r}=n;if(!i||!r)return;let a=Reflect.getMetadata(Z,r),s=Reflect.getMetadata(ue,r),p=Reflect.getMetadata(le,r),d=a?.path;this.service?.registerUpgradePath(d);let l=d?this.server.route(d):this.server.route();s&&l.cors(s);let c={...a};delete c.path,Object.keys(c).length>0&&l.config(c);let u=typeof i.onOcppClientConnected=="function",g=typeof i.onOcppClientDisconnected=="function",b=typeof i.onOcppClientError=="function";(u||g||b||p?.length)&&l.on("client",h=>{if(p?.length)for(let C of p)h.use(C);u&&i.onOcppClientConnected(h),g&&h.on("close",C=>{i.onOcppClientDisconnected(h,C?.code??1e3,C?.reason?C.reason.toString():"");}),b&&h.on("error",C=>{i.onOcppClientError(h,C);});}),this.metadataScanner.scanFromPrototype(i,Object.getPrototypeOf(i),h=>{let C=i[h];if(typeof C!="function")return;Reflect.hasMetadata(ce,C)&&(l.use(w=>this.executeWithParams(i,C,w)),this.logger.log(`Mapped Connection Middleware: ${r.name}.${h}`)),Reflect.hasMetadata(pe,C)&&(l.auth(w=>this.executeWithParams(i,C,w)),this.logger.log(`Mapped Auth Handler: ${r.name}.${h}`));let V=Reflect.getMetadata(se,C);if(V){let{action:w,protocol:_}=V,re=ae=>this.executeWithParams(i,C,ae);_?(l.handle(_,w,re),this.logger.log(`Mapped RPC Event: ${w} (${_}) -> ${r.name}.${h}`)):(l.handle(w,re),this.logger.log(`Mapped RPC Event: ${w} -> ${r.name}.${h}`));}Reflect.hasMetadata(de,C)&&(l.handle((w,_)=>this.executeWithParams(i,C,{..._,method:_?.method??w})),this.logger.log(`Mapped Wildcard Event -> ${r.name}.${h}`));});});}async executeWithParams(e,t,n){let i=Reflect.getMetadata(ee,e.constructor,t.name)||{},r=Math.max(-1,...Object.keys(i).map(Number)),a=new Array(r+1).fill(void 0);if(Object.keys(i).length===0)a[0]=n;else for(let[s,p]of Object.entries(i)){let d=Number(s),l=this.normalizeParamMetadata(p),c=n.handshake??n.client?.handshake;switch(l.type){case 0:a[d]=n.client;break;case 1:a[d]=n.message||{messageId:n.messageId,method:n.method,protocol:n.protocol,params:n.params};break;case 2:a[d]=n.params??n.payload;break;case 3:a[d]=n;break;case 4:a[d]=n.client?.identity??c?.identity;break;case 5:a[d]=c?.pathname;break;case 6:a[d]=n.client?.session??n.state;break;case 7:a[d]=l.data?c?.params?.[l.data]:c?.params;break;case 8:a[d]=n.protocol??n.client?.protocol??c?.protocols;break;case 9:a[d]=n.messageId;break;case 10:a[d]=c;break}}return t.apply(e,a)}normalizeParamMetadata(e){return typeof e=="number"?{type:e}:e}};exports.OcppExplorer=k([common.Injectable()],exports.OcppExplorer);exports.OcppMiddleware=class he{constructor(e){this.ocppService=e;}ocppService;use(e,t,n){e.ocppServer=this.ocppService.server,e.ocpp=this.ocppService,n();}};exports.OcppMiddleware=k([common.Injectable()],exports.OcppMiddleware);var fe=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(),s=(r-a)/r*100,p=i>this._cpuThreshold,d=s>this._memThreshold,l=this._multiplier;p||d?(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!==l&&this.emit("adapted",{multiplier:this._multiplier,cpuPercent:Math.round(i*100)/100,memPercent:Math.round(s*100)/100});}on(e,t){return super.on(e,t)}emit(e,t){return super.emit(e,t)}};function Qe(o){return o.split(".").reduce((e,t)=>(e<<8)+parseInt(t,10),0)>>>0}function Ze(o,e){let t=o;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 s=parseInt(a,10);if(net.isIPv4(t)&&net.isIPv4(r)){let p=Qe(t),d=Qe(r),l=s===0?0:-1<<32-s>>>0;if((p&l)===(d&l))return true}}}return false}function Ue(o,e){if(e.allowedIPs&&e.allowedIPs.length>0){let t=o.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=o.socket instanceof tls.TLSSocket?"wss":"ws",n=o.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=o.headers.origin;if(typeof t=="string"&&!e.allowedOrigins.includes(t))return {allowed:false,reason:"Origin not allowed"}}return {allowed:true}}function At(o){return o.showMetadata===false||o.showSourceMeta===false||o.prettifySource===true||o.prettifyMetadata===true}function $t(o){let e=o.showMetadata??true,t=o.showSourceMeta??true,n=o.prettifySource??false,i=o.prettifyMetadata??false,r="\x1B[2;37m",a="\x1B[0m",s="\x1B[36m";return (p,d)=>{if(!t)p.context=void 0;else if(n&&p.context){let c=[];p.context.component&&c.push(String(p.context.component)),p.context.identity&&c.push(String(p.context.identity)),c.length>0&&(p.message=`${r}[${c.join("/")}]${a} ${p.message}`,p.context=void 0);}let l=p.meta;if(!e)p.meta={};else if(i&&l&&Object.keys(l).length>0){let c=Object.entries(l).filter(([,u])=>u!=null).map(([u,g])=>{let b=typeof g=="object"?JSON.stringify(g):String(g);return typeof g=="string"?b=`${r}${b}${a}`:b=`${r}${b}${a}`,`${s}${u}${a}=${b}`}).join(" ");c&&(p.message=`${p.message} ${c}`),p.meta={};}d(p);}}function ge(o,e){if(o===false||o?.enabled===false)return null;if(o?.logger)return e&&o.logger.child?o.logger.child(e):o.logger;let t=o?.level??"INFO",i=o?.prettify??false?[voltlogIo.prettyTransport({level:t})]:[voltlogIo.consoleTransport({level:t})];if(o?.handler){let s=o.handler;i.push({name:"customHandler",write:p=>s(p)});}let r=[];o&&At(o)&&r.push($t(o));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 ye=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}};var G=class{children=new Map;paramChild=null;paramName="";wildcardChild=null;routers=[]};function et(o){return o.replace(/\/+/g,"/").replace(/^\/|\/$/g,"").split("/").filter(Boolean)}var Te=class{root=new G;_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 G),i=i.wildcardChild;break}else if(r.startsWith(":")){let a=r.slice(1);if(!i.paramChild)i.paramChild=new G,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(),s=i.children.get(a);s||(s=new G,i.children.set(a,s)),i=s;}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],s=a.toLowerCase(),p=e.children.get(s);if(p&&this._matchRecursive(p,t,n+1,i,r),e.paramChild){let d={...i};d[e.paramChild.paramName]=decodeURIComponent(a),this._matchRecursive(e.paramChild,t,n+1,d,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}};async function tt(o,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=o[i];i!==o.length&&a&&(e.next=n.bind(null,i+1),await a(e));};await n(0);}var J=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,s=r[a];return s&&typeof s=="object"&&Object.defineProperty(s,"client",{value:t,enumerable:true,configurable:true}),n(...r)}),t.handle(...i);}),this}};var te=class extends Error{constructor(e="Operation timed out"){super(e),this.name="TimeoutError";}},ve=class extends Error{statusCode;headers;constructor(e,t,n={}){super(e),this.name="UnexpectedHttpResponse",this.statusCode=t,this.headers=n;}};var I=class extends Error{rpcErrorCode="GenericError";rpcErrorMessage="";details;constructor(e,t={}){super(e),this.name="RPCGenericError",this.details=t;}},K=class extends I{rpcErrorCode="NotImplemented";rpcErrorMessage="Requested method is not known";constructor(e,t={}){super(e,t),this.name="RPCNotImplementedError";}},Ce=class extends I{rpcErrorCode="NotSupported";rpcErrorMessage="Requested method is recognised but not supported";constructor(e,t={}){super(e,t),this.name="RPCNotSupportedError";}},be=class extends I{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";}},Pe=class extends I{rpcErrorCode="ProtocolError";rpcErrorMessage="Payload for action is incomplete";constructor(e,t={}){super(e,t),this.name="RPCProtocolError";}},Se=class extends I{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";}},Ie=class extends I{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";}},Ee=class extends I{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";}},De=class extends I{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";}},xe=class extends I{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";}},we=class extends I{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";}},M=class extends I{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";}},_e=class extends I{rpcErrorCode="RpcFrameworkError";rpcErrorMessage="Content of the call is not a valid RPC request";constructor(e,t={}){super(e,t),this.name="RPCFrameworkError";}};function it(o,e,t={}){let n=typeof t=="object"?t:{},{exchangeLog:i=false,prettify:r=false}=n;return async(a,s)=>{let p=Date.now(),d=a.method,l=i?"info":"debug";switch(a.type){case "incoming_call":i&&r?o[l]?.(`\u26A1 ${e} \u2190 ${d} [IN]`,{messageId:a.messageId,method:a.method,protocol:a.protocol,payload:a.params,direction:"IN"}):o[l]?.("CALL \u2190",{messageId:a.messageId,method:a.method,protocol:a.protocol,payload:a.params,direction:"IN"});break;case "outgoing_call":i&&r?o[l]?.(`\u26A1 ${e} \u2192 ${d} [OUT]`,{method:a.method,params:a.params,direction:"OUT"}):o[l]?.("CALL \u2192",{method:a.method,params:a.params,direction:"OUT"});break}try{let c=await s(),u=Date.now()-p;switch(a.type){case "incoming_call":c!=null&&(i&&r?o[l]?.(`\u2705 ${e} \u2192 ${d} [RES]`,{messageId:a.messageId,method:a.method,durationMs:u,params:c,direction:"OUT"}):o[l]?.("CALLRESULT \u2192",{messageId:a.messageId,method:a.method,durationMs:u,params:c,direction:"OUT"}));break;case "outgoing_call":i&&r?o[l]?.(`\u2705 ${e} \u2190 ${d} [RES]`,{messageId:a.messageId,method:a.method,durationMs:u,payload:c,direction:"IN"}):o[l]?.("CALLRESULT \u2190",{messageId:a.messageId,method:a.method,durationMs:u,payload:c,direction:"IN"});break}return c}catch(c){let u=c.message,g=Date.now()-p;throw a.type==="incoming_call"?i&&r?o.error?.(`\u{1F6A8} ${e} \u2192 ${d} [ERR]`,{messageId:a.messageId,method:a.method,durationMs:g,error:u,direction:"OUT"}):o.error?.("CALLERROR \u2192",{messageId:a.messageId,method:a.method,durationMs:g,error:u,direction:"OUT"}):a.type==="outgoing_call"&&(i&&r?o.warn?.(`\u{1F6A8} ${e} \u2190 ${d} [ERR]`,{messageId:a.messageId,method:a.method,durationMs:g,error:u,direction:"IN"}):o.warn?.("CALLERROR \u2190",{messageId:a.messageId,method:a.method,durationMs:g,error:u,direction:"IN"})),c}}}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 Ae=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 nt=[{$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 rt=[{$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 common=require('@nestjs/common'),core=require('@nestjs/core'),events=require('events'),Qt=require('http'),https=require('https'),ie=require('ws'),os=require('os'),tls=require('tls'),net=require('net'),voltlogIo=require('voltlog-io'),zt=require('ajv'),Bt=require('ajv-formats'),crypto=require('crypto'),path=require('path'),worker_threads=require('worker_threads');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var Qt__default=/*#__PURE__*/_interopDefault(Qt);var ie__default=/*#__PURE__*/_interopDefault(ie);var zt__default=/*#__PURE__*/_interopDefault(zt);var Bt__default=/*#__PURE__*/_interopDefault(Bt);var k=(s,e,t,n)=>{for(var i=e,r=s.length-1,a;r>=0;r--)(a=s[r])&&(i=(a(i))||i);return i},B=(s,e)=>(t,n)=>e(t,n,s);var Z="ocpp:gateway",se="ocpp:message_event",de="ocpp:wildcard_event",pe="ocpp:auth",ce="ocpp:connection_middleware",le="ocpp:rpc_middleware",ue="ocpp:cors",ee="ocpp:params_args",F="OCPP_SERVER_OPTIONS",q="OCPP_SERVER_INSTANCE";var Pi=s=>common.SetMetadata(Z,typeof s=="string"?{path:s}:s||{}),Si=s=>common.SetMetadata(ue,s),Ii=(...s)=>common.SetMetadata(le,s);var _i=(s,e)=>common.SetMetadata(se,{action:s,protocol:e}),Li=()=>common.SetMetadata(de,true),Ai=()=>common.SetMetadata(pe,true),$i=()=>common.SetMetadata(ce,true);var Fe=(l=>(l[l.CLIENT=0]="CLIENT",l[l.MESSAGE=1]="MESSAGE",l[l.PARAMS=2]="PARAMS",l[l.CONTEXT=3]="CONTEXT",l[l.IDENTITY=4]="IDENTITY",l[l.PATH=5]="PATH",l[l.SESSION=6]="SESSION",l[l.PATH_PARAMS=7]="PATH_PARAMS",l[l.PROTOCOL=8]="PROTOCOL",l[l.MESSAGE_ID=9]="MESSAGE_ID",l[l.HANDSHAKE=10]="HANDSHAKE",l))(Fe||{});function j(s,e){return ()=>(t,n,i)=>{let r=Reflect.getMetadata(ee,t.constructor,n)||{},a={type:s,data:e};Reflect.defineMetadata(ee,{...r,[i]:a},t.constructor,n);}}var Ni=j(0),ki=j(1),Fi=j(2),Ui=j(3),Wi=j(4),Hi=j(5),zi=j(6),Bi=s=>j(7,s)(),Gi=j(8),Ji=j(9),Ki=j(10);exports.OcppExplorer=class O{constructor(e,t,n,i){this.discoveryService=e;this.metadataScanner=t;this.server=n;this.service=i;}discoveryService;metadataScanner;server;service;logger=new common.Logger(exports.OcppExplorer.name);onModuleInit(){this.explore();}explore(){this.discoveryService.getProviders().filter(n=>n.metatype&&Reflect.hasMetadata(Z,n.metatype)).forEach(n=>{let{instance:i,metatype:r}=n;if(!i||!r)return;let a=Reflect.getMetadata(Z,r),o=Reflect.getMetadata(ue,r),d=Reflect.getMetadata(le,r),p=a?.path;this.service?.registerUpgradePath(p);let c=p?this.server.route(p):this.server.route();o&&c.cors(o);let l={...a};delete l.path,Object.keys(l).length>0&&c.config(l);let u=typeof i.onOcppClientConnected=="function",g=typeof i.onOcppClientDisconnected=="function",b=typeof i.onOcppClientError=="function";(u||g||b||d?.length)&&c.on("client",m=>{if(d?.length)for(let C of d)m.use(C);u&&i.onOcppClientConnected(m),g&&m.on("close",C=>{i.onOcppClientDisconnected(m,C?.code??1e3,C?.reason?C.reason.toString():"");}),b&&m.on("error",C=>{i.onOcppClientError(m,C);});}),this.metadataScanner.scanFromPrototype(i,Object.getPrototypeOf(i),m=>{let C=i[m];if(typeof C!="function")return;Reflect.hasMetadata(ce,C)&&(c.use(w=>this.executeWithParams(i,C,m,w)),this.logger.log(`Mapped Connection Middleware: ${r.name}.${m}`)),Reflect.hasMetadata(pe,C)&&(c.auth(w=>this.executeWithParams(i,C,m,w)),this.logger.log(`Mapped Auth Handler: ${r.name}.${m}`));let V=Reflect.getMetadata(se,C);if(V){let{action:w,protocol:_}=V,re=ae=>this.executeWithParams(i,C,m,ae);_?(c.handle(_,w,re),this.logger.log(`Mapped RPC Event: ${w} (${_}) -> ${r.name}.${m}`)):(c.handle(w,re),this.logger.log(`Mapped RPC Event: ${w} -> ${r.name}.${m}`));}Reflect.hasMetadata(de,C)&&(c.handle((w,_)=>this.executeWithParams(i,C,m,{..._,method:_?.method??w})),this.logger.log(`Mapped Wildcard Event -> ${r.name}.${m}`));});});}async executeWithParams(e,t,n,i){let r=Reflect.getMetadata(ee,e.constructor,n)||{},a=Math.max(-1,...Object.keys(r).map(Number)),o=new Array(a+1).fill(void 0);if(Object.keys(r).length===0)o[0]=i;else for(let[d,p]of Object.entries(r)){let c=Number(d),l=this.normalizeParamMetadata(p),u=i.handshake??i.client?.handshake;switch(l.type){case 0:o[c]=i.client;break;case 1:o[c]=i.message||{messageId:i.messageId,method:i.method,protocol:i.protocol,params:i.params};break;case 2:o[c]=i.params??i.payload;break;case 3:o[c]=i;break;case 4:o[c]=i.client?.identity??u?.identity;break;case 5:o[c]=u?.pathname;break;case 6:o[c]=i.client?.session??i.state;break;case 7:o[c]=l.data?u?.params?.[l.data]:u?.params;break;case 8:o[c]=i.protocol??i.client?.protocol??u?.protocols;break;case 9:o[c]=i.messageId;break;case 10:o[c]=u;break}}return t.apply(e,o)}normalizeParamMetadata(e){return typeof e=="number"?{type:e}:e}};exports.OcppExplorer=k([common.Injectable()],exports.OcppExplorer);exports.OcppMiddleware=class he{constructor(e){this.ocppService=e;}ocppService;use(e,t,n){e.ocppServer=this.ocppService.server,e.ocpp=this.ocppService,n();}};exports.OcppMiddleware=k([common.Injectable()],exports.OcppMiddleware);var fe=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)}};function Qe(s){return s.split(".").reduce((e,t)=>(e<<8)+parseInt(t,10),0)>>>0}var _t=(1n<<128n)-1n;function Ze(s){s=s.split("%")[0];let e=s.match(/^(.*:)(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/);if(e){let a=[e[2],e[3],e[4],e[5]].map(p=>parseInt(p,10));if(a.some(p=>p>255))return null;let o=(a[0]<<8|a[1]).toString(16),d=(a[2]<<8|a[3]).toString(16);s=`${e[1]}${o}:${d}`;}let t=s.split("::");if(t.length>2)return null;let n=t[0]?t[0].split(":"):[],i;if(t.length===2){let a=t[1]?t[1].split(":"):[],o=8-n.length-a.length;if(o<0)return null;i=[...n,...Array(o).fill("0"),...a];}else i=n;if(i.length!==8)return null;let r=0n;for(let a of i){if(!/^[0-9a-fA-F]{1,4}$/.test(a))return null;r=r<<16n|BigInt(parseInt(a,16));}return r}function et(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)){if(o<0||o>32)continue;let d=Qe(t),p=Qe(r),c=o===0?0:-1<<32-o>>>0;if((d&c)===(p&c))return true}else if(net.isIPv6(t)&&net.isIPv6(r)){if(o<0||o>128)continue;let d=Ze(t),p=Ze(r);if(d===null||p===null)continue;let c=o===0?0n:~0n<<BigInt(128-o)&_t;if((d&c)===(p&c))return true}}}return false}function Ue(s,e){if(e.allowedIPs&&e.allowedIPs.length>0){let t=s.socket.remoteAddress;if(!t||!et(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}}function Rt(s){return s.showMetadata===false||s.showSourceMeta===false||s.prettifySource===true||s.prettifyMetadata===true}function qt(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,g])=>{let b=typeof g=="object"?JSON.stringify(g):String(g);return typeof g=="string"?b=`${r}${b}${a}`:b=`${r}${b}${a}`,`${o}${u}${a}=${b}`}).join(" ");l&&(d.message=`${d.message} ${l}`),d.meta={};}p(d);}}function ge(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&&Rt(s)&&r.push(qt(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 ye=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}};var G=class{children=new Map;paramChild=null;paramName="";wildcardChild=null;routers=[]};function tt(s){return s.replace(/\/+/g,"/").replace(/^\/|\/$/g,"").split("/").filter(Boolean)}var Te=class{root=new G;_frozen=false;_size=0;get size(){return this._size}insert(e,t){this._frozen&&(this._frozen=false);let n=tt(e),i=this.root;for(let r of n)if(r==="*"){i.wildcardChild||(i.wildcardChild=new G),i=i.wildcardChild;break}else if(r.startsWith(":")){let a=r.slice(1);if(!i.paramChild)i.paramChild=new G,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 G,i.children.set(a,o)),i=o;}i.routers.push(t),this._size++;}match(e){let t=tt(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}};async function it(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 J=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}};var te=class extends Error{constructor(e="Operation timed out"){super(e),this.name="TimeoutError";}},ve=class extends Error{statusCode;headers;constructor(e,t,n={}){super(e),this.name="UnexpectedHttpResponse",this.statusCode=t,this.headers=n;}};var I=class extends Error{rpcErrorCode="GenericError";rpcErrorMessage="";details;constructor(e,t={}){super(e),this.name="RPCGenericError",this.details=t;}},K=class extends I{rpcErrorCode="NotImplemented";rpcErrorMessage="Requested method is not known";constructor(e,t={}){super(e,t),this.name="RPCNotImplementedError";}},Ce=class extends I{rpcErrorCode="NotSupported";rpcErrorMessage="Requested method is recognised but not supported";constructor(e,t={}){super(e,t),this.name="RPCNotSupportedError";}},be=class extends I{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";}},Pe=class extends I{rpcErrorCode="ProtocolError";rpcErrorMessage="Payload for action is incomplete";constructor(e,t={}){super(e,t),this.name="RPCProtocolError";}},Se=class extends I{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";}},Ie=class extends I{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";}},Ee=class extends I{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";}},De=class extends I{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";}},xe=class extends I{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";}},we=class extends I{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";}},M=class extends I{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";}},_e=class extends I{rpcErrorCode="RpcFrameworkError";rpcErrorMessage="Content of the call is not a valid RPC request";constructor(e,t={}){super(e,t),this.name="RPCFrameworkError";}};function nt(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,g=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:g,error:u,direction:"OUT"}):s.error?.("CALLERROR \u2192",{messageId:a.messageId,method:a.method,durationMs:g,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:g,error:u,direction:"IN"}):s.warn?.("CALLERROR \u2190",{messageId:a.messageId,method:a.method,durationMs:g,error:u,direction:"IN"})),l}}}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 Ae=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 rt=[{$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 at=[{$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
|
|
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 ot=[{$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 $e(){return crypto.randomUUID()}function X(
|
|
4821
|
-
`);
|
|
4822
|
-
${
|
|
4820
|
+
`,type:"integer",minimum:0},status:{$ref:"#/definitions/GenericStatusEnumType"},customData:{$ref:"#/definitions/CustomDataType"}},required:["vatNumber","status"]}];function $e(){return crypto.randomUUID()}function X(s,e,t={}){switch(s){case "GenericError":return new I(e,t);case "RpcFrameworkError":return new _e(e,t);case "MessageTypeNotSupported":return new M(e,t);case "NotImplemented":return new K(e,t);case "NotSupported":return new Ce(e,t);case "InternalError":return new be(e,t);case "ProtocolError":return new Pe(e,t);case "SecurityError":return new Se(e,t);case "FormatViolation":return new Ee(e,t);case "FormationViolation":return new Ie(e,t);case "PropertyConstraintViolation":return new De(e,t);case "OccurrenceConstraintViolation":return new xe(e,t);case "TypeConstraintViolation":return new we(e,t);default:return new I(e,t)}}var Ut=["name","message","stack","code","rpcErrorCode","rpcErrorMessage","details"];function st(s){let e={};for(let t of Ut){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 Wt="ocpp-ws-io",Ht="1.0.1";function dt(){return `${Wt}/${Ht}`}var W={debug:()=>{},info:()=>{},warn:()=>{},error:()=>{},child:()=>W};var Gt=new Set(["type"]),Jt=new Set(["maximum","minimum","maxLength","minLength","pattern","format","anyOf","oneOf","not","if"]),Kt=new Set(["required","maxItems","minItems","maxProperties","minProperties","additionalProperties","additionalItems","exclusiveMaximum","exclusiveMinimum","multipleOf"]),Xt=new Set(["enum","const"]);function Yt(s){return Gt.has(s)?"TypeConstraintViolation":Kt.has(s)?"OccurrenceConstraintViolation":Xt.has(s)?"PropertyConstraintViolation":(Jt.has(s),"FormatViolation")}var We=class{subprotocol;_ajv;constructor(e,t){this.subprotocol=e,this._ajv=new zt__default.default({allErrors:true,strict:false,multipleOfPrecision:4}),Bt__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=Yt(a.keyword),d=this._ajv.errorsText(i.errors);throw X(o,d)}}hasSchema(e){return !!this._ajv.getSchema(this._normalizeSchemaId(e))}},pt=new Map;function je(s,e){let t=pt.get(s);if(t)return t;let n=new We(s,e);return pt.set(s,n),n}var Re=null;function ct(){return Re||(Re=[je("ocpp1.6",rt),je("ocpp2.0.1",at),je("ocpp2.1",ot)],Re)}var qe={CONNECTING:0,OPEN:1,CLOSING:2,CLOSED:3};var x={CALL:2,CALLRESULT:3,CALLERROR:4},lt=Symbol("NOREPLY");function ut(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 mt(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&&ut(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||!ut(s.charCodeAt(r)))throw new SyntaxError("Unexpected end of input")}if(e.size===0)throw new SyntaxError("Unexpected end of input");return e}var Zt=new Set([1004,1005,1006]);function ht(s){return s>=1e3&&s<=1014&&!Zt.has(s)||s>=3e3&&s<=4999}var ei=/^ *[Bb][Aa][Ss][Ii][Cc] +([A-Za-z0-9._~+/-]+=*) *$/;function ft(s,e){if(!s)return;let t=ei.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
|
+
${d}\r
|
|
4823
4823
|
\r
|
|
4824
|
-
${r}`);}var{CONNECTING:Y,OPEN:H,CLOSING:He,CLOSED:A}=qe,Oe=class o extends events.EventEmitter{static CONNECTING=Y;static OPEN=H;static CLOSING=He;static CLOSED=A;_options;_state=A;_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=W;_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 Ae(this._options.callConcurrency),this._middleware=new Le;let t=this._options.logging,n=ge(t,{component:"OCPPClient",identity:this._identity});this._logger=n||W,t&&typeof t=="object"&&(this._exchangeLog=t.exchangeLog??false,this._prettify=t.prettify??false),this._options.logging&&this.use(it(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 s=t==="CALLERROR"?"\u{1F6A8}":t==="CALLRESULT"?"\u2705":"\u26A1",p=n??t,d=`${s} ${this._identity} ${r} ${p} [${e}]`;this._logger?.[a]?.(d,{...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||W}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!==A)throw new Error(`Cannot connect: client is in state ${this._state}`);return this._state=Y,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 ie__default.default(n,this._options.protocols??[],i);this._ws=r;let a=()=>{if(d(),this._state=H,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 g of u)this._ws?.send(g);}this._logger?.info?.("Connected",{protocol:r.protocol});let c={response:r._req?.res};this.emit("open",c),e(c);},s=l=>{d(),this._state=A,this._logger?.error?.("Connection error",{error:l.message}),this.emit("error",l),t(l);},p=(l,c)=>{d(),this._state=A;let u=new ve(`Unexpected HTTP response: ${c.statusCode}`,c.statusCode??0,c.headers);this._logger?.error?.("Unexpected HTTP response",{statusCode:c.statusCode}),this.emit("error",u),t(u);},d=()=>{r.removeListener("open",a),r.removeListener("error",s),r.removeListener("unexpected-response",p);};r.on("open",a),r.on("error",s),r.on("unexpected-response",p);})}async close(e={}){let{code:t=1e3,reason:n="",awaitPending:i=true,force:r=false}=e;return this._closePromise?this._closePromise:this._state===A?{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=He,this._stopPing(),!i&&n){let r=Array.from(this._pendingCalls.values()).map(a=>new Promise(s=>{let p=a.resolve,d=a.reject;a.resolve=l=>{p(l),s();},a.reject=l=>{d(l),s();};}));r.length>0&&await Promise.allSettled(r);}return new Promise(r=>{if(!this._ws||this._ws.readyState===ie__default.default.CLOSED){this._state=A,this._cleanup();let s={code:e,reason:t};this.emit("close",s),r(s);return}let a=(s,p)=>{this._ws?.removeListener("close",a),this._state=A,this._cleanup();let d={code:s,reason:p.toString()};this.emit("close",d),r(d);};this._ws.on("close",a),i?this._ws.terminate():this._ws.close(mt(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!==H){if(this._options.offlineQueue&&(this._state===A||this._state===Y))return new Promise((a,s)=>{let p=this._options.offlineQueueMaxSize??100;this._offlineQueue.length>=p&&(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:s}),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??$e(),r=n.timeoutMs??this._options.callTimeoutMs,a={type:"outgoing_call",messageId:i,method:e,params:t,options:n},s;return await this._middleware.execute(a,async p=>{let d=p;this._options.strictMode&&this._protocol&&this._validateOutbound(d.method,d.params,"req");let l=[x.CALL,i,d.method,d.params],c=this._invokeBeforeSend(l);if(c instanceof Promise){if(await c===false)return}else if(c===false)return;let u=JSON.stringify(l);return s=await new Promise((g,b)=>{let h=setTimeout(()=>{this._pendingCalls.delete(i),b(new te(`Call to "${d.method}" timed out after ${r}ms`));},r),C=()=>{clearTimeout(h),this._pendingCalls.delete(i),b(new Error("Aborted"));};n.signal&&n.signal.addEventListener("abort",C),this._pendingCalls.set(i,{resolve:g,reject:b,timeoutHandle:h,abortHandler:n.signal?()=>n.signal?.removeEventListener("abort",C):void 0,method:d.method,sentAt:Date.now()}),this._ws?.readyState===ie__default.default.OPEN?this._safeSend(this._ws,u,V=>{V?(clearTimeout(h),this._pendingCalls.delete(i),b(V)):this._emitMessageEvent(l,"OUT",{type:"outgoing_call",messageId:i,method:d.method,params:d.params,options:n});}):this._state===Y?(this._logger?.debug?.("Buffering call",{method:d.method}),this._outboundBuffer.push(u)):(clearTimeout(h),this._pendingCalls.delete(i),b(new Error(`WebSocket is not open (state: ${this._state})`)));}),s}),s}sendRaw(e){if(this._state===H&&this._ws)this._ws.send(e);else if(this._state===Y)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===H&&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(p){this._onBadMessage(typeof e=="string"?e:e.toString(),p);return}let i=n[0],r=n[1];if(typeof r!="string"){this._onBadMessage(typeof e=="string"?e:e.toString(),new M(`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 M(`Missing payload elements for message type ${i}`));return}let a=i===x.CALLERROR?4:i===x.CALL?3:2,s=n[a];if(typeof s!="object"||s===null||Array.isArray(s)){this._onBadMessage(JSON.stringify(n),new M(`Payload must be a JSON object, got ${s===null?"null":Array.isArray(s)?"array":typeof s}`));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 M(`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 s=a,p=[x.CALL,s.messageId,s.method,s.params];if(this._emitMessageEvent(p,"IN",s),this.emit("call",p),this._state===H)try{if(this._pendingResponses.has(s.messageId))throw X("RpcFrameworkError",`Already processing call with ID: ${s.messageId}`);let d=(this._protocol?this._handlers.get(`${this._protocol}:${s.method}`):void 0)??this._handlers.get(s.method);if(!d&&!this._wildcardHandler)throw new K(`Method "${s.method}" not implemented`);this._options.strictMode&&this._protocol&&this._validateInbound(s.method,s.params,"req"),this._pendingResponses.add(s.messageId);let l=new AbortController,c={messageId:s.messageId,method:s.method,protocol:this._protocol,params:s.params,signal:l.signal},u;if(d?u=await d(c):this._wildcardHandler&&(u=await this._wildcardHandler(s.method,c)),this._pendingResponses.delete(s.messageId),u===ct)return;this._options.strictMode&&this._protocol&&this._validateOutbound(s.method,u,"conf");let g=[x.CALLRESULT,s.messageId,u],b=this._invokeBeforeSend(g);if(b instanceof Promise){if(await b===!1)return u}else if(b===!1)return u;return this._ws?.send(JSON.stringify(g)),this._emitMessageEvent(g,"OUT",{type:"outgoing_result",messageId:s.messageId,method:s.method,payload:u}),this.emit("callResult",g),u}catch(d){this._pendingResponses.delete(s.messageId);let l=d instanceof I||d.rpcErrorCode?d:X("InternalError",d.message),c=this._options.respondWithDetailedErrors?ot(d):{},u=[x.CALLERROR,s.messageId,l.rpcErrorCode,l.rpcErrorMessage||d.message||"",c],g=this._invokeBeforeSend(u);if(g instanceof Promise){if(await g===!1)throw d}else if(g===!1)throw d;throw this._ws?.send(JSON.stringify(u)),this._emitMessageEvent(u,"OUT",{type:"outgoing_error",messageId:s.messageId,method:s.method,errorCode:l.rpcErrorCode,errorDescription:l.rpcErrorMessage||d.message||""}),this.emit("callError",u),this.emit("handlerError",{method:s.method,error:d}),d}});}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 s=a,p=this._pendingCalls.get(s.messageId);if(!p)return;let d=Date.now()-p.sentAt;this._emitMessageEvent(e,"IN",s,d),this.emit("callResult",e),clearTimeout(p.timeoutHandle),p.abortHandler,this._pendingCalls.delete(s.messageId),p.resolve(s.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,s=this._pendingCalls.get(a.messageId);if(!s)return;let p=Date.now()-s.sentAt;this._emitMessageEvent(e,"IN",a,p),this.emit("callError",e);let[,,d,l,c]=a.error;clearTimeout(s.timeoutHandle),this._pendingCalls.delete(a.messageId);let u=X(d,l,c);s.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!==He?(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=A,this.emit("close",{code:e,reason:n}))):this._state=A;}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=Y;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(o._INTOLERABLE_ERRORS.has(r)){this._logger?.error?.("Intolerable error \u2014 stopping reconnection",{error:r}),this._state=A,this.emit("close",{code:1001,reason:r});return}this._reconnectAttempt<this._options.maxReconnects&&this._options.reconnect?this._scheduleReconnect():(this._state=A,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 s=0;s<=i;s++)try{return await this._callQueue.push(()=>this._sendCall(e,t,n))}catch(p){if(s===i||!(p instanceof te))throw p;let d=Math.min(a,r*2**s),l=Math.random()*d;this._logger?.warn?.("Call retry",{method:e,attempt:s+1,maxRetries:i,delayMs:Math.round(l)}),await new Promise(c=>setTimeout(c,l));}throw new Error("Retry exhausted")}static _BACKPRESSURE_THRESHOLD=512*1024;_invokeBeforeSend(e){return true}_safeSend(e,t,n){if(!e||e.readyState!==ie__default.default.OPEN){n?.(new Error("WebSocket is not open"));return}if(e.bufferedAmount>o._BACKPRESSURE_THRESHOLD){this._logger?.warn?.("Backpressure \u2014 pausing send",{identity:this._identity,bufferedAmount:e.bufferedAmount,threshold:o._BACKPRESSURE_THRESHOLD}),this.emit("backpressure",{identity:this._identity,bufferedAmount:e.bufferedAmount});let i=0,r=setInterval(()=>{if(i+=50,!e||e.readyState!==ie__default.default.OPEN){clearInterval(r),n?.(new Error("WebSocket closed during backpressure wait"));return}(e.bufferedAmount<=o._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!==H||!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=pt(),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":st()}},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 Me=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=qe.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,s)=>{let p=this._rateLimits[r];if(!p)p={tokens:a,lastRefill:n},this._rateLimits[r]=p;else {let d=n-p.lastRefill,l=this._adaptiveMultiplier?.()??1,c=a/s*l,u=d*c;u>0&&(p.tokens=Math.min(a,p.tokens+u),p.lastRefill=n);}return p.tokens>=1?(p.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 ze=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 s=this._pending.get(a.id);s&&(this._pending.delete(a.id),a.error?s.reject(new Error(a.error)):s.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 ft(o={}){try{return new ze(o)}catch{return null}}var ne=class extends events.EventEmitter{_options;_trie=new Te;_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=$e();_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 ye(t),this._wss=new ie.WebSocketServer({noServer:true,maxPayload:this._options.maxPayloadBytes??65536,perMessageDeflate:this._buildCompressionConfig()}),this._gcInterval=setInterval(()=>{let r=Date.now();for(let[a,s]of this._sessions.entries())r-s.lastActive>this._sessionTimeoutMs&&this._sessions.delete(a);},60*1e3).unref(),this._logger=ge(this._options.logging,{component:"OCPPServer"});let n=this._options.rateLimit;n?.adaptive&&(this._adaptiveLimiter=new fe({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=ft(r),this._workerPool&&this._logger?.info?.("Worker thread pool initialized",{poolSize:this._workerPool.size});}}get log(){return this._logger||W}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 J;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 J;return t.use(...e),this._registerRouter(t),t}auth(e){let t=new J;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 s=this._options.tls??{},p={};s.cert&&(p.cert=s.cert),s.key&&(p.key=s.key),s.ca&&(p.ca=s.ca),s.passphrase&&(p.passphrase=s.passphrase),a===3&&(p.requestCert=true,p.rejectUnauthorized=s.rejectUnauthorized??true),i=https.createServer(p);}else i=Kt.createServer();}this._state==="CLOSED"&&(this._state="OPEN");let r=(a,s,p)=>{this._handleUpgrade(a,s,p).catch(d=>{s.destroyed||s.destroy(),this._logger?.error?.("Upgrade error",{error:d.message}),this.emit("upgradeError",{error:d,socket:s});});};if(i.on("upgrade",r),this._httpServers.add(i),this._options.healthEndpoint&&i.on("request",async(a,s)=>{let p=a.url??"";if(p==="/health"){let d=this.stats(),l=JSON.stringify({status:this._state==="OPEN"?"ok":"degraded",state:this._state,connectedClients:d.connectedClients,activeSessions:d.activeSessions,uptimeSeconds:Math.round(d.uptimeSeconds),pid:d.pid});s.writeHead(200,{"Content-Type":"application/json","Cache-Control":"no-cache"}),s.end(l);return}if(p==="/metrics"){let d=this.stats(),l=["# HELP ocpp_connected_clients Number of currently connected OCPP clients","# TYPE ocpp_connected_clients gauge",`ocpp_connected_clients ${d.connectedClients}`,"","# HELP ocpp_active_sessions Number of active in-memory sessions","# TYPE ocpp_active_sessions gauge",`ocpp_active_sessions ${d.activeSessions}`,"","# HELP ocpp_uptime_seconds Process uptime in seconds","# TYPE ocpp_uptime_seconds gauge",`ocpp_uptime_seconds ${Math.round(d.uptimeSeconds)}`,"","# HELP ocpp_memory_rss_bytes Resident set size in bytes","# TYPE ocpp_memory_rss_bytes gauge",`ocpp_memory_rss_bytes ${d.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 ${d.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 ${d.memoryUsage.heapTotal}`,"","# HELP ocpp_ws_buffered_bytes Total buffered WebSocket bytes","# TYPE ocpp_ws_buffered_bytes gauge",`ocpp_ws_buffered_bytes ${d.webSockets?.bufferedAmount??0}`,""];s.writeHead(200,{"Content-Type":"text/plain; version=0.0.4; charset=utf-8","Cache-Control":"no-cache"});for(let c of this._plugins)if(c.getCustomMetrics)try{let u=await c.getCustomMetrics();u?.length&&(l.push(""),l.push(...u));}catch(u){this._logger?.error?.("Plugin getCustomMetrics error",{name:c.name,error:u.message});}s.end(l.join(`
|
|
4825
|
-
`));return}s.writeHead(404,{"Content-Type":"text/plain"}),s.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,s)=>{i.on("error",s),i.listen(e,t,()=>{i.removeListener("error",s);let p=i.address();this._logger?.info?.("Server listening",{port:typeof p=="object"?p?.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",E=Date.now(),P=this._connectionBuckets.get(m);if(!P)P={tokens:i.limit,lastRefill:E},this._connectionBuckets.set(m,P);else {let f=E-P.lastRefill,D=i.limit/i.windowMs;P.tokens=Math.min(i.limit,P.tokens+f*D),P.lastRefill=E;}if(P.tokens<1){this._logger?.warn?.("Connection rate limit exceeded",{ip:m});let f={type:"CONNECTION_RATE_LIMIT",ip:m,timestamp:new Date().toISOString(),details:{tokensRemaining:P.tokens}};this.emit("securityEvent",f);for(let D of this._plugins)try{D.onSecurityEvent?.(f);}catch{}$(t,429,"Too Many Requests");return}P.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:E}=Ue(e,this._globalCORS);if(!m){this._logger?.warn?.("CORS rejected connection",{reason:E,ip:e.socket.remoteAddress}),$(t,403,"Forbidden");return}}let r=new URL(e.url??"/",`http://${e.headers.host??"localhost"}`),a,s=[],p=[],d={},l=r.pathname,c=false,u=this._trie.size>0||this._regexRouters.length>0,g;!this._trie.frozen&&this._trie.size>0&&this._trie.freeze();for(let m of this._globalMiddlewareRouters)p.push(m),m.middlewares.length>0&&s.push(...m.middlewares),m.authCallback&&!a&&(a=m.authCallback);let b=this._trie.match(l);if(b){Object.assign(d,b.params);for(let m of b.routers)p.push(m),c=true,m._routeConfig&&(g=Object.assign(g||{},m._routeConfig)),m.middlewares.length>0&&s.push(...m.middlewares),m.authCallback&&!a&&(a=m.authCallback);}for(let m of this._regexRouters)for(let E of m._regexPatterns){let P=E.regex.exec(l);if(P){if(p.push(m),c=true,P.groups)for(let[f,D]of Object.entries(P.groups))d[f]=decodeURIComponent(D??"");m._routeConfig&&(g=Object.assign(g||{},m._routeConfig)),m.middlewares.length>0&&s.push(...m.middlewares),m.authCallback&&!a&&(a=m.authCallback);break}}let h=d.identity;if(!h){let m=l.split("/").filter(Boolean);h=decodeURIComponent(m[m.length-1]??"");}if(!h){$(t,400,"Missing identity in URL path");return}for(let m of p)if(m._routeCORS){let{allowed:E,reason:P}=Ue(e,m._routeCORS);if(!E){this._logger?.warn?.("Route CORS rejected connection",{reason:P,ip:e.socket.remoteAddress}),$(t,403,"Forbidden");return}}"setKeepAlive"in t&&t.setKeepAlive(true);let C=new Set,V=e.headers["sec-websocket-protocol"];if(V)try{C=ut(V);}catch{$(t,400,"Invalid Sec-WebSocket-Protocol header");return}let w=g?.protocols??this._options.protocols??[],_;if(w.length>0){if(C.size===0){$(t,400,"Missing subprotocol");return}if(_=w.find(m=>C.has(m)),!_){$(t,400,"No matching subprotocol");return}}let re=ht(e.headers.authorization??"",h),ae,Je=this._options.securityProfile??0;Je===3&&"getPeerCertificate"in t&&(ae=t.getPeerCertificate());let Q={identity:h,remoteAddress:e.socket.remoteAddress??"",headers:e.headers,protocols:C,pathname:l,params:d,query:r.searchParams,request:e,password:re,clientCertificate:ae,securityProfile:Je},Ve,Ke;if(a||s.length>0){let m=new AbortController,E=()=>{m.abort(new Error("Socket closed during handshake"));};t.on("close",E),t.on("error",E),t.on("end",E);let P=this._options.handshakeTimeoutMs??3e4,f;P>0&&(f=setTimeout(()=>{m.abort(new Error("Handshake timeout"));},P));try{Ve={handshake:Q,state:{},reject:(T=401,S="Unauthorized")=>{throw {code:T,message:S,_isMiddlewareReject:!0}},next:async T=>{}};let D=[...s],y=!1;if(D.push(async T=>{y=!0,a?Ke=await new Promise((S,N)=>{let L=!1,oe=z=>{L||(L=!0,z?.protocol&&(_=z.protocol),S(z));},Ne=(z=401,Xe="Unauthorized")=>{throw L||(L=!0,N({code:z,message:Xe})),{code:z,message:Xe,_isMiddlewareReject:!0}};if(m.signal.aborted){N(m.signal.reason);return}m.signal.addEventListener("abort",()=>{L||(L=!0,N(m.signal.reason));},{once:!0}),this._logger?.debug?.("Executing auth callback",{identity:h,pathname:l});let yt={handshake:Q,state:T.state,reject:Ne,signal:m.signal,accept:oe};a(yt);}):_=Q.protocols.values().next().value??void 0;}),await tt(D,Ve),!y)throw {code:500,message:"Middleware chain halted unexpectedly without rejecting",_isMiddlewareReject:!0}}catch(D){if(m.signal.aborted){let L=D instanceof Error?D.message:"Unknown abort";this._logger?.warn?.("Handshake aborted",{identity:h,reason:L});let oe={type:"UPGRADE_ABORTED",identity:h,ip:e.socket.remoteAddress,timestamp:new Date().toISOString(),details:{reason:L}};this.emit("securityEvent",oe);for(let Ne of this._plugins)try{Ne.onSecurityEvent?.(oe);}catch{}this.emit("upgradeAborted",{identity:h,reason:L,socket:t,request:e}),t.destroyed||t.destroy();return}let y=D,T=typeof y?.code=="number"?y.code:401,S=typeof y?.message=="string"?y.message:"Unauthorized";this._logger?.warn?.("Auth rejected",{identity:h,code:T});let N={type:"AUTH_FAILED",identity:h,ip:e.socket.remoteAddress,timestamp:new Date().toISOString(),details:{code:T,message:S}};this.emit("securityEvent",N);for(let L of this._plugins){try{L.onSecurityEvent?.(N);}catch{}try{L.onAuthFailed?.(Q,T,S);}catch{}}$(t,T,S);return}finally{f&&clearTimeout(f),t.removeListener("close",E),t.removeListener("error",E),t.removeListener("end",E);}}else if(u&&!c){this._logger?.warn?.("Connection rejected: No matching route found",{pathname:l}),$(t,404,"Endpoint Not Found");return}if(t.readyState!=="open"){this._logger?.debug?.("Socket closed before upgrade completion",{identity:h}),t.destroyed||t.destroy();return}this._wss||(this._wss=new ie.WebSocketServer({noServer:true,maxPayload:this._options.maxPayloadBytes??65536})),this._wss.handleUpgrade(e,t,n,m=>{let E={identity:h,endpoint:"",callTimeoutMs:g?.callTimeoutMs??this._options.callTimeoutMs,pingIntervalMs:g?.pingIntervalMs??this._options.pingIntervalMs,deferPingsOnActivity:g?.deferPingsOnActivity??this._options.deferPingsOnActivity,callConcurrency:g?.callConcurrency??this._options.callConcurrency,maxBadMessages:this._options.maxBadMessages,respondWithDetailedErrors:this._options.respondWithDetailedErrors,strictMode:g?.strictMode??this._options.strictMode,strictModeMethods:g?.strictModeMethods??this._options.strictModeMethods,strictModeValidators:this._options.strictModeValidators,rateLimit:g?.rateLimit??this._options.rateLimit,reconnect:false,logging:this._options.logging},P={...Ve?.state||{},...this._sessions.get(h)?.data||{},...Ke?.session||{}},f=new Me(E,{ws:m,handshake:Q,session:P,protocol:_,adaptiveMultiplier:this._adaptiveLimiter?()=>this._adaptiveLimiter.multiplier:void 0,workerPool:this._workerPool??void 0,plugins:this._plugins});this._updateSessionActivity(h,f.session);let D=this._clientsByIdentity.get(h);if(D&&D!==f){this._logger?.warn?.("Evicting stale connection for identity",{identity:h,reason:"Duplicate identity replaced by new connection"});for(let y of this._plugins)try{y.onEviction?.(D,f);}catch{}D.close({code:4e3,reason:"Evicted by new connection",force:true}).catch(()=>{}),this._clients.delete(D);}this._clients.add(f),this._clientsByIdentity.set(h,f),this._adapter?.setPresence&&this._adapter.setPresence(h,this._nodeId,300).catch(y=>{this._logger?.error?.("Error setting presence",{identity:h,error:y});}),this._logger?.info?.("Client connected",{identity:h,remoteAddress:e.socket.remoteAddress,protocol:_}),f.on("close",({code:y,reason:T})=>{this._clients.delete(f),this._clientsByIdentity.get(h)===f&&this._clientsByIdentity.delete(h),this?._adapter?.removePresence&&this._adapter.removePresence(h).catch(S=>{this._logger?.error?.("Error removing presence",{identity:h,error:S});});for(let S of this._plugins)try{S.onDisconnect?.(f,y,T);}catch(N){this._logger?.error?.("Plugin onDisconnect error",{name:S.name,error:N.message});}this._logger?.info?.("Client disconnected",{identity:h});});for(let y of this._plugins)try{let T=y.onConnection?.(f);T instanceof Promise&&T.catch(S=>{this._logger?.error?.("Plugin onConnection error",{name:y.name,error:S.message});});}catch(T){this._logger?.error?.("Plugin onConnection error",{name:y.name,error:T.message});}f.on("message",y=>{for(let T of this._plugins)try{T.onMessage?.(f,y);}catch{}}),f.on("error",y=>{for(let T of this._plugins)try{T.onError?.(f,y);}catch{}}),f.on("badMessage",({message:y,error:T})=>{for(let S of this._plugins)try{S.onBadMessage?.(f,y,T);}catch{}}),f.on("strictValidationFailure",({message:y,error:T})=>{for(let S of this._plugins)try{S.onValidationFailure?.(f,y,T);}catch{}}),f.on("backpressure",y=>{for(let T of this._plugins)try{T.onBackpressure?.(f,y.bufferedAmount);}catch{}}),f.on("pongTimeout",()=>{for(let y of this._plugins)try{y.onPongTimeout?.(f);}catch{}}),f.on("handlerError",({method:y,error:T})=>{for(let S of this._plugins)try{S.onHandlerError?.(f,y,T);}catch{}}),f.on("rateLimitExceeded",y=>{for(let T of this._plugins)try{T.onRateLimitExceeded?.(f,y.rawData);}catch{}}),this.emit("client",f);for(let y of p)y.emit("client",f);f.on("message",()=>{this._updateSessionActivity(h,f.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 s=a._ws;s&&s.bufferedAmount>0&&(this._logger?.debug?.("Waiting for client buffer to drain",{identity:a.identity,bufferedAmount:s.bufferedAmount}),await new Promise(p=>{let d=0,l=setInterval(()=>{d+=50,(!s||s.bufferedAmount===0||d>=5e3)&&(clearInterval(l),p());},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 ie.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 p of e){let d=this._clientsByIdentity.get(p);d&&(r.add(p),a.push(d.call(t,n,i).catch(()=>{})));}let s=e.filter(p=>!r.has(p));if(s.length>0&&this._adapter){let p=[];this._adapter.getPresenceBatch?p=await this._adapter.getPresenceBatch(s):this._adapter.getPresence&&(p=await Promise.all(s.map(l=>this._adapter.getPresence(l))));let d=[];for(let l=0;l<s.length;l++){let c=p[l];c&&d.push({channel:`ocpp:node:${c}`,data:{source:this._nodeId,target:s[l],method:t,params:n,options:i}});}d.length>0&&(this._adapter.publishBatch?await this._adapter.publishBatch(d):await Promise.all(d.map(l=>this._adapter.publish(l.channel,l.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}};exports.OcppService=class R{constructor(e,t={},n){this.ocppServer=e;this.options=t;this.httpAdapterHost=n;}ocppServer;options;httpAdapterHost;attachedHttpServer;gatewayPatterns=new Set;acceptAllUpgrades=false;upgradeHandler=(e,t,n)=>this.handleUpgrade(e,t,n);onModuleInit(){if(this.options.autoAttach===false)return;let e=this.httpAdapterHost?.httpAdapter?.getHttpServer();!e||this.attachedHttpServer===e||(e.on("upgrade",this.upgradeHandler),this.attachedHttpServer=e);}async onModuleDestroy(){this.attachedHttpServer&&(this.attachedHttpServer.removeListener("upgrade",this.upgradeHandler),this.attachedHttpServer=void 0),await this.ocppServer.close();}get server(){return this.ocppServer}get clients(){return this.ocppServer.clients}stats(){return this.ocppServer.stats()}getClient(e){return this.ocppServer.getLocalClient(e)}getLocalClient(e){return this.ocppServer.getLocalClient(e)}hasLocalClient(e){return this.ocppServer.hasLocalClient(e)}hasClient(e){return this.ocppServer.isClientConnected(e)}async sendToClient(...e){return this.ocppServer.sendToClient.apply(this.ocppServer,e)}async safeSendToClient(...e){return this.ocppServer.safeSendToClient.apply(this.ocppServer,e)}close(e){return this.ocppServer.close(e)}registerUpgradePath(e){if(!e){this.acceptAllUpgrades=true;return}this.gatewayPatterns.add(e);}handleUpgrade(e,t,n){this.shouldHandleUpgrade(e)&&this.ocppServer.handleUpgrade(e,t,n);}shouldHandleUpgrade(e){if(e.headers.upgrade?.toLowerCase()!=="websocket")return false;let t=this.getPathname(e);if(!t)return false;if(this.options.upgradeFilter)return this.options.upgradeFilter(t,e);let n=this.normalizePrefixes(this.options.upgradePathPrefix);if(n.length>0)return n.some(i=>t.startsWith(i));if(this.acceptAllUpgrades||this.gatewayPatterns.size===0)return true;for(let i of this.gatewayPatterns)if(this.matchesPattern(i,t))return true;return false}getPathname(e){try{return new URL(e.url??"/",`http://${e.headers.host??"localhost"}`).pathname}catch{return}}normalizePrefixes(e){return e?(Array.isArray(e)?e:[e]).filter(Boolean):[]}matchesPattern(e,t){if(e instanceof RegExp)return e.test(t);let n=e.split("/").filter(Boolean),i=t.split("/").filter(Boolean);for(let r=0;r<n.length;r+=1){let a=n[r],s=i[r];if(a==="*")return true;if(s===void 0)return false;if(!a.startsWith(":")&&a!==s)return false}return n.length===i.length}};exports.OcppService=k([common.Injectable(),B(0,common.Inject(q)),B(1,common.Optional()),B(1,common.Inject(F)),B(2,common.Optional()),B(2,common.Inject(core.HttpAdapterHost))],exports.OcppService);exports.OcppModule=class U{_isModule=true;static forRoot(e={}){let t={provide:F,useValue:e},n={provide:q,useValue:new ne(e)};return {module:exports.OcppModule,providers:[t,n],exports:[exports.OcppService,q]}}static forRootAsync(e){let i=[exports.OcppModule.createAsyncOptionsProvider(e),{provide:q,useFactory:async r=>new ne(r),inject:[F]}];return e.useClass&&i.push({provide:e.useClass,useClass:e.useClass}),{module:exports.OcppModule,imports:e.imports||[],providers:i,exports:[exports.OcppService,q]}}static createAsyncOptionsProvider(e){if(e.useFactory)return {provide:F,useFactory:e.useFactory,inject:e.inject||[]};let t=e.useExisting||e.useClass;return t?{provide:F,useFactory:async n=>n.createOcppOptions(),inject:[t]}:{provide:F,useValue:{}}}};exports.OcppModule=k([common.Global(),common.Module({imports:[core.DiscoveryModule],providers:[exports.OcppService,{provide:exports.OcppExplorer,inject:[core.DiscoveryService,core.MetadataScanner,q,exports.OcppService],useFactory:(o,e,t,n)=>new exports.OcppExplorer(o,e,t,n)}],exports:[exports.OcppService,q]})],exports.OcppModule);
|
|
4826
|
-
exports.Client=
|
|
4824
|
+
${r}`);}var{CONNECTING:Y,OPEN:H,CLOSING:He,CLOSED:A}=qe,Oe=class s extends events.EventEmitter{static CONNECTING=Y;static OPEN=H;static CLOSING=He;static CLOSED=A;_options;_state=A;_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=W;_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 Ae(this._options.callConcurrency),this._middleware=new Le;let t=this._options.logging,n=ge(t,{component:"OCPPClient",identity:this._identity});this._logger=n||W,t&&typeof t=="object"&&(this._exchangeLog=t.exchangeLog??false,this._prettify=t.prettify??false),this._options.logging&&this.use(nt(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||W}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!==A)throw new Error(`Cannot connect: client is in state ${this._state}`);return this._state=Y,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 ie__default.default(n,this._options.protocols??[],i);this._ws=r;let a=()=>{if(p(),this._state=H,this._protocol=r.protocol,this._badMessageCount=0,r.protocol&&this._reconnectAttempt===0&&(this._options.protocols=[r.protocol]),this._reconnectAttempt=0,this._attachWebsocket(r),this._startPing(),this._flushOfflineQueue(),this._outboundBuffer.length>0){let u=this._outboundBuffer;this._outboundBuffer=[];for(let g of u)this._ws?.send(g);}this._logger?.info?.("Connected",{protocol:r.protocol});let l={response:r._req?.res};this.emit("open",l),e(l);},o=c=>{p(),this._state=A,this._logger?.error?.("Connection error",{error:c.message}),this.emit("error",c),t(c);},d=(c,l)=>{p(),this._state=A;let u=new ve(`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===A?{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=He,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===ie__default.default.CLOSED){this._state=A,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=A,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(ht(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!==H){if(this._options.offlineQueue&&(this._state===A||this._state===Y))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 i={method:e.length>=3&&typeof e[0]=="string"&&typeof e[1]=="string"?e[1]:e[0],error:t};this._logger?.warn?this._logger.warn("SafeCall failed",i):console.warn("SafeCall failed",i);}return}}async _sendCall(e,t,n){let i=n.idempotencyKey??$e(),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((g,b)=>{let m=setTimeout(()=>{this._pendingCalls.delete(i),b(new te(`Call to "${p.method}" timed out after ${r}ms`));},r),C=()=>{clearTimeout(m),this._pendingCalls.delete(i),b(new Error("Aborted"));};n.signal&&n.signal.addEventListener("abort",C),this._pendingCalls.set(i,{resolve:g,reject:b,timeoutHandle:m,abortHandler:n.signal?()=>n.signal?.removeEventListener("abort",C):void 0,method:p.method,sentAt:Date.now()}),this._ws?.readyState===ie__default.default.OPEN?this._safeSend(this._ws,u,V=>{V?(clearTimeout(m),this._pendingCalls.delete(i),b(V)):this._emitMessageEvent(c,"OUT",{type:"outgoing_call",messageId:i,method:p.method,params:p.params,options:n});}):this._state===Y?(this._logger?.debug?.("Buffering call",{method:p.method}),this._outboundBuffer.push(u)):(clearTimeout(m),this._pendingCalls.delete(i),b(new Error(`WebSocket is not open (state: ${this._state})`)));}),o}),o}sendRaw(e){if(this._state===H&&this._ws)this._ws.send(e);else if(this._state===Y)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===H&&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 M(`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 M(`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 M(`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 M(`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===H)try{if(this._pendingResponses.has(o.messageId))throw X("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 K(`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===lt)return;this._options.strictMode&&this._protocol&&this._validateOutbound(o.method,u,"conf");let g=[x.CALLRESULT,o.messageId,u],b=this._invokeBeforeSend(g);if(b instanceof Promise){if(await b===!1)return u}else if(b===!1)return u;return this._ws?.send(JSON.stringify(g)),this._emitMessageEvent(g,"OUT",{type:"outgoing_result",messageId:o.messageId,method:o.method,payload:u}),this.emit("callResult",g),u}catch(p){this._pendingResponses.delete(o.messageId);let c=p instanceof I||p.rpcErrorCode?p:X("InternalError",p.message),l=this._options.respondWithDetailedErrors?st(p):{},u=[x.CALLERROR,o.messageId,c.rpcErrorCode,c.rpcErrorMessage||p.message||"",l],g=this._invokeBeforeSend(u);if(g instanceof Promise){if(await g===!1)throw p}else if(g===!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=X(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!==He?(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=A,this.emit("close",{code:e,reason:n}))):this._state=A;}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=Y;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=A,this.emit("close",{code:1001,reason:r});return}this._reconnectAttempt<this._options.maxReconnects&&this._options.reconnect?this._scheduleReconnect():(this._state=A,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 te))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!==ie__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!==ie__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!==H||!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=ct(),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":dt()}},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 Me=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=qe.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 ze=class{_workers=[];_nextWorker=0;_taskId=0;_pending=new Map;_maxQueueSize;_terminated=false;_workerPath;constructor(e={}){let t=e.poolSize??Math.max(2,os.cpus().length-2);this._maxQueueSize=e.maxQueueSize??1e4,this._workerPath=path.resolve(__dirname,"parse-worker.js");for(let n=0;n<t;n++)this._workers.push(this._createWorker(n));}_createWorker(e){let t=new worker_threads.Worker(this._workerPath);return t.on("message",n=>{let i=this._pending.get(n.id);i&&(this._pending.delete(n.id),n.error?i.reject(new Error(n.error)):i.resolve({message:n.message,validationError:n.validationError}));}),t.on("error",n=>{console.error(`[WorkerPool] Worker ${e} error:`,n.message),this._failWorkerTasks(e,`Worker ${e} crashed: ${n.message}`);}),t.on("exit",n=>{if(!this._terminated&&(this._failWorkerTasks(e,`Worker ${e} exited (code ${n})`),this._workers[e]===t))try{this._workers[e]=this._createWorker(e);}catch{}}),t}_failWorkerTasks(e,t){for(let[n,i]of this._pending)i.workerIndex===e&&(i.reject(new Error(t)),this._pending.delete(n));}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++,a=this._nextWorker%this._workers.length,o=this._workers[a];this._nextWorker=(this._nextWorker+1)%this._workers.length,this._pending.set(r,{resolve:n,reject:i,workerIndex:a});try{o.postMessage({id:r,buffer:e,schemaInfo:t});}catch(d){this._pending.delete(r),i(d);}})}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 gt(s={}){try{return new ze(s)}catch{return null}}var ne=class extends events.EventEmitter{_options;_trie=new Te;_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=$e();_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 ye(t),this._wss=this._createWss(),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=ge(this._options.logging,{component:"OCPPServer"});let n=this._options.rateLimit;n?.adaptive&&(this._adaptiveLimiter=new fe({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=gt(r),this._workerPool&&this._logger?.info?.("Worker thread pool initialized",{poolSize:this._workerPool.size});}}get log(){return this._logger||W}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 J;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 J;return t.use(...e),this._registerRouter(t),t}auth(e){let t=new J;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 h=e.socket.remoteAddress??"unknown",E=Date.now(),P=this._connectionBuckets.get(h);if(!P)P={tokens:i.limit,lastRefill:E},this._connectionBuckets.set(h,P);else {let f=E-P.lastRefill,D=i.limit/i.windowMs;P.tokens=Math.min(i.limit,P.tokens+f*D),P.lastRefill=E;}if(P.tokens<1){this._logger?.warn?.("Connection rate limit exceeded",{ip:h});let f={type:"CONNECTION_RATE_LIMIT",ip:h,timestamp:new Date().toISOString(),details:{tokensRemaining:P.tokens}};this.emit("securityEvent",f);for(let D of this._plugins)try{D.onSecurityEvent?.(f);}catch{}$(t,429,"Too Many Requests");return}P.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:h,reason:E}=Ue(e,this._globalCORS);if(!h){this._logger?.warn?.("CORS rejected connection",{reason:E,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,g;!this._trie.frozen&&this._trie.size>0&&this._trie.freeze();for(let h of this._globalMiddlewareRouters)d.push(h),h.middlewares.length>0&&o.push(...h.middlewares),h.authCallback&&!a&&(a=h.authCallback);let b=this._trie.match(c);if(b){Object.assign(p,b.params);for(let h of b.routers)d.push(h),l=true,h._routeConfig&&(g=Object.assign(g||{},h._routeConfig)),h.middlewares.length>0&&o.push(...h.middlewares),h.authCallback&&!a&&(a=h.authCallback);}for(let h of this._regexRouters)for(let E of h._regexPatterns){let P=E.regex.exec(c);if(P){if(d.push(h),l=true,P.groups)for(let[f,D]of Object.entries(P.groups))p[f]=decodeURIComponent(D??"");h._routeConfig&&(g=Object.assign(g||{},h._routeConfig)),h.middlewares.length>0&&o.push(...h.middlewares),h.authCallback&&!a&&(a=h.authCallback);break}}let m=p.identity;if(!m){let h=c.split("/").filter(Boolean);m=decodeURIComponent(h[h.length-1]??"");}if(!m){$(t,400,"Missing identity in URL path");return}for(let h of d)if(h._routeCORS){let{allowed:E,reason:P}=Ue(e,h._routeCORS);if(!E){this._logger?.warn?.("Route CORS rejected connection",{reason:P,ip:e.socket.remoteAddress}),$(t,403,"Forbidden");return}}"setKeepAlive"in t&&t.setKeepAlive(true);let C=new Set,V=e.headers["sec-websocket-protocol"];if(V)try{C=mt(V);}catch{$(t,400,"Invalid Sec-WebSocket-Protocol header");return}let w=g?.protocols??this._options.protocols??[],_;if(w.length>0){if(C.size===0){$(t,400,"Missing subprotocol");return}if(_=w.find(h=>C.has(h)),!_){$(t,400,"No matching subprotocol");return}}let re=ft(e.headers.authorization??"",m),ae,Ge=this._options.securityProfile??0;Ge===3&&"getPeerCertificate"in t&&(ae=t.getPeerCertificate());let Q={identity:m,remoteAddress:e.socket.remoteAddress??"",headers:e.headers,protocols:C,pathname:c,params:p,query:r.searchParams,request:e,password:re,clientCertificate:ae,securityProfile:Ge},Ve,Je;if(a||o.length>0){let h=new AbortController,E=()=>{h.abort(new Error("Socket closed during handshake"));};t.on("close",E),t.on("error",E),t.on("end",E);let P=this._options.handshakeTimeoutMs??3e4,f;P>0&&(f=setTimeout(()=>{h.abort(new Error("Handshake timeout"));},P));try{Ve={handshake:Q,state:{},reject:(T=401,S="Unauthorized")=>{throw {code:T,message:S,_isMiddlewareReject:!0}},next:async T=>{}};let D=[...o],y=!1;if(D.push(async T=>{y=!0,a?Je=await new Promise((S,N)=>{let L=!1,oe=z=>{L||(L=!0,z?.protocol&&(_=z.protocol),S(z));},Ne=(z=401,Ke="Unauthorized")=>{throw L||(L=!0,N({code:z,message:Ke})),{code:z,message:Ke,_isMiddlewareReject:!0}};if(h.signal.aborted){N(h.signal.reason);return}h.signal.addEventListener("abort",()=>{L||(L=!0,N(h.signal.reason));},{once:!0}),this._logger?.debug?.("Executing auth callback",{identity:m,pathname:c});let vt={handshake:Q,state:T.state,reject:Ne,signal:h.signal,accept:oe};a(vt);}):_=Q.protocols.values().next().value??void 0;}),await it(D,Ve),!y)throw {code:500,message:"Middleware chain halted unexpectedly without rejecting",_isMiddlewareReject:!0}}catch(D){if(h.signal.aborted){let L=D instanceof Error?D.message:"Unknown abort";this._logger?.warn?.("Handshake aborted",{identity:m,reason:L});let oe={type:"UPGRADE_ABORTED",identity:m,ip:e.socket.remoteAddress,timestamp:new Date().toISOString(),details:{reason:L}};this.emit("securityEvent",oe);for(let Ne of this._plugins)try{Ne.onSecurityEvent?.(oe);}catch{}this.emit("upgradeAborted",{identity:m,reason:L,socket:t,request:e}),t.destroyed||t.destroy();return}let y=D,T=typeof y?.code=="number"?y.code:401,S=typeof y?.message=="string"?y.message:"Unauthorized";this._logger?.warn?.("Auth rejected",{identity:m,code:T});let N={type:"AUTH_FAILED",identity:m,ip:e.socket.remoteAddress,timestamp:new Date().toISOString(),details:{code:T,message:S}};this.emit("securityEvent",N);for(let L of this._plugins){try{L.onSecurityEvent?.(N);}catch{}try{L.onAuthFailed?.(Q,T,S);}catch{}}$(t,T,S);return}finally{f&&clearTimeout(f),t.removeListener("close",E),t.removeListener("error",E),t.removeListener("end",E);}}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:m}),t.destroyed||t.destroy();return}this._wss||(this._wss=this._createWss()),this._wss.handleUpgrade(e,t,n,h=>{let E={identity:m,endpoint:"",callTimeoutMs:g?.callTimeoutMs??this._options.callTimeoutMs,pingIntervalMs:g?.pingIntervalMs??this._options.pingIntervalMs,deferPingsOnActivity:g?.deferPingsOnActivity??this._options.deferPingsOnActivity,callConcurrency:g?.callConcurrency??this._options.callConcurrency,maxBadMessages:this._options.maxBadMessages,respondWithDetailedErrors:this._options.respondWithDetailedErrors,strictMode:g?.strictMode??this._options.strictMode,strictModeMethods:g?.strictModeMethods??this._options.strictModeMethods,strictModeValidators:this._options.strictModeValidators,rateLimit:g?.rateLimit??this._options.rateLimit,reconnect:false,logging:this._options.logging},P={...Ve?.state||{},...this._sessions.get(m)?.data||{},...Je?.session||{}},f=new Me(E,{ws:h,handshake:Q,session:P,protocol:_,adaptiveMultiplier:this._adaptiveLimiter?()=>this._adaptiveLimiter.multiplier:void 0,workerPool:this._workerPool??void 0,plugins:this._plugins});this._updateSessionActivity(m,f.session);let D=this._clientsByIdentity.get(m);if(D&&D!==f){this._logger?.warn?.("Evicting stale connection for identity",{identity:m,reason:"Duplicate identity replaced by new connection"});for(let y of this._plugins)try{y.onEviction?.(D,f);}catch{}D.close({code:4e3,reason:"Evicted by new connection",force:true}).catch(()=>{}),this._clients.delete(D);}this._clients.add(f),this._clientsByIdentity.set(m,f),this._adapter?.setPresence&&this._adapter.setPresence(m,this._nodeId,300).catch(y=>{this._logger?.error?.("Error setting presence",{identity:m,error:y});}),this._logger?.info?.("Client connected",{identity:m,remoteAddress:e.socket.remoteAddress,protocol:_}),f.on("close",({code:y,reason:T})=>{this._clients.delete(f),this._clientsByIdentity.get(m)===f&&this._clientsByIdentity.delete(m),this?._adapter?.removePresence&&this._adapter.removePresence(m).catch(S=>{this._logger?.error?.("Error removing presence",{identity:m,error:S});});for(let S of this._plugins)try{S.onDisconnect?.(f,y,T);}catch(N){this._logger?.error?.("Plugin onDisconnect error",{name:S.name,error:N.message});}this._logger?.info?.("Client disconnected",{identity:m});});for(let y of this._plugins)try{let T=y.onConnection?.(f);T instanceof Promise&&T.catch(S=>{this._logger?.error?.("Plugin onConnection error",{name:y.name,error:S.message});});}catch(T){this._logger?.error?.("Plugin onConnection error",{name:y.name,error:T.message});}f.on("message",y=>{for(let T of this._plugins)try{T.onMessage?.(f,y);}catch{}}),f.on("error",y=>{for(let T of this._plugins)try{T.onError?.(f,y);}catch{}}),f.on("badMessage",({message:y,error:T})=>{for(let S of this._plugins)try{S.onBadMessage?.(f,y,T);}catch{}}),f.on("strictValidationFailure",({message:y,error:T})=>{for(let S of this._plugins)try{S.onValidationFailure?.(f,y,T);}catch{}}),f.on("backpressure",y=>{for(let T of this._plugins)try{T.onBackpressure?.(f,y.bufferedAmount);}catch{}}),f.on("pongTimeout",()=>{for(let y of this._plugins)try{y.onPongTimeout?.(f);}catch{}}),f.on("handlerError",({method:y,error:T})=>{for(let S of this._plugins)try{S.onHandlerError?.(f,y,T);}catch{}}),f.on("rateLimitExceeded",y=>{for(let T of this._plugins)try{T.onRateLimitExceeded?.(f,y.rawData);}catch{}}),this.emit("client",f);for(let y of d)y.emit("client",f);f.on("message",()=>{this._updateSessionActivity(m,f.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=this._createWss());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,a;e.length>=4&&typeof e[0]=="string"&&typeof e[1]=="string"&&typeof e[2]=="string"?(t=e[0],n=e[1],i=e[2],r=e[3],a=e[4]):(t=e[0],i=e[1],r=e[2],a=e[3]);let o=this._clientsByIdentity.get(t);if(o)return n?await o.call(n,i,r,a):await o.call(i,r,a);if(this._adapter?.getPresence){let d=await this._adapter.getPresence(t);if(d){await this._adapter.publish(`ocpp:node:${d}`,{source:this._nodeId,target:t,version:n,method:i,params:r,options:a});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,n=this._clientsByIdentity.get(t.target);if(n){(t.version?n.call(t.version,t.method,t.params,t.options):n.call(t.method,t.params,t.options)).catch(r=>{r.name!=="TimeoutError"&&this._logger?.error?.("Error delivering unicast to client",{identity:t.target,error:r});});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);}_createWss(){return new ie.WebSocketServer({noServer:true,maxPayload:this._options.maxPayloadBytes??65536,perMessageDeflate:this._buildCompressionConfig()})}_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}};function yt(s,e){let t=s.endsWith("/*")?s.slice(0,-2):s;return t===""||t==="/"?true:e===t||e.startsWith(`${t}/`)}exports.OcppService=class R{constructor(e,t={},n){this.ocppServer=e;this.options=t;this.httpAdapterHost=n;}ocppServer;options;httpAdapterHost;attachedHttpServer;gatewayPatterns=new Set;acceptAllUpgrades=false;upgradeHandler=(e,t,n)=>this.handleUpgrade(e,t,n);onModuleInit(){if(this.options.autoAttach===false)return;let e=this.httpAdapterHost?.httpAdapter?.getHttpServer();!e||this.attachedHttpServer===e||(e.on("upgrade",this.upgradeHandler),this.attachedHttpServer=e);}async onModuleDestroy(){this.attachedHttpServer&&(this.attachedHttpServer.removeListener("upgrade",this.upgradeHandler),this.attachedHttpServer=void 0),await this.ocppServer.close();}get server(){return this.ocppServer}get clients(){return this.ocppServer.clients}stats(){return this.ocppServer.stats()}getClient(e){return this.ocppServer.getLocalClient(e)}getLocalClient(e){return this.ocppServer.getLocalClient(e)}hasLocalClient(e){return this.ocppServer.hasLocalClient(e)}hasClient(e){return this.ocppServer.isClientConnected(e)}async sendToClient(...e){return this.ocppServer.sendToClient.apply(this.ocppServer,e)}async safeSendToClient(...e){return this.ocppServer.safeSendToClient.apply(this.ocppServer,e)}close(e){return this.ocppServer.close(e)}registerUpgradePath(e){if(!e){this.acceptAllUpgrades=true;return}this.gatewayPatterns.add(e);}handleUpgrade(e,t,n){this.shouldHandleUpgrade(e)&&this.ocppServer.handleUpgrade(e,t,n);}shouldHandleUpgrade(e){if(e.headers.upgrade?.toLowerCase()!=="websocket")return false;let t=this.getPathname(e);if(!t)return false;if(this.options.upgradeFilter)return this.options.upgradeFilter(t,e);let n=this.normalizePrefixes(this.options.upgradePathPrefix);if(n.length>0)return n.some(i=>yt(i,t));if(this.acceptAllUpgrades||this.gatewayPatterns.size===0)return true;for(let i of this.gatewayPatterns)if(this.matchesPattern(i,t))return true;return false}getPathname(e){try{return new URL(e.url??"/",`http://${e.headers.host??"localhost"}`).pathname}catch{return}}normalizePrefixes(e){return e?(Array.isArray(e)?e:[e]).filter(Boolean):[]}matchesPattern(e,t){if(e instanceof RegExp)return e.test(t);let n=e.split("/").filter(Boolean),i=t.split("/").filter(Boolean);for(let r=0;r<n.length;r+=1){let a=n[r],o=i[r];if(a==="*")return true;if(o===void 0)return false;if(!a.startsWith(":")&&a!==o)return false}return n.length===i.length}};exports.OcppService=k([common.Injectable(),B(0,common.Inject(q)),B(1,common.Optional()),B(1,common.Inject(F)),B(2,common.Optional()),B(2,common.Inject(core.HttpAdapterHost))],exports.OcppService);exports.OcppModule=class U{_isModule=true;static forRoot(e={}){let t={provide:F,useValue:e},n={provide:q,useValue:new ne(e)};return {module:exports.OcppModule,providers:[t,n],exports:[exports.OcppService,q]}}static forRootAsync(e){let i=[exports.OcppModule.createAsyncOptionsProvider(e),{provide:q,useFactory:async r=>new ne(r),inject:[F]}];return e.useClass&&i.push({provide:e.useClass,useClass:e.useClass}),{module:exports.OcppModule,imports:e.imports||[],providers:i,exports:[exports.OcppService,q]}}static createAsyncOptionsProvider(e){if(e.useFactory)return {provide:F,useFactory:e.useFactory,inject:e.inject||[]};let t=e.useExisting||e.useClass;return t?{provide:F,useFactory:async n=>n.createOcppOptions(),inject:[t]}:{provide:F,useValue:{}}}};exports.OcppModule=k([common.Global(),common.Module({imports:[core.DiscoveryModule],providers:[exports.OcppService,{provide:exports.OcppExplorer,inject:[core.DiscoveryService,core.MetadataScanner,q,exports.OcppService],useFactory:(s,e,t,n)=>new exports.OcppExplorer(s,e,t,n)}],exports:[exports.OcppService,q]})],exports.OcppModule);
|
|
4826
|
+
exports.Client=Ni;exports.Context=Ui;exports.Handshake=Ki;exports.Identity=Wi;exports.Message=ki;exports.MessageId=Ji;exports.OCPP_AUTH_METADATA=pe;exports.OCPP_CONNECTION_MIDDLEWARE_METADATA=ce;exports.OCPP_CORS_METADATA=ue;exports.OCPP_GATEWAY_METADATA=Z;exports.OCPP_MESSAGE_EVENT_METADATA=se;exports.OCPP_RPC_MIDDLEWARE_METADATA=le;exports.OCPP_SERVER_INSTANCE=q;exports.OCPP_SERVER_OPTIONS=F;exports.OCPP_WILDCARD_EVENT_METADATA=de;exports.OcppAuth=Ai;exports.OcppConnectionMiddleware=$i;exports.OcppCors=Si;exports.OcppGateway=Pi;exports.OcppMessageEvent=_i;exports.OcppParamType=Fe;exports.OcppWildcardEvent=Li;exports.PARAM_ARGS_METADATA=ee;exports.Params=Fi;exports.Path=Hi;exports.PathParam=Bi;exports.Protocol=Gi;exports.Session=zi;exports.UseOcppRpcMiddleware=Ii;
|