@interopio/gateway
Version:
[](https://www.npmjs.com/package/@interopio/gateway)
4 lines • 152 kB
JavaScript
var Uc=Object.defineProperty;var ge=(t,e)=>()=>(t&&(e=t(t=0)),e);var Xe=(t,e)=>{for(var r in e)Uc(t,r,{get:e[r],enumerable:!0})};var Kr={};Xe(Kr,{regexify:()=>Wt,valueMatches:()=>We,valuesMatch:()=>Br});function Hc(t){return typeof t=="string"}function We(t,e){return Hc(t)?t===e:typeof e=="string"?t.test(e):!1}function Br(t,e){for(let r of t)if(We(r,e))return!0;return!1}function Wt(t){if(typeof t=="string"){let e=Fc.exec(t)?.groups;if(e??=Lc.exec(t)?.groups,e?.pattern)return new RegExp(e.pattern,e.flags??"")}return t}var Lc,Fc,Jt=ge(()=>{"use strict";Lc=/^#(\(\?(?<flags>[im]*)\))?(?<pattern>.*)$/,Fc=/^\/(?<pattern>(?:[^/\\]|\\.)+)\/(?<flags>[gimsuyd]*)$/});import*as Fi from"@interopio/gateway/logging/core";function g(t){return Fi.getLogger(t)}var N=ge(()=>{"use strict"});import{produce as md}from"immer";function Xi(t,e){return e.reduce((r,n)=>n===t?r:r.concat(n),[])}function sn(t,e){return t[e]?t:md(t,r=>{r[e]={}})}function $e(t){return t instanceof Set?Array.from(t).map($e):t instanceof Array?t.map($e):t instanceof Map?$e(Object.fromEntries(t)):t instanceof Object?Object.keys(t).reduce((e,r)=>(e[r]=$e(t[r]),e),{}):t}function ld(t){let e=new Map;return function(r,n){let i=e.get(this)+(Array.isArray(this)?`[${r}]`:`.${r}`);return n===Object(n)&&e.set(n,i),n instanceof RegExp&&(n=`#${n.source}`),t.call(this,r,n,i.replace(/undefined\.\.?/,""))}}function nt(...t){return ld((e,r,n)=>t.indexOf(n)!==-1?"******":r)}function it(t){return JSON.stringify(t,Object.keys(t).sort(yd))}function pe(t){return!!t}var yd,me=ge(()=>{"use strict";yd=(t,e)=>t.localeCompare(e)});function pm(t,e){for(let[r,n]of Object.entries(t)){let i=e[r];if(!We(n,i))return!1}return!0}function Ua(t,e){return Br(t,e)}function Ut(t,e,r){let n=r?.publishers?.reduce((o,s)=>{if(pm(s.identity,t)){let a=s.metrics.block??s.metrics.blacklist??[];if(a.length>0&&Ua(a,e))return!1;{let c=s.metrics.allow??s.metrics.whitelist??[];return o||Ua(c,e)}}return o},void 0);if(n!==void 0)return n;let i=r?.non_matched??"allow";return i==="allow"||i==="whitelist"}var ui=ge(()=>{"use strict";Jt()});function vm(t){if(t&&Object.keys(t).length>0)return t}function Ga(t){return typeof t=="object"?{value:Object.entries(t).reduce((r,[n,i])=>(r[n]=Ga(i),r),{})}:typeof t=="string"?{value:t}:{value:t}}function wm(t){return{timestamp:t.timestamp??Date.now(),value:Ga(t.value)}}function Im(t,e){return Array.from(t).reduce((r,n)=>{let i=e(n),o=r.get(i)??[];return o.length===0&&r.set(i,o),o.push(n),r},new Map)}function*bt(t,e){Fa.enabledFor("trace")&&Fa.debug(`conflating ${JSON.stringify(e)}`);let r=Im(e,i=>it(i.identity)),n;for(let[,i]of r){for(let o of i)if(o.status){let{identity:s,status:a,metadata:c}=o;n&&(yield n),yield{identity:s,status:a,metrics:void 0,metadata:vm(c)},n=void 0}else{let{metric:s,identity:a,datapoint:c}=o,d=s?.name;n||(n={identity:a}),n.metrics=n.metrics??{},n.metrics[d]=n.metrics[d]??{definition:{...s},datapoints:[]},delete n.metrics[d].definition.name,n.metrics[d].datapoints.push(wm(c))}n&&(yield n)}}var Fa,Ir=ge(()=>{"use strict";N();me();Fa=g("gateway.metrics.common")});var Ja={};Xe(Ja,{NodeWorker:()=>li});import{fork as Tm}from"child_process";import{EventEmitter as Wa}from"events";import{fileURLToPath as Am}from"url";var li,ja=ge(()=>{"use strict";li=class{events=new Wa;ps;constructor(e,r,n){this.events=new Wa;let i=Am(e);this.ps=Tm(i,r,n),this.ps.on("message",o=>{let s;try{s=JSON.parse(o),s?.type===void 0&&this.events.emit("messageerror",new Error(`Invalid message: ${o}`))}catch(a){this.events.emit("messageerror",a);return}s.type==="error"?this.events.emit("error",new Error(s.message)):this.events.emit("message",{data:s.data})}),this.ps.stdout?.on("data",o=>{console.log(o)}),this.ps.stderr?.on("data",o=>{console.error(o)}),this.ps.on("error",o=>{this.events.emit("error",o)}),this.events.on("message",o=>{this.onmessage&&this.onmessage(o)}),this.events.on("error",o=>{this.onerror&&this.onerror(o)}),this.events.on("messageerror",o=>{this.onmessageerror&&this.onmessageerror(o)})}onerror=null;onmessage=null;onmessageerror=null;postMessage(e){this.ps.send({data:e},r=>{r&&this.events.emit("error",r)})}terminate(){this.ps.kill()}addEventListener(e,r,n){this.events.addListener(e,r)}removeEventListener(e,r,n){this.events.removeListener(e,r)}dispatchEvent(e){return this.events.emit(e.type,e)}}});async function Cm(t,e,r){let{NodeWorker:n}=await Promise.resolve().then(()=>(ja(),Ja)),i=Object.entries(e??{}).map(([o,s])=>`--${o}=${s}`);return new n(t,i,r)}async function Mm(t,e,r){return Object.entries(e??{}).forEach(([n,i])=>t.searchParams.append(n,i)),new Worker(t,r)}function Ba({url:t,parameters:e,options:r}){return typeof process<"u"?Cm(t,e,r):Mm(t,e,r)}var Ka=ge(()=>{"use strict"});async function Pm(t,e){try{let r=await import(e);if(typeof r=="function")return await r();if(typeof r.default=="function")return await r.default()}catch(r){t.error("failed to load preload",r)}}async function Dm(t,e,r){t.debug(`loading publisher from ${e}`);let n=await import(e);return typeof n.default=="object"&&(n=n.default),await n.create(r,t.child(`publisher.${n.name??e}`))}var Tr,Va=ge(()=>{"use strict";Tr=class{#e;#t;#r;constructor(e){this.#e=e}async#n(e){let{publishFn:r,cfg:n}=e;if(n?.preload){let s=await Pm(this.#e,n.preload);if(typeof s=="object")for(let a in s)n[a]=s[a]}let i;typeof r=="function"?i=r:i=await Dm(this.#e,r,n);let o=await i("start");this.#t=i,this.#r=o}async#i(){let e=await this.#t?.("stop");typeof e=="function"&&await e(this.#r)}async#o(e){if(!this.#t)throw new Error("worker not started");await this.#t(e)}async execute(e,r){switch(e){case"start":{await this.#n(r);break}case"stop":{await this.#i();break}case"update":{await this.#o(r);break}}}}});import{getLogger as _m,logEvent as Om}from"@interopio/gateway/logging/core";import{deserializeError as za}from"serialize-error";function yi(t,e,r){let n={identity:t,status:{...e,"updated-at":e.updated,"expires-at":e.expires}};return r&&(n.metadata=r),n}async function Rt(t,e,r){Y.info(`creating publisher with configuration
${JSON.stringify(t,nt("authentication.password"))}`);try{let n=t?.worker;if(n===void 0)return await km(r,t??{},e);{let i=t?Object.fromEntries(Object.entries(t).filter(([o])=>o!=="worker")):{};return await Nm(r,i,e,n)}}catch(n){throw Y.error("Failed to create basic publisher",n),n}}async function km(t,e,r){let n=new hi(e),i=o=>{for(let s of r([o]))n.next(s)};return await n.start(t),i.close=async()=>{await n.stop()},i.on=o=>{n.on(o)},i}async function Nm(t,e,r,n){let i=new bi(await Ba(n),e);await i.start(t);let o=s=>{for(let a of r([s]))i.next(a)};return o.close=async()=>{await i.stop()},o.on=s=>{i.on(s)},o}function xt(t,e){return new gi(t,e)}var Y,fi,gi,Ar,hi,bi,Cr=ge(()=>{"use strict";Ka();me();ui();Va();Y=_m("gateway.metrics.publisher");fi=class{constructor(e,r,n,i,o){this.publisher=e;this.filters=r;this.repoId=n;this.heartbeatInterval=i;this.metadata=o}running=!0;latestStatus={initial:!0,stopped:!1,status:{state:0,updated:Date.now(),description:"Running"}};heartbeatCleanup;metrics=new Map;start(){Y.info(`starting repository for ${JSON.stringify(this.repoId)} with heartbeat interval ${this.heartbeatInterval}ms`);let e=Date.now();if(this.latestStatus.stopped&&(this.latestStatus.status.state=0,this.latestStatus.status.description="Running",this.latestStatus.status.updated=e,this.latestStatus.initial=!0,this.latestStatus.stopped=!1),this.heartbeatInterval>=0){let n={...this.latestStatus.status,timestamp:e,expires:e+3*this.heartbeatInterval},i=yi(this.repoId,n,this.metadata);this.publisher(i)}this.running=!0,this.heartbeatInterval>0&&(this.heartbeatCleanup=setInterval(()=>{if(!this.running)return;let r=Date.now(),i={...this.latestStatus.status,timestamp:r,expires:r+3*this.heartbeatInterval},o=yi(this.repoId,i,this.metadata);this.publisher(o)},this.heartbeatInterval))}stop(){Y.info(`stopping repository for ${JSON.stringify(this.repoId)}`),this.running=!1,this.heartbeatCleanup&&clearInterval(this.heartbeatCleanup);let e=Date.now();this.latestStatus.stopped=!0,this.status({state:-1,timestamp:e,updated:e,expires:e,description:"Repository Stopped"})}add(e){for(let r of e){let n=r.name;this.metrics.has(n)||!(this.filters===void 0||Ut(this.repoId,n,this.filters))||this.metrics.set(n,r)}}publish(e){if(this.running&&e.length>0)for(let r of e){let n=this.metrics.get(r.name);if(n){let i={identity:this.repoId,metric:n,datapoint:{...r}};delete i.datapoint.name,this.publisher(i)}}}status(e){let r={...this.latestStatus};Object.assign(r.status,e),r.timestamp=e.timestamp,r.expires=e.expires;let n=r.status.state!==this.latestStatus.status.state;if((this.latestStatus.initial||n)&&(r.status.updated=e.timestamp),r.initial=!1,Object.assign(this.latestStatus,r),this.running||r.stopped){let i=yi(this.repoId,e,this.metadata);this.publisher(i)}}},gi=class{constructor(e,r){this.config=e;this.publisher=r}repository(e,r){let n=r?.metadata,i=this.config?.heartbeats??0;return new fi(this.publisher,this.config?.filters,e,i,n)}async shutdown(){await this.publisher.close()}on(e){this.publisher.on(e)}};Ar=class{#e;#t;#r;#n;#i;#o;constructor(e){let{buffer_size:r}=e;this.#e=e,this.#t=r??1e3,this.#r=new Map,this.#n=new Map,this.#i=[],this.#o=0}async start(e){try{await this.enqueue("start",{cfg:this.#e,publishFn:e})[1],Y.info(`publisher [${e}] started`)}catch(r){throw Y.error(`error starting publisher [${e}]: ${r}`),r}}next(e){let[r,n]=this.enqueue("update",e);n.catch(i=>{Y.warn(`update [${r}] error`,i)}).finally(()=>{this.#n.delete(r)})}async stop(e=!1,r=1e3){Y.info(`stopping publisher worker rejectProcessing: ${e}, timeout: ${r}, promises: ${this.#n.size}`);let n=s=>{this.#r.forEach(({resolver:a})=>{a.reject(new Error(`reject on stop: ${s}`))})};e&&n("now");let i=Promise.allSettled(this.#n),o=this.enqueue("stop",void 0)[1];await new Promise((s,a)=>{let c=setTimeout(()=>{n("timeout"),a(new Error("timeout"))},r);i.then(d=>{clearTimeout(c);for(let u of d)u.status==="rejected"&&Y.error(`Pending future failed with ${u.reason} on stop`);s()})}),await o,this.#n.size>0&&Y.error(`uncleared promises: ${this.#n.size}`),Y.info("publisher worker stopped")}enqueue(e,r){this.#r.size>=this.#t&&Y.warn(`processing queue is full. dropping cmd: ${JSON.stringify(e)}`);let n=++this.#o;return[n,new Promise((i,o)=>{this.#r.set(n,{resolver:{resolve:i,reject:o}}),this.processRequest(n,e,r)})]}processResult(e,r,n){let i=this.#r.get(e);if(i){let{resolver:o}=i;try{n?o.reject(n):o.resolve(r)}finally{this.#r.delete(e)}}else Y.error(`unknown message id: ${e}`)}emit(e){this.#i.forEach(r=>r(e))}on(e){this.#i.push(e)}},hi=class extends Ar{#e;constructor(e){super(e),this.#e=new Tr(Y)}processRequest(e,r,n){this.#e.execute(r,n).then(()=>{this.processResult(e,"ok")}).catch(i=>{this.processResult(e,"error",i instanceof Error?i:new Error(String(i)))})}},bi=class extends Ar{worker;constructor(e,r){super(r),this.worker=e}processRequest(e,r,n){let i={id:e,cmd:r,arg:n};this.worker.postMessage(i)}async stop(e=!1,r=1e3){try{return await super.stop(e,r)}finally{this.worker.terminate()}}async start(e){await new Promise(r=>{this.worker.onerror=n=>{Y.error(`error from worker: ${n.message}`)},this.worker.onmessageerror=n=>{Y.error(`error receiving message: ${n.data}`)},this.worker.onmessage=n=>{if(n.data.ready){r();return}if(n.data.id){let{id:i,result:o,error:s}=n.data;super.processResult(i,o,s==null?void 0:za(s))}else if(n.data.log){let{level:i,time:o,name:s,message:a,data:c}=n.data.log;Om({level:i,time:new Date(o),name:s,message:a,data:c.map(d=>za(d))})}else n.data.event&&super.emit(n.data.event)}});try{await super.start(e),Y.info(`publisher worker [${e}] started`)}catch(r){throw Y.error(`error starting publisher worker [${e}]: ${r}`),this.worker.terminate(),r}}}});var Za={};Xe(Za,{restPublisher:()=>Ya,restRepositoryFactory:()=>qm});async function Ya(t){let e=t?.conflation?.["max-datapoints-repo"]??50;return await Rt(t,r=>bt(e,r),t?.publishFn??"@interopio/gateway/metrics/publisher/rest")}async function qm(t){return xt(t,await Ya(t))}var Xa=ge(()=>{"use strict";Cr();Ir()});var ec={};Xe(ec,{fileRepositoryFactory:()=>Um});async function Em(t){let e=t.conflation?.["max-datapoints-repo"]??50;return $m.info(`will record metrics to ${t.location}`),await Rt(t,r=>bt(e??1,r),t?.publishFn??"@interopio/gateway/metrics/publisher/file")}async function Um(t){return xt(t,await Em(t))}var $m,tc=ge(()=>{"use strict";Cr();Ir();N();$m=g("gateway.metrics.file")});var $c={};Xe($c,{Encoding:()=>et,Factory:()=>$i,Filtering:()=>Kr,Logging:()=>Ry});var et={};Xe(et,{direct:()=>jr,json:()=>Jr,transit:()=>Wr});import Ce from"transit-js";var Lr=class{map;reverse=new Map;constructor(e){if(e)for(let[r,n]of e)this.reverse.set(n,r);else e=this.reverse;this.map=e}get(e){return this.map.get(e)}rev(e){return this.reverse.get(e)}};function Ei(t,e){let r=t.indexOf("/");if(r===-1)return Ce.keyword(t);let n=t.substring(0,r),i=e?.get(n)??n;return Ce.keyword(i+t.substring(r))}function Ui(t,e){let r=t.name(),n=t.namespace();return n===null?r:(e.rev(n)??n)+"/"+r}function Li(t,e,r,n=""){if(t instanceof Array)return t.map(i=>i);if(t instanceof Object){let i=Ce.map();for(let o in t){let s=r?.get(n),a=s===null?o:Ei(o,e),c=t[o],d=`${n}/${o}`,u=r?.get(d);if(u!==void 0&&typeof c=="string"&&(u==="*"||u?.has(c)))i.set(a,Ei(c,e));else{s===null&&!r?.has(d)&&r?.set(d,null);let m=Li(c,e,r,d);i.set(a,m)}}return i}else return t}function Fr(t,e){if(Ce.isKeyword(t))return Ui(t,e);if(Ce.isMap(t)){let r={};for(let[n,i]of t){let o=Ce.isKeyword(n)?Ui(n,e):n;r[o]=Fr(i,e)}return r}else if(Ce.isList(t)||t instanceof Array){let r=[];for(let n of t)r.push(Fr(n,e));return r}return t}function Wr(t){let e=t?.verbose?"json-verbose":"json",r=new Lr(t?.namespaces);return{encode:n=>{let i=Li(n,r,t?.keywordize);return Ce.writer(e).write(i)},decode:n=>{let i;try{i=Ce.reader(e).read(n)}catch(o){throw new Error(`"${n}" is not valid TRANSIT`,{cause:o})}return Fr(i,r)}}}function Jr(){return{encode:JSON.stringify,decode:JSON.parse}}function Hi(t){return t}function Gr(t){return t instanceof Array||Array.isArray(t)?t.map(Gr):t?.constructor===Object?Object.keys(t).reduce((e,r)=>(e[r]=Gr(t[r]),e),{}):t===void 0?null:t}function jr(t){return{encode:Hi,decode:t?.cljs??!1?Gr:Hi}}Jt();import*as Ry from"@interopio/gateway/logging/core";N();var Se="global",se="context",Ne=`${Se}.errors.failure`;N();function x(t,e){return{receiver:t,body:e}}function G(t,e){return{...x({type:"cluster"},e),source:t}}function K(t,e,r){return{...x(e,r),source:t}}function Gc(t,e,r,n,i){let o={type:"error",request_id:e,reason_uri:n.uri,reason:n.message};return t&&(o.domain=t),r&&(o.peer_id=r),i&&(o.context=i),o}function b(t,e,r,n,i,o){return x(e,Gc(t,r,n,i,o))}function Wc(t,e,r){return{type:"success",request_id:e,domain:t,peer_id:r}}function I(t,e,r,n){return x(e,Wc(t,r,n))}function T(t){let e=t.type;return e&&e==="local"}function W(t){return!T(t)}function Jc(t,e,r,n){return{domain:t,type:"token",request_id:e,peer_id:r,token:n}}function Wi(t,e,r,n,i){return x(e,Jc(t,r,n,i))}function jc(t,e,r,n,i){return{domain:t,type:"peer-added",peer_id:e,new_peer_id:r,identity:n,meta:i}}function qe(t,e,r,n,i,o){return x(e,jc(t,r,n,i,o))}function Bc(t,e,r,n){return{domain:t,type:"peer-removed",peer_id:e,removed_id:r,reason_uri:n.uri,reason:n.message}}function Je(t,e,r,n,i){return x(e,Bc(t,r,n,i))}var ve=class extends Error{data;cause;constructor(e,r,n){super(e),this.name="ExceptionInfo",this.data=r,this.cause=n}};function V(t,e,r){return new ve(t,e,r)}function je(t){if(t instanceof ve)return t.data}function Be(t){if(t instanceof Error)return t.message}function S(t,e){return{uri:t,message:e}}function J(t,e){let r=je(t);return{uri:r?.uri??e,message:r?.message??Be(t)??""}}function k(t,e){let r={uri:t,message:e};throw new ve(e,r)}function Q(t){return{uri:t.reason_uri,message:t.reason}}import{CharStreams as ad,CommonTokenStream as cd}from"antlr4";import{ATN as ji,ATNDeserializer as Kc,DFA as Vc,FailedPredicateException as zc,RecognitionException as we,Parser as Qc,ParserATNSimulator as Yc,ParserRuleContext as Ie,PredictionContextCache as Zc,Token as Xc}from"antlr4";var M=class t extends Qc{static OR=1;static AND=2;static EQ=3;static NEQ=4;static MATCH=5;static LPAREN=6;static RPAREN=7;static DOLLAR=8;static POUND=9;static STR=10;static WORD=11;static NUMBER=12;static WS=13;static EOF=Xc.EOF;static RULE_parse=0;static RULE_expr=1;static RULE_andOr=2;static RULE_eqNeq=3;static RULE_term=4;static RULE_ident=5;static RULE_ownIdent=6;static RULE_str=7;static RULE_word=8;static RULE_number=9;static literalNames=[null,"'||'","'&&'","'=='","'!='","'?'","'('","')'","'$'","'#'"];static symbolicNames=[null,"OR","AND","EQ","NEQ","MATCH","LPAREN","RPAREN","DOLLAR","POUND","STR","WORD","NUMBER","WS"];static ruleNames=["parse","expr","andOr","eqNeq","term","ident","ownIdent","str","word","number"];get grammarFileName(){return"Restrictions.g4"}get literalNames(){return t.literalNames}get symbolicNames(){return t.symbolicNames}get ruleNames(){return t.ruleNames}get serializedATN(){return t._serializedATN}createFailedPredicateException(e,r){return new zc(this,e,r)}constructor(e){super(e),this._interp=new Yc(this,t._ATN,t.DecisionsToDFA,new Zc)}parse(){let e=new Vr(this,this._ctx,this.state);this.enterRule(e,0,t.RULE_parse);try{this.enterOuterAlt(e,1),this.state=20,this.expr(),this.state=21,this.match(t.EOF)}catch(r){if(r instanceof we)e.exception=r,this._errHandler.reportError(this,r),this._errHandler.recover(this,r);else throw r}finally{this.exitRule()}return e}expr(){let e=new jt(this,this._ctx,this.state);this.enterRule(e,2,t.RULE_expr);try{this.enterOuterAlt(e,1),this.state=23,this.andOr(0)}catch(r){if(r instanceof we)e.exception=r,this._errHandler.reportError(this,r),this._errHandler.recover(this,r);else throw r}finally{this.exitRule()}return e}andOr(e){e===void 0&&(e=0);let r=this._ctx,n=this.state,i=new fe(this,this._ctx,n),o=i,s=4;this.enterRecursionRule(i,4,t.RULE_andOr,e);try{let a;for(this.enterOuterAlt(i,1),i=new zr(this,i),this._ctx=i,o=i,this.state=26,this.eqNeq(0),this._ctx.stop=this._input.LT(-1),this.state=36,this._errHandler.sync(this),a=this._interp.adaptivePredict(this._input,1,this._ctx);a!==2&&a!==ji.INVALID_ALT_NUMBER;){if(a===1)switch(this._parseListeners!=null&&this.triggerExitRuleEvent(),o=i,this.state=34,this._errHandler.sync(this),this._interp.adaptivePredict(this._input,0,this._ctx)){case 1:{if(i=new Yr(this,new fe(this,r,n)),this.pushNewRecursionContext(i,s,t.RULE_andOr),this.state=28,!this.precpred(this._ctx,2))throw this.createFailedPredicateException("this.precpred(this._ctx, 2)");this.state=29,this.match(t.AND),this.state=30,this.eqNeq(0)}break;case 2:{if(i=new Qr(this,new fe(this,r,n)),this.pushNewRecursionContext(i,s,t.RULE_andOr),this.state=31,!this.precpred(this._ctx,1))throw this.createFailedPredicateException("this.precpred(this._ctx, 1)");this.state=32,this.match(t.OR),this.state=33,this.eqNeq(0)}break}this.state=38,this._errHandler.sync(this),a=this._interp.adaptivePredict(this._input,1,this._ctx)}}catch(a){if(a instanceof we)i.exception=a,this._errHandler.reportError(this,a),this._errHandler.recover(this,a);else throw a}finally{this.unrollRecursionContexts(r)}return i}eqNeq(e){e===void 0&&(e=0);let r=this._ctx,n=this.state,i=new Z(this,this._ctx,n),o=i,s=6;this.enterRecursionRule(i,6,t.RULE_eqNeq,e);try{let a;for(this.enterOuterAlt(i,1),i=new tn(this,i),this._ctx=i,o=i,this.state=40,this.term(),this._ctx.stop=this._input.LT(-1),this.state=53,this._errHandler.sync(this),a=this._interp.adaptivePredict(this._input,3,this._ctx);a!==2&&a!==ji.INVALID_ALT_NUMBER;){if(a===1)switch(this._parseListeners!=null&&this.triggerExitRuleEvent(),o=i,this.state=51,this._errHandler.sync(this),this._interp.adaptivePredict(this._input,2,this._ctx)){case 1:{if(i=new en(this,new Z(this,r,n)),this.pushNewRecursionContext(i,s,t.RULE_eqNeq),this.state=42,!this.precpred(this._ctx,3))throw this.createFailedPredicateException("this.precpred(this._ctx, 3)");this.state=43,this.match(t.EQ),this.state=44,this.term()}break;case 2:{if(i=new Xr(this,new Z(this,r,n)),this.pushNewRecursionContext(i,s,t.RULE_eqNeq),this.state=45,!this.precpred(this._ctx,2))throw this.createFailedPredicateException("this.precpred(this._ctx, 2)");this.state=46,this.match(t.NEQ),this.state=47,this.term()}break;case 3:{if(i=new Zr(this,new Z(this,r,n)),this.pushNewRecursionContext(i,s,t.RULE_eqNeq),this.state=48,!this.precpred(this._ctx,1))throw this.createFailedPredicateException("this.precpred(this._ctx, 1)");this.state=49,this.match(t.MATCH),this.state=50,this.term()}break}this.state=55,this._errHandler.sync(this),a=this._interp.adaptivePredict(this._input,3,this._ctx)}}catch(a){if(a instanceof we)i.exception=a,this._errHandler.reportError(this,a),this._errHandler.recover(this,a);else throw a}finally{this.unrollRecursionContexts(r)}return i}term(){let e=new Ke(this,this._ctx,this.state);this.enterRule(e,8,t.RULE_term);try{switch(this.enterOuterAlt(e,1),this.state=64,this._errHandler.sync(this),this._interp.adaptivePredict(this._input,4,this._ctx)){case 1:this.state=56,this.ident();break;case 2:this.state=57,this.ownIdent();break;case 3:this.state=58,this.number_();break;case 4:this.state=59,this.str();break;case 5:this.state=60,this.match(t.LPAREN),this.state=61,this.andOr(0),this.state=62,this.match(t.RPAREN);break}}catch(r){if(r instanceof we)e.exception=r,this._errHandler.reportError(this,r),this._errHandler.recover(this,r);else throw r}finally{this.exitRule()}return e}ident(){let e=new Bt(this,this._ctx,this.state);this.enterRule(e,10,t.RULE_ident);try{this.enterOuterAlt(e,1),this.state=66,this.match(t.DOLLAR),this.state=67,this.word()}catch(r){if(r instanceof we)e.exception=r,this._errHandler.reportError(this,r),this._errHandler.recover(this,r);else throw r}finally{this.exitRule()}return e}ownIdent(){let e=new Kt(this,this._ctx,this.state);this.enterRule(e,12,t.RULE_ownIdent);try{this.enterOuterAlt(e,1),this.state=69,this.match(t.POUND),this.state=70,this.word()}catch(r){if(r instanceof we)e.exception=r,this._errHandler.reportError(this,r),this._errHandler.recover(this,r);else throw r}finally{this.exitRule()}return e}str(){let e=new Vt(this,this._ctx,this.state);this.enterRule(e,14,t.RULE_str);let r;try{this.enterOuterAlt(e,1);{for(this.state=75,this._errHandler.sync(this),r=this._input.LA(1);r===13;)this.state=72,this.match(t.WS),this.state=77,this._errHandler.sync(this),r=this._input.LA(1);this.state=78,this.match(t.STR)}}catch(n){if(n instanceof we)e.exception=n,this._errHandler.reportError(this,n),this._errHandler.recover(this,n);else throw n}finally{this.exitRule()}return e}word(){let e=new wt(this,this._ctx,this.state);this.enterRule(e,16,t.RULE_word);try{this.enterOuterAlt(e,1),this.state=80,this.match(t.WORD)}catch(r){if(r instanceof we)e.exception=r,this._errHandler.reportError(this,r),this._errHandler.recover(this,r);else throw r}finally{this.exitRule()}return e}number_(){let e=new zt(this,this._ctx,this.state);this.enterRule(e,18,t.RULE_number);let r;try{this.enterOuterAlt(e,1);{for(this.state=85,this._errHandler.sync(this),r=this._input.LA(1);r===13;)this.state=82,this.match(t.WS),this.state=87,this._errHandler.sync(this),r=this._input.LA(1);this.state=88,this.match(t.NUMBER)}}catch(n){if(n instanceof we)e.exception=n,this._errHandler.reportError(this,n),this._errHandler.recover(this,n);else throw n}finally{this.exitRule()}return e}sempred(e,r,n){switch(r){case 2:return this.andOr_sempred(e,n);case 3:return this.eqNeq_sempred(e,n)}return!0}andOr_sempred(e,r){switch(r){case 0:return this.precpred(this._ctx,2);case 1:return this.precpred(this._ctx,1)}return!0}eqNeq_sempred(e,r){switch(r){case 2:return this.precpred(this._ctx,3);case 3:return this.precpred(this._ctx,2);case 4:return this.precpred(this._ctx,1)}return!0}static _serializedATN=[4,1,13,91,2,0,7,0,2,1,7,1,2,2,7,2,2,3,7,3,2,4,7,4,2,5,7,5,2,6,7,6,2,7,7,7,2,8,7,8,2,9,7,9,1,0,1,0,1,0,1,1,1,1,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,5,2,35,8,2,10,2,12,2,38,9,2,1,3,1,3,1,3,1,3,1,3,1,3,1,3,1,3,1,3,1,3,1,3,1,3,5,3,52,8,3,10,3,12,3,55,9,3,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,3,4,65,8,4,1,5,1,5,1,5,1,6,1,6,1,6,1,7,5,7,74,8,7,10,7,12,7,77,9,7,1,7,1,7,1,8,1,8,1,9,5,9,84,8,9,10,9,12,9,87,9,9,1,9,1,9,1,9,0,2,4,6,10,0,2,4,6,8,10,12,14,16,18,0,0,91,0,20,1,0,0,0,2,23,1,0,0,0,4,25,1,0,0,0,6,39,1,0,0,0,8,64,1,0,0,0,10,66,1,0,0,0,12,69,1,0,0,0,14,75,1,0,0,0,16,80,1,0,0,0,18,85,1,0,0,0,20,21,3,2,1,0,21,22,5,0,0,1,22,1,1,0,0,0,23,24,3,4,2,0,24,3,1,0,0,0,25,26,6,2,-1,0,26,27,3,6,3,0,27,36,1,0,0,0,28,29,10,2,0,0,29,30,5,2,0,0,30,35,3,6,3,0,31,32,10,1,0,0,32,33,5,1,0,0,33,35,3,6,3,0,34,28,1,0,0,0,34,31,1,0,0,0,35,38,1,0,0,0,36,34,1,0,0,0,36,37,1,0,0,0,37,5,1,0,0,0,38,36,1,0,0,0,39,40,6,3,-1,0,40,41,3,8,4,0,41,53,1,0,0,0,42,43,10,3,0,0,43,44,5,3,0,0,44,52,3,8,4,0,45,46,10,2,0,0,46,47,5,4,0,0,47,52,3,8,4,0,48,49,10,1,0,0,49,50,5,5,0,0,50,52,3,8,4,0,51,42,1,0,0,0,51,45,1,0,0,0,51,48,1,0,0,0,52,55,1,0,0,0,53,51,1,0,0,0,53,54,1,0,0,0,54,7,1,0,0,0,55,53,1,0,0,0,56,65,3,10,5,0,57,65,3,12,6,0,58,65,3,18,9,0,59,65,3,14,7,0,60,61,5,6,0,0,61,62,3,4,2,0,62,63,5,7,0,0,63,65,1,0,0,0,64,56,1,0,0,0,64,57,1,0,0,0,64,58,1,0,0,0,64,59,1,0,0,0,64,60,1,0,0,0,65,9,1,0,0,0,66,67,5,8,0,0,67,68,3,16,8,0,68,11,1,0,0,0,69,70,5,9,0,0,70,71,3,16,8,0,71,13,1,0,0,0,72,74,5,13,0,0,73,72,1,0,0,0,74,77,1,0,0,0,75,73,1,0,0,0,75,76,1,0,0,0,76,78,1,0,0,0,77,75,1,0,0,0,78,79,5,10,0,0,79,15,1,0,0,0,80,81,5,11,0,0,81,17,1,0,0,0,82,84,5,13,0,0,83,82,1,0,0,0,84,87,1,0,0,0,85,83,1,0,0,0,85,86,1,0,0,0,86,88,1,0,0,0,87,85,1,0,0,0,88,89,5,12,0,0,89,19,1,0,0,0,7,34,36,51,53,64,75,85];static __ATN;static get _ATN(){return t.__ATN||(t.__ATN=new Kc().deserialize(t._serializedATN)),t.__ATN}static DecisionsToDFA=t._ATN.decisionToState.map((e,r)=>new Vc(e,r))},Vr=class extends Ie{constructor(e,r,n){super(r,n),this.parser=e}expr(){return this.getTypedRuleContext(jt,0)}EOF(){return this.getToken(M.EOF,0)}get ruleIndex(){return M.RULE_parse}enterRule(e){e.enterParse&&e.enterParse(this)}exitRule(e){e.exitParse&&e.exitParse(this)}accept(e){return e.visitParse?e.visitParse(this):e.visitChildren(this)}},jt=class extends Ie{constructor(e,r,n){super(r,n),this.parser=e}andOr(){return this.getTypedRuleContext(fe,0)}get ruleIndex(){return M.RULE_expr}enterRule(e){e.enterExpr&&e.enterExpr(this)}exitRule(e){e.exitExpr&&e.exitExpr(this)}accept(e){return e.visitExpr?e.visitExpr(this):e.visitChildren(this)}},fe=class extends Ie{constructor(e,r,n){super(r,n),this.parser=e}get ruleIndex(){return M.RULE_andOr}copyFrom(e){super.copyFrom(e)}},zr=class extends fe{constructor(e,r){super(e,r.parentCtx,r.invokingState),super.copyFrom(r)}eqNeq(){return this.getTypedRuleContext(Z,0)}enterRule(e){e.enterAndOrEqNeq&&e.enterAndOrEqNeq(this)}exitRule(e){e.exitAndOrEqNeq&&e.exitAndOrEqNeq(this)}accept(e){return e.visitAndOrEqNeq?e.visitAndOrEqNeq(this):e.visitChildren(this)}},Qr=class extends fe{constructor(e,r){super(e,r.parentCtx,r.invokingState),super.copyFrom(r)}andOr(){return this.getTypedRuleContext(fe,0)}OR(){return this.getToken(M.OR,0)}eqNeq(){return this.getTypedRuleContext(Z,0)}enterRule(e){e.enterOr&&e.enterOr(this)}exitRule(e){e.exitOr&&e.exitOr(this)}accept(e){return e.visitOr?e.visitOr(this):e.visitChildren(this)}},Yr=class extends fe{constructor(e,r){super(e,r.parentCtx,r.invokingState),super.copyFrom(r)}andOr(){return this.getTypedRuleContext(fe,0)}AND(){return this.getToken(M.AND,0)}eqNeq(){return this.getTypedRuleContext(Z,0)}enterRule(e){e.enterAnd&&e.enterAnd(this)}exitRule(e){e.exitAnd&&e.exitAnd(this)}accept(e){return e.visitAnd?e.visitAnd(this):e.visitChildren(this)}},Z=class extends Ie{constructor(e,r,n){super(r,n),this.parser=e}get ruleIndex(){return M.RULE_eqNeq}copyFrom(e){super.copyFrom(e)}},Zr=class extends Z{constructor(e,r){super(e,r.parentCtx,r.invokingState),super.copyFrom(r)}eqNeq(){return this.getTypedRuleContext(Z,0)}MATCH(){return this.getToken(M.MATCH,0)}term(){return this.getTypedRuleContext(Ke,0)}enterRule(e){e.enterMatch&&e.enterMatch(this)}exitRule(e){e.exitMatch&&e.exitMatch(this)}accept(e){return e.visitMatch?e.visitMatch(this):e.visitChildren(this)}},Xr=class extends Z{constructor(e,r){super(e,r.parentCtx,r.invokingState),super.copyFrom(r)}eqNeq(){return this.getTypedRuleContext(Z,0)}NEQ(){return this.getToken(M.NEQ,0)}term(){return this.getTypedRuleContext(Ke,0)}enterRule(e){e.enterNeq&&e.enterNeq(this)}exitRule(e){e.exitNeq&&e.exitNeq(this)}accept(e){return e.visitNeq?e.visitNeq(this):e.visitChildren(this)}},en=class extends Z{constructor(e,r){super(e,r.parentCtx,r.invokingState),super.copyFrom(r)}eqNeq(){return this.getTypedRuleContext(Z,0)}EQ(){return this.getToken(M.EQ,0)}term(){return this.getTypedRuleContext(Ke,0)}enterRule(e){e.enterEq&&e.enterEq(this)}exitRule(e){e.exitEq&&e.exitEq(this)}accept(e){return e.visitEq?e.visitEq(this):e.visitChildren(this)}},tn=class extends Z{constructor(e,r){super(e,r.parentCtx,r.invokingState),super.copyFrom(r)}term(){return this.getTypedRuleContext(Ke,0)}enterRule(e){e.enterEqNeqTerm&&e.enterEqNeqTerm(this)}exitRule(e){e.exitEqNeqTerm&&e.exitEqNeqTerm(this)}accept(e){return e.visitEqNeqTerm?e.visitEqNeqTerm(this):e.visitChildren(this)}},Ke=class extends Ie{constructor(e,r,n){super(r,n),this.parser=e}ident(){return this.getTypedRuleContext(Bt,0)}ownIdent(){return this.getTypedRuleContext(Kt,0)}number_(){return this.getTypedRuleContext(zt,0)}str(){return this.getTypedRuleContext(Vt,0)}LPAREN(){return this.getToken(M.LPAREN,0)}andOr(){return this.getTypedRuleContext(fe,0)}RPAREN(){return this.getToken(M.RPAREN,0)}get ruleIndex(){return M.RULE_term}enterRule(e){e.enterTerm&&e.enterTerm(this)}exitRule(e){e.exitTerm&&e.exitTerm(this)}accept(e){return e.visitTerm?e.visitTerm(this):e.visitChildren(this)}},Bt=class extends Ie{constructor(e,r,n){super(r,n),this.parser=e}DOLLAR(){return this.getToken(M.DOLLAR,0)}word(){return this.getTypedRuleContext(wt,0)}get ruleIndex(){return M.RULE_ident}enterRule(e){e.enterIdent&&e.enterIdent(this)}exitRule(e){e.exitIdent&&e.exitIdent(this)}accept(e){return e.visitIdent?e.visitIdent(this):e.visitChildren(this)}},Kt=class extends Ie{constructor(e,r,n){super(r,n),this.parser=e}POUND(){return this.getToken(M.POUND,0)}word(){return this.getTypedRuleContext(wt,0)}get ruleIndex(){return M.RULE_ownIdent}enterRule(e){e.enterOwnIdent&&e.enterOwnIdent(this)}exitRule(e){e.exitOwnIdent&&e.exitOwnIdent(this)}accept(e){return e.visitOwnIdent?e.visitOwnIdent(this):e.visitChildren(this)}},Vt=class extends Ie{constructor(e,r,n){super(r,n),this.parser=e}STR(){return this.getToken(M.STR,0)}WS_list(){return this.getTokens(M.WS)}WS(e){return this.getToken(M.WS,e)}get ruleIndex(){return M.RULE_str}enterRule(e){e.enterStr&&e.enterStr(this)}exitRule(e){e.exitStr&&e.exitStr(this)}accept(e){return e.visitStr?e.visitStr(this):e.visitChildren(this)}},wt=class extends Ie{constructor(e,r,n){super(r,n),this.parser=e}WORD(){return this.getToken(M.WORD,0)}get ruleIndex(){return M.RULE_word}enterRule(e){e.enterWord&&e.enterWord(this)}exitRule(e){e.exitWord&&e.exitWord(this)}accept(e){return e.visitWord?e.visitWord(this):e.visitChildren(this)}},zt=class extends Ie{constructor(e,r,n){super(r,n),this.parser=e}NUMBER(){return this.getToken(M.NUMBER,0)}WS_list(){return this.getTokens(M.WS)}WS(e){return this.getToken(M.WS,e)}get ruleIndex(){return M.RULE_number}enterRule(e){e.enterNumber&&e.enterNumber(this)}exitRule(e){e.exitNumber&&e.exitNumber(this)}accept(e){return e.visitNumber?e.visitNumber(this):e.visitChildren(this)}};import{ATNDeserializer as ed,DFA as td,Lexer as rd,LexerATNSimulator as nd,PredictionContextCache as id,Token as od}from"antlr4";var It=class t extends rd{static OR=1;static AND=2;static EQ=3;static NEQ=4;static MATCH=5;static LPAREN=6;static RPAREN=7;static DOLLAR=8;static POUND=9;static STR=10;static WORD=11;static NUMBER=12;static WS=13;static EOF=od.EOF;static channelNames=["DEFAULT_TOKEN_CHANNEL","HIDDEN"];static literalNames=[null,"'||'","'&&'","'=='","'!='","'?'","'('","')'","'$'","'#'"];static symbolicNames=[null,"OR","AND","EQ","NEQ","MATCH","LPAREN","RPAREN","DOLLAR","POUND","STR","WORD","NUMBER","WS"];static modeNames=["DEFAULT_MODE"];static ruleNames=["OR","AND","EQ","NEQ","MATCH","LPAREN","RPAREN","DOLLAR","POUND","STR","WORD","NUMBER","WS"];constructor(e){super(e),this._interp=new nd(this,t._ATN,t.DecisionsToDFA,new id)}get grammarFileName(){return"Restrictions.g4"}get literalNames(){return t.literalNames}get symbolicNames(){return t.symbolicNames}get ruleNames(){return t.ruleNames}get serializedATN(){return t._serializedATN}get channelNames(){return t.channelNames}get modeNames(){return t.modeNames}static _serializedATN=[4,0,13,86,6,-1,2,0,7,0,2,1,7,1,2,2,7,2,2,3,7,3,2,4,7,4,2,5,7,5,2,6,7,6,2,7,7,7,2,8,7,8,2,9,7,9,2,10,7,10,2,11,7,11,2,12,7,12,1,0,1,0,1,0,1,1,1,1,1,1,1,2,1,2,1,2,1,3,1,3,1,3,1,4,1,4,1,5,1,5,1,6,1,6,1,7,1,7,1,8,1,8,1,9,1,9,4,9,52,8,9,11,9,12,9,53,1,9,1,9,1,10,4,10,59,8,10,11,10,12,10,60,1,11,3,11,64,8,11,1,11,5,11,67,8,11,10,11,12,11,70,9,11,1,11,3,11,73,8,11,1,11,4,11,76,8,11,11,11,12,11,77,1,12,4,12,81,8,12,11,12,12,12,82,1,12,1,12,0,0,13,1,1,3,2,5,3,7,4,9,5,11,6,13,7,15,8,17,9,19,10,21,11,23,12,25,13,1,0,5,1,0,39,39,4,0,45,45,65,90,95,95,97,122,2,0,43,43,45,45,1,0,48,57,2,0,9,9,32,32,92,0,1,1,0,0,0,0,3,1,0,0,0,0,5,1,0,0,0,0,7,1,0,0,0,0,9,1,0,0,0,0,11,1,0,0,0,0,13,1,0,0,0,0,15,1,0,0,0,0,17,1,0,0,0,0,19,1,0,0,0,0,21,1,0,0,0,0,23,1,0,0,0,0,25,1,0,0,0,1,27,1,0,0,0,3,30,1,0,0,0,5,33,1,0,0,0,7,36,1,0,0,0,9,39,1,0,0,0,11,41,1,0,0,0,13,43,1,0,0,0,15,45,1,0,0,0,17,47,1,0,0,0,19,49,1,0,0,0,21,58,1,0,0,0,23,63,1,0,0,0,25,80,1,0,0,0,27,28,5,124,0,0,28,29,5,124,0,0,29,2,1,0,0,0,30,31,5,38,0,0,31,32,5,38,0,0,32,4,1,0,0,0,33,34,5,61,0,0,34,35,5,61,0,0,35,6,1,0,0,0,36,37,5,33,0,0,37,38,5,61,0,0,38,8,1,0,0,0,39,40,5,63,0,0,40,10,1,0,0,0,41,42,5,40,0,0,42,12,1,0,0,0,43,44,5,41,0,0,44,14,1,0,0,0,45,46,5,36,0,0,46,16,1,0,0,0,47,48,5,35,0,0,48,18,1,0,0,0,49,51,7,0,0,0,50,52,8,0,0,0,51,50,1,0,0,0,52,53,1,0,0,0,53,51,1,0,0,0,53,54,1,0,0,0,54,55,1,0,0,0,55,56,7,0,0,0,56,20,1,0,0,0,57,59,7,1,0,0,58,57,1,0,0,0,59,60,1,0,0,0,60,58,1,0,0,0,60,61,1,0,0,0,61,22,1,0,0,0,62,64,7,2,0,0,63,62,1,0,0,0,63,64,1,0,0,0,64,68,1,0,0,0,65,67,7,3,0,0,66,65,1,0,0,0,67,70,1,0,0,0,68,66,1,0,0,0,68,69,1,0,0,0,69,72,1,0,0,0,70,68,1,0,0,0,71,73,9,0,0,0,72,71,1,0,0,0,72,73,1,0,0,0,73,75,1,0,0,0,74,76,7,3,0,0,75,74,1,0,0,0,76,77,1,0,0,0,77,75,1,0,0,0,77,78,1,0,0,0,78,24,1,0,0,0,79,81,7,4,0,0,80,79,1,0,0,0,81,82,1,0,0,0,82,80,1,0,0,0,82,83,1,0,0,0,83,84,1,0,0,0,84,85,6,12,0,0,85,26,1,0,0,0,8,0,53,60,63,68,72,77,82,1,6,0,0];static __ATN;static get _ATN(){return t.__ATN||(t.__ATN=new ed().deserialize(t._serializedATN)),t.__ATN}static DecisionsToDFA=t._ATN.decisionToState.map((e,r)=>new td(e,r))};import{ParseTreeVisitor as sd}from"antlr4";var Tt=class extends sd{visitParse;visitExpr;visitAndOrEqNeq;visitOr;visitAnd;visitMatch;visitNeq;visitEq;visitEqNeqTerm;visitTerm;visitIdent;visitOwnIdent;visitStr;visitWord;visitNumber};var q=new Tt,tt=t=>{let e=q.visitChildren(t);return e.length==1?e[0]:e};q.visitParse=t=>t.expr().accept(q);q.visitExpr=t=>["expr",tt(t)];q.visitAndOrEqNeq=tt;q.visitEqNeqTerm=tt;q.visitTerm=t=>t.getChildCount()===3?q.visit(t.getChild(1)):tt(t);q.visitEq=t=>{let e=tt(t.eqNeq()),r=t.term().accept(q);return["eq",e,r]};q.visitNeq=t=>{let e=tt(t.eqNeq()),r=t.term().accept(q);return["neq",e,r]};q.visitMatch=t=>["match",q.visitChildren(t.eqNeq())[0],t.term().accept(q)];q.visitAnd=t=>{let e=q.visitChildren(t.andOr()),r=q.visitChildren(t.eqNeq());return["and",e[0],r[0]]};q.visitIdent=t=>["ident",t.word().accept(q)];q.visitOwnIdent=t=>["own-ident",t.word().accept(q)];q.visitWord=t=>["word",t.WORD().symbol.text];q.visitNumber=t=>["number",t.NUMBER().symbol.text];q.visitStr=t=>["str",t.STR().symbol.text.slice(1,-1)];var Bi=q;function Ki(t){let e=ad.fromString(t),r=new It(e),n=new cd(r);return new M(n).parse().accept(Bi)}function rn(t,e){if(Array.isArray(e)){let[r,...n]=e,i=t[r];if(i){let s=n.map(a=>rn(t,a));return i.apply(t,s)}let o=n.map(s=>rn(t,s));return[r].concat(o)}return e}function Vi(t,e,r){return(t?.length??0)>0?rn({and:(n,i)=>n&&i,or:(n,i)=>n||i,eq:(n,i)=>n===i,neq:(n,i)=>n!==i,match:(n,i)=>i&&n?new RegExp(i).test(n):n,str(n){return n},number:n=>JSON.parse(n),expr:n=>n,"own-ident":([n,i])=>e[i],ident([n,i]){return r[i]}},t):!0}function X(t){return typeof t=="string"?t==="cluster"||t==="local"?t:Ki(t):t}function ee(t,e,r){let[n,i]=e,[o,s]=r;switch(t){case"local":{if(n){if(n.type==="local")return o?.type==="local";if(n.type==="peer")return o?.type==="peer"?o?.node===n?.node:!1}else return o===void 0||o.type==="local";return!0}case"cluster":return!0;default:return o?.type==="cluster"?!0:!!Vi(t,i,s)}}if(globalThis.crypto===void 0)throw new Error("Crypto API is not available. If Running Node 18, try --experimental-global-webcrypto.");function Me(t=globalThis.crypto){return t.randomUUID().replaceAll("-","")}function A(t){return t?t.nodeId:Me()}function Pe(t){let e=t.currentId??1,r=`r-${t.nodeId}-${e}`;return[{...t,currentId:e+1},r]}function zi(t){let e=t.currentId??1,r=`i-${t.nodeId}-${e}`;return[{...t,currentId:e+1},r]}function Qt(t){let e=t.currentId??1,r=`c-${t.nodeId}-${e}`;return[{...t,currentId:e+1},r]}function Qi(t){let e=t.currentId??1,r=`a-${t.nodeId}-${e}`;return[{...t,currentId:e+1},r]}function Yi(t){let e=t.currentId??1,r=`p-${t.nodeId}-${e}`;return[{...t,currentId:e+1},r]}import{enableMapSet as ud,produce as Yt}from"immer";ud();function Zt(t,e){let r=e??Me();return{ids:{nodeId:t,currentId:1},signatureKey:r}}function he(t,e,r,n){return Yt(t,i=>{i.peers[e][r]=n?{restrictions:n}:{},i.domains=i.domains||{},i.domains[r]=i.domains[r]||new Set,i.domains[r].add(e)})}function te(t,e,r){return Yt(t,n=>{n.peers&&delete n.peers[e][r],n.domains&&n.domains[r]&&n.domains[r].delete(e)})}function de(t,e,r){return!!t.domains?.[r]?.has(e)}function Zi(t,e){return!!t[e]}function on(t,e,r){return e?Yt(t,n=>{n.gatewayRequests=n.gatewayRequests||{},n.gatewayRequests[e]=r}):t}function rt(t,e){return Yt({state:t},r=>{r.state.gatewayRequests&&(r.removed=r.state.gatewayRequests[e],delete r.state.gatewayRequests[e],Object.keys(r.state.gatewayRequests).length===0&&delete r.state.gatewayRequests)})}function At(t,e){return t.registeredDomains?.[e]?.domain}function ue(t,...e){return e.reduce(([r,n],i)=>{let[o,s]=i(r);return[o,n.concat(s)]},[t,[]])}import{castDraft as an,produce as Ve}from"immer";me();function to(t,e){switch(e.type){case"node":return e.node===t.node;case"peer":return e.node===t.node&&e.peer===t.peer;case"local":return e.receive===t.receive;default:return!1}}function Te(t,e,r){return ne(t,r).filter(n=>to(n.source,e))}function ro(t,e){return fd(t).filter(r=>to(r.source,e))}function B(t,e,r){let n=h(t,e);if(n?.[r])return n}function h(t,e){return e?t.peers?.[e]:void 0}function _(t,e){if(e){let r=h(t,e);if(r)return r;throw V(`Unable to find peer ${e}`,{})}else throw V("Peer id is missing",{})}function R(t,e,r){if(e){let n=B(t,e,r);if(n)return n;throw V(`Unable to find peer ${e} in domain ${r}`,{})}else throw V("Peer id is missing",{})}function $(t){return t?.source.type==="local"}function re(t,e,r){return ee(e?.[t]?.restrictions,[e?.source,e?.identity],[{type:"cluster"},r])}function no(t,e){let r=it(e);return t.identities?.get(r)}function fd(t){return Object.values(t.peers||{})}function ne(t,e){return Array.from(t.domains?.[e]??[],r=>B(t,r,e)).filter(pe)}function cn(t,e,r,n,i,o){let s=h(t,r);if(s)return[t,s];let a=Ve({id:r,identity:n,source:e},c=>{o&&(c.options=o),i&&(c.creationRequest=i)});return[Ve(t,c=>{if(c.users=c.users||{},n.user){c.users.byName=c.users.byName||new Map;let d=c.users.byName.get(n.user);d?d.add(r):c.users.byName.set(n.user,new Set([r]))}else c.users.noUser=c.users.noUser||new Set,c.users.noUser.add(r);c.identities=c.identities||new Map,c.identities.set(it(n),r),c.peers=c.peers||{},c.peers[r]=an(a),o?.service&&(c.services=c.services||new Set,c.services.add(r))}),a]}function io(t,e){let r=e.identity,n=e.id,i=r.user;return Ve(t,o=>{if(o.identities&&o.identities.delete(it(r)),o.users)if(i){let s=o.users.byName?.get(i);s&&(s.delete(n),s.size==0&&o.users.byName?.delete(i)),o.users.byName&&o.users.byName.size===0&&delete o.users.byName}else o.users.noUser?.delete(n),o.users.noUser?.size===0&&delete o.users.noUser;o.peers&&delete o.peers[n],o.services=o.services||new Set,o.services&&o.services.delete(n)})}function C(t,e,r){return Ve(t,n=>{n.peers=n.peers||an({}),n.peers[e]=an(r)})}function Ee(t,e,r){return Ve(t,n=>{n.peers[e]=Ve(n.peers[e],r)})}function Xt(t,e){let[r,n,i,o]=t,[s,a,c,d]=e;if(!i&&!c){let u=a?.user,p=n?.user;return d||o||u===p}else return ee(i,[r,n],[s,a])&&ee(c,[s,a],[r,n])}function ot(t,e,r){return r.id!==e.id&&Xt([e.source,e.identity,e[t]?.restrictions,e.options?.service],[r.source,r.identity,r[t]?.restrictions,r.options?.service])}function eo(t,e,r,n=!1){return ne(t,e).concat(Array.from(t.services??[],i=>h(t,i)).filter(pe)).filter(i=>n&&r.id===i.id||ot(e,r,i))}function ie(t,e,r,n){if(r.options?.service)return eo(t,e,r,n);{let i=r.identity.user;return i?Array.from(t.users?.byName?.get(i)??[]).concat(Array.from(t.services??[])).map(o=>h(t,o)).filter(pe).filter(o=>Zi(o,e)&&ot(e,r,o)||n===!0&&o.id===r.id):eo(t,e,r,n)}}function gd(t,e,r,n,i){let o=i.identity,s=i.id,a=n.id,c=$(n);return Ve(e,d=>{c&&d.push(qe(t,r,a,s,o,{local:c})),$(i)&&d.push(qe(t,i.source,s,a,n.identity,{local:c}))})}function er(t,e,r,n,i){return ie(r,e,i).reduce((o,s)=>gd(t,o,n,i,s),[])}function tr(t,e,r,n,i,o){let s=n.id;return[te(r,s,e),ie(r,e,n).filter($).reduce((a,c)=>(a=a.concat(Je(t,c.source,c.id,s,i)),!o&&$(n)&&(a=a.concat(Je(t,n.source,s,c.id,i))),a),[])]}function hd(t,e){if(t===e)return!0;let r=Object.keys(t);if(r.length!==Object.keys(e).length)return!1;for(let n of r)if(t[n]!==e[n])return!1;return!0}function bd(t,e,r){let{peer_id:n}=r,i=h(t,n);if(i&&!hd(e,i.source))throw V(`The original source ${JSON.stringify(i.source)} of peer ${n} doesnt match the current source ${JSON.stringify(e)}`,{message:"Bad Source"})}var st=g("gateway.node");function Rd(t,e){let r=Object.values(e.registeredDomains).filter(n=>n.info.uri!==Se).map(n=>n.domain);return e.registeredDomains[Se]&&r.push(e.registeredDomains[Se].domain),r.reduce(([n,i],o)=>{st.enabledFor("debug")&&st.debug(`About to remove source from domain ${JSON.stringify(o.info())}`);let s=o.handleMessage(n,t);if(s){st.enabledFor("debug")&&st.debug(`removed source from domain ${JSON.stringify(o.info())}`);let[a,c]=s;return[a,i.concat(c)]}else return[n,i]},[e,[]])}function ze(t,e,r){if(e.body.type==="commands/source-removed")return Rd(e,t);{let{body:n}=e,{registeredDomains:i}=t,o=n.domain??Se,s=i[o]?.domain;if(s)return st.enabledFor("debug")&&st.debug(`Handling message with domain ${JSON.stringify(s.info())} message:
${JSON.stringify(e,null," ")}`),bd(t,r,n),s.handleMessage(t,e);{let a=n;return[t,[b(a.domain,r,a.request_id,a.peer_id,S(Ne,`Unable to find domain for message ${JSON.stringify(e)}`))]]}}}function rr(t){return t.reduce((e,r)=>{let n=r.info(),i={};return i[n.uri]={domain:r,info:n},Object.assign(e,i)},{})}N();me();var dn=class{constructor(e){this.handler=e}close(){}message(e){this.handler(e)}addSource(e){}removeSource(e){let r={origin:"local",source:e,body:{type:"commands/source-removed"}};return this.handler(r)}},De=g("gateway.node.local");function xd(t,e){let{source:r,body:n,origin:i}=e;try{return n.dump?(De.info(`state dump:
${JSON.stringify($e(t),null," ")}`),[t,[]]):i==="cluster"?[t,[]]:ze(t,e,r)}catch(o){De.error(`Error handling message ${JSON.stringify(e)}`,o);let s=n;return[t,[b(void 0,r,s.request_id,s.peer_id,J(o,Ne))]]}}function Sd(t){return"receive"in t&&t.receive}function vd(t){switch(t.receiver.type){case"cluster":return;case"node":return;case"peer":return;case"local":{let{receiver:e,body:r}=t;De.enabledFor("debug")&&De.debug(`Sending message ${JSON.stringify(r,null," ")} to ${JSON.stringify(e)}`),Sd(e)&&e.receive(r);break}default:{De.error(`Unable to process response ${JSON.stringify(t)}`);break}}}function wd(t,e){try{De.enabledFor("trace")&&De.debug(`domain handler processing message ${JSON.stringify(e)}`);let[r,n]=xd(t,e);if(n)for(let i of n)vd(i);return r??t}catch(r){return De.error(`error handling message ${JSON.stringify(e)}`,r),t}}function oo(t,e){let r,n=o=>{try{r=wd(r,o)}catch(s){throw De.error(`Error processing internal message ${JSON.stringify(o)}`,s),s}},i=rr(t);return r=t.reduce((o,s)=>s.init(o),{...Zt(e?.nodeId??A(),e?.signingKey),registeredDomains:i,handler:n}),new dn(n)}var D=Se,un=Ne,so=`${D}.errors.unhandled_message`,pn=`${D}.errors.already_seen`,mn=`${D}.errors.invalid_domain`,Ef=`${D}.errors.invalid_context`,ln=`${D}.errors.authentication.failure`,yn=`${D}.errors.invalid_peer`;N();function ao(t,e,r,n,i,o){let s={domain:D,type:"welcome",request_id:e,peer_id:r,available_domains:n,resolved_identity:i};return o&&(s.options=o),x(t,s)}function co(t,e,r,n,i){let o={domain:t,type:"authentication-request",request_id:r,authentication:i};return n&&(o.peer_id=n),x(e,o)}function at(t,e,r,n,i,o){let s={domain:D,type:"join",request_id:t,peer_id:e,destination:n,identity:i};return r&&(s.restrictions=r),o&&(s.options=o),s}function uo(t){return x(t,{type:"ping"})}var fn={application:{required:!0},instance:{required:!1},region:{required:!1},environment:{required:!1},machine:{required:!1},user:{required:!1}};function Td(t){return Object.keys(fn).find(e=>fn[e]&&fn[e].required&&t[e]===void 0)}function po(t){let e=Td(t);if(e)throw new ve(`Identity ${JSON.stringify(t)} is missing required key: ${e}`,{})}function mo(t,e){let r=t;if(r){let n=r.lastIndexOf(":");if(n!==-1&&(r.startsWith("[")?(r=r.substring(1),r=r.substring(0,r.indexOf("]"))):n===r.indexOf(":")&&(r=r.substring(0,n))),r.indexOf("127.0.0.1")>=0)return e??r}return r??e}import{KJUR as gn}from"jsrsasign";function Ct(t,e){return gn.jws.JWS.sign(null,{alg:"HS256",typ:"JWT"},t,e)}function nr(t,e,r){let n;if(gn.jws.JWS.verifyJWT(t,e,{alg:["HS256"],verifyAt:r?.now}))n=gn.jws.JWS.parse(t);else throw new Error("invalid jwt token");return n.payloadObj}function hn(t,e,r,n){let i={type:"gw-request","impersonate-peer":e,"gw-request":r};return n&&(i.exp=Math.floor(n/1e3)),Ct(i,t.signatureKey)}function lo(t,e,r){let n={type:"authentication",user:e.user};return r&&(n.exp=Math.floor(r/1e3)),Ct(n,t.signatureKey)}function yo(t,e,r){r===void 0&&(r=r??Date.now());let n={};return r&&(n.now=Math.floor(r/1e3)),nr(e,t,n)}import{produce as _d}from"immer";function w(t,e){return{type:"peer",peer:e,node:t}}function _e(t){return{type:"node",node:t}}import{castDraft as zf,produce as Yf}from"immer";function bn(t){return Object.values(t.contexts||{})}N();N();var Ad=g("gateway.action"),fo="info";function E(t,e){let r=Ad.child(t);if(r.enabledFor(fo)){let n=e();r[fo](n)}}me();function Mt(t){return`${t}.errors.not_authorized`}function go(t){return`${t}.errors.bad_lifetime`}function ho(t){return`${t}.errors.invalid_context`}function bo(t){return`${t}.errors.unhandled_message`}function Rn(t){return S(`${t}.destroyed`,"Context destroyed explicitly")}function Ro(t){return S(`${t}.peer-left`,"Context destroyed because its owner/last peer left")}function Ue(t){return`${t}.errors.failure`}function xo(t,e,r,n,i,o){return x(e,{domain:t,type:"subscribed-context",request_id:r,peer_id:n,context_id:i,data:o})}function xn(t,e,r,n,i,o){return x(e,{domain:t,type:"context-added",peer_id:r,creator_id:n,context_id:i,name:o})}function Sn(t,e,r,n,i){let o={domain:t,type:"context-destroyed",peer_id:r,context_id:n,reason_uri:i.uri,reason:i.message};return x(e,o)}function So(t,e,r,n,i){return x(e,{domain:t,type:"context-created",request_id:r,peer_id:n,context_id:i})}function vo(t,e,r,n,i,o){return x(e,{domain:t,type:"context-updated",peer_id:r,updater_id:n,context_id:i,delta:o})}import{castDraft as ct,produce as dt}from"immer";function Io(t){return Object.values(t.contexts||{})}function ir(t,e){return dt(t,r=>{r.contexts=r.contexts||{},r.contexts[e.id]=ct(e)})}function or(t,e){return dt(t,r=>{r.contexts&&(delete r.contexts[e],Object.values(r.contexts).length===0&&delete r.contexts)})}function Qe(t,e,r){let n=r.identity.user,i=r.options?.service,o=Object.values(t.contexts||{}),s;return s=o.find(a=>e===a.name&&a.identity.user===n),s||(s=o.find(a=>e===a.name&&(i||a.options?.service))),s}function He(t,e){if(e)return t.contexts?.[e]}function Pt(t,e,r){let n=e.contexts?.[r];if(n)return n;throw V(`Unable to find context with id ${r}`,{uri:ho(t)})}function ut(t,e,r){return e&&r?e.members.has(r)?t:dt(t,i=>{i.contexts=i.contexts||{},i.contexts[e.id]=ct(dt(e,o=>{o.members=o.members||new Set,o.members.add(r)}))}):t}function sr(t,e,r){return dt([t,e],([n,i])=>{i.members.delete(r),r===i.owner&&delete i.owner,n.contexts=n.contexts||{},n.contexts[e.id]=i})}function To(t,e,r){if(!e)return r;if(e.length===1)t[e[0]]=r;else{let n=t[e[0]];(n===void 0||Array.isArray(n)||typeof n=="number"||typeof n=="boolean")&&(n={}),t[e[0]]=To(n,e.slice(1),r)}return t}function Md(t,e){return{...t,...e}}function Pd(t,e){let[r,n]=e;switch(r){case"removed":{n.forEach(i=>{delete t?.[i]});break}case"added":{t=Object.entries(n).reduce((i,[o,s])=>(i[o]=s,i),t??{});break}case"updated":{t=Object.entries(n).reduce((i,[o,s])=>(Array.isArray(s)&&Array.isArray(i[o])?i[o]=s:s instanceof Object&&i[o]instanceof Object?i[o]=Md(i[o],s):i[o]=s,i),t??{});break}case"reset":{n&&(t=n);break}case"commands":{t=n.reduce((i,o)=>{switch(o.type){case"set":return To(i??{},wo(o.path),o.value);case"remove":{let s=wo(o.path);if(s){let a=i;for(let c=0;c<s.length-1;c++){let d;if(typeof a!="object")return i;d=a?.[s[c]],a=d}a&&delete a[s[s.length-1]]}else return{};return i}}},t);break}}return t}function Ao(t,e,r,n){return dt(t,i=>{i.contexts[e].data=Object.entries(r).reduce((o,[s,a])=>Pd(o,[s,a]),i.contexts[e].data),i.contexts[e].version=n})}function wo(t){if(t)return t.split(".")}function ar(t,e,r,n,i,o,s,a,c){let d=t.identity,u=t.options,p={id:a,data:r??{},identity:d,lifetime:n,read_permissions:i,write_permissions:o,permissions:s,members:new Set,version:c,name:e,creator:t.id};return u&&(ct(p).options=u),p.permissions===void 0&&delete ct(p).permissions,p.read_permission