harperdb 4.7.8 → 4.7.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -15,7 +15,7 @@
15
15
  `)}}});var cq,kl,lq,dc,Gp,Nd,gae,hS,GN=se(()=>{cq=b(us()),kl=b(st());G();lq=b(sr());bd();pS();dc=(0,lq.loggerWithTag)("componentStatus.crossThread"),Gp=class{static{a(this,"CrossThreadStatusCollector")}awaitingResponses=new Map;responseCheckers=new Map;nextRequestId=1;listenerAttached=!1;timeout;cleanupTimer=null;constructor(t=5e3){this.timeout=t}attachListener(){this.listenerAttached||((0,kl.onMessageByType)(b_.COMPONENT_STATUS_RESPONSE,({message:t})=>{let r=t.isMainThread?"main":`worker-${t.workerIndex}`;dc.trace?.("Received component status response from %s, with requestId: %d",r,t.requestId);let n=this.awaitingResponses.get(t.requestId);if(n){n.push({workerIndex:t.workerIndex,isMainThread:t.isMainThread||!1,statuses:t.statuses||[]});let s=this.responseCheckers.get(t.requestId);s&&s()}}),this.listenerAttached=!0)}scheduleCleanup(){this.cleanupTimer&&clearTimeout(this.cleanupTimer),this.awaitingResponses.size>0&&(this.cleanupTimer=setTimeout(()=>{this.awaitingResponses.size>0&&(dc.debug?.(`Cleaning up ${this.awaitingResponses.size} stale pending requests`),this.awaitingResponses.clear()),this.cleanupTimer=null},3e4))}async collect(t){try{this.attachListener(),this.scheduleCleanup();let r=this.nextRequestId++,n=[];this.awaitingResponses.set(r,n);let o=((0,kl.getWorkerCount)()||1)+1-1,l=await new Promise((p,h)=>{let E=!1,_=a(()=>{let y=this.awaitingResponses.get(r);y&&y.length>=o&&!E&&(E=!0,S(),dc.trace?.(`Collected all ${y.length} expected responses for request ${r}`),p(y))},"checkComplete"),R=setTimeout(()=>{if(!E){E=!0;let y=this.awaitingResponses.get(r)||[];this.awaitingResponses.delete(r),dc.debug?.(`Collection timeout for request ${r}: collected ${y.length}/${o} responses`),p(y)}},this.timeout),S=a(()=>{this.awaitingResponses.delete(r),clearTimeout(R)},"cleanup");this.responseCheckers.set(r,_),(0,cq.sendItcEvent)({type:b_.COMPONENT_STATUS_REQUEST,message:{requestId:r}}).then(()=>{_()}).catch(y=>{E=!0,S(),this.responseCheckers.delete(r),h(new Id("sendItcEvent",y))})});this.responseCheckers.delete(r);let u=new Map,d=t.getAllStatuses(),f=(0,kl.getWorkerIndex)(),m=f===void 0?"main":`worker-${f}`;for(let[p,h]of d)u.set(`${p}@${m}`,{...h,workerIndex:f});for(let p of l)for(let[h,E]of p.statuses){let _=p.isMainThread?"main":`worker-${p.workerIndex}`;u.set(`${h}@${_}`,{...E,workerIndex:p.workerIndex})}return dc.debug?.(`Collected component status from ${l.length+1} threads (including local)`),u}catch(r){return r instanceof Id?dc.error?.(`ITC failure during component status collection: ${r.message}`):dc.warn?.("Failed to collect component status from all threads:",r),dc.debug?.(`Collection failed for request. Error: ${r instanceof Error?r.message:"Unknown error"}`),this.getLocalStatusOnly(t)}}getLocalStatusOnly(t){let r=t.getAllStatuses(),n=new Map,s=(0,kl.getWorkerIndex)(),i=s===void 0?"main":`worker-${s}`;for(let[o,c]of r)n.set(`${o}@${i}`,{...c,workerIndex:s});return n}cleanup(){this.awaitingResponses.clear(),this.responseCheckers.clear(),this.cleanupTimer&&(clearTimeout(this.cleanupTimer),this.cleanupTimer=null)}},Nd=class{static{a(this,"StatusAggregator")}static aggregate(t){let r=new Map,n=new Map;for(let[s,i]of t){let o=s.indexOf("@"),c=o!==-1?s.substring(0,o):s,l=n.get(c);l||(l=[],n.set(c,l)),l.push([s,i])}for(let[s,i]of n){let o=this.aggregateComponentGroup(s,i);r.set(s,o)}return r}static aggregateComponentGroup(t,r){let n={workers:{}},s=0,i,o,c=new Map,l=new Map;for(let[m,p]of r){let h=m.lastIndexOf("@"),E=h!==-1?m.substring(h+1):"",_=p.lastChecked instanceof Date?p.lastChecked.getTime():new Date(p.lastChecked).getTime();if(E==="main")n.main=_;else if(E&&E.startsWith("worker-")){let R=parseInt(E.substring(7));isNaN(R)||(n.workers[R]=_)}c.set(p.status,(c.get(p.status)||0)+1),p.status!==Pe.HEALTHY&&p.message&&(!i||_>s)&&(s=_,i=p.message),p.error&&!o&&(o=p.error)}let u=this.determineOverallStatus(c);if(Array.from(c.keys()).length>1)for(let[m,p]of r)p.status!==u&&l.set(m,{workerIndex:p.workerIndex!==void 0?p.workerIndex:-1,status:p.status,message:p.message,error:p.error});let f={componentName:t,status:u,lastChecked:n,latestMessage:i,error:o};return l.size>0&&(f.abnormalities=l),f}static determineOverallStatus(t){let r=[Pe.ERROR,Pe.WARNING,Pe.LOADING,Pe.UNKNOWN,Pe.HEALTHY];for(let n of r)if(t.has(n)&&t.get(n)>0)return n;return Pe.UNKNOWN}},gae=parseInt(process.env.COMPONENT_STATUS_TIMEOUT||"5000"),hS=new Gp(gae)});var fc,ES=se(()=>{BN();bd();GN();pS();fc=class e{static{a(this,"ComponentStatusRegistry")}statusMap=new Map;reset(){this.statusMap=new Map}setStatus(t,r,n,s){if(!t||typeof t!="string")throw new wd(String(t),"setStatus","Component name must be a non-empty string");if(!Object.values(Pe).includes(r))throw new wd(t,"setStatus",`Invalid status level: ${r}. Must be one of: ${Object.values(Pe).join(", ")}`);this.statusMap.set(t,new Ad(r,n,s))}getStatus(t){return this.statusMap.get(t)}getAllStatuses(){return this.statusMap}reportHealthy(t,r){this.setStatus(t,Pe.HEALTHY,r)}reportError(t,r,n){this.setStatus(t,Pe.ERROR,n,r)}reportWarning(t,r){this.setStatus(t,Pe.WARNING,r)}initializeLoading(t,r){this.setStatus(t,Pe.LOADING,r||"Component is loading")}markLoaded(t,r){this.setStatus(t,Pe.HEALTHY,r||"Component loaded successfully")}markFailed(t,r,n){this.setStatus(t,Pe.ERROR,n,r)}getComponentsByStatus(t){let r=[];for(let[n,s]of this.statusMap)s.status===t&&r.push({name:n,status:s});return r}getStatusSummary(){let t={[Pe.HEALTHY]:0,[Pe.ERROR]:0,[Pe.WARNING]:0,[Pe.LOADING]:0,[Pe.UNKNOWN]:0};for(let r of this.statusMap.values())t[r.status]++;return t}static async getAggregatedFromAllThreads(t){let r=await hS.collect(t);return Nd.aggregate(r)}async getAggregatedStatusFor(t,r){r||(r=await e.getAggregatedFromAllThreads(this));let n=[],s=t+".",i=r.get(t);i&&n.push({key:t,...i});for(let[f,m]of r)f.startsWith(s)&&n.push({key:f,...m});if(n.length===0)return{status:Pe.UNKNOWN,message:"The component has not been loaded yet (may need a restart)",lastChecked:{workers:{}}};let o=n.some(f=>f.status===Pe.ERROR),c=n.some(f=>f.status===Pe.LOADING),l=o?Pe.ERROR:c?Pe.LOADING:Pe.HEALTHY,u="All components loaded successfully",d={};if(o||c){u=n.filter(m=>m.status===Pe.ERROR||m.status===Pe.LOADING).map(m=>`${m.key}: ${m.latestMessage||m.status}`).join("; ");for(let m of n)m.status!==Pe.HEALTHY&&(d[m.key]={status:m.status,message:m.latestMessage})}return{status:l,message:u,...Object.keys(d).length>0&&{details:d},lastChecked:n[0]?.lastChecked||{workers:{}}}}}});var hr,_S=se(()=>{ES();hr=new fc});function dq(e){let t=uq.get(e);return t||(t=new qN(e),uq.set(e,t)),t}function fq(){hr.reset()}var qN,uq,co,mq,pq=se(()=>{_S();bd();qN=class{static{a(this,"ComponentStatusBuilder")}componentName;constructor(t){this.componentName=t}healthy(t){return hr.setStatus(this.componentName,Pe.HEALTHY,t),this}warning(t){return hr.setStatus(this.componentName,Pe.WARNING,t),this}error(t,r){return hr.setStatus(this.componentName,Pe.ERROR,t,r),this}loading(t){return hr.setStatus(this.componentName,Pe.LOADING,t||"Loading..."),this}unknown(t){return hr.setStatus(this.componentName,Pe.UNKNOWN,t),this}get(){return hr.getStatus(this.componentName)}},uq=new Map;a(dq,"statusForComponent");co={loading(e,t){hr.initializeLoading(e,t)},loaded(e,t){hr.markLoaded(e,t)},failed(e,t,r){hr.markFailed(e,t,r)}};a(fq,"reset");mq=Pe});var qp={};ye(qp,{AggregationError:()=>kN,COMPONENT_STATUS_LEVELS:()=>Pe,ComponentStatus:()=>Ad,ComponentStatusError:()=>uc,ComponentStatusOperationError:()=>wd,ComponentStatusRegistry:()=>fc,CrossThreadCollectionError:()=>HN,CrossThreadStatusCollector:()=>Gp,CrossThreadTimeoutError:()=>FN,ITCError:()=>Id,StatusAggregator:()=>Nd,componentStatusRegistry:()=>hr,crossThreadCollector:()=>hS,query:()=>Sae});var Sae,hq=se(()=>{_S();ES();BN();ES();GN();_S();pS();bd();Sae={get(e){return hr.getStatus(e)},all(){return hr.getAllStatuses()},byStatus(e){return hr.getComponentsByStatus(e)},summary(){return hr.getStatusSummary()},async allThreads(){return fc.getAggregatedFromAllThreads(hr)}}});var $N={};ye($N,{STATUS:()=>mq,internal:()=>qp,lifecycle:()=>co,reset:()=>fq,statusForComponent:()=>dq});var $p=se(()=>{pq();hq()});var Kp=M((dUe,gq)=>{"use strict";var Es=J(),Tn=(G(),D(j)),Tae=eF(),yae=(hs(),D(ao)),{validateEvent:VN}=us(),Vp=ms(),Rae=require("process"),{resetDatabases:bae}=(Oe(),D(pt)),Aae={[Tn.ITC_EVENT_TYPES.SCHEMA]:Iae,[Tn.ITC_EVENT_TYPES.USER]:_q,[Tn.ITC_EVENT_TYPES.COMPONENT_STATUS_REQUEST]:Nae};async function Iae(e){let t=VN(e);if(t){Es.error(t);return}Es.trace("ITC schemaHandler received schema event:",e),await Tae(e.message),await wae(e.message)}a(Iae,"schemaHandler");async function wae(e){try{Vp.resetReadTxn(Tn.SYSTEM_SCHEMA_NAME,Tn.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME),Vp.resetReadTxn(Tn.SYSTEM_SCHEMA_NAME,Tn.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME),Vp.resetReadTxn(Tn.SYSTEM_SCHEMA_NAME,Tn.SYSTEM_TABLE_NAMES.SCHEMA_TABLE_NAME);let t=bae();e.table&&e.database&&await t[e.database][e.table].put(Symbol.for("write-verify"),null)}catch(t){Es.error(t)}}a(wae,"syncSchemaMetadata");var Eq=[];async function _q(e){try{try{Vp.resetReadTxn(Tn.SYSTEM_SCHEMA_NAME,Tn.SYSTEM_TABLE_NAMES.USER_TABLE_NAME),Vp.resetReadTxn(Tn.SYSTEM_SCHEMA_NAME,Tn.SYSTEM_TABLE_NAMES.ROLE_TABLE_NAME)}catch(r){Es.warn(r)}let t=VN(e);if(t){Es.error(t);return}Es.trace(`ITC userHandler ${Tn.HDB_ITC_CLIENT_PREFIX}${Rae.pid} received user event:`,e),await yae.setUsersWithRolesCache();for(let r of Eq)r()}catch(t){Es.error(t)}}a(_q,"userHandler");_q.addListener=function(e){Eq.push(e)};async function Nae(e){try{let t=VN(e);if(t){Es.error(t);return}Es.trace("ITC componentStatusRequestHandler received request:",e);let{internal:r}=($p(),D($N)),{getWorkerIndex:n}=st(),{sendItcEvent:s}=us(),i=r.componentStatusRegistry.getAllStatuses(),o=Array.from(i.entries()),c=n(),l=c===void 0,u=e.message.originator,d={type:Tn.ITC_EVENT_TYPES.COMPONENT_STATUS_RESPONSE,message:{requestId:e.message.requestId,statuses:o,workerIndex:c,isMainThread:l}};u!==void 0&&threads.sendToThread(u,d)?Es.trace(`Sent component status response directly to thread ${u}`):(u===void 0?Es.debug("No originator threadId, falling back to broadcast"):Es.warn(`Failed to send direct response to thread ${u}, falling back to broadcast`),await s(d))}catch(t){Es.error("Error handling component status request:",t)}}a(Nae,"componentStatusRequestHandler");gq.exports=Aae});var us=M((_Ue,Tq)=>{"use strict";var mUe=J(),KN=ae(),Cae=(G(),D(j)),{ITC_ERRORS:Yp}=Qr(),{parentPort:pUe,threadId:Oae,isMainThread:Pae,workerData:hUe}=require("worker_threads"),{onMessageFromWorkers:Lae,broadcast:EUe,broadcastWithAcknowledgement:Dae}=st();Tq.exports={sendItcEvent:vae,validateEvent:Sq,SchemaEventMsg:Mae,UserEventMsg:Uae};var gS;Lae(async(e,t)=>{gS=gS||Kp(),Sq(e),gS[e.type]&&await gS[e.type](e),e.requestId&&t&&t.postMessage({type:"ack",id:e.requestId})});function vae(e){return!Pae&&e.message&&(e.message.originator=Oae),Dae(e)}a(vae,"sendItcEvent");function Sq(e){if(typeof e!="object")return Yp.INVALID_ITC_DATA_TYPE;if(!e.hasOwnProperty("type")||KN.isEmpty(e.type))return Yp.MISSING_TYPE;if(!e.hasOwnProperty("message")||KN.isEmpty(e.message))return Yp.MISSING_MSG;if(!e.message.hasOwnProperty("originator")||KN.isEmpty(e.message.originator))return Yp.MISSING_ORIGIN;if(Cae.ITC_EVENT_TYPES[e.type.toUpperCase()]===void 0)return Yp.INVALID_EVENT(e.type)}a(Sq,"validateEvent");function Mae(e,t,r,n=void 0,s=void 0){this.originator=e,this.operation=t,this.schema=r,this.table=n,this.attribute=s}a(Mae,"SchemaEventMsg");function Uae(e){this.originator=e}a(Uae,"UserEventMsg")});var ea=M((TUe,Aq)=>{"use strict";var yq=(G(),D(j)),SUe=ae(),SS=J(),Rq=xB(),Cd,{sendItcEvent:bq}=us();function xae(e){try{SS.debug("signalSchemaChange called with message:",e),Cd=Cd||Kp();let t=new Rq(yq.ITC_EVENT_TYPES.SCHEMA,e);return Cd.schema(t),bq(t)}catch(t){SS.error(t)}}a(xae,"signalSchemaChange");function Bae(e){try{SS.trace("signalUserChange called with message:",e),Cd=Cd||Kp();let t=new Rq(yq.ITC_EVENT_TYPES.USER,e);return Cd.user(t),bq(t)}catch(t){SS.error(t)}}a(Bae,"signalUserChange");Aq.exports={signalSchemaChange:xae,signalUserChange:Bae}});function Wp(e,t,r,n){if(e.append)e.append(t,r,n);else if(e.set){let s=e.get(t);if(s)if(n)r=(typeof s=="string"?s:s.join(", "))+", "+r;else if(typeof s=="string")r=[s,r];else{s.push(r);return}return e.set(t,r)}else e[t]=(e[t]?e[t]+", ":"")+r}function Iq(e,t){(typeof e.set!="function"||typeof e.has!="function")&&(e=new Hs(e));for(let[r,n]of t)e.has(r)?r.toLowerCase()==="set-cookie"&&e.append?.(r,n,!0):e.set(r,n);return e}var Hs,jp=se(()=>{Hs=class extends Map{static{a(this,"Headers")}constructor(t){if(t)if(t[Symbol.iterator])super(t);else{super();for(let r in t)this.set(r,t[r])}else super()}set(t,r){return typeof t!="string"&&(t=""+t),typeof r!="string"&&(r=""+r),super.set(t.toLowerCase(),[t,r])}get(t){return typeof t!="string"&&(t=""+t),super.get(t.toLowerCase())?.[1]}has(t){return typeof t!="string"&&(t=""+t),super.has(t.toLowerCase())}setIfNone(t,r){typeof t!="string"&&(t=""+t),typeof r!="string"&&(r=""+r);let n=t.toLowerCase();if(!super.has(n))return super.set(n,[t,r])}append(t,r,n){typeof t!="string"&&(t=""+t),typeof r!="string"&&(r=""+r);let s=t.toLowerCase(),i=super.get(s);if(i){let o=i[1];if(n)r=(typeof o=="string"?o:o.join(", "))+", "+r;else if(typeof o=="string")r=[o,r];else{o.push(r);return}}return super.set(s,[t,r])}*[Symbol.iterator](){for(let[t,r]of super.values()){if(Array.isArray(r)&&t.toLowerCase()==="set-cookie"){for(let n of r)yield[t,n];continue}yield[t,r]}}};a(Wp,"appendHeader");a(Iq,"mergeHeaders")});function TS(e,t,r=kae){let n;return function(...i){return n?n.length*YN>r?t(...i):new Promise((o,c)=>{n.push({args:i,fn(){try{let l=e(...i);o(l)}catch(l){c(l)}}})}):(n=[],s(performance.now(),i),e(...i))};function s(i,o){setImmediate(()=>{let c=performance.now();YN=(YN*4+c-i)/5;let l=n.shift();if(l){let{args:u,fn:d}=l;d(),s(c,u)}else n=null})}}var Cq,Fae,kae,wq,Hae,WN,Nq,YN,jN=se(()=>{Cq=b(sr()),Fae=3e3,kae=2e4,wq=0,Hae=3e4,WN=3e3,Nq=performance.now()+WN,YN=0;a(TS,"throttle");setInterval(()=>{let e=performance.now();e-Nq-WN>Fae&&wq+Hae<e&&(Cq.default.warn?.("JavaScript execution has taken too long and is not allowing proper event queue cycling, consider using 'await new Promise(setImmediate)' in code that will execute for a long duration"),wq=e),Nq=e},WN).unref()});var kq={};ye(kq,{EVICTED:()=>Tl,INVALIDATED:()=>kn,coerceType:()=>RS,makeTable:()=>bS});function bS(e){let{primaryKey:t,indices:r,tableId:n,tableName:s,primaryStore:i,databasePath:o,databaseName:c,auditStore:l,schemaDefined:u,dbisDB:d,sealed:f,splitSegments:m,replicate:p}=e,{expirationMS:h,evictionMS:E,audit:_,trackDeletes:R}=e;E??=0;let{attributes:S}=e;S||(S=[]);let y=NI(i,n,l),w,I,H={},X=Promise.resolve(),q,k,z;for(let K of S)(K.assignCreatedTime||K.name==="__createdtime__")&&(q=K),(K.assignUpdatedTime||K.name==="__updatedtime__")&&(k=K),K.expiresAt&&(z=K),K.isPrimaryKey&&(H=K);let Y,ce=[],de=[],te=1,Se=2,Ne={},Ke={},$e=864e5,Ir=0,nr,zr,xr,Lu=!1,Qc,Ft,Ps,Ga=Gl.get(x.REPLICATION_DATABASES);if(Array.isArray(Ga)){for(let K of Ga)if(K.name===c&&K.replicateTo>=0){Ps=K.replicateTo;break}}let l_=i.getRange({start:!1,end:!1}).constructor,lm=10,u_=6;_&&pm(),zm(i.env.path,K=>{if(I)return $a(K)});class um extends Pl{static{a(this,"Updatable")}getUpdatedTime(){return tc.get(this.getRecord())?.version}getExpiresAt(){return tc.get(this.getRecord())?.expiresAt}addTo(g,T){if(typeof T=="number"||typeof T=="bigint")this.set(g,new Op(T));else throw new Error("Can not add or subtract a non-numeric value")}subtractFrom(g,T){return this.addTo(g,-T)}}class ve extends Xt{#e;#t;#n;#r;#s;#i;static name=s;static primaryStore=i;static auditStore=l;static primaryKey=t;static tableName=s;static tableId=n;static indices=r;static audit=_;static databasePath=o;static databaseName=c;static attributes=S;static replicate=p;static sealed=f;static splitSegments=m??!0;static createdTimeProperty=q;static updatedTimeProperty=k;static propertyResolvers;static userResolvers={};static sources=[];static getResidencyById;static get expirationMS(){return h}static dbisDB=d;static schemaDefined=u;static sourcedFrom(g,T){if(T&&(this.sourceOptions=T,(T.expiration||T.eviction||T.scanInterval)&&this.setTTLExpiration(T)),T?.intermediateSource)g.intermediateSource=!0,this.sources.unshift(g);else{if(this.sources.some(v=>!v.intermediateSource)){if(this.sources.some(v=>v.name===g.name))return;throw new Error("Can not have multiple canonical (non-intermediate) sources")}this.sources.push(g)}I=I||g.get&&(!g.get.reliesOnPrototype||g.prototype.get),w=w||g.load;let C=a(v=>{let A=this.sources;if(A=A.filter(U=>U.intermediateSource&&U[v]&&(!U[v].reliesOnPrototype||U.prototype[v])),A.length>0)if(A.length===1){let U=A[0];return(N,L,$)=>{if(N?.source!==U)return U[v](L,$,N)}}else return(U,N,L)=>{let $=[];for(let W of A){if(U?.source===W)break;$.push(W[v](N,L,U))}return Promise.all($)}},"getApplyToIntermediateSource"),P=this.sources[this.sources.length-1];P.intermediateSource&&(P={});let O=a(v=>{if(P[v]&&(!P[v].reliesOnPrototype||P.prototype[v]))return(A,U,N)=>{if(!A?.source)return P[v](U,N,A)}},"getApplyToCanonicalSource");Ne={put:O("put"),patch:O("patch"),delete:O("delete"),publish:O("publish")},Ke={put:C("put"),patch:C("patch"),delete:C("delete"),publish:C("publish"),invalidate:C("invalidate")};let B=P.shouldRevalidateEvents;return(async()=>{let v=!1,A,U=a(async(N,L)=>{let $=N.value,W=N.table?Me[c][N.table]:ve;if(c===gm&&(N.table===Bu.ROLE_TABLE_NAME||N.table===Bu.USER_TABLE_NAME)&&(v=!0),N.id===void 0&&(N.id=$[W.primaryKey],N.id===void 0))throw new Error("Replication message without an id "+JSON.stringify(N));N.source=g;let Q={residencyId:Jc(N.residencyList),isNotification:!0,ensureLoaded:!1,nodeId:N.nodeId,async:!0},F=N.id,he=await W.getResource(F,L,Q);switch(N.finished&&await N.finished,N.type){case"put":return B?he._writeInvalidate(F,$,Q):he._writeUpdate(F,$,!0,Q);case"patch":return B?he._writeInvalidate(F,$,Q):he._writeUpdate(F,$,!1,Q);case"delete":return he._writeDelete(F,Q);case"publish":case"message":return he._writePublish(F,$,Q);case"invalidate":return he._writeInvalidate(F,$,Q);case"relocate":return he._writeRelocate(F,Q);default:Fe.default.error?.("Unknown operation",N.type,N.id)}},"writeUpdate");try{let N=g.subscribe;N&&R==null&&(R=!0);let L={crossThreads:!1,inTransactionUpdates:!0,supportsTransactions:!0,omitCurrent:!0},$=g.subscribeOnThisThread?g.subscribeOnThisThread((0,Hl.getWorkerIndex)(),L):(0,Hl.getWorkerIndex)()===0,W=N&&$&&await g.subscribe?.(L);if(W){let Q;for await(let F of W)try{if(!(F.type==="transaction"?F.writes[0]:F)){Fe.default.error?.("Bad subscription event",F);continue}if(F.source=g,F.type==="end_txn"){Q?.resolve();let _e;if(F.localTime&&A!==F.localTime&&F.remoteNodeIds?.length>0&&(_e=a(()=>{let re=[Symbol.for("seq"),F.remoteNodeIds[0]],oe=d.get(re),ge=oe?.nodes;ge||(ge=[]);for(let ie of F.remoteNodeIds.slice(1)){let Ce=ge.find(Be=>Be.id===ie);ge=ge.filter(Be=>Be.id!==ie||Be===Ce),Ce||(Ce={id:ie,seqId:0},ge.push(Ce)),Ce.seqId=Math.max(oe?.seqId??1,F.localTime),ie===Q?.nodeId&&(Ce.lastTxnTime=F.timestamp)}let me=Math.max(oe?.seqId??1,F.localTime);Fe.default.trace?.("Received txn",c,me,new Date(me),F.localTime,new Date(F.localTime),F.remoteNodeIds),d.put(re,{seqId:me,nodes:ge})},"updateRecordedSequenceId"),A=F.localTime),F.onCommit){let re=Q?Q.committed.then(F.onCommit):F.onCommit();_e&&(re?.then?re.then(_e):_e())}else _e&&_e();continue}if(Q)if(F.beginTxn)Q.resolve();else{Q.writePromises.push(U(F,Q));continue}!F.timestamp&&F.version&&(F.timestamp=F.version);let ue=At(F,()=>{if(F.type==="transaction"){let _e=[];for(let re of F.writes)try{_e.push(U(re,F))}catch(oe){throw oe.message+=" writing "+JSON.stringify(re)+" of event "+JSON.stringify(F),oe}return Promise.all(_e)}else if(F.type==="define_schema"){let _e=this.attributes.slice(0),re=!1;for(let oe of F.attributes)_e.find(ge=>ge.name===oe.name)||(_e.push(oe),re=!0);re&&(ze({table:s,database:c,attributes:_e,origin:"cluster"}),Qp.signalSchemaChange(new Jp.SchemaEventMsg(process.pid,V.CREATE_TABLE,c,s)))}else return F.beginTxn?(Q=F,Q.writePromises=[U(F,F)],new Promise(_e=>{Q.resolve=()=>_e(Promise.all(Q.writePromises))})):U(F,F)});Q&&(Q.committed=ue),v&&ue&&!ue?.waitingForUserChange&&(ue.then(()=>Qp.signalUserChange(new Jp.UserEventMsg(process.pid))),ue.waitingForUserChange=!0),F.onCommit&&(ue?ue.then(F.onCommit):F.onCommit())}catch(he){Fe.default.error?.("error in subscription handler",he)}}}catch(N){Fe.default.error?.(N)}})(),this}static get isCaching(){return I}static get shouldRevalidateEvents(){return this.prototype.get!==ve.prototype.get}static getResource(g,T,C){let P=super.getResource(g,T,C);if(this.loadAsInstance===!1&&(T._freezeRecords=!0),g!=null&&this.loadAsInstance!==!1){Gi(g);try{if(P.getRecord?.())return P;if(typeof g=="object"&&g&&!Array.isArray(g))throw new Error(`Invalid id ${JSON.stringify(g)}`);let O=!C?.async||i.cache?.get?.(g),B=Br(T),v=B.getReadTxn();if(v?.isDone)throw new Error("You can not read from a transaction that has already been committed/aborted");return Fo(g,T,{transaction:v,ensureLoaded:C?.ensureLoaded},O,A=>{if(A?ve._updateResource(P,A):P.#e=null,T.onlyIfCached){if(!P.doesExist())throw new dt.ServerError("Entry is not cached",504)}else if(C?.ensureLoaded){let U=pn(g,A,T,P);if(U)return B?.disregardReadTxn(),P.#i=!0,T.loadedFromSource=!0,Gs(U,N=>(ve._updateResource(P,N),P))}return P})}catch(O){throw O.message.includes("Unable to serialize object")&&(O.message+=": "+JSON.stringify(g)),O}}return P}static _updateResource(g,T){g.#r=T,g.#e=T?.value??null,g.#n=T?.version}ensureLoaded(){let g=pn(this.getId(),this.#r,this.getContext());if(g)return this.#i=!0,this.getContext().loadedFromSource=!0,Gs(g,T=>{this.#r=T,this.#e=T.value,this.#n=T.version})}static getNewId(){let g=H?.type;if(g==="String"||g==="ID")return super.getNewId();if(!Ft){let O=i.getEntry(Symbol.for("id_allocation")),B=O?.value,v;if(B&&B.nodeName===server.hostname&&(!Xae(i)||B.pid===process.pid)){let A=B.start,U=B.end;v=A;for(let N of i.getKeys({start:U,end:A,limit:1,reverse:!0}))v=N}else B=P(O?.version??null),v=B.start;Ft=new BigInt64Array([BigInt(v)+1n]),Ft=new BigInt64Array(i.getUserSharedBuffer("id",Ft.buffer)),Ft.maxSafeId=B.end}let T=Number(Atomics.add(Ft,0,1n)),C=g==="Int"?512:1048576;if(T+C>=Ft.maxSafeId){let O=a(B=>{Ft.maxSafeId=T+(g==="Int"?1023:4194303);let v=(g==="Int"?Math.pow(2,31):Math.pow(2,49))-1,A=B?void 0:i.useReadTransaction(),U=Number(Ft[0]);for(let $ of i.getKeys({start:U+1,end:v,limit:1,transaction:A}))v=$;A?.done();let{value:N,version:L}=i.getEntry(Symbol.for("id_allocation"));if(Ft.maxSafeId<v){if(N.end>Ft.maxSafeId-100)return;Fe.default.info?.("New id allocation",T,Ft.maxSafeId,L),i.put(Symbol.for("id_allocation"),{start:N.start,end:Ft.maxSafeId,nodeName:server.hostname,pid:process.pid},Date.now(),L)}else{Fe.default.warn?.(`Id conflict detected, starting new id allocation range, attempting to allocate to ${Ft.maxSafeId}, but id of ${v} detected`);let $=P(L);$.alreadyUpdated||Atomics.store(Ft,0,BigInt($.start+1)),Ft.maxSafeId=$.end}},"updateEnd");T+C===Ft.maxSafeId?setImmediate(O):T+100>=Ft.maxSafeId&&(Fe.default.warn?.(`Synchronous id allocation required on table ${s}${g=="Int"?", it is highly recommended that you use Long or Float as the type for auto-incremented primary keys":""}`),i.transactionSync(()=>O(!0)))}return T;function P(O){let B=(g==="Int"?Math.pow(2,31):Math.pow(2,49))-1,v=B/4,A,U,N=!1,L,$;do{L=Math.floor(Math.random()*B),$={start:L,end:L+(g==="Int"?1024:4194304),nodeName:server.hostname,pid:process.pid},A=0;for(let W of i.getKeys({start:L,limit:1,reverse:!0}))A=W;U=B;for(let W of i.getKeys({start:L+1,end:B,limit:1}))U=W;v*=.875,v<1e3&&!N&&(N=!0,Fe.default.error?.(`Id allocation in table ${s} is very dense, limited safe range of numbers to allocate ids in${g==="Int"?", it is highly recommended that you use Long or Float as the type for auto-incremented primary keys":""}`,L,A,U,v))}while(!(v<U-L&&(v<L-A||A===0)));return i.transactionSync(()=>{let W=i.getEntry(Symbol.for("id_allocation"));return(W?.version??null)==O?(Fe.default.info?.("Allocated new id range",$),i.put(Symbol.for("id_allocation"),$,Date.now()),$):(Fe.default.debug?.("Looks like ids were already allocated"),{alreadyUpdated:!0,...W.value})})}}static setTTLExpiration(g){if(typeof g=="number")h=g*1e3,E||(E=0);else if(g&&typeof g=="object")h=g.expiration*1e3,E=(g.eviction||0)*1e3,$e=g.scanInterval*1e3;else throw new Error("Invalid expiration value type");if(h<0)throw new Error("Expiration can not be negative");$e=$e||(h+E)/4,$a()}static getResidencyRecord(g){return d.get([Symbol.for("residency_by_id"),g])}static setResidency(g){ve.getResidency=g&&((T,C)=>{try{return g(T,C)}catch(P){throw P.message+=` in residency function for table ${s}`,P}})}static setResidencyById(g){ve.getResidencyById=g&&(T=>{try{return g(T)}catch(C){throw C.message+=` in residency function for table ${s}`,C}})}static getResidency(g,T){if(ve.getResidencyById)return ve.getResidencyById(g[t]);let C=Ps;if(T.replicateTo!=null){if(Array.isArray(T.replicateTo))return T.replicateTo.includes(server.hostname)?T.replicateTo:[server.hostname,...T.replicateTo];T.replicateTo>=0&&(C=T.replicateTo)}if(C>=0&&server.nodes){let P=[server.hostname];if(T.previousResidency)P.push(...T.previousResidency.slice(0,C));else{let O=server.nodes.map(A=>A.name),B=Math.floor(O.length*Math.random());P.push(...O.slice(B,B+C));let v=B+C-O.length;v>0&&P.push(...O.slice(0,v))}return P}}static enableAuditing(){_||(_=!0,pm(),ve.audit=!0)}static coerceId(g){return g===""?null:RS(g,H)}static async dropTable(){delete Me[c][s];for(let g of i.getRange({versions:!0,snapshot:!1,lazy:!0}))g.metadataFlags&Zr&&g.value&&Xa(g.value);if(c===o){for(let g of S)d.remove(ve.tableName+"/"+g.name),r[g.name]?.drop();d.remove(ve.tableName+"/"),i.drop(),await d.committed}else console.log("legacy dropTable"),await i.close(),QN.default.unlinkSync(i.env.path);Qp.signalSchemaChange(new Jp.SchemaEventMsg(process.pid,V.DROP_TABLE,c,s))}get(g){let T=this.constructor;if(typeof g=="string"&&T.loadAsInstance!==!1)return this.getProperty(g);if(dm(g))return this.search(g);if(g&&g.id===void 0&&!g.toString()){let C={records:"./",name:s,database:c,auditSize:l?.getStats().entryCount,attributes:S,recordCount:void 0,estimatedRecordRange:void 0};return this.getContext()?.includeExpensiveRecordCountEstimates?ve.getRecordCount().then(P=>(C.recordCount=P.recordCount,C.estimatedRecordRange=P.estimatedRange,C)):C}if(g!==void 0&&T.loadAsInstance===!1){let C=this.getContext(),P=Br(C),O=P.getReadTxn();if(O?.isDone)throw new Error("You can not read from a transaction that has already been committed/aborted");let B=Ls(g);Gi(B);let v=!0;return g.checkPermission&&(v=this.allowRead(C.user,g)),Gs(Gs(v,A=>{if(!A)throw new dt.AccessViolation(C.user);let U=!0;return Fo(B,C,{transaction:O,ensureLoaded:U},!1,N=>{if(C.onlyIfCached){if(!N?.value)throw new dt.ServerError("Entry is not cached",504)}else if(U){let L=pn(B,N,C);if(L)return P?.disregardReadTxn(),C.loadedFromSource=!0,L.then($=>$?.value)}return N?.value})}),A=>{let U=g?.select;return U&&A!=null?od(U,this.constructor)(A):A})}if(g?.property)return this.getProperty(g.property);if(this.doesExist()||g?.ensureLoaded===!1||this.getContext()?.returnNonexistent)return this}allowRead(g,T){let C=Dn(g,T);if(C?.read){if(C.isSuperUser)return!0;let P=C.attribute_permissions,O=T?.select;if(P?.length>0||Lu&&O){if(T||(T={}),O){let B=Array.isArray(O)?O:[O],v=P?.length>0&&zN(P,"read");T.select=B.map(A=>{let U=A.name||A;if(!v||v[U]){let N=xr[U]?.definition?.tableClass;if(N){if(A.name||(A={name:A}),!A.checkPermission&&T.checkPermission&&(A.checkPermission=T.checkPermission),!N.prototype.allowRead.call(null,g,A))return!1;if(!A.select)return A.name}return A}}).filter(Boolean)}else T.select=P.filter(B=>B.read&&!xr[B.attribute_name]).map(B=>B.attribute_name);return T}else return!0}}allowUpdate(g,T,C){let P=Dn(g,C);if(P?.update){let O=P.attribute_permissions;if(O?.length>0){let B=zN(O,"update");for(let v in T)if(!B[v])return!1;for(let v of O){let A=v.attribute_name;!v.update&&!(A in T)&&(T[A]=this.getProperty(A))}}return qa(this.getContext())}}allowCreate(g,T,C){if(this.isCollection){let P=Dn(g,C);if(P?.insert){let O=P.attribute_permissions;if(O?.length>0){let B=zN(O,"insert");for(let v in T)if(!B[v])return!1;return qa(this.getContext())}else return qa(this.getContext())}}else return this.allowUpdate(g,{})}allowDelete(g,T){return Dn(g,T)?.delete&&qa(this.getContext())}update(g,T){let C,P=typeof T=="boolean"||T===void 0&&(g==null||typeof g=="object"&&!(g instanceof URLSearchParams)),O=!1;P?(O=T,T=g,C=this.getId()):C=Ls(g);let B=this.getContext();if(!Br(B))throw new Error("Can not update a table resource outside of a transaction");if(T===!1)return this;if(typeof T=="object"&&T)if(O)Object.isFrozen(T)&&(T={...T}),this.#e={},this.#t=T;else if(P){let A=this.#t;A&&(T=Object.assign(A,T)),this.#t=T}else{let A=!0;if(g==null)throw new TypeError("Can not put a record without a target");return g.checkPermission&&(A=this.allowUpdate(B.user,T,g)),Gs(A,U=>{if(!U)throw new dt.AccessViolation(B.user);return Gs(i.get(Ls(g)),N=>{let L=new um(N);return L._setChanges(T),this._writeUpdate(C,L.getChanges(),!1),L})})}return this._writeUpdate(C,this.#t,O),this}addTo(g,T){if(typeof T=="number"||typeof T=="bigint")this.#s===Pq?this.set(g,(+this.getProperty(g)||0)+T):(this.#s||this.update(),this.set(g,new Op(T)));else throw new Error("Can not add a non-numeric value")}subtractFrom(g,T){if(typeof T=="number")return this.addTo(g,-T);throw new Error("Can not subtract a non-numeric value")}getMetadata(){return this.#r}getRecord(){return this.#e}getChanges(){return this.#t}_setChanges(g){this.#t=g}setRecord(g){this.#e=g}invalidate(g){let T=!0,C=this.getContext();return g?.checkPermission&&(T=this.allowDelete(C.user,g,C)),Gs(T,P=>{if(!P)throw new dt.AccessViolation(C.user);this._writeInvalidate(g?Ls(g):this.getId())})}_writeInvalidate(g,T,C){let P=this.getContext();Gi(g),Br(this.getContext()).addWrite({key:g,store:i,invalidated:!0,entry:this.#r,before:Ne.invalidate?.bind(this,P,g),beforeIntermediate:Uu(T,Ke.invalidate?.bind(this,P,g)),commit:a((B,v)=>{if(!(Fr(B,v,C?.nodeId)<=0)){T??=null;for(let A in r)T||(T={}),T[A]===void 0&&(T[A]=this.getProperty(A));Fe.default.trace?.(`Invalidating entry in ${s} id: ${g}, timestamp: ${new Date(B).toISOString()}`),y(g,T,v,B,kn,_,{user:P?.user,residencyId:C?.residencyId,nodeId:C?.nodeId,tableToTrack:s},"invalidate")}},"commit")})}_writeRelocate(g,T){let C=this.getContext();Gi(g),Br(this.getContext()).addWrite({key:g,store:i,invalidated:!0,entry:this.#r,before:Ne.relocate?.bind(this,C,g),beforeIntermediate:Ke.relocate?.bind(this,C,g),commit:a((O,B)=>{if(Fr(O,B,T?.nodeId)<=0)return;let v=ve.getResidencyRecord(T.residencyId),A=0,U=null,N=B?.value;if(v&&!v.includes(server.hostname)){for(let L in r)U||(U={}),U[L]=N[L];A=kn}else U=N;Fe.default.trace?.(`Relocating entry id: ${g}, timestamp: ${new Date(O).toISOString()}`),y(g,U,B,O,A,_,{user:C.user,residencyId:T.residencyId,nodeId:T.nodeId,expiresAt:T.expiresAt},"relocate",!1,null)},"commit")})}static _recordRelocate(g,T){if(this.getResidencyById)return!1;let C={previousResidency:this.getResidencyRecord(g.residencyId),isRelocation:!0},P=Va(this.getResidency(T.value,C)),O;if(P){if(!P.includes(server.hostname))return!1;O=Jc(P)}let B=0;Fe.default.debug?.("Performing a relocate of an entry",g.key,T.value,P);let v=y(g.key,T.value,g,g.version,B,!0,{residencyId:O,expiresAt:T.expiresAt},"relocate",!1,null);return!0}static evict(g,T,C){let P=this.Source,O;if(!((I||_)&&(!T||(O=i.getEntry(g),!O||!T)||O.version!==C))){if(I){if(i.hasLock(g,O.version))return;let B;for(let v in r)B||(B={}),B[v]=T[v];if(B)return y(g,B,O,C,Tl,null,null,null,!0)}return i.ifVersion(g,C,()=>{Du(g,T,null)}),Sl(i,O??i.getEntry(g),C)}}lock(){throw new Error("Not yet implemented")}static operation(g,T){return g.table||=s,g.schema||=c,global.operation(g,T)}put(g,T){if(T===void 0||T instanceof URLSearchParams)this.update(g,!0);else{let C=!0;if(g==null)throw new TypeError("Can not put a record without a target");let P=this.getContext();return g.checkPermission&&(C=this.allowUpdate(P.user,T,g)),Gs(C,O=>{if(!O)throw new dt.AccessViolation(P.user);if(Array.isArray(T))for(let B of T){let v=B[t];this._writeUpdate(v,B,!0)}else{let B=Ls(g);this._writeUpdate(B,T,!0)}})}}create(g,T){let C=!0,P=this.getContext();if(!T&&!(g instanceof URLSearchParams)&&(T=g,g=void 0),!T||typeof T!="object"||Array.isArray(T))throw new TypeError("Can not create a record without an object");return g?.checkPermission&&(C=this.allowCreate(P.user,T,g)),Gs(C,O=>{if(!O)throw new dt.AccessViolation(P.user);let B=Ls(g)??T[t];if(B===void 0)B=this.constructor.getNewId(),T[t]=B;else if(i.get(B))throw new dt.ClientError("Record already exists",409);return this._writeUpdate(B,T,!0),T})}patch(g,T){if(T===void 0||T instanceof URLSearchParams)this.update(g,!1);else{let C=this.update(g,T);if(C?.then)return C.then(()=>{})}}_writeUpdate(g,T,C,P){let O=this.getContext(),B=Br(O);Gi(g);let v=this.#r??i.getEntry(g);this.#s=C?Pq:jae;let A=a(N=>C?N.put?()=>N.put(O,g,T):null:N.patch?()=>N.patch(O,g,T):N.put?()=>N.put(O,g,Ll(this)):null,"writeToSources"),U={key:g,store:i,entry:v,nodeName:O?.nodeName,validate:a(N=>{T||(T=this.#t),C||T&&Zg(this.#t===T?this:T)?O?.source||(B.checkOverloaded(),this.validate(T,!C),k&&(T[k.name]=k.type==="Date"?new Date(N):k.type==="String"?new Date(N).toISOString():N),C&&(t&&T[t]!==g&&(T[t]=g),q&&(v?.value?T[q.name]=v?.value[q.name]:T[q.name]=q.type==="Date"?new Date(N):q.type==="String"?new Date(N).toISOString():N),T=Ll(T))):B.removeWrite(U)},"validate"),before:A(Ne),beforeIntermediate:Uu(T,A(Ke)),commit:a((N,L,$)=>{if($){if(O&&L?.version>(O.lastModified||0)&&(O.lastModified=L.version),this.#r=L,L?.value&&L.value.getRecord)throw new Error("Can not assign a record to a record, check for circular references");C||(this.#e=L?.value??null)}this.#t=void 0,this.#n=N;let W=L?.value,Q;this.#s=0;let F=!1,he=Fr(N,L,P?.nodeId),ue,_e=C?"put":"patch",re;P?.residencyId!=null&&(re=P.residencyId);let oe=O?.expiresAt??(h?h+Date.now():-1);if(he<=0){if(_){let ie=L.localTime,Ce=L.version;Fe.default.trace?.("Applying CRDT update to record with id: ",g,"txn time",new Date(N),"applying later update from:",new Date(Ce),"local recorded time",new Date(ie));let Be=[];for(;ie>N||Ce>=N&&ie>0;){let He=l.get(ie);if(!He)break;let Te=It(He);if(Ce=Te.version,Ce>=N){if(Ce===N){if(he=Fr(N,{version:Ce,localTime:ie},P?.nodeId),he===0)return me(!1);if(he>0){ie=Te.previousLocalTime;continue}}if(Te.type==="patch")Be.push(Te),ue=T;else if(Te.type==="put"||Te.type==="delete")return me(!1)}ie=Te.previousLocalTime}ie||Fe.default.debug?.("No further audit history, applying incremental updates based on available history",g,"existing version preserved",L),Be.sort((He,Te)=>He.version-Te.version);for(let He of Be){let Te=He.getValue(i);if(Fe.default.debug?.("Rebuilding update with future patch:",new Date(He.version),Te,He),Q=j_(Q??T,Te,C),!Q)return me(!1)}}else{if(C)return me(!1);Q=j_(Q??T,W,C),Fe.default.debug?.("Rebuilding update without audit:",Q)}Fe.default.trace?.("Rebuilt record to save:",Q," is full update:",C)}let ge;if(C&&!Q?ge=T:this.constructor.loadAsInstance===!1?ge=Ll(W,Q??T):(this.#e=W,ge=Ll(this,Q??T)),this.#e=ge,ge&&ge.getRecord)throw new Error("Can not assign a record to a record, check for circular references");if(re==null){v?.residencyId&&(O.previousResidency=ve.getResidencyRecord(v.residencyId));let ie=Va(ve.getResidency(ge,O));if(ie&&!ie.includes(server.hostname))if(ue??=ge,F=!0,ve.getResidencyById)ge=void 0;else{ge=null;for(let Ce in r)ge||(ge={}),ge[Ce]=ue[Ce]}re=Jc(ie)}C||(ue=T),Fe.default.trace?.(`Saving record with id: ${g}, timestamp: ${new Date(N).toISOString()}${oe?", expires at: "+new Date(oe).toISOString():""}${L?", replaces entry from: "+new Date(L.version).toISOString():", new entry"}`,(()=>{try{return JSON.stringify(ge).slice(0,100)}catch{return""}})()),Du(g,W,ge),me(!0),O.expiresAt&&$a();function me(ie){y(g,ie?ge:void 0,ie?L:{...L,value:void 0},N,F?kn:0,_,{omitLocalRecord:F,user:O?.user,residencyId:re,expiresAt:oe,nodeId:P?.nodeId,originatingOperation:O?.originatingOperation,tableToTrack:c==="system"?null:s},_e,!1,ie?ue:ue??T)}a(me,"writeCommit")},"commit")};B.addWrite(U)}async delete(g){if(dm(g)){g.select=["$id"];for await(let T of this.search(g))this._writeDelete(T.$id);return!0}if(g){let T=!0,C=this.getContext();return g.checkPermission&&(T=this.allowDelete(C.user,g,C)),Gs(T,P=>{if(!P)throw new dt.AccessViolation(C.user);let O=Ls(g);return this._writeDelete(O),!0})}return this._writeDelete(this.getId()),!!this.#e}_writeDelete(g,T){let C=Br(this.getContext());Gi(g);let P=this.getContext();return C.addWrite({key:g,store:i,entry:this.#r,nodeName:P?.nodeName,before:Ne.delete?.bind(this,P,g),beforeIntermediate:Ke.delete?.bind(this,P,g),commit:a((O,B,v)=>{let A=B?.value;v&&(P&&B?.version>(P.lastModified||0)&&(P.lastModified=B.version),ve._updateResource(this,B)),!(Fr(O,B,T?.nodeId)<=0)&&(Du(this.getId(),A),Fe.default.trace?.(`Deleting record with id: ${g}, txn timestamp: ${new Date(O).toISOString()}`),_||R?(y(g,null,B,O,0,_,{user:P?.user,nodeId:T?.nodeId,tableToTrack:s},"delete"),_||$a()):Sl(i,B))},"commit")}),!0}search(g){let T=this.getContext(),C=Br(T);if(!g)throw new Error("No query provided");if(g.parseError)throw g.parseError;if(g.checkPermission&&!this.allowRead(T.user,g))throw new dt.AccessViolation(T.user);T&&(T.lastModified=Vae);let P=g.conditions;P?P.length===void 0&&(P=P[Symbol.iterator]?Array.from(P):[P]):P=Array.isArray(g)?g:g[Symbol.iterator]?Array.from(g):[];let O=g.id??this.getId();O&&(P=[{attribute:null,comparator:Array.isArray(O)?"prefix":"starts_with",value:O}].concat(P));let B,v={};function A(oe,ge){let me;switch(ge){case"and":case void 0:if(oe.length<1)throw new Error('An "and" operator requires at least one condition');me=!0;break;case"or":if(oe.length<2)throw new Error('An "or" operator requires at least two conditions');break;default:throw new Error("Invalid operator "+ge)}for(let ie of oe){if(ie.conditions){ie.conditions=A(ie.conditions,ie.operator);continue}let Ce=ie[0]??ie.attribute,Be=Ce==null?H:zi(S,Ce);if(Be)(Be.type||OI[ie.comparator])&&(ie[1]===void 0?ie.value=N(ie.value,Be):ie[1]=N(ie[1],Be));else if(Ce!=null&&!g.allowConditionsOnDynamicAttributes)throw(0,dt.handleHDBError)(new Error,`${Ce} is not a defined attribute`,404);if(ie.chainedConditions)if(ie.chainedConditions.length===1&&(!ie.operator||ie.operator=="and")){let He=ie.chainedConditions[0],Te,ht;if(He.comparator==="gt"||He.comparator==="greater_than"||He.comparator==="ge"||He.comparator==="greater_than_equal"?(Te=ie,ht=He):(Te=He,ht=ie),Te.comparator!=="lt"&&Te.comparator!=="less_than"&&Te.comparator!=="le"&&Te.comparator!=="less_than_equal")throw new Error("Invalid chained condition, only less than and greater than conditions can be chained together");let Ct=ht.comparator==="ge"||ht.comparator==="greater_than_equal",Ot=Te.comparator==="le"||Te.comparator==="less_than_equal";ie.comparator=(Ct?"ge":"gt")+(Ot?"le":"lt"),ie.value=[ht.value,Te.value]}else throw new Error("Multiple chained conditions are not currently supported")}return oe}a(A,"prepareConditions");function U(oe,ge){if(g.enforceExecutionOrder)return oe;for(let me of oe)me.conditions&&(me.conditions=U(me.conditions,me.operator));return oe.length>1&&ge!=="or"?Gae(oe,Cg(ve)):oe}a(U,"orderConditions");function N(oe,ge){return Array.isArray(oe)?oe.map(me=>RS(me,ge)):RS(oe,ge)}a(N,"coerceTypedValues");let L=g.operator;(P.length>0||L)&&(P=A(P,L));let $=typeof g.sort=="object"&&g.sort,W;if($&&L!=="or"){let oe=$.attribute;if(oe==null)throw new dt.ClientError("Sort requires an attribute");if(B=P.find(ge=>nd(ge.attribute)===nd(oe)),!B){let ge=zi(S,oe);if(!ge)throw(0,dt.handleHDBError)(new Error,`${Array.isArray(oe)?oe.join("."):oe} is not a defined attribute`,404);if(ge.indexed)B={...$,comparator:"sort"},P.push(B);else if(P.length===0&&!g.allowFullScan)throw(0,dt.handleHDBError)(new Error,`${Array.isArray(oe)?oe.join("."):oe} is not indexed and not combined with any other conditions`,404)}B&&(B.descending=!!$.descending)}P=U(P,L),$&&(B&&P[0]===B?$.next&&(W={dbOrderedAttribute:$.attribute,attribute:$.next.attribute,descending:$.next.descending,next:$.next.next}):(B&&P.splice(P.indexOf(B),1),W=$));let Q=g.select;if(P.length===0&&(P=[{attribute:t,comparator:"greater_than",value:!0}]),g.explain)return{conditions:P,operator:L,postOrdering:W,selectApplied:!!Q};let F=C.useReadTxn(),he=PI(P,L,ve,F,g,T,(oe,ge)=>mm(oe,Q,T,F,ge),v),ue=g.ensureLoaded!==!1,_e=ve.transformEntryForSelect(Q,T,F,v,ue,!0),re=ve.transformToOrderedSelect(he,Q,W,T,F,_e);return(g.offset||g.limit!==void 0)&&(re=re.slice(g.offset,g.limit!==void 0?(g.offset||0)+g.limit:void 0)),re.onDone=()=>{re.onDone=null,C.doneReadTxn()},re.selectApplied=!0,re.getColumns=()=>{if(Q){let oe=[];for(let ge of Q)ge==="*"?oe.push(...S.map(me=>me.name)):oe.push(ge.name||ge);return oe}return S.filter(oe=>!oe.computed&&!oe.relationship).map(oe=>oe.name)},re}static transformToOrderedSelect(g,T,C,P,O,B){let v=new l_;if(C){g=mm(g,T,P,O,null);let A;v.iterate=function(){let N,L=g[Symbol.asyncIterator]?g[Symbol.asyncIterator]():g[Symbol.iterator](),$,W=C.dbOrderedAttribute,Q,F,he=!0;function ue(re){let oe=re.next&&ue(re.next),ge=re.descending;return P.sort=re,(me,ie)=>{let Ce=vu(me,re.attribute,P),Be=vu(ie,re.attribute,P),He=ge?(0,ql.compareKeys)(Be,Ce):(0,ql.compareKeys)(Ce,Be);return He===0?oe?.(me,ie)||0:He}}a(ue,"createComparator");let _e=ue(C);return{async next(){let re;if(N)if(re=N.next(),re.done){if($)return v.onDone&&v.onDone(),re}else return{value:await B.call(this,re.value)};A=[],Q&&A.push(Q);do if(re=await L.next(),re.done){if($=!0,A.length)break;return v.onDone&&v.onDone(),re}else{let oe=re.value;if(oe?.then&&(oe=await oe),W){let ge=vu(oe,W,P);if(he)he=!1,F=ge;else if(ge!==F){F=ge,Q=oe;break}}A.push(oe)}while(!0);return C.isGrouped,A.sort(_e),N=A[Symbol.iterator](),re=N.next(),re.done?(v.onDone&&v.onDone(),re):{value:await B.call(this,re.value)}},return(){return v.onDone&&v.onDone(),L.return()},throw(){return v.onDone&&v.onDone(),L.throw()}}};let U=a(N=>{if(typeof T=="object"&&Array.isArray(N.attribute))for(let L=0;L<T.length;L++){let $=T[L],W;if($.name===N.attribute[0]){for(W=$.sort||($.sort={});W.next;)W=W.next;W.attribute=N.attribute.slice(1),W.descending=N.descending}else $===N.attribute[0]&&(T[L]=W={name:$,sort:{attribute:N.attribute.slice(1),descending:N.descending}})}N.next&&U(N.next)},"applySortingOnSelect");U(C)}else v.iterate=(g[Symbol.asyncIterator]||g[Symbol.iterator]).bind(g),v=v.map(function(A){try{let U=B.call(this,A);return typeof U?.catch=="function"?U.catch(N=>{throw N.partialObject={[t]:A.key},N}):U}catch(U){throw U.partialObject={[t]:A.key},U}});return v}static transformEntryForSelect(g,T,C,P,O,B){let v;O&&I&&!(typeof g=="string"?[g]:g)?.every(N=>{let L;return typeof N=="object"?L=N.name:L=N,r[L]||L===t})&&(v=!0);let A,U=a(function(N){let L;if(T?.transaction?.stale&&(T.transaction.stale=!1),N!=null){if(L=N.deref?N.deref():N.value,!L&&(N.key===void 0||N.deref)||N.metadataFlags&kn){if(N.metadataFlags&kn&&T.replicateFrom===!1&&B&&N.residencyId)return pc.SKIP;if(N=Fo(N.key??N,T,{transaction:C,lazy:g?.length<4,ensureLoaded:O},this?.isSync,$=>$),N?.then)return N.then(U.bind(this));L=N?.value}if(v&&N?.metadataFlags&(kn|Tl)||N?.expiresAt!=null&&N?.expiresAt<Date.now()){if(T.onlyIfCached)return{[t]:N.key,message:"This entry has expired"};let $=pn(N.key??N,N,T);if($?.then)return $.then(U)}}if(L==null)return B?pc.SKIP:L;if(g&&!(g[0]==="*"&&g.length===1)){let $,W=a((F,he)=>{let ue;typeof F=="object"?ue=F.name:ue=F;let _e=xr?.[ue],re;if(_e){let oe=P?.[ue];if(oe)if(oe.hasMappings){let me=_e.from?L[_e.from]:nd(N.key);re=oe.get(me),re||(re=[])}else re=oe.fromRecord?.(L);else re=_e(L,T,N,!0);let ge=a(me=>{if(_e.directReturn)return he(me,ue);if(me&&typeof me=="object"){let ie=_e.definition?.tableClass||ve;A||(A={});let Ce=A[ue]||(A[ue]=ie.transformEntryForSelect(ue===F?null:F.select||(Array.isArray(F)?F:null),T,C,oe,O));if(Array.isArray(me)){let Be=[],He=ie.transformToOrderedSelect(me,F.select,typeof F.sort=="object"&&F.sort,T,C,Ce)[this.isSync?Symbol.iterator:Symbol.asyncIterator](),Te=a(Ct=>{for(;!Ct.done;){if(Ct?.then)return Ct.then(Te);Be.push(Ct.value),Ct=He.next()}he(Be,ue)},"nextValue"),ht=Te(He.next());ht&&($||($=[]),$.push(ht));return}else if(me=Ce.call(this,me),me?.then){$||($=[]),$.push(me.then(Be=>he(Be,ue)));return}}he(me,ue)},"handleResolvedValue");re?.then?($||($=[]),$.push(re.then(ge))):ge(re);return}else re=L[ue],re&&typeof re=="object"&&ue!==F&&(re=ve.transformEntryForSelect(F.select||F,T,C,null)({value:re}));he(re,ue)},"selectAttribute"),Q;if(typeof g=="string")W(g,F=>{Q=F});else if(Array.isArray(g))if(g.asArray)Q=[],g.forEach((F,he)=>{F==="*"?g[he]=L:W(F,ue=>Q[he]=ue)});else{Q={};let F=g.forceNulls;for(let he of g)if(he==="*")for(let ue in L)Q[ue]=L[ue];else W(he,(ue,_e)=>{ue===void 0&&F&&(ue=null),Q[_e]=ue})}else throw new dt.ClientError("Invalid select"+g);return $?Promise.all($).then(()=>Q):Q}return L},"transform");return U}async subscribe(g){if(!l)throw new Error("Can not subscribe to a table without an audit log");_||ze({table:s,database:c,schemaDefined:u,attributes:S,audit:!0}),g||(g={});let T=!g.rawEvents,C=[],P=BI(ve,this.getId()??null,function(v,A,U,N){try{let L=A.getValue?.(i,T),$=A.type;if(!L&&$==="patch"&&T){let Q=i.getEntry(v);Q?.version===A.version?L=Q.value:L=A.getValue?.(i,!0,U),$="put"}let W={id:v,localTime:U,value:L,version:A.version,type:$,beginTxn:N};C?C.push(W):(c!=="system"&&We(A.size??1,"db-message",s,null),this.send(W))}catch(L){Fe.default.error?.(L)}},g.startTime||0,g),O=(async()=>{this.isCollection&&(P.includeDescendants=!0,g.onlyChildren&&(P.onlyChildren=!0)),g.supportsTransactions&&(P.supportsTransactions=!0);let v=this.getId(),A=g.previousCount;A>1e3&&(A=1e3);let U=g.startTime;if(this.isCollection){if(U){if(A)throw new dt.ClientError("startTime and previousCount can not be combined for a table level subscription");for(let{key:N,value:L}of l.getRange({start:U,exclusiveStart:!0,snapshot:!1})){let $=It(L);if($.tableId!==n)continue;let W=$.recordId;if(v==null||Mq(v,W)){let Q=$.getValue(i,T,N);if(B({id:W,localTime:N,value:Q,version:$.version,type:$.type,size:$.size}),P.queue?.length>Dq&&await P.waitForDrain()===!1)return}P.startTime=N}}else if(A){let N=[];for(let{key:L,value:$}of l.getRange({start:"z",end:!1,reverse:!0}))try{let W=It($);if(W.tableId!==n)continue;let Q=W.recordId;if(v==null||Mq(v,Q)){let F=W.getValue(i,T,L);if(N.push({id:Q,localTime:L,value:F,version:W.version,type:W.type}),--A<=0)break}}catch(W){Fe.default.error("Error getting history entry",L,W)}for(let L=N.length;L>0;)B(N[--L]);N[0]&&(P.startTime=N[0].localTime)}else if(!g.omitCurrent){for(let{key:N,value:L,version:$,localTime:W,size:Q}of i.getRange({start:v??!1,end:v==null?void 0:[v,ql.MAXIMUM_KEY],versions:!0,snapshot:!1}))if(L&&(B({id:N,localTime:W,value:L,version:$,type:"put",size:Q}),P.queue?.length>Dq&&await P.waitForDrain()===!1))return}}else{A&&!U&&(U=0);let N=this.#r?.localTime;if(N===wI&&(i.cache?.delete(v),this.#r=i.getEntry(v),Fe.default.trace?.("re-retrieved record",N,this.#r?.localTime),N=this.#r?.localTime),Fe.default.trace?.("Subscription from",U,"from",v,N),U<N){let L=[],$=N;do{let W=l.get($);if(W){g.omitCurrent=!0;let Q=It(W),F=Q.getValue(i,T,$);T&&(Q.type="put"),L.push({id:v,value:F,localTime:$,...Q}),$=Q.previousLocalTime}else break;A&&A--}while($>U&&A!==0);for(let W=L.length;W>0;)B(L[--W]);P.startTime=N}!g.omitCurrent&&this.doesExist()&&B({id:v,localTime:N,value:this.#e,version:this.#n,type:"put"})}for(let N of C)B(N);C=null})();function B(v){c!=="system"&&We(v.size??1,"db-message",s,null),P.send(v)}return a(B,"send"),g.listener&&P.on("data",g.listener),P}static subscribeOnThisThread(g,T){return g===0||T?.crossThreads===!1}doesExist(){return!!(this.#e||this.#s)}publish(g,T,C){if(T===void 0||T instanceof URLSearchParams)this._writePublish(this.getId(),g,T);else{let P=!0,O=this.getContext();return g.checkPermission&&(P=this.allowCreate(O.user,g,O)),Gs(P,B=>{if(!B)throw new dt.AccessViolation(O.user);let v=Ls(g);this._writePublish(v,T,C)})}}_writePublish(g,T,C){let P=Br(this.getContext());g??=null,g!==null&&Gi(g);let O=this.getContext();P.addWrite({key:g,store:i,entry:this.#r,nodeName:O?.nodeName,validate:a(()=>{O?.source||(P.checkOverloaded(),this.validate(T))},"validate"),before:Ne.publish?.bind(this,O,g,T),beforeIntermediate:Uu(T,Ke.publish?.bind(this,O,g,T)),commit:a((B,v,A)=>{v===void 0&&R&&!_&&$a(),Fe.default.trace?.(`Publishing message to id: ${g}, timestamp: ${new Date(B).toISOString()}`),y(g,v?.value??null,v,v?.version||B,0,!0,{user:O?.user,residencyId:C?.residencyId,expiresAt:O?.expiresAt,nodeId:C?.nodeId,tableToTrack:s},"message",!1,T)},"commit")})}validate(g,T){let C,P=a((O,B,v)=>{if(B.type&&O!=null)if(T&&O.__op__&&(O=O.value),B.properties){typeof O!="object"&&(C||(C=[])).push(`Value ${qs(O)} in property ${v} must be an object${B.type?" ("+B.type+")":""}`);let A=B.properties;for(let U=0,N=A.length;U<N;U++){let L=A[U];if(L.relationship||L.computed){g.hasOwnProperty(L.name)&&(C||(C=[])).push(`Computed property ${v}.${L.name} may not be directly assigned a value`);continue}let $=P(O[L.name],L,v+"."+L.name);$&&(O[L.name]=$)}if(B.sealed&&O!=null&&typeof O=="object")for(let U in O)A.find(N=>N.name===U)||(C||(C=[])).push(`Property ${U} is not allowed within object in property ${v}`)}else switch(B.type){case"Int":(typeof O!="number"||O>>0!==O)&&(C||(C=[])).push(`Value ${qs(O)} in property ${v} must be an integer (from -2147483648 to 2147483647)`);break;case"Long":(typeof O!="number"||!(Math.floor(O)===O&&Math.abs(O)<=9007199254740992))&&(C||(C=[])).push(`Value ${qs(O)} in property ${v} must be an integer (from -9007199254740992 to 9007199254740992)`);break;case"Float":typeof O!="number"&&(C||(C=[])).push(`Value ${qs(O)} in property ${v} must be a number`);break;case"ID":typeof O=="string"||O?.length>0&&O.every?.(A=>typeof A=="string")||(C||(C=[])).push(`Value ${qs(O)} in property ${v} must be a string, or an array of strings`);break;case"String":typeof O!="string"&&(C||(C=[])).push(`Value ${qs(O)} in property ${v} must be a string`);break;case"Boolean":typeof O!="boolean"&&(C||(C=[])).push(`Value ${qs(O)} in property ${v} must be a boolean`);break;case"Date":if(!(O instanceof Date)){if(typeof O=="string"||typeof O=="number")return new Date(O);(C||(C=[])).push(`Value ${qs(O)} in property ${v} must be a Date`)}break;case"BigInt":if(typeof O!="bigint"){if(typeof O=="string"||typeof O=="number")return BigInt(O);(C||(C=[])).push(`Value ${qs(O)} in property ${v} must be a bigint`)}break;case"Bytes":if(!(O instanceof Uint8Array)){if(typeof O=="string")return Buffer.from(O);(C||(C=[])).push(`Value ${qs(O)} in property ${v} must be a Buffer or Uint8Array`)}break;case"Blob":if(!(O instanceof vs)){if(typeof O=="string"&&(O=Buffer.from(O)),O instanceof Buffer)return createBlob(O,{type:"text/plain"});(C||(C=[])).push(`Value ${qs(O)} in property ${v} must be a Blob`)}break;case"array":if(Array.isArray(O)){if(B.elements)for(let A=0,U=O.length;A<U;A++){let N=O[A],L=P(N,B.elements,v+"[*]");L&&(O[A]=L)}}else(C||(C=[])).push(`Value ${qs(O)} in property ${v} must be an Array`);break}B.nullable===!1&&O==null&&(C||(C=[])).push(`Property ${v} is required (and not does not allow null values)`)},"validateValue");for(let O=0,B=S.length;O<B;O++){let v=S[O];if(v.relationship||v.computed){Object.hasOwn(g,v.name)&&(C||(C=[])).push(`Computed property ${v.name} may not be directly assigned a value`);continue}if(!T||v.name in g){let A=P(g[v.name],v,v.name);A!==void 0&&(g[v.name]=A)}}if(f)for(let O in g)S.find(B=>B.name===O)||(C||(C=[])).push(`Property ${O} is not allowed`);if(C)throw new dt.ClientError(C.join(". "))}getUpdatedTime(){return this.#n}wasLoadedFromSource(){return I?!!this.#i:void 0}static async addAttributes(g){let T=S.slice(0);for(let C of g){if(!C.name)throw new dt.ClientError("Attribute name is required");if(C.name.match(/[`/]/))throw new dt.ClientError("Attribute names cannot include backticks or forward slashes");qae(C.name),T.push(C)}return ze({table:s,database:c,schemaDefined:u,attributes:T}),ve.indexingOperation}static async removeAttributes(g){let T=S.filter(C=>!g.includes(C.name));return ze({table:s,database:c,schemaDefined:u,attributes:T}),ve.indexingOperation}static getSize(){let g=i.getStats();return(g.treeBranchPageCount+g.treeLeafPageCount+g.overflowPages)*g.pageSize}static getAuditSize(){let g=l?.getStats();return g&&(g.treeBranchPageCount+g.treeLeafPageCount+g.overflowPages)*g.pageSize}static getStorageStats(){let g=i.env.path,T=QN.default.statfsSync?.(g)??{};return{available:T.bavail*T.bsize,free:T.bfree*T.bsize,size:T.blocks*T.bsize}}static async getRecordCount(g){let T=i.getStats().entryCount,C=1e3/2,P=performance.now(),O=Math.floor(T/2),B=g?.exactCount,v=0,A=0,U;for(let{value:N}of i.getRange({start:!0,lazy:!0,snapshot:!1}))if(N!=null&&v++,A++,await mc(),!B&&A<O&&performance.now()-P>C){U=A;break}if(U){let N=v;v=0;for(let{value:re}of i.getRange({start:"\uFFFF",reverse:!0,lazy:!0,limit:U,snapshot:!1}))re!=null&&v++,await mc();let L=U*2,$=(v+N)/L,W=Math.pow((v-N+1)/U/2,2)+$*(1-$)/L,Q=Math.max(Math.sqrt(W)*T,1),F=Math.round($*T),he=Math.max(F-1.96*Q,v+N),ue=Math.min(F+1.96*Q,T),_e=Math.pow(10,Math.round(Math.log10(Q)));return _e>F&&(_e=_e/10),v=Math.round(F/_e)*_e,{recordCount:v,estimatedRange:[Math.round(he),Math.round(ue)]}}return{recordCount:v}}static updatedAttributes(){xr=this.propertyResolvers={$id:a((g,T,C)=>({value:C.key}),"$id"),$updatedtime:a((g,T,C)=>C.version,"$updatedtime"),$updatedTime:a((g,T,C)=>C.version,"$updatedTime"),$expiresAt:a((g,T,C)=>C.expiresAt,"$expiresAt"),$record:a((g,T,C)=>C?{value:g}:g,"$record"),$distance:a((g,T,C)=>C&&(C.distance??T?.vectorDistances?.get(C)),"$distance")};for(let g of this.attributes){g.isPrimaryKey&&(H=g),g.resolve=null;let T=g.relationship,C=g.computed;if(T)if(g.indexed&&console.error("A relationship property can not be directly indexed, (but you may want to index the foreign key attribute)"),C&&console.error("A relationship property is already computed and can not be combined with a computed function (the relationship will be given precedence)"),Lu=!0,T.to)g.elements?.definition?(xr[g.name]=g.resolve=(P,O,B,v)=>{let A=P[T.from?T.from:t],U=g.elements.definition.tableClass;return v?rd({attribute:T.to,value:A},Br(O).getReadTxn(),!1,U,!1).map(N=>N&&N.key!==void 0?N:U.primaryStore.getEntry(N,{transaction:Br(O).getReadTxn()})).asArray:U.search([{attribute:T.to,value:A}],O).asArray},g.set=()=>{},g.resolve.definition=g.elements.definition,g.resolve.to=T.to,T.from&&(g.resolve.from=T.from)):console.error(`The one-to-many/many-to-many relationship property "${g.name}" in table "${s}" must have an array type referencing a table as the elements`);else if(T.from){let P=g.definition||g.elements?.definition;P?(xr[g.name]=g.resolve=(O,B,v,A)=>{let U=O[T.from];if(U===void 0)return;if(g.elements){let L,$=U?.map(W=>{let Q=P.tableClass.primaryStore[A?"getEntry":"get"](W,{transaction:Br(B).getReadTxn()});return Q?.then&&(L=!0),ve.loadAsInstance===!1&&Object.freeze(A?Q?.value:Q),Q});return T.filterMissing?L?Promise.all($).then(W=>W.filter(Uq)):$.filter(Uq):L?Promise.all($):$}let N=P.tableClass.primaryStore[A?"getEntry":"get"](U,{transaction:Br(B).getReadTxn()});return ve.loadAsInstance===!1&&Object.freeze(A?N?.value:N),N},g.set=(O,B)=>{if(Array.isArray(B)){let v=B.map(A=>A.getId?.()||A[P.tableClass.primaryKey]);O[T.from]=v}else{let v=B.getId?.()||B[P.tableClass.primaryKey];O[T.from]=v}},g.resolve.definition=g.definition||g.elements?.definition,g.resolve.from=T.from):console.error(`The relationship property "${g.name}" in table "${s}" must be a type that references a table`)}else console.error(`The relationship directive on "${g.name}" in table "${s}" must use either "from" or "to" arguments`);else if(C)typeof C.from=="function"&&this.setComputedAttribute(g.name,C.from),xr[g.name]=g.resolve=(P,O,B)=>{let v=typeof C.from=="string"?P[C.from]:P,A=this.userResolvers[g.name];if(A)return A(v,O,B);Fe.default.warn(`Computed attribute "${g.name}" does not have a function assigned to it. Please use setComputedAttribute('${g.name}', resolver) to assign a resolver function.`),this.userResolvers[g.name]=()=>{}},g.resolve.directReturn=!0;else if(r[g.name]?.customIndex?.propertyResolver){let P=r[g.name].customIndex;xr[g.name]=(O,B,v)=>{let A=O[g.name];return P.propertyResolver(A,B,v)},xr[g.name].directReturn=!0}}Pp(this,this),Pp(um,this,!0);for(let g of S){let T=g.name;g.resolve&&(Object.defineProperty(i.encoder.structPrototype,T,{get(){return g.resolve(this,id.getStore())},set(C){return g.set(this,C)},configurable:!0,enumerable:g.enumerable}),g.enumerable&&!i.encoder.structPrototype.toJSON&&Object.defineProperty(i.encoder.structPrototype,"toJSON",{configurable:!0,value(){let C={};for(let P in this)C[P]=this[P];return C}}))}}static setComputedAttribute(g,T){let C=zi(S,g);if(!C){console.error(`The attribute "${g}" does not exist in the table "${s}"`);return}if(!C.computed){console.error(`The attribute "${g}" is not defined as computed in the table "${s}"`);return}this.userResolvers[g]=T}static async deleteHistory(g=0,T=!1){let C;for(let{key:P,value:O}of l.getRange({start:0,end:g}))await mc(),It(O).tableId===n&&(C=mg(l,P,O));if(T)for(let P of i.getRange({start:0,versions:!0})){let{key:O,value:B,localTime:v}=P;await mc(),B===null&&v<g&&(C=Sl(i,P))}await C}static async*getHistory(g=0,T=1/0){for(let{key:C,value:P}of l.getRange({start:g||1,end:T})){await mc();let O=It(P);O.tableId===n&&(yield{id:O.recordId,localTime:C,version:O.version,type:O.type,value:O.getValue(i,!0,C),user:O.user,operation:O.originatingOperation})}}static async getHistoryOfRecord(g){let T=[];if(g==null)throw new Error("An id is required");let C=i.getEntry(g);if(!C)return T;let P=C.localTime;if(!P)throw new Error("The entry does not have a local audit time");let O=0;do{await mc();let B=l.get(P);if(B){let v=It(B);T.push({id:v.recordId,localTime:P,version:v.version,type:v.type,value:v.getValue(i,!0,P),user:v.user}),P=v.previousLocalTime}else break}while(O<1e3&&P);return T.reverse()}static cleanup(){Y?.remove()}}let d_=TS(async(K,g,T)=>{for(let C of ve.sources)if(C.get&&(!C.get.reliesOnPrototype||C.prototype.get)){if(C.available?.(T)===!1)continue;g.source=C;let P=await C.get(K,g);if(P)return P}},()=>{throw new dt.ServerError("Service unavailable, exceeded request queue limit for resolving cache record",503)});ve.updatedAttributes();let jb=ve.prototype;return h&&ve.setTTLExpiration(h/1e3),z&&f_(),ve;function Du(K,g,T){let C;for(let P in r){let O=r[P],B=O.isIndexing,v=xr[P],A=T&&(v?v(T):T[P]),U=g&&(v?v(g):g[P]);if(A===U&&!B)continue;if(O.customIndex){O.customIndex.index(K,A,U);continue}C=!0;let N=O.indexNulls,L=(0,zp.getIndexedValues)(A,N),$=(0,zp.getIndexedValues)(U,N);if($?.length>0){let W=new Set($);if(L=L?L.filter(Q=>{if(W.has(Q))W.delete(Q);else return!0}):[],$=Array.from(W),($.length>0||L.length>0)&&Oq){let Q=$.concat(L).map(F=>({key:F,value:K}));O.prefetch(Q,vq)}for(let Q=0,F=$.length;Q<F;Q++)O.remove($[Q],K)}else L?.length>0&&Oq&&O.prefetch(L.map(W=>({key:W,value:K})),vq);if(L)for(let W=0,Q=L.length;W<Q;W++)O.put(L[W],K)}return C}a(Du,"updateIndices");function Gi(K){switch(typeof K){case"number":return!0;case"string":if(K.length<659)return!0;if(K.length>Lq)throw new Error("Primary key size is too large: "+K.length);break;case"object":if(K===null)throw new Error("Invalid primary key of null");break;case"bigint":if(K<2n**64n&&K>-(2n**64n))return!0;break;default:throw new Error("Invalid primary key type: "+typeof K)}if((0,ql.writeKey)(K,zae,0)>Lq)throw new Error("Primary key size is too large: "+K.length);return!0}a(Gi,"checkValidId");function Ls(K){return typeof K=="object"&&K?K.id:K}a(Ls,"requestTargetToId");function dm(K){return typeof K=="object"&&K&&K.isCollection}a(dm,"isSearchTarget");function fm(K){}a(fm,"isRequestTarget");function Fo(K,g,T,C,P){if(ve.getResidencyById&&T.ensureLoaded&&g?.replicateFrom!==!1){let B=Va(ve.getResidencyById(K));if(B&&!B.includes(server.hostname)&&w)return w({key:K,residency:B}).then(P)}let O=a(()=>{if(g?.transaction?.stale&&(g.transaction.stale=!1),T.transaction?.isDone)return P(null,K);let B=i.getEntry(K,T);return(c!=="system"||s==="hdb_analytics")&&(Fq.default.trace?.("Recording db-read action for",`${c}.${s}`),We(B?.size??1,"db-read",s,null)),g?._freezeRecords&&Object.freeze(B?.value),B?.residencyId&&B.metadataFlags&kn&&w&&T.ensureLoaded&&g?.replicateFrom!==!1?w(B).then(v=>P(v,K),v=>(Fe.default.error?.("Error loading remote record",K,B,T,v),P(null,K))):(B&&g&&(B?.version>(g.lastModified||0)&&(g.lastModified=B.version),B?.localTime&&!g.lastRefreshed&&(g.lastRefreshed=B.localTime)),P(B,K))},"whenPrefetched");return C?O():te>0?(te--,O()):new Promise((B,v)=>{te===0?(te--,i.prefetch([K],()=>{A(),U()})):(ce.push(K),de.push(U),ce.length>u_&&(te--,A()));function A(){if(ce.length>0){let N=de;i.prefetch(ce,()=>{te===-1?A():te++;for(let L of N)L()}),ce=[],de=[],Se>2&&Se--}else te=Se,Se<lm&&Se++}a(A,"prefetch");function U(){try{B(O())}catch(N){v(N)}}a(U,"load")})}a(Fo,"loadLocalRecord");function Dn(K,g){let T=g?.checkPermission;if(typeof T!="object"){if(!K?.role)return;T=K.role.permission}if(T.super_user)return Qae;let C=T[c],P,O=C?.tables;if(O)return O[s];if(c==="data"&&(P=T[s])&&!P.tables)return P}a(Dn,"getTablePermissions");function pn(K,g,T,C){if(I){let P=!1;if(T.noCache?P=!0:(g?(!g.value||g.metadataFlags&(kn|Tl)||g.expiresAt!=null&&g.expiresAt<Date.now())&&(P=!0):P=!0,tn(!P,"cache-hit",s)),P){let O=Mu(K,g,T).then(B=>(B?.value&&B?.value.getRecord?.()&&Fe.default.error?.("Can not assign a record that is already a resource"),T&&(B?.version>(T.lastModified||0)&&(T.lastModified=B.version),T.lastRefreshed=Date.now()),B));if(T?.onlyIfCached||g?.value&&C?.allowStaleWhileRevalidate?.(g,K)){if(O.catch(B=>Fe.default.warn?.(B)),T?.onlyIfCached&&!C.doesExist())throw new dt.ServerError("Entry is not cached",504);return}else return O}}else if(g?.value&&g.expiresAt!=null&&g.expiresAt<Date.now())return ve.evict(g.key,g.value,g.version),g.value=null,{then(P){return P(g)}}}a(pn,"ensureLoadedFromSource");function Br(K){let g=K?.transaction;if(g){if(!g.lmdbDb)return g.lmdbDb=i,g;do{if(g.lmdbDb?.path===i.path)return g;let T=g.next;if(!T)return g=g.next=new Go,g.lmdbDb=i,g;g=T}while(!0)}else return new K_}a(Br,"txnForContext");function vu(K,g,T){if(!K)return;let C=(K.deref?K.deref():K.value)??i.getEntry(K.key)?.value;if(typeof g=="object"){let O=xr,B=C;for(let v=0,A=g.length;v<A;v++){let U=g[v],N=O?.[U];B=N&&B?N(B,T,K):B?.[U],K=null,O=N?.definition?.tableClass?.propertyResolvers}return B}let P=xr[g];return P?P(C,T,K):C[g]}a(vu,"getAttributeValue");function mm(K,g,T,C,P){let O=P?.length,B={transaction:C,lazy:O>0||typeof g=="string"||g?.length<4,alwaysPrefetch:!0},v;function A(U,N){let L=U?.value;if(!L)return pc.SKIP;for(let $=0;$<O;$++)if(!v?.includes($)&&!P[$](L,U))return pc.SKIP;return N!==void 0&&(U.key=N),U}if(a(A,"processEntry"),O>0||!K.hasEntries){let U=K.map(N=>{if(v=null,typeof N=="object"&&N?.key!==void 0)return O>0?A(N):N;if(N==null)return pc.SKIP;for(let L=0;L<O;L++){let W=P[L].idFilter;if(W){if(!W(N))return pc.SKIP;v||(v=[]),v.push(L)}}return Fo(N,T,B,!1,A)});return Array.isArray(K)&&(U=U.filter(N=>N!==pc.SKIP)),U.hasEntries=!0,U}return K}a(mm,"transformToEntries");function Fr(K,g,T=server.replication?.getThisNodeId(l)){if(K<=g?.version){if(g?.version===K&&T!==void 0){let C=server.replication?.exportIdMapping(l),P=g.localTime,O=P&&l.get(P);if(O){let B,v,A=It(O);for(let U in C)C[U]===T&&(B=U),C[U]===A.nodeId&&(v=U);if(B>v)return 1;if(B===v)return 0}}return-1}return 1}a(Fr,"precedesExistingVersion");async function Mu(K,g,T){let C=g?.metadataFlags,P=g?.version,O,B;if(!i.attemptLock(K,P,()=>{clearTimeout(B);let N=i.getEntry(K);!N||!N.value||N.metadataFlags&(kn|Tl)?O(Mu(K,i.getEntry(K),T)):O(N)}))return new Promise(N=>{O=N,B=setTimeout(()=>{i.unlock(K,P)},Wae)});let v=g?.value,A={requestContext:T,replacingRecord:v,replacingEntry:g,replacingVersion:P,noCacheStore:!1,source:null,resourceCache:T?.resourceCache,transaction:void 0,expiresAt:void 0,lastModified:void 0},U=T?.responseHeaders;return new Promise((N,L)=>{let $;Gs(At(A,async W=>{let Q=performance.now(),F,he,ue;try{F=await d_(K,A,g),ue=C&kn;let re=A.lastModified||ue&&P;re||(re=(0,zp.getNextMonotonicTime)()),he=ue||re>P||!v;let oe=performance.now()-Q;if(We(oe,"cache-resolution",s,null,"success"),U&&Wp(U,"Server-Timing",`cache-resolve;dur=${oe.toFixed(2)}`,!0),W.timestamp=re,h&&A.expiresAt==null&&(A.expiresAt=Date.now()+h),F){if(typeof F!="object")throw new Error("Only objects can be cached and stored in tables");if(F.status>0&&F.headers)if(F.status>=300)if(F.status===304)F=v,re=P;else throw new dt.ServerError(F.body||"Error from source",F.status);else F=F.body;typeof F.toJSON=="function"&&(F=F.toJSON()),t&&F[t]!==K&&(F[t]=K)}$=!0,N({key:K,version:re,value:F})}catch(re){re.message+=` while resolving record ${K} for ${s}`,v&&((re.code==="ECONNRESET"||re.code==="ECONNREFUSED"||re.code==="EAI_AGAIN")&&!T?.mustRevalidate||T?.staleIfError&&(re.statusCode===500||re.statusCode===502||re.statusCode===503||re.statusCode===504))?(N({key:K,version:P,value:v}),Fe.default.trace?.(re.message,"(returned stale record)")):L(re);let oe=performance.now()-Q;We(oe,"cache-resolution",s,null,"fail"),U&&Wp(U,"Server-Timing",`cache-resolve;dur=${oe.toFixed(2)}`,!0),A.transaction.abort();return}if(T?.noCacheStore||A.noCacheStore){A.transaction.abort();return}Br(A).addWrite({key:K,store:i,entry:g,nodeName:"source",before:Uu(F),commit:a((re,oe)=>{if(oe?.version!==P)return;let ge=Du(K,v,F);if(F){Ke.put?.(A,K,F),oe&&(T.previousResidency=ve.getResidencyRecord(oe.residencyId));let me,ie=!1,Ce,Be=Va(ve.getResidency(F,T));if(Be){if(!Be.includes(server.hostname))if(me=F,ie=!0,ve.getResidencyById)F=void 0;else{F=null;for(let He in r)F||(F={}),F[He]=me[He]}Ce=Jc(Be)}Fe.default.trace?.(`Writing resolved record from source with id: ${K}, timestamp: ${new Date(re).toISOString()}`),y(K,F,oe,re,ie?kn:0,_&&(he||ie)||null,{user:A?.user,expiresAt:A.expiresAt,residencyId:Ce,tableToTrack:s},"put",!!ue,me)}else oe&&(Ke.delete?.(A,K),Fe.default.trace?.(`Deleting resolved record from source with id: ${K}, timestamp: ${new Date(re).toISOString()}`),_||R?y(K,null,oe,re,0,_&&he||null,{user:A?.user,tableToTrack:s},"delete",!!ue):Sl(i,oe,P))},"commit")})}),()=>{i.unlock(K,P)},W=>{i.unlock(K,P),$&&Fe.default.error?.("Error committing cache update",W)})})}a(Mu,"getFromSource");function qa(K){if(!K||K.user?.role?.permission?.super_user)return!0;if(K.replicateTo)throw new dt.ClientError("Can not specify replication parameters without super user permissions",403);if(K.replicatedConfirmation)throw new dt.ClientError("Can not specify replication confirmation without super user permissions",403);return!0}a(qa,"checkContextPermissions");function $a(K){let g=!1;if(K&&(K-Ir>1&&(g=!0),Ir=K),!($e===nr&&!g)&&(nr=$e,(0,Hl.getWorkerIndex)()===(0,Hl.getWorkerCount)()-1))return zr&&clearTimeout(zr),$e?new Promise(T=>{let C=new Date;C.setMonth(0),C.setDate(1),C.setHours(0),C.setMinutes(0),C.setSeconds(0);let P=$e/(1+Ir),O=g?Date.now():Math.ceil((Date.now()-C.getTime())/P)*P+C.getTime(),B=a(v=>{Fe.default.trace?.(`Scheduled next cleanup scan at ${new Date(v)}`),zr=setTimeout(()=>X=X.then(async()=>{if(B(Math.max(v+$e,Date.now())),i.rootStore.status!=="open"){clearTimeout(zr);return}let A=50,U=new Array(A),N=0,L=Math.pow(Ir,8)*(Gl.get(x.STORAGE_RECLAMATION_EVICTIONFACTOR)??1e5),$=E/Math.pow(Math.max(Ir,1),4);Fe.default.debug?.(`Starting cleanup scan for ${s}, evict threshold ${L}, adjusted eviction ${$}ms`);function W(Q,F,he,ue){let _e=Q+$-Date.now();if(_e<0)return!0;if(Ir){let re=i.lastSize;return he&Zr&&cl(ue,oe=>{oe.size&&(re+=oe.size)}),Fe.default.trace?.(`shouldEvict adjusted ${_e} ${re}, ${_e*(Q-F)/re} < ${L}`),_e*(Q-F)/re<L}return!1}a(W,"shouldEvict");try{let Q=0;for(let F of i.getRange({start:!1,snapshot:!1,versions:!0,lazy:!0})){let{key:he,value:ue,version:_e,expiresAt:re,metadataFlags:oe}=F,ge;ue===null&&!_&&_e+Yae<Date.now()?ge=Sl(i,F,_e):re!=null&&W(re,_e,oe,ue)&&(ge=ve.evict(he,ue,_e),Q++),ge&&(await U[N],U[N]=ge.catch(me=>{Fe.default.error?.("Cleanup error",me)}),++N>=A&&(N=0)),await mc()}Fe.default.debug?.(`Finished cleanup scan for ${s}, evicted ${Q} entries`)}catch(Q){Fe.default.warn?.(`Error in cleanup scan for ${s}:`,Q)}T(void 0),Ir=0}),Math.min(v-Date.now(),2147483647)).unref()},"startNextTimer");B(O)}):void 0}a($a,"scheduleCleanup");function pm(){Y=l?.addDeleteRemovalCallback(n,i,(K,g)=>{i.remove(K,g)})}a(pm,"addDeleteRemoval");function f_(){(0,Hl.getWorkerIndex)()===0&&setInterval(async()=>{if(!Qc){Qc=!0;try{let K=z.name,g=r[K];if(!g)throw new Error(`expiresAt attribute ${z} must be indexed`);for(let T of g.getRange({start:!0,values:!1,end:Date.now(),snapshot:!1})){for(let C of g.getValues(T)){let P=i.getEntry(C);P?.value?P.value[K]<Date.now()&&ve.evict(C,P.value,P.version):i.ifVersion(C,P?.version,()=>g.remove(T,C))}await mc()}}catch(K){Fe.default.error?.("Error in evicting old records",K)}finally{Qc=!1}}},Kae).unref()}a(f_,"runRecordExpirationEviction");function Va(K){if(K!=null){if(Array.isArray(K))return K;if(typeof K=="number"){if(K>=65536)throw new Error(`Shard id ${K} must be below 65536`);let g=server.shards?.get?.(K);if(g)return Fe.default.trace?.(`Shard ${K} mapped to ${g.map(T=>T.name).join(", ")}`),g.map(T=>T.name);throw new Error(`Shard ${K} is not defined`)}throw new Error(`Shard or residency list ${K} is not a valid type, must be a shard number or residency list of node hostnames`)}}a(Va,"residencyFromFunction");function Jc(K){if(K){let g=K.join(","),T=d.get([Symbol.for("residency_by_set"),g]);return T||(d.put([Symbol.for("residency_by_set"),g],T=Math.floor(Math.random()*2147418112)+65535),d.put([Symbol.for("residency_by_id"),T],K),T)}}a(Jc,"getResidencyId");function Uu(K,g){let T=QA(K,i.rootStore);if(T){let C=g;return C?async()=>{await C(),await T}:()=>T}return g}a(Uu,"preCommitBlobsForRecordBefore")}function zN(e,t){let r=e.attr_object||(e.attr_object={}),n=r[t];if(n)return n;n=r[t]=Object.create(null);for(let s of e)n[s.attribute_name]=s[t];return n}function vq(){}function RS(e,t){let r=t?.type;if(e===null)return e;if(e===""&&r&&r!=="String"&&r!=="Any")return null;try{switch(r){case"Int":case"Long":if(e[0]==="$")return yS(parseInt(e.slice(1),36));if(e==="null")return null;if(!/^-?[0-9]+$/.test(e)&&!(e instanceof Date))throw new SyntaxError;return yS(+e);case"Float":return e==="null"?null:yS(+e);case"BigInt":return e==="null"?null:BigInt(e);case"Boolean":return(0,Od.autoCastBooleanStrict)(e);case"Date":if(isNaN(e)){if(e==="null")return null;Jae.test(e)||(e+="Z");let n=new Date(e);return yS(n.getTime()),n}return new Date(+e);case void 0:case"Any":return(0,Od.autoCast)(e);default:return e}}catch(n){throw n.message=`Invalid value for attribute ${t.name}: "${e}", expecting ${r}`,n.statusCode=400,n}}function yS(e){if(isNaN(e))throw new SyntaxError;return e}function Mq(e,t){if(e==null)return!0;if(!Array.isArray(t))return e===t||t.startsWith?.(e);if(Array.isArray(e)){let r=e.length;if(e[r-1]===null&&r--,t.length>=r){for(let n=0;n<r;n++)if(t[n]!==e[n])return!1;return!0}return!1}else if(t[0]===e)return!0}function Gs(e,t,r){return e?.then?e.then(t,r):t(e)}function Uq(e){return e!=null}function qs(e){try{return JSON.stringify(e)}catch{return e}}function Xae(e){let t=process.pid;return e.env.readerList().slice(1).some(r=>+r.match(/\d+/)?.[0]!=t)}var pc,zp,xq,Bq,Gl,dt,Qp,Jp,Fe,ql,Hl,Od,QN,Fq,Gae,qae,$ae,Vae,Kae,Yae,Oq,Wae,Pq,jae,kn,Tl,zae,Lq,Dq,Qae,qUe,Jae,mc,Lg=se(()=>{G();pc=require("lmdb"),zp=b(xn()),xq=b(require("lodash")),Bq=b(xm());Qi();Fm();Gl=b(fe());FI();dt=b(Ee()),Qp=b(ea()),Jp=b(us());Oe();Pg();Fe=b(sr());Yw();Qa();ql=require("ordered-binary"),Hl=b(st());Vi();Od=b(ae());hl();os();z_();jp();QN=b(require("node:fs"));is();lg();Fq=b(J());jN();({sortBy:Gae}=xq.default),{validateAttribute:qae}=Bq.default,$ae=new Uint8Array(9);$ae[8]=192;Vae=1/0,Kae=6e4,Yae=864e5;Gl.initSync();Oq=Gl.get(x.STORAGE_PREFETCHWRITES),Wae=1e4,Pq=1,jae=2,kn=1,Tl=8,zae=Buffer.allocUnsafeSlow(8192),Lq=1978,Dq=100,Qae={read:!0,insert:!0,update:!0,delete:!0,isSuperUser:!0},qUe=(0,Od.convertToMS)(Gl.get(x.CLUSTERING_LEAFSERVER_STREAMS_MAXAGE))||864e5;a(bS,"makeTable");a(zN,"attributesAsObject");a(vq,"noop");Jae=/[+-][0-9]{2}:[0-9]{2}|[a-zA-Z]$/;a(RS,"coerceType");a(yS,"rejectNaN");a(Mq,"isDescendantId");mc=a(()=>new Promise(setImmediate),"rest");a(Gs,"when");a(Uq,"exists");a(qs,"stringify");a(Xae,"hasOtherProcesses")});function AS(e,t){if(!Array.isArray(e)||!Array.isArray(t))throw new Error("Euclidean distance comparison requires an array");let r=0,n=Math.max(e.length,t.length);for(let s=0;s<n;s++){let i=e[s]||0,o=t[s]||0,c=i-o;r+=c*c}return r}function IS(e,t){if(!Array.isArray(e)||!Array.isArray(t))throw new Error("Cosine distance comparison requires an array");let r=0,n=0,s=0,i=Math.max(e.length,t.length);for(let o=0;o<i;o++){let c=e[o]||0,l=t[o]||0;r+=c*l,n+=c*c,s+=l*l}return n=Math.sqrt(n),s=Math.sqrt(s),1-r/(n*s||1)}var Hq=se(()=>{a(AS,"euclideanDistance");a(IS,"cosineDistance")});var Gq,qq,Ld,lo,Pd,Zae,ece,wS,$q=se(()=>{Hq();Gq=require("msgpackr"),qq=b(sr()),Ld=b(Ee()),lo=(0,qq.loggerWithTag)("HNSW"),Pd=Symbol.for("entryPoint"),Zae=Symbol.for("key"),ece=10,wS=class{static{a(this,"HierarchicalNavigableSmallWorld")}static useObjectStore=!0;indexStore;M=16;efConstruction=100;efConstructionSearch=50;mL=1/Math.log(this.M);optimizeRouting=.5;nodesVisitedCount=0;idIncrementer;distance;constructor(t,r){this.indexStore=t,t&&(this.indexStore.encoder.useFloat32=Gq.FLOAT32_OPTIONS.ALWAYS),this.distance=r?.distance==="euclidean"?AS:IS,r&&(r.M!==void 0&&(this.M=r.M,this.mL=1/Math.log(this.M)),r.efConstruction!==void 0&&(this.efConstruction=this.efConstructionSearch=r.efConstruction),r.efConstructionSearch!==void 0&&(this.efConstructionSearch=r.efConstructionSearch),r.mL!==void 0&&(this.mL=r.mL),r.optimizeRouting!==void 0&&(this.optimizeRouting=r.optimizeRouting))}index(t,r,n){let s=typeof t=="number"?[Zae,t]:t,i=this.indexStore.get(s);if(!i){if(!r)return;if(!this.idIncrementer){let f=0;for(let m of this.indexStore.getKeys({reverse:!0,limit:1,start:1/0,end:0}))typeof m=="number"&&(f=m);this.idIncrementer=new BigInt64Array([BigInt(f)+1n]),this.idIncrementer=new BigInt64Array(this.indexStore.getUserSharedBuffer("next-id",this.idIncrementer.buffer))}i=Number(Atomics.add(this.idIncrementer,0,1n)),this.indexStore.put(s,i)}let o=new Map,c,l=this.indexStore.get(Pd);if(n?c={...this.indexStore.get(i)}:c={},r){let f=l&&this.indexStore.get(l);if(f==null){let E=Math.floor(-Math.log(Math.random())*this.mL),_={vector:r,level:E,primaryKey:t};for(let R=0;R<=E;R++)_[R]=[];if(this.indexStore.put(i,_),typeof i!="number")throw new Error("Invalid nodeId: "+i);lo.debug?.("setting entry point to",i),this.indexStore.put(Pd,i);return}let m=c.level??Math.min(Math.floor(-Math.log(Math.random())*this.mL),ece),p=f.level;if(m>=p){if(typeof i!="number")throw new Error("Invalid nodeId: "+i);lo.debug?.("setting entry point to",i),this.indexStore.put(Pd,i)}for(;p>m;){let E=this.searchLayer(r,l,f,this.efConstruction,p);E.length>0&&(l=E[0].id,f=E[0].node),p--}let h=new Array(m+1);for(let E=0;E<=m;E++)h[E]=[];for(let E=Math.min(m,p);E>=0;E--){let _=this.searchLayer(r,l,f,this.efConstruction,E);_=_.slice(0,this.M<<1),_.length===0&&E===0&&lo.info?.("should not have zero connections for",l);let R=h[E];for(let S=0;S<_.length;S++){let{id:y,distance:w,node:I}=_[S];if(y===i)continue;let H=[];if(this.optimizeRouting){let k=!1,z=I[E],Y=1+this.optimizeRouting*(1+.5*S/this.M);for(let ce=0;ce<z?.length;ce++){let{id:de,distance:te}=z[ce],Se=1+this.optimizeRouting*(1+.5*ce/this.M);for(let Ne=0;Ne<R.length;Ne++){let{id:Ke,distance:$e}=R[Ne];if(Ke===de){w*Y>$e+te?k=!0:te*Se>w+$e&&(H.push({fromId:Ke,toId:y}),H.push({fromId:y,toId:Ke}));break}}if(k)break}if(k)continue}else if(S>=(E>0?this.M:this.M<<1))continue;R.push({id:y,distance:w});for(let{fromId:k,toId:z}of H){let Y=d(k);Y||(Y=d(k,this.indexStore.get(k)));for(let ce=0;ce<Y[E].length;ce++)if(Y[E][ce].id===z){Object.isFrozen(Y[E])&&(Y[E]=Y[E].slice()),Y[E].splice(ce,1);break}}let X=c[E],q=X?.find(({id:k})=>k===y);if(q){let k=X?.indexOf(q);X.copied||(X=[...X],X.copied=!0,c[E]=X),X.splice(k,1)}else this.addConnection(y,d(y,I),i,E,w,d)}}this.indexStore.put(i,{vector:r,level:m,primaryKey:t,...h})}else{if(l===i){let f=c.level??0;for(let m=f;m>=0&&(l=c[m]?.[0]?.id,l===void 0);m--);if(l===void 0){let m=-1;for(let{key:p,value:h}of this.indexStore.getRange({start:0,end:1/0}))if(h.level>m){if(l=p,h.level===f)break;m=h.level}}if(l===void 0)this.indexStore.remove(Pd);else{if(typeof l!="number")throw new Error("Invalid nodeId: "+l);lo.debug?.("setting entry point to",l),this.indexStore.put(Pd,l)}}this.indexStore.remove(i)}let u=new Map;if(c.level!==void 0)for(let f=0;f<=c.level;f++){let m=c[f];for(let{id:p}of m){let h=d(p,this.indexStore.get(p));if(h)for(let E=0;E<=f;E++)h[E]=h[E]?.filter(({id:_})=>_!==i),h[E]?.length===0&&(lo.info?.("node was left orphaned, will reindex",p),u.set(h.primaryKey,h.vector))}}function d(f,m){let p=o.get(f);return!p&&m&&(p={...m},o.set(f,p)),p}a(d,"updateNode");for(let[f,m]of o)this.indexStore.put(f,m);for(let[f,m]of u)this.index(f,m,m);this.checkSymmetry(i,this.indexStore.get(i))}getEntryPoint(){let t=this.indexStore.get(Pd);if(t===void 0)return;let r=this.indexStore.get(t);return{id:t,...r}}searchLayer(t,r,n,s,i,o=this.distance){let c=new Set([r]),l=[{id:r,distance:this.distance(t,n.vector),node:n}],u=[...l];for(;l.length>0;){l.sort((p,h)=>p.distance-h.distance);let d=l.shift(),f=u[u.length-1].distance;if(d.distance>f)break;let m=d.node;for(let{id:p}of m[i]||[]){if(c.has(p)||p===void 0)continue;c.add(p);let h=this.indexStore.get(p);if(!h)continue;this.nodesVisitedCount++;let E=o(t,h.vector);if(E<f||u.length<s){let _={id:p,distance:E,node:h};l.push(_),u.push(_)}}u.sort((p,h)=>p.distance-h.distance),u.length>s&&u.splice(s,u.length-s)}return u.visited=c.size,u}search({target:t,value:r,descending:n,distance:s,comparator:i}){let o=0;switch(i){case"lt":case"le":o=r;case"sort":break;default:throw new Ld.ClientError(`Can not use "${i}" comparator with HNSW`)}if(n)throw new Ld.ClientError("Can not use descending sort order with HNSW");let c;if(s==="cosine")c=IS;else if(s==="euclidean")c=AS;else{if(s)throw new Ld.ClientError("Unknown distance function");c=this.distance}if(!t)throw new Ld.ClientError("A target vector must be provided for an HNSW query");if(!Array.isArray(t))throw new Ld.ClientError("The target vector must be an array");let l=this.getEntryPoint();if(!l)return[];let u=l.id,d=[];for(let f=l.level;f>=0;f--)if(d=this.searchLayer(t,u,l,this.efConstructionSearch,f,c),d.length>0){let m=d[0];l=m.node,u=m.id}return o&&(d=d.filter(f=>f.distance<o)),d.map(f=>({key:f.node.primaryKey,distance:f.distance}))}checkSymmetry(t,r){if(!r)return;let n=0,s;for(;(s=r[n])&&s.length!==0;){for(let{id:i}of s){let o=this.indexStore.get(i);if(!o){lo.info?.("could not find neighbor node",o);continue}o[n]?.find(({id:l})=>l==t)||lo.info?.("asymmetry detected",o[n])}n++}}addConnection(t,r,n,s,i,o){r[s]||(r[s]=[]);let c=s===0?this.M<<1:this.M;if(this.optimizeRouting&&(c<<=2),r[s].length>=c+(c>>2)){lo.debug?.("maxConnections reached, removing some connections",c);let l=[...r[s]];l.sort((f,m)=>f.distance-m.distance);let u=l.slice(0,c),d=l.slice(c);r[s]=u;for(let f of d){let m=o(f.id)??this.indexStore.get(f.id);m&&m[s]&&(m=o(f.id,m),m[s]=m[s].filter(({id:p})=>p!==t),s===0&&m[s].length===0&&lo.info?.("should not remove last connection",t,n))}}r[s].find(({id:l})=>l===n)?lo.debug?.("already connected",t,n):r[s]=[...r[s],{id:n,distance:i}]}validateConnectivity(t=0){let r=this.getEntryPoint(),n=new Set,s=[r.id];n.add(r.id);let i=0;for(;s.length>0;){let o=s.shift(),c=this.indexStore.get(o);for(let l=t;l<=c.level;l++)for(let{id:u}of c[l]||[])i++,n.has(u)||(n.add(u),s.push(u))}return n.size!==this.totalNodes&&console.log("visited",n.size,"total",this.totalNodes),{isFullyConnected:n.size===this.totalNodes,averageConnections:i/n.size}}get totalNodes(){return Array.from(this.indexStore.getKeys({start:0,end:1/0})).length}estimateCountAsSort(){return Math.sqrt(this.indexStore.getStats().entryCount*this.efConstructionSearch)}propertyResolver(t,r,n){let s=r?.sort;if(s){let i=s.vectorDistances;if(i){let l=i.get(n);if(l)return l}else i=r.vectorDistances=s.vectorDistances=new Map;let o=this.distance;s.type&&(o=s.distance==="euclidean"?AS:IS);let c=o(s.target,t);return i.set(n,c),c}return t}}});var JN,Vq=se(()=>{$q();JN={HNSW:wS}});var pt={};ye(pt,{NON_REPLICATING_SYSTEM_TABLES:()=>NS,database:()=>_d,databaseEnvs:()=>ia,databases:()=>Me,dropDatabase:()=>Jw,dropTableMeta:()=>oce,getDatabases:()=>lt,getDefaultCompression:()=>MS,getTables:()=>rce,onRemovedDB:()=>sh,onUpdatedTable:()=>$l,readMetaDb:()=>Xp,resetDatabases:()=>xd,table:()=>ze,tables:()=>yn});function nh(e,t){let r=DS.OpenDBIObject??DS.default.OpenDBIObject;return new r(e,t)}function rce(){return LS||lt(),yn||{}}function lt(){if(LS)return Me;LS=!0,Md=new Map;let e=(0,Zt.getHdbBasePath)()&&(0,Ht.join)((0,Zt.getHdbBasePath)(),el),t=(0,Zt.get)(x.DATABASES)||{};if(process.env.SCHEMAS_DATA_PATH&&(t.data={path:process.env.SCHEMAS_DATA_PATH}),e=process.env.STORAGE_PATH||(0,Zt.get)(x.STORAGE_PATH)||e&&((0,_s.existsSync)(e)?e:(0,Ht.join)((0,Zt.getHdbBasePath)(),T_)),!!e){if((0,_s.existsSync)(e))for(let r of(0,_s.readdirSync)(e,{withFileTypes:!0})){let n=(0,Ht.basename)(r.name,".mdb");r.isFile()&&(0,Ht.extname)(r.name).toLowerCase()===".mdb"&&!t[n]?.path&&Xp((0,Ht.join)(e,r.name),null,n)}if((0,_s.existsSync)((0,vd.getBaseSchemaPath)())){for(let r of(0,_s.readdirSync)((0,vd.getBaseSchemaPath)(),{withFileTypes:!0}))if(!r.isFile()){let n=(0,Ht.join)((0,vd.getBaseSchemaPath)(),r.name),s=(0,Ht.join)((0,vd.getTransactionAuditStoreBasePath)(),r.name);for(let i of(0,_s.readdirSync)(n,{withFileTypes:!0}))if(i.isFile()&&(0,Ht.extname)(i.name).toLowerCase()===".mdb"){let o=(0,Ht.join)(s,i.name);Xp((0,Ht.join)(n,i.name),(0,Ht.basename)(i.name,".mdb"),r.name,o,!0)}}}if(t)for(let r in t){let n=t[r],s=n.path;if((0,_s.existsSync)(s))for(let o of(0,_s.readdirSync)(s,{withFileTypes:!0}))o.isFile()&&(0,Ht.extname)(o.name).toLowerCase()===".mdb"&&Xp((0,Ht.join)(s,o.name),(0,Ht.basename)(o.name,".mdb"),r);let i=n.tables;if(i)for(let o in i){let c=i[o],l=(0,Ht.join)(c.path,(0,Ht.basename)(o+".mdb"));(0,_s.existsSync)(l)&&Xp(l,o,r,null,!0)}}for(let r in Me){let n=Md.get(r);if(n){let s=Me[r];r.includes("delete")&&Cr.trace(`defined tables ${Array.from(n.keys())}`);for(let i in s)n.has(i)||(Cr.trace(`delete table class ${i}`),delete s[i])}else if(delete Me[r],r==="data"){for(let s in yn)delete yn[s];delete yn[vS]}}if((0,Zt.get)(x.ANALYTICS_REPLICATE)===!1?NS.includes("hdb_analytics")||NS.push("hdb_analytics"):(Me.system?.hdb_analytics?.enableAuditing(),Me.system?.hdb_analytics_hostname?.enableAuditing()),Me.system)for(let r of NS)Me.system[r]&&(Me.system[r].replicate=!1);return Md=null,Me}}function xd(){LS=!1;for(let[,e]of ia)e.needsDeletion=!0;lt();for(let[e,t]of ia)if(t.needsDeletion&&!e.endsWith("system.mdb")){t.close(),ia.delete(e);let r=Me[t.databaseName];for(let n in r)if(r[n].primaryStore.path===e){delete Me[t.databaseName],eh.forEach(i=>i(t.databaseName));break}}return Me}function Xp(e,t,r=eC,n,s){let i=new XN.default(e,!1);try{let o=ia.get(e);o?o.needsDeletion=!1:(o=(0,Ud.open)(i),ia.set(e,o));let c=new nh(!1),l=o.dbisDb||(o.dbisDb=o.openDB(CS.INTERNAL_DBIS_NAME,c)),u=o.auditStore;u||(n?(0,_s.existsSync)(n)&&(i.path=n,u=(0,Ud.open)(i),u.isLegacy=!0):u=fg(o));let d=zq(r),f=d[vS],m=new Map;for(let{key:p,value:h}of l.getRange({start:!1})){let[E,_]=p.toString().split("/");_===""?_=h.name:_||(_=E,E=t,h.name||(h.name=_,h.indexed=!h.is_hash_attribute)),f?.add(E);let R=m.get(E);R||m.set(E,R={attributes:[]}),(_==null||h.is_hash_attribute)&&(R.primary=h),_!=null&&R.attributes.push(h),Object.defineProperty(h,"key",{value:p,configurable:!0})}for(let[p,h]of m){let{attributes:E,primary:_}=h;if(!_){for(let te of E)if(te.is_hash_attribute||te.isPrimaryKey){_=te;break}if(!_){Cr.warn(`Unable to find a primary key attribute on table ${p}, with attributes: ${JSON.stringify(E)}`);continue}}let R=d[p],S={},y=[],w,I,H=typeof _.audit=="boolean"?_.audit:(0,Zt.get)(x.LOGGING_AUDITLOG),X=_.trackDeletes,q=_.expiration,k=_.eviction,z=_.sealed,Y=_.splitSegments,ce=_.replicate;if(R)S=R.indices,y=R.attributes,R.schemaVersion++;else{w=_.tableId,w?w>=(l.get(Dd)||0)&&(l.putSync(Dd,w+1),Cr.info(`Updating next table id (it was out of sync) to ${w+1} for ${p}`)):(_.tableId=w=l.get(Dd),w||(w=1),Cr.debug("Table {tableName} missing an id, assigning {tableId}"),l.putSync(Dd,w+1),l.putSync(_.key,_));let te=new nh(!_.is_hash_attribute,_.is_hash_attribute);if(te.compression=_.compression,te.compression){let Se=(0,Zt.get)(x.STORAGE_COMPRESSION_THRESHOLD)||jq;te.compression.threshold=Se}I=wg(o.openDB(_.key,te),o),o.databaseName=r,I.tableId=w}let de;for(let te of E){te.attribute=te.name;try{if(!te.is_hash_attribute&&(te.indexed||te.attribute&&!te.name)){if(!S[te.name]){let Ne=Jq(te.key,o,te);S[te.name]=Ne,S[te.name].indexNulls=te.indexNulls}let Se=y.find(Ne=>Ne.name===te.name);Se?y.splice(y.indexOf(Se),1,te):y.push(te),de=!0}}catch(Se){Cr.error("Error trying to update attribute",te,y,S,Se)}}for(let te of y)if(!E.find(Ne=>Ne.name===te.name)){if(te.is_hash_attribute){Cr.error("Unable to remove existing primary key attribute",te);continue}te.indexed&&(y.splice(y.indexOf(te),1),de=!0)}if(R)de&&(R.schemaVersion++,R.updatedAttributes());else{R=Qq(d,p,bS({primaryStore:I,auditStore:u,audit:H,sealed:z,splitSegments:Y,replicate:ce,expirationMS:q&&q*1e3,evictionMS:k&&k*1e3,trackDeletes:X,tableName:p,tableId:w,primaryKey:_.name,databasePath:s?r+"/"+p:r,databaseName:r,indices:S,attributes:E,schemaDefined:_.schemaDefined,dbisDB:l})),R.schemaVersion=1;for(let te of Zp)te(R)}}return o}catch(o){throw o.message+=` opening database ${e}`,o}}function zq(e){let t=Me[e];if(t||(e==="data"?t=Me[e]=yn:e==="system"?Object.defineProperty(Me,"system",{value:t=Object.create(null),configurable:!0}):t=Me[e]=Object.create(null)),Md&&!Md.has(e)){let r=new Set;t[vS]=r,Md.set(e,r)}return t}function Qq(e,t,r){return e[t]=r,r}function _d({database:e,table:t}){e||(e=eC),lt();let r=zq(e),n=(0,Ht.join)((0,Zt.getHdbBasePath)(),el),s=(0,Zt.get)(x.DATABASES)||{};process.env.SCHEMAS_DATA_PATH&&(s.data={path:process.env.SCHEMAS_DATA_PATH});let i=t&&s[e]?.tables?.[t]?.path;n=i||s[e]?.path||process.env.STORAGE_PATH||(0,Zt.get)(x.STORAGE_PATH)||((0,_s.existsSync)(n)?n:(0,Ht.join)((0,Zt.getHdbBasePath)(),T_));let o=(0,Ht.join)(n,(i?t:e)+".mdb"),c=ia.get(o);if(!c||c.status==="closed"){let l=new XN.default(o,!1);c=(0,Ud.open)(l),ia.set(o,c)}return c.auditStore||(c.auditStore=fg(c)),c}async function Jw(e){if(!Me[e])throw new Error("Schema does not exist");let t=Me[e],r;for(let n in t)r=t[n].primaryStore.rootStore,ia.delete(r.path),r.status==="open"&&(await r.close(),await th.remove(r.path));if(r||(r=_d({database:e,table:null}),r.status==="open"&&(await r.close(),await th.remove(r.path))),e==="data"){for(let n in yn)delete yn[n];delete yn[vS]}delete Me[e],eh.forEach(n=>n(e)),await zA(r)}function Jq(e,t,r){let n=r.is_hash_attribute||r.indexed.type&&JN[r.indexed.type]?.useObjectStore,s=new nh(!n,n),i=t.openDB(e,s);if(r.indexed.type){let o=JN[r.indexed.type];o?i.customIndex=new o(i,r.indexed):Cr.error(`The indexing type '${r.indexed.type}' is unknown`)}return i}function ze(e){let{table:t,database:r,expiration:n,eviction:s,scanInterval:i,attributes:o,audit:c,sealed:l,splitSegments:u,replicate:d,trackDeletes:f,schemaDefined:m,origin:p}=e;r||(r=eC);let h=_d({database:r,table:t}),E=Me[r];Cr.trace(`Defining ${t} in ${r}`);let _=E?.[t];if(h.status==="closed")throw new Error(`Can not use a closed data store for ${t}`);let R,S,y;m==null&&(m=!0);let w=new nh(!1);for(let Y of o)Y.attribute&&!Y.name?(Y.name=Y.attribute,Y.indexed=!0):Y.attribute=Y.name,Y.expiresAt&&(Y.indexed=!0);let I,H;if(_){if(R=_.primaryKey,_.primaryStore.rootStore.status==="closed")throw new Error(`Can not use a closed data store from ${t} class`);u==null&&(u=_.splitSegments),_.attributes.splice(0,_.attributes.length,...o)}else{let Y=h.auditStore;S=o.find(Se=>Se.isPrimaryKey)||{},R=S.name,S.is_hash_attribute=S.isPrimaryKey=!0,S.schemaDefined=m,S.compression=MS(),f&&(S.trackDeletes=!0),c=S.audit=typeof c=="boolean"?c:(0,Zt.get)(x.LOGGING_AUDITLOG),n&&(S.expiration=n),s&&(S.eviction=s),u??=!1,S.splitSegments=u,typeof l=="boolean"&&(S.sealed=l),typeof d=="boolean"&&(S.replicate=d),p&&(S.origins?S.origins.includes(p)||S.origins.push(p):S.origins=[p]),Cr.trace(`${t} table loading, opening primary store`);let ce=new nh(!1,!0);ce.compression=S.compression;let de=t+"/";if(y=h.dbisDb=h.openDB(CS.INTERNAL_DBIS_NAME,w),z(),y.get(de))return H&&H(),xd(),ze(e);let te=wg(h.openDB(de,ce),h);h.databaseName=r,te.tableId=y.get(Dd),Cr.trace(`Assigning new table id ${te.tableId} for ${t}`),te.tableId||(te.tableId=1),y.put(Dd,te.tableId+1),S.tableId=te.tableId,_=Qq(E,t,bS({primaryStore:te,auditStore:Y,audit:c,sealed:l,splitSegments:u,replicate:d,trackDeletes:f,expirationMS:n&&n*1e3,evictionMS:s&&s*1e3,primaryKey:R,tableName:t,tableId:te.tableId,databasePath:r,databaseName:r,indices:{},attributes:o,schemaDefined:m,dbisDB:y})),_.schemaVersion=1,I=!0,y.put(de,S)}let X=_.indices;y=y||(h.dbisDb=h.openDB(CS.INTERNAL_DBIS_NAME,w)),_.dbisDB=y;let q=[];for(let{key:Y,value:ce}of y.getRange({start:!0})){let[de,te]=Y.toString().split("/");if(te===""&&(te=ce.name),te){if(de!==t)continue}else continue;let Se=o.find(Ke=>Ke.name===te),Ne=!Se?.indexed&&ce.indexed&&!ce.isPrimaryKey;if((!Se||Ne)&&(z(),I=!0,Se||y.remove(Y),Ne)){let Ke=_.indices[de];Ke&&q.push(Ke)}}let k=[];try{for(let Y of o||[]){if((Y.relationship||Y.computed)&&(I=!0,Y.relationship))continue;let ce=t+"/"+(Y.name||"");Object.defineProperty(Y,"key",{value:ce,configurable:!0});let de=y.get(ce);if(Y.isPrimaryKey){if(de=de||y.get(ce=t+"/")||{},c!==void 0&&c!==_.audit||l!==void 0&&l!==_.sealed||d!==void 0&&d!==_.replicate||(+n||void 0)!==(+de.expiration||void 0)||(+s||void 0)!==(+de.eviction||void 0)||Y.type!==de.type){let Se={...de};typeof c=="boolean"&&(c&&_.enableAuditing(c),Se.audit=c),n&&(Se.expiration=+n),s&&(Se.eviction=+s),l!==void 0&&(Se.sealed=l),d!==void 0&&(Se.replicate=d),Y.type&&(Se.type=Y.type),I=!0,z(),y.put(ce,Se)}continue}de?.attribute&&!de.name&&(de.indexed=!0);let te=!de||de.type!==Y.type||JSON.stringify(de.indexed)!==JSON.stringify(Y.indexed)||de.nullable!==Y.nullable||de.version!==Y.version||de.enumerable!==Y.enumerable||JSON.stringify(de.properties)!==JSON.stringify(Y.properties)||JSON.stringify(de.elements)!==JSON.stringify(Y.elements);if(Y.indexed){let Se=Jq(ce,h,Y);(te||de.indexingPID&&de.indexingPID!==process.pid||de.restartNumber<rh.workerData?.restartNumber)&&(I=!0,z(),de=y.get(ce),(te||de.indexingPID&&de.indexingPID!==process.pid||de.restartNumber<rh.workerData?.restartNumber)&&(I=!0,Y.indexNulls===void 0&&(Y.indexNulls=!0),_.primaryStore.getStats().entryCount>0&&(Y.lastIndexedKey=de?.lastIndexedKey??void 0,Y.indexingPID=process.pid,Se.isIndexing=!0,Object.defineProperty(Y,"dbi",{value:Se}),k.push(Y))),y.put(ce,Y)),de?.indexNulls&&Y.indexNulls===void 0&&(Y.indexNulls=!0),Se.indexNulls=Y.indexNulls,X[Y.name]=Se}else te&&(I=!0,z(),y.put(ce,Y))}}finally{H&&H()}if(I&&(_.schemaVersion++,_.updatedAttributes()),Cr.trace(`${t} table loading, running index`),k.length>0||q.length>0?_.indexingOperation=ice(_,k,q):I&&OS.signalSchemaChange(new PS.SchemaEventMsg(process.pid,"schema-change",_.databaseName,_.tableName)),_.origin=p,I)for(let Y of Zp)Y(_,p!=="cluster");return(n||s||i)&&_.setTTLExpiration({expiration:n,eviction:s,scanInterval:i}),Cr.trace(`${t} table loaded`),_;function z(){H||h.transactionSync(()=>({then(Y){H=Y}}))}a(z,"startTxn")}async function ice(e,t,r){try{Cr.info(`Indexing ${e.tableName} attributes`,t);let n=e.schemaVersion;await OS.signalSchemaChange(new PS.SchemaEventMsg(process.pid,"schema-change",e.databaseName,e.tableName));let s;for(let u of r)s=u.drop();let i,o={},c=0,l=t.length;if(await new Promise(u=>setImmediate(u)),l>0){let u;for(let f of t)(0,Ud.compareKeys)(f.lastIndexedKey,u)<0&&(u=f.lastIndexedKey),f.lastIndexedKey==null&&f.dbi.clearAsync();let d=0;for(let{key:f,value:m,version:p}of e.primaryStore.getRange({start:u,lazy:l<4,versions:!0,snapshot:!1}))if(m){if(d++,s=e.primaryStore.ifVersion(f,p,()=>{for(let h=0;h<l;h++){let E=t[h],_=E.name,R=E.dbi;try{let S=E.resolve,y=m&&(S?S(m):m[_]);if(R.customIndex){R.customIndex.index(f,y);continue}let w=(0,Kq.getIndexedValues)(y,R.indexNulls);if(w)for(let I=0,H=w.length;I<H;I++)R.put(w[I],f)}catch(S){o[_]||(o[_]=!0,Cr.error(`Error indexing attribute ${_}`,S))}}}),s.then(()=>d--,h=>{d--,Cr.error(h)}),rh.workerData&&rh.workerData.restartNumber!==Wq.restartNumber&&(i=!0),++c%100===0||i){for(let h of t)h.lastIndexedKey=f,e.dbisDB.put(h.key,h);if(i)return}d>nce?await s:d>sce&&await new Promise(h=>setImmediate(h))}for(let f of t)delete f.lastIndexedKey,delete f.indexingPID,f.dbi.isIndexing=!1,s=e.dbisDB.put(f.key,f)}await s,await OS.signalSchemaChange(new PS.SchemaEventMsg(process.pid,"indexing-finished",e.databaseName,e.tableName)),Cr.info(`Finished indexing ${e.tableName} attributes`,t)}catch(n){Cr.error("Error in indexing",n)}}function oce({table:e,database:t}){let r=_d({database:t,table:e}),n=[],s=r.dbisDb;for(let i of s.getKeys({start:e+"/",end:e+"0"}))n.push(s.remove(i));return Promise.all(n)}function $l(e){return Zp.push(e),{remove(){let t=Zp.indexOf(e);t>-1&&Zp.splice(t,1)}}}function sh(e){return eh.push(e),{remove(){let t=eh.indexOf(e);t>-1&&eh.splice(t,1)}}}function MS(){let e=(0,Zt.get)(x.STORAGE_COMPRESSION),t=(0,Zt.get)(x.STORAGE_COMPRESSION_DICTIONARY),r=(0,Zt.get)(x.STORAGE_COMPRESSION_THRESHOLD)||jq,n={startingOffset:32};return t&&(n.dictionary=th.readFileSync(t)),r&&(n.threshold=r),e&&n}var Zt,CS,Ud,Ht,_s,vd,XN,th,ZN,Kq,OS,PS,rh,Yq,Wq,DS,tce,Cr,eC,vS,jq,NS,yn,Me,Dd,Zp,eh,LS,ia,Md,nce,sce,Oe=se(()=>{Zt=b(fe()),CS=b(Qt()),Ud=require("lmdb"),Ht=require("path"),_s=require("fs"),vd=b(bt());Lg();XN=b(fp());G();th=b(require("fs-extra")),ZN=b(oi()),Kq=b(xn()),OS=b(ea()),PS=b(us()),rh=require("worker_threads"),Yq=b(J()),Wq=b(st());Vi();hl();is();Vq();DS=b(dp()),{forComponent:tce}=Yq.default;a(nh,"OpenDBIObject");Cr=tce("storage"),eC="data",vS=Symbol("defined-tables"),jq=((0,Zt.get)(x.STORAGE_PAGESIZE)||4096)-60;(0,Zt.initSync)();NS=["hdb_temp","hdb_certificate","hdb_raw_analytics","hdb_session_will","hdb_job","hdb_info"],yn=Object.create(null),Me=Object.create(null);(0,ZN._assignPackageExport)("databases",Me);(0,ZN._assignPackageExport)("tables",yn);Dd=Symbol.for("next-table-id"),Zp=[],eh=[],ia=new Map;a(rce,"getTables");a(lt,"getDatabases");a(xd,"resetDatabases");a(Xp,"readMetaDb");a(zq,"ensureDB");a(Qq,"setTable");a(_d,"database");a(Jw,"dropDatabase");a(Jq,"openIndex");a(ze,"table");nce=1e3,sce=10;a(ice,"runIndexing");a(oce,"dropTableMeta");a($l,"onUpdatedTable");a(sh,"onRemovedDB");a(MS,"getDefaultCompression")});var nC={};ye(nC,{loadGQLSchema:()=>lce,start:()=>rC,startOnMainThread:()=>cce});function rC({ensureTable:e}){return{handleFile:t,setupFile:t};async function t(r,n,s,i){let{parse:o,Source:c,Kind:l,NamedTypeNode:u,StringValueNode:d}=await import("graphql"),f=o(new c(r.toString(),s)),m=new Map,p=[],h;for(let R of f.definitions)switch(R.kind){case l.OBJECT_TYPE_DEFINITION:let H=function(q){if(q.kind==="NonNullType"){let Y=H(q.type);return Y.nullable=!1,Y}if(q.kind==="ListType")return{type:"array",elements:H(q.type)};let z={type:q.name?.value};return Object.defineProperty(z,"location",{value:q.loc.startToken}),z};a(H,"getProperty");let S=R.name.value,y=[],w={table:null,database:null,properties:y};m.set(S,w),i.allTypes.set(S,w);for(let q of R.directives){if(q.name.value==="table"){for(let z of q.arguments)w[z.name.value]=z.value.value;w.schema&&(w.database=w.schema),w.table||(w.table=S),w.audit&&(w.audit=w.audit!=="false"),w.attributes=w.properties,p.push(w)}if(q.name.value==="sealed"&&(w.sealed=!0),q.name.value==="splitSegments"&&(w.splitSegments=!0),q.name.value==="replicate"&&(w.replicate=!0),q.name.value==="export"){w.export=!0;for(let z of q.arguments)typeof w.export!="object"&&(w.export={}),w.export[z.name.value]=z.value.value}}let I=!1,X={};for(let q of R.fields){let k=H(q.type);k.name=q.name.value,y.push(k),X[k.name]=void 0;for(let z of q.directives){let Y=z.name.value;if(Y==="primaryKey")I?console.warn("Can not define two attributes as a primary key at",z.loc):(k.isPrimaryKey=!0,I=!0);else if(Y==="indexed"){let ce={};for(let de of z.arguments||[])ce[de.name.value]=de.value.value;k.indexed=ce}else if(Y==="computed"){for(let ce of z.arguments||[])if(ce.name.value==="from"){let de=ce.value.value;k.computed={from:_(de,ce,X)},k.version==null&&(k.version=de)}else ce.name.value==="version"&&(k.version=ce.value.value);k.computed=k.computed||!0}else if(Y==="relationship"){let ce={};for(let de of z.arguments)ce[de.name.value]=de.value.value;k.relationship=ce}else if(Y==="createdTime")k.assignCreatedTime=!0;else if(Y==="updatedTime")k.assignUpdatedTime=!0;else if(Y==="expiresAt")k.expiresAt=!0;else if(Y==="enumerable")k.enumerable=!0;else if(Y==="allow"){let ce=k.authorizedRoles=[];for(let de of z.arguments)de.name.value==="role"&&ce.push(de.value.value)}else server.knownGraphQLDirectives.includes(Y)&&console.warn(`@${Y} is an unknown directive, at`,z.loc)}}w.type=S,S==="Query"&&(h=w)}function E(R){let S=m.get(R.type);S?(Object.defineProperty(R,"properties",{value:S.properties}),Object.defineProperty(R,"definition",{value:S})):R.type==="array"?E(R.elements):ace.includes(R.type)||(0,Zq.getWorkerIndex)()===0&&console.error(`The type ${R.type} is unknown at line ${R.location.line}, column ${R.location.column}, in ${s}`)}a(E,"connectPropertyType");for(let R of m.values())for(let S of R.properties)E(S);for(let R of p)R.tableClass=e(R),R.export&&(R.export.name===""?i.set((0,tC.dirname)(n),R.tableClass):i.set((0,tC.dirname)(n)+"/"+(R.export.name||R.type),R.tableClass,R.export));function _(R,S,y){return new Xq.Script(`function computed(attributes) { return function(record) { with(attributes) { with (record) { return ${R}; } } } } computed;`,{filename:s,lineOffset:S.loc.startToken.line-1,columnOffset:S.loc.startToken.column}).runInThisContext()(y)}a(_,"createComputedFrom")}}var tC,Xq,Zq,ace,cce,lce,e$=se(()=>{tC=require("path"),Xq=require("node:vm");Oe();Zq=b(st());nc();ace=["ID","Int","Float","Long","String","Boolean","Date","Bytes","Any","BigInt","Blob"];server.knownGraphQLDirectives||(server.knownGraphQLDirectives=[]);server.knownGraphQLDirectives.push("table","sealed","export","primaryKey","indexed","computed","relationship","createdTime","updatedTime","expiresAt","allow","enumerable");a(rC,"start");cce=rC,lce=a(e=>rC({ensureTable:ze}).handleFile(e,null,null,new ad),"loadGQLSchema")});var iC={};ye(iC,{start:()=>gce});function uce(e){if(e.kind!==qe.Kind.OPERATION_DEFINITION&&e.kind!==qe.Kind.FRAGMENT_DEFINITION)throw new Vr(`Unexpected non-executable definition type ${e.kind}.`)}function t$(e){if(typeof e!="object"||e===null)throw new uo("Request body must be an object.");if(!("query"in e))throw new uo("Request body must contain a `query` field.");if(typeof e.query!="string")throw new uo("Request body `query` field must be a string.");if("variables"in e&&(typeof e.variables!="object"||e.variables===null))throw new uo("Request body `variables` field must be an object.");if("operationName"in e&&typeof e.operationName!="string")throw new uo("Request body `operationName` field must be a string.")}function sC(e){return parseInt(e.value,10)}function n$(e){return parseFloat(e.value)}function s$(e,t,r){let n=r.get(e.name.value);return i$(n)?o$(n,t):{attribute:t,value:n}}function i$(e){return typeof e=="object"&&e!=null&&!Array.isArray(e)}function o$(e,t){return t=typeof t=="string"?[t]:t,Object.entries(e).flatMap(([r,n])=>(t=[...t,r],i$(n)?o$(n,t):{attribute:t,value:n}))}function dce(e,t,r){switch(t=[...t,e.name.value],e.value.kind){case qe.Kind.NULL:return{attribute:t,value:null};case qe.Kind.INT:return{attribute:t,value:sC(e.value)};case qe.Kind.FLOAT:return{attribute:t,value:n$(e.value)};case qe.Kind.BOOLEAN:case qe.Kind.STRING:return{attribute:t,value:e.value.value};case qe.Kind.VARIABLE:return s$(e.value,t,r);case qe.Kind.OBJECT:return a$(e.value,t,r);case qe.Kind.LIST:case qe.Kind.ENUM:default:throw new Vr(`Value type, ${e.value.kind}, is not supported.`)}}function a$(e,t,r){return e.fields.flatMap(n=>dce(n,t,r))}function fce(e,t){switch(e.value.kind){case qe.Kind.NULL:return{attribute:e.name.value,value:null};case qe.Kind.INT:return{attribute:e.name.value,value:sC(e.value)};case qe.Kind.FLOAT:return{attribute:e.name.value,value:n$(e.value)};case qe.Kind.BOOLEAN:case qe.Kind.STRING:return{attribute:e.name.value,value:e.value.value};case qe.Kind.VARIABLE:return s$(e.value,e.name.value,t);case qe.Kind.OBJECT:return a$(e.value,[e.name.value],t);case qe.Kind.LIST:case qe.Kind.ENUM:default:throw new Vr(`Argument type, ${e.value.kind}, is not supported.`)}}function mce(e,t){return e.flatMap(r=>fce(r,t))}function US(e,t){return e.selections.flatMap(r=>{switch(r.kind){case qe.Kind.FIELD:return r;case qe.Kind.FRAGMENT_SPREAD:{let n=r.name.value,s=t.get(n);if(s==null)throw new Vr(`Fragment \`${n}\` not found.`);return US(s.selectionSet,t)}case qe.Kind.INLINE_FRAGMENT:return US(r.selectionSet,t)}})}function c$(e,t){return US(e,t).map(r=>r.selectionSet?.selections.length>0?{name:r.name.value,select:c$(r.selectionSet,t)}:r.name.value)}async function pce(e,t,r,n){let s=Bs.getMatch(e.name.value,"graphql");if(s===void 0)throw new Vr(`Resource \`${e.name.value}\` not found.`);let i=s.Resource,o={select:c$(e.selectionSet,r),conditions:mce(e.arguments,t)},c=[];n.authorize=!0;for await(let l of i.search(o,n))c.push(l);return[e.name.value,c]}function l$(e){switch(e.kind){case qe.Kind.NULL:return null;case qe.Kind.INT:return sC(e);case qe.Kind.FLOAT:return parseFloat(e.value);case qe.Kind.STRING:case qe.Kind.BOOLEAN:return e.value;case qe.Kind.OBJECT:return e.fields.reduce((t,r)=>({[r.name.value]:l$(r.value),...t}),{});case qe.Kind.LIST:case qe.Kind.ENUM:default:throw new Vr(`Value type, ${e.kind}, is not supported.`)}}function hce(e,t){let r=new Map;for(let n of e){let s=n.variable.name.value,i=t?.[s];if(i===void 0&&n.defaultValue!==void 0&&(i=l$(n.defaultValue)),n.type.kind===qe.Kind.NON_NULL_TYPE&&!(s in t)&&i===void 0)throw new Vr(`Variable $${s} is required, but not provided.`);r.set(n.variable.name.value,i??null)}return r}async function Ece(e,t,r,n){if(e.operation===qe.OperationTypeNode.SUBSCRIPTION)throw new Vr("Subscriptions are not supported.");if(e.operation===qe.OperationTypeNode.MUTATION)throw new Vr("Mutations are not supported yet.");let s=hce(e.variableDefinitions,t),i=await Promise.all(US(e.selectionSet,r).map(c=>pce(c,s,r,n))),o={data:{}};for(let[c,l]of i)o.data[c]=l;return o}async function r$({query:e,variables:t={},operationName:r},n){let s=qe.parse(e),i=new Map,o=new Map;for(let u of s.definitions)if(uce(u),u.kind===qe.Kind.FRAGMENT_DEFINITION)o.set(u.name.value,u);else{if(u.name===void 0&&s.definitions.length>1)throw new Vr("Unnamed operations are only allowed when there is a single operation in the document.");let d=u.name?.value??"Unnamed Query";if(i.has(d))throw new Vr(`Duplicate operation definition: ${d}`);i.set(d,u)}let c;if(r==null)if(i.size===1)c=i.entries().next().value[1];else throw new Vr("Operation name is required when there are multiple operations in the document.");else if(c=i.get(r),c==null)throw new Vr(`Operation \`${r}\` not found.`);let l=await Ece(c,t,o,n);return{status:200,headers:{"Content-Type":"application/graphql-response+json; charset=utf-8"},body:JSON.stringify(l)}}async function _ce(e){switch(e.method){case"GET":{let t=new URLSearchParams(e.url.split("?")[1]),r={};for(let[n,s]of t)r[n]=n==="variables"||n==="extensions"?JSON.parse(s):s;return t$(r),r$(r,e)}case"POST":{let r=await Ko(e.headers.get("content-type"),!0)(e._nodeRequest);return t$(r),r$(r,e)}default:throw new uo("Method Not Allowed",405,{Allow:"GET, POST"})}}function gce(e){e.server.http(async(t,r)=>{if(!t.url.startsWith("/graphql"))return r(t);try{return await _ce(t)}catch(n){logger.error(n);let s=t.headers.get("accept")??"application/graphql-response+json";switch(s){case"application/json":{if(n instanceof uo)return{status:n.statusCode,body:JSON.stringify({errors:[{message:n.message}]}),headers:{"Content-Type":"application/json",...n.headers}};if(n instanceof qe.GraphQLError)return{status:200,body:JSON.stringify({errors:[n]}),headers:{"Content-Type":"application/json"}};if(n instanceof Vr)return{status:200,body:JSON.stringify({errors:[{message:n.message}]}),headers:{"Content-Type":"application/json"}};if(n instanceof Error)return{status:500,body:JSON.stringify({errors:[{message:n.message}]}),headers:{"Content-Type":"application/json"}};break}default:logger.info(`Unsupported accept header, ${s}, defaulting to application/graphql-response+json`);case"application/graphql-response+json":{if(n instanceof uo)return{status:n.statusCode,body:JSON.stringify({errors:[{message:n.message}]}),headers:{"Content-Type":"application/graphql-response+json",...n.headers}};if(n instanceof qe.GraphQLError)return{status:400,body:JSON.stringify({errors:[n]}),headers:{"Content-Type":"application/graphql-response+json"}};if(n instanceof Vr)return{status:400,body:JSON.stringify({errors:[{message:n.message}]}),headers:{"Content-Type":"application/graphql-response+json"}};if(n instanceof Error)return{status:500,body:JSON.stringify({errors:[{message:n.message}]}),headers:{"Content-Type":"application/graphql-response+json"}};break}}throw n}},{port:e.port,securePort:e.securePort})}var qe,Vr,uo,u$=se(()=>{qe=b(require("graphql"));Yo();nc();a(uce,"assertExecutableDefinitionNode");a(t$,"assertRequestParams");a(sC,"processIntValueNode");a(n$,"processFloatValueNode");a(s$,"processVariableNode");a(i$,"isObject");a(o$,"transformObjectIntoQueryCondition");a(dce,"processObjectFieldNode");a(a$,"processObjectValueNode");a(fce,"processArgumentNode");a(mce,"buildConditionsQuery");a(US,"fillInFragments");a(c$,"buildSelectQuery");a(pce,"processFieldNode");a(l$,"processConstValueNode");a(hce,"resolveVariables");a(Ece,"executeOperation");a(r$,"resolver");Vr=class extends Error{static{a(this,"GraphQLQueryingError")}},uo=class extends Error{static{a(this,"HTTPError")}statusCode;headers;constructor(t,r=400,n={}){super(t),this.statusCode=r,this.headers=n}};a(_ce,"graphqlQueryingHandler");a(gce,"start")});var E$=M((uxe,h$)=>{var Bd=require("validate.js"),f$=mt(),Fd=(G(),D(j)),{handleHDBError:Sce,hdbErrors:Tce}=Ee(),{HDB_ERROR_MSGS:ar,HTTP_STATUS_CODES:yce}=Tce,oC=a(()=>({role:{presence:!0,format:"[\\w\\-\\_]+"},id:{presence:!0,format:"[\\w\\-\\_]+"},permission:{presence:!0}}),"constraintsTemplate"),Rce={STRUCTURE_USER:"structure_user"},d$=Object.values(Fd.ROLE_TYPES_ENUM),bce="attribute_permissions",Ace="attribute_name",{PERMS_CRUD_ENUM:kd}=Fd,Ice=[bce,...Object.values(kd)],m$=[kd.READ,kd.INSERT,kd.UPDATE],wce=[Ace,...m$];function Nce(e){let t=oC();return t.role.presence=!0,t.id.presence=!1,t.permission.presence=!0,p$(e,t)}a(Nce,"addRoleValidation");function Cce(e){let t=oC();return t.role.presence=!1,t.id.presence=!0,t.permission.presence=!0,p$(e,t)}a(Cce,"alterRoleValidation");function Oce(e){let t=oC();return t.role.presence=!1,t.id.presence=!0,t.permission.presence=!1,f$.validateObject(e,t)}a(Oce,"dropRoleValidation");var Pce=["operation","role","id","permission","hdb_user","access"];function p$(e,t){let r={main_permissions:[],schema_permissions:{}},n=Object.keys(e),s=[];for(let o=0,c=n.length;o<c;o++)Pce.includes(n[o])||s.push(n[o]);s.length>0&&Er(ar.INVALID_ROLE_JSON_KEYS(s),r);let i=f$.validateObject(e,t);if(i&&i.message.split(",").forEach(o=>{Er(o,r)}),e.permission){let o=Lce(e);o&&Er(o,r),d$.forEach(c=>{e.permission[c]&&!Bd.isBoolean(e.permission[c])&&Er(ar.SU_CU_ROLE_BOOLEAN_ERROR(c),r)})}for(let o in e.permission)if(d$.indexOf(o)<0){if(o===Rce.STRUCTURE_USER){let l=e.permission[o];if(typeof l=="boolean")continue;if(Array.isArray(l)){for(let u=0,d=l.length;u<d;u++){let f=l[u];global.hdb_schema[f]||Er(ar.SCHEMA_NOT_FOUND(f),r)}continue}Er(ar.STRUCTURE_USER_ROLE_TYPE_ERROR(o),r);continue}let c=e.permission[o];if(!o||!global.hdb_schema[o]){Er(ar.SCHEMA_NOT_FOUND(o),r);continue}if(c.tables)for(let l in c.tables){let u=c.tables[l];if(!l||!global.hdb_schema[o][l]){Er(ar.TABLE_NOT_FOUND(o,l),r);continue}if(Object.keys(u).forEach(d=>{Ice.includes(d)||Er(ar.INVALID_PERM_KEY(d),r,o,l)}),Object.values(kd).forEach(d=>{Bd.isDefined(u[d])?Bd.isBoolean(u[d])||Er(ar.TABLE_PERM_NOT_BOOLEAN(d),r,o,l):Er(ar.TABLE_PERM_MISSING(d),r,o,l)}),u.attribute_permissions===void 0){Er(ar.ATTR_PERMS_ARRAY_MISSING,r,o,l);continue}else if(!(Array.isArray(u.attribute_permissions)||u.attribute_permissions===null)){Er(ar.ATTR_PERMS_NOT_ARRAY,r,o,l);continue}if(u.attribute_permissions){let d=global.hdb_schema[o][l].attributes.map(({attribute:m})=>m),f={read:!1,insert:!1,update:!1};for(let m in u.attribute_permissions){let p=u.attribute_permissions[m];if(Object.keys(p).forEach(E=>{!wce.includes(E)&&E!==kd.DELETE&&Er(ar.INVALID_ATTR_PERM_KEY(E),r,o,l)}),!Bd.isDefined(p.attribute_name)){Er(ar.ATTR_PERM_MISSING_NAME,r,o,l);continue}let h=p.attribute_name;if(!d.includes(h)){Er(ar.INVALID_ATTRIBUTE_IN_PERMS(h),r,o,l);continue}m$.forEach(E=>{Bd.isDefined(p[E])?Bd.isBoolean(p[E])||Er(ar.ATTR_PERM_NOT_BOOLEAN(E,h),r,o,l):Er(ar.ATTR_PERM_MISSING(E,h),r,o,l)}),!f.read&&p.read===!0&&(f.read=!0),!f.insert&&p.insert===!0&&(f.insert=!0),!f.update&&p.update===!0&&(f.update=!0)}if(u.read===!1&&f.read===!0||u.insert===!1&&f.insert===!0||u.update===!1&&f.update===!0){let m=`${o}.${l}`;Er(ar.MISMATCHED_TABLE_ATTR_PERMS(m),r,o,l)}}}}return Dce(r)}a(p$,"customValidate");h$.exports={addRoleValidation:Nce,alterRoleValidation:Cce,dropRoleValidation:Oce};function Lce(e){let{operation:t,permission:r}=e;if(t===Fd.OPERATIONS_ENUM.ADD_ROLE||t===Fd.OPERATIONS_ENUM.ALTER_ROLE){let n=r.super_user===!0,s=r.cluster_user===!0;if(Object.keys(r).length>1&&(n||s)){if(s&&n)return ar.SU_CU_ROLE_COMBINED_ERROR;{let o=r.super_user?Fd.ROLE_TYPES_ENUM.SUPER_USER:Fd.ROLE_TYPES_ENUM.CLUSTER_USER;return ar.SU_CU_ROLE_NO_PERMS_ALLOWED(o)}}}return null}a(Lce,"validateNoSUPerms");function Dce(e){let{main_permissions:t,schema_permissions:r}=e;if(t.length>0||Object.keys(r).length>0){let n={error:ar.ROLE_PERMS_ERROR,...e};return Sce(new Error,n,yce.BAD_REQUEST)}else return null}a(Dce,"generateRolePermResponse");function Er(e,t,r,n){if(!r)t.main_permissions.push(e);else{let s=n?r+"_"+n:r;t.schema_permissions[s]?t.schema_permissions[s].push(e):t.schema_permissions[s]=[e]}}a(Er,"addPermError")});var oh=M((mxe,T$)=>{"use strict";var _$=Vn(),g$=Sn(),vce=xl(),cC=E$(),lC=ea(),fxe=require("uuid").v4,Mce=require("util"),xS=(G(),D(j)),Uce=ae(),uC=g$.searchByValue,xce=g$.searchByHash,Bce=Mce.promisify(vce.delete),Fce=di(),kce=hd(),{hdbErrors:Hce,handleHDBError:Vl}=Ee(),{HDB_ERROR_MSGS:S$,HTTP_STATUS_CODES:ih}=Hce,{UserEventMsg:dC}=us();T$.exports={addRole:Gce,alterRole:qce,dropRole:$ce,listRoles:Vce};function aC(e){try{e.hdb_auth_header&&delete e.hdb_auth_header,e.HDB_INTERNAL_PATH&&delete e.HDB_INTERNAL_PATH,e.operation&&delete e.operation,e.hdb_user&&delete e.hdb_user}catch{}return e}a(aC,"scrubRoleDetails");async function Gce(e){let t=cC.addRoleValidation(e);if(t)throw t;e=aC(e);let r={schema:"system",table:"hdb_role",attribute:"role",value:e.role,hash_attribute:"id",get_attributes:["*"]},n;try{n=Array.from(await uC(r)||[])}catch(i){throw Vl(i)}if(n&&n.length>0)throw Vl(new Error,S$.ROLE_ALREADY_EXISTS(e.role),ih.CONFLICT,void 0,void 0,!0);e.id||(e.id=e.role);let s={operation:"insert",schema:"system",table:"hdb_role",hash_attribute:"id",records:[e]};return await _$.insert(s),lC.signalUserChange(new dC(process.pid)),e=aC(e),e}a(Gce,"addRole");async function qce(e){let t=cC.alterRoleValidation(e);if(t)throw t;e=aC(e);let r={operation:"update",schema:"system",table:"hdb_role",records:[e]},n;try{n=await _$.update(r)}catch(s){throw Vl(s)}if(n&&n?.message==="updated 0 of 1 records")throw Vl(new Error,"Invalid role id",ih.BAD_REQUEST,void 0,void 0,!0);return await lC.signalUserChange(new dC(process.pid)),e}a(qce,"alterRole");async function $ce(e){let t=cC.dropRoleValidation(e);if(t)throw Vl(new Error,t,ih.BAD_REQUEST,void 0,void 0,!0);let r=new kce(xS.SYSTEM_SCHEMA_NAME,xS.SYSTEM_TABLE_NAMES.ROLE_TABLE_NAME,[e.id],["role"]),n=Array.from(await xce(r));if(n.length===0)throw Vl(new Error,S$.ROLE_NOT_FOUND,ih.NOT_FOUND,void 0,void 0,!0);let s=new Fce(xS.SYSTEM_SCHEMA_NAME,xS.SYSTEM_TABLE_NAMES.USER_TABLE_NAME,"role",e.id,void 0,["username","active"]),i=Array.from(await uC(s)),o=!1;if(Uce.isEmptyOrZeroLength(i)===!1){for(let l=0;l<i.length;l++)if(i[l].active===!0){o=!0;break}}if(o===!0)throw Vl(new Error,`Cannot drop role ${n[0].role} as it has active user(s) tied to this role`,ih.CONFLICT,void 0,void 0,!0);let c={table:"hdb_role",schema:"system",hash_values:[e.id]};return await Bce(c),lC.signalUserChange(new dC(process.pid)),`${n[0].role} successfully deleted`}a($ce,"dropRole");async function Vce(){return uC({table:"hdb_role",schema:"system",hash_attribute:"id",attribute:"id",value:"*",get_attributes:["*"]})}a(Vce,"listRoles")});var fC={};ye(fC,{start:()=>b$,startOnMainThread:()=>Wce});function b$({ensureTable:e}){return{handleFile:t,setupFile:t};async function t(r){let n=(0,y$.parseDocument)(r.toString(),{simpleKeys:!0}).toJSON();for(let s in n){let i=n[s];i.permission||(i={permission:i},i.permission.access&&(i.access=i.permission.access,delete i.permission.access));for(let o in i.permission){if(Kce.includes(o))continue;let c=i.permission[o];c.tables||(i.permission[o]=c={tables:c});for(let l in c.tables){let u=c.tables[l];if(u.read=!!u.read,u.insert=!!u.insert,u.update=!!u.update,u.delete=!!u.delete,u.attributes){let d=[];for(let f in u.attributes){let m=u.attributes[f];m.attribute_name=f,d.push(m)}u.attribute_permissions=d,delete u.attributes}if(u.attribute_permissions){if(!Array.isArray(u.attribute_permissions))throw new Error("attribute_permissions must be an array if defined");for(let d of u.attribute_permissions)d.read=!!d.read,d.insert=!!d.insert,d.update=!!d.update}else u.attribute_permissions=null}}i.role=i.id=s,await Yce(i)}}}async function Yce(e){let t=lt().system.hdb_role;for await(let r of t.search([{attribute:"role",value:e.role}])){let{__createdtime__:n,__updatedtime__:s,...i}=r;return(0,R$.isEqual)(i,e)?void 0:(e.id=r.id,(0,BS.alterRole)(e))}return(0,BS.addRole)(e)}var BS,y$,R$,Kce,Wce,A$=se(()=>{Oe();BS=b(oh()),y$=require("yaml"),R$=require("lodash"),Kce=["super_user","cluster_user","structure_user"];a(b$,"start");a(Yce,"ensureRole");Wce=b$});async function FS(e){let t=(0,N$.pathToFileURL)(e).toString();if(jce)return ah||(ah=zce(Jce)),(await(await ah).import(t)).namespace;try{return await import(t)}catch(r){try{(await import("internal/util")).default.decorateErrorStack(r)}catch{}throw r}}async function zce(e){let{StaticModuleRecord:t}=await import("@endo/static-module-record");return require("ses"),lockdown({domainTaming:"unsafe",consoleTaming:"unsafe",errorTaming:"unsafe",errorTrapping:"none",stackFiltering:"verbose"}),ah=new Compartment({console,Math,Date,fetch:Qce,...e()},{},{name:"h-dapp",resolveHook(r,n){return r==="harperdb"?"harperdb":(r=new URL(r,n).toString(),(0,w$.extname)(r)||(r+=".js"),r)},importHook:a(async r=>{if(r==="harperdb")return{imports:[],exports:["Resource","tables","databases"],execute(s){s.Resource=Xt,s.tables=yn,s.databases=Me}};let n=await(0,I$.readFile)(new URL(r),{encoding:"utf-8"});return new t(n,r)},"importHook")}),ah}function Qce(e,t){let r=typeof e=="string"||e.url;if(new URL(r).protocol!="https")throw new Error("Only https is allowed in fetch");return fetch(e,t)}function Jce(){return{Resource:Xt,tables:yn}}var I$,w$,N$,jce,ah,mC=se(()=>{Qi();Oe();I$=require("fs/promises"),w$=require("path"),N$=require("url"),jce=!1;a(FS,"secureImport");a(zce,"getCompartment");a(Qce,"secureOnlyFetch");a(Jce,"getGlobalVars")});var pC={};ye(pC,{ResourceLoadError:()=>kS,handleApplication:()=>Xce,suppressHandleApplicationWarning:()=>Zce});function O$(e){return typeof e=="function"&&("get"in e||"put"in e||"post"in e||"delete"in e)}async function Xce(e){e.handleEntry(a(async function(r){if(r.entryType!=="file"){e.logger.warn(`jsResource plugin cannot handle entry type ${r.entryType}. Modify the 'files' option in ${e.configFilePath} to only include files.`);return}if(r.eventType!=="add"){e.requestRestart();return}try{let n=await FS(r.absolutePath),s=(0,C$.dirname)(r.urlPath).replace(/\\/g,"/").replace(/^\/$/,"");O$(n.default)&&(e.resources.set(s,n.default),e.logger.debug(`Registered root resource: ${s}`)),P$(e,n,s)}catch(n){throw new kS(r.absolutePath,n)}},"handleResourceEntry"))}function P$(e,t,r){for(let n in t){let s=t[n],i=`${r}/${n}`;O$(s)?(e.resources.set(i,s),e.logger.debug(`Registered resource: ${i}`)):typeof s=="object"&&P$(e,s,i)}}var C$,kS,Zce,L$=se(()=>{mC();C$=require("path");a(O$,"isResource");kS=class extends Error{static{a(this,"ResourceLoadError")}filePath;cause;constructor(t,r){super(`Failed to load resource module ${t}${r?`: ${r.message}`:""}`),this.name="ResourceLoadError",this.filePath=t,this.cause=r}};a(Xce,"handleApplication");a(P$,"recurseForResources");Zce=!0});var EC={};ye(EC,{start:()=>ele});function ele({resources:e}){e.set("login",hC),e.loginPath=t=>"/login?redirect="+encodeURIComponent(t.url)}var hC,D$=se(()=>{Qi();a(ele,"start");hC=class extends Xt{static{a(this,"Login")}static async get(t,r,n){}static async post(t,r,n){let{username:s,password:i,redirect:o}=r;return{data:await n.login(s,i)}}}});function GS(e,t){let r={openapi:tle,info:{title:"HarperDB HTTP REST interface",version:F$.packageJson.version},servers:[{description:"REST API",url:t}],paths:{},components:{schemas:{},securitySchemes:{basicAuth:{type:"http",scheme:"basic"},bearerAuth:{type:"http",scheme:"bearer",bearerFormat:"JWT"}}}},n=[{basicAuth:[],bearerAuth:[]}],s=a(i=>{if(i.type&&!r.components.schemas[i.type]){r.components.schemas[i.type]={};let o={},c=[];for(let l of i.properties)HS[l.type]?o[l.name]=new gC(HS[l.type],l.type):l.properties?(o[l.name]=new H$(l.type),s(l)):l.elements?.properties&&(o[l.name]=new ile(l.elements.type),s(l.elements)),l.nullable===!1&&c.push(l.name);r.components.schemas[i.type]=new B$(o,!i.sealed,c)}},"includeDefinitionInSchema");for(let[,i]of e){if(!i.path||i.Resource.isError)continue;let{path:o}=i,c=o.split("/").pop(),{attributes:l,sealed:u}=i.Resource,{prototype:d,primaryKey:f="id"}=i.Resource;if(!l&&e.allTypes.has(i.path)){let k=e.allTypes.get(i.path);u=k.sealed,l=k.properties}if(!f)continue;let m={},p=[],h=[];if(l)for(let{type:k,name:z,elements:Y,relationship:ce,definition:de,nullable:te}of l){let Se=de??Y?.definition;Se&&s(Se),te===!1&&h.push(z),ce?k==="array"?m[z]={type:"array",items:{$ref:$s+Y.type}}:m[z]={$ref:$s+k}:Se?k==="array"?m[z]={type:"array",items:{$ref:$s+Se.type}}:m[z]={$ref:$s+Se.type}:k==="array"?Y.type==="Any"?m[z]={type:"array",items:{format:Y.type}}:m[z]={type:"array",items:new gC(HS[Y.type],Y.type)}:k==="Any"?m[z]={format:k}:m[z]=new gC(HS[k],k),p.push(new SC(z,"query",m[z]))}let E=Object.keys(m),_=new SC(f,"path",{type:"string",format:"ID"});_.required=!0,_.description="primary key of record";let R=new SC("property","path",{enum:E});R.required=!0,r.components.schemas[c]=new B$(m,!u,h);let S=d.post!==Resource.prototype.post||d.update,y=typeof d.put=="function",w=typeof d.get=="function",I=typeof d.delete=="function",H=typeof d.patch=="function",X=`/${o}/`;r.paths[X]||(r.paths[X]={}),S&&(r.paths[X].post=new rle(c,n,{200:new Hd({$ref:$s+c},{Location:{description:"primary key of new record",schema:{type:"string",format:"ID"}}})},"create a new record auto-assigning a primary key")),r.paths[X].options=new v$(p,n,{200:new M$},"retrieve information about the communication options available for a target resource or the server as a whole, without performing any resource action"),w&&(r.paths[X].get=new _C(p,n,{200:new Hd({type:"array",items:{$ref:$s+c}})},"search for records by the specified property name and value pairs")),I&&(r.paths[X].delete=new x$(p,n,"delete all the records that match the provided query",{204:new U$}));let q="/"+o+"/{"+f+"}";if(r.paths[q]||(r.paths[q]={}),r.paths[q].options=new v$(p,n,{200:new M$},"retrieve information about the communication options available for a target resource or the server as a whole, without performing any resource action"),w&&(r.paths[q].get=new _C([_],n,{200:new Hd({$ref:$s+c})},"retrieve a record by its primary key")),y&&(r.paths[q].put=new nle([_],n,c,{200:new Hd({$ref:$s+c})},"create or update the record with the URL path that maps to the record's primary key")),H&&(r.paths[q].patch=new sle([_],n,c,{200:new Hd({$ref:$s+c})},"patch the record with the URL path that maps to the record's primary key")),I&&(r.paths[q].delete=new x$([_],n,"delete a record with the given primary key",{204:new U$})),w&&R.schema.enum.length>0){let k=`/${o}/{${f}}.{property}`;r.paths[k]||(r.paths[k]={}),r.paths[k].get=new _C([_,R],n,{200:new Hd({enum:E})},"used to retrieve the specified property of the specified record")}}for(let[,i]of e.allTypes)s(i),i.sealed&&r.components.schemas[i.type].additionalProperties&&(r.components.schemas[i.type].additionalProperties=!1);return r}function rle(e,t,r,n){this.description=n,this.requestBody={content:{"application/json":{schema:{$ref:$s+e}}}},this.security=t,this.responses=r}function _C(e,t,r,n){this.description=n,this.parameters=e,this.security=t,this.responses=r}function v$(e,t,r,n){this.description=n,this.parameters=e,this.security=t,this.responses=r}function M$(){this.description=k$,this.headers={},this.content={}}function Hd(e,t){this.description=k$,this.content={"application/json":{schema:e}},this.headers=t}function U$(){this.description="successfully processed request, no content returned to client"}function nle(e,t,r,n,s){this.description=s,this.parameters=e,this.security=t,this.requestBody={content:{"application/json":{schema:{$ref:$s+r}}}},this.responses=n}function sle(e,t,r,n,s){this.description=s,this.parameters=e,this.security=t,this.requestBody={content:{"application/json":{schema:{$ref:$s+r}}}},this.responses=n}function x$(e,t,r,n){this.description=r,this.parameters=e,this.security=t,this.responses=n}function B$(e,t,r){this.type="object",this.properties=e,this.additionalProperties=t,this.required=r}function gC(e,t){this.type=e,(e==="string"||e==="number"||e==="integer")&&t!=="String"&&(this.format=t)}function H$(e){this.$ref=`#/components/schemas/${e}`}function ile(e){this.type="array",this.items=new H$(e)}function SC(e,t,r){this.name=e,this.in=t,this.schema=r}var F$,tle,HS,$s,k$,TC=se(()=>{F$=b(Rt()),tle="3.0.3",HS={Int:"integer",Float:"number",Long:"integer",ID:"string",String:"string",Boolean:"boolean",Date:"string",Bytes:"string",BigInt:"integer"},$s="#/components/schemas/",k$="successful operation";a(GS,"generateJsonApi");a(rle,"Post");a(_C,"Get");a(v$,"Options");a(M$,"ResponseOptions200");a(Hd,"Response200");a(U$,"Response204");a(nle,"Put");a(sle,"Patch");a(x$,"Delete");a(B$,"ResourceSchema");a(gC,"Type");a(H$,"Ref");a(ile,"ArrayRef");a(SC,"Parameter")});var q$={};ye(q$,{Request:()=>hc,createReuseportFd:()=>qS});var G$,hc,yC,RC,qS,ch=se(()=>{G$=require("os"),hc=class{static{a(this,"Request")}#e;#t;_nodeRequest;_nodeResponse;method;url;headers;isWebSocket;user;constructor(t,r){this.method=t.method;let n=t.url;this._nodeRequest=t,this._nodeResponse=r,this.url=n,this.headers=new RC(t.headers)}get absoluteURL(){return this.protocol+"://"+this.host+this.url}get pathname(){let t=this.url.indexOf("?");return t>-1?this.url.slice(0,t):this.url}set pathname(t){let r=this.url.indexOf("?");r>-1?this.url=t+this.url.slice(r):this.url=t}get protocol(){return this._nodeRequest.socket.encrypted?"https":"http"}get ip(){return this._nodeRequest.socket.remoteAddress}get authorized(){return this._nodeRequest.socket.authorized}get peerCertificate(){return this.#t===void 0&&(this.#t=this._nodeRequest.socket.getPeerCertificate?.(!0)||null),this.#t}get mtlsConfig(){return this._nodeRequest.socket.server.mtlsConfig}get body(){return this.#e||(this.#e=new yC(this._nodeRequest))}get host(){return this._nodeRequest.authority||this._nodeRequest.headers.host}get hostname(){return this._nodeRequest.headers.host}get httpVersion(){return this._nodeRequest.httpVersion}get isAborted(){return!1}get nodeRequest(){return this._nodeRequest}sendEarlyHints(t,r={}){r.link=t,this._nodeResponse.writeEarlyHints(r)}},yC=class{static{a(this,"RequestBody")}#e;constructor(t){this.#e=t}on(t,r){return this.#e.on(t,r),this}pipe(t,r){return this.#e.pipe(t,r)}},RC=class{static{a(this,"Headers")}asObject;constructor(t){this.asObject=t}set(t,r){this.asObject[t.toLowerCase()]=r}get(t){return this.asObject[t.toLowerCase()]}has(t){return Object.prototype.hasOwnProperty.call(this.asObject,t.toLowerCase())}[Symbol.iterator](){return Object.entries(this.asObject)[Symbol.iterator]()}keys(){return Object.keys(this.asObject)}values(){return Object.values(this.asObject)}delete(t){delete this.asObject[t.toLowerCase()]}forEach(t){for(let[r,n]of this)t(n,r,this)}};(0,G$.platform)()!="win32"&&(qS=require("node-unix-socket").createReuseportFd)});var VS={};ye(VS,{parseHeaderValue:()=>AC,start:()=>cle});async function ale(e,t){let r=e.headers.asObject,n=r.accept==="text/event-stream",s=n?"CONNECT":e.method;e.search&&Og(e);let i=new Hs;try{e.responseHeaders=i;let o=e.url.slice(1),c,l;if(o!==$$){let _=$S.getMatch(o,n?"sse":"rest");if(!_)return t(e);e.handlerPath=_.path,c=new xs(_.relativeURL),c.async=!0,l=_.Resource}if(l?.isCaching){let _=r["cache-control"];if(_){let R=AC(_);for(let S of R)switch(S.name){case"max-age":e.expiresAt=S.value*1e3+Date.now();break;case"only-if-cached":e.onlyIfCached=!0;break;case"no-cache":e.noCache=!0;break;case"no-store":e.noCacheStore=!0;break;case"stale-if-error":e.staleIfError=!0;break;case"must-revalidate":e.mustRevalidate=!0;break}}}let u=r["x-replicate-to"];if(u){let _=AC(u).map(R=>(R.next?.name==="confirm"&&R.next.value>=0&&(e.replicatedConfirmation=+R.next.value),R.name));e.replicateTo=_.length===1&&+_[0]>=0?+_[0]:_[0]==="*"?void 0:_}r["x-replicate-from"]==="none"&&(e.replicateFrom=!1);let f=await At(e,()=>{if(r["content-length"]||r["transfer-encoding"])try{e.data=Ko(r["content-type"],!0)(e.body,e.headers)}catch(_){throw new Gd.ClientError(_,400)}if(e.authorize=!0,o===$$&&s==="GET"){if(e?.user?.role?.permission?.super_user)return GS($S,`${e.protocol}://${e.hostname}`);throw new Gd.ServerError("Forbidden",403)}switch(c.checkPermission=e.user?.role?.permission??{},s){case"GET":case"HEAD":return l.get(c,e);case"POST":return l.post(c,e.data,e);case"PUT":return l.put(c,e.data,e);case"DELETE":return l.delete(c,e);case"PATCH":return l.patch(c,e.data,e);case"OPTIONS":i.setIfNone("Allow","GET, HEAD, POST, PUT, DELETE, PATCH, OPTIONS, TRACE, QUERY, COPY, MOVE");return;case"CONNECT":return l.connect(c,null,e);case"TRACE":return"HarperDB is the terminating server";case"QUERY":return l.query(c,e.data,e);case"COPY":return l.copy(c,r.destination,e);case"MOVE":return l.move(c,r.destination,e);case"BREW":throw new Gd.ClientError("HarperDB is short and stout and can't brew coffee",418);default:throw new Gd.ServerError(`Method ${s} is not recognized`,501)}}),m=200,p=e.lastModified;if(f==null)m=s==="GET"||s==="HEAD"?404:204,bC.lastModified&&isFinite(p)&&i.setIfNone("Last-Modified",new Date(p).toUTCString());else if(f.status>0&&f.headers){let _=Iq(f.headers,i);return f.headers!==_&&(f.headers=_),f.data!==void 0&&(f.body=Vm(f.data,e,f)),f}else if(isFinite(p)){ole[0]=p;let _=String.fromCharCode(34,(sn[0]&63)+62,(sn[0]>>6)+(sn[1]<<2&63)+62,(sn[1]>>4)+(sn[2]<<4&63)+62,(sn[2]>>2)+62,(sn[3]&63)+62,(sn[3]>>6)+(sn[4]<<2&63)+62,(sn[4]>>4)+(sn[5]<<4&63)+62,(sn[5]>>2)+62,(sn[6]&63)+62,(sn[6]>>6)+(sn[7]<<2&63)+62,34),R=r["if-none-match"];R&&_==R?(f?.onDone&&f.onDone(),m=304,f=void 0):i.setIfNone("ETag",_),bC.lastModified&&i.setIfNone("Last-Modified",new Date(p).toUTCString())}e.createdResource&&(m=201),e.newLocation&&i.setIfNone("Location",e.newLocation);let h={status:m,headers:i,body:void 0},E=e.loadedFromSource??f?.wasLoadedFromSource?.();return E!==void 0&&(h.wasCacheMiss=E,!E&&isFinite(p)&&i.setIfNone("Age",Math.round((Date.now()-(e.lastRefreshed||p))/1e3))),f!==void 0&&(h.body=Vm(f,e,h),s==="HEAD"&&(h.body=void 0)),h}catch(o){o.statusCode?o.statusCode===500?_i.warn(o):_i.info(o):_i.error(o),o.statusCode===405&&(o.method&&(o.message+=` to handle HTTP method ${o.method.toUpperCase()||""}`),o.allow&&(o.allow.push("trace","head","options"),i.setIfNone("Allow",o.allow.map(l=>l.toUpperCase()).join(", "))));let c={status:o.statusCode||500,headers:i,body:void 0};return c.body=Vm(o instanceof Error?Y$(o):o,e,c),c}}function cle(e){bC=e,e.includeExpensiveRecordCountEstimates&&(hc.prototype.includeExpensiveRecordCountEstimates=!0),!V$&&(V$=!0,$S=e.resources,e.server.http(async(t,r)=>{if(!t.isWebSocket)return ale(t,r)},e),e.webSocket!==!1&&e.server.ws(async(t,r,n)=>{lh++;let s=new ss;K$||(K$=!0,op(l=>{lh>0&&l.push({metric:"ws-connections",connections:lh,byThread:!0})}));let i;t.on("error",l=>{i=!0,_i.warn(l)});let o;t.on("message",a(function(u){o||(o=Ko(r.requestedContentType??r.headers.asObject["content-type"],!1));let d=o(u);We(u.length,"bytes-received",r.handlerPath,"message","ws"),s.push(d)},"message"));let c;t.on("close",()=>{lh--,tn(!i,"connection","ws","disconnect"),s.emit("close"),c&&c.return()});try{await n;let l=r.url.slice(1),u=$S.getMatch(l,"ws");if(tn(!!u,"connection","ws","connect"),u){r.handlerPath=u.path,We(h=>({count:h.count,total:lh}),"connections",r.handlerPath,"connect","ws"),r.authorize=!0;let d=new xs(u.relativeURL);d.checkPermission=r.user?.role?.permission??{};let f=u.Resource;c=(await At(r,()=>f.connect(d,s,r)))[Symbol.asyncIterator]();let p;for(;!(p=await c.next()).done;){let h=await Vo(p.value,r);t.send(h),We(h.length,"bytes-sent",r.handlerPath,"message","ws"),t._socket.writableNeedDrain&&await new Promise(E=>t._socket.once("drain",E))}}else return t.close(1011,`No resource was found to handle ${r.pathname}`)}catch(l){l.statusCode?l.statusCode===500?_i.warn(l):_i.info(l):_i.error(l),t.close(lle[l.statusCode]||1011,Y$(l))}t.close()},e))}function AC(e){return e.trim().split(",").map(t=>{let r,n=t.trim().split(";"),s;for(;s=n.pop();)if(s.includes("=")){let[i,o]=s.trim().split("=");i=i.trim(),o&&(o=o.trim()),r={name:i.toLowerCase(),value:o,next:r}}else r={name:s.toLowerCase(),next:r};return r})}var _i,Gd,Y$,sn,ole,bC,$$,V$,$S,K$,lh,lle,W$=se(()=>{Yo();os();_i=b(J()),Gd=b(Ee());Pg();$u();Qa();jp();TC();ch();Dg();({errorToString:Y$}=_i),sn=new Uint8Array(8),ole=new Float64Array(sn.buffer,0,1),bC={},$$="openapi";a(ale,"http");lh=0;a(cle,"start");lle={401:3e3,403:3003};a(AC,"parseHeaderValue")});var IC=M((kxe,z$)=>{var{recordAction:KS,recordActionBinary:j$}=(os(),D(Tg)),ule=require("fastify-plugin"),dle=200;z$.exports=ule(function(e,t,r){e.addHook("onResponse",async(n,s)=>{let i=s.elapsedTime}),e.addHook("onSend",async(n,s,i)=>{let o=s.elapsedTime,c=performance.now(),l=s.request.routeOptions,u,d,f;l.config?.isOperation?(u=n.body?.operation,d="operation"):(u=l.url,d="fastify-route",f=l.method),KS(o,"duration",u,f,d),j$(s.raw.statusCode<400,"success",u,f,d),j$(1,"response_"+s.raw.statusCode,u,f,d);let m=dle;i?.pipe?(i.on("data",_=>{m+=_.length}),i.on("end",()=>{KS(performance.now()-c,"transfer",u,f,d),KS(m,"bytes-sent",u,f,d)})):(m+=i?.length||0,KS(m,"bytes-sent",u,f,d));let p=o.toFixed(3),h=s.getHeader("Server-Timing"),E=`db;dur=${p}`;s.header("Server-Timing",h?`${h}, ${E}`:E)}),r()},{name:"hdb-request-time"})});var J$=M((Hxe,Q$)=>{var fle=mt(),mle={user:{presence:!0},schema:{presence:!0},table:{presence:!0},operation:{presence:!0}};Q$.exports=function(e){return fle.validateObject(e,mle)}});var YS=M((Gxe,X$)=>{"use strict";var ple=(G(),D(j)).OPERATIONS_ENUM,wC=class{static{a(this,"UpdateObject")}constructor(t,r,n,s=void 0){this.operation=ple.UPDATE,this.schema=t,this.table=r,this.records=n,this.__origin=s}};X$.exports=wC});var fh={};ye(fh,{createTokens:()=>CC,getJWTRSAKeys:()=>JS,refreshOperationToken:()=>OC,validateOperationToken:()=>PC,validateRefreshToken:()=>XS});async function JS(){if(WS)return WS;try{let e=uh.default.join(dh.default.getHdbBasePath(),sA),t=await jS.default.readFile(uh.default.join(e,Tm.JWT_PASSPHRASE_NAME),"utf8"),r=await jS.default.readFile(uh.default.join(e,Tm.JWT_PRIVATE_KEY_NAME),"utf8");return WS={publicKey:await jS.default.readFile(uh.default.join(e,Tm.JWT_PUBLIC_KEY_NAME),"utf8"),privateKey:r,passphrase:t},WS}catch(e){throw QS.default.error(e),new gi.ClientError($d.NO_ENCRYPTION_KEYS,qd.INTERNAL_SERVER_ERROR)}}async function CC(e){let t=(0,NC.validateBySchema)(e,fo.default.object({username:fo.default.string().optional(),password:fo.default.string().optional(),role:fo.default.string().optional(),expires_in:fo.default.alternatives(fo.default.string(),fo.default.number()).optional()}));if(t)throw new gi.ClientError(t.message);let r;try{let f=e.bypass_auth!==!0;!e.username&&!e.password&&(e.username=e.hdb_user?.username,f=!1),r=await Rd(e.username,e.password,f)}catch(f){throw QS.default.error(f),new gi.ClientError($d.INVALID_CREDENTIALS,qd.UNAUTHORIZED)}if(!r)throw new gi.ClientError($d.INVALID_CREDENTIALS,qd.UNAUTHORIZED);let n=!1,s=!1;r.role?.permission&&(n=r.role.permission.super_user===!0,s=r.role.permission.cluster_user===!0);let i={username:e.username,super_user:n,cluster_user:s};e.role&&(i.role=e.role);let o=await JS(),c=await Vd.default.sign(i,{key:o.privateKey,passphrase:o.passphrase},{expiresIn:e.expires_in??nV,algorithm:zS,subject:Kd.OPERATION}),l=await Vd.default.sign(i,{key:o.privateKey,passphrase:o.passphrase},{expiresIn:hle,algorithm:zS,subject:Kd.REFRESH}),u=lN(l,$r.SHA256);if((await(0,Z$.update)(new eV.default(gm,Bu.USER_TABLE_NAME,[{username:e.username,refresh_token:u}]))).skipped_hashes.length>0)throw new gi.ClientError($d.REFRESH_TOKEN_SAVE_FAILED,qd.INTERNAL_SERVER_ERROR);return tV.default.signalUserChange(new rV.UserEventMsg(process.pid)),{operation_token:c,refresh_token:l}}async function OC(e){let t=(0,NC.validateBySchema)(e,fo.default.object({refresh_token:fo.default.string().required()}).required());if(t)throw new gi.ClientError(t.message);let{refresh_token:r}=e;await XS(r);let n=await JS(),s=await Vd.default.decode(r);return{operation_token:await Vd.default.sign({username:s.username,super_user:s.super_user,cluster_user:s.cluster_user},{key:n.privateKey,passphrase:n.passphrase},{expiresIn:nV,algorithm:zS,subject:Kd.OPERATION})}}async function PC(e){return sV(e,Kd.OPERATION)}async function XS(e){return sV(e,Kd.REFRESH)}async function sV(e,t){try{let r=await JS(),n=await Vd.default.verify(e,r.publicKey,{algorithms:zS,subject:t});if(n.role)throw new Error("Invalid token");let s=await Rd(n.username,void 0,!1);if(t===Kd.REFRESH&&!uN(s.refresh_token,e))throw new Error("Invalid token");return s}catch(r){throw QS.default.warn(r),r?.name==="TokenExpiredError"?new gi.ClientError($d.TOKEN_EXPIRED,qd.FORBIDDEN):new gi.ClientError($d.INVALID_TOKEN,qd.UNAUTHORIZED)}}var Vd,jS,uh,fo,NC,gi,QS,Z$,eV,tV,rV,dh,qd,$d,nV,hle,zS,Kd,WS,Yd=se(()=>{Vd=b(require("jsonwebtoken")),jS=b(require("fs-extra")),uh=b(require("node:path")),fo=b(require("joi")),NC=b(mt());G();gi=b(Ee()),QS=b(J());fN();hs();Z$=b(Vn()),eV=b(YS()),tV=b(ea()),rV=b(us()),dh=b(fe()),{HTTP_STATUS_CODES:qd,AUTHENTICATION_ERROR_MSGS:$d}=gi.hdbErrors;dh.default.initSync();nV=dh.default.get(x.AUTHENTICATION_OPERATIONTOKENTIMEOUT)||"1d",hle=dh.default.get(x.AUTHENTICATION_REFRESHTOKENTIMEOUT)||"30d",zS="RS256",Kd={OPERATION:"operation",REFRESH:"refresh"};a(JS,"getJWTRSAKeys");a(CC,"createTokens");a(OC,"refreshOperationToken");a(PC,"validateOperationToken");a(XS,"validateRefreshToken");a(sV,"validateToken")});var LC=M((Wxe,aV)=>{"use strict";var Ele=J$(),Wd=require("passport"),_le=require("passport-local").Strategy,gle=require("passport-http").BasicStrategy,Sle=require("util"),Tle=(hs(),D(ao)),oV=Sle.callbackify(Tle.findAndValidateUser),Yxe=Qr(),yle=(G(),D(j)),iV=(Yd(),D(fh)),{AccessViolation:Rle}=Ee();Wd.use(new _le(function(e,t,r){oV(e,t,r)}));Wd.use(new gle(function(e,t,r){oV(e,t,r)}));Wd.serializeUser(function(e,t){t(null,e)});Wd.deserializeUser(function(e,t){t(null,e)});function ble(e,t,r){if(e.raw?.user!==void 0)return r(null,e.raw.user);let n,s;if(e.headers?.authorization){let o=e.headers.authorization.split(" ");n=o[0],s=o[1]}function i(o,c){return o?r(o):c?r(null,c):r(new Rle)}switch(a(i,"handleResponse"),n){case"Basic":Wd.authenticate("basic",{session:!1},(o,c)=>{i(o,c)})(e,t,r);break;case"Bearer":e.body?.operation&&e.body.operation===yle.OPERATIONS_ENUM.REFRESH_OPERATION_TOKEN?iV.validateRefreshToken(s).then(o=>{e.body.refresh_token=s,r(null,o)}).catch(o=>{r(o)}):iV.validateOperationToken(s).then(o=>{r(null,o)}).catch(o=>{r(o)});break;default:Wd.authenticate("local",{session:!1},function(o,c){i(o,c)})(e,t,r);break}}a(ble,"authorize");function Ale(e,t){let r=Ele(e);if(r){t(r);return}let n={authorized:!0,messages:[]},s=e.user.role;if(!s?.permission)return t("Invalid role");let i=JSON.parse(s.permission);if(i.super_user)return t(null,n);if(!i[e.schema])return n.authorized=!1,n.messages.push(`Not authorized to access ${e.schema} schema`),t(null,n);if(!i[e.schema].tables[e.table])return n.authorized=!1,n.messages.push(`Not authorized to access ${e.table} table`),t(null,n);if(!i[e.schema].tables[e.table][e.operation])return n.authorized=!1,n.messages.push(`Not authorized to access ${e.operation} on ${e.table} table`),t(null,n);if(i[e.schema].tables[e.table].attribute_permissions&&!e.attributes)return n.authorized=!1,n.messages.push(`${e.schema}.${e.table} has attribute permissions. Missing attributes to validate`),t(null,n);if(i[e.schema].tables[e.table].attribute_permissions&&e.attributes){let o=i[e.schema].tables[e.table].attribute_permissions;for(let c in o)e.attributes.indexOf(o[c].attribute_name)>-1&&!o[c][e.operation]&&(n.authorized=!1,n.messages.push(`Not authorized to ${e.operation} ${o[c].attribute_name} `))}return t(null,n)}a(Ale,"checkPermissions");aV.exports={authorize:ble,checkPermissions:Ale}});var BC=M((Jxe,dV)=>{var rT=require("clone"),nT=mt(),Ile=ae(),eT=(G(),D(j)),zxe=J(),DC=require("fs"),MC=require("joi"),{string:tT}=MC.types(),{hdbErrors:wle,handleHDBError:ZS}=Ee(),{HDB_ERROR_MSGS:Qxe,HTTP_STATUS_CODES:vC}=wle,{commonValidators:jd}=Xi(),cV=" is required",Nle=["insert","update","upsert"],UC={database:{presence:!1,format:jd.schema_format,length:jd.schema_length},schema:{presence:!1,format:jd.schema_format,length:jd.schema_length},table:{presence:!0,format:jd.schema_format,length:jd.schema_length},action:{inclusion:{within:Nle,message:"is required and must be either insert, update, or upsert"}},file_path:{},csv_url:{url:{allowLocal:!0}},data:{},passthrough_headers:{}},Cle={schema:tT.required(),table:tT.required(),action:tT.valid("insert","update","upsert")},{AWS_ACCESS_KEY:Ole,AWS_SECRET:Ple,AWS_BUCKET:Lle,AWS_FILE_KEY:Dle,REGION:vle}=eT.S3_BUCKET_AUTH_KEYS,Mle={s3:{presence:!0},[`s3.${Ole}`]:{presence:!0,type:"String"},[`s3.${Ple}`]:{presence:!0,type:"String"},[`s3.${Lle}`]:{presence:!0,type:"String"},[`s3.${Dle}`]:{presence:!0,type:"String",hasValidFileExt:[".csv",".json"]},[`s3.${vle}`]:{presence:!0,type:"String"}},lV=rT(UC);lV.data.presence={message:cV};var uV=rT(UC);uV.file_path.presence={message:cV};var Ule=Object.assign(rT(UC),Mle),xC=rT(Cle);xC.csv_url=tT.uri().messages({"string.uri":"'csv_url' must be a valid url"}).required();xC.passthrough_headers=MC.object();function xle(e){let t=nT.validateObject(e,lV);return sT(e,t)}a(xle,"dataObject");function Ble(e){let t=nT.validateBySchema(e,MC.object(xC));return sT(e,t)}a(Ble,"urlObject");function Fle(e){let t=nT.validateObject(e,uV);return sT(e,t)}a(Fle,"fileObject");function kle(e){let t=nT.validateObject(e,Ule);return sT(e,t)}a(kle,"s3FileObject");function sT(e,t){if(!t){let r=Ile.checkGlobalSchemaTable(e.schema,e.table);if(r)return ZS(new Error,r,vC.BAD_REQUEST);if(e.operation===eT.OPERATIONS_ENUM.CSV_FILE_LOAD)try{DC.accessSync(e.file_path,DC.constants.R_OK|DC.constants.F_OK)}catch(n){return n.code===eT.NODE_ERROR_CODES.ENOENT?ZS(n,`No such file or directory ${n.path}`,vC.BAD_REQUEST):n.code===eT.NODE_ERROR_CODES.EACCES?ZS(n,`Permission denied ${n.path}`,vC.BAD_REQUEST):ZS(n)}}return t}a(sT,"postValidateChecks");dV.exports={dataObject:xle,urlObject:Ble,fileObject:Fle,s3FileObject:kle}});var FC=M((Zxe,fV)=>{"use strict";var mh=J(),iT=(G(),D(j));async function Hle(e,t,r,n=void 0){if(!e||typeof e!="function")throw new Error("Invalid function parameter");let s;try{return s=await e(t),r&&await r(t,s,n),t.operation===iT.OPERATIONS_ENUM.INSERT||t.operation===iT.OPERATIONS_ENUM.UPDATE||t.operation===iT.OPERATIONS_ENUM.UPSERT?(delete s.new_attributes,delete s.txn_time):t.operation===iT.OPERATIONS_ENUM.DELETE&&delete s.txn_time,s}catch(i){throw i.message&&typeof i.message=="string"&&i.message.includes("already exists")?(mh.info(i.message),i):i.http_resp_msg?(mh.error(`Error calling operation: ${e.name}`),mh.error(i.http_resp_msg),i):(mh.error(`Error calling operation: ${e.name}`),mh.error(i),i)}}a(Hle,"callOperationFunctionAsAwait");fV.exports={callOperationFunctionAsAwait:Hle}});var kC=M((t0e,pV)=>{"use strict";var{S3:Gle,GetObjectCommand:qle}=require("@aws-sdk/client-s3");pV.exports={getFileStreamFromS3:$le,getS3AuthObj:mV};async function $le(e){let{s3:t}=e,r={Bucket:t.bucket,Key:t.key};return(await mV(t.aws_access_key_id,t.aws_secret_access_key,t.region).send(new qle(r))).Body}a($le,"getFileStreamFromS3");function mV(e,t,r){return new Gle({credentials:{accessKeyId:e,secretAccessKey:t},region:r})}a(mV,"getS3AuthObj")});var EV=M((n0e,hV)=>{"use strict";var HC=class{static{a(this,"BulkLoadFileObject")}constructor(t,r,n,s,i,o,c=null){this.op=t,this.action=r,this.schema=n,this.table=s,this.file_path=i,this.file_type=o,this.role_perms=c}},GC=class{static{a(this,"BulkLoadDataObject")}constructor(t,r,n,s){this.action=t,this.schema=r,this.table=n,this.data=s}};hV.exports={BulkLoadFileObject:HC,BulkLoadDataObject:GC}});var gV=M((i0e,_V)=>{"use strict";var qC=class{static{a(this,"PermissionTableResponseObject")}constructor(t,r,n=[],s=[]){this.schema=t,this.table=r,this.required_table_permissions=n,this.required_attribute_permissions=s}};_V.exports=qC});var TV=M((a0e,SV)=>{"use strict";var $C=class{static{a(this,"PermissionAttributeResponseObject")}constructor(t,r=[]){this.attribute_name=t,this.required_permissions=r}};SV.exports=$C});var KC=M((l0e,RV)=>{"use strict";var yV=gV(),Vle=TV(),{HDB_ERROR_MSGS:Kle}=Qr(),VC=class{static{a(this,"PermissionResponseObject")}constructor(){this.error=Kle.OP_AUTH_PERMS_ERROR,this.unauthorized_access={},this.invalid_schema_items=[]}handleUnauthorizedItem(t){return this.invalid_schema_items=[],this.unauthorized_access=[t],this}handleInvalidItem(t){return this.invalid_schema_items=[t],this.unauthorized_access=[],this}addInvalidItem(t,r,n){if(r&&n){let s=`${r}_${n}`;if(this.unauthorized_access[s])return}this.invalid_schema_items.push(t)}addUnauthorizedTable(t,r,n){let s=new yV(t,r,n),i=`${t}_${r}`;this.unauthorized_access[i]=s}addUnauthorizedAttributes(t,r,n,s){let i=[];t.forEach(c=>{let l=new Vle(c,s[c]);i.push(l)});let o=`${r}_${n}`;if(this.unauthorized_access[o])this.unauthorized_access[o].required_attribute_permissions=i;else{let c=new yV(r,n,[],i);this.unauthorized_access[o]=c}}getPermsResponse(){let t=Object.values(this.unauthorized_access);return t.length>0||this.invalid_schema_items.length>0?(this.unauthorized_access=t,this):null}};RV.exports=VC});var Kl=M((f0e,wV)=>{"use strict";var d0e=Sn(),ph=J(),{validateBySchema:bV}=mt(),oa=require("joi"),Yle=so(),oT=ae(),{handleHDBError:aT,hdbErrors:Wle,ClientError:AV}=Ee(),{HDB_ERROR_MSGS:cT,HTTP_STATUS_CODES:YC}=Wle,IV=fe();IV.initSync();var{getDatabases:WC}=(Oe(),D(pt)),jle=require("fs-extra"),zle=(G(),D(j));wV.exports={describeAll:Qle,describeTable:lT,describeSchema:Jle};async function Qle(e={}){try{let t=oT.isEmptyOrZeroLength(e),r=!!e.bypass_auth,n,s;!t&&!r&&(n=e.hdb_user?.role?.permission,s=n?.super_user||n?.cluster_user);let i=WC(),o={},c={},l=[],u=e?.exact_count,d=e?.include_computed;for(let m in i){o[m]=!0,!t&&!s&&!r&&(c[m]=e.hdb_user?.role?.permission[m]?.describe);let p=i[m];for(let h in p)try{let E;if(t||s||r)E=await lT({schema:m,table:h,exact_count:u,include_computed:d});else if(n&&n[m].describe&&n[m].tables[h].describe){let _=n[m].tables[h].attribute_permissions;E=await lT({schema:m,table:h,exact_count:u,include_computed:d},_)}E&&l.push(E)}catch(E){ph.error(E)}}let f={};for(let m in l)t||s||r?(f[l[m].schema]==null&&(f[l[m].schema]={}),f[l[m].schema][l[m].name]=l[m],o[l[m].schema]&&delete o[l[m].schema]):c[l[m].schema]&&(f[l[m].schema]==null&&(f[l[m].schema]={}),f[l[m].schema][l[m].name]=l[m],o[l[m].schema]&&delete o[l[m].schema]);for(let m in o)t||s||r?f[m]={}:c[m]&&(f[m]={});return f}catch(t){return ph.error("Got an error in describeAll"),ph.error(t),aT(new Error,cT.DESCRIBE_ALL_ERR)}}a(Qle,"describeAll");async function lT(e,t){oT.transformReq(e);let{schema:r,table:n}=e;r=r?.toString(),n=n?.toString();let s=t;e.hdb_user&&!e.hdb_user?.role?.permission?.super_user&&(s=e.hdb_user?.role?.permission[r]?.tables[n]?.attribute_permissions);let i=bV(e,oa.object({database:oa.string(),table:oa.string().required(),exact_count:oa.boolean().strict(),include_computed:oa.boolean().strict()}));if(i)throw new AV(i.message);let c=WC()[r];if(!c)throw aT(new Error,cT.SCHEMA_NOT_FOUND(e.schema),YC.NOT_FOUND);let l=c[n];if(!l)throw aT(new Error,cT.TABLE_NOT_FOUND(e.schema,e.table),YC.NOT_FOUND);function u(p){(!p.computed||e.include_computed)&&d.push({attribute:p.attribute,type:p.type,elements:p.elements?.type,indexed:p.indexed,is_primary_key:p.isPrimaryKey,assigned_created_time:p.assignCreatedTime,assigned_updated_time:p.assignUpdatedTime,nullable:p.nullable,computed:p.computed?!0:void 0,properties:p.properties?p.properties.map(h=>({type:h.type,name:h.name})):void 0})}a(u,"pushAtt");let d=[];if(s){let p={};s.forEach(h=>{h.describe&&(p[h.attribute_name]=!0)}),l.attributes.forEach(h=>{p[h.name]&&u(h)})}else l.attributes?.forEach(p=>u(p));let f;try{f=(await jle.stat(l.primaryStore.env.path)).size}catch(p){ph.warn("unable to get database size",p)}let m={schema:r,name:l.tableName,hash_attribute:l.attributes.find(p=>p.isPrimaryKey||p.is_hash_attribute)?.name,audit:l.audit,schema_defined:l.schemaDefined,attributes:d,db_size:f};l.replicate!==void 0&&(m.replicate=l.replicate),l.expirationMS!==void 0&&(m.expiration=l.expirationMS/1e3+"s"),l.sealed!==void 0&&(m.sealed=l.sealed),l.sources?.length>0&&(m.sources=l.sources.map(p=>p.name).filter(p=>p&&p!=="NATSReplicator"&&p!=="Replicator")),IV.get(zle.CONFIG_PARAMS.CLUSTERING_ENABLED)&&(m.clustering_stream_name=Yle.createNatsTableStreamName(m.schema,m.name));try{let p=await l.getRecordCount({exactCount:!!e.exact_count});m.record_count=p.recordCount,m.table_size=l.getSize(),m.db_audit_size=l.getAuditSize(),m.estimated_record_range=p.estimatedRange;let h=l.auditStore;if(h)for(let E of h.getKeys({reverse:!0,limit:1}))m.last_updated_record=E[0];if(!m.last_updated_record&&l.indices.__updatedtime__)for(let E of l.indices.__updatedtime__.getKeys({reverse:!0,limit:1}))m.last_updated_record=E}catch(p){ph.warn(`unable to stat table dbi due to ${p}`)}return m}a(lT,"descTable");async function Jle(e){oT.transformReq(e);let t=bV(e,oa.object({database:oa.string(),exact_count:oa.boolean().strict(),include_computed:oa.boolean().strict()}));if(t)throw new AV(t.message);let r;e.hdb_user&&!e.hdb_user?.role?.permission?.super_user&&(r=e.hdb_user?.role?.permission[e.schema]);let n=e.schema.toString(),i=WC()[n];if(!i)throw aT(new Error,cT.SCHEMA_NOT_FOUND(e.schema),YC.NOT_FOUND);let o={};for(let c in i){let l;if(r&&r.tables[c]&&(l=r.tables[c]),oT.isEmpty(l)||l.describe){let u=await lT({schema:e.schema,table:c,exact_count:e.exact_count,include_computed:e.include_computed},l?l.attribute_permissions:null);u&&(o[u.name]=u)}}return o}a(Jle,"describeSchema")});var LV=M((p0e,PV)=>{"use strict";var Xle=Kl(),{hdbErrors:NV}=Ee(),{getDatabases:CV}=(Oe(),D(pt));PV.exports={checkSchemaExists:OV,checkSchemaTableExists:Zle,schemaDescribe:Xle};async function OV(e){if(!CV()[e])return NV.HDB_ERROR_MSGS.SCHEMA_NOT_FOUND(e)}a(OV,"checkSchemaExists");async function Zle(e,t){let r=await OV(e);if(r)return r;if(!CV()[e][t])return NV.HDB_ERROR_MSGS.TABLE_NOT_FOUND(e,t)}a(Zle,"checkSchemaTableExists")});var uT=M((E0e,DV)=>{"use strict";var eue=ms();DV.exports={writeTransaction:tue};function tue(e,t,r){return eue.writeTransaction(e,t,r)}a(tue,"writeTransaction")});var XC=M((y0e,VV)=>{"use strict";var{decode:rue}=require("msgpackr"),{isMainThread:g0e,parentPort:S0e,threadId:T0e}=require("worker_threads"),mT=_r(),zd=vt(),QC=(G(),D(j)),Rn=J(),zC=fe(),nue=(G(),D(j)),{onMessageByType:sue}=st(),xV=so(),{recordAction:vV,recordActionBinary:iue}=(os(),D(Tg)),{publishToStream:oue}=mT,{ConsumerEvents:MV}=require("nats"),aue=Sn(),{promisify:cue}=require("util"),{decodeBlobsWithWrites:lue}=(is(),D(ig)),BV=cue(setTimeout),pT=1e4,hT,fT,uue,due,FV,hh=new Map,Qd=new Map;VV.exports={initialize:kV,ingestConsumer:JC,setSubscription:fue,setIgnoreOrigin:hue,getDatabaseSubscriptions:pue,updateConsumer:HV};async function kV(){sue(QC.ITC_EVENT_TYPES.NATS_CONSUMER_UPDATE,async n=>{await HV(n)}),FV=!0,Rn.notify("Initializing clustering ingest service.");let{connection:e,jsm:t,js:r}=await mT.getNATSReferences();hT=e,fT=e.info.server_name,uue=t,due=r}a(kV,"initialize");async function HV(e){if(e.status==="start"){let{js:t,jsm:r}=await GV(e.node_domain_name);JC(e.stream_name,t,r,e.node_domain_name)}else if(e.status==="stop"){let t=hh.get(e.stream_name+e.node_domain_name);t&&(Rn.notify("Closing ingest consumer for node:",e.node_domain_name,"stream:",e.stream_name),await t.close?.(),hh.set(e.stream_name+e.node_domain_name,"close")),Qd.get(e.node_domain_name)==="failed"&&Qd.set(e.node_domain_name,"close")}}a(HV,"updateConsumer");var ET=new Map;function fue(e,t,r){let n=ET.get(e);n||ET.set(e,n=new Map),n.set(t,r),FV||kV().then(mue)}a(fue,"setSubscription");async function mue(){let e=await aue.searchByValue({database:"system",table:"hdb_nodes",attribute:"name",value:"*"});for await(let t of e){let r=t.name+zd.SERVER_SUFFIX.LEAF,n,s;for(let i of t.subscriptions||[])if(i.subscribe===!0){if(!n&&({js:n,jsm:s}=await GV(r),!n))break;let{schema:o,table:c}=i,l=xV.createNatsTableStreamName(o,c);JC(l,n,s,r)}}}a(mue,"accessConsumers");async function GV(e){let t,r,n=1;for(;!r;)try{t=await hT.jetstream({domain:e}),r=await hT.jetstreamManager({domain:e,checkAPI:!1})}catch(s){if(Qd.get(e)==="close")break;Qd.set(e,"failed"),n%10===1&&Rn.warn("Nats ingest attempting to connect to:",e,"Nats error:",s.message);let i=n++*100<pT?n++*100:pT;await BV(i)}return{js:t,jsm:r}}a(GV,"connectToRemoteJS");function pue(){return ET}a(pue,"getDatabaseSubscriptions");var qV;function hue(e){qV=e}a(hue,"setIgnoreOrigin");var $V=100,UV=new Array($V),dT=0;async function JC(e,t,r,n){let{connection:s}=await mT.getNATSReferences();hT=s,fT=s.info.server_name;let i,o=1;for(;!i;)try{i=await t.consumers.get(e,fT),Rn.notify("Initializing ingest consumer for node:",n,"stream:",e)}catch(u){if(Qd.get(n)==="close")break;o%10===1&&Rn.warn("Nats ingest error getting consumer:",n,"stream:",e,"Nats error:",u.message),u.code==="404"&&(Rn.notify("Nats ingest creating consumer for node:",n,"stream:",e),i=await mT.createConsumer(r,e,fT,new Date(Date.now()).toISOString()));let d=o++*100<pT?o++*100:pT;await BV(d)}let c=!1,l;for(;!c;){if(hh.get(e+n)==="close"||Qd.get(n)==="close"){hh.delete(e+n),c=!0;continue}l=await i.consume({max_messages:zC.get(QC.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXCONSUMEMSGS)??100,bind:!0}),hh.set(e+n,l);let u=!1;(async()=>{for await(let d of await l.status())if(d.type===MV.ConsumerDeleted&&(await l.close(),c=!0),d.type===MV.HeartbeatsMissed){let f=d.data;Rn.trace(`${f} clustering ingest consumer heartbeats missed, node: ${n} stream: ${l.consumer.stream}`),f===100&&(Rn.warn(`Restarting clustering ingest consumer due to missed heartbeat threshold being met, node: ${n} stream: ${l.consumer.stream}`),l.stop(),u=!0)}})();try{for await(let d of l)await UV[dT],UV[dT]=Eue(d).catch(f=>{Rn.error(f)}),++dT>=$V&&(dT=0)}catch(d){d.message==="consumer deleted"?(Rn.notify("Nats consumer deleted, closing messages for node:",n,"stream:",l.consumer.stream),await l.close(),c=!0):Rn.error("Error consuming clustering ingest, restarting consumer",d)}}}a(JC,"ingestConsumer");async function Eue(e){let t;await lue(()=>{t=rue(e.data)}),vV(e.data.length,"bytes-received",e.subject,t.operation,"ingest"),Rn.trace("Nats message processor message size:",e?.msg?._msg?.size,"bytes");let r=e.headers,n=!1,s=zC.get(QC.CONFIG_PARAMS.CLUSTERING_NODENAME);r.has(zd.MSG_HEADERS.TRANSACTED_NODES)&&r.values(zd.MSG_HEADERS.TRANSACTED_NODES).indexOf(s)>-1&&(n=!0);let i=r.get(zd.MSG_HEADERS.ORIGIN);if(n||(n=i===s&&!qV),iue(n,"echo",e.subject,t.operation,"ingest"),n){e.ack();return}r.append(zd.MSG_HEADERS.TRANSACTED_NODES,s);try{let{operation:o,schema:c,next:l,table:u,records:d,hash_values:f,__origin:m,expiresAt:p}=t;Rn.trace("processing message:",o,c,u,(d?"records: "+d.map(I=>I?.id):"")+(f?"ids: "+f:""),"with sequence:",e.seq),Rn.trace(`messageProcessor nats msg id: ${e.headers.get(zd.MSG_HEADERS.NATS_MSG_ID)}`);let h;d||(d=f);let E=new Promise(I=>h=I),{timestamp:_,user:R,node_name:S}=m||{},y=ET.get(c)?.get(u);if(!y)throw new Error(`Missing table for replication message: ${u}`);if(o==="define_schema")t.type=o,t.onCommit=h,y.send(t);else if(d.length===1&&!l)y.send({type:jC(o),value:d[0],id:f?.[0],expiresAt:p,timestamp:_,table:u,onCommit:h,user:R,nodeName:S});else{let I=d.map((H,X)=>({type:jC(o),value:H,expiresAt:p,id:f?.[X],table:u}));for(;l;)I.push({type:jC(l.operation),value:l.record,expiresAt:l.expiresAt,id:l.id,table:l.table}),l=l.next;y.send({type:"transaction",writes:I,table:u,timestamp:_,onCommit:h,user:R,nodeName:S})}zC.get(nue.CONFIG_PARAMS.CLUSTERING_REPUBLISHMESSAGES)!==!1&&oue(e.subject.split(".").slice(0,-1).join("."),xV.createNatsTableStreamName(c,u),e.headers,e.data),await E;let w=Date.now()-_;_&&vV(w,"replication-latency",e.subject,o,"ingest")}catch(o){Rn.error(o)}e.ack()}a(Eue,"messageProcessor");function jC(e){switch(e){case"insert":case"upsert":case"update":return"put"}return e}a(jC,"convertOperation")});var _r=M((C0e,a1)=>{"use strict";var Kr=fe();Kr.initSync();var _ue=require("fs-extra"),gue=require("semver"),gh=require("path"),{monotonicFactory:Sue}=require("ulidx"),YV=Sue(),Tue=require("util"),WV=require("child_process"),yue=Tue.promisify(WV.exec),Rue=WV.spawn,on=vt(),rt=(G(),D(j)),{packageJson:bue,PACKAGE_ROOT:Aue}=Rt(),_T=ae(),Si=J(),gT=so(),Iue=uT(),Eh=_t(),{broadcast:wue,onMessageByType:Nue,getWorkerIndex:Cue}=st(),{isMainThread:jV}=require("worker_threads"),{Encoder:Oue,decode:rO}=require("msgpackr"),zV=new Oue,{isEmpty:zl}=_T,QV=(hs(),D(ao)),b0e=48*36e11;jV&&Nue(rt.ITC_EVENT_TYPES.RESTART,()=>{bn=void 0,jl=void 0});var{connect:Pue,StorageType:Lue,RetentionPolicy:Due,AckPolicy:nO,DeliverPolicy:sO,DiscardPolicy:vue,NatsConnection:A0e,JetStreamManager:I0e,JetStreamClient:w0e,StringCodec:N0e,JSONCodec:Mue,createInbox:iO,headers:Uue,ErrorCode:KV}=require("nats"),{recordAction:xue}=(os(),D(Tg)),{encodeBlobsAsBuffers:Bue}=(is(),D(ig)),JV=Mue(),Fue="clustering",kue=bue.engines[on.NATS_SERVER_NAME],Hue=gh.join(Aue,"dependencies"),tO=gh.join(Hue,`${process.platform}-${process.arch}`,on.NATS_BINARY_NAME),ZC,eO,_h,Yl,Wl;a1.exports={runCommand:XV,checkNATSServerInstalled:Gue,createConnection:oO,getConnection:Sh,getJetStreamManager:Th,getJetStream:e1,getNATSReferences:mo,getServerList:$ue,createLocalStream:aO,listStreams:t1,deleteLocalStream:Vue,getServerConfig:Jd,listRemoteStreams:Kue,viewStream:Yue,viewStreamIterator:Wue,publishToStream:jue,request:Jue,reloadNATS:cO,reloadNATSHub:Xue,reloadNATSLeaf:Zue,extractServerName:Que,requestErrorHandler:ede,createLocalTableStream:i1,createTableStreams:nde,purgeTableStream:o1,purgeSchemaTableStreams:sde,getStreamInfo:ide,updateLocalStreams:ade,closeConnection:que,getJsmServerName:ST,addNatsMsgHeader:r1,clearClientCache:ZV,updateRemoteConsumer:tde,createConsumer:n1,updateConsumerIterator:rde};async function XV(e,t=void 0){let{stdout:r,stderr:n}=await yue(e,{cwd:t});if(n)throw new Error(n.replace(`
16
16
  `,""));return r.replace(`
17
17
  `,"")}a(XV,"runCommand");async function Gue(){try{await _ue.access(tO)}catch{return!1}let e=await XV(`${tO} --version`,void 0),t=e.substring(e.lastIndexOf("v")+1,e.length);return gue.eq(t,kue)}a(Gue,"checkNATSServerInstalled");async function oO(e,t,r,n=!0,s="127.0.0.1"){if(!t&&!r){let o=await QV.getClusterUser();if(zl(o))throw new Error("Unable to get nats connection. Cluster user is undefined.");t=o.username,r=o.decrypt_hash}Si.trace("create nats connection called");let i=await Pue({name:s,port:e,user:t,pass:r,maxReconnectAttempts:-1,waitOnFirstConnect:n,timeout:2e5,tls:{keyFile:Kr.get(rt.CONFIG_PARAMS.CLUSTERING_TLS_PRIVATEKEY),certFile:Kr.get(rt.CONFIG_PARAMS.CLUSTERING_TLS_CERTIFICATE),caFile:Kr.get(rt.CONFIG_PARAMS.CLUSTERING_TLS_CERT_AUTH),rejectUnauthorized:!1}});return i.protocol.transport.socket.unref(),Si.trace("create connection established a nats client connection with id",i?.info?.client_id),i.closed().then(o=>{o&&Si.error("Error with Nats client connection, connection closed",o),i===bn&&ZV()}),i}a(oO,"createConnection");function ZV(){bn=void 0,Yl=void 0,Wl=void 0,jl=void 0}a(ZV,"clearClientCache");async function que(){bn&&(await bn.drain(),bn=void 0,Yl=void 0,Wl=void 0,jl=void 0)}a(que,"closeConnection");var bn,jl;async function Sh(){return jl||(jl=oO(Kr.get(rt.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_PORT),void 0,void 0),bn=await jl),bn||jl}a(Sh,"getConnection");async function Th(){if(Yl)return Yl;zl(bn)&&await Sh();let{domain:e}=Jd(rt.PROCESS_DESCRIPTORS.CLUSTERING_LEAF);if(zl(e))throw new Error("Error getting JetStream domain. Unable to get JetStream manager.");return Yl=await bn.jetstreamManager({domain:e,timeout:6e4}),Yl}a(Th,"getJetStreamManager");async function e1(){if(Wl)return Wl;zl(bn)&&await Sh();let{domain:e}=Jd(rt.PROCESS_DESCRIPTORS.CLUSTERING_LEAF);if(zl(e))throw new Error("Error getting JetStream domain. Unable to get JetStream manager.");return Wl=bn.jetstream({domain:e,timeout:6e4}),Wl}a(e1,"getJetStream");async function mo(){let e=bn||await Sh(),t=Yl||await Th(),r=Wl||await e1();return{connection:e,jsm:t,js:r}}a(mo,"getNATSReferences");async function $ue(e){let t=Kr.get(rt.CONFIG_PARAMS.CLUSTERING_HUBSERVER_NETWORK_PORT),{sys_name:r,decrypt_hash:n}=await QV.getClusterUser(),s=await oO(t,r,n),i=iO(),o=s.subscribe(i),c=[],l,u=(async()=>{for await(let d of o){let f=JV.decode(d.data);f.response_time=Date.now()-l,c.push(f)}})();return l=Date.now(),await s.publish("$SYS.REQ.SERVER.PING.VARZ",void 0,{reply:i}),await s.publish("$SYS.REQ.SERVER.PING",void 0,{reply:i}),await s.flush(),await _T.asyncSetTimeout(e),await o.drain(),await s.close(),await u,c}a($ue,"getServerList");async function aO(e,t){let{jsm:r}=await mo(),n=Kr.get(rt.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXAGE);n=n===null?0:n*1e9;let s=Kr.get(rt.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXMSGS);s=s===null?-1:s;let i=Kr.get(rt.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXBYTES);i=i===null?-1:i,await r.streams.add({name:e,storage:Lue.File,retention:Due.Limits,subjects:t,discard:vue.Old,maxMsgs:s,maxBytes:i,maxAge:n})}a(aO,"createLocalStream");async function t1(){let{jsm:e}=await mo(),t=await e.streams.list().next(),r=[];return t.forEach(n=>{r.push(n)}),r}a(t1,"listStreams");async function Vue(e){let{jsm:t}=await mo();await t.streams.delete(e)}a(Vue,"deleteLocalStream");async function Kue(e){let{connection:t}=await mo(),r=[],n=iO(),s=t.subscribe(n),i=(async()=>{for await(let o of s)r.push(JV.decode(o.data))})();return await t.publish(`$JS.${e}.API.STREAM.LIST`,void 0,{reply:n}),await t.flush(),await s.drain(),await i,r}a(Kue,"listRemoteStreams");async function Yue(e,t=void 0,r=void 0){let{jsm:n,js:s}=await mo(),i=YV(),o={durable_name:i,ack_policy:nO.Explicit};t&&(o.deliver_policy=sO.StartTime,o.opt_start_time=new Date(t).toISOString()),await n.consumers.add(e,o);let c=await s.consumers.get(e,i),l=r?await c.fetch({max_messages:r,expires:2e3}):await c.consume();if(c._info.num_pending===0)return[];let u=[];for await(let d of l){let f=rO(d.data),m={nats_timestamp:d.info.timestampNanos,nats_sequence:d.info.streamSequence,entry:f};if(d.headers&&(m.origin=d.headers.get(on.MSG_HEADERS.ORIGIN)),u.push(m),d.ack(),d.info.pending===0)break}return await c.delete(),u}a(Yue,"viewStream");async function*Wue(e,t=void 0,r=void 0){let{jsm:n,js:s}=await mo(),i=YV(),o={durable_name:i,ack_policy:nO.Explicit};t&&(o.deliver_policy=sO.StartTime,o.opt_start_time=new Date(t).toISOString()),await n.consumers.add(e,o);let c=await s.consumers.get(e,i),l=r?await c.fetch({max_messages:r,expires:2e3}):await c.consume();if(c._info.num_pending===0)return[];for await(let u of l){let d=rO(u.data);d[0]||(d=[d]);for(let f of d){let m={nats_timestamp:u.info.timestampNanos,nats_sequence:u.info.streamSequence,entry:f};u.headers&&(m.origin=u.headers.get(on.MSG_HEADERS.ORIGIN)),yield m}if(u.ack(),u.info.pending===0)break}await c.delete()}a(Wue,"viewStreamIterator");async function jue(e,t,r,n){Si.trace(`publishToStream called with subject: ${e}, stream: ${t}, entries:`,n.operation),r=r1(n,r);let{js:s}=await mo(),i=await ST(),o=`${e}.${i}`,c=await Bue(()=>n instanceof Uint8Array?n:zV.encode(n));try{Si.trace(`publishToStream publishing to subject: ${o}`),xue(c.length,"bytes-sent",e,n.operation,"replication"),await s.publish(o,c,{headers:r})}catch(l){if(l.code&&l.code.toString()==="503")return s1(async()=>{try{await s.publish(o,c,{headers:r})}catch{if(l.code&&l.code.toString()==="503"){Si.trace(`publishToStream creating stream: ${t}`);let d=o.split(".");d[2]="*",await aO(t,[o]),await s.publish(o,c,{headers:r})}else throw l}});throw l}}a(jue,"publishToStream");function r1(e,t){t===void 0&&(t=Uue());let r=Kr.get(rt.CONFIG_PARAMS.CLUSTERING_NODENAME);return!t.has(on.MSG_HEADERS.ORIGIN)&&r&&t.append(on.MSG_HEADERS.ORIGIN,r),t}a(r1,"addNatsMsgHeader");function Jd(e){e=e.toLowerCase();let t=gh.join(Kr.get(rt.CONFIG_PARAMS.ROOTPATH),Fue);if(e===rt.PROCESS_DESCRIPTORS.CLUSTERING_HUB.toLowerCase())return zl(eO)&&(eO={port:Eh.getConfigFromFile(rt.CONFIG_PARAMS.CLUSTERING_HUBSERVER_NETWORK_PORT),server_name:Eh.getConfigFromFile(rt.CONFIG_PARAMS.CLUSTERING_NODENAME)+on.SERVER_SUFFIX.HUB,config_file:on.NATS_CONFIG_FILES.HUB_SERVER,pid_file_path:gh.join(t,on.PID_FILES.HUB),hdbNatsPath:t}),eO;if(e===rt.PROCESS_DESCRIPTORS.CLUSTERING_LEAF.toLowerCase())return zl(ZC)&&(ZC={port:Eh.getConfigFromFile(rt.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_PORT),server_name:Eh.getConfigFromFile(rt.CONFIG_PARAMS.CLUSTERING_NODENAME)+on.SERVER_SUFFIX.LEAF,config_file:on.NATS_CONFIG_FILES.LEAF_SERVER,domain:Eh.getConfigFromFile(rt.CONFIG_PARAMS.CLUSTERING_NODENAME)+on.SERVER_SUFFIX.LEAF,pid_file_path:gh.join(t,on.PID_FILES.LEAF),hdbNatsPath:t}),ZC;Si.error(`Unable to get Nats server config. Unrecognized process: ${e}`)}a(Jd,"getServerConfig");async function n1(e,t,r,n){try{await e.consumers.add(t,{ack_policy:nO.Explicit,durable_name:r,deliver_policy:sO.StartTime,opt_start_time:n})}catch(s){if(s.message!=="consumer already exists")throw s}}a(n1,"createConsumer");async function zue(e,t,r){await e.consumers.delete(t,r)}a(zue,"removeConsumer");function Que(e){return e.split(".")[1]}a(Que,"extractServerName");async function Jue(e,t,r=6e4,n=iO()){if(!_T.isObject(t))throw new Error("data param must be an object");let s=zV.encode(t),{connection:i}=await mo(),o={timeout:r};n&&(o.reply=n,o.noMux=!0);let c=await i.request(e,s,o);return rO(c.data)}a(Jue,"request");function cO(e){return new Promise(async(t,r)=>{let n=Rue(tO,["--signal",`reload=${e}`],{cwd:__dirname}),s,i;n.on("error",o=>{r(o)}),n.stdout.on("data",o=>{i+=o.toString()}),n.stderr.on("data",o=>{s+=o.toString()}),n.stderr.on("close",o=>{s&&r(s),t(i)})})}a(cO,"reloadNATS");async function Xue(){let{pid_file_path:e}=Jd(rt.PROCESS_DESCRIPTORS.CLUSTERING_HUB);await cO(e)}a(Xue,"reloadNATSHub");async function Zue(){let{pid_file_path:e}=Jd(rt.PROCESS_DESCRIPTORS.CLUSTERING_LEAF);await cO(e)}a(Zue,"reloadNATSLeaf");function ede(e,t,r){let n;switch(e.code){case KV.NoResponders:n=`Unable to ${t}, node '${r}' is not listening.`;break;case KV.Timeout:n=`Unable to ${t}, node '${r}' is listening but did not respond.`;break;default:n=e.message;break}return n}a(ede,"requestErrorHandler");async function tde(e,t){let r=t+on.SERVER_SUFFIX.LEAF,{connection:n}=await mo(),{jsm:s}=await lde(r),{schema:i,table:o}=e,c=gT.createNatsTableStreamName(i,o),l=e.start_time?e.start_time:new Date(Date.now()).toISOString();await s1(async()=>{if(e.subscribe===!0)await n1(s,c,n.info.server_name,l);else try{await zue(s,c,n.info.server_name)}catch(u){Si.trace(u)}})}a(tde,"updateRemoteConsumer");async function rde(e,t,r,n){let s=gT.createNatsTableStreamName(e,t),i=r+on.SERVER_SUFFIX.LEAF,o={type:rt.ITC_EVENT_TYPES.NATS_CONSUMER_UPDATE,status:n,stream_name:s,node_domain_name:i};if(!jV&&Cue()<Kr.get(rt.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXINGESTTHREADS)){let{updateConsumer:c}=XC();await c(o)}await wue(o),n==="stop"&&await _T.asyncSetTimeout(1e3)}a(rde,"updateConsumerIterator");function s1(e){return Iue.writeTransaction(rt.SYSTEM_SCHEMA_NAME,rt.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,e)}a(s1,"exclusiveLock");async function i1(e,t){let r=gT.createNatsTableStreamName(e,t),n=await ST(),s=ode(e,t,n);await aO(r,[s])}a(i1,"createLocalTableStream");async function nde(e){for(let t=0,r=e.length;t<r;t++){let n=e[t].schema,s=e[t].table;await i1(n,s)}}a(nde,"createTableStreams");async function o1(e,t,r=void 0){if(Kr.get(rt.CONFIG_PARAMS.CLUSTERING_ENABLED))try{let n=gT.createNatsTableStreamName(e,t),{domain:s}=Jd(rt.PROCESS_DESCRIPTORS.CLUSTERING_LEAF);await(await(await Sh()).jetstreamManager({domain:s,timeout:24e4})).streams.purge(n,r)}catch(n){if(n.message==="stream not found")Si.warn(n);else throw n}}a(o1,"purgeTableStream");async function sde(e,t){if(Kr.get(rt.CONFIG_PARAMS.CLUSTERING_ENABLED))for(let r=0,n=t.length;r<n;r++)await o1(e,t[r])}a(sde,"purgeSchemaTableStreams");async function ide(e){return(await Th()).streams.info(e)}a(ide,"getStreamInfo");function ode(e,t,r){return`${on.SUBJECT_PREFIXES.TXN}.${e}${t?"."+t:""}.${r}`}a(ode,"createSubjectName");async function ST(){if(_h)return _h;if(_h=(await Th())?.nc?.info?.server_name,_h===void 0)throw new Error("Unable to get jetstream manager server name");return _h}a(ST,"getJsmServerName");async function ade(){let e=await Th(),t=await ST(),r=await t1();for(let n of r){let s=n.config,i=s.subjects[0];if(!i)continue;let o=cde(n),c=i.split(".");if(c[c.length-1]===t&&!o||s.name==="__HARPERDB_WORK_QUEUE__")continue;let u=i.split(".");u[u.length-1]=t;let d=u.join(".");Si.trace(`Updating stream subject name from: ${i} to: ${d}`),s.subjects[0]=d,await e.streams.update(s.name,s)}}a(ade,"updateLocalStreams");function cde(e){let{config:t}=e,r=!1,n=Kr.get(rt.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXAGE);n=n===null?0:n*1e9;let s=Kr.get(rt.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXBYTES);s=s===null?-1:s;let i=Kr.get(rt.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXMSGS);return i=i===null?-1:i,n!==t.max_age&&(t.max_age=n,r=!0),s!==t.max_bytes&&(t.max_bytes=s,r=!0),i!==t.max_msgs&&(t.max_msgs=i,r=!0),r}a(cde,"updateStreamLimits");async function lde(e){let t,r;try{t=await bn.jetstream({domain:e}),r=await bn.jetstreamManager({domain:e,checkAPI:!1})}catch(n){throw Si.error("Unable to connect to:",e),n}return{js:t,jsm:r}}a(lde,"connectToRemoteJS")});function lO(e){let t=e.get(TT),r=t?(0,Xd.unpack)(t):null;r||(r={remoteNameToId:{}});let n=nt(),s=!1;r.nodeName=nt();let i=r.remoteNameToId;if(i[n]!==0){let o=0,c;for(let l in i){let u=i[l];u===0?c=l:u>o&&(o=u)}if(c){o++,i[c]=o;let l=[Symbol.for("seq"),o];e.rootStore.dbisDb.transactionSync(()=>{e.rootStore.dbisDb.get(l)||e.rootStore.dbisDb.putSync(l,{seqId:Rh(e)??1,nodes:[]})})}i[n]=0,e.putSync(TT,(0,Xd.pack)(r))}return r}function yh(e){return lO(e).remoteNameToId}function l1(e,t){let r=lO(t),n=r.remoteNameToId,s=new Map,i=!1;for(let o in e){let c=e[o],l=n[o];if(l==null){let u=0;for(let d in n){let f=n[d];f>u&&(u=f)}l=u+1,n[o]=l,i=!0}s.set(c,l)}return i&&t.putSync(TT,(0,Xd.pack)(r)),s}function yT(e,t){let r=lO(t),n=r.remoteNameToId,s=n[e];if(s==null){let i=0;for(let o in n){let c=n[o];c>i&&(i=c)}s=i+1,n[e]=s,t.putSync(TT,(0,Xd.pack)(r))}return c1.trace?.("The remote node name map",e,n,s),s}var c1,Xd,TT,uO=se(()=>{c1=b(sr());gs();Xd=require("msgpackr"),TT=Symbol.for("remote-ids");a(lO,"getIdMappingRecord");a(yh,"exportIdMapping");a(l1,"remoteToLocalNodeId");a(yT,"getIdOfRemoteNode")});var h1={};ye(h1,{commitsAwaitingReplication:()=>Zd,getHDBNodeTable:()=>Gt,getReplicationSharedStatus:()=>ef,iterateRoutes:()=>Ah,shouldReplicateToNode:()=>bh,subscribeToNodeUpdates:()=>tf});function Gt(){return u1||(u1=ze({table:"hdb_nodes",database:"system",attributes:[{name:"name",isPrimaryKey:!0},{attribute:"subscriptions"},{attribute:"system_info"},{attribute:"url"},{attribute:"routes"},{attribute:"ca"},{attribute:"ca_info"},{attribute:"replicates"},{attribute:"revoked_certificates"},{attribute:"__createdtime__"},{attribute:"__updatedtime__"}]}))}function ef(e,t,r,n){return new Float64Array(e.getUserSharedBuffer(["replicated",t,r],new ArrayBuffer(64),n&&{callback:n}))}function tf(e){Gt().subscribe({}).then(async t=>{for await(let r of t){let n=r?.value?.name;p1.debug?.("adding node",n,"on node",nt()," on process",process.pid),server.nodes=server.nodes.filter(i=>i.name!==n),r.type==="put"&&n!==nt()&&(r.value?server.nodes.push(r.value):console.error("Invalid node update event",r));let s=new Map;for await(let i of Gt().search({}))if(i.shard!=null){let o=s.get(i.shard);o||s.set(i.shard,o=[]),o.push(i)}server.shards=s,(r.type==="put"||r.type==="delete")&&e(r.value,r.id)}})}function bh(e,t){let r=Ec.default.get(x.REPLICATION_DATABASES);return(e.replicates===!0||e.replicates?.sends)&&databases[t]&&(r==="*"||r?.find?.(n=>(typeof n=="string"?n:n.name)===t&&(!n.sharded||e.shard===Ec.default.get(x.REPLICATION_SHARD))))&&Gt().primaryStore.get(nt())?.replicates||e.subscriptions?.some(n=>(n.database||n.schema)===t&&n.subscribe)}function ude(){tf(e=>{_c({},(t,r)=>{let n=e.name,s=d1.get(n);if(s||d1.set(n,s=new Map),s.has(r))return;let i;for(let o in t)if(i=t[o].auditStore,i)break;if(i){let o=ef(i,r,n,()=>{let c=o[0],l=o.lastTime;for(let{txnTime:u,onConfirm:d}of Zd.get(r)||[])u>l&&u<=c&&d();o.lastTime=c});o.lastTime=0,s.set(r,o)}})})}function*Ah(e){for(let t of e.routes||[]){let r=t.url,n;if(typeof t=="string"?t.includes("://")?r=t:n=t:n=t.hostname??t.host,n&&!r){let s=Ec.default.get(x.REPLICATION_SECUREPORT)??(!Ec.default.get(x.REPLICATION_PORT)&&Ec.default.get(x.OPERATIONSAPI_NETWORK_SECUREPORT)),i;(i=n.match(/:(\d+)$/)?.[1])?n=n.slice(0,-i[0].length-1):t.port?i=t.port:i=s||Ec.default.get(x.REPLICATION_PORT)||Ec.default.get(x.OPERATIONSAPI_NETWORK_PORT);let o=i?.lastIndexOf?.(":");o>0&&(i=+i.slice(o+1).replace(/[\[\]]/g,"")),r=(s?"wss://":"ws://")+n+":"+i}if(!r){f1.isMainThread&&console.error("Invalid route, must specify a url or host (with port)");continue}yield{replicates:!t.subscriptions,url:r,subscription:t.subscriptions,routes:t.routes,startTime:t.startTime,revoked_certificates:t.revokedCertificates}}}var f1,m1,Ec,p1,u1,d1,Zd,rf=se(()=>{Oe();gs();Fm();f1=require("worker_threads"),m1=b(Ee()),Ec=b(fe());G();p1=b(sr());server.nodes=[];a(Gt,"getHDBNodeTable");a(ef,"getReplicationSharedStatus");a(tf,"subscribeToNodeUpdates");a(bh,"shouldReplicateToNode");d1=new Map;xx((e,t,r)=>{if(r>server.nodes.length)throw new m1.ClientError(`Cannot confirm replication to more nodes (${r}) than are in the network (${server.nodes.length})`);Zd||(Zd=new Map,ude());let n=Zd.get(e);return n||(n=[],Zd.set(e,n)),new Promise(s=>{let i=0;n.push({txnTime:t,onConfirm:a(()=>{++i===r&&s()},"onConfirm")})})});a(ude,"startSubscriptionToReplications");a(Ah,"iterateRoutes")});var R1={};ye(R1,{connectedToNode:()=>Ql,disconnectedFromNode:()=>sf,ensureNode:()=>aa,requestClusterStatus:()=>y1,startOnMainThread:()=>dO});async function dO(e){let t=0,r=lt();for(let o of Object.getOwnPropertyNames(r)){let c=r[o];for(let l in c){let u=c[l];if(u.auditStore){RT.set(o,Rh(u.auditStore));break}}}Ti.whenThreadsStarted.then(async()=>{let o=[];for await(let u of r.system.hdb_nodes?.search([])||[])o.push(u);let c=nt();function l(){let u=Gt().primaryStore.get(c);if(u!==null){let d=e.url??gc();if(u===void 0||u.url!==d||u.shard!==e.shard)return aa(c,{name:c,url:d,shard:e.shard,replicates:!0})}}a(l,"ensureThisNode"),Gt().primaryStore.get(c)&&l();for(let u of Ah(e))try{let d=!u.subscriptions;if(d&&await l(),d&&u.replicates==null&&(u.replicates=!0),E1.push(u),o.find(f=>f.url===u.url))continue;s(u)}catch(d){console.error(d)}tf(s)});let n;function s(o,c=o?.name){let l=nt()&&c===nt()||gc()&&o?.url===gc();if(l){let m=!!o?.replicates;if(n!==void 0&&n!==m)for(let p of Gt().search([]))p.replicates&&p.name!==c&&s(p,p.name);n=m}if(ot.trace("Setting up node replication for",o),!o){for(let[m,p]of po){let h;for(let[E,{worker:_,nodes:R}]of p){let S=R[0];if(S&&S.name==c){h=!0;for(let[y,{worker:w}]of p)p.delete(y),ot.warn("Node was deleted, unsubscribing from node",c,y,m),w?.postMessage({type:"unsubscribe-from-node",node:c,nodes:R,database:y,url:m});break}}if(h){po.get(m).iterator.remove(),po.delete(m);return}}return}if(l)return;if(!o.url){ot.info(`Node ${o.name} is missing url`);return}let u=po.get(o.url);if(u&&u.iterator.remove(),!(o.replicates===!0||o.replicates?.sends)&&!o.subscriptions?.length&&!u)return;if(ot.info(`Added node ${o.name} at ${o.url} for process ${nt()}`),o.replicates&&o.subscriptions&&(o={...o,subscriptions:null}),o.name){for(let[m,p]of nf)if(o.url===p.url){nf.delete(m);break}nf.set(o.name,o)}let d=lt();if(u||(u=new Map,po.set(o.url,u)),u.iterator=_c(e,(m,p,h)=>{h?f(p,!0):f(p,!1)}),o.subscriptions)for(let m of o.subscriptions){let p=m.database||m.schema;d[p]||(ot.warn(`Database ${p} not found for node ${o.name}, making a subscription anyway`),f(p,!1))}function f(m,p){ot.trace("Setting up replication for database",m,"on node",o.name);let h=u.get(m),E,_=[{replicateByDefault:p,...o}];RT.has(m)&&Ih.default.get(x.REPLICATION_FAILOVER)&&(_.push({replicateByDefault:p,name:nt(),startTime:RT.get(m),endTime:Date.now(),replicates:!0}),RT.delete(m));let R=bh(o,m),S=Ti.workers.filter(y=>y.name==="http");if(h){if(E=h.worker,h.nodes=_,R)return}else R&&(t=t%S.length,E=S[t++],E||ot.warn("No http workers available to subscribe to node",o.name,o.url),u.set(m,{worker:E,nodes:_,url:o.url}),E?.on("exit",()=>{u.get(m)?.worker===E&&(u.delete(m),f(m,p))}));if(R){let y=dde.HDB_LEADER_URL??process.env.HDB_LEADER_URL??E1[0]?.url,w=y?new URL(y).hostname:Array.from(Gt().primaryStore.getKeys({}).filter(H=>H!==nt()))[0],I=_[0].name??(_[0].url&&new URL(_[0].url).hostname);ot.warn(`Setting up subscription with leader ${w} for node ${I}`),_[0].isLeader=!w||I===w,setTimeout(()=>{let H={..._[0],type:"subscribe-to-node",database:m,nodes:_};E?E.postMessage(H):wh(H)},fde)}else{ot.info("Node no longer should be used, unsubscribing from node",{replicates:o.replicates,databaseName:m,node:o,subscriptions:o.subscriptions,hasDatabase:!!d[m],thisReplicates:Gt().primaryStore.get(nt())?.replicates}),Gt().primaryStore.get(nt())?.replicates||(n=!1,ot.info("Disabling replication, this node name",nt(),Gt().primaryStore.get(nt()),m));let y={type:"unsubscribe-from-node",database:m,url:o.url,name:o.name,nodes:_};E?E.postMessage(y):AT(y)}}a(f,"onDatabase")}a(s,"onNodeUpdate"),sf=a(function(o){try{ot.info("Disconnected from node",o.name,o.url,"finished",!!o.finished);let c=Array.from(nf.keys()),l=c.sort(),u=l.indexOf(o.name||yi(o.url));if(u===-1){ot.warn("Disconnected node not found in node map",o.name,c);return}let d=po.get(o.url),f=d?.get(o.database);if(!f){ot.warn("Disconnected node not found in replication map",o.database,d);return}if(f.connected=!1,o.finished||!Ih.default.get(x.REPLICATION_FAILOVER))return;let m=f.nodes[0];if(!(m.replicates===!0||m.replicates?.sends||m.subscriptions?.length))return;let p=m.shard,h=(u+1)%l.length;for(;u!==h;){let E=l[h],_=nf.get(E);d=po.get(_.url);let R=d?.get(o.database);if(!R||R.connected===!1||R.nodes[0].shard!==p){h=(h+1)%l.length;continue}let{nodes:S}=R,y=!1;for(let w of f.nodes){if(S.some(I=>I.name===w.name)){ot.info(`Disconnected node is already failing over to ${E} for ${o.database}`);continue}w.endTime<Date.now()||(S.push(w),ot.info(`Failing over ${o.database} from ${o.name} to ${E}`),i(w,o.database,R.nodes[0]),y=!0)}f.nodes=[f.nodes[0]],y||ot.info(`Disconnected node ${o.name} has no nodes to fail over to ${E}`);return}ot.warn("Unable to find any other node to fail over to",o.name,o.url)}catch(c){ot.error("Error failing over node",c)}},"disconnectedFromNode"),Ql=a(function(o){let c=po.get(o.url),l=c?.get(o.database);if(!l){ot.warn("Connected node not found in replication map, this may be because the node is being removed",o.database,c);return}l.connected=!0,l.latency=o.latency;let u=l.nodes[0];if(!u){ot.warn("Newly connected node has no node subscriptions",o.database,l);return}if(!u.name){ot.debug("Connected node is not named yet",o.database,l);return}if(!Ih.default.get(x.REPLICATION_FAILOVER))return;l.nodes=[u];let d=!1;for(let f of po.values()){let m=f.get(o.database);if(!m||m==l)continue;let{worker:p,nodes:h,connected:E}=m;if(h)if(E===!1&&h[0].shard===u.shard&&node.url===u.url)for(let _ of h)i(_,o.database);else{let _=h.filter(R=>{if(R)return R.name===u.name&&R.worker?(R.worker.postMessage({type:"unsubscribe-to-node",database:o.database,url:o.url,nodes:[R]}),!1):!0});_.length<h.length&&(m.nodes=_)}}},"connectedToNode");function i(o,c,l=o){let u=Ti.workers.filter(f=>f.name==="http");t=t%u.length;let d=u[t++];Object.defineProperty(o,"worker",{value:d,configurable:!0}),d?d.postMessage({url:l.url,name:l.name,type:"subscribe-to-node",database:c,nodes:[o]}):wh({url:l.url,name:l.name,database:c,nodes:[o]})}a(i,"connectToNextWorker"),(0,Ti.onMessageByType)("disconnected-from-node",sf),(0,Ti.onMessageByType)("connected-to-node",Ql),(0,Ti.onMessageByType)("request-cluster-status",y1)}function y1(e,t){let r=[];for(let[n,s]of nf)try{let i=po.get(s.url);ot.info("Getting cluster status for",n,s.url,"has dbs",i?.size);let o=[];if(i){for(let[l,{worker:u,connected:d,nodes:f,latency:m}]of i)o.push({database:l,connected:d,latency:m,threadId:u?.threadId,nodes:f.filter(p=>!(p.endTime<Date.now())).map(p=>p.name)});let c=g1(s);c.database_sockets=o,delete c.ca,delete c.node_name,delete c.__updatedtime__,delete c.__createdtime__,r.push(c)}}catch(i){ot.warn("Error getting cluster status for",s?.url,i)}return t?.postMessage({type:"cluster-status",connections:r}),{connections:r}}async function aa(e,t){let r=Gt();e=e??yi(t.url),t.name=e;try{if(t.ca){let s=new S1.X509Certificate(t.ca);t.ca_info={issuer:s.issuer.replace(/\n/g," "),subject:s.subject.replace(/\n/g," "),subjectAltName:s.subjectAltName,serialNumber:s.serialNumber,validFrom:s.validFrom,validTo:s.validTo}}}catch(s){ot.error("Error parsing replication CA info for hdb_nodes table",s.message)}let n=r.primaryStore.get(e);if(ot.debug(`Ensuring node ${e} at ${t.url}, existing record:`,n,"new record:",t),!n)await r.patch(t);else{t.replicates&&!Ih.default.get(x.CLUSTERING_ENABLED)&&(t.subscriptions=null);for(let s in t)if(n[s]!==t[s]&&s==="subscriptions"&&t[s]&&n[s]){let i=[],o=g1(n[s]);for(let c of t[s]){let l=!1;for(let u of o)if((c.database??c.schema)===(u.database??u.schema)&&c.table===u.table){u.publish=c.publish,u.subscribe=c.subscribe,l=!0;break}l||i.push(c)}t.subscriptions=[...o,...i];break}if(Array.isArray(t.revoked_certificates)){let s=n.revoked_certificates||[];t.revoked_certificates=[...new Set([...s,...t.revoked_certificates])]}ot.info(`Updating node ${e} at ${t.url}`),await r.patch(t)}}var Ti,bT,ot,_1,Ih,S1,T1,g1,dde,fde,po,sf,Ql,nf,RT,E1,Nh=se(()=>{Oe();Ti=b(st());gs();bT=require("worker_threads");rf();ot=b(J()),_1=b(require("lodash")),Ih=b(fe());G();S1=require("crypto"),T1=b(require("minimist")),{cloneDeep:g1}=_1.default,dde=(0,T1.default)(process.argv),fde=200,po=new Map,nf=new Map,RT=new Map,E1=[];a(dO,"startOnMainThread");a(y1,"requestClusterStatus");bT.parentPort&&(sf=a(e=>{bT.parentPort.postMessage({type:"disconnected-from-node",...e})},"disconnectedFromNode"),Ql=a(e=>{bT.parentPort.postMessage({type:"connected-to-node",...e})},"connectedToNode"),(0,Ti.onMessageByType)("subscribe-to-node",e=>{wh(e)}),(0,Ti.onMessageByType)("unsubscribe-from-node",e=>{AT(e)}));a(aa,"ensureNode")});var Ts=M(qt=>{"use strict";var gr=require("path"),{watch:mde}=require("chokidar"),Yn=require("fs-extra"),of=require("node-forge"),C1=require("net"),{generateKeyPair:fO,X509Certificate:ca,createPrivateKey:O1,randomBytes:pde}=require("node:crypto"),hde=require("util");fO=hde.promisify(fO);var Mt=of.pki,Ri=require("joi"),{v4:P1}=require("uuid"),{validateBySchema:EO}=mt(),{forComponent:Ede}=J(),Ss=fe(),Vs=(G(),D(j)),{CONFIG_PARAMS:Xl}=Vs,bi=uA(),{ClientError:Sc}=Ee(),wT=require("node:tls"),{relative:L1,join:_de}=require("node:path"),{CERTIFICATE_VALUES:b1}=bi,gde=tl(),mO=_t(),{table:Sde,getDatabases:Tde,databases:IT}=(Oe(),D(pt)),{getJWTRSAKeys:A1}=(Yd(),D(fh)),Xe=Ede("tls").conditional;qt.generateKeys=SO;qt.updateConfigCert=k1;qt.createCsr=Nde;qt.signCertificate=Cde;qt.setCertTable=af;qt.loadCertificates=x1;qt.reviewSelfSignedCert=yO;qt.createTLSSelector=G1;qt.listCertificates=$1;qt.addCertificate=Mde;qt.removeCertificate=xde;qt.createNatsCerts=Lde;qt.generateCertsKeys=Pde;qt.getReplicationCert=Oh;qt.getReplicationCertAuth=wde;qt.renewSelfSigned=Dde;qt.hostnamesFromCert=bO;qt.getKey=Bde;qt.getHostnamesFromCertificate=Fde;qt.getPrimaryHostName=RO;qt.generateSerialNumber=OT;var{urlToNodeName:D1,getThisNodeUrl:yde,getThisNodeName:CT,clearThisNodeName:Rde}=(gs(),D(la)),{readFileSync:bde,statSync:v1}=require("node:fs"),$0e=fe(),{getTicketKeys:Ade,onMessageFromWorkers:Ide}=st(),{isMainThread:M1}=require("worker_threads"),{TLSSocket:U1,createSecureContext:V0e}=require("node:tls"),_O=3650,Ch=["127.0.0.1","localhost","::1"],gO=[{name:"countryName",value:"USA"},{name:"stateOrProvinceName",value:"Colorado"},{name:"localityName",value:"Denver"},{name:"organizationName",value:"HarperDB, Inc."}];function OT(){let e=pde(8);return e[0]=e[0]&127|1,e.toString("hex")}a(OT,"generateSerialNumber");Ide(async e=>{e.type===Vs.ITC_EVENT_TYPES.RESTART&&(Ss.initSync(!0),await yO())});var an;function yc(){return an||(an=Tde().system.hdb_certificate,an||(an=Sde({table:"hdb_certificate",database:"system",attributes:[{name:"name",isPrimaryKey:!0},{attribute:"uses"},{attribute:"certificate"},{attribute:"is_authority"},{attribute:"private_key_name"},{attribute:"details"},{attribute:"is_self_signed"},{attribute:"__updatedtime__"}]}))),an}a(yc,"getCertTable");async function Oh(){let e=G1("operations-api"),t={secureContexts:null,setSecureContext:a(s=>{},"setSecureContext")};await e.initialize(t);let r=t.secureContexts.get(CT());if(!r)return;let n=new ca(r.options.cert);return r.cert_parsed=n,r.issuer=n.issuer,r}a(Oh,"getReplicationCert");async function wde(){yc();let e=(await Oh()).options.cert,r=new ca(e).issuer.match(/CN=(.*)/)?.[1];return an.get(r)}a(wde,"getReplicationCertAuth");var I1,Tc=new Map;function x1(){if(I1)return;I1=!0;let e=[{configKey:Xl.TLS},{configKey:Xl.OPERATIONSAPI_TLS}];yc();let t=gr.dirname(mO.getConfigFilePath()),r;for(let{configKey:n}of e){let s=mO.getConfigFromFile(n);if(s){Array.isArray(s)||(s=[s]);for(let i of s){let o=i.privateKey,c=o&&L1(_de(t,"keys"),o);c&&w1(o,l=>{Tc.set(c,l)},"private key");for(let l of[!1,!0]){let u=i[l?"certificateAuthority":"certificate"];if(u&&M1){let d;w1(u,f=>{if(b1.cert===f)return;let m=i.hostname??i.hostnames??i.host??i.hosts;m&&!Array.isArray(m)&&(m=[m]);let p=H1(u),h=new ca(p),E;try{E=RO(h)}catch(y){Xe.error?.("error extracting host name from certificate",y);return}if(E==null){Xe.error?.("No host name found on certificate");return}if(h.checkIssued(new ca(b1.cert)))return;let _=an.primaryStore.get(E),R=v1(u).mtimeMs,S=!_||_.is_self_signed?1:_.file_timestamp??_.__updatedtime__;if(_&&R<=S){R<S&&Xe.info?.(`Certificate ${E} at ${u} is older (${new Date(R)}) than the certificate in the database (${S>1?new Date(S):"only self signed certificate available"})`);return}r=an.put({name:E,uses:["https",...n.includes("operations")?["operations"]:[]],ciphers:i.ciphers,certificate:p,private_key_name:c,is_authority:l,hostnames:m,fileTimestamp:R,details:{issuer:h.issuer.replace(/\n/g," "),subject:h.subject?.replace(/\n/g," "),subject_alt_name:h.subjectAltName,serial_number:h.serialNumber,valid_from:h.validFrom,valid_to:h.validTo}})},l?"certificate authority":"certificate")}}}}}return r}a(x1,"loadCertificates");function w1(e,t,r){let n,s=a((i,o)=>{try{let c=o.mtimeMs;c&&c!==n&&(n&&M1&&Xe.warn?.(`Reloading ${r}:`,i),n=c,t(H1(i)))}catch(c){Xe.error?.(`Error loading ${r}:`,i,c)}},"loadFile");Yn.existsSync(e)?s(e,v1(e)):Xe.error?.(`${r} file not found:`,e),mde(e,{persistent:!1}).on("change",s)}a(w1,"loadAndWatch");function pO(){let e=yde();if(e==null){let t=Ch[0];return Xe.info?.("replication url is missing from harperdb-config.yaml, using default host"+t),t}return D1(e)}a(pO,"getHost");function NT(){let e=CT();if(e==null){let t=Ch[0];return Xe.info?.("replication url is missing from harperdb-config.yaml, using default host"+t),t}return e}a(NT,"getCommonName");async function Nde(){let e=await Oh(),t=Mt.certificateFromPem(e.options.cert),r=Mt.privateKeyFromPem(e.options.key);Xe.info?.("Creating CSR with cert named:",e.name);let n=Mt.createCertificationRequest();n.publicKey=t.publicKey;let s=[{name:"commonName",value:NT()},...gO];Xe.info?.("Creating CSR with subject",s),n.setSubject(s);let i=[{name:"unstructuredName",value:"HarperDB, Inc."},{name:"extensionRequest",extensions:B1()}];return Xe.info?.("Creating CSR with attributes",i),n.setAttributes(i),n.sign(r),of.pki.certificationRequestToPem(n)}a(Nde,"createCsr");function B1(){let e=Ch.includes(NT())?Ch:[...Ch,NT()];return e.includes(pO())||e.push(pO()),[{name:"basicConstraints",cA:!1,critical:!0},{name:"keyUsage",digitalSignature:!0,keyEncipherment:!0,critical:!0},{name:"extKeyUsage",serverAuth:!0,clientAuth:!0},{name:"nsCertType",client:!0,server:!0},{name:"subjectAltName",altNames:e.map(t=>C1.isIP(t)?{type:7,ip:t}:{type:2,value:t})}]}a(B1,"certExtensions");async function Cde(e){let t={},r=gr.join(Ss.getHdbBasePath(),Vs.LICENSE_KEY_DIR_NAME);if(e.csr){let n,s;yc();for await(let d of an.search([]))if(d.is_authority&&!d.details.issuer.includes("HarperDB-Certificate-Authority")){if(Tc.has(d.private_key_name)){n=Tc.get(d.private_key_name),s=d;break}else if(d.private_key_name&&await Yn.exists(gr.join(r,d.private_key_name))){n=Yn.readFile(gr.join(r,d.private_key_name)),s=d;break}}if(!n){let d=await hO();s=d.ca,n=d.private_key}n=Mt.privateKeyFromPem(n),t.signingCA=s.certificate;let i=Mt.certificateFromPem(s.certificate);Xe.info?.("Signing CSR with cert named",s.name);let o=Mt.certificationRequestFromPem(e.csr);try{o.verify()}catch(d){return Xe.error?.(d),new Error("Error verifying CSR: "+d.message)}let c=of.pki.createCertificate();c.serialNumber=OT(),c.validity.notBefore=new Date;let l=new Date;c.validity.notAfter=l,c.validity.notAfter.setDate(l.getDate()+_O),Xe.info?.("sign cert setting validity:",c.validity),Xe.info?.("sign cert setting subject from CSR:",o.subject.attributes),c.setSubject(o.subject.attributes),Xe.info?.("sign cert setting issuer:",i.subject.attributes),c.setIssuer(i.subject.attributes);let u=o.getAttribute({name:"extensionRequest"}).extensions;Xe.info?.("sign cert adding extensions from CSR:",u),c.setExtensions(u),c.publicKey=o.publicKey,c.sign(n,of.md.sha256.create()),t.certificate=Mt.certificateToPem(c)}else Xe.info?.("Sign cert did not receive a CSR from:",e.url,"only the CA will be returned");return t}a(Cde,"signCertificate");async function Ode(e,t){await af({name:CT(),uses:["https","wss"],certificate:e,private_key_name:"privateKey.pem",is_authority:!1,is_self_signed:!0}),await af({name:t.subject.getField("CN").value,uses:["https","wss"],certificate:Mt.certificateToPem(t),private_key_name:"privateKey.pem",is_authority:!0,is_self_signed:!0})}a(Ode,"createCertificateTable");async function af(e){let t;try{t=new ca(e.certificate)}catch(r){Xe.error?.(`Failed to parse certificate for ${e.name}:`,r.message),Xe.debug?.("Certificate record details:",JSON.stringify(e,null,2));let n=new Error(`Invalid certificate format for ${e.name}: ${r.message}. This may be due to corrupted certificate data during transfer or encoding issues.`);throw n.code="INVALID_CERTIFICATE_FORMAT",n.cause=r,n}e.details={issuer:t.issuer.replace(/\n/g," "),subject:t.subject?.replace(/\n/g," "),subject_alt_name:t.subjectAltName,serial_number:t.serialNumber,valid_from:t.validFrom,valid_to:t.validTo},yc(),await an.patch(e)}a(af,"setCertTable");async function SO(){let e=await fO("rsa",{modulusLength:4096,publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs8",format:"pem"}});return{publicKey:Mt.publicKeyFromPem(e.publicKey),privateKey:Mt.privateKeyFromPem(e.privateKey)}}a(SO,"generateKeys");async function TO(e,t,r){let n=Mt.createCertificate();if(!t){let o=await Oh();t=Mt.certificateFromPem(o.options.cert).publicKey}n.publicKey=t,n.serialNumber=OT(),n.validity.notBefore=new Date;let s=new Date;n.validity.notAfter=s,n.validity.notAfter.setDate(s.getDate()+_O);let i=[{name:"commonName",value:NT()},...gO];return n.setSubject(i),n.setIssuer(r.subject.attributes),n.setExtensions(B1()),n.sign(e,of.md.sha256.create()),Mt.certificateToPem(n)}a(TO,"generateCertificates");async function hO(){let e=await $1(),t;for(let r of e){if(!r.is_authority)continue;let n=await q1(r.private_key_name);if(r.private_key_name&&n&&new ca(r.certificate).checkPrivateKey(O1(n))){Xe.trace?.(`CA named: ${r.name} found with matching private key`),t={ca:r,private_key:n};break}}if(t)return t;Xe.trace?.("No CA found with matching private key")}a(hO,"getCertAuthority");async function F1(e,t,r=!0){let n=Mt.createCertificate();n.publicKey=t,n.serialNumber=OT(),n.validity.notBefore=new Date;let s=new Date;n.validity.notAfter=s,n.validity.notAfter.setDate(s.getDate()+_O);let i=[{name:"commonName",value:`HarperDB-Certificate-Authority-${Ss.get(Xl.REPLICATION_HOSTNAME)??D1(Ss.get(Xl.REPLICATION_URL))??P1().split("-")[0]}`},...gO];n.setSubject(i),n.setIssuer(i),n.setExtensions([{name:"basicConstraints",cA:!0,critical:!0},{name:"keyUsage",keyCertSign:!0,critical:!0},{name:"subjectKeyIdentifier"}]),n.sign(e,of.md.sha256.create());let o=gr.join(Ss.getHdbBasePath(),Vs.LICENSE_KEY_DIR_NAME),c=gr.join(o,bi.PRIVATEKEY_PEM_NAME);return r&&await Yn.writeFile(c,Mt.privateKeyToPem(e)),n}a(F1,"generateCertAuthority");async function Pde(){let{privateKey:e,publicKey:t}=await SO(),r=await F1(e,t),n=await TO(e,t,r);await Ode(n,r),k1()}a(Pde,"generateCertsKeys");async function Lde(){let e=await TO(Mt.privateKeyFromPem(bi.CERTIFICATE_VALUES.key),void 0,Mt.certificateFromPem(bi.CERTIFICATE_VALUES.cert)),t=gr.join(Ss.getHdbBasePath(),Vs.LICENSE_KEY_DIR_NAME),r=gr.join(t,bi.NATS_CERTIFICATE_PEM_NAME);await Yn.exists(r)||await Yn.writeFile(r,e);let n=gr.join(t,bi.NATS_CA_PEM_NAME);await Yn.exists(n)||await Yn.writeFile(n,bi.CERTIFICATE_VALUES.cert)}a(Lde,"createNatsCerts");async function Dde(){yc();for await(let e of an.search([{attribute:"is_self_signed",value:!0}]))await an.delete(e.name);await yO()}a(Dde,"renewSelfSigned");async function yO(){Rde(),await x1(),yc();let e=await hO();if(!e){Xe.notify?.("A matching Certificate Authority and key was not found. A new CA will be created in advance, so it's available if needed.");let r=a(u=>{try{return{key:Mt.privateKeyFromPem(Yn.readFileSync(u)),keyPath:u}}catch(d){return Xe.warn?.(`Failed to parse private key from ${u}:`,d.message),{key:null,keyPath:u}}},"tryToParseKey"),n=Ss.get(Xl.TLS),s,i;if(Array.isArray(n)){for(let u of n)if(u.privateKey){let d=r(u.privateKey);if(s=d.key,i=d.keyPath,d.key)break}}else{let u=Ss.get(Xl.TLS_PRIVATEKEY),d=r(u);s=d.key,i=d.keyPath}let o=gr.join(Ss.getHdbBasePath(),Vs.LICENSE_KEY_DIR_NAME),c=L1(o,i);s||(Xe.warn?.("Unable to parse the TLS key",i,"A new key will be generated and used to create Certificate Authority"),{privateKey:s}=await SO(),Yn.existsSync(gr.join(o,bi.PRIVATEKEY_PEM_NAME))&&(c=`privateKey${P1().split("-")[0]}.pem`),await Yn.writeFile(gr.join(o,c),Mt.privateKeyToPem(s)));let l=await F1(s,Mt.setRsaPublicKey(s.n,s.e),!1);await af({name:l.subject.getField("CN").value,uses:["https"],certificate:Mt.certificateToPem(l),private_key_name:c,is_authority:!0,is_self_signed:!0})}if(!await Oh()){let r=CT();Xe.notify?.(`A suitable replication certificate was not found, creating new self singed cert named: ${r}`),e=e??await hO();let n=Mt.certificateFromPem(e.ca.certificate),s=n.publicKey,i=await TO(Mt.privateKeyFromPem(e.private_key),s,n);await af({name:r,uses:["https","operations","wss"],certificate:i,is_authority:!1,private_key_name:e.ca.private_key_name,is_self_signed:!0})}}a(yO,"reviewSelfSignedCert");function k1(){let e=gde(Object.keys(Vs.CONFIG_PARAM_MAP),!0),t=gr.join(Ss.getHdbBasePath(),Vs.LICENSE_KEY_DIR_NAME),r=gr.join(t,bi.PRIVATEKEY_PEM_NAME),n=gr.join(t,bi.NATS_CERTIFICATE_PEM_NAME),s=gr.join(t,bi.NATS_CA_PEM_NAME),i=Vs.CONFIG_PARAMS,o={[i.TLS_PRIVATEKEY]:e[i.TLS_PRIVATEKEY.toLowerCase()]?e[i.TLS_PRIVATEKEY.toLowerCase()]:r};e[i.TLS_CERTIFICATE.toLowerCase()]&&(o[i.TLS_CERTIFICATE]=e[i.TLS_CERTIFICATE.toLowerCase()]),e[i.TLS_CERTIFICATEAUTHORITY.toLowerCase()]&&(o[i.TLS_CERTIFICATEAUTHORITY]=e[i.TLS_CERTIFICATEAUTHORITY.toLowerCase()]),e[i.OPERATIONSAPI_TLS_CERTIFICATE.toLowerCase()]&&(o[i.OPERATIONSAPI_TLS_CERTIFICATE]=e[i.OPERATIONSAPI_TLS_CERTIFICATE.toLowerCase()]),e[i.OPERATIONSAPI_TLS_PRIVATEKEY.toLowerCase()]&&(o[i.OPERATIONSAPI_TLS_PRIVATEKEY]=e[i.OPERATIONSAPI_TLS_PRIVATEKEY.toLowerCase()]),e[i.OPERATIONSAPI_TLS_CERTIFICATEAUTHORITY.toLowerCase()]&&(o[i.OPERATIONSAPI_TLS_CERTIFICATEAUTHORITY]=e[i.OPERATIONSAPI_TLS_CERTIFICATEAUTHORITY.toLowerCase()]),(e[i.CLUSTERING_ENABLED.toLowerCase()]||e.clustering)&&(o[i.CLUSTERING_TLS_CERTIFICATE]=e[i.CLUSTERING_TLS_CERTIFICATE.toLowerCase()]??n,o[i.CLUSTERING_TLS_CERT_AUTH]=e[i.CLUSTERING_TLS_CERT_AUTH.toLowerCase()]??s,o[i.CLUSTERING_TLS_PRIVATEKEY]=e[i.CLUSTERING_TLS_PRIVATEKEY.toLowerCase()]??r),mO.updateConfigValue(void 0,void 0,o,!1,!0)}a(k1,"updateConfigCert");function H1(e){return e.startsWith("-----BEGIN")?e:bde(e,"utf8")}a(H1,"readPEM");var N1=wT.createSecureContext;wT.createSecureContext=function(e){if(!e.cert||!e.key)return N1(e);let t={...e};delete t.key,delete t.cert;let r=N1(t);return r.context.setCert(e.cert),r.context.setKey(e.key,void 0),r};var vde=U1.prototype._init;U1.prototype._init=function(e,t){vde.call(this,e,t);let r=this;this._handle.oncertcb=function(n){let s=n.servername;r._SNICallback(s,(i,o)=>{this.sni_context=o?.context||o,this.certCbDone()})}};var Jl=new Map;function G1(e,t){let r=new Map,n,s=!1;return i.initialize=o=>i.ready?i.ready:(o&&(o.secureContexts=r,o.secureContextsListeners=[]),i.ready=new Promise((c,l)=>{async function u(){try{r.clear(),Jl.clear();let d=0;if(IT===void 0){c();return}for await(let f of IT.system.hdb_certificate.search([])){let m=f.certificate,p=new ca(m);f.is_authority&&(p.asString=m,Jl.set(p.subject,m))}for await(let f of IT.system.hdb_certificate.search([]))try{if(f.is_authority)continue;let m=e==="operations-api",p=f.is_self_signed?1:3;m&&f.uses?.includes?.("operations")&&(p+=1);let h=await q1(f.private_key_name),E=f.certificate,_=new ca(E);if(Jl.has(_.issuer)&&(E+=`
18
- `+Jl.get(_.issuer)),!h||!E)throw new Error("Missing private key or certificate for secure server");let R={ciphers:f.ciphers,ticketKeys:Ade(),availableCAs:Jl,ca:t&&Array.from(Jl.values()),cert:E,key:h,key_file:f.private_key_name,is_self_signed:f.is_self_signed};o&&(R.sessionIdContext=o.sessionIdContext);let S=f.hostnames??bO(_);Array.isArray(S)||(S=[S]);for(let I of S)I===pO()&&(p+=1);let y=wT.createSecureContext(R);y.name=f.name,y.options=R,y.quality=p,y.certificateAuthorities=Array.from(Jl),y.certStart=E.toString().slice(0,100);let w;for(let I of S)if(I){I[0]==="*"&&(s=!0,I=I.slice(1)),C1.isIP(I)&&(w=!0);let H=r.get(I)?.quality??0;Xe.trace?.("Assigning TLS for hostname",I,"if",p,">",H),p>H&&r.set(I,y)}else Xe.error?.("No hostname found for certificate at",wT.certificate);Xe.trace?.("Adding TLS",y.name,"for",o.ports||"client","cert named",f.name,"hostnames",S,"quality",p,"best quality",d),p>d&&(i.defaultContext=n=y,d=p,o&&(o.defaultContext=y))}catch(m){Xe.error?.("Error applying TLS for",f.name,m)}o?.secureContextsListeners.forEach(f=>f()),c(n)}catch(d){l(d)}}a(u,"updateTLS"),IT?.system.hdb_certificate.subscribe({listener:a(()=>setTimeout(()=>u(),1500).unref(),"listener"),omitCurrent:!0}),u()})),i;function i(o,c){Xe.info?.("TLS requested for",o||"(no SNI)");let l=o;for(;;){let d=r.get(l);if(d)return Xe.debug?.("Found certificate for",o,d.certStart),d.updatedContext&&(d=d.updatedContext),c(null,d);if(s&&l){let f=l.indexOf(".",1);f<0?l="":l=l.slice(f)}else break}o?Xe.debug?.("No certificate found to match",o,"using the default certificate"):Xe.debug?.("No SNI, using the default certificate",n?.name);let u=n;u?u.updatedContext&&(u=u.updatedContext):Xe.info?.("No default certificate found"),c(null,u)}a(i,"SNICallback")}a(G1,"createTLSSelector");async function q1(e){let t=Tc.get(e);return!t&&e?await Yn.readFile(gr.join(Ss.get(Xl.ROOTPATH),Vs.LICENSE_KEY_DIR_NAME,e),"utf8"):t}a(q1,"getPrivateKeyByName");async function $1(){yc();let e=[];for await(let t of an.search([]))e.push(t);return e}a($1,"listCertificates");async function Mde(e){let t=EO(e,Ri.object({name:Ri.string().required(),certificate:Ri.string().required(),is_authority:Ri.boolean().required(),private_key:Ri.string(),hosts:Ri.array(),uses:Ri.array()}));if(t)throw new Sc(t.message);let{name:r,certificate:n,private_key:s,is_authority:i}=e,o=new ca(n),c=!1,l=!1,u;for(let[p,h]of Tc)!s&&!c&&o.checkPrivateKey(O1(h))&&(c=!0,u=p),s&&s===h&&(l=!0,u=p);if(!i&&!s&&!c)throw new Sc("A suitable private key was not found for this certificate");let d;if(!r){try{d=RO(o)}catch(p){Xe.error?.(p)}if(d==null)throw new Sc("Error extracting certificate host name, please provide a name parameter")}let f=Ude(r??d);s&&!c&&!l&&(await Yn.writeFile(gr.join(Ss.getHdbBasePath(),Vs.LICENSE_KEY_DIR_NAME,f+".pem"),s),Tc.set(f,s));let m={name:r??d,certificate:n,is_authority:i,hosts:e.hosts,uses:e.uses};return(!i||i&&u||i&&s)&&(m.private_key_name=u??f+".pem"),e.ciphers&&(m.ciphers=e.ciphers),await af(m),"Successfully added certificate: "+f}a(Mde,"addCertificate");function Ude(e){return e.replace(/[^a-z0-9\.]/gi,"-")}a(Ude,"sanitizeName");async function xde(e){let t=EO(e,Ri.object({name:Ri.string().required()}));if(t)throw new Sc(t.message);let{name:r}=e;yc();let n=await an.get(r);if(!n)throw new Sc(r+" not found");let{private_key_name:s}=n;if(s){let i=Array.from(await an.search([{attribute:"private_key_name",value:s}]));i.length===1&&i[0].name===r&&(Xe.info?.("Removing private key named",s),await Yn.remove(gr.join(Ss.getHdbBasePath(),Vs.LICENSE_KEY_DIR_NAME,s)))}return await an.delete(r),"Successfully removed "+r}a(xde,"removeCertificate");function RO(e){let t=e.subject?.match(/CN=(.*)/)?.[1];return t||bO(e)[0]}a(RO,"getPrimaryHostName");function bO(e){if(e.subjectAltName)return e.subjectAltName.split(",").map(r=>{let n=r.indexOf(":");if(r=r.slice(n+1),r=r.trim(),r[0]==='"')try{r=JSON.parse(r)}catch{}return r.indexOf("=")>-1?r.match(/CN=([^,]*)/)?.[1]:r}).filter(r=>r);let t=e.subject?.match(/CN=(.*)/)?.[1];return t?[t]:[]}a(bO,"hostnamesFromCert");async function Bde(e){if(e.bypass_auth!==!0)throw new Sc("Unauthorized","401");let t=EO(e,Ri.object({name:Ri.string().required()}));if(t)throw new Sc(t.message);let{name:r}=e;if(r===".jwtPrivate")return(await A1()).privateKey;if(r===".jwtPublic")return(await A1()).publicKey;if(Tc.get(r))return Tc.get(e.name);throw new Sc("Key not found")}a(Bde,"getKey");function Fde(e){return[e.subject?.CN,...e.subjectaltname.split(",").filter(t=>t.trim().startsWith("DNS:")).map(t=>t.trim().substring(4))]}a(Fde,"getHostnamesFromCertificate")});var fK={};ye(fK,{BACK_PRESSURE_RATIO_POSITION:()=>uK,CONFIRMATION_STATUS_POSITION:()=>lK,LATENCY_POSITION:()=>BT,NodeReplicationConnection:()=>lf,OPERATION_REQUEST:()=>CO,RECEIVED_TIME_POSITION:()=>UT,RECEIVED_VERSION_POSITION:()=>MT,RECEIVING_STATUS_POSITION:()=>xT,RECEIVING_STATUS_RECEIVING:()=>dK,RECEIVING_STATUS_WAITING:()=>OO,SENDING_TIME_POSITION:()=>Lh,createWebSocket:()=>FT,databaseSubscriptions:()=>bc,replicateOverWS:()=>Dh,tableUpdateListeners:()=>DO});async function FT(e,t){let{authorization:r,rejectUnauthorized:n}=t||{},s=nt(),i;if(e==null)throw new TypeError(`Invalid URL: Expected a string URL for node "${s}" but received ${e}`);if(e.includes("wss://")){if(!wO){let l=(0,iK.createTLSSelector)("operations-api"),u={secureContexts:null};await l.initialize(u),wO=u.secureContexts}if(i=wO.get(s),i&&le.debug?.("Creating web socket for URL",e,"with certificate named:",i.name),!i&&n!==!1)throw new Error("Unable to find a valid certificate to use for replication to connect to "+e)}let o={};r&&(o.Authorization=r);let c={headers:o,localAddress:s?.startsWith("127.0")?s:void 0,servername:(0,aK.isIP)(t?.serverName)?void 0:t?.serverName,noDelay:!0,highWaterMark:128*1024,rejectUnauthorized:n!==!1,secureContext:void 0};return i&&((cf?.caCount!==ua.size||cf?.derivedFromContext!==i)&&(cf=oK.createSecureContext({...i.options,ca:[...ua,...i.options.availableCAs.values()]}),cf.caCount=ua.size,cf.derivedFromContext=i),c.secureContext=cf),new rK.WebSocket(e,"harperdb-replication-v1",c)}function Dh(e,t,r){let n=t.port||t.securePort,s=LO.pid%1e3+"-"+nK.threadId+(n?"s:"+n:"c:"+t.url?.slice(-4))+" "+Math.random().toString().slice(2,3);le.debug?.(s,"Initializing replication connection",r);let i=0,o=Buffer.allocUnsafeSlow(1024),c=0,l=new DataView(o.buffer,0,1024),u=t.database,d=t.databaseSubscriptions||bc,f,m,p=!1,h=t.subscription;h?.then&&h.then(A=>{h=A,h.auditStore&&(f=h.auditStore)});let E=t.tables||u&&lt()[u],_,R=new Map,S=[];_=r.name,_&&t.connection&&(t.connection.nodeName=_);let y,w,I,H,X,q,k,z=6e4,Y,ce=0,de=0,te=0,Se=tK.default.get(x.REPLICATION_BLOBTIMEOUT)??12e4,Ne=new Map,Ke=[],$e=0,Ir;if(t.url){let A=a(()=>{X&&de===e._socket?.bytesRead&&te===e._socket?.bytesWritten?e.terminate():(X=performance.now(),e.ping(),de=e._socket?.bytesRead,te=e._socket?.bytesWritten)},"sendPing");I=setInterval(A,Z1).unref(),A()}else nr();e._socket?.setMaxListeners(200);function nr(){clearTimeout(H),de=e._socket?.bytesRead,te=e._socket?.bytesWritten,H=setTimeout(()=>{de===e._socket?.bytesRead&&te===e._socket?.bytesWritten&&(le.warn?.(`Timeout waiting for ping from ${_}, terminating connection and reconnecting`),e.terminate())},Z1*2).unref()}a(nr,"resetPingTimer");let zr=0,xr=0,Lu=!1,Qc=3e4;function Ft(){if(pn?.length>0){let A=performance.now(),U=A-xr;zr=(zr*Qc+(Lu?U:0))/(Qc+U),m&&(m[uK]=zr),xr=A}}a(Ft,"updateBackPressureRatio"),setInterval(Ft,Qc).unref();function Ps(){if(!(!_||!u))return m||(m=ef(f,u,_)),m}a(Ps,"getSharedStatus"),u&&Jc(u);let Ga,l_,lm=[],u_=[],um,ve=[],d_=[],jb=[],Du=150,Gi=25,Ls=0,dm=0,fm=!1,Fo,Dn,pn,Br;e.on("message",vu);async function vu(A){if(r=await r,!r){le.error?.(s,"No authorization provided"),Fr(1008,"Unauthorized");return}mm(A),e.off("message",vu),e.on("message",mm)}a(vu,"onWSMessageWhenAuthorized");function mm(A){ce=performance.now();try{let U=A.dataView=new dl(A.buffer,A.byteOffset,A.byteLength);if(A[0]>127){let W=(0,at.decode)(A),[Q,F,he]=W;switch(Q){case K1:{if(F){if(_){if(_!==F){le.error?.(s,`Node name mismatch, expecting to connect to ${_}, but peer reported name as ${F}, disconnecting`),e.send((0,at.encode)([Ph])),Fr(1008,"Node name mismatch");return}}else if(_=F,t.connection?.tentativeNode){let me=t.connection.tentativeNode;me.name=_,t.connection.tentativeNode=null,aa(_,me)}if(t.connection&&(t.connection.nodeName=_),le.debug?.(s,"received node name:",_,"db:",u??W[2]),!u)try{Jc(u=W[2]),u==="system"&&(Ga=_c(t,(me,ie)=>{Va(ie)&&K(ie)}),e.on("close",()=>{Ga?.remove()}))}catch(me){le.warn?.(s,"Error setting database",me),e.send((0,at.encode)([Ph])),Fr(1008,me.message);return}pm()}break}case J1:{le.debug?.(s,"Received table definitions for",F.map(me=>me.table));for(let me of F){let ie=W[2];me.database=ie;let Ce;if(Va(ie)){if(u==="system")Me[ie]?.[me.table]||(Ce=v(me,Me[ie]?.[me.table]));else{if(ie!=="data"&&!Me[ie]){le.warn?.("Database not found",ie);return}Ce=v(me,Me[ie]?.[me.table])}f||(f=Ce?.auditStore),E||(E=lt()?.[ie])}}break}case Ph:Fr();break;case CO:try{let me=r?.replicates||r?.subscribers||r?.name;le.debug?.("Received operation request",F,"from",_),server.operation(F,{user:r},!me).then(ie=>{le.debug?.("Requested request from finished",_,ie),Array.isArray(ie)&&(ie={results:ie}),ie.requestId=F.requestId,e.send((0,at.encode)([LT,ie]))},ie=>{le.debug?.("Failed requested operation from",_,ie),e.send((0,at.encode)([LT,{requestId:F.requestId,error:AO(ie)}]))})}catch(me){e.send((0,at.encode)([LT,{requestId:F.requestId,error:AO(me)}]))}break;case LT:let{resolve:ue,reject:_e}=R.get(F.requestId);le.debug?.("Received completed operation request",_,F),F.error?_e(new Error(F.error)):ue(F),R.delete(F.requestId);break;case IO:let re=W[3];if(!E){u?le.error?.(s,"No database found for",u):le.error?.(s,"Database name never received"),Fr();return}let oe=E[re];oe=v({table:re,database:u,attributes:F.attributes,schemaDefined:F.schemaDefined},oe),lm[he]={name:re,decoder:new at.Packr({useBigIntExtension:!0,randomAccessStructure:!0,freezeData:!0,typedStructs:F.typedStructs,structures:F.structures}),getEntry(me){return oe.primaryStore.getEntry(me)},rootStore:oe.primaryStore.rootStore};break;case Y1:Br=f?l1(F,f):new Map,um=W[2],le.debug?.(s,`Acknowledged subscription request, receiving messages for nodes: ${um}`);break;case W1:let ge=he;jb[ge]=F;break;case Q1:Ps()[lK]=F,le.trace?.(s,"received and broadcasting committed update",F),Ps().buffer.notify();break;case z1:y=F,h.send({type:"end_txn",localTime:y,remoteNodeIds:S}),Ps(),replication_shared_status[MT]=last_sequence_id_received,replication_shared_status[UT]=Date.now(),replication_shared_status[xT]=OO;break;case DT:{let me=W[1],{fileId:ie,size:Ce,finished:Be,error:He}=me,Te=Ne.get(ie);le.debug?.("Received blob",ie,"has stream",!!Te,"connectedToBlob",!!Te?.connectedToBlob,"length",W[2].length,"finished",Be),Te||(Te=new NO.PassThrough,Te.expectedSize=Ce,Ne.set(ie,Te)),Te.lastChunk=Date.now();let ht=W[2];We(ht.byteLength,"bytes-received",`${_}.${u}`,"replication","blob");try{Be?(He?(Te.on("error",()=>{}),Te.destroy(new Error("Blob error: "+He+" for record "+(Te.recordId??"unknown")+" from "+_))):Te.end(ht),Te.connectedToBlob&&Ne.delete(ie)):Te.write(ht)}catch(Ct){le.error?.(`Error receiving blob for ${Te.recordId} from ${_} and streaming to storage`,Ct),Ne.delete(ie)}break}case j1:{let me=F,ie;try{let Ce=W[3],Be=u_[he]||(u_[he]=E[W[4]]);if(!Be)return le.warn?.("Unknown table id trying to handle record request",he);let He=Be.primaryStore.getBinaryFast(Symbol.for("structures")),Te=He?.length??0;if(Te>0&&Te!==dm){dm=Te;let Ct=(0,at.decode)(He);e.send((0,at.encode)([IO,{typedStructs:Ct.typed,structures:Ct.named},he,Be.tableName]))}let ht=Be.primaryStore.getBinaryFast(Ce);if(ht){let Ct=Be.primaryStore.decoder.decode(ht,{valueAsBuffer:!0}),Ot=ut||{};Ot.version=(0,cK.getLastVersion)(),ut&&ut[Xu]&Zr&&(Ct=Buffer.from(Ct),jm(()=>Be.primaryStore.decoder.decode(ht),m_=>qa(m_,Ce),Be.primaryStore.rootStore)),ie=(0,at.encode)([PT,me,{value:Ct,expiresAt:Ot.expiresAt,version:Ot.version,residencyId:Ot.residencyId,nodeId:Ot.nodeId,user:Ot.user}])}else ie=(0,at.encode)([PT,me])}catch(Ce){ie=(0,at.encode)([PT,me,{error:Ce.message}])}e.send(ie);break}case PT:{let{resolve:me,reject:ie,tableId:Ce,key:Be}=R.get(W[1]),He=W[2];if(He?.error)ie(new Error(He.error));else if(He){let Te;sg(()=>{let ht=lm[Ce].decoder.decode(He.value);He.value=ht,He.key=Be,me(He)||Te&&setTimeout(()=>Te.forEach(tg),6e4).unref()},f?.rootStore,ht=>{let Ct=$a(ht,Be);return Te||(Te=[]),Te.push(Ct),Ct})}else me();R.delete(W[1]);break}case V1:{pn=F;let me,ie,Ce=!1;if(h){if(u!==h.databaseName&&!h.then){le.error?.("Subscription request for wrong database",u,h.databaseName);return}}else h=d.get(u);if(le.debug?.(s,"received subscription request for",u,"at",pn),!h){let De;h=new Promise(ft=>{le.debug?.("Waiting for subscription to database "+u),De=ft}),h.ready=De,bc.set(u,h)}if(r.name)ie=Gt().subscribe(r.name),ie.then(async De=>{me=De;for await(let ft of me){let kr=ft.value;if(!(kr?.replicates===!0||kr?.replicates?.receives||kr?.subscriptions?.some(fr=>(fr.database||fr.schema)===u&&fr.publish!==!1))){Ce=!0,Fr(1008,`Unauthorized database subscription to ${u}`);return}}},De=>{le.error?.(s,"Error subscribing to HDB nodes",De)});else if(!(r?.role?.permission?.super_user||r.replicates)){e.send((0,at.encode)([Ph])),Fr(1008,`Unauthorized database subscription to ${u}`);return}if(Dn&&(le.debug?.(s,"stopping previous subscription",u),Dn.emit("close")),pn.length===0)return;let Be=pn[0],He=a(De=>{if(De&&(Be.replicateByDefault?!Be.tables.includes(De.tableName):Be.tables.includes(De.tableName)))return{table:De}},"tableToTableEntry"),Te={txnTime:0},ht,Ct,Ot=1/0,m_,p_=a((De,ft)=>{if(De.type==="end_txn"){Te.txnTime&&(o[i]!==66&&le.error?.("Invalid encoding of message"),C(9),C(hg),O(m_=ft),iU()),i=c,Te.txnTime=0;return}let kr=De.nodeId,fr=De.tableId,zt=Ct[fr];if(!zt&&(zt=Ct[fr]=He(h.tableById[fr]),!zt))return le.debug?.("Not subscribed to table",fr);let yt=zt.table,xu=yt.primaryStore,si=xu.encoder;(De.extendedType&Ig||!si.typedStructs)&&(si._mergeStructures(si.getStructures()),si.typedStructs&&(si.lastTypedStructuresLength=si.typedStructs.length));let h_=ht[kr];if(!(h_&&h_.startTime<ft&&(!h_.endTime||h_.endTime>ft)))return vT&&le.trace?.(s,"skipping replication update",De.recordId,"to:",_,"from:",kr,"subscribed:",ht),oU();vT&&le.trace?.(s,"sending replication update",De.recordId,"to:",_,"from:",kr,"subscribed:",ht);let zb=De.version,Xc=De.residencyId,Qb=f_(Xc,yt),E_;if(Qb&&!Qb.includes(_)){let qi=f_(De.previousResidencyId,yt);if(qi&&!qi.includes(_)&&(De.type==="put"||De.type==="patch")||yt.getResidencyById)return oU();let Zc=De.recordId;le.trace?.(s,"sending invalidation",Zc,_,"from",kr);let hm=0;Xc&&(hm|=fl),De.previousResidencyId&&(hm|=ml);let Zb,__=null;for(let aU in yt.indices){if(!__){if(Zb=De.getValue(xu,!0),!Zb)break;__={}}__[aU]=Zb[aU]}E_=pl(De.version,fr,Zc,null,kr,De.user,De.type==="put"||De.type==="patch"?"invalidate":De.type,si.encode(__),hm,Xc,De.previousResidencyId,De.expiresAt)}function oU(){return le.trace?.(s,"skipping audit record",De.recordId),q||(q=setTimeout(()=>{q=null,(m_||0)+X1/2<Ot&&(vT&&le.trace?.(s,"sending skipped sequence update",Ot),e.send((0,at.encode)([z1,Ot])))},X1).unref()),new Promise(setImmediate)}a(oU,"skipAuditRecord");let Jb=si.typedStructs,Xb=si.structures;if((Jb?.length!=zt.typed_length||Xb?.length!=zt.structure_length)&&(zt.typed_length=Jb?.length,zt.structure_length=Xb.length,le.debug?.(s,"send table struct",zt.typed_length,zt.structure_length),zt.sentName||(zt.sentName=!0),e.send((0,at.encode)([IO,{typedStructs:Jb,structures:Xb,attributes:yt.attributes,schemaDefined:yt.schemaDefined},fr,zt.table.tableName]))),Xc&&!d_[Xc]&&(e.send((0,at.encode)([W1,Qb,Xc])),d_[Xc]=!0),Te.txnTime!==zb&&(Te.txnTime&&(vT&&le.trace?.(s,"new txn time, sending queued txn",Te.txnTime),o[i]!==66&&le.error?.("Invalid encoding of message"),iU()),Te.txnTime=zb,i=c,O(zb)),E_)C(E_.length),P(E_);else{let qi=De.encoded;De.extendedType&Zr&&jm(()=>De.getValue(xu),hm=>qa(hm,De.recordId),xu.rootStore);let Zc=qi[0]===66?8:0;C(qi.length-Zc),P(qi,Zc),le.trace?.("wrote record",De.recordId,"length:",qi.length)}if(e._socket.writableNeedDrain){let qi=performance.now();return Lu=!0,Ft(),new Promise(Zc=>{le.debug?.(`Waiting for remote node ${_} to allow more commits ${e._socket.writableNeedDrain?"due to network backlog":"due to requested flow directive"}`),e._socket.once("drain",()=>{Zc(),Lu=!1,Ft()})})}else return $e>Gi?new Promise(qi=>{Ir=qi}):new Promise(setImmediate)},"sendAuditRecord"),iU=a(()=>{c-i>8?(e.send(o.subarray(i,c)),le.debug?.(s,"Sent message, size:",c-i),u!=="system"&&We(c-i,"bytes-sent",`${_}.${u}`,"replication","egress")):le.debug?.(s,"skipping empty transaction")},"sendQueuedData");Dn=new PO.EventEmitter,Dn.once("close",()=>{Ce=!0,me?.end()});for(let{startTime:De}of pn)De<Ot&&(Ot=De);(ie||Promise.resolve()).then(async()=>{h=await h,f=h.auditStore,Ct=h.tableById.map(He),ht=[];for(let{name:ft,startTime:kr,endTime:fr}of pn){let zt=yT(ft,f);le.debug?.("subscription to",ft,"using local id",zt,"starting",kr),ht[zt]={startTime:kr,endTime:fr}}K(u),Ga||(Ga=$l(ft=>{ft.databaseName===u&&K(u)}),l_=sh(ft=>{ft===u&&(e.send((0,at.encode)([Ph])),Fr())}),e.on("close",()=>{Ga?.remove(),l_?.remove()})),e.send((0,at.encode)([Y1,yh(h.auditStore),pn.map(({name:ft})=>ft)]));let De=!0;do{if(isFinite(Ot)||(le.warn?.("Invalid sequence id "+Ot),Fr(1008,"Invalid sequence id"+Ot)),De&&!Ce&&(De=!1,Ot===0)){le.info?.("Replicating all tables to",_);let ft=Date.now(),kr=kT(f);for(let fr in E){if(!He(fr))continue;let zt=E[fr];for(let yt of zt.primaryStore.getRange({snapshot:!1,versions:!0})){if(Ce)return;le.trace?.(s,"Copying record from",u,fr,yt.key,yt.localTime),ft=Math.max(yt.localTime??1,ft),Ps()[Lh]=1;let xu=pl(yt.version,zt.tableId,yt.key,null,kr,null,"put",jm(()=>zt.primaryStore.encoder.encode(yt.value),si=>qa(si,yt.key)),yt.metadataFlags&-256,yt.residencyId,null,yt.expiresAt);await p_({recordId:yt.key,tableId:zt.tableId,type:"put",getValue(){return yt.value},encoded:xu,version:yt.version,residencyId:yt.residencyId,nodeId:kr,extendedType:yt.metadataFlags},yt.localTime)}}Te.txnTime||(Te.txnTime=ft,O(ft)),c-i>8&&p_({type:"end_txn"},Ot),Ps()[Lh]=0,Ot=ft}for(let{key:ft,value:kr}of f.getRange({start:Ot||1,exclusiveStart:!0,snapshot:!1})){if(Ce)return;let fr=It(kr);le.debug?.("sending audit record",ft,fr.recordId),Ps()[Lh]=ft,Ot=ft,await p_(fr,ft),Dn.startTime=ft}c-i>8&&p_({type:"end_txn"},Ot),Ps()[Lh]=0,await MB(f)}while(!Ce)}).catch(De=>{le.error?.(s,"Error handling subscription to node",De),Fr(1008,"Error handling subscription to node")});break}}return}U.position=8;let N=!0,L,$;do{Ps();let W=U.readInt();if(W===9&&U.getUint8(U.position)==hg){U.position++,y=$=U.readFloat64(),m[MT]=y,m[UT]=Date.now(),m[xT]=OO,h.send({type:"end_txn",localTime:y,remoteNodeIds:S}),le.trace?.("received remote sequence update",y,u);break}let Q=U.position,F=It(A,Q,Q+W),he=lm[F.tableId];he||le.error?.(`No table found with an id of ${F.tableId}`);let ue;F.residencyId&&(ue=jb[F.residencyId],le.trace?.(s,"received residency list",ue,F.type,F.recordId));let _e=F.recordId;try{sg(()=>{L={table:he.name,id:F.recordId,type:F.type,nodeId:Br.get(F.nodeId),residencyList:ue,timestamp:F.version,value:F.getValue(he),user:F.user,beginTxn:N,expiresAt:F.expiresAt}},f?.rootStore,re=>$a(re,_e))}catch(re){throw re.message+=" record id: "+_e,re.message+=" typed structures for current decoder"+JSON.stringify(he.decoder.typedStructs),re.message+=" structures for current decoder"+JSON.stringify(he.decoder.structures),re}N=!1,le.debug?.(s,"received replication message",F.type,"id",L.id,"version",new Date(F.version),"nodeId",L.nodeId),m[MT]=F.version,m[UT]=Date.now(),m[xT]=dK,h.send(L),U.position=Q+W}while(U.position<A.byteLength);Ls++,u!=="system"&&We(A.byteLength,"bytes-received",`${_}.${u}.${L?.table||"unknown_table"}`,"replication","ingest"),Ls>Du&&!fm&&(fm=!0,e.pause(),le.debug?.(`Commit backlog causing replication back-pressure, requesting that ${_} pause replication`)),h.send({type:"end_txn",localTime:y,remoteNodeIds:S,async onCommit(){if(L){let W=Date.now()-L.timestamp;u!=="system"&&We(W,"replication-latency",_+"."+u+"."+L.table,L.type,"ingest")}Ls--,fm&&(fm=!1,e.resume(),le.debug?.(`Replication resuming ${_}`)),Ke.length>0&&await Promise.all(Ke),le.trace?.("All blobs finished"),!w&&$&&(le.trace?.(s,"queuing confirmation of a commit at",$),setTimeout(()=>{e.send((0,at.encode)([Q1,w])),le.trace?.(s,"sent confirmation of a commit at",w),w=null},Hde)),w=$,le.debug?.("last sequence committed",new Date($),u)}})}catch(U){le.error?.(s,"Error handling incoming replication message",U)}}a(mm,"onWSMessage"),e.on("ping",nr),e.on("pong",()=>{if(t.connection){let A=performance.now()-X;t.connection.latency=A,Ps()&&(m[BT]=A),t.isSubscriptionConnection&&Ql({name:_,database:u,url:t.url,latency:A})}X=null}),e.on("close",(A,U)=>{clearInterval(I),clearTimeout(H),clearInterval(k),Dn&&Dn.emit("close"),Fo&&Fo.end();for(let[N,{reject:L}]of R)L(new Error(`Connection closed ${U?.toString()} ${A}`));le.debug?.(s,"closed",A,U?.toString())});function Fr(A,U){try{e.isFinished=!0,le.debug?.(s,"closing",_,u,A,U),e.close(A,U),t.connection?.emit("finished")}catch(N){le.error?.(s,"Error closing connection",N)}}a(Fr,"close");let Mu=new Set;async function qa(A,U){let N=rg(A);if(Mu.has(N)){le.debug?.("Blob already being sent",N);return}Mu.add(N);try{let L;$e++;for await(let $ of A.stream())L&&(le.debug?.("Sending blob chunk",N,"length",L.length),e.send((0,at.encode)([DT,{fileId:N,size:A.size},L]))),L=$,e._socket.writableNeedDrain&&(le.debug?.("draining",N),await new Promise(W=>e._socket.once("drain",W)),le.debug?.("drained",N)),We($.length,"bytes-sent",`${_}.${u}`,"replication","blob");le.debug?.("Sending final blob chunk",N,"length",L.length),e.send((0,at.encode)([DT,{fileId:N,size:A.size,finished:!0},L]))}catch(L){le.warn?.("Error sending blob",L,"blob id",N,"for record",U),e.send((0,at.encode)([DT,{fileId:N,finished:!0,error:AO(L)},Buffer.alloc(0)]))}finally{Mu.delete(N),$e--,$e<Gi&&Ir?.()}}a(qa,"sendBlobs");function $a(A,U){let N=rg(A),L=Ne.get(N);le.debug?.("Received transaction with blob",N,"has stream",!!L,"ended",!!L?.writableEnded),L?L.writableEnded&&Ne.delete(N):(L=new NO.PassThrough,Ne.set(N,L)),L.connectedToBlob=!0,L.lastChunk=Date.now(),L.recordId=U,A.size===void 0&&L.expectedSize&&(A.size=L.expectedSize);let $=L.blob??createBlob(L,A);L.blob=$;let W=jo(()=>Wm($).saving,h.auditStore?.rootStore);return W&&(W.blobId=N,Ke.push(W),W.finally(()=>{le.debug?.(`Finished receiving blob stream ${N}`),Ke.splice(Ke.indexOf(W),1)})),$}a($a,"receiveBlobs");function pm(){if(p||(p=!0,t.connection?.on("subscriptions-updated",pm)),!f&&h&&(f=h.auditStore),t.connection?.isFinished)throw new Error("Can not make a subscription request on a connection that is already closed");let A=new Map;f||(f=h?.auditStore);try{for(let L of h?.dbisDB?.getRange({start:Symbol.for("seq"),end:[Symbol.for("seq"),Buffer.from([255])]})||[])for(let $ of L.value.nodes||[])$.lastTxnTime>(A.get($.id)??0)&&A.set($.id,$.lastTxnTime)}catch(L){if(!L.message.includes("Can not re"))throw L}let U=t.connection?.nodeSubscriptions?.[0];S=[];let N=t.connection?.nodeSubscriptions.map((L,$)=>{let W=[],{replicateByDefault:Q}=L;if(L.subscriptions){for(let _e of L.subscriptions)if(_e.subscribe&&(_e.schema||_e.database)===u){let re=_e.table;E?.[re]?.replicate!==!1&&W.push(re)}Q=!1}else for(let _e in E)(Q?E[_e].replicate===!1:E[_e].replicate)&&W.push(_e);let F=f&&yT(L.name,f),he=h?.dbisDB?.get([Symbol.for("seq"),F])??1,ue=Math.max(he?.seqId??1,(typeof L.startTime=="string"?new Date(L.startTime).getTime():L.startTime)??1);if(le.debug?.("Starting time recorded in db",L.name,F,u,he?.seqId,"start time:",ue,new Date(ue)),U!==L){let _e=f&&yT(U.name,f),re=h?.dbisDB?.get([Symbol.for("seq"),_e])??1;for(let oe of re?.nodes||[])oe.name===L.name&&(ue=oe.seqId,le.debug?.("Using sequence id from proxy node",U.name,ue))}return F===void 0?le.warn("Starting subscription request from node",L,"but no node id found"):S.push(F),A.get(F)>ue&&(ue=A.get(F),le.debug?.("Updating start time from more recent txn recorded",U.name,ue)),ue===1&&(L.isLeader?(le.warn?.(`Requesting full copy of database ${u} from ${L.url}`),ue=0):ue=Date.now()-6e4),le.trace?.(s,"defining subscription request",L.name,u,new Date(ue)),{name:L.name,replicateByDefault:Q,tables:W,startTime:ue,isLeader:L.isLeader,endTime:L.endTime}});if(N)if(le.debug?.(s,"sending subscription request",N,h?.dbisDB?.path),clearTimeout(Y),N.length>0)e.send((0,at.encode)([V1,N]));else{let L=a(()=>{let $=performance.now();Y=setTimeout(()=>{ce<=$?Fr(1008,"Connection has no subscriptions and is no longer used"):L()},z).unref()},"scheduleClose");L()}}a(pm,"sendSubscriptionRequestUpdate");function f_(A,U){if(!A)return;let N=ve[A];return N||(N=U.getResidencyRecord(A),ve[A]=N),N}a(f_,"getResidence");function Va(A){return!(Rc&&Rc!="*"&&!Rc[A]&&!Rc.includes?.(A)&&!Rc.some?.(U=>U.name===A))}a(Va,"checkDatabaseAccess");function Jc(A){if(h=h||d.get(A),!Va(A))throw new Error(`Access to database "${A}" is not permitted`);h||le.warn?.(`No database named "${A}" was declared and registered`),f=h?.auditStore,E||(E=lt()?.[A]);let U=nt();if(U===_)throw U?new Error("Should not connect to self",U):new Error("Node name not defined");return Uu(U,A),!0}a(Jc,"setDatabase");function Uu(A,U){let N=lt()?.[U],L=[];for(let $ in N){let W=N[$];L.push({table:$,schemaDefined:W.schemaDefined,attributes:W.attributes.map(Q=>({name:Q.name,type:Q.type,isPrimaryKey:Q.isPrimaryKey}))})}le.trace?.("Sending database info for node",A,"database name",U),e.send((0,at.encode)([K1,A,U,L]))}a(Uu,"sendNodeDBName");function K(A){let U=lt()?.[A],N=[];for(let L in U){if(pn&&!pn.some(W=>W.replicateByDefault?!W.tables.includes(L):W.tables.includes(L)))continue;let $=U[L];N.push({table:L,schemaDefined:$.schemaDefined,attributes:$.attributes.map(W=>({name:W.name,type:W.type,isPrimaryKey:W.isPrimaryKey}))})}e.send((0,at.encode)([J1,N,A]))}a(K,"sendDBSchema"),k=setInterval(()=>{for(let[A,U]of Ne)U.lastChunk+Se<Date.now()&&(le.warn?.(`Timeout waiting for blob stream to finish ${A} for record ${U.recordId??"unknown"} from ${_}`),Ne.delete(A),U.end())},Se).unref();let g=1,T=[];return{end(){Fo&&Fo.end(),Dn&&Dn.emit("close")},getRecord(A){let U=g++;return new Promise((N,L)=>{let $=[j1,U,A.table.tableId,A.id];T[A.table.tableId]||($.push(A.table.tableName),T[A.table.tableId]=!0),e.send((0,at.encode)($)),ce=performance.now(),R.set(U,{tableId:A.table.tableId,key:A.id,resolve(W){let{table:Q,entry:F}=A;if(N(W),W)return Q._recordRelocate(F,W)},reject:L})})},sendOperation(A){let U=g++;return A.requestId=U,e.send((0,at.encode)([CO,A])),new Promise((N,L)=>{R.set(U,{resolve:N,reject:L})})}};function C(A){B(5),A<128?o[c++]=A:A<16384?(l.setUint16(c,A|32768),c+=2):A<1056964608?(l.setUint32(c,A|3221225472),c+=4):(o[c]=255,l.setUint32(c+1,A),c+=5)}function P(A,U=0,N=A.length){let L=N-U;B(L),A.copy(o,c,U,N),c+=L}function O(A){B(8),l.setFloat64(c,A),c+=8}function B(A){if(A+16>o.length-c){let U=Buffer.allocUnsafeSlow(c+A-i+65536>>10<<11);o.copy(U,0,i,c),c=c-i,i=0,o=U,l=new DataView(o.buffer,0,o.length)}}function v(A,U){let N=A.database??"data";U||(U={});let L=U.schemaDefined,$=!1,W=A.schemaDefined,Q=U.attributes||[];for(let F=0;F<A.attributes?.length;F++){let he=A.attributes[F],ue=Q.find(_e=>_e.name===he.name);(!ue||ue.type!==he.type)&&(L?le.error?.(`Schema for '${u}.${A.table}' is defined locally, but attribute '${he.name}: ${he.type}' from '${_}' does not match local attribute ${ue?"'"+ue.name+": "+ue.type+"'":"which does not exist"}`):($=!0,W||(he.indexed=!0),ue?Q[Q.indexOf(ue)]=he:Q.push(he)))}return $?(le.debug?.("(Re)creating",A),ze({table:A.table,database:A.database,schemaDefined:A.schemaDefined,attributes:Q,...U})):U}}var tK,at,rK,nK,sK,PO,iK,oK,LO,aK,NO,cK,kde,AO,le,V1,K1,Y1,Ph,W1,IO,j1,PT,CO,LT,z1,Q1,J1,DT,lK,MT,UT,Lh,BT,xT,uK,OO,dK,DO,bc,vT,X1,Hde,Z1,wO,cf,eK,lf,vO=se(()=>{Oe();Vi();uO();FI();gs();tK=b(fe());G();hl();at=require("msgpackr"),rK=require("ws"),nK=require("worker_threads"),sK=b(J());Nh();PO=require("events"),iK=b(Ts()),oK=b(require("node:tls"));rf();LO=b(require("node:process")),aK=require("node:net");os();is();NO=require("node:stream"),cK=require("lmdb"),{forComponent:kde,errorToString:AO}=sK.default,le=kde("replication").conditional,V1=129,K1=140,Y1=141,Ph=142,W1=130,IO=132,j1=133,PT=134,CO=136,LT=137,z1=143,Q1=144,J1=145,DT=146,lK=0,MT=1,UT=2,Lh=3,BT=4,xT=5,uK=6,OO=0,dK=1,DO=new Map,bc=new Map,vT=!0,X1=300,Hde=2,Z1=3e4;a(FT,"createWebSocket");eK=500,lf=class extends PO.EventEmitter{static{a(this,"NodeReplicationConnection")}socket;startTime;retryTime=eK;retries=0;isConnected=!0;isFinished=!1;nodeSubscriptions;latency=0;replicateTablesByDefault;session;sessionResolve;sessionReject;url;subscription;databaseName;nodeName;authorization;constructor(t,r,n,s,i){super(),this.url=t,this.subscription=r,this.databaseName=n,this.authorization=i,this.nodeName=this.nodeName??yi(t)}async connect(){this.session||this.resetSession();let t=[];this.socket=await FT(this.url,{serverName:this.nodeName,authorization:this.authorization});let r;le.debug?.(`Connecting to ${this.url}, db: ${this.databaseName}, process ${LO.pid}`),this.socket.on("open",()=>{this.socket._socket.unref(),le[this.isConnected?"info":"warn"]?.(`Connected to ${this.url}, db: ${this.databaseName}`),this.retries=0,this.retryTime=eK,this.nodeSubscriptions&&Ql({name:this.nodeName,database:this.databaseName,url:this.url}),this.isConnected=!0,r=Dh(this.socket,{database:this.databaseName,subscription:this.subscription,url:this.url,connection:this,isSubscriptionConnection:this.nodeSubscriptions!==void 0},{replicates:!0}),this.sessionResolve(r)}),this.socket.on("error",n=>{n.code==="SELF_SIGNED_CERT_IN_CHAIN"?(le.warn?.(`Can not connect to ${this.url}, this server does not have a certificate authority for the certificate provided by ${this.url}`),n.isHandled=!0):n.code!=="ECONNREFUSED"&&(n.code==="UNABLE_TO_VERIFY_LEAF_SIGNATURE"?le.error?.(`Can not connect to ${this.url}, the certificate provided by ${this.url} is not trusted, this node needs to be added to the cluster, or a certificate authority needs to be added`):le.error?.(`Error in connection to ${this.url} due to ${n.message}`)),this.sessionReject(n)}),this.socket.on("close",(n,s)=>{if(this.isConnected&&(this.nodeSubscriptions&&sf({name:this.nodeName,database:this.databaseName,url:this.url,finished:this.socket.isFinished}),this.isConnected=!1),this.removeAllListeners("subscriptions-updated"),this.socket.isFinished){this.isFinished=!0,r?.end(),this.emit("finished");return}if(++this.retries%20===1){let i=s?.toString();le.warn?.(`${r?"Disconnected from":"Failed to connect to"} ${this.url} (db: "${this.databaseName}"), due to ${i?'"'+i+'" ':""}(code: ${n})`)}r=null,this.resetSession(),setTimeout(()=>{this.connect()},this.retryTime).unref(),this.retryTime+=this.retryTime>>8})}resetSession(){this.session=new Promise((t,r)=>{this.sessionResolve=t,this.sessionReject=r})}subscribe(t,r){this.nodeSubscriptions=t,this.replicateTablesByDefault=r,this.emit("subscriptions-updated",t)}unsubscribe(){this.socket.isFinished=!0,this.socket.close(1008,"No longer subscribed")}getRecord(t){return this.session.then(r=>r.getRecord(t))}};a(Dh,"replicateOverWS")});function Ac(e,t){let r=e.toString("base64"),n=[`-----BEGIN ${t}-----`];for(let s=0;s<r.length;s+=64)n.push(r.substring(s,s+64));return n.push(`-----END ${t}-----`),n.join(`
18
+ `+Jl.get(_.issuer)),!h||!E)throw new Error("Missing private key or certificate for secure server");let R={ciphers:f.ciphers,ticketKeys:Ade(),availableCAs:Jl,ca:t&&Array.from(Jl.values()),cert:E,key:h,key_file:f.private_key_name,is_self_signed:f.is_self_signed};o&&(R.sessionIdContext=o.sessionIdContext);let S=f.hostnames??bO(_);Array.isArray(S)||(S=[S]);for(let I of S)I===pO()&&(p+=1);let y=wT.createSecureContext(R);y.name=f.name,y.options=R,y.quality=p,y.certificateAuthorities=Array.from(Jl),y.certStart=E.toString().slice(0,100);let w;for(let I of S)if(I){I[0]==="*"&&(s=!0,I=I.slice(1)),C1.isIP(I)&&(w=!0);let H=r.get(I)?.quality??0;Xe.trace?.("Assigning TLS for hostname",I,"if",p,">",H),p>H&&r.set(I,y)}else Xe.error?.("No hostname found for certificate at",wT.certificate);Xe.trace?.("Adding TLS",y.name,"for",o.ports||"client","cert named",f.name,"hostnames",S,"quality",p,"best quality",d),p>d&&(i.defaultContext=n=y,d=p,o&&(o.defaultContext=y))}catch(m){Xe.error?.("Error applying TLS for",f.name,m)}o?.secureContextsListeners.forEach(f=>f()),c(n)}catch(d){l(d)}}a(u,"updateTLS"),IT?.system.hdb_certificate.subscribe({listener:a(()=>setTimeout(()=>u(),1500).unref(),"listener"),omitCurrent:!0}),u()})),i;function i(o,c){Xe.info?.("TLS requested for",o||"(no SNI)");let l=o;for(;;){let d=r.get(l);if(d)return Xe.debug?.("Found certificate for",o,d.certStart),d.updatedContext&&(d=d.updatedContext),c(null,d);if(s&&l){let f=l.indexOf(".",1);f<0?l="":l=l.slice(f)}else break}o?Xe.debug?.("No certificate found to match",o,"using the default certificate"):Xe.debug?.("No SNI, using the default certificate",n?.name);let u=n;u?u.updatedContext&&(u=u.updatedContext):Xe.info?.("No default certificate found"),c(null,u)}a(i,"SNICallback")}a(G1,"createTLSSelector");async function q1(e){let t=Tc.get(e);return!t&&e?await Yn.readFile(gr.join(Ss.get(Xl.ROOTPATH),Vs.LICENSE_KEY_DIR_NAME,e),"utf8"):t}a(q1,"getPrivateKeyByName");async function $1(){yc();let e=[];for await(let t of an.search([]))e.push(t);return e}a($1,"listCertificates");async function Mde(e){let t=EO(e,Ri.object({name:Ri.string().required(),certificate:Ri.string().required(),is_authority:Ri.boolean().required(),private_key:Ri.string(),hosts:Ri.array(),uses:Ri.array()}));if(t)throw new Sc(t.message);let{name:r,certificate:n,private_key:s,is_authority:i}=e,o=new ca(n),c=!1,l=!1,u;for(let[p,h]of Tc)!s&&!c&&o.checkPrivateKey(O1(h))&&(c=!0,u=p),s&&s===h&&(l=!0,u=p);if(!i&&!s&&!c)throw new Sc("A suitable private key was not found for this certificate");let d;if(!r){try{d=RO(o)}catch(p){Xe.error?.(p)}if(d==null)throw new Sc("Error extracting certificate host name, please provide a name parameter")}let f=Ude(r??d);s&&!c&&!l&&(await Yn.writeFile(gr.join(Ss.getHdbBasePath(),Vs.LICENSE_KEY_DIR_NAME,f+".pem"),s),Tc.set(f,s));let m={name:r??d,certificate:n,is_authority:i,hosts:e.hosts,uses:e.uses};return(!i||i&&u||i&&s)&&(m.private_key_name=u??f+".pem"),e.ciphers&&(m.ciphers=e.ciphers),await af(m),"Successfully added certificate: "+f}a(Mde,"addCertificate");function Ude(e){return e.replace(/[^a-z0-9\.]/gi,"-")}a(Ude,"sanitizeName");async function xde(e){let t=EO(e,Ri.object({name:Ri.string().required()}));if(t)throw new Sc(t.message);let{name:r}=e;yc();let n=await an.get(r);if(!n)throw new Sc(r+" not found");let{private_key_name:s}=n;if(s){let i=Array.from(await an.search([{attribute:"private_key_name",value:s}]));i.length===1&&i[0].name===r&&(Xe.info?.("Removing private key named",s),await Yn.remove(gr.join(Ss.getHdbBasePath(),Vs.LICENSE_KEY_DIR_NAME,s)))}return await an.delete(r),"Successfully removed "+r}a(xde,"removeCertificate");function RO(e){let t=e.subject?.match(/CN=(.*)/)?.[1];return t||bO(e)[0]}a(RO,"getPrimaryHostName");function bO(e){if(e.subjectAltName)return e.subjectAltName.split(",").map(r=>{let n=r.indexOf(":");if(r=r.slice(n+1),r=r.trim(),r[0]==='"')try{r=JSON.parse(r)}catch{}return r.indexOf("=")>-1?r.match(/CN=([^,]*)/)?.[1]:r}).filter(r=>r);let t=e.subject?.match(/CN=(.*)/)?.[1];return t?[t]:[]}a(bO,"hostnamesFromCert");async function Bde(e){if(e.bypass_auth!==!0)throw new Sc("Unauthorized","401");let t=EO(e,Ri.object({name:Ri.string().required()}));if(t)throw new Sc(t.message);let{name:r}=e;if(r===".jwtPrivate")return(await A1()).privateKey;if(r===".jwtPublic")return(await A1()).publicKey;if(Tc.get(r))return Tc.get(e.name);throw new Sc("Key not found")}a(Bde,"getKey");function Fde(e){return[e.subject?.CN,...e.subjectaltname.split(",").filter(t=>t.trim().startsWith("DNS:")).map(t=>t.trim().substring(4))]}a(Fde,"getHostnamesFromCertificate")});var fK={};ye(fK,{BACK_PRESSURE_RATIO_POSITION:()=>uK,CONFIRMATION_STATUS_POSITION:()=>lK,LATENCY_POSITION:()=>BT,NodeReplicationConnection:()=>lf,OPERATION_REQUEST:()=>CO,RECEIVED_TIME_POSITION:()=>UT,RECEIVED_VERSION_POSITION:()=>MT,RECEIVING_STATUS_POSITION:()=>xT,RECEIVING_STATUS_RECEIVING:()=>dK,RECEIVING_STATUS_WAITING:()=>OO,SENDING_TIME_POSITION:()=>Lh,createWebSocket:()=>FT,databaseSubscriptions:()=>bc,replicateOverWS:()=>Dh,tableUpdateListeners:()=>DO});async function FT(e,t){let{authorization:r,rejectUnauthorized:n}=t||{},s=nt(),i;if(e==null)throw new TypeError(`Invalid URL: Expected a string URL for node "${s}" but received ${e}`);if(e.includes("wss://")){if(!wO){let l=(0,iK.createTLSSelector)("operations-api"),u={secureContexts:null};await l.initialize(u),wO=u.secureContexts}if(i=wO.get(s),i&&le.debug?.("Creating web socket for URL",e,"with certificate named:",i.name),!i&&n!==!1)throw new Error("Unable to find a valid certificate to use for replication to connect to "+e)}let o={};r&&(o.Authorization=r);let c={headers:o,localAddress:s?.startsWith("127.0")?s:void 0,servername:(0,aK.isIP)(t?.serverName)?void 0:t?.serverName,noDelay:!0,highWaterMark:128*1024,rejectUnauthorized:n!==!1,secureContext:void 0};return i&&((cf?.caCount!==ua.size||cf?.derivedFromContext!==i)&&(cf=oK.createSecureContext({...i.options,ca:[...ua,...i.options.availableCAs.values()]}),cf.caCount=ua.size,cf.derivedFromContext=i),c.secureContext=cf),new rK.WebSocket(e,"harperdb-replication-v1",c)}function Dh(e,t,r){let n=t.port||t.securePort,s=LO.pid%1e3+"-"+nK.threadId+(n?"s:"+n:"c:"+t.url?.slice(-4))+" "+Math.random().toString().slice(2,3);le.debug?.(s,"Initializing replication connection",r);let i=0,o=Buffer.allocUnsafeSlow(1024),c=0,l=new DataView(o.buffer,0,1024),u=t.database,d=t.databaseSubscriptions||bc,f,m,p=!1,h=t.subscription;h?.then&&h.then(A=>{h=A,h.auditStore&&(f=h.auditStore)});let E=t.tables||u&&lt()[u],_,R=new Map,S=[];_=r.name,_&&t.connection&&(t.connection.nodeName=_);let y,w,I,H,X,q,k,z=6e4,Y,ce=0,de=0,te=0,Se=tK.default.get(x.REPLICATION_BLOBTIMEOUT)??12e4,Ne=new Map,Ke=[],$e=0,Ir;if(t.url){let A=a(()=>{X&&de===e._socket?.bytesRead&&te===e._socket?.bytesWritten?e.terminate():(X=performance.now(),e.ping(),de=e._socket?.bytesRead,te=e._socket?.bytesWritten)},"sendPing");I=setInterval(A,Z1).unref(),A()}else nr();e._socket?.setMaxListeners(200);function nr(){clearTimeout(H),de=e._socket?.bytesRead,te=e._socket?.bytesWritten,H=setTimeout(()=>{de===e._socket?.bytesRead&&te===e._socket?.bytesWritten&&(le.warn?.(`Timeout waiting for ping from ${_}, terminating connection and reconnecting`),e.terminate())},Z1*2).unref()}a(nr,"resetPingTimer");let zr=0,xr=0,Lu=!1,Qc=3e4;function Ft(){if(pn?.length>0){let A=performance.now(),U=A-xr;zr=(zr*Qc+(Lu?U:0))/(Qc+U),m&&(m[uK]=zr),xr=A}}a(Ft,"updateBackPressureRatio"),setInterval(Ft,Qc).unref();function Ps(){if(!(!_||!u))return m||(m=ef(f,u,_)),m}a(Ps,"getSharedStatus"),u&&Jc(u);let Ga,l_,lm=[],u_=[],um,ve=[],d_=[],jb=[],Du=150,Gi=25,Ls=0,dm=0,fm=!1,Fo,Dn,pn,Br;e.on("message",vu);async function vu(A){if(r=await r,!r){le.error?.(s,"No authorization provided"),Fr(1008,"Unauthorized");return}mm(A),e.off("message",vu),e.on("message",mm)}a(vu,"onWSMessageWhenAuthorized");function mm(A){ce=performance.now();try{let U=A.dataView=new dl(A.buffer,A.byteOffset,A.byteLength);if(A[0]>127){let W=(0,at.decode)(A),[Q,F,he]=W;switch(Q){case K1:{if(F){if(_){if(_!==F){le.error?.(s,`Node name mismatch, expecting to connect to ${_}, but peer reported name as ${F}, disconnecting`),e.send((0,at.encode)([Ph])),Fr(1008,"Node name mismatch");return}}else if(_=F,t.connection?.tentativeNode){let me=t.connection.tentativeNode;me.name=_,t.connection.tentativeNode=null,aa(_,me)}if(t.connection&&(t.connection.nodeName=_),le.debug?.(s,"received node name:",_,"db:",u??W[2]),!u)try{Jc(u=W[2]),u==="system"&&(Ga=_c(t,(me,ie)=>{Va(ie)&&K(ie)}),e.on("close",()=>{Ga?.remove()}))}catch(me){le.warn?.(s,"Error setting database",me),e.send((0,at.encode)([Ph])),Fr(1008,me.message);return}pm()}break}case J1:{le.debug?.(s,"Received table definitions for",F.map(me=>me.table));for(let me of F){let ie=W[2];me.database=ie;let Ce;if(Va(ie)){if(u==="system")Me[ie]?.[me.table]||(Ce=v(me,Me[ie]?.[me.table]));else{if(ie!=="data"&&!Me[ie]){le.warn?.("Database not found",ie);return}Ce=v(me,Me[ie]?.[me.table])}f||(f=Ce?.auditStore),E||(E=lt()?.[ie])}}break}case Ph:Fr();break;case CO:try{let me=r?.replicates||r?.subscribers||r?.name;le.debug?.("Received operation request",F,"from",_),server.operation(F,{user:r},!me).then(ie=>{le.debug?.("Requested request from finished",_,ie),Array.isArray(ie)&&(ie={results:ie}),ie.requestId=F.requestId,e.send((0,at.encode)([LT,ie]))},ie=>{le.debug?.("Failed requested operation from",_,ie),e.send((0,at.encode)([LT,{requestId:F.requestId,error:AO(ie)}]))})}catch(me){e.send((0,at.encode)([LT,{requestId:F.requestId,error:AO(me)}]))}break;case LT:let{resolve:ue,reject:_e}=R.get(F.requestId);le.debug?.("Received completed operation request",_,F),F.error?_e(new Error(F.error)):ue(F),R.delete(F.requestId);break;case IO:let re=W[3];if(!E){u?le.error?.(s,"No database found for",u):le.error?.(s,"Database name never received"),Fr();return}let oe=E[re];oe=v({table:re,database:u,attributes:F.attributes,schemaDefined:F.schemaDefined},oe),lm[he]={name:re,decoder:new at.Packr({useBigIntExtension:!0,randomAccessStructure:!0,freezeData:!0,typedStructs:F.typedStructs,structures:F.structures}),getEntry(me){return oe.primaryStore.getEntry(me)},rootStore:oe.primaryStore.rootStore};break;case Y1:Br=f?l1(F,f):new Map,um=W[2],le.debug?.(s,`Acknowledged subscription request, receiving messages for nodes: ${um}`);break;case W1:let ge=he;jb[ge]=F;break;case Q1:Ps()[lK]=F,le.trace?.(s,"received and broadcasting committed update",F),Ps().buffer.notify();break;case z1:y=F,h.send({type:"end_txn",localTime:y,remoteNodeIds:S}),Ps(),m[MT]=last_sequence_id_received,m[UT]=Date.now(),m[xT]=OO;break;case DT:{let me=W[1],{fileId:ie,size:Ce,finished:Be,error:He}=me,Te=Ne.get(ie);le.debug?.("Received blob",ie,"has stream",!!Te,"connectedToBlob",!!Te?.connectedToBlob,"length",W[2].length,"finished",Be),Te||(Te=new NO.PassThrough,Te.expectedSize=Ce,Ne.set(ie,Te)),Te.lastChunk=Date.now();let ht=W[2];We(ht.byteLength,"bytes-received",`${_}.${u}`,"replication","blob");try{Be?(He?(Te.on("error",()=>{}),Te.destroy(new Error("Blob error: "+He+" for record "+(Te.recordId??"unknown")+" from "+_))):Te.end(ht),Te.connectedToBlob&&Ne.delete(ie)):Te.write(ht)}catch(Ct){le.error?.(`Error receiving blob for ${Te.recordId} from ${_} and streaming to storage`,Ct),Ne.delete(ie)}break}case j1:{let me=F,ie;try{let Ce=W[3],Be=u_[he]||(u_[he]=E[W[4]]);if(!Be)return le.warn?.("Unknown table id trying to handle record request",he);let He=Be.primaryStore.getBinaryFast(Symbol.for("structures")),Te=He?.length??0;if(Te>0&&Te!==dm){dm=Te;let Ct=(0,at.decode)(He);e.send((0,at.encode)([IO,{typedStructs:Ct.typed,structures:Ct.named},he,Be.tableName]))}let ht=Be.primaryStore.getBinaryFast(Ce);if(ht){let Ct=Be.primaryStore.decoder.decode(ht,{valueAsBuffer:!0}),Ot=ut||{};Ot.version=(0,cK.getLastVersion)(),ut&&ut[Xu]&Zr&&(Ct=Buffer.from(Ct),jm(()=>Be.primaryStore.decoder.decode(ht),m_=>qa(m_,Ce),Be.primaryStore.rootStore)),ie=(0,at.encode)([PT,me,{value:Ct,expiresAt:Ot.expiresAt,version:Ot.version,residencyId:Ot.residencyId,nodeId:Ot.nodeId,user:Ot.user}])}else ie=(0,at.encode)([PT,me])}catch(Ce){ie=(0,at.encode)([PT,me,{error:Ce.message}])}e.send(ie);break}case PT:{let{resolve:me,reject:ie,tableId:Ce,key:Be}=R.get(W[1]),He=W[2];if(He?.error)ie(new Error(He.error));else if(He){let Te;sg(()=>{let ht=lm[Ce].decoder.decode(He.value);He.value=ht,He.key=Be,me(He)||Te&&setTimeout(()=>Te.forEach(tg),6e4).unref()},f?.rootStore,ht=>{let Ct=$a(ht,Be);return Te||(Te=[]),Te.push(Ct),Ct})}else me();R.delete(W[1]);break}case V1:{pn=F;let me,ie,Ce=!1;if(h){if(u!==h.databaseName&&!h.then){le.error?.("Subscription request for wrong database",u,h.databaseName);return}}else h=d.get(u);if(le.debug?.(s,"received subscription request for",u,"at",pn),!h){let De;h=new Promise(ft=>{le.debug?.("Waiting for subscription to database "+u),De=ft}),h.ready=De,bc.set(u,h)}if(r.name)ie=Gt().subscribe(r.name),ie.then(async De=>{me=De;for await(let ft of me){let kr=ft.value;if(!(kr?.replicates===!0||kr?.replicates?.receives||kr?.subscriptions?.some(fr=>(fr.database||fr.schema)===u&&fr.publish!==!1))){Ce=!0,Fr(1008,`Unauthorized database subscription to ${u}`);return}}},De=>{le.error?.(s,"Error subscribing to HDB nodes",De)});else if(!(r?.role?.permission?.super_user||r.replicates)){e.send((0,at.encode)([Ph])),Fr(1008,`Unauthorized database subscription to ${u}`);return}if(Dn&&(le.debug?.(s,"stopping previous subscription",u),Dn.emit("close")),pn.length===0)return;let Be=pn[0],He=a(De=>{if(De&&(Be.replicateByDefault?!Be.tables.includes(De.tableName):Be.tables.includes(De.tableName)))return{table:De}},"tableToTableEntry"),Te={txnTime:0},ht,Ct,Ot=1/0,m_,p_=a((De,ft)=>{if(De.type==="end_txn"){Te.txnTime&&(o[i]!==66&&le.error?.("Invalid encoding of message"),C(9),C(hg),O(m_=ft),iU()),i=c,Te.txnTime=0;return}let kr=De.nodeId,fr=De.tableId,zt=Ct[fr];if(!zt&&(zt=Ct[fr]=He(h.tableById[fr]),!zt))return le.debug?.("Not subscribed to table",fr);let yt=zt.table,xu=yt.primaryStore,si=xu.encoder;(De.extendedType&Ig||!si.typedStructs)&&(si._mergeStructures(si.getStructures()),si.typedStructs&&(si.lastTypedStructuresLength=si.typedStructs.length));let h_=ht[kr];if(!(h_&&h_.startTime<ft&&(!h_.endTime||h_.endTime>ft)))return vT&&le.trace?.(s,"skipping replication update",De.recordId,"to:",_,"from:",kr,"subscribed:",ht),oU();vT&&le.trace?.(s,"sending replication update",De.recordId,"to:",_,"from:",kr,"subscribed:",ht);let zb=De.version,Xc=De.residencyId,Qb=f_(Xc,yt),E_;if(Qb&&!Qb.includes(_)){let qi=f_(De.previousResidencyId,yt);if(qi&&!qi.includes(_)&&(De.type==="put"||De.type==="patch")||yt.getResidencyById)return oU();let Zc=De.recordId;le.trace?.(s,"sending invalidation",Zc,_,"from",kr);let hm=0;Xc&&(hm|=fl),De.previousResidencyId&&(hm|=ml);let Zb,__=null;for(let aU in yt.indices){if(!__){if(Zb=De.getValue(xu,!0),!Zb)break;__={}}__[aU]=Zb[aU]}E_=pl(De.version,fr,Zc,null,kr,De.user,De.type==="put"||De.type==="patch"?"invalidate":De.type,si.encode(__),hm,Xc,De.previousResidencyId,De.expiresAt)}function oU(){return le.trace?.(s,"skipping audit record",De.recordId),q||(q=setTimeout(()=>{q=null,(m_||0)+X1/2<Ot&&(vT&&le.trace?.(s,"sending skipped sequence update",Ot),e.send((0,at.encode)([z1,Ot])))},X1).unref()),new Promise(setImmediate)}a(oU,"skipAuditRecord");let Jb=si.typedStructs,Xb=si.structures;if((Jb?.length!=zt.typed_length||Xb?.length!=zt.structure_length)&&(zt.typed_length=Jb?.length,zt.structure_length=Xb.length,le.debug?.(s,"send table struct",zt.typed_length,zt.structure_length),zt.sentName||(zt.sentName=!0),e.send((0,at.encode)([IO,{typedStructs:Jb,structures:Xb,attributes:yt.attributes,schemaDefined:yt.schemaDefined},fr,zt.table.tableName]))),Xc&&!d_[Xc]&&(e.send((0,at.encode)([W1,Qb,Xc])),d_[Xc]=!0),Te.txnTime!==zb&&(Te.txnTime&&(vT&&le.trace?.(s,"new txn time, sending queued txn",Te.txnTime),o[i]!==66&&le.error?.("Invalid encoding of message"),iU()),Te.txnTime=zb,i=c,O(zb)),E_)C(E_.length),P(E_);else{let qi=De.encoded;De.extendedType&Zr&&jm(()=>De.getValue(xu),hm=>qa(hm,De.recordId),xu.rootStore);let Zc=qi[0]===66?8:0;C(qi.length-Zc),P(qi,Zc),le.trace?.("wrote record",De.recordId,"length:",qi.length)}if(e._socket.writableNeedDrain){let qi=performance.now();return Lu=!0,Ft(),new Promise(Zc=>{le.debug?.(`Waiting for remote node ${_} to allow more commits ${e._socket.writableNeedDrain?"due to network backlog":"due to requested flow directive"}`),e._socket.once("drain",()=>{Zc(),Lu=!1,Ft()})})}else return $e>Gi?new Promise(qi=>{Ir=qi}):new Promise(setImmediate)},"sendAuditRecord"),iU=a(()=>{c-i>8?(e.send(o.subarray(i,c)),le.debug?.(s,"Sent message, size:",c-i),u!=="system"&&We(c-i,"bytes-sent",`${_}.${u}`,"replication","egress")):le.debug?.(s,"skipping empty transaction")},"sendQueuedData");Dn=new PO.EventEmitter,Dn.once("close",()=>{Ce=!0,me?.end()});for(let{startTime:De}of pn)De<Ot&&(Ot=De);(ie||Promise.resolve()).then(async()=>{h=await h,f=h.auditStore,Ct=h.tableById.map(He),ht=[];for(let{name:ft,startTime:kr,endTime:fr}of pn){let zt=yT(ft,f);le.debug?.("subscription to",ft,"using local id",zt,"starting",kr),ht[zt]={startTime:kr,endTime:fr}}K(u),Ga||(Ga=$l(ft=>{ft.databaseName===u&&K(u)}),l_=sh(ft=>{ft===u&&(e.send((0,at.encode)([Ph])),Fr())}),e.on("close",()=>{Ga?.remove(),l_?.remove()})),e.send((0,at.encode)([Y1,yh(h.auditStore),pn.map(({name:ft})=>ft)]));let De=!0;do{if(isFinite(Ot)||(le.warn?.("Invalid sequence id "+Ot),Fr(1008,"Invalid sequence id"+Ot)),De&&!Ce&&(De=!1,Ot===0)){le.info?.("Replicating all tables to",_);let ft=Date.now(),kr=kT(f);for(let fr in E){if(!He(fr))continue;let zt=E[fr];for(let yt of zt.primaryStore.getRange({snapshot:!1,versions:!0})){if(Ce)return;le.trace?.(s,"Copying record from",u,fr,yt.key,yt.localTime),ft=Math.max(yt.localTime??1,ft),Ps()[Lh]=1;let xu=pl(yt.version,zt.tableId,yt.key,null,kr,null,"put",jm(()=>zt.primaryStore.encoder.encode(yt.value),si=>qa(si,yt.key)),yt.metadataFlags&-256,yt.residencyId,null,yt.expiresAt);await p_({recordId:yt.key,tableId:zt.tableId,type:"put",getValue(){return yt.value},encoded:xu,version:yt.version,residencyId:yt.residencyId,nodeId:kr,extendedType:yt.metadataFlags},yt.localTime)}}Te.txnTime||(Te.txnTime=ft,O(ft)),c-i>8&&p_({type:"end_txn"},Ot),Ps()[Lh]=0,Ot=ft}for(let{key:ft,value:kr}of f.getRange({start:Ot||1,exclusiveStart:!0,snapshot:!1})){if(Ce)return;let fr=It(kr);le.debug?.("sending audit record",ft,fr.recordId),Ps()[Lh]=ft,Ot=ft,await p_(fr,ft),Dn.startTime=ft}c-i>8&&p_({type:"end_txn"},Ot),Ps()[Lh]=0,await MB(f)}while(!Ce)}).catch(De=>{le.error?.(s,"Error handling subscription to node",De),Fr(1008,"Error handling subscription to node")});break}}return}U.position=8;let N=!0,L,$;do{Ps();let W=U.readInt();if(W===9&&U.getUint8(U.position)==hg){U.position++,y=$=U.readFloat64(),m[MT]=y,m[UT]=Date.now(),m[xT]=OO,h.send({type:"end_txn",localTime:y,remoteNodeIds:S}),le.trace?.("received remote sequence update",y,u);break}let Q=U.position,F=It(A,Q,Q+W),he=lm[F.tableId];he||le.error?.(`No table found with an id of ${F.tableId}`);let ue;F.residencyId&&(ue=jb[F.residencyId],le.trace?.(s,"received residency list",ue,F.type,F.recordId));let _e=F.recordId;try{sg(()=>{L={table:he.name,id:F.recordId,type:F.type,nodeId:Br.get(F.nodeId),residencyList:ue,timestamp:F.version,value:F.getValue(he),user:F.user,beginTxn:N,expiresAt:F.expiresAt}},f?.rootStore,re=>$a(re,_e))}catch(re){throw re.message+=" record id: "+_e,re.message+=" typed structures for current decoder"+JSON.stringify(he.decoder.typedStructs),re.message+=" structures for current decoder"+JSON.stringify(he.decoder.structures),re}N=!1,le.debug?.(s,"received replication message",F.type,"id",L.id,"version",new Date(F.version),"nodeId",L.nodeId),m[MT]=F.version,m[UT]=Date.now(),m[xT]=dK,h.send(L),U.position=Q+W}while(U.position<A.byteLength);Ls++,u!=="system"&&We(A.byteLength,"bytes-received",`${_}.${u}.${L?.table||"unknown_table"}`,"replication","ingest"),Ls>Du&&!fm&&(fm=!0,e.pause(),le.debug?.(`Commit backlog causing replication back-pressure, requesting that ${_} pause replication`)),h.send({type:"end_txn",localTime:y,remoteNodeIds:S,async onCommit(){if(L){let W=Date.now()-L.timestamp;u!=="system"&&We(W,"replication-latency",_+"."+u+"."+L.table,L.type,"ingest")}Ls--,fm&&(fm=!1,e.resume(),le.debug?.(`Replication resuming ${_}`)),Ke.length>0&&await Promise.all(Ke),le.trace?.("All blobs finished"),!w&&$&&(le.trace?.(s,"queuing confirmation of a commit at",$),setTimeout(()=>{e.send((0,at.encode)([Q1,w])),le.trace?.(s,"sent confirmation of a commit at",w),w=null},Hde)),w=$,le.debug?.("last sequence committed",new Date($),u)}})}catch(U){le.error?.(s,"Error handling incoming replication message",U)}}a(mm,"onWSMessage"),e.on("ping",nr),e.on("pong",()=>{if(t.connection){let A=performance.now()-X;t.connection.latency=A,Ps()&&(m[BT]=A),t.isSubscriptionConnection&&Ql({name:_,database:u,url:t.url,latency:A})}X=null}),e.on("close",(A,U)=>{clearInterval(I),clearTimeout(H),clearInterval(k),Dn&&Dn.emit("close"),Fo&&Fo.end();for(let[N,{reject:L}]of R)L(new Error(`Connection closed ${U?.toString()} ${A}`));le.debug?.(s,"closed",A,U?.toString())});function Fr(A,U){try{e.isFinished=!0,le.debug?.(s,"closing",_,u,A,U),e.close(A,U),t.connection?.emit("finished")}catch(N){le.error?.(s,"Error closing connection",N)}}a(Fr,"close");let Mu=new Set;async function qa(A,U){let N=rg(A);if(Mu.has(N)){le.debug?.("Blob already being sent",N);return}Mu.add(N);try{let L;$e++;for await(let $ of A.stream())L&&(le.debug?.("Sending blob chunk",N,"length",L.length),e.send((0,at.encode)([DT,{fileId:N,size:A.size},L]))),L=$,e._socket.writableNeedDrain&&(le.debug?.("draining",N),await new Promise(W=>e._socket.once("drain",W)),le.debug?.("drained",N)),We($.length,"bytes-sent",`${_}.${u}`,"replication","blob");le.debug?.("Sending final blob chunk",N,"length",L.length),e.send((0,at.encode)([DT,{fileId:N,size:A.size,finished:!0},L]))}catch(L){le.warn?.("Error sending blob",L,"blob id",N,"for record",U),e.send((0,at.encode)([DT,{fileId:N,finished:!0,error:AO(L)},Buffer.alloc(0)]))}finally{Mu.delete(N),$e--,$e<Gi&&Ir?.()}}a(qa,"sendBlobs");function $a(A,U){let N=rg(A),L=Ne.get(N);le.debug?.("Received transaction with blob",N,"has stream",!!L,"ended",!!L?.writableEnded),L?L.writableEnded&&Ne.delete(N):(L=new NO.PassThrough,Ne.set(N,L)),L.connectedToBlob=!0,L.lastChunk=Date.now(),L.recordId=U,A.size===void 0&&L.expectedSize&&(A.size=L.expectedSize);let $=L.blob??createBlob(L,A);L.blob=$;let W=jo(()=>Wm($).saving,h.auditStore?.rootStore);return W&&(W.blobId=N,Ke.push(W),W.finally(()=>{le.debug?.(`Finished receiving blob stream ${N}`),Ke.splice(Ke.indexOf(W),1)})),$}a($a,"receiveBlobs");function pm(){if(p||(p=!0,t.connection?.on("subscriptions-updated",pm)),!f&&h&&(f=h.auditStore),t.connection?.isFinished)throw new Error("Can not make a subscription request on a connection that is already closed");let A=new Map;f||(f=h?.auditStore);try{for(let L of h?.dbisDB?.getRange({start:Symbol.for("seq"),end:[Symbol.for("seq"),Buffer.from([255])]})||[])for(let $ of L.value.nodes||[])$.lastTxnTime>(A.get($.id)??0)&&A.set($.id,$.lastTxnTime)}catch(L){if(!L.message.includes("Can not re"))throw L}let U=t.connection?.nodeSubscriptions?.[0];S=[];let N=t.connection?.nodeSubscriptions.map((L,$)=>{let W=[],{replicateByDefault:Q}=L;if(L.subscriptions){for(let _e of L.subscriptions)if(_e.subscribe&&(_e.schema||_e.database)===u){let re=_e.table;E?.[re]?.replicate!==!1&&W.push(re)}Q=!1}else for(let _e in E)(Q?E[_e].replicate===!1:E[_e].replicate)&&W.push(_e);let F=f&&yT(L.name,f),he=h?.dbisDB?.get([Symbol.for("seq"),F])??1,ue=Math.max(he?.seqId??1,(typeof L.startTime=="string"?new Date(L.startTime).getTime():L.startTime)??1);if(le.debug?.("Starting time recorded in db",L.name,F,u,he?.seqId,"start time:",ue,new Date(ue)),U!==L){let _e=f&&yT(U.name,f),re=h?.dbisDB?.get([Symbol.for("seq"),_e])??1;for(let oe of re?.nodes||[])oe.name===L.name&&(ue=oe.seqId,le.debug?.("Using sequence id from proxy node",U.name,ue))}return F===void 0?le.warn("Starting subscription request from node",L,"but no node id found"):S.push(F),A.get(F)>ue&&(ue=A.get(F),le.debug?.("Updating start time from more recent txn recorded",U.name,ue)),ue===1&&(L.isLeader?(le.warn?.(`Requesting full copy of database ${u} from ${L.url}`),ue=0):ue=Date.now()-6e4),le.trace?.(s,"defining subscription request",L.name,u,new Date(ue)),{name:L.name,replicateByDefault:Q,tables:W,startTime:ue,isLeader:L.isLeader,endTime:L.endTime}});if(N)if(le.debug?.(s,"sending subscription request",N,h?.dbisDB?.path),clearTimeout(Y),N.length>0)e.send((0,at.encode)([V1,N]));else{let L=a(()=>{let $=performance.now();Y=setTimeout(()=>{ce<=$?Fr(1008,"Connection has no subscriptions and is no longer used"):L()},z).unref()},"scheduleClose");L()}}a(pm,"sendSubscriptionRequestUpdate");function f_(A,U){if(!A)return;let N=ve[A];return N||(N=U.getResidencyRecord(A),ve[A]=N),N}a(f_,"getResidence");function Va(A){return!(Rc&&Rc!="*"&&!Rc[A]&&!Rc.includes?.(A)&&!Rc.some?.(U=>U.name===A))}a(Va,"checkDatabaseAccess");function Jc(A){if(h=h||d.get(A),!Va(A))throw new Error(`Access to database "${A}" is not permitted`);h||le.warn?.(`No database named "${A}" was declared and registered`),f=h?.auditStore,E||(E=lt()?.[A]);let U=nt();if(U===_)throw U?new Error("Should not connect to self",U):new Error("Node name not defined");return Uu(U,A),!0}a(Jc,"setDatabase");function Uu(A,U){let N=lt()?.[U],L=[];for(let $ in N){let W=N[$];L.push({table:$,schemaDefined:W.schemaDefined,attributes:W.attributes.map(Q=>({name:Q.name,type:Q.type,isPrimaryKey:Q.isPrimaryKey}))})}le.trace?.("Sending database info for node",A,"database name",U),e.send((0,at.encode)([K1,A,U,L]))}a(Uu,"sendNodeDBName");function K(A){let U=lt()?.[A],N=[];for(let L in U){if(pn&&!pn.some(W=>W.replicateByDefault?!W.tables.includes(L):W.tables.includes(L)))continue;let $=U[L];N.push({table:L,schemaDefined:$.schemaDefined,attributes:$.attributes.map(W=>({name:W.name,type:W.type,isPrimaryKey:W.isPrimaryKey}))})}e.send((0,at.encode)([J1,N,A]))}a(K,"sendDBSchema"),k=setInterval(()=>{for(let[A,U]of Ne)U.lastChunk+Se<Date.now()&&(le.warn?.(`Timeout waiting for blob stream to finish ${A} for record ${U.recordId??"unknown"} from ${_}`),Ne.delete(A),U.end())},Se).unref();let g=1,T=[];return{end(){Fo&&Fo.end(),Dn&&Dn.emit("close")},getRecord(A){let U=g++;return new Promise((N,L)=>{let $=[j1,U,A.table.tableId,A.id];T[A.table.tableId]||($.push(A.table.tableName),T[A.table.tableId]=!0),e.send((0,at.encode)($)),ce=performance.now(),R.set(U,{tableId:A.table.tableId,key:A.id,resolve(W){let{table:Q,entry:F}=A;if(N(W),W)return Q._recordRelocate(F,W)},reject:L})})},sendOperation(A){let U=g++;return A.requestId=U,e.send((0,at.encode)([CO,A])),new Promise((N,L)=>{R.set(U,{resolve:N,reject:L})})}};function C(A){B(5),A<128?o[c++]=A:A<16384?(l.setUint16(c,A|32768),c+=2):A<1056964608?(l.setUint32(c,A|3221225472),c+=4):(o[c]=255,l.setUint32(c+1,A),c+=5)}function P(A,U=0,N=A.length){let L=N-U;B(L),A.copy(o,c,U,N),c+=L}function O(A){B(8),l.setFloat64(c,A),c+=8}function B(A){if(A+16>o.length-c){let U=Buffer.allocUnsafeSlow(c+A-i+65536>>10<<11);o.copy(U,0,i,c),c=c-i,i=0,o=U,l=new DataView(o.buffer,0,o.length)}}function v(A,U){let N=A.database??"data";U||(U={});let L=U.schemaDefined,$=!1,W=A.schemaDefined,Q=U.attributes||[];for(let F=0;F<A.attributes?.length;F++){let he=A.attributes[F],ue=Q.find(_e=>_e.name===he.name);(!ue||ue.type!==he.type)&&(L?le.error?.(`Schema for '${u}.${A.table}' is defined locally, but attribute '${he.name}: ${he.type}' from '${_}' does not match local attribute ${ue?"'"+ue.name+": "+ue.type+"'":"which does not exist"}`):($=!0,W||(he.indexed=!0),ue?Q[Q.indexOf(ue)]=he:Q.push(he)))}return $?(le.debug?.("(Re)creating",A),ze({table:A.table,database:A.database,schemaDefined:A.schemaDefined,attributes:Q,...U})):U}}var tK,at,rK,nK,sK,PO,iK,oK,LO,aK,NO,cK,kde,AO,le,V1,K1,Y1,Ph,W1,IO,j1,PT,CO,LT,z1,Q1,J1,DT,lK,MT,UT,Lh,BT,xT,uK,OO,dK,DO,bc,vT,X1,Hde,Z1,wO,cf,eK,lf,vO=se(()=>{Oe();Vi();uO();FI();gs();tK=b(fe());G();hl();at=require("msgpackr"),rK=require("ws"),nK=require("worker_threads"),sK=b(J());Nh();PO=require("events"),iK=b(Ts()),oK=b(require("node:tls"));rf();LO=b(require("node:process")),aK=require("node:net");os();is();NO=require("node:stream"),cK=require("lmdb"),{forComponent:kde,errorToString:AO}=sK.default,le=kde("replication").conditional,V1=129,K1=140,Y1=141,Ph=142,W1=130,IO=132,j1=133,PT=134,CO=136,LT=137,z1=143,Q1=144,J1=145,DT=146,lK=0,MT=1,UT=2,Lh=3,BT=4,xT=5,uK=6,OO=0,dK=1,DO=new Map,bc=new Map,vT=!0,X1=300,Hde=2,Z1=3e4;a(FT,"createWebSocket");eK=500,lf=class extends PO.EventEmitter{static{a(this,"NodeReplicationConnection")}socket;startTime;retryTime=eK;retries=0;isConnected=!0;isFinished=!1;nodeSubscriptions;latency=0;replicateTablesByDefault;session;sessionResolve;sessionReject;url;subscription;databaseName;nodeName;authorization;constructor(t,r,n,s,i){super(),this.url=t,this.subscription=r,this.databaseName=n,this.authorization=i,this.nodeName=this.nodeName??yi(t)}async connect(){this.session||this.resetSession();let t=[];this.socket=await FT(this.url,{serverName:this.nodeName,authorization:this.authorization});let r;le.debug?.(`Connecting to ${this.url}, db: ${this.databaseName}, process ${LO.pid}`),this.socket.on("open",()=>{this.socket._socket.unref(),le[this.isConnected?"info":"warn"]?.(`Connected to ${this.url}, db: ${this.databaseName}`),this.retries=0,this.retryTime=eK,this.nodeSubscriptions&&Ql({name:this.nodeName,database:this.databaseName,url:this.url}),this.isConnected=!0,r=Dh(this.socket,{database:this.databaseName,subscription:this.subscription,url:this.url,connection:this,isSubscriptionConnection:this.nodeSubscriptions!==void 0},{replicates:!0}),this.sessionResolve(r)}),this.socket.on("error",n=>{n.code==="SELF_SIGNED_CERT_IN_CHAIN"?(le.warn?.(`Can not connect to ${this.url}, this server does not have a certificate authority for the certificate provided by ${this.url}`),n.isHandled=!0):n.code!=="ECONNREFUSED"&&(n.code==="UNABLE_TO_VERIFY_LEAF_SIGNATURE"?le.error?.(`Can not connect to ${this.url}, the certificate provided by ${this.url} is not trusted, this node needs to be added to the cluster, or a certificate authority needs to be added`):le.error?.(`Error in connection to ${this.url} due to ${n.message}`)),this.sessionReject(n)}),this.socket.on("close",(n,s)=>{if(this.isConnected&&(this.nodeSubscriptions&&sf({name:this.nodeName,database:this.databaseName,url:this.url,finished:this.socket.isFinished}),this.isConnected=!1),this.removeAllListeners("subscriptions-updated"),this.socket.isFinished){this.isFinished=!0,r?.end(),this.emit("finished");return}if(++this.retries%20===1){let i=s?.toString();le.warn?.(`${r?"Disconnected from":"Failed to connect to"} ${this.url} (db: "${this.databaseName}"), due to ${i?'"'+i+'" ':""}(code: ${n})`)}r=null,this.resetSession(),setTimeout(()=>{this.connect()},this.retryTime).unref(),this.retryTime+=this.retryTime>>8})}resetSession(){this.session=new Promise((t,r)=>{this.sessionResolve=t,this.sessionReject=r})}subscribe(t,r){this.nodeSubscriptions=t,this.replicateTablesByDefault=r,this.emit("subscriptions-updated",t)}unsubscribe(){this.socket.isFinished=!0,this.socket.close(1008,"No longer subscribed")}getRecord(t){return this.session.then(r=>r.getRecord(t))}};a(Dh,"replicateOverWS")});function Ac(e,t){let r=e.toString("base64"),n=[`-----BEGIN ${t}-----`];for(let s=0;s<r.length;s+=64)n.push(r.substring(s,s+64));return n.push(`-----END ${t}-----`),n.join(`
19
19
  `)}function pK(e){let t=[],r=e;for(;r?.raw;){let n={cert:r.raw};if(r.issuerCertificate&&r.issuerCertificate!==r&&r.issuerCertificate.raw&&(n.issuer=r.issuerCertificate.raw),t.push(n),r.issuerCertificate&&r.issuerCertificate!==r)r=r.issuerCertificate;else break}return t}function xO(e){try{let t=Zl(e),n=_o.Certificate.fromBER(t).extensions?.find(c=>c.extnID==="2.5.29.31");if(!n)return ho.debug?.("Certificate has no CRL Distribution Points extension"),[];let s=Eo.fromBER(n.extnValue.valueBlock.valueHexView);if(s.offset===-1)throw new Error("Failed to parse ASN.1 structure in CRL Distribution Points extension");let i=new _o.CRLDistributionPoints({schema:s.result}),o=[];for(let c of i.distributionPoints)if(c.distributionPoint&&Array.isArray(c.distributionPoint)){for(let l of c.distributionPoint)if(l.type===6&&typeof l.value=="string"){let u=l.value;(u.startsWith("http://")||u.startsWith("https://"))&&o.push(u)}}return ho.debug?.(`Found ${o.length} CRL distribution points: ${o}`),o}catch(t){return ho.warn?.(`Failed to extract CRL distribution points: ${t}`),[]}}function hK(e){try{let t=Zl(e),r=_o.Certificate.fromBER(t),n=[],s=[];for(let i of r.extensions||[])if(i.extnID==="2.5.29.31")try{let o=Eo.fromBER(i.extnValue.valueBlock.valueHexView);if(o.offset!==-1){let c=new _o.CRLDistributionPoints({schema:o.result});for(let l of c.distributionPoints)if(l.distributionPoint&&Array.isArray(l.distributionPoint)){for(let u of l.distributionPoint)if(u.type===6&&typeof u.value=="string"){let d=u.value;(d.startsWith("http://")||d.startsWith("https://"))&&n.push(d)}}}}catch(o){ho.warn?.(`Failed to parse CRL Distribution Points extension: ${o}`)}else if(i.extnID==="1.3.6.1.5.5.7.1.1")try{let o=Eo.fromBER(i.extnValue.valueBlock.valueHexView);if(o.offset!==-1&&o.result instanceof Eo.Sequence){for(let c of o.result.valueBlock.value)if(c instanceof Eo.Sequence&&c.valueBlock.value.length>=2){let l=c.valueBlock.value[0],u=c.valueBlock.value[1];if(l instanceof Eo.ObjectIdentifier&&l.valueBlock.toString()==="1.3.6.1.5.5.7.48.1"&&u.idBlock.tagNumber===6){let d=String.fromCharCode(...Array.from(u.valueBlock.valueHexView));(d.startsWith("http://")||d.startsWith("https://"))&&s.push(d)}}}}catch(o){ho.warn?.(`Failed to parse Authority Information Access extension: ${o}`)}return ho.debug?.(`Found ${n.length} CRL distribution points and ${s.length} OCSP responder URLs`),{crlUrls:n,ocspUrls:s}}catch(t){return ho.warn?.(`Failed to extract revocation URLs: ${t}`),{crlUrls:[],ocspUrls:[]}}}function Zl(e){let t=e.replace(/-----BEGIN [^-]+-----/g,"").replace(/-----END [^-]+-----/g,"").replace(/\s/g,""),r=atob(t),n=new ArrayBuffer(r.length),s=new Uint8Array(n);for(let i=0;i<r.length;i++)s[i]=r.charCodeAt(i);return n}function HT(e,t,r,n){let s={certPem:e,issuerPem:t,method:r,...n},i=(0,UO.createHash)("sha256").update(JSON.stringify(s)).digest("hex");return`${r}:${i}`}function BO(e,t){return`${e}:${t}`}function EK(e){try{let t=Zl(e),n=_o.Certificate.fromBER(t).serialNumber.valueBlock.valueHexView;return Array.from(n).map(s=>s.toString(16).padStart(2,"0")).join("")}catch(t){throw ho.error?.(`Failed to extract serial number: ${t}`),new Error(`Failed to extract certificate serial number: ${t.message}`)}}function FO(e){try{let t=Zl(e),r=_o.Certificate.fromBER(t),n=r.extensions?.find(i=>i.extnID==="2.5.29.35");if(n)try{let i=Eo.fromBER(n.extnValue.valueBlock.valueHexView);if(i.offset!==-1){let o=new _o.AuthorityKeyIdentifier({schema:i.result});if(o.keyIdentifier){let c=o.keyIdentifier.valueBlock.valueHexView;return Array.from(c).map(l=>l.toString(16).padStart(2,"0")).join("")}}}catch(i){ho.debug?.(`Failed to parse Authority Key Identifier: ${i}, falling back to hash`)}let s=r.issuer.typesAndValues.map(i=>`${i.type}=${i.value.valueBlock.value}`).join(",");return(0,UO.createHash)("sha256").update(s).digest("hex")}catch(t){throw ho.error?.(`Failed to extract issuer key ID: ${t}`),new Error(`Failed to extract issuer key ID: ${t.message}`)}}function GT(){return MO||(MO=ze({table:"hdb_certificate_cache",database:"system",attributes:[{name:"certificate_id",isPrimaryKey:!0},{name:"status"},{name:"reason"},{name:"checked_at"},{name:"expiresAt",expiresAt:!0,indexed:!0},{name:"method"}]})),MO}var UO,_o,Eo,mK,ho,MO,qT=se(()=>{UO=require("node:crypto"),_o=b(require("pkijs")),Eo=b(require("asn1js")),mK=b(sr());Oe();ho=(0,mK.loggerWithTag)("cert-verification-utils");a(Ac,"bufferToPem");a(pK,"extractCertificateChain");a(xO,"extractCRLDistributionPoints");a(hK,"extractRevocationUrls");a(Zl,"pemToBuffer");a(HT,"createCacheKey");a(BO,"createRevokedCertificateId");a(EK,"extractSerialNumber");a(FO,"extractIssuerKeyId");MO=null;a(GT,"getCertificateCacheTable")});function _K(e){let{error:t,value:r}=Vde.validate(e,{abortEarly:!1,allowUnknown:!1});if(t){let n=t.details.map(s=>s.message).join("; ");throw new Error(`Invalid certificate verification configuration: ${n}`)}return r}var Yr,Gde,uf,df,kO,qde,$de,Vde,gK=se(()=>{Yr=b(require("joi")),Gde="fail-closed",uf={timeout:5e3,cacheTtl:36e5,errorCacheTtl:3e5,failureMode:"fail-closed"},df={timeout:1e4,cacheTtl:864e5,failureMode:"fail-closed",gracePeriod:864e5},kO=Yr.default.string().valid("fail-open","fail-closed"),qde=Yr.default.alternatives().try(Yr.default.boolean().custom(e=>e===!1?{enabled:!1}:{enabled:!0,...df}),Yr.default.object({enabled:Yr.default.boolean().default(!0),timeout:Yr.default.number().min(1e3).default(df.timeout).messages({"number.min":"CRL timeout must be at least 1000ms (1 second)"}),cacheTtl:Yr.default.number().min(1e3).default(df.cacheTtl).messages({"number.min":"CRL cacheTtl must be at least 1000ms (1 second)"}),failureMode:kO.default(df.failureMode),gracePeriod:Yr.default.number().min(0).default(df.gracePeriod).messages({"number.min":"CRL gracePeriod must be at least 0ms"})})),$de=Yr.default.alternatives().try(Yr.default.boolean().custom(e=>e===!1?{enabled:!1}:{enabled:!0,...uf}),Yr.default.object({enabled:Yr.default.boolean().default(!0),timeout:Yr.default.number().min(1e3).default(uf.timeout).messages({"number.min":"OCSP timeout must be at least 1000ms (1 second)"}),cacheTtl:Yr.default.number().min(1e3).default(uf.cacheTtl).messages({"number.min":"OCSP cacheTtl must be at least 1000ms (1 second)"}),errorCacheTtl:Yr.default.number().min(1e3).default(uf.errorCacheTtl).messages({"number.min":"OCSP errorCacheTtl must be at least 1000ms (1 second)"}),failureMode:kO.default(uf.failureMode)})),Vde=Yr.default.object({failureMode:kO.default(Gde),crl:qde.default({enabled:!0,...df}),ocsp:$de.default({enabled:!0,...uf})});a(_K,"validateAndParseCertificateVerificationConfig")});function NK(e){if(typeof e=="boolean"||e==null){if(e===HO&&GO)return go.trace?.("Using cached validation error result (primitive) - returning disabled"),!1;if(e===HO&&$T!==null)return go.trace?.("Using cached certificate verification config (primitive)"),$T;go.trace?.("Parsing and caching certificate verification config (primitive)"),HO=e;try{return $T=yK(e),GO=null,$T}catch(n){return GO=n,go.error?.(`Certificate verification config validation failed - defaulting to disabled: ${n.message}`),!1}}if(TK.get(e))return go.trace?.("Using cached validation error result (object) - returning disabled"),!1;let r=SK.get(e);if(r!==void 0)return go.trace?.("Using cached certificate verification config (object)"),r;go.trace?.("Parsing and caching certificate verification config (object)");try{let n=yK(e);return SK.set(e,n),n}catch(n){return TK.set(e,n),go.error?.(`Certificate verification config validation failed - defaulting to disabled: ${n.message}`),!1}}function yK(e){if(go.trace?.(`getCertificateVerificationConfig called with: ${JSON.stringify({mtlsConfig:e})}`),!e)return!1;let t=e===!0?void 0:e.certificateVerification;return go.trace?.(`Certificate verification config: ${JSON.stringify({verificationConfig:t})}`),t==null||t===!1?!1:_K(t===!0?{}:t)}var RK,bK,go,AK,IK,wK,SK,HO,$T,TK,GO,qO=se(()=>{RK=b(sr()),bK=b(Rt());gK();go=(0,RK.loggerWithTag)("cert-verification-config"),AK=10080*60*1e3,IK=3e5,wK=`Harper/${bK.packageJson.version} CRL-Client`,SK=new WeakMap,HO=null,$T=null,TK=new WeakMap,GO=null;a(NK,"getCachedCertificateVerificationConfig");a(yK,"getCertificateVerificationConfig")});function vh(e){return e===OK||e===Kde}function Yde(e){return e===PK||e===LK}function $O(e){return e===OK?PK:LK}function Wde(){if(CK)return;CK=!0;let e=eu.CryptoEngine.prototype,t=eu.Certificate.prototype,r={getHashAlgorithm:e.getHashAlgorithm,getAlgorithmByOID:e.getAlgorithmByOID,getAlgorithmParameters:e.getAlgorithmParameters,verifyWithPublicKey:e.verifyWithPublicKey,certificateVerify:t.verify,getPublicKey:t.getPublicKey};e.getHashAlgorithm=function(...n){let[s]=n;return vh(s.algorithmId)?"UNUSED-EDDSA-BUILTIN-HASH":r.getHashAlgorithm.call(this,s)},e.getAlgorithmByOID=function(...n){let[s]=n;return vh(s)?{name:$O(s)}:r.getAlgorithmByOID.call(this,...n)},e.getAlgorithmParameters=function(...n){let[s,i]=n;return Yde(s)?{algorithm:{name:s},usages:i==="sign"?["sign"]:["verify"]}:r.getAlgorithmParameters.call(this,...n)},t.getPublicKey=async function(...n){let[,s=eu.getCrypto(!0)]=n,i=this.subjectPublicKeyInfo.algorithm.algorithmId;if(vh(i)){let o=$O(i);return s.importKey("spki",this.subjectPublicKeyInfo.toSchema().toBER(!1),o,!0,["verify"])}return r.getPublicKey.call(this,...n)},t.verify=async function(...n){let[s]=n;if(vh(this.signatureAlgorithm.algorithmId))try{let i=this.toSchema().toBER(!1),o=s.toSchema().toBER(!1),c=new Mh.X509Certificate(Buffer.from(i)),l=new Mh.X509Certificate(Buffer.from(o));return c.verify(l.publicKey)}catch{return!1}return r.certificateVerify.call(this,...n)},r.verifyWithPublicKey&&(e.verifyWithPublicKey=async function(...n){let[s,i,o]=n,c=o.algorithm.algorithmId;if(vh(c)){let l=$O(c);try{let u=this.crypto?.subtle||this.subtle||eu.getCrypto(!0)?.subtle||Mh.webcrypto?.subtle;if(!u)throw new Error("No crypto.subtle available");let d=await u.importKey("spki",o.toSchema().toBER(!1),l,!1,["verify"]),f=i.valueBlock.valueHexView;return"unusedBits"in i.valueBlock&&i.valueBlock.unusedBits>0&&(f=f.slice(0,f.length-1)),await u.verify(l,d,f,s)}catch{return!1}}return r.verifyWithPublicKey.call(this,...n)})}var eu,Mh,OK,Kde,PK,LK,CK,DK=se(()=>{eu=b(require("pkijs")),Mh=require("node:crypto"),OK="1.3.101.112",Kde="1.3.101.113",PK="Ed25519",LK="Ed448",CK=!1;a(vh,"isEd25519OrEd448");a(Yde,"isEdDSAAlgorithmName");a($O,"getEdDSAAlgorithmName");a(Wde,"applyEd25519Patch");Wde()});var xK={};ye(xK,{CRLSignatureVerificationError:()=>Uh,performCRLCheck:()=>Qde,verifyCRL:()=>YO});function jde(){return VT||(VT=GT(),VT.sourcedFrom(ff)),VT}function zde(){return KT||(KT=ze({table:"hdb_crl_cache",database:"system",attributes:[{name:"distribution_point",isPrimaryKey:!0},{name:"issuer_dn"},{name:"crl_blob"},{name:"this_update"},{name:"next_update"},{name:"signature_valid"},{name:"expiresAt",expiresAt:!0,indexed:!0}]}),KT.sourcedFrom(KO)),KT}function MK(){return VO||(VO=ze({table:"hdb_revoked_certificates",database:"system",attributes:[{name:"composite_id",isPrimaryKey:!0},{name:"serial_number",indexed:!0},{name:"issuer_key_id",indexed:!0},{name:"revocation_date"},{name:"revocation_reason"},{name:"crl_source",indexed:!0},{name:"crl_next_update"},{name:"expiresAt",expiresAt:!0,indexed:!0}]})),VO}async function YO(e,t,r,n){if(r?.enabled===!1)return{valid:!0,status:"disabled",method:"disabled"};try{let s=Ac(e,"CERTIFICATE"),i=Ac(t,"CERTIFICATE"),o=n??xO(s);if(o.length===0)return{valid:!0,status:"no-crl-distribution-points",method:"crl"};let c=HT(s,i,"crl"),l=await jde().get(c,{certPem:s,issuerPem:i,distributionPoint:o[0],config:{crl:r??{}}});if(!l)return Or.error?.("Cache fetch returned null - this indicates a source configuration issue"),r.failureMode==="fail-closed"?{valid:!1,status:"error",error:"Cache fetch failed",method:"crl"}:(Or.warn?.("CRL cache fetch failed, allowing connection (fail-open mode)"),{valid:!0,status:"error-allowed",method:"crl"});let u=l,d=l.wasLoadedFromSource?.();return Or.trace?.(`CRL ${d?"source fetch":"cache hit"} for certificate`),{valid:u.status==="good",status:u.status,cached:!d,method:u.method||"crl"}}catch(s){return Or.error?.(`CRL verification error: ${s}`),r.failureMode==="fail-closed"?{valid:!1,status:"error",error:s.message,method:"crl"}:(Or.warn?.("CRL check failed, allowing connection (fail-open mode)"),{valid:!0,status:"error-allowed",method:"crl"})}}async function Qde(e,t,r,n){let s=n??xO(e);if(s.length===0)return{status:"good"};let i=EK(e),o=FO(t),c=BO(o,i);try{let u=await MK().get(c);if(u){let f=Date.now(),m=u;return m.crl_next_update>f?{status:"revoked",reason:m.revocation_reason||"unspecified",source:m.crl_source}:m.crl_next_update+r.gracePeriod>f?(Or.warn?.("Using expired CRL data within grace period"),{status:"revoked",reason:m.revocation_reason||"unspecified",source:m.crl_source}):(Or.warn?.("CRL data is too old, treating as unknown"),{status:"unknown",reason:"crl-expired"})}let d=await Jde(s,t,r);return d.upToDate?{status:"good",source:d.source}:(Or.warn?.("CRL data is stale or missing, treating as unknown"),{status:"unknown",reason:d.reason||"crl-unavailable"})}catch(l){return Or.error?.(`CRL lookup error: ${l}`),{status:"unknown",reason:l.message}}}async function Jde(e,t,r){let n=Date.now();for(let s of e)try{let i=zde(),o=null,c=null;try{c=await i.get(s),(c&&c.next_update>n||c&&c.next_update+r.gracePeriod>n)&&(o=c)}catch{}o||(o=await UK(s,t,r.timeout));let l=o.next_update;if(l>n){if(!c)try{await i.put(s,o)}catch{}return{upToDate:!0,source:s}}else return l+r.gracePeriod>n?{upToDate:!0,source:s}:{upToDate:!1,reason:"crl-expired"}}catch(i){if(i instanceof Uh)throw i}return{upToDate:!1,reason:"no-current-crl-data"}}async function UK(e,t,r){let n=new AbortController,s=setTimeout(()=>n.abort(),r);try{let i=await fetch(e,{signal:n.signal,headers:{"User-Agent":wK}});if(clearTimeout(s),!i.ok)throw new Error(`CRL download failed: ${i.status}`);let o=Buffer.from(await i.arrayBuffer()),c,l=o.toString("utf8");l.includes("-----BEGIN X509 CRL-----")?c=Buffer.from(Zl(l)):c=o;let u=YT.CertificateRevocationList.fromBER(c),d=YT.Certificate.fromBER(Zl(t)),f=await u.verify({issuerCertificate:d});if(!f){let _=`CRL signature verification failed for: ${e}`;throw Or.error?.(_),new Uh(_)}let m=u.thisUpdate.value.getTime(),p=u.nextUpdate?.value.getTime()??m+AK,h=d.issuer.typesAndValues.map(_=>`${_.type}=${_.value.valueBlock.value}`).join(","),E={distribution_point:e,issuer_dn:h,crl_blob:o,this_update:m,next_update:p,signature_valid:f,expiresAt:p};return Xde(u,t,e,p).catch(_=>{Or.error?.(`Error processing revoked certificates: ${_}`)}),E}finally{clearTimeout(s)}}async function Xde(e,t,r,n){let s=MK(),i=FO(t),o=r;try{await Zde(s,o)}catch(c){Or.warn?.(`Failed to clear existing CRL entries: ${c}`)}if(e.revokedCertificates)for(let c of e.revokedCertificates)try{let l=c.userCertificate.valueBlock.valueHexView;if(!l){Or.warn?.("Could not extract serial number from revoked certificate");continue}let u=Array.from(l).map(h=>h.toString(16).padStart(2,"0")).join(""),d=BO(i,u),f=c.revocationDate.value.getTime(),p={composite_id:d,serial_number:u,issuer_key_id:i,revocation_date:f,revocation_reason:"unspecified",crl_source:o,crl_next_update:n,expiresAt:n};await s.create(p.composite_id,p)}catch(l){Or.warn?.(`Failed to process revoked certificate: ${l}`)}}async function Zde(e,t){try{let r=e.search([{attribute:"crl_source",value:t}]);for await(let n of r)try{await e.delete(n.composite_id)}catch(s){Or.warn?.(`Failed to delete revoked certificate entry: ${s}`)}}catch(r){throw Or.error?.(`Failed to search for existing CRL entries: ${r}`),r}}var YT,vK,Uh,Or,VT,KO,KT,VO,WO=se(()=>{YT=b(require("pkijs")),vK=b(sr());Oe();Qi();qT();qO();jO();Uh=class extends Error{static{a(this,"CRLSignatureVerificationError")}constructor(t){super(t),this.name="CRLSignatureVerificationError"}},Or=(0,vK.loggerWithTag)("crl-verification");a(jde,"getCertificateCacheTable");KO=class extends Xt{static{a(this,"CertificateRevocationListSource")}async get(t){let n=this.getContext()?.requestContext;if(!n?.distributionPoint||!n?.issuerPem)throw new Error(`No CRL data provided for cache key: ${t}`);let{distributionPoint:s,issuerPem:i,config:o}=n;try{let c=await UK(s,i,o.timeout),l=c.next_update,u=Date.now()+o.cacheTtl,d=Math.min(l,u);return{...c,expiresAt:d}}catch(c){if(Or.error?.(`CRL fetch error for: ${s} - ${c}`),o.failureMode==="fail-closed"){let l=Date.now()+IK;return{crl_id:t,distribution_point:s,issuer_dn:"unknown",crl_blob:Buffer.alloc(0),this_update:Date.now(),next_update:l,signature_valid:!1,expiresAt:l}}return Or.warn?.("CRL fetch failed, not caching (fail-open mode)"),null}}};a(zde,"getCRLCacheTable");a(MK,"getRevokedCertificateTable");a(YO,"verifyCRL");a(Qde,"performCRLCheck");a(Jde,"checkCRLFreshness");a(UK,"downloadAndParseCRL");a(Xde,"processRevokedCertificates");a(Zde,"clearExistingCRLEntries")});async function efe(){zO||(zO=(await Promise.resolve().then(()=>(WO(),xK))).performCRLCheck),QO||(QO=(await Promise.resolve().then(()=>(JO(),FK))).performOCSPCheck)}var BK,RBe,zO,QO,ff,jO=se(()=>{Qi();BK=b(sr()),RBe=(0,BK.loggerWithTag)("cert-verification-source");a(efe,"loadVerificationFunctions");ff=class extends Xt{static{a(this,"CertificateVerificationSource")}async get(t){let r=t.id,s=this.getContext()?.requestContext;if(!s||!s.certPem||!s.issuerPem)return null;let{certPem:i,issuerPem:o,ocspUrls:c,config:l}=s,u;r.startsWith("crl:")?u="crl":r.startsWith("ocsp:")?u="ocsp":u="unknown",await efe();let d,f;if(u==="crl"){f=l.crl;let p=s.distributionPoint?[s.distributionPoint]:void 0;d=await zO(i,o,f,p)}else if(u==="ocsp")f=l.ocsp,d=await QO(i,o,f,c);else throw new Error(`Unsupported verification method: ${u} for ID: ${r}`);let m=Date.now()+f.cacheTtl;return{certificate_id:r,status:d.status,reason:d.reason,checked_at:Date.now(),expiresAt:m,method:u}}}});var FK={};ye(FK,{performOCSPCheck:()=>rfe,verifyOCSP:()=>XO});function tfe(){return jT||(jT=GT(),jT.sourcedFrom(ff)),jT}async function XO(e,t,r,n){if(r?.enabled===!1)return{valid:!0,status:"disabled",method:"disabled"};try{let s=Ac(e,"CERTIFICATE"),i=Ac(t,"CERTIFICATE"),o=HT(s,i,"ocsp"),c=await tfe().get(o,{certPem:s,issuerPem:i,ocspUrls:n,config:{ocsp:r??{}}});if(!c)return r.failureMode==="fail-closed"?{valid:!1,status:"error",error:"Cache fetch failed",method:"ocsp"}:(WT.warn?.("OCSP cache fetch failed, allowing connection (fail-open mode)"),{valid:!0,status:"error-allowed",method:"ocsp"});let l=c,u=c.wasLoadedFromSource?.();return WT.trace?.(`OCSP ${u?"source fetch":"cache hit"} for certificate`),{valid:l.status==="good",status:l.status,cached:!u,method:l.method||"ocsp"}}catch(s){return WT.error?.(`OCSP verification error: ${s}`),r.failureMode==="fail-closed"?{valid:!1,status:"error",error:s.message,method:"ocsp"}:(WT.warn?.("OCSP check failed, allowing connection (fail-open mode)"),{valid:!0,status:"error-allowed",method:"ocsp"})}}async function rfe(e,t,r,n){try{let s=await(0,kK.getCertStatus)(e,{ca:t,timeout:r.timeout,...n?.length&&{ocspUrl:n[0]}});switch(s.status){case"good":return{status:"good"};case"revoked":return{status:"revoked",reason:s.revocationReason?.toString()||"unspecified"};default:return{status:"unknown",reason:"unknown-status"}}}catch(s){return{status:"unknown",reason:s.name==="AbortError"?"timeout":"ocsp-error"}}}var kK,HK,WT,jT,JO=se(()=>{DK();kK=require("easy-ocsp"),HK=b(sr());qT();jO();WT=(0,HK.loggerWithTag)("ocsp-verification");a(tfe,"getCertificateCacheTable");a(XO,"verifyOCSP");a(rfe,"performOCSPCheck")});async function mf(e,t){cn.debug?.(`verifyCertificate called for: ${e.subject?.CN||"unknown"}`);let r=NK(t);if(r===!1)return cn.debug?.("Certificate verification disabled"),{valid:!0,status:"disabled",method:"disabled"};let n=pK(e);if(cn.trace?.(`Certificate chain length: ${n.length}`),n.length<2||!n[0].issuer)return cn.debug?.("Certificate chain insufficient for revocation checking - need certificate and issuer"),{valid:!0,status:"no-issuer-cert",method:"disabled"};let s=Ac(n[0].cert,"CERTIFICATE"),{crlUrls:i,ocspUrls:o}=hK(s);if(cn.debug?.(`Certificate extensions: CRL distribution points=${i.length}, OCSP URLs=${o.length}`),i.length>0)if(r.crl.enabled)try{cn.debug?.("Attempting CRL verification");let c=await YO(n[0].cert,n[0].issuer,r.crl,i);if(c.status==="good"||c.status==="revoked")return cn.debug?.(`CRL verification result: ${c.status}`),c;cn.debug?.(`CRL verification inconclusive: ${c.status}, trying OCSP fallback`)}catch(c){cn.warn?.(`CRL verification failed: ${c}`)}else cn.debug?.("Skipping CRL - disabled in configuration");else cn.debug?.("Skipping CRL - no distribution points in certificate");if(o.length>0)if(r.ocsp.enabled)try{cn.debug?.("Attempting OCSP verification");let c=await XO(n[0].cert,n[0].issuer,r.ocsp,o);return cn.debug?.(`OCSP verification result: ${c.status}`),c}catch(c){cn.warn?.(`OCSP verification failed: ${c}`)}else cn.debug?.("Skipping OCSP - disabled in configuration");else cn.debug?.("Skipping OCSP - no responder URLs in certificate");return r.failureMode==="fail-closed"?{valid:!1,status:"no-verification-available",method:"disabled"}:{valid:!0,status:"verification-unavailable-allowed",method:"disabled"}}var GK,cn,zT=se(()=>{GK=b(sr());qT();qO();JO();WO();cn=(0,GK.loggerWithTag)("cert-verification");a(mf,"verifyCertificate")});var la={};ye(la,{buildReplicationMtlsConfig:()=>QK,clearThisNodeName:()=>dfe,disableReplication:()=>ofe,enabledDatabases:()=>Rc,forEachReplicatedDatabase:()=>_c,getThisNodeId:()=>kT,getThisNodeName:()=>nt,getThisNodeUrl:()=>gc,hostnameToUrl:()=>ey,lastTimeInAuditStore:()=>Rh,monitorNodeCAs:()=>JK,replicateOperation:()=>mfe,replicationCertificateAuthorities:()=>ua,sendOperationToNode:()=>xh,servers:()=>sfe,setReplicator:()=>ZK,start:()=>ife,startOnMainThread:()=>dO,subscribeToNode:()=>wh,unsubscribeFromNode:()=>AT,urlToNodeName:()=>yi});function QK(e){return e?.mtls&&typeof e.mtls=="object"?e.mtls:!0}function ife(e){if(!e.port&&!e.securePort&&(e.port=Ks.default.get(x.OPERATIONSAPI_NETWORK_PORT),e.securePort=Ks.default.get(x.OPERATIONSAPI_NETWORK_SECUREPORT)),!nt())throw new Error("Can not load replication without a url (see replication.url in the config)");let t=new Map;for(let i of Ah(e))t.set(yi(i.url),i);afe(e);let r=QK(e);e={isOperationsServer:!0,maxPayload:10*1024*1024*1024,...e,mtls:r};let n=Ue.ws(async(i,o,c,l)=>{if(wt.debug("Incoming WS connection received "+o.url),o.headers.get("sec-websocket-protocol")!=="harperdb-replication-v1")return l(i,o,c);i._socket.unref(),Dh(i,e,c.then(()=>o?.user)),i.on("error",u=>{u.code!=="ECONNREFUSED"&&wt.error("Error in connection to "+this.url,u.message)})},e);e.runFirst=!0,Ue.http(async(i,o)=>{if(i.isWebSocket&&i.headers.get("Sec-WebSocket-Protocol")==="harperdb-replication-v1"){wt.debug("Incoming replication WS connection received, authorized: "+i.authorized),!i.authorized&&i._nodeRequest.socket.authorizationError&&wt.error(`Incoming client connection from ${i.ip} did not have valid certificate, you may need turn on enableRootCAs in the config if you are using a publicly signed certificate, or add the CA to the server's trusted CAs`,i._nodeRequest.socket.authorizationError);let c=Gt().primaryStore;if(i.authorized&&i.peerCertificate.subjectaltname){let l=(0,jK.getHostnamesFromCertificate)(i.peerCertificate),u;for(let d of l)if(u=d&&(c.get(d)||t.get(d)),u)break;if(u){let d=await mf(i.peerCertificate,e.mtls);if(!d.valid){wt.warn("Certificate verification failed:",d.status,"for node",u.name,"certificate serial number",i.peerCertificate.serialNumber);return}if(u?.revoked_certificates?.includes(i.peerCertificate.serialNumber)){wt.warn("Revoked certificate used in attempt to connect to node",u.name,"certificate serial number",i.peerCertificate.serialNumber);return}else i.user=u}else wt.warn(`No node found for certificate common name/SANs: ${l}, available nodes are ${Array.from(c.getRange({}).filter(({value:d})=>d).map(({key:d})=>d)).join(", ")} and routes ${Array.from(t.keys()).join(", ")}, connection will require credentials.`)}else{let l=c.get(i.ip)||t.get(i.ip);l?i.user=l:wt.warn(`No node found for IP address ${i.ip}, available nodes are ${Array.from(new Set([...c.getKeys(),...t.keys()])).join(", ")}, connection will require credentials.`)}}return o(i)},e);let s=[];for(let i of n)if(i.secureContexts){let o=a(()=>{let c=new Set(i.secureContexts.values());i.defaultContext&&c.add(i.defaultContext);for(let l of c)try{let u=Array.from(ua);l.options.availableCAs&&u.push(...l.options.availableCAs.values());let d={...l.options,ca:u};l.updatedContext=ZT.createSecureContext(d)}catch(u){wt.error("Error creating replication TLS config",u)}},"updateContexts");i.secureContextsListeners.push(o),s.push(o),Ks.default.get(x.REPLICATION_ENABLEROOTCAS)!==!1&&o()}JK(()=>{for(let i of s)i()})}function JK(e){let t=0;tf(r=>{r?.ca&&(ua.add(r.ca),ua.size!==t&&(t=ua.size,e?.()))})}function ofe(e=!0){zK=e}function afe(e){zK||(lt(),Rc=e.databases,_c(e,(t,r)=>{if(!t){let n=e.databaseSubscriptions||bc;for(let[s,i]of JT){let o=i.get(r);o&&(o.subscribe([],!1),i.delete(r))}n.delete(r);return}for(let n in t){let s=t[n];ZK(r,s,e),DO.get(s)?.forEach(i=>i(s))}}))}function ZK(e,t,r){if(!t)return console.error(`Attempt to replicate non-existent table ${t.name} from database ${e}`);if(t.replicate===!1||t.sources?.some(s=>s.isReplicator))return;let n;t.sourcedFrom(class XK extends Xt{static{a(this,"Replicator")}static connection;static subscription;static async subscribe(){let i=r.databaseSubscriptions||bc,o=i.get(e),c=o?.tableById||[];c[t.tableId]=t;let l=o?.ready;if(wt.trace("Setting up replicator subscription to database",e),!o?.auditStore)return this.subscription=o=new ss,i.set(e,o),o.tableById=c,o.auditStore=t.auditStore,o.dbisDB=t.dbisDB,o.databaseName=e,l&&l(o),o;this.subscription=o}static subscribeOnThisThread(i,o){return!0}static async load(i){if(i){let o=i.residencyId,c=i.residency||t.dbisDB.get([Symbol.for("residency_by_id"),o]);if(c){let l,u=new Set;do{let d,f="",m=1/0;for(let h of c){if(u.has(h)||h===Ue.hostname)continue;let E=lfe(h,XK.subscription,e);if(E?.isConnected){let _=ef(t.auditStore,e,h)[BT];(!d||_<m)&&(d=E,f=h,m=_)}}if(!d)throw l||new YK.ServerError(`No connection to any other nodes are available: ${c}`,502);let p={requestId:nfe++,table:t,entry:i,id:i.key};u.add(f);try{return await d.getRecord(p)}catch(h){if(d.isConnected)throw h;wt.warn("Error in load from node",XT,h),l||(l=h)}}while(!0)}}}static isReplicator=!0},{intermediateSource:!0})}function cfe(e,t,r,n,s,i){let o=t+"-"+e,c=JT.get(o);c||(c=new Map,JT.set(o,c));let l=c.get(n);if(l)return l;if(r)return c.set(n,l=new lf(t,r,n,s,i)),l.connect(),l.once("finished",()=>c.delete(n)),l}function lfe(e,t,r){let n=qK.get(e);n||(n=new Map,qK.set(e,n));let s=n.get(r);if(s)return s;let i=Gt().primaryStore.get(e);return i?.url&&(s=new lf(i.url,t,r,e,i.authorization),n.set(r,s),s.connect(),s.once("finished",()=>n.delete(r))),s}async function xh(e,t,r){r||(r={}),r.serverName=e.name;let n=await FT(e.url,r),s=Dh(n,{},{});return new Promise((i,o)=>{n.on("open",()=>{wt.debug("Sending operation connection to "+e.url+" opened",t),i(s.sendOperation(t))}),n.on("error",c=>{o(c)}),n.on("close",c=>{wt.info("Sending operation connection to "+e.url+" closed",c)})}).finally(()=>{n.close()})}function wh(e){try{WK.isMainThread&&wt.warn("Subscribing on main thread (should not happen in multi-threaded instance)",e.nodes[0].url,e.database);let t=bc.get(e.database);if(!t){let n;t=new Promise(s=>{wt.info("Waiting for subscription to database "+e.database),n=s}),t.ready=n,bc.set(e.database,t)}let r=cfe(e.nodes[0].url,e.url,t,e.database,e.name,e.nodes[0].authorization);e.nodes[0].name===void 0?r.tentativeNode=e.nodes[0]:r.nodeName=e.nodes[0].name,r.subscribe(e.nodes.filter(n=>bh(n,e.database)),e.replicateByDefault)}catch(t){wt.error("Error in subscription to node",e.nodes[0]?.url,t)}}async function AT({url:e,nodes:t,database:r}){wt.trace("Unsubscribing from node",e,r,"nodes",Array.from(Gt().primaryStore.getRange({})));let n=e+"-"+(t[0]?.url??e),s=JT.get(n);if(s){let i=s.get(r);i&&(i.unsubscribe(),s.delete(r))}}function ufe(){if(ZO!==void 0)return ZO;let e=Ks.default.get(x.OPERATIONSAPI_TLS_CERTIFICATE)||Ks.default.get(x.TLS_CERTIFICATE);if(e)return ZO=new VK.X509Certificate((0,KK.readFileSync)(e)).subject?.match(/CN=(.*)/)?.[1]??null}function nt(){return XT||(XT=Ks.default.get("replication_hostname")??yi(Ks.default.get("replication_url"))??ufe()??$K("operationsapi_network_secureport")??$K("operationsapi_network_port")??"127.0.0.1")}function dfe(){XT=void 0}function $K(e){let t=Ks.default.get(e),r=t?.lastIndexOf?.(":");if(r>0)return t.slice(0,r)}function QT(e){let t=Ks.default.get(e),r=t?.lastIndexOf?.(":");return r>0?+t.slice(r+1).replace(/[\[\]]/g,""):+t}function kT(e){return yh(e)?.[nt()]}function gc(){let e=Ks.default.get("replication_url");return e||ey(nt())}function ey(e){let t=QT("replication_port");if(t)return`ws://${e}:${t}`;if(t=QT("replication_secureport"),t)return`wss://${e}:${t}`;if(t=QT("operationsapi_network_port"),t)return`ws://${e}:${t}`;if(t=QT("operationsapi_network_secureport"),t)return`wss://${e}:${t}`}function yi(e){if(e)return new URL(e).hostname}function _c(e,t){for(let n of Object.getOwnPropertyNames(Me))r(n);return sh(n=>{r(n)}),$l((n,s)=>{r(n.databaseName)});function r(n){let s=Me[n];wt.trace("Checking replication status of ",n,e?.databases),e?.databases===void 0||e.databases==="*"||e.databases.includes(n)||e.databases.some?.(i=>i.name===n)||!s?t(s,n,!0):ffe(n)&&t(s,n,!1)}a(r,"forDatabase")}function ffe(e){let t=Me[e];for(let r in t)if(t[r].replicate)return!0}function Rh(e){for(let t of e.getKeys({limit:1,reverse:!0}))return t}async function mfe(e){let t={message:""};if(e.replicated){e.replicated=!1,wt.trace?.("Replicating operation",e.operation,"to nodes",Ue.nodes.map(n=>n.name));let r=await Promise.allSettled(Ue.nodes.map(n=>xh(n,e)));t.replicated=r.map((n,s)=>{let i=n.status==="rejected"?{status:"failed",reason:n.reason.toString()}:n.value;return i.node=Ue.nodes[s]?.name,i})}return t}var Ks,wt,VK,KK,ZT,YK,WK,jK,zK,nfe,sfe,ua,Rc,JT,qK,ZO,XT,gs=se(()=>{Oe();Qi();$u();vO();Hr();Ks=b(fe()),wt=b(J()),VK=require("crypto");zT();KK=require("fs");Nh();rf();G();uO();ZT=b(require("node:tls")),YK=b(Ee()),WK=require("worker_threads"),jK=b(Ts()),nfe=1,sfe=[],ua=Ks.default.get(x.REPLICATION_ENABLEROOTCAS)!==!1?new Set(ZT.rootCertificates):new Set;a(QK,"buildReplicationMtlsConfig");a(ife,"start");a(JK,"monitorNodeCAs");a(ofe,"disableReplication");a(afe,"assignReplicationSource");a(ZK,"setReplicator");JT=new Map;a(cfe,"getSubscriptionConnection");qK=new Map;a(lfe,"getRetrievalConnectionByName");a(xh,"sendOperationToNode");a(wh,"subscribeToNode");a(AT,"unsubscribeFromNode");a(ufe,"getCommonNameFromCert");a(nt,"getThisNodeName");a(dfe,"clearThisNodeName");Object.defineProperty(Ue,"hostname",{get(){return nt()}});a($K,"getHostFromListeningPort");a(QT,"getPortFromListeningPort");a(kT,"getThisNodeId");Ue.replication={getThisNodeId:kT,exportIdMapping:yh};a(gc,"getThisNodeUrl");a(ey,"hostnameToUrl");a(yi,"urlToNodeName");a(_c,"forEachReplicatedDatabase");a(ffe,"hasExplicitlyReplicatedTable");a(Rh,"lastTimeInAuditStore");a(mfe,"replicateOperation")});var iy=M((YBe,sY)=>{"use strict";var pf=LV(),{validateBySchema:Bh}=mt(),{commonValidators:hf,schemaRegex:eP}=Xi(),Sr=require("joi"),pfe=J(),hfe=require("uuid").v4,ny=ea(),Ef=(G(),D(j)),Efe=require("util"),Ic=ms(),{handleHDBError:da,hdbErrors:_fe,ClientError:tu}=Ee(),{HDB_ERROR_MSGS:ty,HTTP_STATUS_CODES:fa}=_fe,{SchemaEventMsg:sy}=us(),eY=_r(),{getDatabases:gfe}=(Oe(),D(pt)),{transformReq:_f}=ae(),{replicateOperation:tY}=(gs(),D(la)),{cleanupOrphans:Sfe}=(is(),D(ig)),ry=Sr.string().min(1).max(hf.schema_length.maximum).pattern(eP).messages({"string.pattern.base":"{:#label} "+hf.schema_format.message}),Tfe=Sr.string().min(1).max(hf.schema_length.maximum).pattern(eP).messages({"string.pattern.base":"{:#label} "+hf.schema_format.message}).required(),yfe=Sr.string().min(1).max(hf.schema_length.maximum).pattern(eP).messages({"string.pattern.base":"{:#label} "+hf.schema_format.message,"any.required":"'primary_key' is required","string.base":"'primary_key' must be a string"}).required();sY.exports={createSchema:Rfe,createSchemaStructure:rY,createTable:bfe,createTableStructure:nY,createAttribute:Cfe,dropSchema:Afe,dropTable:Ife,dropAttribute:wfe,getBackup:Ofe,cleanupOrphanBlobs:Pfe};async function Rfe(e){let t=await rY(e);return ny.signalSchemaChange(new sy(process.pid,e.operation,e.schema)),t}a(Rfe,"createSchema");async function rY(e){let t=Bh(e,Sr.object({database:ry,schema:ry}));if(t)throw new tu(t.message);if(_f(e),!await pf.checkSchemaExists(e.schema))throw da(new Error,ty.SCHEMA_EXISTS_ERR(e.schema),fa.BAD_REQUEST,Ef.LOG_LEVELS.ERROR,ty.SCHEMA_EXISTS_ERR(e.schema),!0);return await Ic.createSchema(e),`database '${e.schema}' successfully created`}a(rY,"createSchemaStructure");async function bfe(e){return _f(e),e.hash_attribute=e.primary_key??e.hash_attribute,await nY(e)}a(bfe,"createTable");async function nY(e){let t=Bh(e,Sr.object({database:ry,schema:ry,table:Tfe,residence:Sr.array().items(Sr.string().min(1)).optional(),hash_attribute:yfe}));if(t)throw new tu(t.message);if(!await pf.checkSchemaTableExists(e.schema,e.table))throw da(new Error,ty.TABLE_EXISTS_ERR(e.schema,e.table),fa.BAD_REQUEST,Ef.LOG_LEVELS.ERROR,ty.TABLE_EXISTS_ERR(e.schema,e.table),!0);let n={name:e.table,schema:e.schema,id:hfe(),hash_attribute:e.hash_attribute};try{if(e.residence)if(global.clustering_on)n.residence=e.residence,await Ic.createTable(n,e);else throw da(new Error,"Clustering does not appear to be enabled. Cannot insert table with property 'residence'.",fa.BAD_REQUEST);else await Ic.createTable(n,e);return`table '${e.schema}.${e.table}' successfully created.`}catch(s){throw s}}a(nY,"createTableStructure");async function Afe(e){let t=Bh(e,Sr.object({database:Sr.string(),schema:Sr.string()}).or("database","schema").messages({"object.missing":"'database' is required"}));if(t)throw new tu(t.message);_f(e);let r=await pf.checkSchemaExists(e.schema);if(r)throw da(new Error,r,fa.NOT_FOUND,Ef.LOG_LEVELS.ERROR,r,!0);let n=await pf.schemaDescribe.describeSchema({schema:e.schema}),s=Object.keys(global.hdb_schema[e.schema]);await Ic.dropSchema(e),ny.signalSchemaChange(new sy(process.pid,e.operation,e.schema)),await eY.purgeSchemaTableStreams(e.schema,s);let i=await tY(e);return i.message=`successfully deleted '${e.schema}'`,i}a(Afe,"dropSchema");async function Ife(e){let t=Bh(e,Sr.object({database:Sr.string(),schema:Sr.string(),table:Sr.string().required()}));if(t)throw new tu(t.message);_f(e);let r=await pf.checkSchemaTableExists(e.schema,e.table);if(r)throw da(new Error,r,fa.NOT_FOUND,Ef.LOG_LEVELS.ERROR,r,!0);await Ic.dropTable(e),await eY.purgeTableStream(e.schema,e.table);let n=await tY(e);return n.message=`successfully deleted table '${e.schema}.${e.table}'`,n}a(Ife,"dropTable");async function wfe(e){let t=Bh(e,Sr.object({database:Sr.string(),schema:Sr.string(),table:Sr.string().required(),attribute:Sr.string().required()}));if(t)throw new tu(t.message);_f(e);let r=await pf.checkSchemaTableExists(e.schema,e.table);if(r)throw da(new Error,r,fa.NOT_FOUND,Ef.LOG_LEVELS.ERROR,r,!0);if(e.attribute===global.hdb_schema[e.schema][e.table].hash_attribute)throw da(new Error,"You cannot drop a hash attribute",fa.BAD_REQUEST,void 0,void 0,!0);if(Ef.TIME_STAMP_NAMES.indexOf(e.attribute)>=0)throw da(new Error,`cannot drop internal timestamp attribute: ${e.attribute}`,fa.BAD_REQUEST,void 0,void 0,!0);try{return await Ic.dropAttribute(e),Nfe(e),ny.signalSchemaChange(new sy(process.pid,e.operation,e.schema,e.table,e.attribute)),`successfully deleted attribute '${e.attribute}'`}catch(n){throw pfe.error(`Got an error deleting attribute ${Efe.inspect(e)}.`),n}}a(wfe,"dropAttribute");function Nfe(e){let t=Object.values(global.hdb_schema[e.schema][e.table].attributes);for(let r=0;r<t.length;r++)t[r].attribute===e.attribute&&global.hdb_schema[e.schema][e.table].attributes.splice(r,1)}a(Nfe,"dropAttributeFromGlobal");async function Cfe(e){_f(e);let t=gfe()[e.schema][e.table].attributes;for(let{name:r}of t)if(r===e.attribute)throw da(new Error,`attribute '${e.attribute}' already exists in ${e.schema}.${e.table}`,fa.BAD_REQUEST,void 0,void 0,!0);return await Ic.createAttribute(e),ny.signalSchemaChange(new sy(process.pid,e.operation,e.schema,e.table,e.attribute)),`attribute '${e.schema}.${e.table}.${e.attribute}' successfully created.`}a(Cfe,"createAttribute");function Ofe(e){return Ic.getBackup(e)}a(Ofe,"getBackup");function Pfe(e){if(!e.database)throw new tu('Must provide "database" name for search for orphaned blobs');if(!databases[e.database])throw new tu(`Unknown database '${e.database}'`);return Sfe(databases[e.database],e.database),{message:"Orphaned blobs cleanup started, check logs for progress"}}a(Pfe,"cleanupOrphanBlobs")});var oY=M((jBe,iY)=>{"use strict";var{OPERATIONS_ENUM:Lfe}=(G(),D(j)),tP=class{static{a(this,"ReadAuditLogObject")}constructor(t,r,n=void 0,s=void 0){this.operation=Lfe.READ_AUDIT_LOG,this.schema=t,this.table=r,this.search_type=n,this.search_values=s}};iY.exports=tP});var rP=M((JBe,dY)=>{"use strict";var Dfe=ms(),QBe=oY(),oy=ae(),ay=(G(),D(j)),vfe=fe(),{handleHDBError:aY,hdbErrors:Mfe}=Ee(),{HDB_ERROR_MSGS:cY,HTTP_STATUS_CODES:lY}=Mfe,Ufe=Object.values(ay.READ_AUDIT_LOG_SEARCH_TYPES_ENUM),uY="To use this operation audit log must be enabled in harperdb-config.yaml";dY.exports=xfe;async function xfe(e){if(oy.isEmpty(e.schema))throw new Error(cY.SCHEMA_REQUIRED_ERR);if(oy.isEmpty(e.table))throw new Error(cY.TABLE_REQUIRED_ERR);if(!vfe.get(ay.CONFIG_PARAMS.LOGGING_AUDITLOG))throw aY(new Error,uY,lY.BAD_REQUEST,ay.LOG_LEVELS.ERROR,uY,!0);let t=oy.checkSchemaTableExist(e.schema,e.table);if(t)throw aY(new Error,t,lY.NOT_FOUND,ay.LOG_LEVELS.ERROR,t,!0);if(!oy.isEmpty(e.search_type)&&Ufe.indexOf(e.search_type)<0)throw new Error(`Invalid searchType '${read_audit_log_object.search_type}'`);return await Dfe.readAuditLog(e)}a(xfe,"readAuditLog")});var mY=M((ZBe,fY)=>{"use strict";var{OPERATIONS_ENUM:Bfe}=(G(),D(j)),nP=class{static{a(this,"GetBackupObject")}constructor(t,r,n=void 0,s=void 0){this.operation=Bfe.GET_BACKUP,this.schema=t,this.table=r}};fY.exports=nP});var EY=M((nFe,hY)=>{"use strict";var Ffe=ms(),tFe=mY(),sP=ae(),kfe=(G(),D(j)),rFe=fe(),{handleHDBError:Hfe,hdbErrors:Gfe}=Ee(),{HDB_ERROR_MSGS:pY,HTTP_STATUS_CODES:qfe}=Gfe;hY.exports=$fe;async function $fe(e){if(sP.isEmpty(e.schema))throw new Error(pY.SCHEMA_REQUIRED_ERR);if(sP.isEmpty(e.table))throw new Error(pY.TABLE_REQUIRED_ERR);let t=sP.checkSchemaTableExist(e.schema,e.table);if(t)throw Hfe(new Error,t,qfe.NOT_FOUND,kfe.LOG_LEVELS.ERROR,t,!0);return await Ffe.getBackup(readAuditLogObject)}a($fe,"getBackup")});var SY=M((iFe,gY)=>{"use strict";var Vfe=fe(),ma=require("joi"),Kfe=mt(),_Y=require("moment"),Yfe=require("fs-extra"),oP=require("path"),Wfe=require("lodash"),Fh=(G(),D(j)),{LOG_LEVELS:ru}=(G(),D(j)),jfe="YYYY-MM-DD hh:mm:ss",zfe=oP.resolve(__dirname,"../logs");gY.exports=function(e){return Kfe.validateBySchema(e,Qfe)};var Qfe=ma.object({from:ma.custom(iP),until:ma.custom(iP),to:ma.custom(iP),level:ma.valid(ru.NOTIFY,ru.FATAL,ru.ERROR,ru.WARN,ru.INFO,ru.DEBUG,ru.TRACE),order:ma.valid("asc","desc"),limit:ma.number().min(1),start:ma.number().min(0),log_name:ma.custom(Jfe)});function iP(e,t){if(_Y(e,_Y.ISO_8601).format(jfe)==="Invalid date")return t.message(`'${t.state.path[0]}' date '${e}' is invalid.`)}a(iP,"validateDatetime");function Jfe(e,t){if(Wfe.invert(Fh.LOG_NAMES)[e]===void 0)return t.message(`'log_name' '${e}' is invalid.`);let n=Vfe.get(Fh.HDB_SETTINGS_NAMES.LOG_PATH_KEY),s=e===void 0?Fh.LOG_NAMES.HDB:e,i=s===Fh.LOG_NAMES.INSTALL?oP.join(zfe,Fh.LOG_NAMES.INSTALL):oP.join(n,s);return Yfe.existsSync(i)?null:t.message(`'log_name' '${e}' does not exist.`)}a(Jfe,"validateReadLogPath")});var cP=M((aFe,yY)=>{"use strict";var cy=(G(),D(j)),Xfe=J(),Zfe=fe(),eme=SY(),aP=require("path"),TY=require("fs-extra"),{once:tme}=require("events"),{handleHDBError:rme,hdbErrors:nme}=Ee(),{PACKAGE_ROOT:sme}=Rt(),{replicateOperation:ime}=(gs(),D(la)),ome=aP.join(sme,"logs"),ame=1e3,cme=200;yY.exports=lme;async function lme(e){let t=eme(e);if(t)throw rme(t,t.message,nme.HTTP_STATUS_CODES.BAD_REQUEST,void 0,void 0,!0);let r=ime(e),n=Zfe.get(cy.HDB_SETTINGS_NAMES.LOG_PATH_KEY),s=e.log_name===void 0?cy.LOG_NAMES.HDB:e.log_name,i=s===cy.LOG_NAMES.INSTALL?aP.join(ome,cy.LOG_NAMES.INSTALL):aP.join(n,s);e.to===void 0&&e.until!==void 0&&(e.to=e.until);let o=e.level!==void 0,c=o?e.level:void 0,l=e.from!==void 0,u=l?new Date(e.from):void 0,d=e.to!==void 0,f=d?new Date(e.to):void 0,m=e.limit===void 0?ame:e.limit,p=e.order===void 0?void 0:e.order,h=e.start===void 0?0:e.start,E=h+m,_=0;p==="desc"&&!u&&!f&&(_=Math.max(TY.statSync(i).size-(E+5)*cme,0));let R=TY.createReadStream(i,{start:_});R.on("error",q=>{Xfe.error(q)});let S=0,y=[],w="",I;R.on("data",q=>{let k=/(?:^|\n)(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:[\d.]+Z) \[(.+?)]: /g;q=w+q;let z=0,Y;for(;(Y=k.exec(q))&&!R.destroyed;){I&&(I.message=q.slice(z,Y.index),H(I));let[ce,de,te]=Y,Se=te.split("] ["),Ne=Se[0],Ke=Se[1];Se.splice(0,2),I={timestamp:de,thread:Ne,level:Ke,tags:Se,message:""},z=Y.index+ce.length}w=q.slice(z)}),R.on("end",q=>{R.destroyed||I&&(I.message=w.trim(),H(I))}),R.resume();function H(q){let k,z,Y;switch(!0){case(o&&l&&d):k=new Date(q.timestamp),z=new Date(u),Y=new Date(f),q.level===c&&k>=z&&k<=Y&&S<h?S++:q.level===c&&k>=z&&k<=Y&&(So(q,p,y),S++,S===E&&R.destroy());break;case(o&&l):k=new Date(q.timestamp),z=new Date(u),q.level===c&&k>=z&&S<h?S++:q.level===c&&k>=z&&(So(q,p,y),S++,S===E&&R.destroy());break;case(o&&d):k=new Date(q.timestamp),Y=new Date(f),q.level===c&&k<=Y&&S<h?S++:q.level===c&&k<=Y&&(So(q,p,y),S++,S===E&&R.destroy());break;case(l&&d):k=new Date(q.timestamp),z=new Date(u),Y=new Date(f),k>=z&&k<=Y&&S<h?S++:k>=z&&k<=Y&&(So(q,p,y),S++,S===E&&R.destroy());break;case o:q.level===c&&S<h?S++:q.level===c&&(So(q,p,y),S++,S===E&&R.destroy());break;case l:k=new Date(q.timestamp),z=new Date(u),k>=z&&S<h?S++:k>=z&&S>=h&&(So(q,p,y),S++,S===E&&R.destroy());break;case d:k=new Date(q.timestamp),Y=new Date(f),k<=Y&&S<h?S++:k<=Y&&S>=h&&(So(q,p,y),S++,S===E&&R.destroy());break;default:S<h?S++:(So(q,p,y),S++,S===E&&R.destroy())}}a(H,"onLogMessage"),await tme(R,"close");let X=await r;if(X.replicated){for(let q of y)q.node=server.hostname;for(let q of X.replicated){let k=q.node;if(q.status==="failed")So({timestamp:new Date().toISOString(),level:"error",node:k,message:`Error retrieving logs: ${q.reason}`},p,y);else for(let z of q.results)z.node=k,So(z,p,y)}}return y}a(lme,"readLog");function So(e,t,r){t==="desc"?ume(e,r):t==="asc"?dme(e,r):r.push(e)}a(So,"pushLineToResult");function ume(e,t){let r=new Date(e.timestamp),n=0,s=t.length;for(;n<s;){let i=n+s>>>1;new Date(t[i].timestamp)>r?n=i+1:s=i}t.splice(n,0,e)}a(ume,"insertDescending");function dme(e,t){let r=new Date(e.timestamp),n=0,s=t.length;for(;n<s;){let i=n+s>>>1;new Date(t[i].timestamp)<r?n=i+1:s=i}t.splice(n,0,e)}a(dme,"insertAscending")});var ly=M((mFe,IY)=>{"use strict";var lP=require("joi"),{string:gf,boolean:RY,date:fme}=lP.types(),mme=mt(),{validateSchemaExists:lFe,validateTableExists:uFe,validateSchemaName:dFe}=Xi(),pme=(G(),D(j)),hme=vt(),bY=fe();bY.initSync();var fFe=gf.invalid(bY.get(pme.CONFIG_PARAMS.CLUSTERING_NODENAME)??"node_name").pattern(hme.NATS_TERM_CONSTRAINTS_RX).messages({"string.pattern.base":"{:#label} invalid, must not contain ., * or >","any.invalid":"'node_name' cannot be this nodes name"}).empty(null),AY={operation:gf.valid("add_node","update_node","set_node_replication"),node_name:gf.optional(),subscriptions:lP.array().items({table:gf.optional(),schema:gf.optional(),database:gf.optional(),subscribe:RY.required(),publish:RY.required().custom(_me),start_time:fme.iso()})};function Eme(e){return mme.validateBySchema(e,lP.object(AY))}a(Eme,"addUpdateNodeValidator");function _me(e,t){if(t.state.ancestors[2].operation==="add_node"&&e===!1&&t.state.ancestors[0].subscribe===!1)return t.message(`'subscriptions[${t.state.path[1]}]' subscribe and/or publish must be set to true when adding a node`)}a(_me,"checkForFalsy");IY.exports={addUpdateNodeValidator:Eme,validationSchema:AY}});var Sf=M((hFe,wY)=>{"use strict";var uP=class{static{a(this,"Node")}constructor(t,r,n){this.name=t,this.subscriptions=r,this.system_info=n}},dP=class{static{a(this,"NodeSubscription")}constructor(t,r,n,s){this.schema=t,this.table=r,this.publish=n,this.subscribe=s}};wY.exports={Node:uP,NodeSubscription:dP}});var CY=M((_Fe,NY)=>{"use strict";var gme=(G(),D(j)).OPERATIONS_ENUM,fP=class{static{a(this,"UpsertObject")}constructor(t,r,n,s=void 0){this.operation=gme.UPSERT,this.schema=t,this.table=r,this.records=n,this.__origin=s}};NY.exports=fP});var kh=M((SFe,OY)=>{"use strict";var mP=class{static{a(this,"RemotePayloadObject")}constructor(t,r,n,s){this.operation=t,this.node_name=r,this.subscriptions=n,this.system_info=s}},pP=class{static{a(this,"RemotePayloadSubscription")}constructor(t,r,n,s,i,o,c){this.schema=t,this.table=r,this.hash_attribute=n,this.publish=s,this.subscribe=i,this.start_time=o,c!==void 0&&(this.attributes=c)}};OY.exports={RemotePayloadObject:mP,RemotePayloadSubscription:pP}});var LY=M((yFe,PY)=>{"use strict";var hP=class{static{a(this,"TableSizeObject")}constructor(t,r,n=0,s=0,i=0,o=0){this.schema=t,this.table=r,this.table_size=n,this.record_count=s,this.transaction_log_size=i,this.transaction_log_record_count=o}};PY.exports=hP});var vY=M((NFe,DY)=>{"use strict";var Sme=LY(),bFe=Qt(),AFe=gt(),Tme=J(),{getSchemaPath:IFe,getTransactionAuditStorePath:wFe}=bt(),{getDatabases:yme}=(Oe(),D(pt));DY.exports=Rme;async function Rme(e){let t=new Sme;try{let r=yme()[e.schema]?.[e.name],n=r.primaryStore.getStats(),s=r.auditStore?.getStats();t.schema=e.schema,t.table=e.name,t.record_count=n.entryCount,t.transaction_log_record_count=s.entryCount}catch(r){Tme.warn(`unable to stat table dbi due to ${r}`)}return t}a(Rme,"lmdbGetTableSize")});var UY=M((OFe,MY)=>{"use strict";var EP=class{static{a(this,"SystemInformationObject")}constructor(t,r,n,s,i,o,c){this.system=t,this.time=r,this.cpu=n,this.memory=s,this.disk=i,this.network=o,this.harperdb_processes=c}};MY.exports=EP});var Gh=M((UFe,kY)=>{"use strict";var bme=require("fs-extra"),Ame=require("path"),An=require("systeminformation"),wc=J(),xY=_r(),LFe=vt(),Tf=(G(),D(j)),Ime=vY(),wme=Kl(),{getThreadInfo:BY}=st(),Hh=fe();Hh.initSync();var Nme=UY(),{openEnvironment:DFe}=gt(),{getSchemaPath:vFe}=bt(),{database:MFe,databases:_P}=(Oe(),D(pt)),uy;kY.exports={getHDBProcessInfo:yP,getNetworkInfo:bP,getDiskInfo:RP,getMemoryInfo:TP,getCPUInfo:SP,getTimeInfo:gP,getSystemInformation:AP,systemInformation:Cme,getTableSize:IP,getMetrics:wP};function gP(){return An.time()}a(gP,"getTimeInfo");async function SP(){try{let{family:e,model:t,stepping:r,revision:n,voltage:s,speedmin:i,speedmax:o,governor:c,socket:l,cache:u,...d}=await An.cpu();d.cpu_speed=await An.cpuCurrentSpeed();let{rawCurrentload:f,rawCurrentloadIdle:m,rawCurrentloadIrq:p,rawCurrentloadNice:h,rawCurrentloadSystem:E,rawCurrentloadUser:_,cpus:R,...S}=await An.currentLoad();return S.cpus=[],R.forEach(y=>{let{rawLoad:w,rawLoadIdle:I,rawLoadIrq:H,rawLoadNice:X,rawLoadSystem:q,rawLoadUser:k,...z}=y;S.cpus.push(z)}),d.current_load=S,d}catch(e){return wc.error(`error in getCPUInfo: ${e}`),{}}}a(SP,"getCPUInfo");async function TP(){try{let{buffers:e,cached:t,slab:r,buffcache:n,...s}=await An.mem();return Object.assign(s,process.memoryUsage())}catch(e){return wc.error(`error in getMemoryInfo: ${e}`),{}}}a(TP,"getMemoryInfo");async function yP(){let e={core:[],clustering:[]};try{let t=await An.processes(),r;try{r=Number.parseInt(await bme.readFile(Ame.join(Hh.get(Tf.CONFIG_PARAMS.ROOTPATH),Tf.HDB_PID_FILE),"utf8"))}catch(n){if(n.code===Tf.NODE_ERROR_CODES.ENOENT)wc.warn("Unable to locate 'hdb.pid' file, try stopping and starting HarperDB. This could be because HarperDB is not running.");else throw n}t.list.forEach(n=>{n.pid===r?e.core.push(n):n.name==="nats-server"&&e.clustering.push(n)});for(let n of e.core)for(let s of t.list)s.pid===n.parentPid&&(s.name==="PM2"||s.command==="PM2")&&(n.parent="PM2");return e}catch(t){return wc.error(`error in getHDBProcessInfo: ${t}`),e}}a(yP,"getHDBProcessInfo");async function RP(){let e={};try{if(!Hh.get(Tf.CONFIG_PARAMS.OPERATIONSAPI_SYSINFO_DISK))return e;let{rIO_sec:t,wIO_sec:r,tIO_sec:n,ms:s,...i}=await An.disksIO();e.io=i;let{rxSec:o,txSec:c,wxSec:l,...u}=await An.fsStats();return e.read_write=u,e.size=await An.fsSize(),e}catch(t){return wc.error(`error in getDiskInfo: ${t}`),e}}a(RP,"getDiskInfo");async function bP(){let e={default_interface:null,latency:{},interfaces:[],stats:[],connections:[]};try{return Hh.get(Tf.CONFIG_PARAMS.OPERATIONSAPI_SYSINFO_NETWORK)&&(e.default_interface=await An.networkInterfaceDefault(),e.latency=await An.inetChecksite("google.com"),(await An.networkInterfaces()).forEach(n=>{let{internal:s,virtual:i,mtu:o,dhcp:c,dnsSuffix:l,ieee8021xAuth:u,ieee8021xState:d,carrierChanges:f,...m}=n;e.interfaces.push(m)}),(await An.networkStats()).forEach(n=>{let{rxSec:s,txSec:i,ms:o,...c}=n;e.stats.push(c)})),e}catch(t){return wc.error(`error in getNetworkInfo: ${t}`),e}}a(bP,"getNetworkInfo");async function AP(){if(uy!==void 0)return uy;let e={};try{let{codepage:t,logofile:r,serial:n,build:s,servicepack:i,uefi:o,...c}=await An.osInfo();e=c;let l=await An.versions("node, npm");return e.node_version=l.node,e.npm_version=l.npm,uy=e,uy}catch(t){return wc.error(`error in getSystemInformation: ${t}`),e}}a(AP,"getSystemInformation");async function IP(){let e=[],t=await wme.describeAll();for(let r of Object.values(t))for(let n of Object.values(r))e.push(await Ime(n));return e}a(IP,"getTableSize");async function wP(){let e={};for(let t in _P){let r=e[t]={},n=r.tables={};for(let s in _P[t])try{let i=_P[t][s];if(!r.readers&&(Object.assign(r,i.primaryStore.rootStore.getStats()),delete r.root,r.readers=i.primaryStore.rootStore.readerList().split(/\n\s+/).slice(1).map(l=>{let[u,d,f]=l.trim().split(" ");return{pid:u,thread:d,txnid:f}}),i.auditStore)){let{treeDepth:l,treeBranchPageCount:u,treeLeafPageCount:d,entryCount:f,overflowPages:m}=i.auditStore.getStats();r.audit={treeDepth:l,treeBranchPageCount:u,treeLeafPageCount:d,entryCount:f,overflowPages:m}}let o=i.primaryStore.getStats(),c={};for(let l of["treeDepth","treeBranchPageCount","treeLeafPageCount","entryCount","overflowPages"])c[l]=o[l];n[s]=c}catch(i){wc.notify(`Error getting stats for table ${s}: ${i}`)}}return e}a(wP,"getMetrics");async function FY(){if(Hh.get(Tf.CONFIG_PARAMS.CLUSTERING_ENABLED)){let{jsm:e}=await xY.getNATSReferences(),t=await xY.listStreams(),r=[];for(let n of t){let s=[],i=await e.consumers.list(n.config.name);for await(let c of i)s.push({name:c.name,created:c.created,num_ack_pending:c.num_ack_pending,num_redelivered:c.num_redelivered,num_waiting:c.num_waiting,num_pending:c.num_pending});let o={stream_name:n.config.name,database:n.config.subjects[0].split(".")[1],table:n.config.subjects[0].split(".")[2],state:n.state,consumers:s};r.push(o)}return r}}a(FY,"getNatsStreamInfo");async function Cme(e){let t=new Nme;if(!Array.isArray(e.attributes)||e.attributes.length===0)return t.system=await AP(),t.time=gP(),t.cpu=await SP(),t.memory=await TP(),t.disk=await RP(),t.network=await bP(),t.harperdb_processes=await yP(),t.table_size=await IP(),t.metrics=await wP(),t.threads=await BY(),t.replication=await FY(),t;for(let r=0;r<e.attributes.length;r++)switch(e.attributes[r]){case"system":t.system=await AP();break;case"time":t.time=gP();break;case"cpu":t.cpu=await SP();break;case"memory":t.memory=await TP();break;case"disk":t.disk=await RP();break;case"network":t.network=await bP();break;case"harperdb_processes":t.harperdb_processes=await yP();break;case"table_size":t.table_size=await IP();break;case"database_metrics":case"metrics":t.metrics=await wP();break;case"threads":t.threads=await BY();break;case"replication":t.replication=await FY();break;default:break}return t}a(Cme,"systemInformation")});var To=M((HFe,$Y)=>{"use strict";var Ome=Vn(),NP=ae(),Pme=require("util"),nu=(G(),D(j)),HY=fe();HY.initSync();var Lme=LC(),GY=Sn(),{Node:BFe,NodeSubscription:FFe}=Sf(),Dme=hd(),vme=CY(),{RemotePayloadObject:Mme,RemotePayloadSubscription:Ume}=kh(),{handleHDBError:xme,hdbErrors:Bme}=Ee(),{HTTP_STATUS_CODES:Fme,HDB_ERROR_MSGS:kme}=Bme,Hme=di(),Gme=Gh(),{packageJson:qme}=Rt(),{getDatabases:$me}=(Oe(),D(pt)),kFe=Pme.promisify(Lme.authorize),Vme=GY.searchByHash,Kme=GY.searchByValue;$Y.exports={isEmpty:Yme,getNodeRecord:Wme,upsertNodeRecord:jme,buildNodePayloads:zme,checkClusteringEnabled:Qme,getAllNodeRecords:Jme,getSystemInfo:Xme,reverseSubscription:qY};function Yme(e){return e==null}a(Yme,"isEmpty");async function Wme(e){let t=new Dme(nu.SYSTEM_SCHEMA_NAME,nu.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,[e],["*"]);return Vme(t)}a(Wme,"getNodeRecord");async function jme(e){let t=new vme(nu.SYSTEM_SCHEMA_NAME,nu.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,[e]);return Ome.upsert(t)}a(jme,"upsertNodeRecord");function qY(e){if(NP.isEmpty(e.subscribe)||NP.isEmpty(e.publish))throw new Error("Received invalid subscription object");let{schema:t,table:r,hash_attribute:n}=e,s={schema:t,table:r,hash_attribute:n};return e.subscribe===!0&&e.publish===!1?(s.subscribe=!1,s.publish=!0):e.subscribe===!1&&e.publish===!0?(s.subscribe=!0,s.publish=!1):(s.subscribe=e.subscribe,s.publish=e.publish),s}a(qY,"reverseSubscription");function zme(e,t,r,n){let s=[];for(let i=0,o=e.length;i<o;i++){let c=e[i],{schema:l,table:u}=c,d=NP.getTableHashAttribute(l,u),{subscribe:f,publish:m}=qY(c),p=$me()[l]?.[u],h=new Ume(l,u,d,m,f,c.start_time,p.schemaDefined?p.attributes:void 0);s.push(h)}return new Mme(r,t,s,n)}a(zme,"buildNodePayloads");function Qme(){if(!HY.get(nu.CONFIG_PARAMS.CLUSTERING_ENABLED))throw xme(new Error,kme.CLUSTERING_NOT_ENABLED,Fme.BAD_REQUEST,void 0,void 0,!0)}a(Qme,"checkClusteringEnabled");async function Jme(){let e=new Hme(nu.SYSTEM_SCHEMA_NAME,nu.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,"name","*",void 0,["*"]);return Array.from(await Kme(e))}a(Jme,"getAllNodeRecords");async function Xme(){let e=await Gme.getSystemInformation();return{hdb_version:qme.version,node_version:e.node_version,platform:e.platform}}a(Xme,"getSystemInfo")});var CP=M((qFe,JY)=>{"use strict";var dy=_r(),VY=ae(),KY=vt(),YY=(G(),D(j)),fy=J(),WY=iy(),Zme=Ip(),{RemotePayloadObject:epe}=kh(),{handleHDBError:jY,hdbErrors:tpe}=Ee(),{HTTP_STATUS_CODES:zY}=tpe,{NodeSubscription:QY}=Sf();JY.exports=rpe;async function rpe(e,t){let r;try{r=await dy.request(`${t}.${KY.REQUEST_SUFFIX}`,new epe(YY.OPERATIONS_ENUM.DESCRIBE_ALL,t,void 0,void 0)),fy.trace("Response from remote describe all request:",r)}catch(o){fy.error(`addNode received error from describe all request to remote node: ${o}`);let c=dy.requestErrorHandler(o,"add_node",t);throw jY(new Error,c,zY.INTERNAL_SERVER_ERROR,"error",c)}if(r.status===KY.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR){let o=`Error returned from remote node ${t}: ${r.message}`;throw jY(new Error,o,zY.INTERNAL_SERVER_ERROR,"error",o)}let n=r.message,s=[],i=[];for(let o of e){let{table:c}=o,l=o.database??o.schema??"data";if(l===YY.SYSTEM_SCHEMA_NAME){await dy.createLocalTableStream(l,c);let h=new QY(l,c,o.publish,o.subscribe);h.start_time=o.start_time,i.push(h);continue}let u=VY.doesSchemaExist(l),d=n[l]!==void 0,f=c?VY.doesTableExist(l,c):!0,m=c?n?.[l]?.[c]!==void 0:!0;if(!u&&!d||!f&&!m){s.push(o);continue}if(!u&&d&&(fy.trace(`addNode creating schema: ${l}`),await WY.createSchema({operation:"create_schema",schema:l})),!f&&m){fy.trace(`addNode creating table: ${c} in schema: ${l} with attributes ${JSON.stringify(n[l][c].attributes)}`);let h=new Zme(l,c,n[l][c].hash_attribute);n[l][c].attributes&&(h.attributes=n[l][c].attributes),await WY.createTable(h)}await dy.createLocalTableStream(l,c);let p=new QY(l,c,o.publish,o.subscribe);p.start_time=o.start_time,i.push(p)}return{added:i,skipped:s}}a(rpe,"reviewSubscriptions")});var yf={};ye(yf,{addNodeBack:()=>OP,removeNodeBack:()=>PP,setNode:()=>ope});async function ope(e){e.node_name&&!e.hostname&&(e.hostname=e.node_name),e.verify_tls!==void 0&&(e.rejectUnauthorized=e.verify_tls);let{url:t,hostname:r}=e;t?r||(r=e.hostname=yi(t)):t=ey(r);let n=(0,ZY.validateBySchema)(e,ipe);if(n)throw(0,pa.handleHDBError)(n,n.message,spe.BAD_REQUEST,void 0,void 0,!0);if(e.operation==="remove_node"){if(!t&&!r)throw new pa.ClientError("url or hostname is required for remove_node operation");let p=r,h=Gt(),E=await h.get(p);if(!E)throw new pa.ClientError(p+" does not exist");try{await xh({url:E.url},{operation:V.REMOVE_NODE_BACK,name:E?.subscriptions?.length>0?nt():p},void 0)}catch(_){ys.warn(`Error removing node from target node ${p}, if it is offline and we be online in the future, you may need to clean up this node manually, or retry:`,_)}return await h.delete(p),`Successfully removed '${p}' from cluster`}if(!t)throw new pa.ClientError("url required for this operation");let s=gc();if(s==null)throw new pa.ClientError("replication url is missing from harperdb-config.yaml");let i,o,c;if(t?.startsWith("wss:")){i=await(0,Ys.getReplicationCert)();let p=await(0,Ys.getReplicationCertAuth)();if(!i)throw new Error("Unable to find a certificate to use for replication");i.options.is_self_signed?(o=await(0,Ys.createCsr)(),ys.info("Sending CSR to target node:",t)):p&&(c=p.certificate,ys.info("Sending CA named",p.name,"to target node",t))}let l={operation:V.ADD_NODE_BACK,hostname:(0,Cc.get)(x.REPLICATION_HOSTNAME),target_hostname:r,url:s,csr:o,cert_auth:c,authorization:e.retain_authorization?e.authorization:null};if((0,Cc.get)(x.REPLICATION_SHARD)!==void 0&&(l.shard=(0,Cc.get)(x.REPLICATION_SHARD)),e.subscriptions?l.subscriptions=e.subscriptions.map(XY):l.subscriptions=null,e.hasOwnProperty("subscribe")||e.hasOwnProperty("publish")){let p=XY(e);l.subscribe=p.subscribe,l.publish=p.publish}e?.authorization?.username&&e?.authorization?.password&&(e.authorization="Basic "+Buffer.from(e.authorization.username+":"+e.authorization.password).toString("base64"));let u,d;try{u=await xh({url:t},l,e)}catch(p){p.message=`Error returned from ${t}: `+p.message,ys.warn("Error adding node:",t,"to cluster:",p),d=p}if(o&&(!u?.certificate||!u?.certificate?.includes?.("BEGIN CERTIFICATE")))throw d?(d.message+=" and connection was required to sign certificate",d):new Error(`Unexpected certificate signature response from node ${t} response: ${JSON.stringify(u)}`);o&&(ys.info("CSR response received from node:",t,"saving certificate and CA in hdb_certificate"),await(0,Ys.setCertTable)({name:npe.certificateFromPem(u.signingCA).issuer.getField("CN").value,certificate:u.signingCA,is_authority:!0}),u.certificate&&await(0,Ys.setCertTable)({name:nt(),uses:["https","operations","wss"],certificate:u.certificate,private_key_name:i?.options?.key_file,is_authority:!1,is_self_signed:!1}),c=u.signingCA);let f={url:t,ca:u?.usingCA};if(e.hostname&&(f.name=e.hostname),e.subscriptions?f.subscriptions=e.subscriptions:f.replicates=!0,e.start_time&&(f.start_time=typeof e.start_time=="string"?new Date(e.start_time).getTime():e.start_time),e.retain_authorization&&(f.authorization=e.authorization),e.revoked_certificates&&(f.revoked_certificates=e.revoked_certificates),u?.shard!==void 0?f.shard=u.shard:e.shard!==void 0&&(f.shard=e.shard),f.replicates){let p={url:s,ca:c,replicates:!0,subscriptions:null};(0,Cc.get)(x.REPLICATION_SHARD)!==void 0&&(p.shard=(0,Cc.get)(x.REPLICATION_SHARD)),e.retain_authorization&&(p.authorization=e.authorization),e.start_time&&(p.start_time=e.start_time),await aa(nt(),p)}await aa(u?u.nodeName:f.name??yi(t),f);let m;return e.operation==="update_node"?m=`Successfully updated '${t}'`:m=`Successfully added '${t}' to cluster`,d&&(m+=" but there was an error updating target node: "+d.message),m}async function OP(e){ys.trace("addNodeBack received request:",e);let t=await(0,Ys.signCertificate)(e),r;e.csr?(r=t.signingCA,ys.info("addNodeBack received CSR from node:",e.url,"this node will use and respond with CA that was used to issue CSR")):(r=e?.cert_auth,ys.info("addNodeBack received CA from node:",e.url));let n={url:e.url,ca:r};e.subscriptions?n.subscriptions=e.subscriptions:(n.replicates=!0,n.subscriptions=null),e.start_time&&(n.start_time=e.start_time),e.authorization&&(n.authorization=e.authorization),e.shard!==void 0&&(n.shard=e.shard);let s=await(0,Ys.getReplicationCertAuth)();if(n.replicates){let i={url:gc(),ca:s?.certificate,replicates:!0,subscriptions:null};(0,Cc.get)(x.REPLICATION_SHARD)!==void 0&&(i.shard=(0,Cc.get)(x.REPLICATION_SHARD),t.shard=i.shard),e.start_time&&(i.start_time=e.start_time),e.authorization&&(i.authorization=e.authorization),await aa(nt(),i)}return await aa(e.hostname,n),t.nodeName=nt(),t.usingCA=s?.certificate,ys.info("addNodeBack responding to:",e.url,"with CA named:",s?.name),t}async function PP(e){ys.trace("removeNodeBack received request:",e),await Gt().delete(e.name)}function XY(e){let{subscribe:t,publish:r}=e;return{...e,subscribe:r,publish:t}}var Ys,ZY,Nc,Cc,ys,pa,npe,spe,ipe,Rf=se(()=>{Ys=b(Ts()),ZY=b(mt()),Nc=b(require("joi")),Cc=b(fe());G();Nh();rf();gs();ys=b(J()),pa=b(Ee()),{pki:npe}=require("node-forge"),{HTTP_STATUS_CODES:spe}=pa.hdbErrors,ipe=Nc.default.object({hostname:Nc.default.string(),verify_tls:Nc.default.boolean(),replicates:Nc.default.boolean(),subscriptions:Nc.default.array(),revoked_certificates:Nc.default.array(),shard:Nc.default.number()});a(ope,"setNode");a(OP,"addNodeBack");a(PP,"removeNodeBack");a(XY,"reverseSubscription")});var Vh=M((JFe,tW)=>{"use strict";var{handleHDBError:my,hdbErrors:ape}=Ee(),{HTTP_STATUS_CODES:py}=ape,{addUpdateNodeValidator:cpe}=ly(),hy=J(),Ey=(G(),D(j)),eW=vt(),lpe=ae(),qh=_r(),$h=To(),LP=fe(),upe=CP(),{Node:dpe,NodeSubscription:fpe}=Sf(),{broadcast:mpe}=st(),{setNode:ppe}=(Rf(),D(yf)),zFe=fe(),QFe=(G(),D(j)),hpe="Unable to create subscriptions due to schema and/or tables not existing on the local or remote node",Epe="Some subscriptions were unsuccessful due to schema and/or tables not existing on the local or remote node",_pe=LP.get(Ey.CONFIG_PARAMS.CLUSTERING_NODENAME);tW.exports=gpe;async function gpe(e,t=!1){if(hy.trace("addNode called with:",e),LP.get(Ey.CONFIG_PARAMS.REPLICATION_URL)||LP.get(Ey.CONFIG_PARAMS.REPLICATION_HOSTNAME))return ppe(e);$h.checkClusteringEnabled();let r=cpe(e);if(r)throw my(r,r.message,py.BAD_REQUEST,void 0,void 0,!0);let n=e.node_name;if(!t){let f=await $h.getNodeRecord(n);if(!lpe.isEmptyOrZeroLength(f))throw my(new Error,`Node '${n}' has already been added, perform update_node to proceed.`,py.BAD_REQUEST,void 0,void 0,!0)}let{added:s,skipped:i}=await upe(e.subscriptions,n),o={message:void 0,added:s,skipped:i};if(s.length===0)return o.message=hpe,o;let c=$h.buildNodePayloads(s,_pe,Ey.OPERATIONS_ENUM.ADD_NODE,await $h.getSystemInfo()),l=[];for(let f=0,m=s.length;f<m;f++){let p=s[f];s[f].start_time===void 0&&delete s[f].start_time,l.push(new fpe(p.schema,p.table,p.publish,p.subscribe))}hy.trace("addNode sending remote payload:",c);let u;try{u=await qh.request(`${n}.${eW.REQUEST_SUFFIX}`,c)}catch(f){hy.error(`addNode received error from request: ${f}`);for(let p=0,h=s.length;p<h;p++){let E=s[p];E.publish=!1,E.subscribe=!1,await qh.updateRemoteConsumer(E,n)}let m=qh.requestErrorHandler(f,"add_node",n);throw my(new Error,m,py.INTERNAL_SERVER_ERROR,"error",m)}if(u.status===eW.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR){let f=`Error returned from remote node ${n}: ${u.message}`;throw my(new Error,f,py.INTERNAL_SERVER_ERROR,"error",f)}hy.trace(u);for(let f=0,m=s.length;f<m;f++){let p=s[f];await qh.updateRemoteConsumer(p,n),p.subscribe===!0&&await qh.updateConsumerIterator(p.schema,p.table,n,"start")}let d=new dpe(n,l,u.system_info);return await $h.upsertNodeRecord(d),mpe({type:"nats_update"}),i.length>0?o.message=Epe:o.message=`Successfully added '${n}' to manifest`,o}a(gpe,"addNode")});var UP=M((eke,nW)=>{"use strict";var{handleHDBError:DP,hdbErrors:Spe}=Ee(),{HTTP_STATUS_CODES:vP}=Spe,{addUpdateNodeValidator:Tpe}=ly(),Kh=J(),_y=(G(),D(j)),rW=vt(),ZFe=ae(),Yh=_r(),Wh=To(),MP=fe(),{cloneDeep:ype}=require("lodash"),Rpe=CP(),{Node:bpe,NodeSubscription:Ape}=Sf(),{broadcast:Ipe}=st(),{setNode:wpe}=(Rf(),D(yf)),Npe="Unable to update subscriptions due to schema and/or tables not existing on the local or remote node",Cpe="Some subscriptions were unsuccessful due to schema and/or tables not existing on the local or remote node",Ope=MP.get(_y.CONFIG_PARAMS.CLUSTERING_NODENAME);nW.exports=Ppe;async function Ppe(e){if(Kh.trace("updateNode called with:",e),MP.get(_y.CONFIG_PARAMS.REPLICATION_URL)??MP.get(_y.CONFIG_PARAMS.REPLICATION_HOSTNAME))return wpe(e);Wh.checkClusteringEnabled();let t=Tpe(e);if(t)throw DP(t,t.message,vP.BAD_REQUEST,void 0,void 0,!0);let r=e.node_name,n,s=await Wh.getNodeRecord(r);s.length>0&&(n=ype(s));let{added:i,skipped:o}=await Rpe(e.subscriptions,r),c={message:void 0,updated:i,skipped:o};if(i.length===0)return c.message=Npe,c;let l=Wh.buildNodePayloads(i,Ope,_y.OPERATIONS_ENUM.UPDATE_NODE,await Wh.getSystemInfo());for(let d=0,f=i.length;d<f;d++){let m=i[d];Kh.trace(`updateNode updating work stream for node: ${r} subscription:`,m),i[d].start_time===void 0&&delete i[d].start_time}Kh.trace("updateNode sending remote payload:",l);let u;try{u=await Yh.request(`${r}.${rW.REQUEST_SUFFIX}`,l)}catch(d){Kh.error(`updateNode received error from request: ${d}`);let f=Yh.requestErrorHandler(d,"update_node",r);throw DP(new Error,f,vP.INTERNAL_SERVER_ERROR,"error",f)}if(u.status===rW.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR){let d=`Error returned from remote node ${r}: ${u.message}`;throw DP(new Error,d,vP.INTERNAL_SERVER_ERROR,"error",d)}Kh.trace(u);for(let d=0,f=i.length;d<f;d++){let m=i[d];await Yh.updateRemoteConsumer(m,r),m.subscribe===!0?await Yh.updateConsumerIterator(m.schema,m.table,r,"start"):await Yh.updateConsumerIterator(m.schema,m.table,r,"stop")}return n||(n=[new bpe(r,[],u.system_info)]),await Lpe(n[0],i,u.system_info),o.length>0?c.message=Cpe:c.message=`Successfully updated '${r}'`,c}a(Ppe,"updateNode");async function Lpe(e,t,r){let n=e;for(let s=0,i=t.length;s<i;s++){let o=t[s],c=!1;for(let l=0,u=e.subscriptions.length;l<u;l++){let d=n.subscriptions[l];if(d.schema===o.schema&&d.table===o.table){d.publish=o.publish,d.subscribe=o.subscribe,c=!0;break}}c||n.subscriptions.push(new Ape(o.schema,o.table,o.publish,o.subscribe))}n.system_info=r,await Wh.upsertNodeRecord(n),Ipe({type:"nats_update"})}a(Lpe,"updateNodeTable")});var cW=M((rke,aW)=>{"use strict";var oW=require("joi"),{string:sW}=oW.types(),Dpe=mt(),iW=(G(),D(j)),vpe=fe(),Mpe=vt();aW.exports=Upe;function Upe(e){let t=sW.invalid(vpe.get(iW.CONFIG_PARAMS.CLUSTERING_NODENAME)).pattern(Mpe.NATS_TERM_CONSTRAINTS_RX).messages({"string.pattern.base":"{:#label} invalid, must not contain ., * or >","any.invalid":"'node_name' cannot be this nodes name"}).empty(null),r=oW.object({operation:sW.valid(iW.OPERATIONS_ENUM.REMOVE_NODE).required(),node_name:t});return Dpe.validateBySchema(e,r)}a(Upe,"removeNodeValidator")});var zh=M((ske,mW)=>{"use strict";var{handleHDBError:lW,hdbErrors:xpe}=Ee(),{HTTP_STATUS_CODES:uW}=xpe,Bpe=cW(),jh=J(),dW=To(),Fpe=ae(),bf=(G(),D(j)),fW=vt(),xP=_r(),BP=fe(),{RemotePayloadObject:kpe}=kh(),{NodeSubscription:Hpe}=Sf(),Gpe=Ap(),qpe=xl(),{broadcast:$pe}=st(),{setNode:Vpe}=(Rf(),D(yf)),Kpe=BP.get(bf.CONFIG_PARAMS.CLUSTERING_NODENAME);mW.exports=Ype;async function Ype(e){if(jh.trace("removeNode called with:",e),BP.get(bf.CONFIG_PARAMS.REPLICATION_URL)??BP.get(bf.CONFIG_PARAMS.REPLICATION_HOSTNAME))return Vpe(e);dW.checkClusteringEnabled();let t=Bpe(e);if(t)throw lW(t,t.message,uW.BAD_REQUEST,void 0,void 0,!0);let r=e.node_name,n=await dW.getNodeRecord(r);if(Fpe.isEmptyOrZeroLength(n))throw lW(new Error,`Node '${r}' was not found.`,uW.BAD_REQUEST,void 0,void 0,!0);n=n[0];let s=new kpe(bf.OPERATIONS_ENUM.REMOVE_NODE,Kpe,[]),i,o=!1;for(let l=0,u=n.subscriptions.length;l<u;l++){let d=n.subscriptions[l];d.subscribe===!0&&await xP.updateConsumerIterator(d.schema,d.table,r,"stop");try{await xP.updateRemoteConsumer(new Hpe(d.schema,d.table,!1,!1),r)}catch(f){jh.error(f)}}try{i=await xP.request(`${r}.${fW.REQUEST_SUFFIX}`,s),jh.trace("Remove node reply from remote node:",r,i)}catch(l){jh.error("removeNode received error from request:",l),o=!0}let c=new Gpe(bf.SYSTEM_SCHEMA_NAME,bf.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,[r]);return await qpe.deleteRecord(c),$pe({type:"nats_update"}),i?.status===fW.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR||o?(jh.error("Error returned from remote node:",r,i?.message),`Successfully removed '${r}' from local manifest, however there was an error reaching remote node. Check the logs for more details.`):`Successfully removed '${r}' from manifest`}a(Ype,"removeNode")});var EW=M((oke,hW)=>{"use strict";var pW=require("joi"),{string:Wpe,array:jpe}=pW.types(),zpe=mt(),Qpe=ly();hW.exports=Jpe;function Jpe(e){let t=pW.object({operation:Wpe.valid("configure_cluster").required(),connections:jpe.items(Qpe.validationSchema).required()});return zpe.validateBySchema(e,t)}a(Jpe,"configureClusterValidator")});var FP=M((cke,yW)=>{"use strict";var _W=(G(),D(j)),gy=J(),Xpe=ae(),Zpe=fe(),ehe=zh(),the=Vh(),rhe=To(),nhe=EW(),{handleHDBError:gW,hdbErrors:she}=Ee(),{HTTP_STATUS_CODES:SW}=she,ihe="Configure cluster complete.",ohe="Failed to configure the cluster. Check the logs for more details.",ahe="Configure cluster was partially successful. Errors occurred when attempting to configure the following nodes. Check the logs for more details.";yW.exports=che;async function che(e){gy.trace("configure cluster called with:",e);let t=nhe(e);if(t)throw gW(t,t.message,SW.BAD_REQUEST,void 0,void 0,!0);let r=await rhe.getAllNodeRecords(),n=[];if(Zpe.get(_W.CONFIG_PARAMS.CLUSTERING_ENABLED)){for(let d=0,f=r.length;d<f;d++){let m=await TW(ehe,{operation:_W.OPERATIONS_ENUM.REMOVE_NODE,node_name:r[d].name},r[d].name);n.push(m)}gy.trace("All results from configure_cluster remove node:",n)}let s=[],i=e.connections.length;for(let d=0;d<i;d++){let f=e.connections[d],m=await TW(the,f,f.node_name);s.push(m)}gy.trace("All results from configure_cluster add node:",s);let o=[],c=[],l=!1,u=n.concat(s);for(let d=0,f=u.length;d<f;d++){let m=u[d];m.status==="rejected"&&(gy.error(m.node_name,m?.error?.message,m?.error?.stack),o.includes(m.node_name)||o.push(m.node_name)),(m?.result?.message?.includes?.("Successfully")||m?.result?.includes?.("Successfully"))&&(l=!0),!(typeof m.result=="string"&&m.result.includes("Successfully removed")||m.status==="rejected")&&c.push({node_name:m?.node_name,response:m?.result})}if(Xpe.isEmptyOrZeroLength(o))return{message:ihe,connections:c};if(l)return{message:ahe,failed_nodes:o,connections:c};throw gW(new Error,ohe,SW.INTERNAL_SERVER_ERROR,void 0,void 0,!0)}a(che,"configureCluster");async function TW(e,t,r){try{return{node_name:r,result:await e(t)}}catch(n){return{node_name:r,error:n,status:"rejected"}}}a(TW,"functionWrapper")});var IW=M((uke,AW)=>{"use strict";var Qh=require("joi"),lhe=mt(),{validateSchemaExists:RW,validateTableExists:uhe,validateSchemaName:bW}=Xi(),dhe=Qh.object({operation:Qh.string().valid("purge_stream"),schema:Qh.string().custom(RW).custom(bW).optional(),database:Qh.string().custom(RW).custom(bW).optional(),table:Qh.string().custom(uhe).required()});function fhe(e){return lhe.validateBySchema(e,dhe)}a(fhe,"purgeStreamValidator");AW.exports=fhe});var kP=M((fke,wW)=>{"use strict";var{handleHDBError:mhe,hdbErrors:phe}=Ee(),{HTTP_STATUS_CODES:hhe}=phe,Ehe=IW(),_he=_r(),ghe=To();wW.exports=She;async function She(e){e.schema=e.schema??e.database;let t=Ehe(e);if(t)throw mhe(t,t.message,hhe.BAD_REQUEST,void 0,void 0,!0);ghe.checkClusteringEnabled();let{schema:r,table:n,options:s}=e;return await _he.purgeTableStream(r,n,s),`Successfully purged table '${r}.${n}'`}a(She,"purgeStream")});var yy=M((pke,MW)=>{"use strict";var GP=To(),The=_r(),Ty=fe(),Af=(G(),D(j)),su=vt(),yhe=ae(),HP=J(),{RemotePayloadObject:Rhe}=kh(),{ErrorCode:NW}=require("nats"),{parentPort:CW}=require("worker_threads"),{onMessageByType:bhe}=st(),{getThisNodeName:Ahe}=(gs(),D(la)),{requestClusterStatus:Ihe}=(Nh(),D(R1)),{getReplicationSharedStatus:whe,getHDBNodeTable:Nhe}=(rf(),D(h1)),{CONFIRMATION_STATUS_POSITION:Che,RECEIVED_VERSION_POSITION:OW,RECEIVED_TIME_POSITION:Ohe,SENDING_TIME_POSITION:Phe,RECEIVING_STATUS_POSITION:Lhe,RECEIVING_STATUS_RECEIVING:Dhe,BACK_PRESSURE_RATIO_POSITION:vhe}=(vO(),D(fK)),PW=Ty.get(Af.CONFIG_PARAMS.CLUSTERING_ENABLED),LW=Ty.get(Af.CONFIG_PARAMS.CLUSTERING_NODENAME);MW.exports={clusterStatus:Mhe,buildNodeStatus:vW};var DW;bhe("cluster-status",async e=>{DW(e)});async function Mhe(){if(Ty.get(Af.CONFIG_PARAMS.REPLICATION_URL)||Ty.get(Af.CONFIG_PARAMS.REPLICATION_HOSTNAME)){let n;CW?(CW.postMessage({type:"request-cluster-status"}),n=await new Promise(i=>{DW=i})):n=Ihe();for(let i of n.connections){let o=i.name;for(let c of i.database_sockets){let l=c.database,u;for(let f of Object.values(databases[l]||{}))if(u=f.auditStore,u)break;if(!u)continue;let d=whe(u,l,o);c.lastCommitConfirmed=Sy(d[Che]),c.lastReceivedRemoteTime=Sy(d[OW]),c.lastReceivedLocalTime=Sy(d[Ohe]),c.lastReceivedVersion=d[OW],c.sendingMessage=Sy(d[Phe]),c.backPressurePercent=d[vhe]*100,c.lastReceivedStatus=d[Lhe]===Dhe?"Receiving":"Waiting"}}n.node_name=Ahe();let s=Nhe().primaryStore.get(n.node_name);return s?.shard&&(n.shard=s.shard),s?.url&&(n.url=s.url),n.is_enabled=!0,n}let e={node_name:LW,is_enabled:PW,connections:[]};if(!PW)return e;let t=await GP.getAllNodeRecords();if(yhe.isEmptyOrZeroLength(t))return e;let r=[];for(let n=0,s=t.length;n<s;n++)r.push(vW(t[n],e.connections));return await Promise.allSettled(r),e}a(Mhe,"clusterStatus");function Sy(e){return e?e===1?"Copying":new Date(e).toUTCString():void 0}a(Sy,"asDate");async function vW(e,t){let r=e.name,n=new Rhe(Af.OPERATIONS_ENUM.CLUSTER_STATUS,LW,void 0,await GP.getSystemInfo()),s,i,o=su.CLUSTER_STATUS_STATUSES.OPEN;try{let l=Date.now();s=await The.request(su.REQUEST_SUBJECT(r),n),i=Date.now()-l,s.status===su.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR&&(o=su.CLUSTER_STATUS_STATUSES.CLOSED,HP.error(`Error getting node status from ${r} `,s))}catch(l){HP.warn(`Error getting node status from ${r}`,l),l.code===NW.NoResponders?o=su.CLUSTER_STATUS_STATUSES.NO_RESPONDERS:l.code===NW.Timeout?o=su.CLUSTER_STATUS_STATUSES.TIMEOUT:o=su.CLUSTER_STATUS_STATUSES.CLOSED}let c=new Uhe(r,o,s?.message?.ports?.clustering,s?.message?.ports?.operations_api,i,s?.message?.uptime,e.subscriptions,s?.message?.system_info);try{let l={name:r,system_info:s?.message?.system_info};e.system_info?.hdb_version!==Af.PRE_4_0_0_VERSION&&await GP.upsertNodeRecord(l)}catch(l){HP.error("Cluster status encountered an error updating system info for node:",r,l)}t.push(c)}a(vW,"buildNodeStatus");function Uhe(e,t,r,n,s,i,o,c){this.node_name=e,this.status=t,this.ports={clustering:r,operations_api:n},this.latency_ms=s,this.uptime=i,this.subscriptions=o,this.system_info=c}a(Uhe,"NodeStatusObject")});var $P=M((Eke,UW)=>{"use strict";var{handleHDBError:xhe,hdbErrors:Bhe}=Ee(),{HTTP_STATUS_CODES:Fhe}=Bhe,khe=_r(),Hhe=To(),qP=ae(),Ry=require("joi"),Ghe=mt(),qhe=2e3,$he=Ry.object({timeout:Ry.number().min(1),connected_nodes:Ry.boolean(),routes:Ry.boolean()});UW.exports=Vhe;async function Vhe(e){Hhe.checkClusteringEnabled();let t=Ghe.validateBySchema(e,$he);if(t)throw xhe(t,t.message,Fhe.BAD_REQUEST,void 0,void 0,!0);let{timeout:r,connected_nodes:n,routes:s}=e,i=n===void 0||qP.autoCastBoolean(n),o=s===void 0||qP.autoCastBoolean(s),c={nodes:[]},l=await khe.getServerList(r??qhe),u={};if(i)for(let d=0,f=l.length;d<f;d++){let m=l[d].statsz;m&&(u[l[d].server.name]=m.routes)}for(let d=0,f=l.length;d<f;d++){if(l[d].statsz)continue;let m=l[d].server,p=l[d].data;if(m.name.endsWith("-hub")){let h={name:m.name.slice(0,-4),response_time:l[d].response_time};i&&(h.connected_nodes=[],u[m.name]&&u[m.name].forEach(E=>{h.connected_nodes.includes(E.name.slice(0,-4))||h.connected_nodes.push(E.name.slice(0,-4))})),o&&(h.routes=p.cluster?.urls?p.cluster?.urls.map(E=>({host:E.split(":")[0],port:qP.autoCast(E.split(":")[1])})):[]),c.nodes.push(h)}}return c}a(Vhe,"clusterNetwork")});var kW=M((gke,FW)=>{"use strict";var VP=require("joi"),xW=mt(),{routeConstraints:BW}=fA();FW.exports={setRoutesValidator:Khe,deleteRoutesValidator:Yhe};function Khe(e){let t=VP.object({server:VP.valid("hub","leaf"),routes:BW.required()});return xW.validateBySchema(e,t)}a(Khe,"setRoutesValidator");function Yhe(e){let t=VP.object({routes:BW.required()});return xW.validateBySchema(e,t)}a(Yhe,"deleteRoutesValidator")});var by=M((Tke,YW)=>{"use strict";var ha=_t(),KP=ae(),Ws=(G(),D(j)),If=fe(),HW=kW(),{handleHDBError:GW,hdbErrors:Whe}=Ee(),{HTTP_STATUS_CODES:qW}=Whe,$W="cluster routes successfully set",VW="cluster routes successfully deleted";YW.exports={setRoutes:zhe,getRoutes:Qhe,deleteRoutes:Jhe};function jhe(e){let t=ha.getClusteringRoutes(),r=e.server==="hub"?t.hub_routes:t.leaf_routes,n=e.server==="hub"?t.leaf_routes:t.hub_routes,s=[],i=[];for(let o=0,c=e.routes.length;o<c;o++){let l=e.routes[o];l.port=KP.autoCast(l.port);let u=r.some(f=>f.host===l.host&&f.port===l.port),d=n.some(f=>f.host===l.host&&f.port===l.port);u||d?s.push(l):(r.push(l),i.push(l))}return e.server==="hub"?ha.updateConfigValue(Ws.CONFIG_PARAMS.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_ROUTES,r):ha.updateConfigValue(Ws.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_ROUTES,r),{message:$W,set:i,skipped:s}}a(jhe,"setRoutesNats");function zhe(e){let t=HW.setRoutesValidator(e);if(t)throw GW(t,t.message,qW.BAD_REQUEST,void 0,void 0,!0);if(If.get(Ws.CONFIG_PARAMS.CLUSTERING_ENABLED))return jhe(e);let r=[],n=[],s=If.get(Ws.CONFIG_PARAMS.REPLICATION_ROUTES)??[];return e.routes.forEach(i=>{KW(s,i)?n.push(i):(s.push(i),r.push(i))}),ha.updateConfigValue(Ws.CONFIG_PARAMS.REPLICATION_ROUTES,s),{message:$W,set:r,skipped:n}}a(zhe,"setRoutes");function KW(e,t){return typeof t=="string"?e.includes(t):typeof t=="object"&&t!==null?e.some(r=>(r.host===t.host||r.hostname===t.hostname)&&r.port===t.port):!1}a(KW,"existsInArray");function Qhe(){if(If.get(Ws.CONFIG_PARAMS.CLUSTERING_ENABLED)){let e=ha.getClusteringRoutes();return{hub:e.hub_routes,leaf:e.leaf_routes}}else return If.get(Ws.CONFIG_PARAMS.REPLICATION_ROUTES)??[]}a(Qhe,"getRoutes");function Jhe(e){let t=HW.deleteRoutesValidator(e);if(t)throw GW(t,t.message,qW.BAD_REQUEST,void 0,void 0,!0);if(If.get(Ws.CONFIG_PARAMS.CLUSTERING_ENABLED))return Xhe(e);let r=[],n=[],s=If.get(Ws.CONFIG_PARAMS.REPLICATION_ROUTES)??[],i=[];return s.forEach(o=>{KW(e.routes,o)?r.push(o):(i.push(o),n.push(o))}),ha.updateConfigValue(Ws.CONFIG_PARAMS.REPLICATION_ROUTES,i),{message:VW,deleted:r,skipped:n}}a(Jhe,"deleteRoutes");function Xhe(e){let t=ha.getClusteringRoutes(),r=t.hub_routes,n=t.leaf_routes,s=[],i=[],o=!1,c=!1;for(let l=0,u=e.routes.length;l<u;l++){let d=e.routes[l],f=!1;for(let m=0,p=r.length;m<p;m++){let h=r[m];if(d.host===h.host&&d.port===h.port){r.splice(m,1),f=!0,o=!0,s.push(d);break}}if(!f){let m=!0;for(let p=0,h=n.length;p<h;p++){let E=n[p];if(d.host===E.host&&d.port===E.port){n.splice(p,1),c=!0,m=!1,s.push(d);break}}m&&i.push(d)}}return o&&(r=KP.isEmptyOrZeroLength(r)?null:r,ha.updateConfigValue(Ws.CONFIG_PARAMS.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_ROUTES,r)),c&&(n=KP.isEmptyOrZeroLength(n)?null:n,ha.updateConfigValue(Ws.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_ROUTES,n)),{message:VW,deleted:s,skipped:i}}a(Xhe,"deleteRoutesNats")});var jW=M((Rke,WW)=>{"use strict";var Zhe=vt(),YP=class{static{a(this,"HubConfigObject")}constructor(t,r,n,s,i,o,c,l,u,d,f,m,p,h){this.port=t,o===null&&(o=void 0),this.server_name=r+Zhe.SERVER_SUFFIX.HUB,this.pid_file=n,this.max_payload=67108864,this.reconnect_error_reports=100,this.jetstream={enabled:!1},this.tls={cert_file:s,key_file:i,ca_file:o,insecure:c,verify:l},this.leafnodes={port:u,tls:{cert_file:s,key_file:i,ca_file:o,insecure:c}},this.cluster={name:d,port:f,routes:m,tls:{cert_file:s,key_file:i,ca_file:o,insecure:c,verify:l}},this.accounts={SYS:{users:p},HDB:{users:h}},this.system_account="SYS"}};WW.exports=YP});var JW=M((Ake,QW)=>{"use strict";var zW=vt(),WP=class{static{a(this,"LeafConfigObject")}constructor(t,r,n,s,i,o,c,l,u,d,f){this.port=t,f===null&&(f=void 0),this.server_name=r+zW.SERVER_SUFFIX.LEAF,this.pid_file=n,this.max_payload=67108864,this.jetstream={enabled:!0,store_dir:s,domain:r+zW.SERVER_SUFFIX.LEAF},this.tls={cert_file:u,key_file:d,ca_file:f,insecure:!0},this.leafnodes={remotes:[{tls:{ca_file:f,insecure:!0},urls:i,account:"SYS"},{tls:{ca_file:f,insecure:!0},urls:o,account:"HDB"}]},this.accounts={SYS:{users:c},HDB:{users:l,jetstream:"enabled"}},this.system_account="SYS"}};QW.exports=WP});var ZW=M((wke,XW)=>{"use strict";var jP=class{static{a(this,"HdbUserObject")}constructor(t,r){this.user=t,this.password=r}};XW.exports=jP});var tj=M((Cke,ej)=>{"use strict";var eEe=vt(),zP=class{static{a(this,"SysUserObject")}constructor(t,r){this.user=t+eEe.SERVER_SUFFIX.ADMIN,this.password=r}};ej.exports=zP});var Ny=M((Pke,sj)=>{"use strict";var iu=require("path"),ou=require("fs-extra"),tEe=jW(),rEe=JW(),nEe=ZW(),sEe=tj(),QP=(hs(),D(ao)),Nf=ae(),Wn=_t(),Iy=(G(),D(j)),Jh=vt(),{CONFIG_PARAMS:cr}=Iy,Cf=J(),Xh=fe(),rj=so(),JP=_r(),iEe=Ts(),wf="clustering",oEe=1e4,nj=50;sj.exports={generateNatsConfig:cEe,removeNatsConfig:lEe,getHubConfigPath:aEe};function aEe(){let e=Xh.get(cr.ROOTPATH);return iu.join(e,wf,Jh.NATS_CONFIG_FILES.HUB_SERVER)}a(aEe,"getHubConfigPath");async function cEe(e=!1,t=void 0){console.error("Warning: NATS replication is deprecated and will be removed in version 5.0 of Harper");let r=Xh.get(cr.ROOTPATH);ou.ensureDirSync(iu.join(r,"clustering","leaf")),Xh.initSync();let n=Wn.getConfigFromFile(cr.CLUSTERING_TLS_CERT_AUTH),s=Wn.getConfigFromFile(cr.CLUSTERING_TLS_PRIVATEKEY),i=Wn.getConfigFromFile(cr.CLUSTERING_TLS_CERTIFICATE);!await ou.exists(i)&&!await ou.exists(!n)&&await iEe.createNatsCerts();let o=iu.join(r,wf,Jh.PID_FILES.HUB),c=iu.join(r,wf,Jh.PID_FILES.LEAF),l=Wn.getConfigFromFile(cr.CLUSTERING_LEAFSERVER_STREAMS_PATH),u=iu.join(r,wf,Jh.NATS_CONFIG_FILES.HUB_SERVER),d=iu.join(r,wf,Jh.NATS_CONFIG_FILES.LEAF_SERVER),f=Wn.getConfigFromFile(cr.CLUSTERING_TLS_INSECURE),m=Wn.getConfigFromFile(cr.CLUSTERING_TLS_VERIFY),p=Wn.getConfigFromFile(cr.CLUSTERING_NODENAME),h=Wn.getConfigFromFile(cr.CLUSTERING_HUBSERVER_LEAFNODES_NETWORK_PORT);await JP.checkNATSServerInstalled()||wy("nats-server dependency is either missing or the wrong version. Run 'npm install' to fix");let E=await QP.listUsers(),_=Wn.getConfigFromFile(cr.CLUSTERING_USER),R=await QP.getClusterUser();(Nf.isEmpty(R)||R.active!==!0)&&wy(`Invalid cluster user '${_}'. A valid user with the role 'cluster_user' must be defined under clustering.user in harperdb-config.yaml`),e||(await Ay(cr.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT),await Ay(cr.CLUSTERING_HUBSERVER_LEAFNODES_NETWORK_PORT),await Ay(cr.CLUSTERING_HUBSERVER_NETWORK_PORT),await Ay(cr.CLUSTERING_LEAFSERVER_NETWORK_PORT));let S=[],y=[];for(let[z,Y]of E.entries())Y.role?.role===Iy.ROLE_TYPES_ENUM.CLUSTER_USER&&Y.active&&(S.push(new sEe(Y.username,rj.decrypt(Y.hash))),y.push(new nEe(Y.username,rj.decrypt(Y.hash))));let w=[],{hub_routes:I}=Wn.getClusteringRoutes();if(!Nf.isEmptyOrZeroLength(I))for(let z of I)w.push(`tls://${R.sys_name_encoded}:${R.uri_encoded_d_hash}@${z.host}:${z.port}`);let H=new tEe(Wn.getConfigFromFile(cr.CLUSTERING_HUBSERVER_NETWORK_PORT),p,o,i,s,n,f,m,h,Wn.getConfigFromFile(cr.CLUSTERING_HUBSERVER_CLUSTER_NAME),Wn.getConfigFromFile(cr.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT),w,S,y);n==null&&(delete H.tls.ca_file,delete H.leafnodes.tls.ca_file),t=Nf.isEmpty(t)?void 0:t.toLowerCase(),(t===void 0||t===Iy.PROCESS_DESCRIPTORS.CLUSTERING_HUB.toLowerCase())&&(await ou.writeJson(u,H),Cf.trace(`Hub server config written to ${u}`));let X=`tls://${R.sys_name_encoded}:${R.uri_encoded_d_hash}@0.0.0.0:${h}`,q=`tls://${R.uri_encoded_name}:${R.uri_encoded_d_hash}@0.0.0.0:${h}`,k=new rEe(Wn.getConfigFromFile(cr.CLUSTERING_LEAFSERVER_NETWORK_PORT),p,c,l,[X],[q],S,y,i,s,n,f);n==null&&delete k.tls.ca_file,(t===void 0||t===Iy.PROCESS_DESCRIPTORS.CLUSTERING_LEAF.toLowerCase())&&(await ou.writeJson(d,k),Cf.trace(`Leaf server config written to ${d}`))}a(cEe,"generateNatsConfig");async function Ay(e){let t=Xh.get(e);return Nf.isEmpty(t)&&wy(`port undefined for '${e}'`),await Nf.isPortTaken(t)&&wy(`'${e}' port '${t}' is is in use by another process, check to see if HarperDB is already running or another process is using this port.`),!0}a(Ay,"isPortAvailable");function wy(e){let t=`Error generating clustering config: ${e}`;Cf.error(t),console.error(t),process.exit(1)}a(wy,"generateNatsConfigError");async function lEe(e){let{port:t,config_file:r}=JP.getServerConfig(e),{username:n,decrypt_hash:s}=await QP.getClusterUser(),i=0,o=2e3;for(;i<nj;){try{let d=await JP.createConnection(t,n,s,!1);if(d.protocol.connected===!0){d.close();break}}catch(d){Cf.trace(`removeNatsConfig waiting for ${e}. Caught and swallowed error ${d}`)}if(i++,i>=nj)throw new Error(`Operations API timed out attempting to connect to ${e}. This is commonly caused by incorrect clustering config. Check hdb.log for further details.`);let u=o*(i*2);u>3e4&&Cf.notify("Operations API waiting for Nats server connection. This could be caused by large Nats streams or incorrect clustering config."),await Nf.asyncSetTimeout(u)}let c="0".repeat(oEe),l=iu.join(Xh.get(cr.ROOTPATH),wf,r);await ou.writeFile(l,c),await ou.remove(l),Cf.notify(e,"started.")}a(lEe,"removeNatsConfig")});var uj=M((Dke,lj)=>{"use strict";var Rs=fe(),et=(G(),D(j)),Zh=vt(),Ea=require("path"),{PACKAGE_ROOT:Oy}=Rt(),ij=fe(),Cy=ae(),Of="/dev/null",uEe=Ea.join(Oy,"launchServiceScripts"),oj=Ea.join(Oy,"utility/scripts"),dEe=Ea.join(oj,et.HDB_RESTART_SCRIPT),aj=Ea.resolve(Oy,"dependencies",`${process.platform}-${process.arch}`,Zh.NATS_BINARY_NAME);function cj(){let e={[et.PROCESS_NAME_ENV_PROP]:et.PROCESS_DESCRIPTORS.HDB,IS_SCRIPTED_SERVICE:!0,...process.env};return Cy.noBootFile()&&(e[et.CONFIG_PARAMS.ROOTPATH.toUpperCase()]=Cy.getEnvCliRootPath()),{name:et.PROCESS_DESCRIPTORS.HDB,script:et.LAUNCH_SERVICE_SCRIPTS.MAIN,exec_mode:"fork",env:e,execArgv:process.execArgv,cwd:Oy}}a(cj,"generateMainServerConfig");var fEe=9930;function mEe(){Rs.initSync(!0);let e=Rs.get(et.CONFIG_PARAMS.ROOTPATH),t=Ea.join(e,"clustering",Zh.NATS_CONFIG_FILES.HUB_SERVER),r=Ea.join(Rs.get(et.HDB_SETTINGS_NAMES.LOG_PATH_KEY),et.LOG_NAMES.HDB),n=ij.get(et.CONFIG_PARAMS.CLUSTERING_HUBSERVER_NETWORK_PORT),s=Zh.LOG_LEVEL_FLAGS[Rs.get(et.CONFIG_PARAMS.CLUSTERING_LOGLEVEL)]??void 0,i={name:et.PROCESS_DESCRIPTORS.CLUSTERING_HUB+(n!==fEe?"-"+n:""),binFile:aj,args:s?`${s} -c ${t}`:`-c ${t}`,exec_mode:"fork",env:{[et.PROCESS_NAME_ENV_PROP]:et.PROCESS_DESCRIPTORS.CLUSTERING_HUB},merge_logs:!0,out_file:r,error_file:r,instances:1};return Rs.get(et.HDB_SETTINGS_NAMES.LOG_TO_FILE)||(i.out_file=Of,i.error_file=Of),i}a(mEe,"generateNatsHubServerConfig");var pEe=9940;function hEe(){Rs.initSync(!0);let e=Rs.get(et.CONFIG_PARAMS.ROOTPATH),t=Ea.join(e,"clustering",Zh.NATS_CONFIG_FILES.LEAF_SERVER),r=Ea.join(Rs.get(et.HDB_SETTINGS_NAMES.LOG_PATH_KEY),et.LOG_NAMES.HDB),n=ij.get(et.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_PORT),s=Zh.LOG_LEVEL_FLAGS[Rs.get(et.CONFIG_PARAMS.CLUSTERING_LOGLEVEL)]??void 0,i={name:et.PROCESS_DESCRIPTORS.CLUSTERING_LEAF+(n!==pEe?"-"+n:""),binFile:aj,args:s?`${s} -c ${t}`:`-c ${t}`,exec_mode:"fork",env:{[et.PROCESS_NAME_ENV_PROP]:et.PROCESS_DESCRIPTORS.CLUSTERING_LEAF},merge_logs:!0,out_file:r,error_file:r,instances:1};return Rs.get(et.HDB_SETTINGS_NAMES.LOG_TO_FILE)||(i.out_file=Of,i.error_file=Of),i}a(hEe,"generateNatsLeafServerConfig");function EEe(){Rs.initSync();let e=Ea.join(Rs.get(et.CONFIG_PARAMS.LOGGING_ROOT),et.LOG_NAMES.HDB),t={name:et.PROCESS_DESCRIPTORS.CLUSTERING_UPGRADE_4_0_0,binFile:et.LAUNCH_SERVICE_SCRIPTS.NODES_UPGRADE_4_0_0,exec_mode:"fork",env:{[et.PROCESS_NAME_ENV_PROP]:et.PROCESS_DESCRIPTORS.CLUSTERING_UPGRADE_4_0_0},merge_logs:!0,out_file:e,error_file:e,instances:1,cwd:uEe,autorestart:!1};return Rs.get(et.HDB_SETTINGS_NAMES.LOG_TO_FILE)||(t.out_file=Of,t.error_file=Of),t}a(EEe,"generateClusteringUpgradeV4ServiceConfig");function _Ee(){let e={[et.PROCESS_NAME_ENV_PROP]:et.PROCESS_DESCRIPTORS.RESTART_HDB};return Cy.noBootFile()&&(e[et.CONFIG_PARAMS.ROOTPATH.toUpperCase()]=Cy.getEnvCliRootPath()),{...{name:et.PROCESS_DESCRIPTORS.RESTART_HDB,exec_mode:"fork",env:e,instances:1,autorestart:!1,cwd:oj},script:dEe}}a(_Ee,"generateRestart");function gEe(){return{apps:[cj()]}}a(gEe,"generateAllServiceConfigs");lj.exports={generateAllServiceConfigs:gEe,generateMainServerConfig:cj,generateRestart:_Ee,generateNatsHubServerConfig:mEe,generateNatsLeafServerConfig:hEe,generateClusteringUpgradeV4ServiceConfig:EEe}});var au=M((Uke,_j)=>{"use strict";var Pr=(G(),D(j)),Mke=ae(),ga=Ny(),Py=_r(),_a=vt(),Oc=uj(),ZP=fe(),Pc=J(),SEe=To(),{startWorker:dj,onMessageFromWorkers:TEe}=st(),fj=require("fs"),yEe=require("node:path"),REe=(G(),D(j)),{setTimeout:bEe}=require("node:timers/promises"),{execFile:AEe,fork:IEe}=require("node:child_process");_j.exports={start:Lc,restart:NEe,kill:LEe,startAllServices:DEe,startService:pj,restartHdb:CEe,startClusteringProcesses:hj,startClusteringThreads:Ej,isHdbRestartRunning:OEe,getHdbPid:PEe,cleanupChildrenProcesses:eE,reloadClustering:MEe,expectedRestartOfChildren:mj};TEe(e=>{e.type==="restart"&&ZP.initSync(!0)});var yo=[],wEe=10,XP;function Lc(e,t=!1){let r=typeof e.args=="string"?e.args.split(" "):e.args;e.silent=!0,e.detached=!0;let n=e.script?IEe(e.script,r,e):AEe(e.binFile,r,e);n.name=e.name,n.config=e,n.on("error",(o,c)=>{console.error(o,c)}),n.on("exit",async o=>{let c=yo.indexOf(n);c>-1&&yo.splice(c,1),!XP&&o!==0&&(e.restarts=(e.restarts||0)+1,e.restarts<wEe&&(fj.existsSync(ga.getHubConfigPath())?Lc(e):(await ga.generateNatsConfig(!0),Lc(e),await new Promise(l=>setTimeout(l,3e3)),await ga.removeNatsConfig(Pr.PROCESS_DESCRIPTORS.CLUSTERING_HUB),await ga.removeNatsConfig(Pr.PROCESS_DESCRIPTORS.CLUSTERING_LEAF))))});let s={serviceName:e.name.replace(/ /g,"-")};function i(o){let c=ZP.get(Pr.CONFIG_PARAMS.CLUSTERING_LOGLEVEL),l=/\[\d+][^\[]+\[(\w+)]/g,u,d=0,f;for(;u=l.exec(o);){if(u.index&&_a.LOG_LEVEL_HIERARCHY[c]>=_a.LOG_LEVEL_HIERARCHY[f||"info"]){let h=f===_a.LOG_LEVELS.ERR||f===_a.LOG_LEVELS.WRN?Pc.OUTPUTS.STDERR:Pc.OUTPUTS.STDOUT;Pc.logCustomLevel(f||"info",h,s,o.slice(d,u.index).trim())}let[m,p]=u;d=u.index+m.length,f=_a.LOG_LEVELS[p]}if(_a.LOG_LEVEL_HIERARCHY[c]>=_a.LOG_LEVEL_HIERARCHY[f||"info"]){let m=f===_a.LOG_LEVELS.ERR||f===_a.LOG_LEVELS.WRN?Pc.OUTPUTS.STDERR:Pc.OUTPUTS.STDOUT;Pc.logCustomLevel(f||"info",m,s,o.toString().slice(d).trim())}}a(i,"extractMessages"),n.stdout.on("data",i),n.stderr.on("data",i),n.unref(),yo.length===0&&(t||(process.on("exit",eE),process.on("SIGINT",eE),process.on("SIGQUIT",eE),process.on("SIGTERM",eE))),yo.push(n)}a(Lc,"start");function eE(e=!0){if(!XP&&(XP=!0,yo.length!==0))if(Pc.info("Killing child processes..."),yo.map(t=>t.kill()),e)process.exit(0);else return bEe(2e3)}a(eE,"cleanupChildrenProcesses");function NEe(e){mj();for(let t of yo)t.name===e&&t.kill()}a(NEe,"restart");function mj(){for(let e of yo)e.config&&(e.config.restarts=0)}a(mj,"expectedRestartOfChildren");async function CEe(){await Lc(Oc.generateRestart())}a(CEe,"restartHdb");async function OEe(){let e=await list();for(let t in e)if(e[t].name===Pr.PROCESS_DESCRIPTORS.RESTART_HDB)return!0;return!1}a(OEe,"isHdbRestartRunning");function PEe(){let e=ZP.getHdbBasePath();if(!e)return;let t=yEe.join(e,REe.HDB_PID_FILE),r=UEe(t);if(!(!r||r===process.pid)&&xEe(r))return r}a(PEe,"getHdbPid");function LEe(){for(let e of yo)e.kill();yo=[]}a(LEe,"kill");async function DEe(){await hj(),await Ej(),await Lc(Oc.generateAllServiceConfigs())}a(DEe,"startAllServices");async function pj(e,t=!1){let r;switch(e=e.toLowerCase(),e){case Pr.PROCESS_DESCRIPTORS.HDB.toLowerCase():r=Oc.generateMainServerConfig();break;case Pr.PROCESS_DESCRIPTORS.CLUSTERING_INGEST_SERVICE.toLowerCase():r=Oc.generateNatsIngestServiceConfig();break;case Pr.PROCESS_DESCRIPTORS.CLUSTERING_REPLY_SERVICE.toLowerCase():r=Oc.generateNatsReplyServiceConfig();break;case Pr.PROCESS_DESCRIPTORS.CLUSTERING_HUB.toLowerCase():r=Oc.generateNatsHubServerConfig(),await Lc(r,t),await ga.removeNatsConfig(e);return;case Pr.PROCESS_DESCRIPTORS.CLUSTERING_LEAF.toLowerCase():r=Oc.generateNatsLeafServerConfig(),await Lc(r,t),await ga.removeNatsConfig(e);return;case Pr.PROCESS_DESCRIPTORS.CLUSTERING_UPGRADE_4_0_0.toLowerCase():r=Oc.generateClusteringUpgradeV4ServiceConfig();break;default:throw new Error(`Start service called with unknown service config: ${e}`)}Lc(r,t)}a(pj,"startService");var vEe;async function hj(e=!1){for(let t in Pr.CLUSTERING_PROCESSES){let r=Pr.CLUSTERING_PROCESSES[t];await pj(r,e)}}a(hj,"startClusteringProcesses");async function Ej(){vEe=dj(Pr.LAUNCH_SERVICE_SCRIPTS.NATS_REPLY_SERVICE,{name:Pr.PROCESS_DESCRIPTORS.CLUSTERING_REPLY_SERVICE});try{await Py.deleteLocalStream("__HARPERDB_WORK_QUEUE__")}catch{}await Py.updateLocalStreams();let e=await SEe.getAllNodeRecords();for(let t=0,r=e.length;t<r;t++)if(e[t].system_info?.hdb_version===Pr.PRE_4_0_0_VERSION){Pc.info("Starting clustering upgrade 4.0.0 process"),dj(Pr.LAUNCH_SERVICE_SCRIPTS.NODES_UPGRADE_4_0_0,{name:"Upgrade-4-0-0"});break}}a(Ej,"startClusteringThreads");async function MEe(){await ga.generateNatsConfig(!0),await Py.reloadNATSHub(),await Py.reloadNATSLeaf(),await ga.removeNatsConfig(Pr.PROCESS_DESCRIPTORS.CLUSTERING_HUB.toLowerCase()),await ga.removeNatsConfig(Pr.PROCESS_DESCRIPTORS.CLUSTERING_LEAF.toLowerCase())}a(MEe,"reloadClustering");function UEe(e){try{return Number.parseInt(fj.readFileSync(e,"utf8"),10)}catch{return null}}a(UEe,"readPidFile");function xEe(e){try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}}a(xEe,"isProcessRunning")});var rL={};ye(rL,{compactOnStart:()=>BEe,copyDb:()=>bj});async function BEe(){Sa.notify("Running compact on start"),console.log("Running compact on start");let e=(0,eL.get)(x.ROOTPATH),t=new Map,r=lt();(0,tL.updateConfigValue)(x.STORAGE_COMPACTONSTART,!1);try{for(let n in r){if(n==="system"||n.endsWith("-copy"))continue;let s;for(let l in r[n]){s=r[n][l].primaryStore.path;break}if(!s){console.log("Couldn't find any tables in database",n);continue}let i=(0,Ly.join)(e,"backup",n+".mdb"),o=(0,Ly.join)(e,el,n+"-copy.mdb"),c=0;try{c=await gj(n),console.log("Database",n,"before compact has a total record count of",c)}catch(l){Sa.error("Error getting record count for database",n,l),console.error("Error getting record count for database",n,l)}t.set(n,{dbPath:s,copyDest:o,backupDest:i,recordCount:c}),await bj(n,o),console.log("Backing up",n,"to",i);try{await(0,cu.move)(s,i,{overwrite:!0})}catch(l){console.log("Error moving database",s,"to",i,l)}console.log("Moving copy compacted",n,"to",s),await(0,cu.move)(o,s,{overwrite:!0}),await(0,cu.remove)((0,Ly.join)(e,el,`${n}-copy.mdb-lock`))}try{xd()}catch(n){Sa.error("Error resetting databases after backup",n),console.error("Error resetting databases after backup",n)}try{xd()}catch(n){Sa.error("Error resetting databases after backup",n),console.error("Error resetting databases after backup",n),process.exit(0)}}catch(n){Sa.error("Error compacting database, rolling back operation",n),console.error("Error compacting database, rolling back operation",n),(0,tL.updateConfigValue)(x.STORAGE_COMPACTONSTART,!1);for(let[s,{dbPath:i,backupDest:o}]of t){console.error("Moving backup database",o,"back to",i);try{await(0,cu.move)(o,i,{overwrite:!0})}catch(c){console.error(c)}}throw xd(),n}for(let[n,{backupDest:s,recordCount:i}]of t){let o=await gj(n);if(console.log("Database",n,"after compact has a total record count of",o),i!==o){let c=`There is a discrepancy between pre and post compact record count for database ${n}.
20
20
  Total record count before compaction: ${i}, total after: ${o}.
21
21
  Database backup has not been removed and can be found here: ${s}`;Sa.warn(c),console.warn(c)}(0,eL.get)(x.STORAGE_COMPACTONSTARTKEEPBACKUP)!==!0&&(console.log("Removing backup",s),await(0,cu.remove)(s))}}async function gj(e){let t=await(0,Rj.describeSchema)({database:e}),r=0;for(let n in t)r+=t[n].record_count;return r}function Pf(){}async function bj(e,t){console.log(`Copying database ${e} to ${t}`);let r=lt()[e];if(!r)throw new Error(`Source database not found: ${e}`);let n;for(let f in r){let m=r[f];m.primaryStore.put=Pf,m.primaryStore.remove=Pf;for(let p in m.indices){let h=m.indices[p];h.put=Pf,h.remove=Pf}m.auditStore&&(m.auditStore.put=Pf,m.auditStore.remove=Pf),n=m.primaryStore.rootStore}if(!n)throw new Error(`Source database does not have any tables: ${e}`);let s=n.dbisDb,i=n.auditStore,o=(0,Sj.open)(new Tj.default(t)),c=o.openDB(Dy.INTERNAL_DBIS_NAME),l,u=0,d=s.useReadTransaction();try{for(let{key:m,value:p}of s.getRange({transaction:d})){let h=p.is_hash_attribute||p.isPrimaryKey,E,_;if(h&&(E=p.compression,_=MS(),_?p.compression=_:delete p.compression,E?.dictionary?.toString()===_?.dictionary?.toString()&&(E=null,_=null)),c.put(m,p),!(h||p.indexed))continue;let R=new yj.OpenDBIObject(!h,h);R.encoding="binary",R.compression=E;let S=n.openDB(m,R);S.decoder=null,S.decoderCopies=!1,S.encoding="binary",R.compression=_;let y=o.openDB(m,R);y.encoder=null,console.log("copying",m,"from",e,"to",t),await f(S,y,h,d)}if(i){let m=n.openDB(Dy.AUDIT_STORE_NAME,Xm);console.log("copying audit log for",e,"to",t),f(i,m,!1,d)}async function f(m,p,h,E){let _=0,R=0,S=0,y=1e7,w=null;for(;y-- >0;)try{for(let I of m.getKeys({start:w,transaction:E}))try{w=I;let{value:H,version:X}=m.getEntry(I,{transaction:E});if(H?.length<14&&h){S++;continue}l=p.put(I,H,h?X:void 0),_++,E.openTimer&&(E.openTimer=0),R+=(I?.length||10)+H.length,u++>5e3&&(await l,console.log("copied",_,"entries",S,"delete records,",R,"bytes"),u=0)}catch(H){console.error("Error copying record",typeof I=="symbol"?"symbol":I,"from",e,"to",t,H)}console.log("finish copying, copied",_,"entries",S,"delete records,",R,"bytes");return}catch{if(typeof w=="string"){if(w==="z")return console.error("Reached end of dbi",w,"for",e,"to",t);w=w.slice(0,-2)+"z"}else if(typeof w=="number")w++;else return console.error("Unknown key type",w,"for",e,"to",t)}}a(f,"copyDbi"),await l,console.log("copied database "+e+" to "+t)}finally{d.done(),o.close()}}var Sj,Ly,cu,eL,Tj,yj,Dy,Rj,tL,Sa,nL=se(()=>{Oe();Sj=require("lmdb"),Ly=require("path"),cu=require("fs-extra"),eL=b(fe()),Tj=b(fp()),yj=b(dp()),Dy=b(Qt());G();Vi();Rj=b(Kl()),tL=b(_t()),Sa=b(J());a(BEe,"compactOnStart");a(gj,"getTotalDBRecordCount");a(Pf,"noop");a(bj,"copyDb")});var iL=M((Gke,Aj)=>{"use strict";var tE=fe();tE.initSync();var Lf=require("fs-extra"),sL=require("path"),Df=(G(),D(j)),FEe=require("crypto"),kEe=require("uuid").v4;Aj.exports=HEe;function HEe(){if(tE.getHdbBasePath()!==void 0){let e=sL.join(tE.getHdbBasePath(),Df.LICENSE_KEY_DIR_NAME,Df.JWT_ENUM.JWT_PRIVATE_KEY_NAME),t=sL.join(tE.getHdbBasePath(),Df.LICENSE_KEY_DIR_NAME,Df.JWT_ENUM.JWT_PUBLIC_KEY_NAME),r=sL.join(tE.getHdbBasePath(),Df.LICENSE_KEY_DIR_NAME,Df.JWT_ENUM.JWT_PASSPHRASE_NAME);try{Lf.accessSync(r),Lf.accessSync(e),Lf.accessSync(t)}catch(n){if(n.code==="ENOENT"){let s=kEe(),i=FEe.generateKeyPairSync("rsa",{modulusLength:4096,publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs8",format:"pem",cipher:"aes-256-cbc",passphrase:s}});Lf.writeFileSync(r,s),Lf.writeFileSync(e,i.privateKey),Lf.writeFileSync(t,i.publicKey)}else throw n}}}a(HEe,"checkJWTTokenExist")});var wj=M(($ke,Ij)=>{"use strict";var oL=class{static{a(this,"HdbInfoInsertObject")}constructor(t,r,n){this.info_id=t,this.data_version_num=r,this.hdb_version_num=n}};Ij.exports={HdbInfoInsertObject:oL}});var Oj=M((Kke,Cj)=>{"use strict";var Nj=(G(),D(j)),aL=class{static{a(this,"UpgradeObject")}constructor(t,r){this[Nj.UPGRADE_JSON_FIELD_NAMES_ENUM.DATA_VERSION]=t,this[Nj.UPGRADE_JSON_FIELD_NAMES_ENUM.UPGRADE_VERSION]=r}};Cj.exports={UpgradeObject:aL}});var vy=M((Wke,Lj)=>{"use strict";var js=require("prompt"),vf=require("chalk"),Pj=J(),Ai=require("os"),cL=tl(),lL=["yes","y"];async function GEe(e){let t=`${Ai.EOL}`+vf.bold.green("Your current HarperDB version requires that we complete an update process.")+`${Ai.EOL}If a backup of your data has not been created, we recommend you cancel this process and backup before proceeding.${Ai.EOL}${Ai.EOL}You can read more about the changes in this upgrade at https://harperdb.io/developers/release-notes/${Ai.EOL}`;js.override=cL(["CONFIRM_UPGRADE"]),js.start(),js.message=t;let r={properties:{CONFIRM_UPGRADE:{description:vf.magenta(`${Ai.EOL}[CONFIRM_UPGRADE] Do you want to upgrade your HDB instance now? (yes/no)`),pattern:/y(es)?$|n(o)?$/,message:"Must respond 'yes' or 'no'",default:"no",required:!0}}},n;try{n=await js.get([r])}catch(s){return Pj.error("There was an error when prompting user about an upgrade."),Pj.error(s),!1}return lL.includes(n.CONFIRM_UPGRADE)}a(GEe,"forceUpdatePrompt");async function qEe(e){let t=`${Ai.EOL}`+vf.bold.green(`Your installed HarperDB version is older than the version used to create your data. Downgrading is not recommended as it is not tested and guaranteed to work. However, if you need to downgrade, and a backup of your data has not been created, we recommend you cancel this process and backup before proceeding.${Ai.EOL}`);js.override=cL(["CONFIRM_DOWNGRADE"]),js.start(),js.message=t;let r={properties:{CONFIRM_DOWNGRADE:{description:vf.magenta(`${Ai.EOL}[CONFIRM_DOWNGRADE] Do you want to proceed with using your downgraded HDB instance now? (yes/no)`),pattern:/y(es)?$|n(o)?$/,message:"Must respond 'yes' or 'no'",default:"no",required:!0}}},n=await js.get([r]);return lL.includes(n.CONFIRM_DOWNGRADE)}a(qEe,"forceDowngradePrompt");async function $Ee(){let e=`${Ai.EOL}`+vf.bold.green("We now require a Certifacte Authority certificate. HarperDB can generate all new certificates for you (your existing certificates will be backed up) or you can keep any existing certificates and add your own CA certificate. To add your own CA certificate set the <certificateAuthority> parameter in harperdb-config.yaml");js.override=cL(["GENERATE_CERTS"]),js.start(),js.message=e;let t={properties:{GENERATE_CERTS:{description:vf.magenta(`${Ai.EOL}[GENERATE_CERTS] Do you want HarperDB to generate all new certificates? (yes/no)`),pattern:/y(es)?$|n(o)?$/,message:"Must respond 'yes' or 'no'",default:"yes",required:!0}}},r=await js.get([t]);return lL.includes(r.GENERATE_CERTS)}a($Ee,"upgradeCertsPrompt");Lj.exports={forceUpdatePrompt:GEe,forceDowngradePrompt:qEe,upgradeCertsPrompt:$Ee}});var My=M((zke,Dj)=>{"use strict";var uL=class{static{a(this,"UpgradeDirective")}constructor(t){this.version=t,this.sync_functions=[],this.async_functions=[]}};Dj.exports=uL});var Mj=M((tHe,vj)=>{"use strict";var VEe=ae(),KEe=_t(),Jke=J(),Xke=require("path"),Zke=require("fs"),eHe=(G(),D(j));vj.exports={getOldPropsValue:YEe};function YEe(e,t,r=!1){let n=t.getRaw(e);return VEe.isNotEmptyAndHasValue(n)?n:r?KEe.getDefaultConfig(e):""}a(YEe,"getOldPropsValue")});var Fj=M((nHe,Bj)=>{"use strict";var Dc=require("path"),vc=require("fs-extra"),WEe=require("properties-reader"),jEe=My(),Tr=J(),{getOldPropsValue:St}=Mj(),{HDB_SETTINGS_NAMES:be,CONFIG_PARAMS:lu}=(G(),D(j)),uu=_t(),Uy=fe(),Uj=ae(),Ro=(G(),D(j)),dL=new jEe("3.1.0"),xj=[];function zEe(){let e=WEe(Uy.get(be.SETTINGS_PATH_KEY)),t="Updating settings file for version 3.1.0";console.log(t),Tr.info(t);let r=` ;Settings for the HarperDB process.