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.
- package/README.md +1 -1
- package/bin/harperdb.js +1 -1
- package/bin/lite.js +1 -1
- package/launchServiceScripts/launchNatsIngestService.js +1 -1
- package/launchServiceScripts/launchNatsReplyService.js +1 -1
- package/launchServiceScripts/launchUpdateNodes4-0-0.js +1 -1
- package/npm-shrinkwrap.json +2 -2
- package/package.json +1 -1
- package/server/jobs/jobProcess.js +1 -1
- package/server/threads/threadServer.js +1 -1
- package/studio/web/assets/{index-DzmdGhay.js → index-B9_qS7Kl.js} +1 -1
- package/studio/web/assets/{index-4tz9iZO6.js → index-DTFv2HfO.js} +4 -4
- package/studio/web/assets/{index-n1A9yxoS.js → index-zg8oq7u7.js} +1 -1
- package/studio/web/assets/{index.lazy-DhQph7si.js → index.lazy-WznRtvfY.js} +1 -1
- package/studio/web/assets/{profiler-xCOLgFE8.js → profiler-B8q4d48d.js} +1 -1
- package/studio/web/assets/{react-redux-C8VgMI21.js → react-redux-DGTs_kVY.js} +1 -1
- package/studio/web/assets/{startRecording-CapM7c3R.js → startRecording-DFPWzJie.js} +1 -1
- package/studio/web/index.html +1 -1
- package/utility/scripts/restartHdb.js +1 -1
|
@@ -15,7 +15,7 @@
|
|
|
15
15
|
`)}}});var uq,kl,dq,uc,Gp,wd,Tae,hS,KN=se(()=>{uq=b(ds()),kl=b(st());G();dq=b(sr());Rd();pS();uc=(0,dq.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}`;uc.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&&(uc.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(),uc.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),uc.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,uq.sendItcEvent)({type:b_.COMPONENT_STATUS_REQUEST,message:{requestId:r}}).then(()=>{_()}).catch(y=>{E=!0,S(),this.responseCheckers.delete(r),h(new Ad("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 uc.debug?.(`Collected component status from ${l.length+1} threads (including local)`),u}catch(r){return r instanceof Ad?uc.error?.(`ITC failure during component status collection: ${r.message}`):uc.warn?.("Failed to collect component status from all threads:",r),uc.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)}},wd=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}},Tae=parseInt(process.env.COMPONENT_STATUS_TIMEOUT||"5000"),hS=new Gp(Tae)});var dc,ES=se(()=>{GN();Rd();KN();pS();dc=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 Id(String(t),"setStatus","Component name must be a non-empty string");if(!Object.values(Pe).includes(r))throw new Id(t,"setStatus",`Invalid status level: ${r}. Must be one of: ${Object.values(Pe).join(", ")}`);this.statusMap.set(t,new bd(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 wd.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 Er,_S=se(()=>{ES();Er=new dc});function mq(e){let t=fq.get(e);return t||(t=new YN(e),fq.set(e,t)),t}function pq(){Er.reset()}var YN,fq,ao,hq,Eq=se(()=>{_S();Rd();YN=class{static{a(this,"ComponentStatusBuilder")}componentName;constructor(t){this.componentName=t}healthy(t){return Er.setStatus(this.componentName,Pe.HEALTHY,t),this}warning(t){return Er.setStatus(this.componentName,Pe.WARNING,t),this}error(t,r){return Er.setStatus(this.componentName,Pe.ERROR,t,r),this}loading(t){return Er.setStatus(this.componentName,Pe.LOADING,t||"Loading..."),this}unknown(t){return Er.setStatus(this.componentName,Pe.UNKNOWN,t),this}get(){return Er.getStatus(this.componentName)}},fq=new Map;a(mq,"statusForComponent");ao={loading(e,t){Er.initializeLoading(e,t)},loaded(e,t){Er.markLoaded(e,t)},failed(e,t,r){Er.markFailed(e,t,r)}};a(pq,"reset");hq=Pe});var qp={};ye(qp,{AggregationError:()=>$N,COMPONENT_STATUS_LEVELS:()=>Pe,ComponentStatus:()=>bd,ComponentStatusError:()=>lc,ComponentStatusOperationError:()=>Id,ComponentStatusRegistry:()=>dc,CrossThreadCollectionError:()=>VN,CrossThreadStatusCollector:()=>Gp,CrossThreadTimeoutError:()=>qN,ITCError:()=>Ad,StatusAggregator:()=>wd,componentStatusRegistry:()=>Er,crossThreadCollector:()=>hS,query:()=>yae});var yae,_q=se(()=>{_S();ES();GN();ES();KN();_S();pS();Rd();yae={get(e){return Er.getStatus(e)},all(){return Er.getAllStatuses()},byStatus(e){return Er.getComponentsByStatus(e)},summary(){return Er.getStatusSummary()},async allThreads(){return dc.getAggregatedFromAllThreads(Er)}}});var WN={};ye(WN,{STATUS:()=>hq,internal:()=>qp,lifecycle:()=>ao,reset:()=>pq,statusForComponent:()=>mq});var $p=se(()=>{Eq();_q()});var Kp=M((cUe,Tq)=>{"use strict";var Es=Q(),Tn=(G(),D(j)),Rae=rF(),bae=(Yn(),D(_i)),{validateEvent:jN}=ds(),Vp=ps(),Aae=require("process"),{resetDatabases:Iae}=(Oe(),D(pt)),wae={[Tn.ITC_EVENT_TYPES.SCHEMA]:Nae,[Tn.ITC_EVENT_TYPES.USER]:Sq,[Tn.ITC_EVENT_TYPES.COMPONENT_STATUS_REQUEST]:Oae};async function Nae(e){let t=jN(e);if(t){Es.error(t);return}Es.trace("ITC schemaHandler received schema event:",e),await Rae(e.message),await Cae(e.message)}a(Nae,"schemaHandler");async function Cae(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=Iae();e.table&&e.database&&await t[e.database][e.table].put(Symbol.for("write-verify"),null)}catch(t){Es.error(t)}}a(Cae,"syncSchemaMetadata");var gq=[];async function Sq(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=jN(e);if(t){Es.error(t);return}Es.trace(`ITC userHandler ${Tn.HDB_ITC_CLIENT_PREFIX}${Aae.pid} received user event:`,e),await bae.setUsersWithRolesCache();for(let r of gq)r()}catch(t){Es.error(t)}}a(Sq,"userHandler");Sq.addListener=function(e){gq.push(e)};async function Oae(e){try{let t=jN(e);if(t){Es.error(t);return}Es.trace("ITC componentStatusRequestHandler received request:",e);let{internal:r}=($p(),D(WN)),{getWorkerIndex:n}=st(),{sendItcEvent:s}=ds(),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(Oae,"componentStatusRequestHandler");Tq.exports=wae});var ds=M((pUe,Rq)=>{"use strict";var uUe=Q(),zN=ae(),Pae=(G(),D(j)),{ITC_ERRORS:Yp}=Jr(),{parentPort:dUe,threadId:Lae,isMainThread:Dae,workerData:fUe}=require("worker_threads"),{onMessageFromWorkers:vae,broadcast:mUe,broadcastWithAcknowledgement:Mae}=st();Rq.exports={sendItcEvent:Uae,validateEvent:yq,SchemaEventMsg:xae,UserEventMsg:Bae};var gS;vae(async(e,t)=>{gS=gS||Kp(),yq(e),gS[e.type]&&await gS[e.type](e),e.requestId&&t&&t.postMessage({type:"ack",id:e.requestId})});function Uae(e){return!Dae&&e.message&&(e.message.originator=Lae),Mae(e)}a(Uae,"sendItcEvent");function yq(e){if(typeof e!="object")return Yp.INVALID_ITC_DATA_TYPE;if(!e.hasOwnProperty("type")||zN.isEmpty(e.type))return Yp.MISSING_TYPE;if(!e.hasOwnProperty("message")||zN.isEmpty(e.message))return Yp.MISSING_MSG;if(!e.message.hasOwnProperty("originator")||zN.isEmpty(e.message.originator))return Yp.MISSING_ORIGIN;if(Pae.ITC_EVENT_TYPES[e.type.toUpperCase()]===void 0)return Yp.INVALID_EVENT(e.type)}a(yq,"validateEvent");function xae(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(xae,"SchemaEventMsg");function Bae(e){this.originator=e}a(Bae,"UserEventMsg")});var Xo=M((_Ue,wq)=>{"use strict";var bq=(G(),D(j)),EUe=ae(),SS=Q(),Aq=FB(),Nd,{sendItcEvent:Iq}=ds();function Fae(e){try{SS.debug("signalSchemaChange called with message:",e),Nd=Nd||Kp();let t=new Aq(bq.ITC_EVENT_TYPES.SCHEMA,e);return Nd.schema(t),Iq(t)}catch(t){SS.error(t)}}a(Fae,"signalSchemaChange");function kae(e){try{SS.trace("signalUserChange called with message:",e),Nd=Nd||Kp();let t=new Aq(bq.ITC_EVENT_TYPES.USER,e);return Nd.user(t),Iq(t)}catch(t){SS.error(t)}}a(kae,"signalUserChange");wq.exports={signalSchemaChange:Fae,signalUserChange:kae}});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 Nq(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(Nq,"mergeHeaders")});function TS(e,t,r=Gae){let n;return function(...i){return n?n.length*JN>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();JN=(JN*4+c-i)/5;let l=n.shift();if(l){let{args:u,fn:d}=l;d(),s(c,u)}else n=null})}}var Pq,Hae,Gae,Cq,qae,QN,Oq,JN,XN=se(()=>{Pq=b(sr()),Hae=3e3,Gae=2e4,Cq=0,qae=3e4,QN=3e3,Oq=performance.now()+QN,JN=0;a(TS,"throttle");setInterval(()=>{let e=performance.now();e-Oq-QN>Hae&&Cq+qae<e&&(Pq.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"),Cq=e),Oq=e},QN).unref()});var Gq={};ye(Gq,{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=LI(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,Pu=!1,Jc,Ft,Ps,Ha=Gl.get(x.REPLICATION_DATABASES);if(Array.isArray(Ha)){for(let K of Ha)if(K.name===c&&K.replicateTo>=0){Ps=K.replicateTo;break}}let c_=i.getRange({start:!1,end:!1}).constructor,lm=10,l_=6;_&&pm(),zm(i.env.path,K=>{if(I)return qa(K)});class um extends Pl{static{a(this,"Updatable")}getUpdatedTime(){return ec.get(this.getRecord())?.version}getExpiresAt(){return ec.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===xu.ROLE_TABLE_NAME||N.table===xu.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 J={residencyId:Qc(N.residencyList),isNotification:!0,ensureLoaded:!1,nodeId:N.nodeId,async:!0},F=N.id,he=await W.getResource(F,L,J);switch(N.finished&&await N.finished,N.type){case"put":return B?he._writeInvalidate(F,$,J):he._writeUpdate(F,$,!0,J);case"patch":return B?he._writeInvalidate(F,$,J):he._writeUpdate(F,$,!1,J);case"delete":return he._writeDelete(F,J);case"publish":case"message":return he._writePublish(F,$,J);case"invalidate":return he._writeInvalidate(F,$,J);case"relocate":return he._writeRelocate(F,J);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 J;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"){J?.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===J?.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=J?J.committed.then(F.onCommit):F.onCommit();_e&&(re?.then?re.then(_e):_e())}else _e&&_e();continue}if(J)if(F.beginTxn)J.resolve();else{J.writePromises.push(U(F,J));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"}),Jp.signalSchemaChange(new Qp.SchemaEventMsg(process.pid,V.CREATE_TABLE,c,s)))}else return F.beginTxn?(J=F,J.writePromises=[U(F,F)],new Promise(_e=>{J.resolve=()=>_e(Promise.all(J.writePromises))})):U(F,F)});J&&(J.committed=ue),v&&ue&&!ue?.waitingForUserChange&&(ue.then(()=>Jp.signalUserChange(new Qp.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 xo(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&&(!ece(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,qa()}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&&Qa(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(),eC.default.unlinkSync(i.env.path);Jp.signalSchemaChange(new Qp.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 xo(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?id(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||Pu&&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 Ga(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 Ga(this.getContext())}else return Ga(this.getContext())}}else return this.allowUpdate(g,{})}allowDelete(g,T){return Dn(g,T)?.delete&&Ga(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===Dq?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:Mu(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=$a(this.getResidency(T.value,C)),O;if(P){if(!P.includes(server.hostname))return!1;O=Qc(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,()=>{Lu(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?Dq: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:Mu(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,J;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),J=j_(J??T,Te,C),!J)return me(!1)}}else{if(C)return me(!1);J=j_(J??T,W,C),Fe.default.debug?.("Rebuilding update without audit:",J)}Fe.default.trace?.("Rebuilt record to save:",J," is full update:",C)}let ge;if(C&&!J?ge=T:this.constructor.loadAsInstance===!1?ge=Ll(W,J??T):(this.#e=W,ge=Ll(this,J??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=$a(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=Qc(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""}})()),Lu(g,W,ge),me(!0),O.expiresAt&&qa();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)&&(Lu(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"),_||qa()):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=Yae);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||vI[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"?$ae(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=>rd(ge.attribute)===rd(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 J=g.select;if(P.length===0&&(P=[{attribute:t,comparator:"greater_than",value:!0}]),g.explain)return{conditions:P,operator:L,postOrdering:W,selectApplied:!!J};let F=C.useReadTxn(),he=MI(P,L,ve,F,g,T,(oe,ge)=>mm(oe,J,T,F,ge),v),ue=g.ensureLoaded!==!1,_e=ve.transformEntryForSelect(J,T,F,v,ue,!0),re=ve.transformToOrderedSelect(he,J,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(J){let oe=[];for(let ge of J)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 c_;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,J,F,he=!0;function ue(re){let oe=re.next&&ue(re.next),ge=re.descending;return P.sort=re,(me,ie)=>{let Ce=Du(me,re.attribute,P),Be=Du(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=[],J&&A.push(J);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=Du(oe,W,P);if(he)he=!1,F=ge;else if(ge!==F){F=ge,J=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 mc.SKIP;if(N=xo(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?mc.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]:rd(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"),J;if(typeof g=="string")W(g,F=>{J=F});else if(Array.isArray(g))if(g.asArray)J=[],g.forEach((F,he)=>{F==="*"?g[he]=L:W(F,ue=>J[he]=ue)});else{J={};let F=g.forceNulls;for(let he of g)if(he==="*")for(let ue in L)J[ue]=L[ue];else W(he,(ue,_e)=>{ue===void 0&&F&&(ue=null),J[_e]=ue})}else throw new dt.ClientError("Invalid select"+g);return $?Promise.all($).then(()=>J):J}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=GI(ve,this.getId()??null,function(v,A,U,N){try{let L=A.getValue?.(i,T),$=A.type;if(!L&&$==="patch"&&T){let J=i.getEntry(v);J?.version===A.version?L=J.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||xq(v,W)){let J=$.getValue(i,T,N);if(B({id:W,localTime:N,value:J,version:$.version,type:$.type,size:$.size}),P.queue?.length>Mq&&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 J=W.recordId;if(v==null||xq(v,J)){let F=W.getValue(i,T,L);if(N.push({id:J,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:J}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:J}),P.queue?.length>Mq&&await P.waitForDrain()===!1))return}}else{A&&!U&&(U=0);let N=this.#r?.localTime;if(N===PI&&(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 J=It(W),F=J.getValue(i,T,$);T&&(J.type="put"),L.push({id:v,value:F,localTime:$,...J}),$=J.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:Mu(T,Ke.publish?.bind(this,O,g,T)),commit:a((B,v,A)=>{v===void 0&&R&&!_&&qa(),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");Vae(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=eC.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 fc(),!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 fc();let L=U*2,$=(v+N)/L,W=Math.pow((v-N+1)/U/2,2)+$*(1-$)/L,J=Math.max(Math.sqrt(W)*T,1),F=Math.round($*T),he=Math.max(F-1.96*J,v+N),ue=Math.min(F+1.96*J,T),_e=Math.pow(10,Math.round(Math.log10(J)));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)"),Pu=!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?td({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 J=P.tableClass.primaryStore[A?"getEntry":"get"](W,{transaction:Br(B).getReadTxn()});return J?.then&&(L=!0),ve.loadAsInstance===!1&&Object.freeze(A?J?.value:J),J});return T.filterMissing?L?Promise.all($).then(W=>W.filter(Bq)):$.filter(Bq):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,sd.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 fc(),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 fc(),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 fc();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 fc();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 u_=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 Zb=ve.prototype;return h&&ve.setTTLExpiration(h/1e3),z&&d_(),ve;function Lu(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(J=>{if(W.has(J))W.delete(J);else return!0}):[],$=Array.from(W),($.length>0||L.length>0)&&Lq){let J=$.concat(L).map(F=>({key:F,value:K}));O.prefetch(J,Uq)}for(let J=0,F=$.length;J<F;J++)O.remove($[J],K)}else L?.length>0&&Lq&&O.prefetch(L.map(W=>({key:W,value:K})),Uq);if(L)for(let W=0,J=L.length;W<J;W++)O.put(L[W],K)}return C}a(Lu,"updateIndices");function Gi(K){switch(typeof K){case"number":return!0;case"string":if(K.length<659)return!0;if(K.length>vq)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,Qae,0)>vq)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 xo(K,g,T,C,P){if(ve.getResidencyById&&T.ensureLoaded&&g?.replicateFrom!==!1){let B=$a(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")&&(Hq.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>l_&&(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(xo,"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 Xae;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=vu(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 ko,g.lmdbDb=i,g;g=T}while(!0)}else return new K_}a(Br,"txnForContext");function Du(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(Du,"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 mc.SKIP;for(let $=0;$<O;$++)if(!v?.includes($)&&!P[$](L,U))return mc.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 mc.SKIP;for(let L=0;L<O;L++){let W=P[L].idFilter;if(W){if(!W(N))return mc.SKIP;v||(v=[]),v.push(L)}}return xo(N,T,B,!1,A)});return Array.isArray(K)&&(U=U.filter(N=>N!==mc.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 vu(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(vu(K,i.getEntry(K),T)):O(N)}))return new Promise(N=>{O=N,B=setTimeout(()=>{i.unlock(K,P)},zae)});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 J=performance.now(),F,he,ue;try{F=await u_(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()-J;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()-J;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:Mu(F),commit:a((re,oe)=>{if(oe?.version!==P)return;let ge=Lu(K,v,F);if(F){Ke.put?.(A,K,F),oe&&(T.previousResidency=ve.getResidencyRecord(oe.residencyId));let me,ie=!1,Ce,Be=$a(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=Qc(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(vu,"getFromSource");function Ga(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(Ga,"checkContextPermissions");function qa(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(J,F,he,ue){let _e=J+$-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*(J-F)/re} < ${L}`),_e*(J-F)/re<L}return!1}a(W,"shouldEvict");try{let J=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+jae<Date.now()?ge=Sl(i,F,_e):re!=null&&W(re,_e,oe,ue)&&(ge=ve.evict(he,ue,_e),J++),ge&&(await U[N],U[N]=ge.catch(me=>{Fe.default.error?.("Cleanup error",me)}),++N>=A&&(N=0)),await fc()}Fe.default.debug?.(`Finished cleanup scan for ${s}, evicted ${J} entries`)}catch(J){Fe.default.warn?.(`Error in cleanup scan for ${s}:`,J)}T(void 0),Ir=0}),Math.min(v-Date.now(),2147483647)).unref()},"startNextTimer");B(O)}):void 0}a(qa,"scheduleCleanup");function pm(){Y=l?.addDeleteRemovalCallback(n,i,(K,g)=>{i.remove(K,g)})}a(pm,"addDeleteRemoval");function d_(){(0,Hl.getWorkerIndex)()===0&&setInterval(async()=>{if(!Jc){Jc=!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 fc()}}catch(K){Fe.default.error?.("Error in evicting old records",K)}finally{Jc=!1}}},Wae).unref()}a(d_,"runRecordExpirationEviction");function $a(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($a,"residencyFromFunction");function Qc(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(Qc,"getResidencyId");function Mu(K,g){let T=eI(K,i.rootStore);if(T){let C=g;return C?async()=>{await C(),await T}:()=>T}return g}a(Mu,"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 Uq(){}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,Cd.autoCastBooleanStrict)(e);case"Date":if(isNaN(e)){if(e==="null")return null;Zae.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,Cd.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 xq(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 Bq(e){return e!=null}function qs(e){try{return JSON.stringify(e)}catch{return e}}function ece(e){let t=process.pid;return e.env.readerList().slice(1).some(r=>+r.match(/\d+/)?.[0]!=t)}var mc,zp,Fq,kq,Gl,dt,Jp,Qp,Fe,ql,Hl,Cd,eC,Hq,$ae,Vae,Kae,Yae,Wae,jae,Lq,zae,Dq,Jae,kn,Tl,Qae,vq,Mq,Xae,kUe,Zae,fc,Lg=se(()=>{G();mc=require("lmdb"),zp=b(xn()),Fq=b(require("lodash")),kq=b(xm());Ji();Fm();Gl=b(fe());qI();dt=b(Ee()),Jp=b(Xo()),Qp=b(ds());Oe();Pg();Fe=b(sr());Jw();za();ql=require("ordered-binary"),Hl=b(st());Vi();Cd=b(ae());hl();as();z_();jp();eC=b(require("node:fs"));os();lg();Hq=b(Q());XN();({sortBy:$ae}=Fq.default),{validateAttribute:Vae}=kq.default,Kae=new Uint8Array(9);Kae[8]=192;Yae=1/0,Wae=6e4,jae=864e5;Gl.initSync();Lq=Gl.get(x.STORAGE_PREFETCHWRITES),zae=1e4,Dq=1,Jae=2,kn=1,Tl=8,Qae=Buffer.allocUnsafeSlow(8192),vq=1978,Mq=100,Xae={read:!0,insert:!0,update:!0,delete:!0,isSuperUser:!0},kUe=(0,Cd.convertToMS)(Gl.get(x.CLUSTERING_LEAFSERVER_STREAMS_MAXAGE))||864e5;a(bS,"makeTable");a(ZN,"attributesAsObject");a(Uq,"noop");Zae=/[+-][0-9]{2}:[0-9]{2}|[a-zA-Z]$/;a(RS,"coerceType");a(yS,"rejectNaN");a(xq,"isDescendantId");fc=a(()=>new Promise(setImmediate),"rest");a(Gs,"when");a(Bq,"exists");a(qs,"stringify");a(ece,"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 qq=se(()=>{a(AS,"euclideanDistance");a(IS,"cosineDistance")});var $q,Vq,Pd,co,Od,tce,rce,wS,Kq=se(()=>{qq();$q=require("msgpackr"),Vq=b(sr()),Pd=b(Ee()),co=(0,Vq.loggerWithTag)("HNSW"),Od=Symbol.for("entryPoint"),tce=Symbol.for("key"),rce=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=$q.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"?[tce,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(Od);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);co.debug?.("setting entry point to",i),this.indexStore.put(Od,i);return}let m=c.level??Math.min(Math.floor(-Math.log(Math.random())*this.mL),rce),p=f.level;if(m>=p){if(typeof i!="number")throw new Error("Invalid nodeId: "+i);co.debug?.("setting entry point to",i),this.indexStore.put(Od,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&&co.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(Od);else{if(typeof l!="number")throw new Error("Invalid nodeId: "+l);co.debug?.("setting entry point to",l),this.indexStore.put(Od,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&&(co.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(Od);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 Pd.ClientError(`Can not use "${i}" comparator with HNSW`)}if(n)throw new Pd.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 Pd.ClientError("Unknown distance function");c=this.distance}if(!t)throw new Pd.ClientError("A target vector must be provided for an HNSW query");if(!Array.isArray(t))throw new Pd.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){co.info?.("could not find neighbor node",o);continue}o[n]?.find(({id:l})=>l==t)||co.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)){co.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&&co.info?.("should not remove last connection",t,n))}}r[s].find(({id:l})=>l===n)?co.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 tC,Yq=se(()=>{Kq();tC={HNSW:wS}});var pt={};ye(pt,{NON_REPLICATING_SYSTEM_TABLES:()=>NS,database:()=>Ed,databaseEnvs:()=>na,databases:()=>Me,dropDatabase:()=>tN,dropTableMeta:()=>cce,getDatabases:()=>lt,getDefaultCompression:()=>MS,getTables:()=>sce,onRemovedDB:()=>sh,onUpdatedTable:()=>$l,readMetaDb:()=>Xp,resetDatabases:()=>Ud,table:()=>ze,tables:()=>yn});function nh(e,t){let r=DS.OpenDBIObject??DS.default.OpenDBIObject;return new r(e,t)}function sce(){return LS||lt(),yn||{}}function lt(){if(LS)return Me;LS=!0,vd=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,Dd.getBaseSchemaPath)())){for(let r of(0,_s.readdirSync)((0,Dd.getBaseSchemaPath)(),{withFileTypes:!0}))if(!r.isFile()){let n=(0,Ht.join)((0,Dd.getBaseSchemaPath)(),r.name),s=(0,Ht.join)((0,Dd.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=vd.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 vd=null,Me}}function Ud(){LS=!1;for(let[,e]of na)e.needsDeletion=!0;lt();for(let[e,t]of na)if(t.needsDeletion&&!e.endsWith("system.mdb")){t.close(),na.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=sC,n,s){let i=new rC.default(e,!1);try{let o=na.get(e);o?o.needsDeletion=!1:(o=(0,Md.open)(i),na.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,Md.open)(i),u.isLegacy=!0):u=fg(o));let d=Qq(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(Ld)||0)&&(l.putSync(Ld,w+1),Cr.info(`Updating next table id (it was out of sync) to ${w+1} for ${p}`)):(_.tableId=w=l.get(Ld),w||(w=1),Cr.debug("Table {tableName} missing an id, assigning {tableId}"),l.putSync(Ld,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=Zq(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=Xq(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 Qq(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)),vd&&!vd.has(e)){let r=new Set;t[vS]=r,vd.set(e,r)}return t}function Xq(e,t,r){return e[t]=r,r}function Ed({database:e,table:t}){e||(e=sC),lt();let r=Qq(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=na.get(o);if(!c||c.status==="closed"){let l=new rC.default(o,!1);c=(0,Md.open)(l),na.set(o,c)}return c.auditStore||(c.auditStore=fg(c)),c}async function tN(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,na.delete(r.path),r.status==="open"&&(await r.close(),await th.remove(r.path));if(r||(r=Ed({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 Zq(e,t,r){let n=r.is_hash_attribute||r.indexed.type&&tC[r.indexed.type]?.useObjectStore,s=new nh(!n,n),i=t.openDB(e,s);if(r.indexed.type){let o=tC[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=sC);let h=Ed({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(),Ud(),ze(e);let te=wg(h.openDB(de,ce),h);h.databaseName=r,te.tableId=y.get(Ld),Cr.trace(`Assigning new table id ${te.tableId} for ${t}`),te.tableId||(te.tableId=1),y.put(Ld,te.tableId+1),S.tableId=te.tableId,_=Xq(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=Zq(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=ace(_,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 ace(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,Md.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,Wq.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!==zq.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>ice?await s:d>oce&&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 cce({table:e,database:t}){let r=Ed({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,Md,Ht,_s,Dd,rC,th,nC,Wq,OS,PS,rh,jq,zq,DS,nce,Cr,sC,vS,Jq,NS,yn,Me,Ld,Zp,eh,LS,na,vd,ice,oce,Oe=se(()=>{Zt=b(fe()),CS=b(Jt()),Md=require("lmdb"),Ht=require("path"),_s=require("fs"),Dd=b(bt());Lg();rC=b(fp());G();th=b(require("fs-extra")),nC=b(oi()),Wq=b(xn()),OS=b(Xo()),PS=b(ds()),rh=require("worker_threads"),jq=b(Q()),zq=b(st());Vi();hl();os();Yq();DS=b(dp()),{forComponent:nce}=jq.default;a(nh,"OpenDBIObject");Cr=nce("storage"),sC="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,nC._assignPackageExport)("databases",Me);(0,nC._assignPackageExport)("tables",yn);Ld=Symbol.for("next-table-id"),Zp=[],eh=[],na=new Map;a(sce,"getTables");a(lt,"getDatabases");a(Ud,"resetDatabases");a(Xp,"readMetaDb");a(Qq,"ensureDB");a(Xq,"setTable");a(Ed,"database");a(tN,"dropDatabase");a(Zq,"openIndex");a(ze,"table");ice=1e3,oce=10;a(ace,"runIndexing");a(cce,"dropTableMeta");a($l,"onUpdatedTable");a(sh,"onRemovedDB");a(MS,"getDefaultCompression")});var aC={};ye(aC,{loadGQLSchema:()=>dce,start:()=>oC,startOnMainThread:()=>uce});function oC({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):lce.includes(R.type)||(0,t$.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,iC.dirname)(n),R.tableClass):i.set((0,iC.dirname)(n)+"/"+(R.export.name||R.type),R.tableClass,R.export));function _(R,S,y){return new e$.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 iC,e$,t$,lce,uce,dce,r$=se(()=>{iC=require("path"),e$=require("node:vm");Oe();t$=b(st());rc();lce=["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(oC,"start");uce=oC,dce=a(e=>oC({ensureTable:ze}).handleFile(e,null,null,new od),"loadGQLSchema")});var lC={};ye(lC,{start:()=>Tce});function fce(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 n$(e){if(typeof e!="object"||e===null)throw new lo("Request body must be an object.");if(!("query"in e))throw new lo("Request body must contain a `query` field.");if(typeof e.query!="string")throw new lo("Request body `query` field must be a string.");if("variables"in e&&(typeof e.variables!="object"||e.variables===null))throw new lo("Request body `variables` field must be an object.");if("operationName"in e&&typeof e.operationName!="string")throw new lo("Request body `operationName` field must be a string.")}function cC(e){return parseInt(e.value,10)}function i$(e){return parseFloat(e.value)}function o$(e,t,r){let n=r.get(e.name.value);return a$(n)?c$(n,t):{attribute:t,value:n}}function a$(e){return typeof e=="object"&&e!=null&&!Array.isArray(e)}function c$(e,t){return t=typeof t=="string"?[t]:t,Object.entries(e).flatMap(([r,n])=>(t=[...t,r],a$(n)?c$(n,t):{attribute:t,value:n}))}function mce(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:cC(e.value)};case qe.Kind.FLOAT:return{attribute:t,value:i$(e.value)};case qe.Kind.BOOLEAN:case qe.Kind.STRING:return{attribute:t,value:e.value.value};case qe.Kind.VARIABLE:return o$(e.value,t,r);case qe.Kind.OBJECT:return l$(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 l$(e,t,r){return e.fields.flatMap(n=>mce(n,t,r))}function pce(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:cC(e.value)};case qe.Kind.FLOAT:return{attribute:e.name.value,value:i$(e.value)};case qe.Kind.BOOLEAN:case qe.Kind.STRING:return{attribute:e.name.value,value:e.value.value};case qe.Kind.VARIABLE:return o$(e.value,e.name.value,t);case qe.Kind.OBJECT:return l$(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 hce(e,t){return e.flatMap(r=>pce(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 u$(e,t){return US(e,t).map(r=>r.selectionSet?.selections.length>0?{name:r.name.value,select:u$(r.selectionSet,t)}:r.name.value)}async function Ece(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:u$(e.selectionSet,r),conditions:hce(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 d$(e){switch(e.kind){case qe.Kind.NULL:return null;case qe.Kind.INT:return cC(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]:d$(r.value),...t}),{});case qe.Kind.LIST:case qe.Kind.ENUM:default:throw new Vr(`Value type, ${e.kind}, is not supported.`)}}function _ce(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=d$(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 gce(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=_ce(e.variableDefinitions,t),i=await Promise.all(US(e.selectionSet,r).map(c=>Ece(c,s,r,n))),o={data:{}};for(let[c,l]of i)o.data[c]=l;return o}async function s$({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(fce(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 gce(c,t,o,n);return{status:200,headers:{"Content-Type":"application/graphql-response+json; charset=utf-8"},body:JSON.stringify(l)}}async function Sce(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 n$(r),s$(r,e)}case"POST":{let r=await $o(e.headers.get("content-type"),!0)(e._nodeRequest);return n$(r),s$(r,e)}default:throw new lo("Method Not Allowed",405,{Allow:"GET, POST"})}}function Tce(e){e.server.http(async(t,r)=>{if(!t.url.startsWith("/graphql"))return r(t);try{return await Sce(t)}catch(n){logger.error(n);let s=t.headers.get("accept")??"application/graphql-response+json";switch(s){case"application/json":{if(n instanceof lo)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 lo)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,lo,f$=se(()=>{qe=b(require("graphql"));Vo();rc();a(fce,"assertExecutableDefinitionNode");a(n$,"assertRequestParams");a(cC,"processIntValueNode");a(i$,"processFloatValueNode");a(o$,"processVariableNode");a(a$,"isObject");a(c$,"transformObjectIntoQueryCondition");a(mce,"processObjectFieldNode");a(l$,"processObjectValueNode");a(pce,"processArgumentNode");a(hce,"buildConditionsQuery");a(US,"fillInFragments");a(u$,"buildSelectQuery");a(Ece,"processFieldNode");a(d$,"processConstValueNode");a(_ce,"resolveVariables");a(gce,"executeOperation");a(s$,"resolver");Vr=class extends Error{static{a(this,"GraphQLQueryingError")}},lo=class extends Error{static{a(this,"HTTPError")}statusCode;headers;constructor(t,r=400,n={}){super(t),this.statusCode=r,this.headers=n}};a(Sce,"graphqlQueryingHandler");a(Tce,"start")});var g$=M((axe,_$)=>{var xd=require("validate.js"),p$=mt(),Bd=(G(),D(j)),{handleHDBError:yce,hdbErrors:Rce}=Ee(),{HDB_ERROR_MSGS:ar,HTTP_STATUS_CODES:bce}=Rce,uC=a(()=>({role:{presence:!0,format:"[\\w\\-\\_]+"},id:{presence:!0,format:"[\\w\\-\\_]+"},permission:{presence:!0}}),"constraintsTemplate"),Ace={STRUCTURE_USER:"structure_user"},m$=Object.values(Bd.ROLE_TYPES_ENUM),Ice="attribute_permissions",wce="attribute_name",{PERMS_CRUD_ENUM:Fd}=Bd,Nce=[Ice,...Object.values(Fd)],h$=[Fd.READ,Fd.INSERT,Fd.UPDATE],Cce=[wce,...h$];function Oce(e){let t=uC();return t.role.presence=!0,t.id.presence=!1,t.permission.presence=!0,E$(e,t)}a(Oce,"addRoleValidation");function Pce(e){let t=uC();return t.role.presence=!1,t.id.presence=!0,t.permission.presence=!0,E$(e,t)}a(Pce,"alterRoleValidation");function Lce(e){let t=uC();return t.role.presence=!1,t.id.presence=!0,t.permission.presence=!1,p$.validateObject(e,t)}a(Lce,"dropRoleValidation");var Dce=["operation","role","id","permission","hdb_user","access"];function E$(e,t){let r={main_permissions:[],schema_permissions:{}},n=Object.keys(e),s=[];for(let o=0,c=n.length;o<c;o++)Dce.includes(n[o])||s.push(n[o]);s.length>0&&_r(ar.INVALID_ROLE_JSON_KEYS(s),r);let i=p$.validateObject(e,t);if(i&&i.message.split(",").forEach(o=>{_r(o,r)}),e.permission){let o=vce(e);o&&_r(o,r),m$.forEach(c=>{e.permission[c]&&!xd.isBoolean(e.permission[c])&&_r(ar.SU_CU_ROLE_BOOLEAN_ERROR(c),r)})}for(let o in e.permission)if(m$.indexOf(o)<0){if(o===Ace.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]||_r(ar.SCHEMA_NOT_FOUND(f),r)}continue}_r(ar.STRUCTURE_USER_ROLE_TYPE_ERROR(o),r);continue}let c=e.permission[o];if(!o||!global.hdb_schema[o]){_r(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]){_r(ar.TABLE_NOT_FOUND(o,l),r);continue}if(Object.keys(u).forEach(d=>{Nce.includes(d)||_r(ar.INVALID_PERM_KEY(d),r,o,l)}),Object.values(Fd).forEach(d=>{xd.isDefined(u[d])?xd.isBoolean(u[d])||_r(ar.TABLE_PERM_NOT_BOOLEAN(d),r,o,l):_r(ar.TABLE_PERM_MISSING(d),r,o,l)}),u.attribute_permissions===void 0){_r(ar.ATTR_PERMS_ARRAY_MISSING,r,o,l);continue}else if(!(Array.isArray(u.attribute_permissions)||u.attribute_permissions===null)){_r(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=>{!Cce.includes(E)&&E!==Fd.DELETE&&_r(ar.INVALID_ATTR_PERM_KEY(E),r,o,l)}),!xd.isDefined(p.attribute_name)){_r(ar.ATTR_PERM_MISSING_NAME,r,o,l);continue}let h=p.attribute_name;if(!d.includes(h)){_r(ar.INVALID_ATTRIBUTE_IN_PERMS(h),r,o,l);continue}h$.forEach(E=>{xd.isDefined(p[E])?xd.isBoolean(p[E])||_r(ar.ATTR_PERM_NOT_BOOLEAN(E,h),r,o,l):_r(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}`;_r(ar.MISMATCHED_TABLE_ATTR_PERMS(m),r,o,l)}}}}return Mce(r)}a(E$,"customValidate");_$.exports={addRoleValidation:Oce,alterRoleValidation:Pce,dropRoleValidation:Lce};function vce(e){let{operation:t,permission:r}=e;if(t===Bd.OPERATIONS_ENUM.ADD_ROLE||t===Bd.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?Bd.ROLE_TYPES_ENUM.SUPER_USER:Bd.ROLE_TYPES_ENUM.CLUSTER_USER;return ar.SU_CU_ROLE_NO_PERMS_ALLOWED(o)}}}return null}a(vce,"validateNoSUPerms");function Mce(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 yce(new Error,n,bce.BAD_REQUEST)}else return null}a(Mce,"generateRolePermResponse");function _r(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(_r,"addPermError")});var oh=M((uxe,R$)=>{"use strict";var S$=Vn(),T$=Sn(),Uce=xl(),fC=g$(),mC=Xo(),lxe=require("uuid").v4,xce=require("util"),xS=(G(),D(j)),Bce=ae(),pC=T$.searchByValue,Fce=T$.searchByHash,kce=xce.promisify(Uce.delete),Hce=di(),Gce=pd(),{hdbErrors:qce,handleHDBError:Vl}=Ee(),{HDB_ERROR_MSGS:y$,HTTP_STATUS_CODES:ih}=qce,{UserEventMsg:hC}=ds();R$.exports={addRole:$ce,alterRole:Vce,dropRole:Kce,listRoles:Yce};function dC(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(dC,"scrubRoleDetails");async function $ce(e){let t=fC.addRoleValidation(e);if(t)throw t;e=dC(e);let r={schema:"system",table:"hdb_role",attribute:"role",value:e.role,hash_attribute:"id",get_attributes:["*"]},n;try{n=Array.from(await pC(r)||[])}catch(i){throw Vl(i)}if(n&&n.length>0)throw Vl(new Error,y$.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 S$.insert(s),mC.signalUserChange(new hC(process.pid)),e=dC(e),e}a($ce,"addRole");async function Vce(e){let t=fC.alterRoleValidation(e);if(t)throw t;e=dC(e);let r={operation:"update",schema:"system",table:"hdb_role",records:[e]},n;try{n=await S$.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 mC.signalUserChange(new hC(process.pid)),e}a(Vce,"alterRole");async function Kce(e){let t=fC.dropRoleValidation(e);if(t)throw Vl(new Error,t,ih.BAD_REQUEST,void 0,void 0,!0);let r=new Gce(xS.SYSTEM_SCHEMA_NAME,xS.SYSTEM_TABLE_NAMES.ROLE_TABLE_NAME,[e.id],["role"]),n=Array.from(await Fce(r));if(n.length===0)throw Vl(new Error,y$.ROLE_NOT_FOUND,ih.NOT_FOUND,void 0,void 0,!0);let s=new Hce(xS.SYSTEM_SCHEMA_NAME,xS.SYSTEM_TABLE_NAMES.USER_TABLE_NAME,"role",e.id,void 0,["username","active"]),i=Array.from(await pC(s)),o=!1;if(Bce.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 kce(c),mC.signalUserChange(new hC(process.pid)),`${n[0].role} successfully deleted`}a(Kce,"dropRole");async function Yce(){return pC({table:"hdb_role",schema:"system",hash_attribute:"id",attribute:"id",value:"*",get_attributes:["*"]})}a(Yce,"listRoles")});var EC={};ye(EC,{start:()=>I$,startOnMainThread:()=>zce});function I$({ensureTable:e}){return{handleFile:t,setupFile:t};async function t(r){let n=(0,b$.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(Wce.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 jce(i)}}}async function jce(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,A$.isEqual)(i,e)?void 0:(e.id=r.id,(0,BS.alterRole)(e))}return(0,BS.addRole)(e)}var BS,b$,A$,Wce,zce,w$=se(()=>{Oe();BS=b(oh()),b$=require("yaml"),A$=require("lodash"),Wce=["super_user","cluster_user","structure_user"];a(I$,"start");a(jce,"ensureRole");zce=I$});async function FS(e){let t=(0,O$.pathToFileURL)(e).toString();if(Jce)return ah||(ah=Qce(Zce)),(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 Qce(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:Xce,...e()},{},{name:"h-dapp",resolveHook(r,n){return r==="harperdb"?"harperdb":(r=new URL(r,n).toString(),(0,C$.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,N$.readFile)(new URL(r),{encoding:"utf-8"});return new t(n,r)},"importHook")}),ah}function Xce(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 Zce(){return{Resource:Xt,tables:yn}}var N$,C$,O$,Jce,ah,_C=se(()=>{Ji();Oe();N$=require("fs/promises"),C$=require("path"),O$=require("url"),Jce=!1;a(FS,"secureImport");a(Qce,"getCompartment");a(Xce,"secureOnlyFetch");a(Zce,"getGlobalVars")});var gC={};ye(gC,{ResourceLoadError:()=>kS,handleApplication:()=>ele,suppressHandleApplicationWarning:()=>tle});function L$(e){return typeof e=="function"&&("get"in e||"put"in e||"post"in e||"delete"in e)}async function ele(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,P$.dirname)(r.urlPath).replace(/\\/g,"/").replace(/^\/$/,"");L$(n.default)&&(e.resources.set(s,n.default),e.logger.debug(`Registered root resource: ${s}`)),D$(e,n,s)}catch(n){throw new kS(r.absolutePath,n)}},"handleResourceEntry"))}function D$(e,t,r){for(let n in t){let s=t[n],i=`${r}/${n}`;L$(s)?(e.resources.set(i,s),e.logger.debug(`Registered resource: ${i}`)):typeof s=="object"&&D$(e,s,i)}}var P$,kS,tle,v$=se(()=>{_C();P$=require("path");a(L$,"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(ele,"handleApplication");a(D$,"recurseForResources");tle=!0});var TC={};ye(TC,{start:()=>rle});function rle({resources:e}){e.set("login",SC),e.loginPath=t=>"/login?redirect="+encodeURIComponent(t.url)}var SC,M$=se(()=>{Ji();a(rle,"start");SC=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:nle,info:{title:"HarperDB HTTP REST interface",version:H$.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 RC(HS[l.type],l.type):l.properties?(o[l.name]=new q$(l.type),s(l)):l.elements?.properties&&(o[l.name]=new ale(l.elements.type),s(l.elements)),l.nullable===!1&&c.push(l.name);r.components.schemas[i.type]=new k$(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 RC(HS[Y.type],Y.type)}:k==="Any"?m[z]={format:k}:m[z]=new RC(HS[k],k),p.push(new bC(z,"query",m[z]))}let E=Object.keys(m),_=new bC(f,"path",{type:"string",format:"ID"});_.required=!0,_.description="primary key of record";let R=new bC("property","path",{enum:E});R.required=!0,r.components.schemas[c]=new k$(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 sle(c,n,{200:new kd({$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 U$(p,n,{200:new x$},"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 yC(p,n,{200:new kd({type:"array",items:{$ref:$s+c}})},"search for records by the specified property name and value pairs")),I&&(r.paths[X].delete=new F$(p,n,"delete all the records that match the provided query",{204:new B$}));let q="/"+o+"/{"+f+"}";if(r.paths[q]||(r.paths[q]={}),r.paths[q].options=new U$(p,n,{200:new x$},"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 yC([_],n,{200:new kd({$ref:$s+c})},"retrieve a record by its primary key")),y&&(r.paths[q].put=new ile([_],n,c,{200:new kd({$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 ole([_],n,c,{200:new kd({$ref:$s+c})},"patch the record with the URL path that maps to the record's primary key")),I&&(r.paths[q].delete=new F$([_],n,"delete a record with the given primary key",{204:new B$})),w&&R.schema.enum.length>0){let k=`/${o}/{${f}}.{property}`;r.paths[k]||(r.paths[k]={}),r.paths[k].get=new yC([_,R],n,{200:new kd({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 sle(e,t,r,n){this.description=n,this.requestBody={content:{"application/json":{schema:{$ref:$s+e}}}},this.security=t,this.responses=r}function yC(e,t,r,n){this.description=n,this.parameters=e,this.security=t,this.responses=r}function U$(e,t,r,n){this.description=n,this.parameters=e,this.security=t,this.responses=r}function x$(){this.description=G$,this.headers={},this.content={}}function kd(e,t){this.description=G$,this.content={"application/json":{schema:e}},this.headers=t}function B$(){this.description="successfully processed request, no content returned to client"}function ile(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 ole(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 F$(e,t,r,n){this.description=r,this.parameters=e,this.security=t,this.responses=n}function k$(e,t,r){this.type="object",this.properties=e,this.additionalProperties=t,this.required=r}function RC(e,t){this.type=e,(e==="string"||e==="number"||e==="integer")&&t!=="String"&&(this.format=t)}function q$(e){this.$ref=`#/components/schemas/${e}`}function ale(e){this.type="array",this.items=new q$(e)}function bC(e,t,r){this.name=e,this.in=t,this.schema=r}var H$,nle,HS,$s,G$,AC=se(()=>{H$=b(Rt()),nle="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/",G$="successful operation";a(GS,"generateJsonApi");a(sle,"Post");a(yC,"Get");a(U$,"Options");a(x$,"ResponseOptions200");a(kd,"Response200");a(B$,"Response204");a(ile,"Put");a(ole,"Patch");a(F$,"Delete");a(k$,"ResourceSchema");a(RC,"Type");a(q$,"Ref");a(ale,"ArrayRef");a(bC,"Parameter")});var V$={};ye(V$,{Request:()=>pc,createReuseportFd:()=>qS});var $$,pc,IC,wC,qS,ch=se(()=>{$$=require("os"),pc=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 wC(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 IC(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)}},IC=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)}},wC=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,$$.platform)()!="win32"&&(qS=require("node-unix-socket").createReuseportFd)});var VS={};ye(VS,{parseHeaderValue:()=>CC,start:()=>ule});async function lle(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!==K$){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=CC(_);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 _=CC(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=$o(r["content-type"],!0)(e.body,e.headers)}catch(_){throw new Hd.ClientError(_,400)}if(e.authorize=!0,o===K$&&s==="GET"){if(e?.user?.role?.permission?.super_user)return GS($S,`${e.protocol}://${e.hostname}`);throw new Hd.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 Hd.ClientError("HarperDB is short and stout and can't brew coffee",418);default:throw new Hd.ServerError(`Method ${s} is not recognized`,501)}}),m=200,p=e.lastModified;if(f==null)m=s==="GET"||s==="HEAD"?404:204,NC.lastModified&&isFinite(p)&&i.setIfNone("Last-Modified",new Date(p).toUTCString());else if(f.status>0&&f.headers){let _=Nq(f.headers,i);return f.headers!==_&&(f.headers=_),f.data!==void 0&&(f.body=Vm(f.data,e,f)),f}else if(isFinite(p)){cle[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",_),NC.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?gi.warn(o):gi.info(o):gi.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?j$(o):o,e,c),c}}function ule(e){NC=e,e.includeExpensiveRecordCountEstimates&&(pc.prototype.includeExpensiveRecordCountEstimates=!0),!Y$&&(Y$=!0,$S=e.resources,e.server.http(async(t,r)=>{if(!t.isWebSocket)return lle(t,r)},e),e.webSocket!==!1&&e.server.ws(async(t,r,n)=>{lh++;let s=new is;W$||(W$=!0,op(l=>{lh>0&&l.push({metric:"ws-connections",connections:lh,byThread:!0})}));let i;t.on("error",l=>{i=!0,gi.warn(l)});let o;t.on("message",a(function(u){o||(o=$o(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 qo(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?gi.warn(l):gi.info(l):gi.error(l),t.close(dle[l.statusCode]||1011,j$(l))}t.close()},e))}function CC(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 gi,Hd,j$,sn,cle,NC,K$,Y$,$S,W$,lh,dle,z$=se(()=>{Vo();as();gi=b(Q()),Hd=b(Ee());Pg();qu();za();jp();AC();ch();Dg();({errorToString:j$}=gi),sn=new Uint8Array(8),cle=new Float64Array(sn.buffer,0,1),NC={},K$="openapi";a(lle,"http");lh=0;a(ule,"start");dle={401:3e3,403:3003};a(CC,"parseHeaderValue")});var OC=M((xxe,Q$)=>{var{recordAction:KS,recordActionBinary:J$}=(as(),D(Tg)),fle=require("fastify-plugin"),mle=200;Q$.exports=fle(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=mle;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 Z$=M((Bxe,X$)=>{var ple=mt(),hle={user:{presence:!0},schema:{presence:!0},table:{presence:!0},operation:{presence:!0}};X$.exports=function(e){return ple.validateObject(e,hle)}});var YS=M((Fxe,eV)=>{"use strict";var Ele=(G(),D(j)).OPERATIONS_ENUM,PC=class{static{a(this,"UpdateObject")}constructor(t,r,n,s=void 0){this.operation=Ele.UPDATE,this.schema=t,this.table=r,this.records=n,this.__origin=s}};eV.exports=PC});var fh={};ye(fh,{createTokens:()=>DC,getJWTRSAKeys:()=>QS,refreshOperationToken:()=>vC,validateOperationToken:()=>MC,validateRefreshToken:()=>XS});async function QS(){if(WS)return WS;try{let e=uh.default.join(dh.default.getHdbBasePath(),lA),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 JS.default.error(e),new Si.ClientError(qd.NO_ENCRYPTION_KEYS,Gd.INTERNAL_SERVER_ERROR)}}async function DC(e){let t=(0,LC.validateBySchema)(e,uo.default.object({username:uo.default.string().optional(),password:uo.default.string().optional(),role:uo.default.string().optional(),expires_in:uo.default.alternatives(uo.default.string(),uo.default.number()).optional()}));if(t)throw new Si.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 yd(e.username,e.password,f)}catch(f){throw JS.default.error(f),new Si.ClientError(qd.INVALID_CREDENTIALS,Gd.UNAUTHORIZED)}if(!r)throw new Si.ClientError(qd.INVALID_CREDENTIALS,Gd.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 QS(),c=await $d.default.sign(i,{key:o.privateKey,passphrase:o.passphrase},{expiresIn:e.expires_in??iV,algorithm:zS,subject:Vd.OPERATION}),l=await $d.default.sign(i,{key:o.privateKey,passphrase:o.passphrase},{expiresIn:_le,algorithm:zS,subject:Vd.REFRESH}),u=mN(l,$r.SHA256);if((await(0,tV.update)(new rV.default(gm,xu.USER_TABLE_NAME,[{username:e.username,refresh_token:u}]))).skipped_hashes.length>0)throw new Si.ClientError(qd.REFRESH_TOKEN_SAVE_FAILED,Gd.INTERNAL_SERVER_ERROR);return nV.default.signalUserChange(new sV.UserEventMsg(process.pid)),{operation_token:c,refresh_token:l}}async function vC(e){let t=(0,LC.validateBySchema)(e,uo.default.object({refresh_token:uo.default.string().required()}).required());if(t)throw new Si.ClientError(t.message);let{refresh_token:r}=e;await XS(r);let n=await QS(),s=await $d.default.decode(r);return{operation_token:await $d.default.sign({username:s.username,super_user:s.super_user,cluster_user:s.cluster_user},{key:n.privateKey,passphrase:n.passphrase},{expiresIn:iV,algorithm:zS,subject:Vd.OPERATION})}}async function MC(e){return oV(e,Vd.OPERATION)}async function XS(e){return oV(e,Vd.REFRESH)}async function oV(e,t){try{let r=await QS(),n=await $d.default.verify(e,r.publicKey,{algorithms:zS,subject:t});if(n.role)throw new Error("Invalid token");let s=await yd(n.username,void 0,!1);if(t===Vd.REFRESH&&!pN(s.refresh_token,e))throw new Error("Invalid token");return s}catch(r){throw JS.default.warn(r),r?.name==="TokenExpiredError"?new Si.ClientError(qd.TOKEN_EXPIRED,Gd.FORBIDDEN):new Si.ClientError(qd.INVALID_TOKEN,Gd.UNAUTHORIZED)}}var $d,jS,uh,uo,LC,Si,JS,tV,rV,nV,sV,dh,Gd,qd,iV,_le,zS,Vd,WS,Kd=se(()=>{$d=b(require("jsonwebtoken")),jS=b(require("fs-extra")),uh=b(require("node:path")),uo=b(require("joi")),LC=b(mt());G();Si=b(Ee()),JS=b(Q());EN();Yn();tV=b(Vn()),rV=b(YS()),nV=b(Xo()),sV=b(ds()),dh=b(fe()),{HTTP_STATUS_CODES:Gd,AUTHENTICATION_ERROR_MSGS:qd}=Si.hdbErrors;dh.default.initSync();iV=dh.default.get(x.AUTHENTICATION_OPERATIONTOKENTIMEOUT)||"1d",_le=dh.default.get(x.AUTHENTICATION_REFRESHTOKENTIMEOUT)||"30d",zS="RS256",Vd={OPERATION:"operation",REFRESH:"refresh"};a(QS,"getJWTRSAKeys");a(DC,"createTokens");a(vC,"refreshOperationToken");a(MC,"validateOperationToken");a(XS,"validateRefreshToken");a(oV,"validateToken")});var UC=M((Vxe,lV)=>{"use strict";var gle=Z$(),Yd=require("passport"),Sle=require("passport-local").Strategy,Tle=require("passport-http").BasicStrategy,yle=require("util"),Rle=(Yn(),D(_i)),cV=yle.callbackify(Rle.findAndValidateUser),$xe=Jr(),ble=(G(),D(j)),aV=(Kd(),D(fh)),{AccessViolation:Ale}=Ee();Yd.use(new Sle(function(e,t,r){cV(e,t,r)}));Yd.use(new Tle(function(e,t,r){cV(e,t,r)}));Yd.serializeUser(function(e,t){t(null,e)});Yd.deserializeUser(function(e,t){t(null,e)});function Ile(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 Ale)}switch(a(i,"handleResponse"),n){case"Basic":Yd.authenticate("basic",{session:!1},(o,c)=>{i(o,c)})(e,t,r);break;case"Bearer":e.body?.operation&&e.body.operation===ble.OPERATIONS_ENUM.REFRESH_OPERATION_TOKEN?aV.validateRefreshToken(s).then(o=>{e.body.refresh_token=s,r(null,o)}).catch(o=>{r(o)}):aV.validateOperationToken(s).then(o=>{r(null,o)}).catch(o=>{r(o)});break;default:Yd.authenticate("local",{session:!1},function(o,c){i(o,c)})(e,t,r);break}}a(Ile,"authorize");function wle(e,t){let r=gle(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(wle,"checkPermissions");lV.exports={authorize:Ile,checkPermissions:wle}});var GC=M((jxe,mV)=>{var rT=require("clone"),nT=mt(),Nle=ae(),eT=(G(),D(j)),Yxe=Q(),xC=require("fs"),FC=require("joi"),{string:tT}=FC.types(),{hdbErrors:Cle,handleHDBError:ZS}=Ee(),{HDB_ERROR_MSGS:Wxe,HTTP_STATUS_CODES:BC}=Cle,{commonValidators:Wd}=Xi(),uV=" is required",Ole=["insert","update","upsert"],kC={database:{presence:!1,format:Wd.schema_format,length:Wd.schema_length},schema:{presence:!1,format:Wd.schema_format,length:Wd.schema_length},table:{presence:!0,format:Wd.schema_format,length:Wd.schema_length},action:{inclusion:{within:Ole,message:"is required and must be either insert, update, or upsert"}},file_path:{},csv_url:{url:{allowLocal:!0}},data:{},passthrough_headers:{}},Ple={schema:tT.required(),table:tT.required(),action:tT.valid("insert","update","upsert")},{AWS_ACCESS_KEY:Lle,AWS_SECRET:Dle,AWS_BUCKET:vle,AWS_FILE_KEY:Mle,REGION:Ule}=eT.S3_BUCKET_AUTH_KEYS,xle={s3:{presence:!0},[`s3.${Lle}`]:{presence:!0,type:"String"},[`s3.${Dle}`]:{presence:!0,type:"String"},[`s3.${vle}`]:{presence:!0,type:"String"},[`s3.${Mle}`]:{presence:!0,type:"String",hasValidFileExt:[".csv",".json"]},[`s3.${Ule}`]:{presence:!0,type:"String"}},dV=rT(kC);dV.data.presence={message:uV};var fV=rT(kC);fV.file_path.presence={message:uV};var Ble=Object.assign(rT(kC),xle),HC=rT(Ple);HC.csv_url=tT.uri().messages({"string.uri":"'csv_url' must be a valid url"}).required();HC.passthrough_headers=FC.object();function Fle(e){let t=nT.validateObject(e,dV);return sT(e,t)}a(Fle,"dataObject");function kle(e){let t=nT.validateBySchema(e,FC.object(HC));return sT(e,t)}a(kle,"urlObject");function Hle(e){let t=nT.validateObject(e,fV);return sT(e,t)}a(Hle,"fileObject");function Gle(e){let t=nT.validateObject(e,Ble);return sT(e,t)}a(Gle,"s3FileObject");function sT(e,t){if(!t){let r=Nle.checkGlobalSchemaTable(e.schema,e.table);if(r)return ZS(new Error,r,BC.BAD_REQUEST);if(e.operation===eT.OPERATIONS_ENUM.CSV_FILE_LOAD)try{xC.accessSync(e.file_path,xC.constants.R_OK|xC.constants.F_OK)}catch(n){return n.code===eT.NODE_ERROR_CODES.ENOENT?ZS(n,`No such file or directory ${n.path}`,BC.BAD_REQUEST):n.code===eT.NODE_ERROR_CODES.EACCES?ZS(n,`Permission denied ${n.path}`,BC.BAD_REQUEST):ZS(n)}}return t}a(sT,"postValidateChecks");mV.exports={dataObject:Fle,urlObject:kle,fileObject:Hle,s3FileObject:Gle}});var qC=M((Jxe,pV)=>{"use strict";var mh=Q(),iT=(G(),D(j));async function qle(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(qle,"callOperationFunctionAsAwait");pV.exports={callOperationFunctionAsAwait:qle}});var $C=M((Xxe,EV)=>{"use strict";var{S3:$le,GetObjectCommand:Vle}=require("@aws-sdk/client-s3");EV.exports={getFileStreamFromS3:Kle,getS3AuthObj:hV};async function Kle(e){let{s3:t}=e,r={Bucket:t.bucket,Key:t.key};return(await hV(t.aws_access_key_id,t.aws_secret_access_key,t.region).send(new Vle(r))).Body}a(Kle,"getFileStreamFromS3");function hV(e,t,r){return new $le({credentials:{accessKeyId:e,secretAccessKey:t},region:r})}a(hV,"getS3AuthObj")});var gV=M((e0e,_V)=>{"use strict";var VC=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}},KC=class{static{a(this,"BulkLoadDataObject")}constructor(t,r,n,s){this.action=t,this.schema=r,this.table=n,this.data=s}};_V.exports={BulkLoadFileObject:VC,BulkLoadDataObject:KC}});var TV=M((r0e,SV)=>{"use strict";var YC=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}};SV.exports=YC});var RV=M((s0e,yV)=>{"use strict";var WC=class{static{a(this,"PermissionAttributeResponseObject")}constructor(t,r=[]){this.attribute_name=t,this.required_permissions=r}};yV.exports=WC});var zC=M((o0e,AV)=>{"use strict";var bV=TV(),Yle=RV(),{HDB_ERROR_MSGS:Wle}=Jr(),jC=class{static{a(this,"PermissionResponseObject")}constructor(){this.error=Wle.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 bV(t,r,n),i=`${t}_${r}`;this.unauthorized_access[i]=s}addUnauthorizedAttributes(t,r,n,s){let i=[];t.forEach(c=>{let l=new Yle(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 bV(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}};AV.exports=jC});var Kl=M((l0e,CV)=>{"use strict";var c0e=Sn(),ph=Q(),{validateBySchema:IV}=mt(),sa=require("joi"),jle=so(),oT=ae(),{handleHDBError:aT,hdbErrors:zle,ClientError:wV}=Ee(),{HDB_ERROR_MSGS:cT,HTTP_STATUS_CODES:JC}=zle,NV=fe();NV.initSync();var{getDatabases:QC}=(Oe(),D(pt)),Jle=require("fs-extra"),Qle=(G(),D(j));CV.exports={describeAll:Xle,describeTable:lT,describeSchema:Zle};async function Xle(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=QC(),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(Xle,"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=IV(e,sa.object({database:sa.string(),table:sa.string().required(),exact_count:sa.boolean().strict(),include_computed:sa.boolean().strict()}));if(i)throw new wV(i.message);let c=QC()[r];if(!c)throw aT(new Error,cT.SCHEMA_NOT_FOUND(e.schema),JC.NOT_FOUND);let l=c[n];if(!l)throw aT(new Error,cT.TABLE_NOT_FOUND(e.schema,e.table),JC.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")),NV.get(Qle.CONFIG_PARAMS.CLUSTERING_ENABLED)&&(m.clustering_stream_name=jle.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 Zle(e){oT.transformReq(e);let t=IV(e,sa.object({database:sa.string(),exact_count:sa.boolean().strict(),include_computed:sa.boolean().strict()}));if(t)throw new wV(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=QC()[n];if(!i)throw aT(new Error,cT.SCHEMA_NOT_FOUND(e.schema),JC.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(Zle,"describeSchema")});var vV=M((d0e,DV)=>{"use strict";var eue=Kl(),{hdbErrors:OV}=Ee(),{getDatabases:PV}=(Oe(),D(pt));DV.exports={checkSchemaExists:LV,checkSchemaTableExists:tue,schemaDescribe:eue};async function LV(e){if(!PV()[e])return OV.HDB_ERROR_MSGS.SCHEMA_NOT_FOUND(e)}a(LV,"checkSchemaExists");async function tue(e,t){let r=await LV(e);if(r)return r;if(!PV()[e][t])return OV.HDB_ERROR_MSGS.TABLE_NOT_FOUND(e,t)}a(tue,"checkSchemaTableExists")});var uT=M((m0e,MV)=>{"use strict";var rue=ps();MV.exports={writeTransaction:nue};function nue(e,t,r){return rue.writeTransaction(e,t,r)}a(nue,"writeTransaction")});var rO=M((g0e,YV)=>{"use strict";var{decode:sue}=require("msgpackr"),{isMainThread:h0e,parentPort:E0e,threadId:_0e}=require("worker_threads"),mT=cr(),jd=vt(),eO=(G(),D(j)),Rn=Q(),ZC=fe(),iue=(G(),D(j)),{onMessageByType:oue}=st(),FV=so(),{recordAction:UV,recordActionBinary:aue}=(as(),D(Tg)),{publishToStream:cue}=mT,{ConsumerEvents:xV}=require("nats"),lue=Sn(),{promisify:uue}=require("util"),{decodeBlobsWithWrites:due}=(os(),D(ig)),kV=uue(setTimeout),pT=1e4,hT,fT,fue,mue,HV,hh=new Map,zd=new Map;YV.exports={initialize:GV,ingestConsumer:tO,setSubscription:pue,setIgnoreOrigin:_ue,getDatabaseSubscriptions:Eue,updateConsumer:qV};async function GV(){oue(eO.ITC_EVENT_TYPES.NATS_CONSUMER_UPDATE,async n=>{await qV(n)}),HV=!0,Rn.notify("Initializing clustering ingest service.");let{connection:e,jsm:t,js:r}=await mT.getNATSReferences();hT=e,fT=e.info.server_name,fue=t,mue=r}a(GV,"initialize");async function qV(e){if(e.status==="start"){let{js:t,jsm:r}=await $V(e.node_domain_name);tO(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")),zd.get(e.node_domain_name)==="failed"&&zd.set(e.node_domain_name,"close")}}a(qV,"updateConsumer");var ET=new Map;function pue(e,t,r){let n=ET.get(e);n||ET.set(e,n=new Map),n.set(t,r),HV||GV().then(hue)}a(pue,"setSubscription");async function hue(){let e=await lue.searchByValue({database:"system",table:"hdb_nodes",attribute:"name",value:"*"});for await(let t of e){let r=t.name+jd.SERVER_SUFFIX.LEAF,n,s;for(let i of t.subscriptions||[])if(i.subscribe===!0){if(!n&&({js:n,jsm:s}=await $V(r),!n))break;let{schema:o,table:c}=i,l=FV.createNatsTableStreamName(o,c);tO(l,n,s,r)}}}a(hue,"accessConsumers");async function $V(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(zd.get(e)==="close")break;zd.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 kV(i)}return{js:t,jsm:r}}a($V,"connectToRemoteJS");function Eue(){return ET}a(Eue,"getDatabaseSubscriptions");var VV;function _ue(e){VV=e}a(_ue,"setIgnoreOrigin");var KV=100,BV=new Array(KV),dT=0;async function tO(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(zd.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 kV(d)}let c=!1,l;for(;!c;){if(hh.get(e+n)==="close"||zd.get(n)==="close"){hh.delete(e+n),c=!0;continue}l=await i.consume({max_messages:ZC.get(eO.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===xV.ConsumerDeleted&&(await l.close(),c=!0),d.type===xV.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 BV[dT],BV[dT]=gue(d).catch(f=>{Rn.error(f)}),++dT>=KV&&(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(tO,"ingestConsumer");async function gue(e){let t;await due(()=>{t=sue(e.data)}),UV(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(eO.CONFIG_PARAMS.CLUSTERING_NODENAME);r.has(jd.MSG_HEADERS.TRANSACTED_NODES)&&r.values(jd.MSG_HEADERS.TRANSACTED_NODES).indexOf(s)>-1&&(n=!0);let i=r.get(jd.MSG_HEADERS.ORIGIN);if(n||(n=i===s&&!VV),aue(n,"echo",e.subject,t.operation,"ingest"),n){e.ack();return}r.append(jd.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(jd.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:XC(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:XC(o),value:H,expiresAt:p,id:f?.[X],table:u}));for(;l;)I.push({type:XC(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(iue.CONFIG_PARAMS.CLUSTERING_REPUBLISHMESSAGES)!==!1&&cue(e.subject.split(".").slice(0,-1).join("."),FV.createNatsTableStreamName(c,u),e.headers,e.data),await E;let w=Date.now()-_;_&&UV(w,"replication-latency",e.subject,o,"ingest")}catch(o){Rn.error(o)}e.ack()}a(gue,"messageProcessor");function XC(e){switch(e){case"insert":case"upsert":case"update":return"put"}return e}a(XC,"convertOperation")});var cr=M((I0e,l1)=>{"use strict";var Kr=fe();Kr.initSync();var Sue=require("fs-extra"),Tue=require("semver"),gh=require("path"),{monotonicFactory:yue}=require("ulidx"),jV=yue(),Rue=require("util"),zV=require("child_process"),bue=Rue.promisify(zV.exec),Aue=zV.spawn,on=vt(),rt=(G(),D(j)),{packageJson:Iue,PACKAGE_ROOT:wue}=Rt(),_T=ae(),Ti=Q(),gT=so(),Nue=uT(),Eh=_t(),{broadcast:Cue,onMessageByType:Oue,getWorkerIndex:Pue}=st(),{isMainThread:JV}=require("worker_threads"),{Encoder:Lue,decode:oO}=require("msgpackr"),QV=new Lue,{isEmpty:zl}=_T,XV=(Yn(),D(_i)),T0e=48*36e11;JV&&Oue(rt.ITC_EVENT_TYPES.RESTART,()=>{bn=void 0,jl=void 0});var{connect:Due,StorageType:vue,RetentionPolicy:Mue,AckPolicy:aO,DeliverPolicy:cO,DiscardPolicy:Uue,NatsConnection:y0e,JetStreamManager:R0e,JetStreamClient:b0e,StringCodec:A0e,JSONCodec:xue,createInbox:lO,headers:Bue,ErrorCode:WV}=require("nats"),{recordAction:Fue}=(as(),D(Tg)),{encodeBlobsAsBuffers:kue}=(os(),D(ig)),ZV=xue(),Hue="clustering",Gue=Iue.engines[on.NATS_SERVER_NAME],que=gh.join(wue,"dependencies"),iO=gh.join(que,`${process.platform}-${process.arch}`,on.NATS_BINARY_NAME),nO,sO,_h,Yl,Wl;l1.exports={runCommand:e1,checkNATSServerInstalled:$ue,createConnection:uO,getConnection:Sh,getJetStreamManager:Th,getJetStream:r1,getNATSReferences:fo,getServerList:Kue,createLocalStream:dO,listStreams:n1,deleteLocalStream:Yue,getServerConfig:Jd,listRemoteStreams:Wue,viewStream:jue,viewStreamIterator:zue,publishToStream:Jue,request:Zue,reloadNATS:fO,reloadNATSHub:ede,reloadNATSLeaf:tde,extractServerName:Xue,requestErrorHandler:rde,createLocalTableStream:a1,createTableStreams:ide,purgeTableStream:c1,purgeSchemaTableStreams:ode,getStreamInfo:ade,updateLocalStreams:lde,closeConnection:Vue,getJsmServerName:ST,addNatsMsgHeader:s1,clearClientCache:t1,updateRemoteConsumer:nde,createConsumer:i1,updateConsumerIterator:sde};async function e1(e,t=void 0){let{stdout:r,stderr:n}=await bue(e,{cwd:t});if(n)throw new Error(n.replace(`
|
|
16
16
|
`,""));return r.replace(`
|
|
17
17
|
`,"")}a(e1,"runCommand");async function $ue(){try{await Sue.access(iO)}catch{return!1}let e=await e1(`${iO} --version`,void 0),t=e.substring(e.lastIndexOf("v")+1,e.length);return Tue.eq(t,Gue)}a($ue,"checkNATSServerInstalled");async function uO(e,t,r,n=!0,s="127.0.0.1"){if(!t&&!r){let o=await XV.getClusterUser();if(zl(o))throw new Error("Unable to get nats connection. Cluster user is undefined.");t=o.username,r=o.decrypt_hash}Ti.trace("create nats connection called");let i=await Due({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(),Ti.trace("create connection established a nats client connection with id",i?.info?.client_id),i.closed().then(o=>{o&&Ti.error("Error with Nats client connection, connection closed",o),i===bn&&t1()}),i}a(uO,"createConnection");function t1(){bn=void 0,Yl=void 0,Wl=void 0,jl=void 0}a(t1,"clearClientCache");async function Vue(){bn&&(await bn.drain(),bn=void 0,Yl=void 0,Wl=void 0,jl=void 0)}a(Vue,"closeConnection");var bn,jl;async function Sh(){return jl||(jl=uO(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 r1(){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(r1,"getJetStream");async function fo(){let e=bn||await Sh(),t=Yl||await Th(),r=Wl||await r1();return{connection:e,jsm:t,js:r}}a(fo,"getNATSReferences");async function Kue(e){let t=Kr.get(rt.CONFIG_PARAMS.CLUSTERING_HUBSERVER_NETWORK_PORT),{sys_name:r,decrypt_hash:n}=await XV.getClusterUser(),s=await uO(t,r,n),i=lO(),o=s.subscribe(i),c=[],l,u=(async()=>{for await(let d of o){let f=ZV.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(Kue,"getServerList");async function dO(e,t){let{jsm:r}=await fo(),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:vue.File,retention:Mue.Limits,subjects:t,discard:Uue.Old,maxMsgs:s,maxBytes:i,maxAge:n})}a(dO,"createLocalStream");async function n1(){let{jsm:e}=await fo(),t=await e.streams.list().next(),r=[];return t.forEach(n=>{r.push(n)}),r}a(n1,"listStreams");async function Yue(e){let{jsm:t}=await fo();await t.streams.delete(e)}a(Yue,"deleteLocalStream");async function Wue(e){let{connection:t}=await fo(),r=[],n=lO(),s=t.subscribe(n),i=(async()=>{for await(let o of s)r.push(ZV.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(Wue,"listRemoteStreams");async function jue(e,t=void 0,r=void 0){let{jsm:n,js:s}=await fo(),i=jV(),o={durable_name:i,ack_policy:aO.Explicit};t&&(o.deliver_policy=cO.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=oO(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(jue,"viewStream");async function*zue(e,t=void 0,r=void 0){let{jsm:n,js:s}=await fo(),i=jV(),o={durable_name:i,ack_policy:aO.Explicit};t&&(o.deliver_policy=cO.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=oO(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(zue,"viewStreamIterator");async function Jue(e,t,r,n){Ti.trace(`publishToStream called with subject: ${e}, stream: ${t}, entries:`,n.operation),r=s1(n,r);let{js:s}=await fo(),i=await ST(),o=`${e}.${i}`,c=await kue(()=>n instanceof Uint8Array?n:QV.encode(n));try{Ti.trace(`publishToStream publishing to subject: ${o}`),Fue(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 o1(async()=>{try{await s.publish(o,c,{headers:r})}catch{if(l.code&&l.code.toString()==="503"){Ti.trace(`publishToStream creating stream: ${t}`);let d=o.split(".");d[2]="*",await dO(t,[o]),await s.publish(o,c,{headers:r})}else throw l}});throw l}}a(Jue,"publishToStream");function s1(e,t){t===void 0&&(t=Bue());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(s1,"addNatsMsgHeader");function Jd(e){e=e.toLowerCase();let t=gh.join(Kr.get(rt.CONFIG_PARAMS.ROOTPATH),Hue);if(e===rt.PROCESS_DESCRIPTORS.CLUSTERING_HUB.toLowerCase())return zl(sO)&&(sO={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}),sO;if(e===rt.PROCESS_DESCRIPTORS.CLUSTERING_LEAF.toLowerCase())return zl(nO)&&(nO={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}),nO;Ti.error(`Unable to get Nats server config. Unrecognized process: ${e}`)}a(Jd,"getServerConfig");async function i1(e,t,r,n){try{await e.consumers.add(t,{ack_policy:aO.Explicit,durable_name:r,deliver_policy:cO.StartTime,opt_start_time:n})}catch(s){if(s.message!=="consumer already exists")throw s}}a(i1,"createConsumer");async function Que(e,t,r){await e.consumers.delete(t,r)}a(Que,"removeConsumer");function Xue(e){return e.split(".")[1]}a(Xue,"extractServerName");async function Zue(e,t,r=6e4,n=lO()){if(!_T.isObject(t))throw new Error("data param must be an object");let s=QV.encode(t),{connection:i}=await fo(),o={timeout:r};n&&(o.reply=n,o.noMux=!0);let c=await i.request(e,s,o);return oO(c.data)}a(Zue,"request");function fO(e){return new Promise(async(t,r)=>{let n=Aue(iO,["--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(fO,"reloadNATS");async function ede(){let{pid_file_path:e}=Jd(rt.PROCESS_DESCRIPTORS.CLUSTERING_HUB);await fO(e)}a(ede,"reloadNATSHub");async function tde(){let{pid_file_path:e}=Jd(rt.PROCESS_DESCRIPTORS.CLUSTERING_LEAF);await fO(e)}a(tde,"reloadNATSLeaf");function rde(e,t,r){let n;switch(e.code){case WV.NoResponders:n=`Unable to ${t}, node '${r}' is not listening.`;break;case WV.Timeout:n=`Unable to ${t}, node '${r}' is listening but did not respond.`;break;default:n=e.message;break}return n}a(rde,"requestErrorHandler");async function nde(e,t){let r=t+on.SERVER_SUFFIX.LEAF,{connection:n}=await fo(),{jsm:s}=await dde(r),{schema:i,table:o}=e,c=gT.createNatsTableStreamName(i,o),l=e.start_time?e.start_time:new Date(Date.now()).toISOString();await o1(async()=>{if(e.subscribe===!0)await i1(s,c,n.info.server_name,l);else try{await Que(s,c,n.info.server_name)}catch(u){Ti.trace(u)}})}a(nde,"updateRemoteConsumer");async function sde(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&&Pue()<Kr.get(rt.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXINGESTTHREADS)){let{updateConsumer:c}=rO();await c(o)}await Cue(o),n==="stop"&&await _T.asyncSetTimeout(1e3)}a(sde,"updateConsumerIterator");function o1(e){return Nue.writeTransaction(rt.SYSTEM_SCHEMA_NAME,rt.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,e)}a(o1,"exclusiveLock");async function a1(e,t){let r=gT.createNatsTableStreamName(e,t),n=await ST(),s=cde(e,t,n);await dO(r,[s])}a(a1,"createLocalTableStream");async function ide(e){for(let t=0,r=e.length;t<r;t++){let n=e[t].schema,s=e[t].table;await a1(n,s)}}a(ide,"createTableStreams");async function c1(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")Ti.warn(n);else throw n}}a(c1,"purgeTableStream");async function ode(e,t){if(Kr.get(rt.CONFIG_PARAMS.CLUSTERING_ENABLED))for(let r=0,n=t.length;r<n;r++)await c1(e,t[r])}a(ode,"purgeSchemaTableStreams");async function ade(e){return(await Th()).streams.info(e)}a(ade,"getStreamInfo");function cde(e,t,r){return`${on.SUBJECT_PREFIXES.TXN}.${e}${t?"."+t:""}.${r}`}a(cde,"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 lde(){let e=await Th(),t=await ST(),r=await n1();for(let n of r){let s=n.config,i=s.subjects[0];if(!i)continue;let o=ude(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(".");Ti.trace(`Updating stream subject name from: ${i} to: ${d}`),s.subjects[0]=d,await e.streams.update(s.name,s)}}a(lde,"updateLocalStreams");function ude(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(ude,"updateStreamLimits");async function dde(e){let t,r;try{t=await bn.jetstream({domain:e}),r=await bn.jetstreamManager({domain:e,checkAPI:!1})}catch(n){throw Ti.error("Unable to connect to:",e),n}return{js:t,jsm:r}}a(dde,"connectToRemoteJS")});function mO(e){let t=e.get(TT),r=t?(0,Qd.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,Qd.pack)(r))}return r}function yh(e){return mO(e).remoteNameToId}function d1(e,t){let r=mO(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,Qd.pack)(r)),s}function yT(e,t){let r=mO(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,Qd.pack)(r))}return u1.trace?.("The remote node name map",e,n,s),s}var u1,Qd,TT,pO=se(()=>{u1=b(sr());gs();Qd=require("msgpackr"),TT=Symbol.for("remote-ids");a(mO,"getIdMappingRecord");a(yh,"exportIdMapping");a(d1,"remoteToLocalNodeId");a(yT,"getIdOfRemoteNode")});var _1={};ye(_1,{commitsAwaitingReplication:()=>Xd,getHDBNodeTable:()=>Gt,getReplicationSharedStatus:()=>Zd,iterateRoutes:()=>Ah,shouldReplicateToNode:()=>bh,subscribeToNodeUpdates:()=>ef});function Gt(){return f1||(f1=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 Zd(e,t,r,n){return new Float64Array(e.getUserSharedBuffer(["replicated",t,r],new ArrayBuffer(64),n&&{callback:n}))}function ef(e){Gt().subscribe({}).then(async t=>{for await(let r of t){let n=r?.value?.name;E1.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=hc.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===hc.default.get(x.REPLICATION_SHARD))))&&Gt().primaryStore.get(nt())?.replicates||e.subscriptions?.some(n=>(n.database||n.schema)===t&&n.subscribe)}function fde(){ef(e=>{Ec({},(t,r)=>{let n=e.name,s=m1.get(n);if(s||m1.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=Zd(i,r,n,()=>{let c=o[0],l=o.lastTime;for(let{txnTime:u,onConfirm:d}of Xd.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=hc.default.get(x.REPLICATION_SECUREPORT)??(!hc.default.get(x.REPLICATION_PORT)&&hc.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||hc.default.get(x.REPLICATION_PORT)||hc.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){p1.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 p1,h1,hc,E1,f1,m1,Xd,tf=se(()=>{Oe();gs();Fm();p1=require("worker_threads"),h1=b(Ee()),hc=b(fe());G();E1=b(sr());server.nodes=[];a(Gt,"getHDBNodeTable");a(Zd,"getReplicationSharedStatus");a(ef,"subscribeToNodeUpdates");a(bh,"shouldReplicateToNode");m1=new Map;Fx((e,t,r)=>{if(r>server.nodes.length)throw new h1.ClientError(`Cannot confirm replication to more nodes (${r}) than are in the network (${server.nodes.length})`);Xd||(Xd=new Map,fde());let n=Xd.get(e);return n||(n=[],Xd.set(e,n)),new Promise(s=>{let i=0;n.push({txnTime:t,onConfirm:a(()=>{++i===r&&s()},"onConfirm")})})});a(fde,"startSubscriptionToReplications");a(Ah,"iterateRoutes")});var A1={};ye(A1,{connectedToNode:()=>Jl,disconnectedFromNode:()=>nf,ensureNode:()=>ia,requestClusterStatus:()=>b1,startOnMainThread:()=>hO});async function hO(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}}}yi.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??_c();if(u===void 0||u.url!==d||u.shard!==e.shard)return ia(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),g1.push(u),o.find(f=>f.url===u.url))continue;s(u)}catch(d){console.error(d)}ef(s)});let n;function s(o,c=o?.name){let l=nt()&&c===nt()||_c()&&o?.url===_c();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 mo){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){mo.get(m).iterator.remove(),mo.delete(m);return}}return}if(l)return;if(!o.url){ot.info(`Node ${o.name} is missing url`);return}let u=mo.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 rf)if(o.url===p.url){rf.delete(m);break}rf.set(o.name,o)}let d=lt();if(u||(u=new Map,mo.set(o.url,u)),u.iterator=Ec(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=yi.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=mde.HDB_LEADER_URL??process.env.HDB_LEADER_URL??g1[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)},pde)}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"),nf=a(function(o){try{ot.info("Disconnected from node",o.name,o.url,"finished",!!o.finished);let c=Array.from(rf.keys()),l=c.sort(),u=l.indexOf(o.name||Ri(o.url));if(u===-1){ot.warn("Disconnected node not found in node map",o.name,c);return}let d=mo.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],_=rf.get(E);d=mo.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"),Jl=a(function(o){let c=mo.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 mo.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=yi.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,yi.onMessageByType)("disconnected-from-node",nf),(0,yi.onMessageByType)("connected-to-node",Jl),(0,yi.onMessageByType)("request-cluster-status",b1)}function b1(e,t){let r=[];for(let[n,s]of rf)try{let i=mo.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=T1(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 ia(e,t){let r=Gt();e=e??Ri(t.url),t.name=e;try{if(t.ca){let s=new y1.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=T1(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 yi,bT,ot,S1,Ih,y1,R1,T1,mde,pde,mo,nf,Jl,rf,RT,g1,Nh=se(()=>{Oe();yi=b(st());gs();bT=require("worker_threads");tf();ot=b(Q()),S1=b(require("lodash")),Ih=b(fe());G();y1=require("crypto"),R1=b(require("minimist")),{cloneDeep:T1}=S1.default,mde=(0,R1.default)(process.argv),pde=200,mo=new Map,rf=new Map,RT=new Map,g1=[];a(hO,"startOnMainThread");a(b1,"requestClusterStatus");bT.parentPort&&(nf=a(e=>{bT.parentPort.postMessage({type:"disconnected-from-node",...e})},"disconnectedFromNode"),Jl=a(e=>{bT.parentPort.postMessage({type:"connected-to-node",...e})},"connectedToNode"),(0,yi.onMessageByType)("subscribe-to-node",e=>{wh(e)}),(0,yi.onMessageByType)("unsubscribe-from-node",e=>{AT(e)}));a(ia,"ensureNode")});var Ts=M(qt=>{"use strict";var gr=require("path"),{watch:hde}=require("chokidar"),Wn=require("fs-extra"),sf=require("node-forge"),P1=require("net"),{generateKeyPair:EO,X509Certificate:oa,createPrivateKey:L1,randomBytes:Ede}=require("node:crypto"),_de=require("util");EO=_de.promisify(EO);var Mt=sf.pki,bi=require("joi"),{v4:D1}=require("uuid"),{validateBySchema:TO}=mt(),{forComponent:gde}=Q(),Ss=fe(),Vs=(G(),D(j)),{CONFIG_PARAMS:Xl}=Vs,Ai=hA(),{ClientError:gc}=Ee(),wT=require("node:tls"),{relative:v1,join:Sde}=require("node:path"),{CERTIFICATE_VALUES:I1}=Ai,Tde=tl(),_O=_t(),{table:yde,getDatabases:Rde,databases:IT}=(Oe(),D(pt)),{getJWTRSAKeys:w1}=(Kd(),D(fh)),Xe=gde("tls").conditional;qt.generateKeys=bO;qt.updateConfigCert=G1;qt.createCsr=Ode;qt.signCertificate=Pde;qt.setCertTable=of;qt.loadCertificates=F1;qt.reviewSelfSignedCert=IO;qt.createTLSSelector=$1;qt.listCertificates=K1;qt.addCertificate=xde;qt.removeCertificate=Fde;qt.createNatsCerts=vde;qt.generateCertsKeys=Dde;qt.getReplicationCert=Oh;qt.getReplicationCertAuth=Cde;qt.renewSelfSigned=Mde;qt.hostnamesFromCert=NO;qt.getKey=kde;qt.getHostnamesFromCertificate=Hde;qt.getPrimaryHostName=wO;qt.generateSerialNumber=OT;var{urlToNodeName:M1,getThisNodeUrl:bde,getThisNodeName:CT,clearThisNodeName:Ade}=(gs(),D(aa)),{readFileSync:Ide,statSync:U1}=require("node:fs"),H0e=fe(),{getTicketKeys:wde,onMessageFromWorkers:Nde}=st(),{isMainThread:x1}=require("worker_threads"),{TLSSocket:B1,createSecureContext:G0e}=require("node:tls"),yO=3650,Ch=["127.0.0.1","localhost","::1"],RO=[{name:"countryName",value:"USA"},{name:"stateOrProvinceName",value:"Colorado"},{name:"localityName",value:"Denver"},{name:"organizationName",value:"HarperDB, Inc."}];function OT(){let e=Ede(8);return e[0]=e[0]&127|1,e.toString("hex")}a(OT,"generateSerialNumber");Nde(async e=>{e.type===Vs.ITC_EVENT_TYPES.RESTART&&(Ss.initSync(!0),await IO())});var an;function Tc(){return an||(an=Rde().system.hdb_certificate,an||(an=yde({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(Tc,"getCertTable");async function Oh(){let e=$1("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 oa(r.options.cert);return r.cert_parsed=n,r.issuer=n.issuer,r}a(Oh,"getReplicationCert");async function Cde(){Tc();let e=(await Oh()).options.cert,r=new oa(e).issuer.match(/CN=(.*)/)?.[1];return an.get(r)}a(Cde,"getReplicationCertAuth");var N1,Sc=new Map;function F1(){if(N1)return;N1=!0;let e=[{configKey:Xl.TLS},{configKey:Xl.OPERATIONSAPI_TLS}];Tc();let t=gr.dirname(_O.getConfigFilePath()),r;for(let{configKey:n}of e){let s=_O.getConfigFromFile(n);if(s){Array.isArray(s)||(s=[s]);for(let i of s){let o=i.privateKey,c=o&&v1(Sde(t,"keys"),o);c&&C1(o,l=>{Sc.set(c,l)},"private key");for(let l of[!1,!0]){let u=i[l?"certificateAuthority":"certificate"];if(u&&x1){let d;C1(u,f=>{if(I1.cert===f)return;let m=i.hostname??i.hostnames??i.host??i.hosts;m&&!Array.isArray(m)&&(m=[m]);let p=q1(u),h=new oa(p),E;try{E=wO(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 oa(I1.cert)))return;let _=an.primaryStore.get(E),R=U1(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(F1,"loadCertificates");function C1(e,t,r){let n,s=a((i,o)=>{try{let c=o.mtimeMs;c&&c!==n&&(n&&x1&&Xe.warn?.(`Reloading ${r}:`,i),n=c,t(q1(i)))}catch(c){Xe.error?.(`Error loading ${r}:`,i,c)}},"loadFile");Wn.existsSync(e)?s(e,U1(e)):Xe.error?.(`${r} file not found:`,e),hde(e,{persistent:!1}).on("change",s)}a(C1,"loadAndWatch");function gO(){let e=bde();if(e==null){let t=Ch[0];return Xe.info?.("replication url is missing from harperdb-config.yaml, using default host"+t),t}return M1(e)}a(gO,"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 Ode(){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()},...RO];Xe.info?.("Creating CSR with subject",s),n.setSubject(s);let i=[{name:"unstructuredName",value:"HarperDB, Inc."},{name:"extensionRequest",extensions:k1()}];return Xe.info?.("Creating CSR with attributes",i),n.setAttributes(i),n.sign(r),sf.pki.certificationRequestToPem(n)}a(Ode,"createCsr");function k1(){let e=Ch.includes(NT())?Ch:[...Ch,NT()];return e.includes(gO())||e.push(gO()),[{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=>P1.isIP(t)?{type:7,ip:t}:{type:2,value:t})}]}a(k1,"certExtensions");async function Pde(e){let t={},r=gr.join(Ss.getHdbBasePath(),Vs.LICENSE_KEY_DIR_NAME);if(e.csr){let n,s;Tc();for await(let d of an.search([]))if(d.is_authority&&!d.details.issuer.includes("HarperDB-Certificate-Authority")){if(Sc.has(d.private_key_name)){n=Sc.get(d.private_key_name),s=d;break}else if(d.private_key_name&&await Wn.exists(gr.join(r,d.private_key_name))){n=Wn.readFile(gr.join(r,d.private_key_name)),s=d;break}}if(!n){let d=await SO();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=sf.pki.createCertificate();c.serialNumber=OT(),c.validity.notBefore=new Date;let l=new Date;c.validity.notAfter=l,c.validity.notAfter.setDate(l.getDate()+yO),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,sf.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(Pde,"signCertificate");async function Lde(e,t){await of({name:CT(),uses:["https","wss"],certificate:e,private_key_name:"privateKey.pem",is_authority:!1,is_self_signed:!0}),await of({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(Lde,"createCertificateTable");async function of(e){let t;try{t=new oa(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},Tc(),await an.patch(e)}a(of,"setCertTable");async function bO(){let e=await EO("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(bO,"generateKeys");async function AO(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()+yO);let i=[{name:"commonName",value:NT()},...RO];return n.setSubject(i),n.setIssuer(r.subject.attributes),n.setExtensions(k1()),n.sign(e,sf.md.sha256.create()),Mt.certificateToPem(n)}a(AO,"generateCertificates");async function SO(){let e=await K1(),t;for(let r of e){if(!r.is_authority)continue;let n=await V1(r.private_key_name);if(r.private_key_name&&n&&new oa(r.certificate).checkPrivateKey(L1(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(SO,"getCertAuthority");async function H1(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()+yO);let i=[{name:"commonName",value:`HarperDB-Certificate-Authority-${Ss.get(Xl.REPLICATION_HOSTNAME)??M1(Ss.get(Xl.REPLICATION_URL))??D1().split("-")[0]}`},...RO];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,sf.md.sha256.create());let o=gr.join(Ss.getHdbBasePath(),Vs.LICENSE_KEY_DIR_NAME),c=gr.join(o,Ai.PRIVATEKEY_PEM_NAME);return r&&await Wn.writeFile(c,Mt.privateKeyToPem(e)),n}a(H1,"generateCertAuthority");async function Dde(){let{privateKey:e,publicKey:t}=await bO(),r=await H1(e,t),n=await AO(e,t,r);await Lde(n,r),G1()}a(Dde,"generateCertsKeys");async function vde(){let e=await AO(Mt.privateKeyFromPem(Ai.CERTIFICATE_VALUES.key),void 0,Mt.certificateFromPem(Ai.CERTIFICATE_VALUES.cert)),t=gr.join(Ss.getHdbBasePath(),Vs.LICENSE_KEY_DIR_NAME),r=gr.join(t,Ai.NATS_CERTIFICATE_PEM_NAME);await Wn.exists(r)||await Wn.writeFile(r,e);let n=gr.join(t,Ai.NATS_CA_PEM_NAME);await Wn.exists(n)||await Wn.writeFile(n,Ai.CERTIFICATE_VALUES.cert)}a(vde,"createNatsCerts");async function Mde(){Tc();for await(let e of an.search([{attribute:"is_self_signed",value:!0}]))await an.delete(e.name);await IO()}a(Mde,"renewSelfSigned");async function IO(){Ade(),await F1(),Tc();let e=await SO();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(Wn.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=v1(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 bO(),Wn.existsSync(gr.join(o,Ai.PRIVATEKEY_PEM_NAME))&&(c=`privateKey${D1().split("-")[0]}.pem`),await Wn.writeFile(gr.join(o,c),Mt.privateKeyToPem(s)));let l=await H1(s,Mt.setRsaPublicKey(s.n,s.e),!1);await of({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 SO();let n=Mt.certificateFromPem(e.ca.certificate),s=n.publicKey,i=await AO(Mt.privateKeyFromPem(e.private_key),s,n);await of({name:r,uses:["https","operations","wss"],certificate:i,is_authority:!1,private_key_name:e.ca.private_key_name,is_self_signed:!0})}}a(IO,"reviewSelfSignedCert");function G1(){let e=Tde(Object.keys(Vs.CONFIG_PARAM_MAP),!0),t=gr.join(Ss.getHdbBasePath(),Vs.LICENSE_KEY_DIR_NAME),r=gr.join(t,Ai.PRIVATEKEY_PEM_NAME),n=gr.join(t,Ai.NATS_CERTIFICATE_PEM_NAME),s=gr.join(t,Ai.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),_O.updateConfigValue(void 0,void 0,o,!1,!0)}a(G1,"updateConfigCert");function q1(e){return e.startsWith("-----BEGIN")?e:Ide(e,"utf8")}a(q1,"readPEM");var O1=wT.createSecureContext;wT.createSecureContext=function(e){if(!e.cert||!e.key)return O1(e);let t={...e};delete t.key,delete t.cert;let r=O1(t);return r.context.setCert(e.cert),r.context.setKey(e.key,void 0),r};var Ude=B1.prototype._init;B1.prototype._init=function(e,t){Ude.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 Ql=new Map;function $1(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(),Ql.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 oa(m);f.is_authority&&(p.asString=m,Ql.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 V1(f.private_key_name),E=f.certificate,_=new oa(E);if(Ql.has(_.issuer)&&(E+=`
|
|
18
|
-
`+Ql.get(_.issuer)),!h||!E)throw new Error("Missing private key or certificate for secure server");let R={ciphers:f.ciphers,ticketKeys:wde(),availableCAs:Ql,ca:t&&Array.from(Ql.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??NO(_);Array.isArray(S)||(S=[S]);for(let I of S)I===gO()&&(p+=1);let y=wT.createSecureContext(R);y.name=f.name,y.options=R,y.quality=p,y.certificateAuthorities=Array.from(Ql),y.certStart=E.toString().slice(0,100);let w;for(let I of S)if(I){I[0]==="*"&&(s=!0,I=I.slice(1)),P1.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($1,"createTLSSelector");async function V1(e){let t=Sc.get(e);return!t&&e?await Wn.readFile(gr.join(Ss.get(Xl.ROOTPATH),Vs.LICENSE_KEY_DIR_NAME,e),"utf8"):t}a(V1,"getPrivateKeyByName");async function K1(){Tc();let e=[];for await(let t of an.search([]))e.push(t);return e}a(K1,"listCertificates");async function xde(e){let t=TO(e,bi.object({name:bi.string().required(),certificate:bi.string().required(),is_authority:bi.boolean().required(),private_key:bi.string(),hosts:bi.array(),uses:bi.array()}));if(t)throw new gc(t.message);let{name:r,certificate:n,private_key:s,is_authority:i}=e,o=new oa(n),c=!1,l=!1,u;for(let[p,h]of Sc)!s&&!c&&o.checkPrivateKey(L1(h))&&(c=!0,u=p),s&&s===h&&(l=!0,u=p);if(!i&&!s&&!c)throw new gc("A suitable private key was not found for this certificate");let d;if(!r){try{d=wO(o)}catch(p){Xe.error?.(p)}if(d==null)throw new gc("Error extracting certificate host name, please provide a name parameter")}let f=Bde(r??d);s&&!c&&!l&&(await Wn.writeFile(gr.join(Ss.getHdbBasePath(),Vs.LICENSE_KEY_DIR_NAME,f+".pem"),s),Sc.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 of(m),"Successfully added certificate: "+f}a(xde,"addCertificate");function Bde(e){return e.replace(/[^a-z0-9\.]/gi,"-")}a(Bde,"sanitizeName");async function Fde(e){let t=TO(e,bi.object({name:bi.string().required()}));if(t)throw new gc(t.message);let{name:r}=e;Tc();let n=await an.get(r);if(!n)throw new gc(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 Wn.remove(gr.join(Ss.getHdbBasePath(),Vs.LICENSE_KEY_DIR_NAME,s)))}return await an.delete(r),"Successfully removed "+r}a(Fde,"removeCertificate");function wO(e){let t=e.subject?.match(/CN=(.*)/)?.[1];return t||NO(e)[0]}a(wO,"getPrimaryHostName");function NO(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(NO,"hostnamesFromCert");async function kde(e){if(e.bypass_auth!==!0)throw new gc("Unauthorized","401");let t=TO(e,bi.object({name:bi.string().required()}));if(t)throw new gc(t.message);let{name:r}=e;if(r===".jwtPrivate")return(await w1()).privateKey;if(r===".jwtPublic")return(await w1()).publicKey;if(Sc.get(r))return Sc.get(e.name);throw new gc("Key not found")}a(kde,"getKey");function Hde(e){return[e.subject?.CN,...e.subjectaltname.split(",").filter(t=>t.trim().startsWith("DNS:")).map(t=>t.trim().substring(4))]}a(Hde,"getHostnamesFromCertificate")});var pK={};ye(pK,{BACK_PRESSURE_RATIO_POSITION:()=>fK,CONFIRMATION_STATUS_POSITION:()=>dK,LATENCY_POSITION:()=>BT,NodeReplicationConnection:()=>cf,OPERATION_REQUEST:()=>DO,RECEIVED_TIME_POSITION:()=>UT,RECEIVED_VERSION_POSITION:()=>MT,RECEIVING_STATUS_POSITION:()=>xT,RECEIVING_STATUS_RECEIVING:()=>mK,RECEIVING_STATUS_WAITING:()=>vO,SENDING_TIME_POSITION:()=>Lh,createWebSocket:()=>FT,databaseSubscriptions:()=>Rc,replicateOverWS:()=>Dh,tableUpdateListeners:()=>xO});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(!PO){let l=(0,aK.createTLSSelector)("operations-api"),u={secureContexts:null};await l.initialize(u),PO=u.secureContexts}if(i=PO.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,lK.isIP)(t?.serverName)?void 0:t?.serverName,noDelay:!0,highWaterMark:128*1024,rejectUnauthorized:n!==!1,secureContext:void 0};return i&&((af?.caCount!==ca.size||af?.derivedFromContext!==i)&&(af=cK.createSecureContext({...i.options,ca:[...ca,...i.options.availableCAs.values()]}),af.caCount=ca.size,af.derivedFromContext=i),c.secureContext=af),new sK.WebSocket(e,"harperdb-replication-v1",c)}function Dh(e,t,r){let n=t.port||t.securePort,s=UO.pid%1e3+"-"+iK.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||Rc,f,m,p=!1,h=t.subscription;h?.then&&h.then(A=>{h=A,h.auditStore&&(f=h.auditStore)});let E=t.tables||u&<()[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=nK.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,tK).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())},tK*2).unref()}a(nr,"resetPingTimer");let zr=0,xr=0,Pu=!1,Jc=3e4;function Ft(){if(pn?.length>0){let A=performance.now(),U=A-xr;zr=(zr*Jc+(Pu?U:0))/(Jc+U),m&&(m[fK]=zr),xr=A}}a(Ft,"updateBackPressureRatio"),setInterval(Ft,Jc).unref();function Ps(){if(!(!_||!u))return m||(m=Zd(f,u,_)),m}a(Ps,"getSharedStatus"),u&&Qc(u);let Ha,c_,lm=[],l_=[],um,ve=[],u_=[],Zb=[],Lu=150,Gi=25,Ls=0,dm=0,fm=!1,xo,Dn,pn,Br;e.on("message",Du);async function Du(A){if(r=await r,!r){le.error?.(s,"No authorization provided"),Fr(1008,"Unauthorized");return}mm(A),e.off("message",Du),e.on("message",mm)}a(Du,"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),[J,F,he]=W;switch(J){case W1:{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,ia(_,me)}if(t.connection&&(t.connection.nodeName=_),le.debug?.(s,"received node name:",_,"db:",u??W[2]),!u)try{Qc(u=W[2]),u==="system"&&(Ha=Ec(t,(me,ie)=>{$a(ie)&&K(ie)}),e.on("close",()=>{Ha?.remove()}))}catch(me){le.warn?.(s,"Error setting database",me),e.send((0,at.encode)([Ph])),Fr(1008,me.message);return}pm()}break}case Z1:{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($a(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 DO: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:CO(ie)}]))})}catch(me){e.send((0,at.encode)([LT,{requestId:F.requestId,error:CO(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 OO: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 j1:Br=f?d1(F,f):new Map,um=W[2],le.debug?.(s,`Acknowledged subscription request, receiving messages for nodes: ${um}`);break;case z1:let ge=he;Zb[ge]=F;break;case X1:Ps()[dK]=F,le.trace?.(s,"received and broadcasting committed update",F),Ps().buffer.notify();break;case Q1: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]=vO;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 LO.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=l_[he]||(l_[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)([OO,{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,uK.getLastVersion)(),ut&&ut[Qu]&Zr&&(Ct=Buffer.from(Ct),jm(()=>Be.primaryStore.decoder.decode(ht),f_=>Ga(f_,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=qa(ht,Be);return Te||(Te=[]),Te.push(Ct),Ct})}else me();R.delete(W[1]);break}case Y1:{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,Rc.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(mr=>(mr.database||mr.schema)===u&&mr.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,f_,m_=a((De,ft)=>{if(De.type==="end_txn"){Te.txnTime&&(o[i]!==66&&le.error?.("Invalid encoding of message"),C(9),C(hg),O(f_=ft),aU()),i=c,Te.txnTime=0;return}let kr=De.nodeId,mr=De.tableId,zt=Ct[mr];if(!zt&&(zt=Ct[mr]=He(h.tableById[mr]),!zt))return le.debug?.("Not subscribed to table",mr);let yt=zt.table,Uu=yt.primaryStore,si=Uu.encoder;(De.extendedType&Ig||!si.typedStructs)&&(si._mergeStructures(si.getStructures()),si.typedStructs&&(si.lastTypedStructuresLength=si.typedStructs.length));let p_=ht[kr];if(!(p_&&p_.startTime<ft&&(!p_.endTime||p_.endTime>ft)))return vT&&le.trace?.(s,"skipping replication update",De.recordId,"to:",_,"from:",kr,"subscribed:",ht),cU();vT&&le.trace?.(s,"sending replication update",De.recordId,"to:",_,"from:",kr,"subscribed:",ht);let eA=De.version,Xc=De.residencyId,tA=d_(Xc,yt),h_;if(tA&&!tA.includes(_)){let qi=d_(De.previousResidencyId,yt);if(qi&&!qi.includes(_)&&(De.type==="put"||De.type==="patch")||yt.getResidencyById)return cU();let Zc=De.recordId;le.trace?.(s,"sending invalidation",Zc,_,"from",kr);let hm=0;Xc&&(hm|=fl),De.previousResidencyId&&(hm|=ml);let sA,E_=null;for(let lU in yt.indices){if(!E_){if(sA=De.getValue(Uu,!0),!sA)break;E_={}}E_[lU]=sA[lU]}h_=pl(De.version,mr,Zc,null,kr,De.user,De.type==="put"||De.type==="patch"?"invalidate":De.type,si.encode(E_),hm,Xc,De.previousResidencyId,De.expiresAt)}function cU(){return le.trace?.(s,"skipping audit record",De.recordId),q||(q=setTimeout(()=>{q=null,(f_||0)+eK/2<Ot&&(vT&&le.trace?.(s,"sending skipped sequence update",Ot),e.send((0,at.encode)([Q1,Ot])))},eK).unref()),new Promise(setImmediate)}a(cU,"skipAuditRecord");let rA=si.typedStructs,nA=si.structures;if((rA?.length!=zt.typed_length||nA?.length!=zt.structure_length)&&(zt.typed_length=rA?.length,zt.structure_length=nA.length,le.debug?.(s,"send table struct",zt.typed_length,zt.structure_length),zt.sentName||(zt.sentName=!0),e.send((0,at.encode)([OO,{typedStructs:rA,structures:nA,attributes:yt.attributes,schemaDefined:yt.schemaDefined},mr,zt.table.tableName]))),Xc&&!u_[Xc]&&(e.send((0,at.encode)([z1,tA,Xc])),u_[Xc]=!0),Te.txnTime!==eA&&(Te.txnTime&&(vT&&le.trace?.(s,"new txn time, sending queued txn",Te.txnTime),o[i]!==66&&le.error?.("Invalid encoding of message"),aU()),Te.txnTime=eA,i=c,O(eA)),h_)C(h_.length),P(h_);else{let qi=De.encoded;De.extendedType&Zr&&jm(()=>De.getValue(Uu),hm=>Ga(hm,De.recordId),Uu.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 Pu=!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(),Pu=!1,Ft()})})}else return $e>Gi?new Promise(qi=>{Ir=qi}):new Promise(setImmediate)},"sendAuditRecord"),aU=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 MO.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:mr}of pn){let zt=yT(ft,f);le.debug?.("subscription to",ft,"using local id",zt,"starting",kr),ht[zt]={startTime:kr,endTime:mr}}K(u),Ha||(Ha=$l(ft=>{ft.databaseName===u&&K(u)}),c_=sh(ft=>{ft===u&&(e.send((0,at.encode)([Ph])),Fr())}),e.on("close",()=>{Ha?.remove(),c_?.remove()})),e.send((0,at.encode)([j1,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 mr in E){if(!He(mr))continue;let zt=E[mr];for(let yt of zt.primaryStore.getRange({snapshot:!1,versions:!0})){if(Ce)return;le.trace?.(s,"Copying record from",u,mr,yt.key,yt.localTime),ft=Math.max(yt.localTime??1,ft),Ps()[Lh]=1;let Uu=pl(yt.version,zt.tableId,yt.key,null,kr,null,"put",jm(()=>zt.primaryStore.encoder.encode(yt.value),si=>Ga(si,yt.key)),yt.metadataFlags&-256,yt.residencyId,null,yt.expiresAt);await m_({recordId:yt.key,tableId:zt.tableId,type:"put",getValue(){return yt.value},encoded:Uu,version:yt.version,residencyId:yt.residencyId,nodeId:kr,extendedType:yt.metadataFlags},yt.localTime)}}Te.txnTime||(Te.txnTime=ft,O(ft)),c-i>8&&m_({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 mr=It(kr);le.debug?.("sending audit record",ft,mr.recordId),Ps()[Lh]=ft,Ot=ft,await m_(mr,ft),Dn.startTime=ft}c-i>8&&m_({type:"end_txn"},Ot),Ps()[Lh]=0,await xB(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]=vO,h.send({type:"end_txn",localTime:y,remoteNodeIds:S}),le.trace?.("received remote sequence update",y,u);break}let J=U.position,F=It(A,J,J+W),he=lm[F.tableId];he||le.error?.(`No table found with an id of ${F.tableId}`);let ue;F.residencyId&&(ue=Zb[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=>qa(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]=mK,h.send(L),U.position=J+W}while(U.position<A.byteLength);Ls++,u!=="system"&&We(A.byteLength,"bytes-received",`${_}.${u}.${L?.table||"unknown_table"}`,"replication","ingest"),Ls>Lu&&!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)([X1,w])),le.trace?.(s,"sent confirmation of a commit at",w),w=null},qde)),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&&Jl({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"),xo&&xo.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 vu=new Set;async function Ga(A,U){let N=rg(A);if(vu.has(N)){le.debug?.("Blob already being sent",N);return}vu.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:CO(L)},Buffer.alloc(0)]))}finally{vu.delete(N),$e--,$e<Gi&&Ir?.()}}a(Ga,"sendBlobs");function qa(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 LO.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=Yo(()=>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(qa,"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:J}=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)}J=!1}else for(let _e in E)(J?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:J,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)([Y1,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 d_(A,U){if(!A)return;let N=ve[A];return N||(N=U.getResidencyRecord(A),ve[A]=N),N}a(d_,"getResidence");function $a(A){return!(yc&&yc!="*"&&!yc[A]&&!yc.includes?.(A)&&!yc.some?.(U=>U.name===A))}a($a,"checkDatabaseAccess");function Qc(A){if(h=h||d.get(A),!$a(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 Mu(U,A),!0}a(Qc,"setDatabase");function Mu(A,U){let N=lt()?.[U],L=[];for(let $ in N){let W=N[$];L.push({table:$,schemaDefined:W.schemaDefined,attributes:W.attributes.map(J=>({name:J.name,type:J.type,isPrimaryKey:J.isPrimaryKey}))})}le.trace?.("Sending database info for node",A,"database name",U),e.send((0,at.encode)([W1,A,U,L]))}a(Mu,"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)([Z1,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(){xo&&xo.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:J,entry:F}=A;if(N(W),W)return J._recordRelocate(F,W)},reject:L})})},sendOperation(A){let U=g++;return A.requestId=U,e.send((0,at.encode)([DO,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,J=U.attributes||[];for(let F=0;F<A.attributes?.length;F++){let he=A.attributes[F],ue=J.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?J[J.indexOf(ue)]=he:J.push(he)))}return $?(le.debug?.("(Re)creating",A),ze({table:A.table,database:A.database,schemaDefined:A.schemaDefined,attributes:J,...U})):U}}var nK,at,sK,iK,oK,MO,aK,cK,UO,lK,LO,uK,Gde,CO,le,Y1,W1,j1,Ph,z1,OO,J1,PT,DO,LT,Q1,X1,Z1,DT,dK,MT,UT,Lh,BT,xT,fK,vO,mK,xO,Rc,vT,eK,qde,tK,PO,af,rK,cf,BO=se(()=>{Oe();Vi();pO();qI();gs();nK=b(fe());G();hl();at=require("msgpackr"),sK=require("ws"),iK=require("worker_threads"),oK=b(Q());Nh();MO=require("events"),aK=b(Ts()),cK=b(require("node:tls"));tf();UO=b(require("node:process")),lK=require("node:net");as();os();LO=require("node:stream"),uK=require("lmdb"),{forComponent:Gde,errorToString:CO}=oK.default,le=Gde("replication").conditional,Y1=129,W1=140,j1=141,Ph=142,z1=130,OO=132,J1=133,PT=134,DO=136,LT=137,Q1=143,X1=144,Z1=145,DT=146,dK=0,MT=1,UT=2,Lh=3,BT=4,xT=5,fK=6,vO=0,mK=1,xO=new Map,Rc=new Map,vT=!0,eK=300,qde=2,tK=3e4;a(FT,"createWebSocket");rK=500,cf=class extends MO.EventEmitter{static{a(this,"NodeReplicationConnection")}socket;startTime;retryTime=rK;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??Ri(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 ${UO.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=rK,this.nodeSubscriptions&&Jl({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&&nf({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 bc(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
|
+
`+Ql.get(_.issuer)),!h||!E)throw new Error("Missing private key or certificate for secure server");let R={ciphers:f.ciphers,ticketKeys:wde(),availableCAs:Ql,ca:t&&Array.from(Ql.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??NO(_);Array.isArray(S)||(S=[S]);for(let I of S)I===gO()&&(p+=1);let y=wT.createSecureContext(R);y.name=f.name,y.options=R,y.quality=p,y.certificateAuthorities=Array.from(Ql),y.certStart=E.toString().slice(0,100);let w;for(let I of S)if(I){I[0]==="*"&&(s=!0,I=I.slice(1)),P1.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($1,"createTLSSelector");async function V1(e){let t=Sc.get(e);return!t&&e?await Wn.readFile(gr.join(Ss.get(Xl.ROOTPATH),Vs.LICENSE_KEY_DIR_NAME,e),"utf8"):t}a(V1,"getPrivateKeyByName");async function K1(){Tc();let e=[];for await(let t of an.search([]))e.push(t);return e}a(K1,"listCertificates");async function xde(e){let t=TO(e,bi.object({name:bi.string().required(),certificate:bi.string().required(),is_authority:bi.boolean().required(),private_key:bi.string(),hosts:bi.array(),uses:bi.array()}));if(t)throw new gc(t.message);let{name:r,certificate:n,private_key:s,is_authority:i}=e,o=new oa(n),c=!1,l=!1,u;for(let[p,h]of Sc)!s&&!c&&o.checkPrivateKey(L1(h))&&(c=!0,u=p),s&&s===h&&(l=!0,u=p);if(!i&&!s&&!c)throw new gc("A suitable private key was not found for this certificate");let d;if(!r){try{d=wO(o)}catch(p){Xe.error?.(p)}if(d==null)throw new gc("Error extracting certificate host name, please provide a name parameter")}let f=Bde(r??d);s&&!c&&!l&&(await Wn.writeFile(gr.join(Ss.getHdbBasePath(),Vs.LICENSE_KEY_DIR_NAME,f+".pem"),s),Sc.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 of(m),"Successfully added certificate: "+f}a(xde,"addCertificate");function Bde(e){return e.replace(/[^a-z0-9\.]/gi,"-")}a(Bde,"sanitizeName");async function Fde(e){let t=TO(e,bi.object({name:bi.string().required()}));if(t)throw new gc(t.message);let{name:r}=e;Tc();let n=await an.get(r);if(!n)throw new gc(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 Wn.remove(gr.join(Ss.getHdbBasePath(),Vs.LICENSE_KEY_DIR_NAME,s)))}return await an.delete(r),"Successfully removed "+r}a(Fde,"removeCertificate");function wO(e){let t=e.subject?.match(/CN=(.*)/)?.[1];return t||NO(e)[0]}a(wO,"getPrimaryHostName");function NO(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(NO,"hostnamesFromCert");async function kde(e){if(e.bypass_auth!==!0)throw new gc("Unauthorized","401");let t=TO(e,bi.object({name:bi.string().required()}));if(t)throw new gc(t.message);let{name:r}=e;if(r===".jwtPrivate")return(await w1()).privateKey;if(r===".jwtPublic")return(await w1()).publicKey;if(Sc.get(r))return Sc.get(e.name);throw new gc("Key not found")}a(kde,"getKey");function Hde(e){return[e.subject?.CN,...e.subjectaltname.split(",").filter(t=>t.trim().startsWith("DNS:")).map(t=>t.trim().substring(4))]}a(Hde,"getHostnamesFromCertificate")});var pK={};ye(pK,{BACK_PRESSURE_RATIO_POSITION:()=>fK,CONFIRMATION_STATUS_POSITION:()=>dK,LATENCY_POSITION:()=>BT,NodeReplicationConnection:()=>cf,OPERATION_REQUEST:()=>DO,RECEIVED_TIME_POSITION:()=>UT,RECEIVED_VERSION_POSITION:()=>MT,RECEIVING_STATUS_POSITION:()=>xT,RECEIVING_STATUS_RECEIVING:()=>mK,RECEIVING_STATUS_WAITING:()=>vO,SENDING_TIME_POSITION:()=>Lh,createWebSocket:()=>FT,databaseSubscriptions:()=>Rc,replicateOverWS:()=>Dh,tableUpdateListeners:()=>xO});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(!PO){let l=(0,aK.createTLSSelector)("operations-api"),u={secureContexts:null};await l.initialize(u),PO=u.secureContexts}if(i=PO.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,lK.isIP)(t?.serverName)?void 0:t?.serverName,noDelay:!0,highWaterMark:128*1024,rejectUnauthorized:n!==!1,secureContext:void 0};return i&&((af?.caCount!==ca.size||af?.derivedFromContext!==i)&&(af=cK.createSecureContext({...i.options,ca:[...ca,...i.options.availableCAs.values()]}),af.caCount=ca.size,af.derivedFromContext=i),c.secureContext=af),new sK.WebSocket(e,"harperdb-replication-v1",c)}function Dh(e,t,r){let n=t.port||t.securePort,s=UO.pid%1e3+"-"+iK.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||Rc,f,m,p=!1,h=t.subscription;h?.then&&h.then(A=>{h=A,h.auditStore&&(f=h.auditStore)});let E=t.tables||u&<()[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=nK.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,tK).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())},tK*2).unref()}a(nr,"resetPingTimer");let zr=0,xr=0,Pu=!1,Jc=3e4;function Ft(){if(pn?.length>0){let A=performance.now(),U=A-xr;zr=(zr*Jc+(Pu?U:0))/(Jc+U),m&&(m[fK]=zr),xr=A}}a(Ft,"updateBackPressureRatio"),setInterval(Ft,Jc).unref();function Ps(){if(!(!_||!u))return m||(m=Zd(f,u,_)),m}a(Ps,"getSharedStatus"),u&&Qc(u);let Ha,c_,lm=[],l_=[],um,ve=[],u_=[],Zb=[],Lu=150,Gi=25,Ls=0,dm=0,fm=!1,xo,Dn,pn,Br;e.on("message",Du);async function Du(A){if(r=await r,!r){le.error?.(s,"No authorization provided"),Fr(1008,"Unauthorized");return}mm(A),e.off("message",Du),e.on("message",mm)}a(Du,"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),[J,F,he]=W;switch(J){case W1:{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,ia(_,me)}if(t.connection&&(t.connection.nodeName=_),le.debug?.(s,"received node name:",_,"db:",u??W[2]),!u)try{Qc(u=W[2]),u==="system"&&(Ha=Ec(t,(me,ie)=>{$a(ie)&&K(ie)}),e.on("close",()=>{Ha?.remove()}))}catch(me){le.warn?.(s,"Error setting database",me),e.send((0,at.encode)([Ph])),Fr(1008,me.message);return}pm()}break}case Z1:{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($a(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 DO: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:CO(ie)}]))})}catch(me){e.send((0,at.encode)([LT,{requestId:F.requestId,error:CO(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 OO: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 j1:Br=f?d1(F,f):new Map,um=W[2],le.debug?.(s,`Acknowledged subscription request, receiving messages for nodes: ${um}`);break;case z1:let ge=he;Zb[ge]=F;break;case X1:Ps()[dK]=F,le.trace?.(s,"received and broadcasting committed update",F),Ps().buffer.notify();break;case Q1:y=F,h.send({type:"end_txn",localTime:y,remoteNodeIds:S}),Ps(),m[MT]=last_sequence_id_received,m[UT]=Date.now(),m[xT]=vO;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 LO.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=l_[he]||(l_[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)([OO,{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,uK.getLastVersion)(),ut&&ut[Qu]&Zr&&(Ct=Buffer.from(Ct),jm(()=>Be.primaryStore.decoder.decode(ht),f_=>Ga(f_,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=qa(ht,Be);return Te||(Te=[]),Te.push(Ct),Ct})}else me();R.delete(W[1]);break}case Y1:{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,Rc.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(mr=>(mr.database||mr.schema)===u&&mr.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,f_,m_=a((De,ft)=>{if(De.type==="end_txn"){Te.txnTime&&(o[i]!==66&&le.error?.("Invalid encoding of message"),C(9),C(hg),O(f_=ft),aU()),i=c,Te.txnTime=0;return}let kr=De.nodeId,mr=De.tableId,zt=Ct[mr];if(!zt&&(zt=Ct[mr]=He(h.tableById[mr]),!zt))return le.debug?.("Not subscribed to table",mr);let yt=zt.table,Uu=yt.primaryStore,si=Uu.encoder;(De.extendedType&Ig||!si.typedStructs)&&(si._mergeStructures(si.getStructures()),si.typedStructs&&(si.lastTypedStructuresLength=si.typedStructs.length));let p_=ht[kr];if(!(p_&&p_.startTime<ft&&(!p_.endTime||p_.endTime>ft)))return vT&&le.trace?.(s,"skipping replication update",De.recordId,"to:",_,"from:",kr,"subscribed:",ht),cU();vT&&le.trace?.(s,"sending replication update",De.recordId,"to:",_,"from:",kr,"subscribed:",ht);let eA=De.version,Xc=De.residencyId,tA=d_(Xc,yt),h_;if(tA&&!tA.includes(_)){let qi=d_(De.previousResidencyId,yt);if(qi&&!qi.includes(_)&&(De.type==="put"||De.type==="patch")||yt.getResidencyById)return cU();let Zc=De.recordId;le.trace?.(s,"sending invalidation",Zc,_,"from",kr);let hm=0;Xc&&(hm|=fl),De.previousResidencyId&&(hm|=ml);let sA,E_=null;for(let lU in yt.indices){if(!E_){if(sA=De.getValue(Uu,!0),!sA)break;E_={}}E_[lU]=sA[lU]}h_=pl(De.version,mr,Zc,null,kr,De.user,De.type==="put"||De.type==="patch"?"invalidate":De.type,si.encode(E_),hm,Xc,De.previousResidencyId,De.expiresAt)}function cU(){return le.trace?.(s,"skipping audit record",De.recordId),q||(q=setTimeout(()=>{q=null,(f_||0)+eK/2<Ot&&(vT&&le.trace?.(s,"sending skipped sequence update",Ot),e.send((0,at.encode)([Q1,Ot])))},eK).unref()),new Promise(setImmediate)}a(cU,"skipAuditRecord");let rA=si.typedStructs,nA=si.structures;if((rA?.length!=zt.typed_length||nA?.length!=zt.structure_length)&&(zt.typed_length=rA?.length,zt.structure_length=nA.length,le.debug?.(s,"send table struct",zt.typed_length,zt.structure_length),zt.sentName||(zt.sentName=!0),e.send((0,at.encode)([OO,{typedStructs:rA,structures:nA,attributes:yt.attributes,schemaDefined:yt.schemaDefined},mr,zt.table.tableName]))),Xc&&!u_[Xc]&&(e.send((0,at.encode)([z1,tA,Xc])),u_[Xc]=!0),Te.txnTime!==eA&&(Te.txnTime&&(vT&&le.trace?.(s,"new txn time, sending queued txn",Te.txnTime),o[i]!==66&&le.error?.("Invalid encoding of message"),aU()),Te.txnTime=eA,i=c,O(eA)),h_)C(h_.length),P(h_);else{let qi=De.encoded;De.extendedType&Zr&&jm(()=>De.getValue(Uu),hm=>Ga(hm,De.recordId),Uu.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 Pu=!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(),Pu=!1,Ft()})})}else return $e>Gi?new Promise(qi=>{Ir=qi}):new Promise(setImmediate)},"sendAuditRecord"),aU=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 MO.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:mr}of pn){let zt=yT(ft,f);le.debug?.("subscription to",ft,"using local id",zt,"starting",kr),ht[zt]={startTime:kr,endTime:mr}}K(u),Ha||(Ha=$l(ft=>{ft.databaseName===u&&K(u)}),c_=sh(ft=>{ft===u&&(e.send((0,at.encode)([Ph])),Fr())}),e.on("close",()=>{Ha?.remove(),c_?.remove()})),e.send((0,at.encode)([j1,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 mr in E){if(!He(mr))continue;let zt=E[mr];for(let yt of zt.primaryStore.getRange({snapshot:!1,versions:!0})){if(Ce)return;le.trace?.(s,"Copying record from",u,mr,yt.key,yt.localTime),ft=Math.max(yt.localTime??1,ft),Ps()[Lh]=1;let Uu=pl(yt.version,zt.tableId,yt.key,null,kr,null,"put",jm(()=>zt.primaryStore.encoder.encode(yt.value),si=>Ga(si,yt.key)),yt.metadataFlags&-256,yt.residencyId,null,yt.expiresAt);await m_({recordId:yt.key,tableId:zt.tableId,type:"put",getValue(){return yt.value},encoded:Uu,version:yt.version,residencyId:yt.residencyId,nodeId:kr,extendedType:yt.metadataFlags},yt.localTime)}}Te.txnTime||(Te.txnTime=ft,O(ft)),c-i>8&&m_({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 mr=It(kr);le.debug?.("sending audit record",ft,mr.recordId),Ps()[Lh]=ft,Ot=ft,await m_(mr,ft),Dn.startTime=ft}c-i>8&&m_({type:"end_txn"},Ot),Ps()[Lh]=0,await xB(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]=vO,h.send({type:"end_txn",localTime:y,remoteNodeIds:S}),le.trace?.("received remote sequence update",y,u);break}let J=U.position,F=It(A,J,J+W),he=lm[F.tableId];he||le.error?.(`No table found with an id of ${F.tableId}`);let ue;F.residencyId&&(ue=Zb[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=>qa(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]=mK,h.send(L),U.position=J+W}while(U.position<A.byteLength);Ls++,u!=="system"&&We(A.byteLength,"bytes-received",`${_}.${u}.${L?.table||"unknown_table"}`,"replication","ingest"),Ls>Lu&&!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)([X1,w])),le.trace?.(s,"sent confirmation of a commit at",w),w=null},qde)),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&&Jl({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"),xo&&xo.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 vu=new Set;async function Ga(A,U){let N=rg(A);if(vu.has(N)){le.debug?.("Blob already being sent",N);return}vu.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:CO(L)},Buffer.alloc(0)]))}finally{vu.delete(N),$e--,$e<Gi&&Ir?.()}}a(Ga,"sendBlobs");function qa(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 LO.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=Yo(()=>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(qa,"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:J}=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)}J=!1}else for(let _e in E)(J?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:J,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)([Y1,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 d_(A,U){if(!A)return;let N=ve[A];return N||(N=U.getResidencyRecord(A),ve[A]=N),N}a(d_,"getResidence");function $a(A){return!(yc&&yc!="*"&&!yc[A]&&!yc.includes?.(A)&&!yc.some?.(U=>U.name===A))}a($a,"checkDatabaseAccess");function Qc(A){if(h=h||d.get(A),!$a(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 Mu(U,A),!0}a(Qc,"setDatabase");function Mu(A,U){let N=lt()?.[U],L=[];for(let $ in N){let W=N[$];L.push({table:$,schemaDefined:W.schemaDefined,attributes:W.attributes.map(J=>({name:J.name,type:J.type,isPrimaryKey:J.isPrimaryKey}))})}le.trace?.("Sending database info for node",A,"database name",U),e.send((0,at.encode)([W1,A,U,L]))}a(Mu,"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)([Z1,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(){xo&&xo.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:J,entry:F}=A;if(N(W),W)return J._recordRelocate(F,W)},reject:L})})},sendOperation(A){let U=g++;return A.requestId=U,e.send((0,at.encode)([DO,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,J=U.attributes||[];for(let F=0;F<A.attributes?.length;F++){let he=A.attributes[F],ue=J.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?J[J.indexOf(ue)]=he:J.push(he)))}return $?(le.debug?.("(Re)creating",A),ze({table:A.table,database:A.database,schemaDefined:A.schemaDefined,attributes:J,...U})):U}}var nK,at,sK,iK,oK,MO,aK,cK,UO,lK,LO,uK,Gde,CO,le,Y1,W1,j1,Ph,z1,OO,J1,PT,DO,LT,Q1,X1,Z1,DT,dK,MT,UT,Lh,BT,xT,fK,vO,mK,xO,Rc,vT,eK,qde,tK,PO,af,rK,cf,BO=se(()=>{Oe();Vi();pO();qI();gs();nK=b(fe());G();hl();at=require("msgpackr"),sK=require("ws"),iK=require("worker_threads"),oK=b(Q());Nh();MO=require("events"),aK=b(Ts()),cK=b(require("node:tls"));tf();UO=b(require("node:process")),lK=require("node:net");as();os();LO=require("node:stream"),uK=require("lmdb"),{forComponent:Gde,errorToString:CO}=oK.default,le=Gde("replication").conditional,Y1=129,W1=140,j1=141,Ph=142,z1=130,OO=132,J1=133,PT=134,DO=136,LT=137,Q1=143,X1=144,Z1=145,DT=146,dK=0,MT=1,UT=2,Lh=3,BT=4,xT=5,fK=6,vO=0,mK=1,xO=new Map,Rc=new Map,vT=!0,eK=300,qde=2,tK=3e4;a(FT,"createWebSocket");rK=500,cf=class extends MO.EventEmitter{static{a(this,"NodeReplicationConnection")}socket;startTime;retryTime=rK;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??Ri(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 ${UO.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=rK,this.nodeSubscriptions&&Jl({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&&nf({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 bc(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 EK(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 HO(e){try{let t=Zl(e),n=Eo.Certificate.fromBER(t).extensions?.find(c=>c.extnID==="2.5.29.31");if(!n)return po.debug?.("Certificate has no CRL Distribution Points extension"),[];let s=ho.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 Eo.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 po.debug?.(`Found ${o.length} CRL distribution points: ${o}`),o}catch(t){return po.warn?.(`Failed to extract CRL distribution points: ${t}`),[]}}function _K(e){try{let t=Zl(e),r=Eo.Certificate.fromBER(t),n=[],s=[];for(let i of r.extensions||[])if(i.extnID==="2.5.29.31")try{let o=ho.fromBER(i.extnValue.valueBlock.valueHexView);if(o.offset!==-1){let c=new Eo.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){po.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=ho.fromBER(i.extnValue.valueBlock.valueHexView);if(o.offset!==-1&&o.result instanceof ho.Sequence){for(let c of o.result.valueBlock.value)if(c instanceof ho.Sequence&&c.valueBlock.value.length>=2){let l=c.valueBlock.value[0],u=c.valueBlock.value[1];if(l instanceof ho.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){po.warn?.(`Failed to parse Authority Information Access extension: ${o}`)}return po.debug?.(`Found ${n.length} CRL distribution points and ${s.length} OCSP responder URLs`),{crlUrls:n,ocspUrls:s}}catch(t){return po.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,kO.createHash)("sha256").update(JSON.stringify(s)).digest("hex");return`${r}:${i}`}function GO(e,t){return`${e}:${t}`}function gK(e){try{let t=Zl(e),n=Eo.Certificate.fromBER(t).serialNumber.valueBlock.valueHexView;return Array.from(n).map(s=>s.toString(16).padStart(2,"0")).join("")}catch(t){throw po.error?.(`Failed to extract serial number: ${t}`),new Error(`Failed to extract certificate serial number: ${t.message}`)}}function qO(e){try{let t=Zl(e),r=Eo.Certificate.fromBER(t),n=r.extensions?.find(i=>i.extnID==="2.5.29.35");if(n)try{let i=ho.fromBER(n.extnValue.valueBlock.valueHexView);if(i.offset!==-1){let o=new Eo.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){po.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,kO.createHash)("sha256").update(s).digest("hex")}catch(t){throw po.error?.(`Failed to extract issuer key ID: ${t}`),new Error(`Failed to extract issuer key ID: ${t.message}`)}}function GT(){return FO||(FO=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"}]})),FO}var kO,Eo,ho,hK,po,FO,qT=se(()=>{kO=require("node:crypto"),Eo=b(require("pkijs")),ho=b(require("asn1js")),hK=b(sr());Oe();po=(0,hK.loggerWithTag)("cert-verification-utils");a(bc,"bufferToPem");a(EK,"extractCertificateChain");a(HO,"extractCRLDistributionPoints");a(_K,"extractRevocationUrls");a(Zl,"pemToBuffer");a(HT,"createCacheKey");a(GO,"createRevokedCertificateId");a(gK,"extractSerialNumber");a(qO,"extractIssuerKeyId");FO=null;a(GT,"getCertificateCacheTable")});function SK(e){let{error:t,value:r}=Yde.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,$de,lf,uf,$O,Vde,Kde,Yde,TK=se(()=>{Yr=b(require("joi")),$de="fail-closed",lf={timeout:5e3,cacheTtl:36e5,errorCacheTtl:3e5,failureMode:"fail-closed"},uf={timeout:1e4,cacheTtl:864e5,failureMode:"fail-closed",gracePeriod:864e5},$O=Yr.default.string().valid("fail-open","fail-closed"),Vde=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":"CRL timeout must be at least 1000ms (1 second)"}),cacheTtl:Yr.default.number().min(1e3).default(uf.cacheTtl).messages({"number.min":"CRL cacheTtl must be at least 1000ms (1 second)"}),failureMode:$O.default(uf.failureMode),gracePeriod:Yr.default.number().min(0).default(uf.gracePeriod).messages({"number.min":"CRL gracePeriod must be at least 0ms"})})),Kde=Yr.default.alternatives().try(Yr.default.boolean().custom(e=>e===!1?{enabled:!1}:{enabled:!0,...lf}),Yr.default.object({enabled:Yr.default.boolean().default(!0),timeout:Yr.default.number().min(1e3).default(lf.timeout).messages({"number.min":"OCSP timeout must be at least 1000ms (1 second)"}),cacheTtl:Yr.default.number().min(1e3).default(lf.cacheTtl).messages({"number.min":"OCSP cacheTtl must be at least 1000ms (1 second)"}),errorCacheTtl:Yr.default.number().min(1e3).default(lf.errorCacheTtl).messages({"number.min":"OCSP errorCacheTtl must be at least 1000ms (1 second)"}),failureMode:$O.default(lf.failureMode)})),Yde=Yr.default.object({failureMode:$O.default($de),crl:Vde.default({enabled:!0,...uf}),ocsp:Kde.default({enabled:!0,...lf})});a(SK,"validateAndParseCertificateVerificationConfig")});function OK(e){if(typeof e=="boolean"||e==null){if(e===VO&&KO)return _o.trace?.("Using cached validation error result (primitive) - returning disabled"),!1;if(e===VO&&$T!==null)return _o.trace?.("Using cached certificate verification config (primitive)"),$T;_o.trace?.("Parsing and caching certificate verification config (primitive)"),VO=e;try{return $T=bK(e),KO=null,$T}catch(n){return KO=n,_o.error?.(`Certificate verification config validation failed - defaulting to disabled: ${n.message}`),!1}}if(RK.get(e))return _o.trace?.("Using cached validation error result (object) - returning disabled"),!1;let r=yK.get(e);if(r!==void 0)return _o.trace?.("Using cached certificate verification config (object)"),r;_o.trace?.("Parsing and caching certificate verification config (object)");try{let n=bK(e);return yK.set(e,n),n}catch(n){return RK.set(e,n),_o.error?.(`Certificate verification config validation failed - defaulting to disabled: ${n.message}`),!1}}function bK(e){if(_o.trace?.(`getCertificateVerificationConfig called with: ${JSON.stringify({mtlsConfig:e})}`),!e)return!1;let t=e===!0?void 0:e.certificateVerification;return _o.trace?.(`Certificate verification config: ${JSON.stringify({verificationConfig:t})}`),t==null||t===!1?!1:SK(t===!0?{}:t)}var AK,IK,_o,wK,NK,CK,yK,VO,$T,RK,KO,YO=se(()=>{AK=b(sr()),IK=b(Rt());TK();_o=(0,AK.loggerWithTag)("cert-verification-config"),wK=10080*60*1e3,NK=3e5,CK=`Harper/${IK.packageJson.version} CRL-Client`,yK=new WeakMap,VO=null,$T=null,RK=new WeakMap,KO=null;a(OK,"getCachedCertificateVerificationConfig");a(bK,"getCertificateVerificationConfig")});function vh(e){return e===LK||e===Wde}function jde(e){return e===DK||e===vK}function WO(e){return e===LK?DK:vK}function zde(){if(PK)return;PK=!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:WO(s)}:r.getAlgorithmByOID.call(this,...n)},e.getAlgorithmParameters=function(...n){let[s,i]=n;return jde(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=WO(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=WO(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,LK,Wde,DK,vK,PK,MK=se(()=>{eu=b(require("pkijs")),Mh=require("node:crypto"),LK="1.3.101.112",Wde="1.3.101.113",DK="Ed25519",vK="Ed448",PK=!1;a(vh,"isEd25519OrEd448");a(jde,"isEdDSAAlgorithmName");a(WO,"getEdDSAAlgorithmName");a(zde,"applyEd25519Patch");zde()});var FK={};ye(FK,{CRLSignatureVerificationError:()=>Uh,performCRLCheck:()=>Xde,verifyCRL:()=>JO});function Jde(){return VT||(VT=GT(),VT.sourcedFrom(df)),VT}function Qde(){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(zO)),KT}function xK(){return jO||(jO=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}]})),jO}async function JO(e,t,r,n){if(r?.enabled===!1)return{valid:!0,status:"disabled",method:"disabled"};try{let s=bc(e,"CERTIFICATE"),i=bc(t,"CERTIFICATE"),o=n??HO(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 Xde(e,t,r,n){let s=n??HO(e);if(s.length===0)return{status:"good"};let i=gK(e),o=qO(t),c=GO(o,i);try{let u=await xK().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 Zde(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 Zde(e,t,r){let n=Date.now();for(let s of e)try{let i=Qde(),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 BK(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 BK(e,t,r){let n=new AbortController,s=setTimeout(()=>n.abort(),r);try{let i=await fetch(e,{signal:n.signal,headers:{"User-Agent":CK}});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+wK,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 efe(u,t,e,p).catch(_=>{Or.error?.(`Error processing revoked certificates: ${_}`)}),E}finally{clearTimeout(s)}}async function efe(e,t,r,n){let s=xK(),i=qO(t),o=r;try{await tfe(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=GO(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 tfe(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,UK,Uh,Or,VT,zO,KT,jO,QO=se(()=>{YT=b(require("pkijs")),UK=b(sr());Oe();Ji();qT();YO();XO();Uh=class extends Error{static{a(this,"CRLSignatureVerificationError")}constructor(t){super(t),this.name="CRLSignatureVerificationError"}},Or=(0,UK.loggerWithTag)("crl-verification");a(Jde,"getCertificateCacheTable");zO=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 BK(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()+NK;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(Qde,"getCRLCacheTable");a(xK,"getRevokedCertificateTable");a(JO,"verifyCRL");a(Xde,"performCRLCheck");a(Zde,"checkCRLFreshness");a(BK,"downloadAndParseCRL");a(efe,"processRevokedCertificates");a(tfe,"clearExistingCRLEntries")});async function rfe(){ZO||(ZO=(await Promise.resolve().then(()=>(QO(),FK))).performCRLCheck),eP||(eP=(await Promise.resolve().then(()=>(tP(),HK))).performOCSPCheck)}var kK,SBe,ZO,eP,df,XO=se(()=>{Ji();kK=b(sr()),SBe=(0,kK.loggerWithTag)("cert-verification-source");a(rfe,"loadVerificationFunctions");df=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 rfe();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 eP(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 HK={};ye(HK,{performOCSPCheck:()=>sfe,verifyOCSP:()=>rP});function nfe(){return jT||(jT=GT(),jT.sourcedFrom(df)),jT}async function rP(e,t,r,n){if(r?.enabled===!1)return{valid:!0,status:"disabled",method:"disabled"};try{let s=bc(e,"CERTIFICATE"),i=bc(t,"CERTIFICATE"),o=HT(s,i,"ocsp"),c=await nfe().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 sfe(e,t,r,n){try{let s=await(0,GK.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 GK,qK,WT,jT,tP=se(()=>{MK();GK=require("easy-ocsp"),qK=b(sr());qT();XO();WT=(0,qK.loggerWithTag)("ocsp-verification");a(nfe,"getCertificateCacheTable");a(rP,"verifyOCSP");a(sfe,"performOCSPCheck")});async function ff(e,t){cn.debug?.(`verifyCertificate called for: ${e.subject?.CN||"unknown"}`);let r=OK(t);if(r===!1)return cn.debug?.("Certificate verification disabled"),{valid:!0,status:"disabled",method:"disabled"};let n=EK(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=bc(n[0].cert,"CERTIFICATE"),{crlUrls:i,ocspUrls:o}=_K(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 JO(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 rP(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 $K,cn,zT=se(()=>{$K=b(sr());qT();YO();tP();QO();cn=(0,$K.loggerWithTag)("cert-verification");a(ff,"verifyCertificate")});var aa={};ye(aa,{buildReplicationMtlsConfig:()=>XK,clearThisNodeName:()=>mfe,disableReplication:()=>cfe,enabledDatabases:()=>yc,forEachReplicatedDatabase:()=>Ec,getThisNodeId:()=>kT,getThisNodeName:()=>nt,getThisNodeUrl:()=>_c,hostnameToUrl:()=>ey,lastTimeInAuditStore:()=>Rh,monitorNodeCAs:()=>ZK,replicateOperation:()=>hfe,replicationCertificateAuthorities:()=>ca,sendOperationToNode:()=>xh,servers:()=>ofe,setReplicator:()=>tY,start:()=>afe,startOnMainThread:()=>hO,subscribeToNode:()=>wh,unsubscribeFromNode:()=>AT,urlToNodeName:()=>Ri});function XK(e){return e?.mtls&&typeof e.mtls=="object"?e.mtls:!0}function afe(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(Ri(i.url),i);lfe(e);let r=XK(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 ff(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(ca);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()}ZK(()=>{for(let i of s)i()})}function ZK(e){let t=0;ef(r=>{r?.ca&&(ca.add(r.ca),ca.size!==t&&(t=ca.size,e?.()))})}function cfe(e=!0){QK=e}function lfe(e){QK||(lt(),yc=e.databases,Ec(e,(t,r)=>{if(!t){let n=e.databaseSubscriptions||Rc;for(let[s,i]of QT){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];tY(r,s,e),xO.get(s)?.forEach(i=>i(s))}}))}function tY(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 eY extends Xt{static{a(this,"Replicator")}static connection;static subscription;static async subscribe(){let i=r.databaseSubscriptions||Rc,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 is,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=dfe(h,eY.subscription,e);if(E?.isConnected){let _=Zd(t.auditStore,e,h)[BT];(!d||_<m)&&(d=E,f=h,m=_)}}if(!d)throw l||new jK.ServerError(`No connection to any other nodes are available: ${c}`,502);let p={requestId:ife++,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 ufe(e,t,r,n,s,i){let o=t+"-"+e,c=QT.get(o);c||(c=new Map,QT.set(o,c));let l=c.get(n);if(l)return l;if(r)return c.set(n,l=new cf(t,r,n,s,i)),l.connect(),l.once("finished",()=>c.delete(n)),l}function dfe(e,t,r){let n=VK.get(e);n||(n=new Map,VK.set(e,n));let s=n.get(r);if(s)return s;let i=Gt().primaryStore.get(e);return i?.url&&(s=new cf(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{zK.isMainThread&&wt.warn("Subscribing on main thread (should not happen in multi-threaded instance)",e.nodes[0].url,e.database);let t=Rc.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,Rc.set(e.database,t)}let r=ufe(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=QT.get(n);if(s){let i=s.get(r);i&&(i.unsubscribe(),s.delete(r))}}function ffe(){if(nP!==void 0)return nP;let e=Ks.default.get(x.OPERATIONSAPI_TLS_CERTIFICATE)||Ks.default.get(x.TLS_CERTIFICATE);if(e)return nP=new YK.X509Certificate((0,WK.readFileSync)(e)).subject?.match(/CN=(.*)/)?.[1]??null}function nt(){return XT||(XT=Ks.default.get("replication_hostname")??Ri(Ks.default.get("replication_url"))??ffe()??KK("operationsapi_network_secureport")??KK("operationsapi_network_port")??"127.0.0.1")}function mfe(){XT=void 0}function KK(e){let t=Ks.default.get(e),r=t?.lastIndexOf?.(":");if(r>0)return t.slice(0,r)}function JT(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 _c(){let e=Ks.default.get("replication_url");return e||ey(nt())}function ey(e){let t=JT("replication_port");if(t)return`ws://${e}:${t}`;if(t=JT("replication_secureport"),t)return`wss://${e}:${t}`;if(t=JT("operationsapi_network_port"),t)return`ws://${e}:${t}`;if(t=JT("operationsapi_network_secureport"),t)return`wss://${e}:${t}`}function Ri(e){if(e)return new URL(e).hostname}function Ec(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):pfe(n)&&t(s,n,!1)}a(r,"forDatabase")}function pfe(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 hfe(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,YK,WK,ZT,jK,zK,JK,QK,ife,ofe,ca,yc,QT,VK,nP,XT,gs=se(()=>{Oe();Ji();qu();BO();Hr();Ks=b(fe()),wt=b(Q()),YK=require("crypto");zT();WK=require("fs");Nh();tf();G();pO();ZT=b(require("node:tls")),jK=b(Ee()),zK=require("worker_threads"),JK=b(Ts()),ife=1,ofe=[],ca=Ks.default.get(x.REPLICATION_ENABLEROOTCAS)!==!1?new Set(ZT.rootCertificates):new Set;a(XK,"buildReplicationMtlsConfig");a(afe,"start");a(ZK,"monitorNodeCAs");a(cfe,"disableReplication");a(lfe,"assignReplicationSource");a(tY,"setReplicator");QT=new Map;a(ufe,"getSubscriptionConnection");VK=new Map;a(dfe,"getRetrievalConnectionByName");a(xh,"sendOperationToNode");a(wh,"subscribeToNode");a(AT,"unsubscribeFromNode");a(ffe,"getCommonNameFromCert");a(nt,"getThisNodeName");a(mfe,"clearThisNodeName");Object.defineProperty(Ue,"hostname",{get(){return nt()}});a(KK,"getHostFromListeningPort");a(JT,"getPortFromListeningPort");a(kT,"getThisNodeId");Ue.replication={getThisNodeId:kT,exportIdMapping:yh};a(_c,"getThisNodeUrl");a(ey,"hostnameToUrl");a(Ri,"urlToNodeName");a(Ec,"forEachReplicatedDatabase");a(pfe,"hasExplicitlyReplicatedTable");a(Rh,"lastTimeInAuditStore");a(hfe,"replicateOperation")});var iy=M(($Be,oY)=>{"use strict";var mf=vV(),{validateBySchema:Bh}=mt(),{commonValidators:pf,schemaRegex:sP}=Xi(),Sr=require("joi"),Efe=Q(),_fe=require("uuid").v4,ny=Xo(),hf=(G(),D(j)),gfe=require("util"),Ac=ps(),{handleHDBError:la,hdbErrors:Sfe,ClientError:tu}=Ee(),{HDB_ERROR_MSGS:ty,HTTP_STATUS_CODES:ua}=Sfe,{SchemaEventMsg:sy}=ds(),rY=cr(),{getDatabases:Tfe}=(Oe(),D(pt)),{transformReq:Ef}=ae(),{replicateOperation:nY}=(gs(),D(aa)),{cleanupOrphans:yfe}=(os(),D(ig)),ry=Sr.string().min(1).max(pf.schema_length.maximum).pattern(sP).messages({"string.pattern.base":"{:#label} "+pf.schema_format.message}),Rfe=Sr.string().min(1).max(pf.schema_length.maximum).pattern(sP).messages({"string.pattern.base":"{:#label} "+pf.schema_format.message}).required(),bfe=Sr.string().min(1).max(pf.schema_length.maximum).pattern(sP).messages({"string.pattern.base":"{:#label} "+pf.schema_format.message,"any.required":"'primary_key' is required","string.base":"'primary_key' must be a string"}).required();oY.exports={createSchema:Afe,createSchemaStructure:sY,createTable:Ife,createTableStructure:iY,createAttribute:Pfe,dropSchema:wfe,dropTable:Nfe,dropAttribute:Cfe,getBackup:Lfe,cleanupOrphanBlobs:Dfe};async function Afe(e){let t=await sY(e);return ny.signalSchemaChange(new sy(process.pid,e.operation,e.schema)),t}a(Afe,"createSchema");async function sY(e){let t=Bh(e,Sr.object({database:ry,schema:ry}));if(t)throw new tu(t.message);if(Ef(e),!await mf.checkSchemaExists(e.schema))throw la(new Error,ty.SCHEMA_EXISTS_ERR(e.schema),ua.BAD_REQUEST,hf.LOG_LEVELS.ERROR,ty.SCHEMA_EXISTS_ERR(e.schema),!0);return await Ac.createSchema(e),`database '${e.schema}' successfully created`}a(sY,"createSchemaStructure");async function Ife(e){return Ef(e),e.hash_attribute=e.primary_key??e.hash_attribute,await iY(e)}a(Ife,"createTable");async function iY(e){let t=Bh(e,Sr.object({database:ry,schema:ry,table:Rfe,residence:Sr.array().items(Sr.string().min(1)).optional(),hash_attribute:bfe}));if(t)throw new tu(t.message);if(!await mf.checkSchemaTableExists(e.schema,e.table))throw la(new Error,ty.TABLE_EXISTS_ERR(e.schema,e.table),ua.BAD_REQUEST,hf.LOG_LEVELS.ERROR,ty.TABLE_EXISTS_ERR(e.schema,e.table),!0);let n={name:e.table,schema:e.schema,id:_fe(),hash_attribute:e.hash_attribute};try{if(e.residence)if(global.clustering_on)n.residence=e.residence,await Ac.createTable(n,e);else throw la(new Error,"Clustering does not appear to be enabled. Cannot insert table with property 'residence'.",ua.BAD_REQUEST);else await Ac.createTable(n,e);return`table '${e.schema}.${e.table}' successfully created.`}catch(s){throw s}}a(iY,"createTableStructure");async function wfe(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);Ef(e);let r=await mf.checkSchemaExists(e.schema);if(r)throw la(new Error,r,ua.NOT_FOUND,hf.LOG_LEVELS.ERROR,r,!0);let n=await mf.schemaDescribe.describeSchema({schema:e.schema}),s=Object.keys(global.hdb_schema[e.schema]);await Ac.dropSchema(e),ny.signalSchemaChange(new sy(process.pid,e.operation,e.schema)),await rY.purgeSchemaTableStreams(e.schema,s);let i=await nY(e);return i.message=`successfully deleted '${e.schema}'`,i}a(wfe,"dropSchema");async function Nfe(e){let t=Bh(e,Sr.object({database:Sr.string(),schema:Sr.string(),table:Sr.string().required()}));if(t)throw new tu(t.message);Ef(e);let r=await mf.checkSchemaTableExists(e.schema,e.table);if(r)throw la(new Error,r,ua.NOT_FOUND,hf.LOG_LEVELS.ERROR,r,!0);await Ac.dropTable(e),await rY.purgeTableStream(e.schema,e.table);let n=await nY(e);return n.message=`successfully deleted table '${e.schema}.${e.table}'`,n}a(Nfe,"dropTable");async function Cfe(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);Ef(e);let r=await mf.checkSchemaTableExists(e.schema,e.table);if(r)throw la(new Error,r,ua.NOT_FOUND,hf.LOG_LEVELS.ERROR,r,!0);if(e.attribute===global.hdb_schema[e.schema][e.table].hash_attribute)throw la(new Error,"You cannot drop a hash attribute",ua.BAD_REQUEST,void 0,void 0,!0);if(hf.TIME_STAMP_NAMES.indexOf(e.attribute)>=0)throw la(new Error,`cannot drop internal timestamp attribute: ${e.attribute}`,ua.BAD_REQUEST,void 0,void 0,!0);try{return await Ac.dropAttribute(e),Ofe(e),ny.signalSchemaChange(new sy(process.pid,e.operation,e.schema,e.table,e.attribute)),`successfully deleted attribute '${e.attribute}'`}catch(n){throw Efe.error(`Got an error deleting attribute ${gfe.inspect(e)}.`),n}}a(Cfe,"dropAttribute");function Ofe(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(Ofe,"dropAttributeFromGlobal");async function Pfe(e){Ef(e);let t=Tfe()[e.schema][e.table].attributes;for(let{name:r}of t)if(r===e.attribute)throw la(new Error,`attribute '${e.attribute}' already exists in ${e.schema}.${e.table}`,ua.BAD_REQUEST,void 0,void 0,!0);return await Ac.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(Pfe,"createAttribute");function Lfe(e){return Ac.getBackup(e)}a(Lfe,"getBackup");function Dfe(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 yfe(databases[e.database],e.database),{message:"Orphaned blobs cleanup started, check logs for progress"}}a(Dfe,"cleanupOrphanBlobs")});var cY=M((KBe,aY)=>{"use strict";var{OPERATIONS_ENUM:vfe}=(G(),D(j)),iP=class{static{a(this,"ReadAuditLogObject")}constructor(t,r,n=void 0,s=void 0){this.operation=vfe.READ_AUDIT_LOG,this.schema=t,this.table=r,this.search_type=n,this.search_values=s}};aY.exports=iP});var oP=M((jBe,mY)=>{"use strict";var Mfe=ps(),WBe=cY(),oy=ae(),ay=(G(),D(j)),Ufe=fe(),{handleHDBError:lY,hdbErrors:xfe}=Ee(),{HDB_ERROR_MSGS:uY,HTTP_STATUS_CODES:dY}=xfe,Bfe=Object.values(ay.READ_AUDIT_LOG_SEARCH_TYPES_ENUM),fY="To use this operation audit log must be enabled in harperdb-config.yaml";mY.exports=Ffe;async function Ffe(e){if(oy.isEmpty(e.schema))throw new Error(uY.SCHEMA_REQUIRED_ERR);if(oy.isEmpty(e.table))throw new Error(uY.TABLE_REQUIRED_ERR);if(!Ufe.get(ay.CONFIG_PARAMS.LOGGING_AUDITLOG))throw lY(new Error,fY,dY.BAD_REQUEST,ay.LOG_LEVELS.ERROR,fY,!0);let t=oy.checkSchemaTableExist(e.schema,e.table);if(t)throw lY(new Error,t,dY.NOT_FOUND,ay.LOG_LEVELS.ERROR,t,!0);if(!oy.isEmpty(e.search_type)&&Bfe.indexOf(e.search_type)<0)throw new Error(`Invalid searchType '${read_audit_log_object.search_type}'`);return await Mfe.readAuditLog(e)}a(Ffe,"readAuditLog")});var hY=M((JBe,pY)=>{"use strict";var{OPERATIONS_ENUM:kfe}=(G(),D(j)),aP=class{static{a(this,"GetBackupObject")}constructor(t,r,n=void 0,s=void 0){this.operation=kfe.GET_BACKUP,this.schema=t,this.table=r}};pY.exports=aP});var gY=M((eFe,_Y)=>{"use strict";var Hfe=ps(),XBe=hY(),cP=ae(),Gfe=(G(),D(j)),ZBe=fe(),{handleHDBError:qfe,hdbErrors:$fe}=Ee(),{HDB_ERROR_MSGS:EY,HTTP_STATUS_CODES:Vfe}=$fe;_Y.exports=Kfe;async function Kfe(e){if(cP.isEmpty(e.schema))throw new Error(EY.SCHEMA_REQUIRED_ERR);if(cP.isEmpty(e.table))throw new Error(EY.TABLE_REQUIRED_ERR);let t=cP.checkSchemaTableExist(e.schema,e.table);if(t)throw qfe(new Error,t,Vfe.NOT_FOUND,Gfe.LOG_LEVELS.ERROR,t,!0);return await Hfe.getBackup(readAuditLogObject)}a(Kfe,"getBackup")});var yY=M((rFe,TY)=>{"use strict";var Yfe=fe(),da=require("joi"),Wfe=mt(),SY=require("moment"),jfe=require("fs-extra"),uP=require("path"),zfe=require("lodash"),Fh=(G(),D(j)),{LOG_LEVELS:ru}=(G(),D(j)),Jfe="YYYY-MM-DD hh:mm:ss",Qfe=uP.resolve(__dirname,"../logs");TY.exports=function(e){return Wfe.validateBySchema(e,Xfe)};var Xfe=da.object({from:da.custom(lP),until:da.custom(lP),to:da.custom(lP),level:da.valid(ru.NOTIFY,ru.FATAL,ru.ERROR,ru.WARN,ru.INFO,ru.DEBUG,ru.TRACE),order:da.valid("asc","desc"),limit:da.number().min(1),start:da.number().min(0),log_name:da.custom(Zfe)});function lP(e,t){if(SY(e,SY.ISO_8601).format(Jfe)==="Invalid date")return t.message(`'${t.state.path[0]}' date '${e}' is invalid.`)}a(lP,"validateDatetime");function Zfe(e,t){if(zfe.invert(Fh.LOG_NAMES)[e]===void 0)return t.message(`'log_name' '${e}' is invalid.`);let n=Yfe.get(Fh.HDB_SETTINGS_NAMES.LOG_PATH_KEY),s=e===void 0?Fh.LOG_NAMES.HDB:e,i=s===Fh.LOG_NAMES.INSTALL?uP.join(Qfe,Fh.LOG_NAMES.INSTALL):uP.join(n,s);return jfe.existsSync(i)?null:t.message(`'log_name' '${e}' does not exist.`)}a(Zfe,"validateReadLogPath")});var fP=M((sFe,bY)=>{"use strict";var cy=(G(),D(j)),eme=Q(),tme=fe(),rme=yY(),dP=require("path"),RY=require("fs-extra"),{once:nme}=require("events"),{handleHDBError:sme,hdbErrors:ime}=Ee(),{PACKAGE_ROOT:ome}=Rt(),{replicateOperation:ame}=(gs(),D(aa)),cme=dP.join(ome,"logs"),lme=1e3,ume=200;bY.exports=dme;async function dme(e){let t=rme(e);if(t)throw sme(t,t.message,ime.HTTP_STATUS_CODES.BAD_REQUEST,void 0,void 0,!0);let r=ame(e),n=tme.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?dP.join(cme,cy.LOG_NAMES.INSTALL):dP.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?lme: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(RY.statSync(i).size-(E+5)*ume,0));let R=RY.createReadStream(i,{start:_});R.on("error",q=>{eme.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&&(go(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&&(go(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&&(go(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&&(go(q,p,y),S++,S===E&&R.destroy());break;case o:q.level===c&&S<h?S++:q.level===c&&(go(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&&(go(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&&(go(q,p,y),S++,S===E&&R.destroy());break;default:S<h?S++:(go(q,p,y),S++,S===E&&R.destroy())}}a(H,"onLogMessage"),await nme(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")go({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,go(z,p,y)}}return y}a(dme,"readLog");function go(e,t,r){t==="desc"?fme(e,r):t==="asc"?mme(e,r):r.push(e)}a(go,"pushLineToResult");function fme(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(fme,"insertDescending");function mme(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(mme,"insertAscending")});var ly=M((uFe,NY)=>{"use strict";var mP=require("joi"),{string:_f,boolean:AY,date:pme}=mP.types(),hme=mt(),{validateSchemaExists:oFe,validateTableExists:aFe,validateSchemaName:cFe}=Xi(),Eme=(G(),D(j)),_me=vt(),IY=fe();IY.initSync();var lFe=_f.invalid(IY.get(Eme.CONFIG_PARAMS.CLUSTERING_NODENAME)??"node_name").pattern(_me.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),wY={operation:_f.valid("add_node","update_node","set_node_replication"),node_name:_f.optional(),subscriptions:mP.array().items({table:_f.optional(),schema:_f.optional(),database:_f.optional(),subscribe:AY.required(),publish:AY.required().custom(Sme),start_time:pme.iso()})};function gme(e){return hme.validateBySchema(e,mP.object(wY))}a(gme,"addUpdateNodeValidator");function Sme(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(Sme,"checkForFalsy");NY.exports={addUpdateNodeValidator:gme,validationSchema:wY}});var gf=M((fFe,CY)=>{"use strict";var pP=class{static{a(this,"Node")}constructor(t,r,n){this.name=t,this.subscriptions=r,this.system_info=n}},hP=class{static{a(this,"NodeSubscription")}constructor(t,r,n,s){this.schema=t,this.table=r,this.publish=n,this.subscribe=s}};CY.exports={Node:pP,NodeSubscription:hP}});var PY=M((pFe,OY)=>{"use strict";var Tme=(G(),D(j)).OPERATIONS_ENUM,EP=class{static{a(this,"UpsertObject")}constructor(t,r,n,s=void 0){this.operation=Tme.UPSERT,this.schema=t,this.table=r,this.records=n,this.__origin=s}};OY.exports=EP});var kh=M((EFe,LY)=>{"use strict";var _P=class{static{a(this,"RemotePayloadObject")}constructor(t,r,n,s){this.operation=t,this.node_name=r,this.subscriptions=n,this.system_info=s}},gP=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)}};LY.exports={RemotePayloadObject:_P,RemotePayloadSubscription:gP}});var vY=M((gFe,DY)=>{"use strict";var SP=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}};DY.exports=SP});var UY=M((AFe,MY)=>{"use strict";var yme=vY(),TFe=Jt(),yFe=gt(),Rme=Q(),{getSchemaPath:RFe,getTransactionAuditStorePath:bFe}=bt(),{getDatabases:bme}=(Oe(),D(pt));MY.exports=Ame;async function Ame(e){let t=new yme;try{let r=bme()[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){Rme.warn(`unable to stat table dbi due to ${r}`)}return t}a(Ame,"lmdbGetTableSize")});var BY=M((wFe,xY)=>{"use strict";var TP=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}};xY.exports=TP});var Gh=M((DFe,GY)=>{"use strict";var Ime=require("fs-extra"),wme=require("path"),An=require("systeminformation"),Ic=Q(),FY=cr(),CFe=vt(),Sf=(G(),D(j)),Nme=UY(),Cme=Kl(),{getThreadInfo:kY}=st(),Hh=fe();Hh.initSync();var Ome=BY(),{openEnvironment:OFe}=gt(),{getSchemaPath:PFe}=bt(),{database:LFe,databases:yP}=(Oe(),D(pt)),uy;GY.exports={getHDBProcessInfo:IP,getNetworkInfo:NP,getDiskInfo:wP,getMemoryInfo:AP,getCPUInfo:bP,getTimeInfo:RP,getSystemInformation:CP,systemInformation:Pme,getTableSize:OP,getMetrics:PP};function RP(){return An.time()}a(RP,"getTimeInfo");async function bP(){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 Ic.error(`error in getCPUInfo: ${e}`),{}}}a(bP,"getCPUInfo");async function AP(){try{let{buffers:e,cached:t,slab:r,buffcache:n,...s}=await An.mem();return Object.assign(s,process.memoryUsage())}catch(e){return Ic.error(`error in getMemoryInfo: ${e}`),{}}}a(AP,"getMemoryInfo");async function IP(){let e={core:[],clustering:[]};try{let t=await An.processes(),r;try{r=Number.parseInt(await Ime.readFile(wme.join(Hh.get(Sf.CONFIG_PARAMS.ROOTPATH),Sf.HDB_PID_FILE),"utf8"))}catch(n){if(n.code===Sf.NODE_ERROR_CODES.ENOENT)Ic.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 Ic.error(`error in getHDBProcessInfo: ${t}`),e}}a(IP,"getHDBProcessInfo");async function wP(){let e={};try{if(!Hh.get(Sf.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 Ic.error(`error in getDiskInfo: ${t}`),e}}a(wP,"getDiskInfo");async function NP(){let e={default_interface:null,latency:{},interfaces:[],stats:[],connections:[]};try{return Hh.get(Sf.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 Ic.error(`error in getNetworkInfo: ${t}`),e}}a(NP,"getNetworkInfo");async function CP(){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 Ic.error(`error in getSystemInformation: ${t}`),e}}a(CP,"getSystemInformation");async function OP(){let e=[],t=await Cme.describeAll();for(let r of Object.values(t))for(let n of Object.values(r))e.push(await Nme(n));return e}a(OP,"getTableSize");async function PP(){let e={};for(let t in yP){let r=e[t]={},n=r.tables={};for(let s in yP[t])try{let i=yP[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){Ic.notify(`Error getting stats for table ${s}: ${i}`)}}return e}a(PP,"getMetrics");async function HY(){if(Hh.get(Sf.CONFIG_PARAMS.CLUSTERING_ENABLED)){let{jsm:e}=await FY.getNATSReferences(),t=await FY.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(HY,"getNatsStreamInfo");async function Pme(e){let t=new Ome;if(!Array.isArray(e.attributes)||e.attributes.length===0)return t.system=await CP(),t.time=RP(),t.cpu=await bP(),t.memory=await AP(),t.disk=await wP(),t.network=await NP(),t.harperdb_processes=await IP(),t.table_size=await OP(),t.metrics=await PP(),t.threads=await kY(),t.replication=await HY(),t;for(let r=0;r<e.attributes.length;r++)switch(e.attributes[r]){case"system":t.system=await CP();break;case"time":t.time=RP();break;case"cpu":t.cpu=await bP();break;case"memory":t.memory=await AP();break;case"disk":t.disk=await wP();break;case"network":t.network=await NP();break;case"harperdb_processes":t.harperdb_processes=await IP();break;case"table_size":t.table_size=await OP();break;case"database_metrics":case"metrics":t.metrics=await PP();break;case"threads":t.threads=await kY();break;case"replication":t.replication=await HY();break;default:break}return t}a(Pme,"systemInformation")});var fa=M((BFe,KY)=>{"use strict";var Lme=Vn(),LP=ae(),Dme=require("util"),nu=(G(),D(j)),qY=fe();qY.initSync();var vme=UC(),$Y=Sn(),{Node:MFe,NodeSubscription:UFe}=gf(),Mme=pd(),Ume=PY(),{RemotePayloadObject:xme,RemotePayloadSubscription:Bme}=kh(),{handleHDBError:Fme,hdbErrors:kme}=Ee(),{HTTP_STATUS_CODES:Hme,HDB_ERROR_MSGS:Gme}=kme,qme=di(),$me=Gh(),{packageJson:Vme}=Rt(),{getDatabases:Kme}=(Oe(),D(pt)),xFe=Dme.promisify(vme.authorize),Yme=$Y.searchByHash,Wme=$Y.searchByValue;KY.exports={isEmpty:jme,getNodeRecord:zme,upsertNodeRecord:Jme,buildNodePayloads:Qme,checkClusteringEnabled:Xme,getAllNodeRecords:Zme,getSystemInfo:epe,reverseSubscription:VY};function jme(e){return e==null}a(jme,"isEmpty");async function zme(e){let t=new Mme(nu.SYSTEM_SCHEMA_NAME,nu.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,[e],["*"]);return Yme(t)}a(zme,"getNodeRecord");async function Jme(e){let t=new Ume(nu.SYSTEM_SCHEMA_NAME,nu.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,[e]);return Lme.upsert(t)}a(Jme,"upsertNodeRecord");function VY(e){if(LP.isEmpty(e.subscribe)||LP.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(VY,"reverseSubscription");function Qme(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=LP.getTableHashAttribute(l,u),{subscribe:f,publish:m}=VY(c),p=Kme()[l]?.[u],h=new Bme(l,u,d,m,f,c.start_time,p.schemaDefined?p.attributes:void 0);s.push(h)}return new xme(r,t,s,n)}a(Qme,"buildNodePayloads");function Xme(){if(!qY.get(nu.CONFIG_PARAMS.CLUSTERING_ENABLED))throw Fme(new Error,Gme.CLUSTERING_NOT_ENABLED,Hme.BAD_REQUEST,void 0,void 0,!0)}a(Xme,"checkClusteringEnabled");async function Zme(){let e=new qme(nu.SYSTEM_SCHEMA_NAME,nu.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,"name","*",void 0,["*"]);return Array.from(await Wme(e))}a(Zme,"getAllNodeRecords");async function epe(){let e=await $me.getSystemInformation();return{hdb_version:Vme.version,node_version:e.node_version,platform:e.platform}}a(epe,"getSystemInfo")});var DP=M((kFe,ZY)=>{"use strict";var dy=cr(),YY=ae(),WY=vt(),jY=(G(),D(j)),fy=Q(),zY=iy(),tpe=Ip(),{RemotePayloadObject:rpe}=kh(),{handleHDBError:JY,hdbErrors:npe}=Ee(),{HTTP_STATUS_CODES:QY}=npe,{NodeSubscription:XY}=gf();ZY.exports=spe;async function spe(e,t){let r;try{r=await dy.request(`${t}.${WY.REQUEST_SUFFIX}`,new rpe(jY.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,QY.INTERNAL_SERVER_ERROR,"error",c)}if(r.status===WY.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR){let o=`Error returned from remote node ${t}: ${r.message}`;throw JY(new Error,o,QY.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===jY.SYSTEM_SCHEMA_NAME){await dy.createLocalTableStream(l,c);let h=new XY(l,c,o.publish,o.subscribe);h.start_time=o.start_time,i.push(h);continue}let u=YY.doesSchemaExist(l),d=n[l]!==void 0,f=c?YY.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 zY.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 tpe(l,c,n[l][c].hash_attribute);n[l][c].attributes&&(h.attributes=n[l][c].attributes),await zY.createTable(h)}await dy.createLocalTableStream(l,c);let p=new XY(l,c,o.publish,o.subscribe);p.start_time=o.start_time,i.push(p)}return{added:i,skipped:s}}a(spe,"reviewSubscriptions")});var Tf={};ye(Tf,{addNodeBack:()=>vP,removeNodeBack:()=>MP,setNode:()=>cpe});async function cpe(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=Ri(t)):t=ey(r);let n=(0,tW.validateBySchema)(e,ape);if(n)throw(0,ma.handleHDBError)(n,n.message,ope.BAD_REQUEST,void 0,void 0,!0);if(e.operation==="remove_node"){if(!t&&!r)throw new ma.ClientError("url or hostname is required for remove_node operation");let p=r,h=Gt(),E=await h.get(p);if(!E)throw new ma.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 ma.ClientError("url required for this operation");let s=_c();if(s==null)throw new ma.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,Nc.get)(x.REPLICATION_HOSTNAME),target_hostname:r,url:s,csr:o,cert_auth:c,authorization:e.retain_authorization?e.authorization:null};if((0,Nc.get)(x.REPLICATION_SHARD)!==void 0&&(l.shard=(0,Nc.get)(x.REPLICATION_SHARD)),e.subscriptions?l.subscriptions=e.subscriptions.map(eW):l.subscriptions=null,e.hasOwnProperty("subscribe")||e.hasOwnProperty("publish")){let p=eW(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:ipe.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,Nc.get)(x.REPLICATION_SHARD)!==void 0&&(p.shard=(0,Nc.get)(x.REPLICATION_SHARD)),e.retain_authorization&&(p.authorization=e.authorization),e.start_time&&(p.start_time=e.start_time),await ia(nt(),p)}await ia(u?u.nodeName:f.name??Ri(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 vP(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:_c(),ca:s?.certificate,replicates:!0,subscriptions:null};(0,Nc.get)(x.REPLICATION_SHARD)!==void 0&&(i.shard=(0,Nc.get)(x.REPLICATION_SHARD),t.shard=i.shard),e.start_time&&(i.start_time=e.start_time),e.authorization&&(i.authorization=e.authorization),await ia(nt(),i)}return await ia(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 MP(e){ys.trace("removeNodeBack received request:",e),await Gt().delete(e.name)}function eW(e){let{subscribe:t,publish:r}=e;return{...e,subscribe:r,publish:t}}var Ys,tW,wc,Nc,ys,ma,ipe,ope,ape,yf=se(()=>{Ys=b(Ts()),tW=b(mt()),wc=b(require("joi")),Nc=b(fe());G();Nh();tf();gs();ys=b(Q()),ma=b(Ee()),{pki:ipe}=require("node-forge"),{HTTP_STATUS_CODES:ope}=ma.hdbErrors,ape=wc.default.object({hostname:wc.default.string(),verify_tls:wc.default.boolean(),replicates:wc.default.boolean(),subscriptions:wc.default.array(),revoked_certificates:wc.default.array(),shard:wc.default.number()});a(cpe,"setNode");a(vP,"addNodeBack");a(MP,"removeNodeBack");a(eW,"reverseSubscription")});var _y=M((jFe,nW)=>{"use strict";var{handleHDBError:my,hdbErrors:lpe}=Ee(),{HTTP_STATUS_CODES:py}=lpe,{addUpdateNodeValidator:upe}=ly(),hy=Q(),Ey=(G(),D(j)),rW=vt(),dpe=ae(),qh=cr(),$h=fa(),UP=fe(),fpe=DP(),{Node:mpe,NodeSubscription:ppe}=gf(),{broadcast:hpe}=st(),{setNode:Epe}=(yf(),D(Tf)),YFe=fe(),WFe=(G(),D(j)),_pe="Unable to create subscriptions due to schema and/or tables not existing on the local or remote node",gpe="Some subscriptions were unsuccessful due to schema and/or tables not existing on the local or remote node",Spe=UP.get(Ey.CONFIG_PARAMS.CLUSTERING_NODENAME);nW.exports=Tpe;async function Tpe(e,t=!1){if(hy.trace("addNode called with:",e),UP.get(Ey.CONFIG_PARAMS.REPLICATION_URL)||UP.get(Ey.CONFIG_PARAMS.REPLICATION_HOSTNAME))return Epe(e);$h.checkClusteringEnabled();let r=upe(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(!dpe.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 fpe(e.subscriptions,n),o={message:void 0,added:s,skipped:i};if(s.length===0)return o.message=_pe,o;let c=$h.buildNodePayloads(s,Spe,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 ppe(p.schema,p.table,p.publish,p.subscribe))}hy.trace("addNode sending remote payload:",c);let u;try{u=await qh.request(`${n}.${rW.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===rW.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 mpe(n,l,u.system_info);return await $h.upsertNodeRecord(d),hpe({type:"nats_update"}),i.length>0?o.message=gpe:o.message=`Successfully added '${n}' to manifest`,o}a(Tpe,"addNode")});var kP=M((QFe,iW)=>{"use strict";var{handleHDBError:xP,hdbErrors:ype}=Ee(),{HTTP_STATUS_CODES:BP}=ype,{addUpdateNodeValidator:Rpe}=ly(),Vh=Q(),gy=(G(),D(j)),sW=vt(),JFe=ae(),Kh=cr(),Yh=fa(),FP=fe(),{cloneDeep:bpe}=require("lodash"),Ape=DP(),{Node:Ipe,NodeSubscription:wpe}=gf(),{broadcast:Npe}=st(),{setNode:Cpe}=(yf(),D(Tf)),Ope="Unable to update subscriptions due to schema and/or tables not existing on the local or remote node",Ppe="Some subscriptions were unsuccessful due to schema and/or tables not existing on the local or remote node",Lpe=FP.get(gy.CONFIG_PARAMS.CLUSTERING_NODENAME);iW.exports=Dpe;async function Dpe(e){if(Vh.trace("updateNode called with:",e),FP.get(gy.CONFIG_PARAMS.REPLICATION_URL)??FP.get(gy.CONFIG_PARAMS.REPLICATION_HOSTNAME))return Cpe(e);Yh.checkClusteringEnabled();let t=Rpe(e);if(t)throw xP(t,t.message,BP.BAD_REQUEST,void 0,void 0,!0);let r=e.node_name,n,s=await Yh.getNodeRecord(r);s.length>0&&(n=bpe(s));let{added:i,skipped:o}=await Ape(e.subscriptions,r),c={message:void 0,updated:i,skipped:o};if(i.length===0)return c.message=Ope,c;let l=Yh.buildNodePayloads(i,Lpe,gy.OPERATIONS_ENUM.UPDATE_NODE,await Yh.getSystemInfo());for(let d=0,f=i.length;d<f;d++){let m=i[d];Vh.trace(`updateNode updating work stream for node: ${r} subscription:`,m),i[d].start_time===void 0&&delete i[d].start_time}Vh.trace("updateNode sending remote payload:",l);let u;try{u=await Kh.request(`${r}.${sW.REQUEST_SUFFIX}`,l)}catch(d){Vh.error(`updateNode received error from request: ${d}`);let f=Kh.requestErrorHandler(d,"update_node",r);throw xP(new Error,f,BP.INTERNAL_SERVER_ERROR,"error",f)}if(u.status===sW.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR){let d=`Error returned from remote node ${r}: ${u.message}`;throw xP(new Error,d,BP.INTERNAL_SERVER_ERROR,"error",d)}Vh.trace(u);for(let d=0,f=i.length;d<f;d++){let m=i[d];await Kh.updateRemoteConsumer(m,r),m.subscribe===!0?await Kh.updateConsumerIterator(m.schema,m.table,r,"start"):await Kh.updateConsumerIterator(m.schema,m.table,r,"stop")}return n||(n=[new Ipe(r,[],u.system_info)]),await vpe(n[0],i,u.system_info),o.length>0?c.message=Ppe:c.message=`Successfully updated '${r}'`,c}a(Dpe,"updateNode");async function vpe(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 wpe(o.schema,o.table,o.publish,o.subscribe))}n.system_info=r,await Yh.upsertNodeRecord(n),Npe({type:"nats_update"})}a(vpe,"updateNodeTable")});var uW=M((ZFe,lW)=>{"use strict";var cW=require("joi"),{string:oW}=cW.types(),Mpe=mt(),aW=(G(),D(j)),Upe=fe(),xpe=vt();lW.exports=Bpe;function Bpe(e){let t=oW.invalid(Upe.get(aW.CONFIG_PARAMS.CLUSTERING_NODENAME)).pattern(xpe.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=cW.object({operation:oW.valid(aW.OPERATIONS_ENUM.REMOVE_NODE).required(),node_name:t});return Mpe.validateBySchema(e,r)}a(Bpe,"removeNodeValidator")});var Sy=M((tke,hW)=>{"use strict";var{handleHDBError:dW,hdbErrors:Fpe}=Ee(),{HTTP_STATUS_CODES:fW}=Fpe,kpe=uW(),Wh=Q(),mW=fa(),Hpe=ae(),Rf=(G(),D(j)),pW=vt(),HP=cr(),GP=fe(),{RemotePayloadObject:Gpe}=kh(),{NodeSubscription:qpe}=gf(),$pe=Ap(),Vpe=xl(),{broadcast:Kpe}=st(),{setNode:Ype}=(yf(),D(Tf)),Wpe=GP.get(Rf.CONFIG_PARAMS.CLUSTERING_NODENAME);hW.exports=jpe;async function jpe(e){if(Wh.trace("removeNode called with:",e),GP.get(Rf.CONFIG_PARAMS.REPLICATION_URL)??GP.get(Rf.CONFIG_PARAMS.REPLICATION_HOSTNAME))return Ype(e);mW.checkClusteringEnabled();let t=kpe(e);if(t)throw dW(t,t.message,fW.BAD_REQUEST,void 0,void 0,!0);let r=e.node_name,n=await mW.getNodeRecord(r);if(Hpe.isEmptyOrZeroLength(n))throw dW(new Error,`Node '${r}' was not found.`,fW.BAD_REQUEST,void 0,void 0,!0);n=n[0];let s=new Gpe(Rf.OPERATIONS_ENUM.REMOVE_NODE,Wpe,[]),i,o=!1;for(let l=0,u=n.subscriptions.length;l<u;l++){let d=n.subscriptions[l];d.subscribe===!0&&await HP.updateConsumerIterator(d.schema,d.table,r,"stop");try{await HP.updateRemoteConsumer(new qpe(d.schema,d.table,!1,!1),r)}catch(f){Wh.error(f)}}try{i=await HP.request(`${r}.${pW.REQUEST_SUFFIX}`,s),Wh.trace("Remove node reply from remote node:",r,i)}catch(l){Wh.error("removeNode received error from request:",l),o=!0}let c=new $pe(Rf.SYSTEM_SCHEMA_NAME,Rf.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,[r]);return await Vpe.deleteRecord(c),Kpe({type:"nats_update"}),i?.status===pW.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR||o?(Wh.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(jpe,"removeNode")});var gW=M((nke,_W)=>{"use strict";var EW=require("joi"),{string:zpe,array:Jpe}=EW.types(),Qpe=mt(),Xpe=ly();_W.exports=Zpe;function Zpe(e){let t=EW.object({operation:zpe.valid("configure_cluster").required(),connections:Jpe.items(Xpe.validationSchema).required()});return Qpe.validateBySchema(e,t)}a(Zpe,"configureClusterValidator")});var qP=M((ike,bW)=>{"use strict";var SW=(G(),D(j)),Ty=Q(),ehe=ae(),the=fe(),rhe=Sy(),nhe=_y(),she=fa(),ihe=gW(),{handleHDBError:TW,hdbErrors:ohe}=Ee(),{HTTP_STATUS_CODES:yW}=ohe,ahe="Configure cluster complete.",che="Failed to configure the cluster. Check the logs for more details.",lhe="Configure cluster was partially successful. Errors occurred when attempting to configure the following nodes. Check the logs for more details.";bW.exports=uhe;async function uhe(e){Ty.trace("configure cluster called with:",e);let t=ihe(e);if(t)throw TW(t,t.message,yW.BAD_REQUEST,void 0,void 0,!0);let r=await she.getAllNodeRecords(),n=[];if(the.get(SW.CONFIG_PARAMS.CLUSTERING_ENABLED)){for(let d=0,f=r.length;d<f;d++){let m=await RW(rhe,{operation:SW.OPERATIONS_ENUM.REMOVE_NODE,node_name:r[d].name},r[d].name);n.push(m)}Ty.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 RW(nhe,f,f.node_name);s.push(m)}Ty.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"&&(Ty.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(ehe.isEmptyOrZeroLength(o))return{message:ahe,connections:c};if(l)return{message:lhe,failed_nodes:o,connections:c};throw TW(new Error,che,yW.INTERNAL_SERVER_ERROR,void 0,void 0,!0)}a(uhe,"configureCluster");async function RW(e,t,r){try{return{node_name:r,result:await e(t)}}catch(n){return{node_name:r,error:n,status:"rejected"}}}a(RW,"functionWrapper")});var NW=M((ake,wW)=>{"use strict";var jh=require("joi"),dhe=mt(),{validateSchemaExists:AW,validateTableExists:fhe,validateSchemaName:IW}=Xi(),mhe=jh.object({operation:jh.string().valid("purge_stream"),schema:jh.string().custom(AW).custom(IW).optional(),database:jh.string().custom(AW).custom(IW).optional(),table:jh.string().custom(fhe).required()});function phe(e){return dhe.validateBySchema(e,mhe)}a(phe,"purgeStreamValidator");wW.exports=phe});var $P=M((lke,CW)=>{"use strict";var{handleHDBError:hhe,hdbErrors:Ehe}=Ee(),{HTTP_STATUS_CODES:_he}=Ehe,ghe=NW(),She=cr(),The=fa();CW.exports=yhe;async function yhe(e){e.schema=e.schema??e.database;let t=ghe(e);if(t)throw hhe(t,t.message,_he.BAD_REQUEST,void 0,void 0,!0);The.checkClusteringEnabled();let{schema:r,table:n,options:s}=e;return await She.purgeTableStream(r,n,s),`Successfully purged table '${r}.${n}'`}a(yhe,"purgeStream")});var YP=M((dke,xW)=>{"use strict";var KP=fa(),Rhe=cr(),Ry=fe(),bf=(G(),D(j)),su=vt(),bhe=ae(),VP=Q(),{RemotePayloadObject:Ahe}=kh(),{ErrorCode:OW}=require("nats"),{parentPort:PW}=require("worker_threads"),{onMessageByType:Ihe}=st(),{getThisNodeName:whe}=(gs(),D(aa)),{requestClusterStatus:Nhe}=(Nh(),D(A1)),{getReplicationSharedStatus:Che,getHDBNodeTable:Ohe}=(tf(),D(_1)),{CONFIRMATION_STATUS_POSITION:Phe,RECEIVED_VERSION_POSITION:LW,RECEIVED_TIME_POSITION:Lhe,SENDING_TIME_POSITION:Dhe,RECEIVING_STATUS_POSITION:vhe,RECEIVING_STATUS_RECEIVING:Mhe,BACK_PRESSURE_RATIO_POSITION:Uhe}=(BO(),D(pK)),DW=Ry.get(bf.CONFIG_PARAMS.CLUSTERING_ENABLED),vW=Ry.get(bf.CONFIG_PARAMS.CLUSTERING_NODENAME);xW.exports={clusterStatus:xhe,buildNodeStatus:UW};var MW;Ihe("cluster-status",async e=>{MW(e)});async function xhe(){if(Ry.get(bf.CONFIG_PARAMS.REPLICATION_URL)||Ry.get(bf.CONFIG_PARAMS.REPLICATION_HOSTNAME)){let n;PW?(PW.postMessage({type:"request-cluster-status"}),n=await new Promise(i=>{MW=i})):n=Nhe();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=Che(u,l,o);c.lastCommitConfirmed=yy(d[Phe]),c.lastReceivedRemoteTime=yy(d[LW]),c.lastReceivedLocalTime=yy(d[Lhe]),c.lastReceivedVersion=d[LW],c.sendingMessage=yy(d[Dhe]),c.backPressurePercent=d[Uhe]*100,c.lastReceivedStatus=d[vhe]===Mhe?"Receiving":"Waiting"}}n.node_name=whe();let s=Ohe().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:vW,is_enabled:DW,connections:[]};if(!DW)return e;let t=await KP.getAllNodeRecords();if(bhe.isEmptyOrZeroLength(t))return e;let r=[];for(let n=0,s=t.length;n<s;n++)r.push(UW(t[n],e.connections));return await Promise.allSettled(r),e}a(xhe,"clusterStatus");function yy(e){return e?e===1?"Copying":new Date(e).toUTCString():void 0}a(yy,"asDate");async function UW(e,t){let r=e.name,n=new Ahe(bf.OPERATIONS_ENUM.CLUSTER_STATUS,vW,void 0,await KP.getSystemInfo()),s,i,o=su.CLUSTER_STATUS_STATUSES.OPEN;try{let l=Date.now();s=await Rhe.request(su.REQUEST_SUBJECT(r),n),i=Date.now()-l,s.status===su.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR&&(o=su.CLUSTER_STATUS_STATUSES.CLOSED,VP.error(`Error getting node status from ${r} `,s))}catch(l){VP.warn(`Error getting node status from ${r}`,l),l.code===OW.NoResponders?o=su.CLUSTER_STATUS_STATUSES.NO_RESPONDERS:l.code===OW.Timeout?o=su.CLUSTER_STATUS_STATUSES.TIMEOUT:o=su.CLUSTER_STATUS_STATUSES.CLOSED}let c=new Bhe(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!==bf.PRE_4_0_0_VERSION&&await KP.upsertNodeRecord(l)}catch(l){VP.error("Cluster status encountered an error updating system info for node:",r,l)}t.push(c)}a(UW,"buildNodeStatus");function Bhe(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(Bhe,"NodeStatusObject")});var jP=M((mke,BW)=>{"use strict";var{handleHDBError:Fhe,hdbErrors:khe}=Ee(),{HTTP_STATUS_CODES:Hhe}=khe,Ghe=cr(),qhe=fa(),WP=ae(),by=require("joi"),$he=mt(),Vhe=2e3,Khe=by.object({timeout:by.number().min(1),connected_nodes:by.boolean(),routes:by.boolean()});BW.exports=Yhe;async function Yhe(e){qhe.checkClusteringEnabled();let t=$he.validateBySchema(e,Khe);if(t)throw Fhe(t,t.message,Hhe.BAD_REQUEST,void 0,void 0,!0);let{timeout:r,connected_nodes:n,routes:s}=e,i=n===void 0||WP.autoCastBoolean(n),o=s===void 0||WP.autoCastBoolean(s),c={nodes:[]},l=await Ghe.getServerList(r??Vhe),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:WP.autoCast(E.split(":")[1])})):[]),c.nodes.push(h)}}return c}a(Yhe,"clusterNetwork")});var GW=M((hke,HW)=>{"use strict";var zP=require("joi"),FW=mt(),{routeConstraints:kW}=_A();HW.exports={setRoutesValidator:Whe,deleteRoutesValidator:jhe};function Whe(e){let t=zP.object({server:zP.valid("hub","leaf"),routes:kW.required()});return FW.validateBySchema(e,t)}a(Whe,"setRoutesValidator");function jhe(e){let t=zP.object({routes:kW.required()});return FW.validateBySchema(e,t)}a(jhe,"deleteRoutesValidator")});var Ay=M((_ke,jW)=>{"use strict";var pa=_t(),JP=ae(),Ws=(G(),D(j)),Af=fe(),qW=GW(),{handleHDBError:$W,hdbErrors:zhe}=Ee(),{HTTP_STATUS_CODES:VW}=zhe,KW="cluster routes successfully set",YW="cluster routes successfully deleted";jW.exports={setRoutes:Qhe,getRoutes:Xhe,deleteRoutes:Zhe};function Jhe(e){let t=pa.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=JP.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"?pa.updateConfigValue(Ws.CONFIG_PARAMS.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_ROUTES,r):pa.updateConfigValue(Ws.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_ROUTES,r),{message:KW,set:i,skipped:s}}a(Jhe,"setRoutesNats");function Qhe(e){let t=qW.setRoutesValidator(e);if(t)throw $W(t,t.message,VW.BAD_REQUEST,void 0,void 0,!0);if(Af.get(Ws.CONFIG_PARAMS.CLUSTERING_ENABLED))return Jhe(e);let r=[],n=[],s=Af.get(Ws.CONFIG_PARAMS.REPLICATION_ROUTES)??[];return e.routes.forEach(i=>{WW(s,i)?n.push(i):(s.push(i),r.push(i))}),pa.updateConfigValue(Ws.CONFIG_PARAMS.REPLICATION_ROUTES,s),{message:KW,set:r,skipped:n}}a(Qhe,"setRoutes");function WW(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(WW,"existsInArray");function Xhe(){if(Af.get(Ws.CONFIG_PARAMS.CLUSTERING_ENABLED)){let e=pa.getClusteringRoutes();return{hub:e.hub_routes,leaf:e.leaf_routes}}else return Af.get(Ws.CONFIG_PARAMS.REPLICATION_ROUTES)??[]}a(Xhe,"getRoutes");function Zhe(e){let t=qW.deleteRoutesValidator(e);if(t)throw $W(t,t.message,VW.BAD_REQUEST,void 0,void 0,!0);if(Af.get(Ws.CONFIG_PARAMS.CLUSTERING_ENABLED))return eEe(e);let r=[],n=[],s=Af.get(Ws.CONFIG_PARAMS.REPLICATION_ROUTES)??[],i=[];return s.forEach(o=>{WW(e.routes,o)?r.push(o):(i.push(o),n.push(o))}),pa.updateConfigValue(Ws.CONFIG_PARAMS.REPLICATION_ROUTES,i),{message:YW,deleted:r,skipped:n}}a(Zhe,"deleteRoutes");function eEe(e){let t=pa.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=JP.isEmptyOrZeroLength(r)?null:r,pa.updateConfigValue(Ws.CONFIG_PARAMS.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_ROUTES,r)),c&&(n=JP.isEmptyOrZeroLength(n)?null:n,pa.updateConfigValue(Ws.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_ROUTES,n)),{message:YW,deleted:s,skipped:i}}a(eEe,"deleteRoutesNats")});var JW=M((Ske,zW)=>{"use strict";var tEe=vt(),QP=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+tEe.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"}};zW.exports=QP});var ZW=M((yke,XW)=>{"use strict";var QW=vt(),XP=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+QW.SERVER_SUFFIX.LEAF,this.pid_file=n,this.max_payload=67108864,this.jetstream={enabled:!0,store_dir:s,domain:r+QW.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"}};XW.exports=XP});var tj=M((bke,ej)=>{"use strict";var ZP=class{static{a(this,"HdbUserObject")}constructor(t,r){this.user=t,this.password=r}};ej.exports=ZP});var nj=M((Ike,rj)=>{"use strict";var rEe=vt(),eL=class{static{a(this,"SysUserObject")}constructor(t,r){this.user=t+rEe.SERVER_SUFFIX.ADMIN,this.password=r}};rj.exports=eL});var Cy=M((Nke,oj)=>{"use strict";var iu=require("path"),ou=require("fs-extra"),nEe=JW(),sEe=ZW(),iEe=tj(),oEe=nj(),tL=(Yn(),D(_i)),wf=ae(),jn=_t(),wy=(G(),D(j)),zh=vt(),{CONFIG_PARAMS:lr}=wy,Nf=Q(),Jh=fe(),sj=so(),rL=cr(),aEe=Ts(),If="clustering",cEe=1e4,ij=50;oj.exports={generateNatsConfig:uEe,removeNatsConfig:dEe,getHubConfigPath:lEe};function lEe(){let e=Jh.get(lr.ROOTPATH);return iu.join(e,If,zh.NATS_CONFIG_FILES.HUB_SERVER)}a(lEe,"getHubConfigPath");async function uEe(e=!1,t=void 0){console.error("Warning: NATS replication is deprecated and will be removed in version 5.0 of Harper");let r=Jh.get(lr.ROOTPATH);ou.ensureDirSync(iu.join(r,"clustering","leaf")),Jh.initSync();let n=jn.getConfigFromFile(lr.CLUSTERING_TLS_CERT_AUTH),s=jn.getConfigFromFile(lr.CLUSTERING_TLS_PRIVATEKEY),i=jn.getConfigFromFile(lr.CLUSTERING_TLS_CERTIFICATE);!await ou.exists(i)&&!await ou.exists(!n)&&await aEe.createNatsCerts();let o=iu.join(r,If,zh.PID_FILES.HUB),c=iu.join(r,If,zh.PID_FILES.LEAF),l=jn.getConfigFromFile(lr.CLUSTERING_LEAFSERVER_STREAMS_PATH),u=iu.join(r,If,zh.NATS_CONFIG_FILES.HUB_SERVER),d=iu.join(r,If,zh.NATS_CONFIG_FILES.LEAF_SERVER),f=jn.getConfigFromFile(lr.CLUSTERING_TLS_INSECURE),m=jn.getConfigFromFile(lr.CLUSTERING_TLS_VERIFY),p=jn.getConfigFromFile(lr.CLUSTERING_NODENAME),h=jn.getConfigFromFile(lr.CLUSTERING_HUBSERVER_LEAFNODES_NETWORK_PORT);await rL.checkNATSServerInstalled()||Ny("nats-server dependency is either missing or the wrong version. Run 'npm install' to fix");let E=await tL.listUsers(),_=jn.getConfigFromFile(lr.CLUSTERING_USER),R=await tL.getClusterUser();(wf.isEmpty(R)||R.active!==!0)&&Ny(`Invalid cluster user '${_}'. A valid user with the role 'cluster_user' must be defined under clustering.user in harperdb-config.yaml`),e||(await Iy(lr.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT),await Iy(lr.CLUSTERING_HUBSERVER_LEAFNODES_NETWORK_PORT),await Iy(lr.CLUSTERING_HUBSERVER_NETWORK_PORT),await Iy(lr.CLUSTERING_LEAFSERVER_NETWORK_PORT));let S=[],y=[];for(let[z,Y]of E.entries())Y.role?.role===wy.ROLE_TYPES_ENUM.CLUSTER_USER&&Y.active&&(S.push(new oEe(Y.username,sj.decrypt(Y.hash))),y.push(new iEe(Y.username,sj.decrypt(Y.hash))));let w=[],{hub_routes:I}=jn.getClusteringRoutes();if(!wf.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 nEe(jn.getConfigFromFile(lr.CLUSTERING_HUBSERVER_NETWORK_PORT),p,o,i,s,n,f,m,h,jn.getConfigFromFile(lr.CLUSTERING_HUBSERVER_CLUSTER_NAME),jn.getConfigFromFile(lr.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT),w,S,y);n==null&&(delete H.tls.ca_file,delete H.leafnodes.tls.ca_file),t=wf.isEmpty(t)?void 0:t.toLowerCase(),(t===void 0||t===wy.PROCESS_DESCRIPTORS.CLUSTERING_HUB.toLowerCase())&&(await ou.writeJson(u,H),Nf.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 sEe(jn.getConfigFromFile(lr.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===wy.PROCESS_DESCRIPTORS.CLUSTERING_LEAF.toLowerCase())&&(await ou.writeJson(d,k),Nf.trace(`Leaf server config written to ${d}`))}a(uEe,"generateNatsConfig");async function Iy(e){let t=Jh.get(e);return wf.isEmpty(t)&&Ny(`port undefined for '${e}'`),await wf.isPortTaken(t)&&Ny(`'${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(Iy,"isPortAvailable");function Ny(e){let t=`Error generating clustering config: ${e}`;Nf.error(t),console.error(t),process.exit(1)}a(Ny,"generateNatsConfigError");async function dEe(e){let{port:t,config_file:r}=rL.getServerConfig(e),{username:n,decrypt_hash:s}=await tL.getClusterUser(),i=0,o=2e3;for(;i<ij;){try{let d=await rL.createConnection(t,n,s,!1);if(d.protocol.connected===!0){d.close();break}}catch(d){Nf.trace(`removeNatsConfig waiting for ${e}. Caught and swallowed error ${d}`)}if(i++,i>=ij)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&&Nf.notify("Operations API waiting for Nats server connection. This could be caused by large Nats streams or incorrect clustering config."),await wf.asyncSetTimeout(u)}let c="0".repeat(cEe),l=iu.join(Jh.get(lr.ROOTPATH),If,r);await ou.writeFile(l,c),await ou.remove(l),Nf.notify(e,"started.")}a(dEe,"removeNatsConfig")});var fj=M((Oke,dj)=>{"use strict";var Rs=fe(),et=(G(),D(j)),Qh=vt(),ha=require("path"),{PACKAGE_ROOT:Py}=Rt(),aj=fe(),Oy=ae(),Cf="/dev/null",fEe=ha.join(Py,"launchServiceScripts"),cj=ha.join(Py,"utility/scripts"),mEe=ha.join(cj,et.HDB_RESTART_SCRIPT),lj=ha.resolve(Py,"dependencies",`${process.platform}-${process.arch}`,Qh.NATS_BINARY_NAME);function uj(){let e={[et.PROCESS_NAME_ENV_PROP]:et.PROCESS_DESCRIPTORS.HDB,IS_SCRIPTED_SERVICE:!0,...process.env};return Oy.noBootFile()&&(e[et.CONFIG_PARAMS.ROOTPATH.toUpperCase()]=Oy.getEnvCliRootPath()),{name:et.PROCESS_DESCRIPTORS.HDB,script:et.LAUNCH_SERVICE_SCRIPTS.MAIN,exec_mode:"fork",env:e,execArgv:process.execArgv,cwd:Py}}a(uj,"generateMainServerConfig");var pEe=9930;function hEe(){Rs.initSync(!0);let e=Rs.get(et.CONFIG_PARAMS.ROOTPATH),t=ha.join(e,"clustering",Qh.NATS_CONFIG_FILES.HUB_SERVER),r=ha.join(Rs.get(et.HDB_SETTINGS_NAMES.LOG_PATH_KEY),et.LOG_NAMES.HDB),n=aj.get(et.CONFIG_PARAMS.CLUSTERING_HUBSERVER_NETWORK_PORT),s=Qh.LOG_LEVEL_FLAGS[Rs.get(et.CONFIG_PARAMS.CLUSTERING_LOGLEVEL)]??void 0,i={name:et.PROCESS_DESCRIPTORS.CLUSTERING_HUB+(n!==pEe?"-"+n:""),binFile:lj,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=Cf,i.error_file=Cf),i}a(hEe,"generateNatsHubServerConfig");var EEe=9940;function _Ee(){Rs.initSync(!0);let e=Rs.get(et.CONFIG_PARAMS.ROOTPATH),t=ha.join(e,"clustering",Qh.NATS_CONFIG_FILES.LEAF_SERVER),r=ha.join(Rs.get(et.HDB_SETTINGS_NAMES.LOG_PATH_KEY),et.LOG_NAMES.HDB),n=aj.get(et.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_PORT),s=Qh.LOG_LEVEL_FLAGS[Rs.get(et.CONFIG_PARAMS.CLUSTERING_LOGLEVEL)]??void 0,i={name:et.PROCESS_DESCRIPTORS.CLUSTERING_LEAF+(n!==EEe?"-"+n:""),binFile:lj,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=Cf,i.error_file=Cf),i}a(_Ee,"generateNatsLeafServerConfig");function gEe(){Rs.initSync();let e=ha.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:fEe,autorestart:!1};return Rs.get(et.HDB_SETTINGS_NAMES.LOG_TO_FILE)||(t.out_file=Cf,t.error_file=Cf),t}a(gEe,"generateClusteringUpgradeV4ServiceConfig");function SEe(){let e={[et.PROCESS_NAME_ENV_PROP]:et.PROCESS_DESCRIPTORS.RESTART_HDB};return Oy.noBootFile()&&(e[et.CONFIG_PARAMS.ROOTPATH.toUpperCase()]=Oy.getEnvCliRootPath()),{...{name:et.PROCESS_DESCRIPTORS.RESTART_HDB,exec_mode:"fork",env:e,instances:1,autorestart:!1,cwd:cj},script:mEe}}a(SEe,"generateRestart");function TEe(){return{apps:[uj()]}}a(TEe,"generateAllServiceConfigs");dj.exports={generateAllServiceConfigs:TEe,generateMainServerConfig:uj,generateRestart:SEe,generateNatsHubServerConfig:hEe,generateNatsLeafServerConfig:_Ee,generateClusteringUpgradeV4ServiceConfig:gEe}});var Of=M((Dke,Sj)=>{"use strict";var Pr=(G(),D(j)),Lke=ae(),_a=Cy(),Ly=cr(),Ea=vt(),Cc=fj(),sL=fe(),Oc=Q(),yEe=fa(),{startWorker:mj,onMessageFromWorkers:REe}=st(),pj=require("fs"),bEe=require("node:path"),AEe=(G(),D(j)),{setTimeout:IEe}=require("node:timers/promises"),{execFile:wEe,fork:NEe}=require("node:child_process");Sj.exports={start:Pc,restart:OEe,kill:vEe,startAllServices:MEe,startService:Ej,restartHdb:PEe,startClusteringProcesses:_j,startClusteringThreads:gj,isHdbRestartRunning:LEe,getHdbPid:DEe,cleanupChildrenProcesses:Xh,reloadClustering:xEe,expectedRestartOfChildren:hj};REe(e=>{e.type==="restart"&&sL.initSync(!0)});var So=[],CEe=10,nL;function Pc(e,t=!1){let r=typeof e.args=="string"?e.args.split(" "):e.args;e.silent=!0,e.detached=!0;let n=e.script?NEe(e.script,r,e):wEe(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=So.indexOf(n);c>-1&&So.splice(c,1),!nL&&o!==0&&(e.restarts=(e.restarts||0)+1,e.restarts<CEe&&(pj.existsSync(_a.getHubConfigPath())?Pc(e):(await _a.generateNatsConfig(!0),Pc(e),await new Promise(l=>setTimeout(l,3e3)),await _a.removeNatsConfig(Pr.PROCESS_DESCRIPTORS.CLUSTERING_HUB),await _a.removeNatsConfig(Pr.PROCESS_DESCRIPTORS.CLUSTERING_LEAF))))});let s={serviceName:e.name.replace(/ /g,"-")};function i(o){let c=sL.get(Pr.CONFIG_PARAMS.CLUSTERING_LOGLEVEL),l=/\[\d+][^\[]+\[(\w+)]/g,u,d=0,f;for(;u=l.exec(o);){if(u.index&&Ea.LOG_LEVEL_HIERARCHY[c]>=Ea.LOG_LEVEL_HIERARCHY[f||"info"]){let h=f===Ea.LOG_LEVELS.ERR||f===Ea.LOG_LEVELS.WRN?Oc.OUTPUTS.STDERR:Oc.OUTPUTS.STDOUT;Oc.logCustomLevel(f||"info",h,s,o.slice(d,u.index).trim())}let[m,p]=u;d=u.index+m.length,f=Ea.LOG_LEVELS[p]}if(Ea.LOG_LEVEL_HIERARCHY[c]>=Ea.LOG_LEVEL_HIERARCHY[f||"info"]){let m=f===Ea.LOG_LEVELS.ERR||f===Ea.LOG_LEVELS.WRN?Oc.OUTPUTS.STDERR:Oc.OUTPUTS.STDOUT;Oc.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(),So.length===0&&(t||(process.on("exit",Xh),process.on("SIGINT",Xh),process.on("SIGQUIT",Xh),process.on("SIGTERM",Xh))),So.push(n)}a(Pc,"start");function Xh(e=!0){if(!nL&&(nL=!0,So.length!==0))if(Oc.info("Killing child processes..."),So.map(t=>t.kill()),e)process.exit(0);else return IEe(2e3)}a(Xh,"cleanupChildrenProcesses");function OEe(e){hj();for(let t of So)t.name===e&&t.kill()}a(OEe,"restart");function hj(){for(let e of So)e.config&&(e.config.restarts=0)}a(hj,"expectedRestartOfChildren");async function PEe(){await Pc(Cc.generateRestart())}a(PEe,"restartHdb");async function LEe(){let e=await list();for(let t in e)if(e[t].name===Pr.PROCESS_DESCRIPTORS.RESTART_HDB)return!0;return!1}a(LEe,"isHdbRestartRunning");function DEe(){let e=sL.getHdbBasePath();if(!e)return;let t=bEe.join(e,AEe.HDB_PID_FILE),r=BEe(t);if(!(!r||r===process.pid)&&FEe(r))return r}a(DEe,"getHdbPid");function vEe(){for(let e of So)e.kill();So=[]}a(vEe,"kill");async function MEe(){await _j(),await gj(),await Pc(Cc.generateAllServiceConfigs())}a(MEe,"startAllServices");async function Ej(e,t=!1){let r;switch(e=e.toLowerCase(),e){case Pr.PROCESS_DESCRIPTORS.HDB.toLowerCase():r=Cc.generateMainServerConfig();break;case Pr.PROCESS_DESCRIPTORS.CLUSTERING_INGEST_SERVICE.toLowerCase():r=Cc.generateNatsIngestServiceConfig();break;case Pr.PROCESS_DESCRIPTORS.CLUSTERING_REPLY_SERVICE.toLowerCase():r=Cc.generateNatsReplyServiceConfig();break;case Pr.PROCESS_DESCRIPTORS.CLUSTERING_HUB.toLowerCase():r=Cc.generateNatsHubServerConfig(),await Pc(r,t),await _a.removeNatsConfig(e);return;case Pr.PROCESS_DESCRIPTORS.CLUSTERING_LEAF.toLowerCase():r=Cc.generateNatsLeafServerConfig(),await Pc(r,t),await _a.removeNatsConfig(e);return;case Pr.PROCESS_DESCRIPTORS.CLUSTERING_UPGRADE_4_0_0.toLowerCase():r=Cc.generateClusteringUpgradeV4ServiceConfig();break;default:throw new Error(`Start service called with unknown service config: ${e}`)}Pc(r,t)}a(Ej,"startService");var UEe;async function _j(e=!1){for(let t in Pr.CLUSTERING_PROCESSES){let r=Pr.CLUSTERING_PROCESSES[t];await Ej(r,e)}}a(_j,"startClusteringProcesses");async function gj(){UEe=mj(Pr.LAUNCH_SERVICE_SCRIPTS.NATS_REPLY_SERVICE,{name:Pr.PROCESS_DESCRIPTORS.CLUSTERING_REPLY_SERVICE});try{await Ly.deleteLocalStream("__HARPERDB_WORK_QUEUE__")}catch{}await Ly.updateLocalStreams();let e=await yEe.getAllNodeRecords();for(let t=0,r=e.length;t<r;t++)if(e[t].system_info?.hdb_version===Pr.PRE_4_0_0_VERSION){Oc.info("Starting clustering upgrade 4.0.0 process"),mj(Pr.LAUNCH_SERVICE_SCRIPTS.NODES_UPGRADE_4_0_0,{name:"Upgrade-4-0-0"});break}}a(gj,"startClusteringThreads");async function xEe(){await _a.generateNatsConfig(!0),await Ly.reloadNATSHub(),await Ly.reloadNATSLeaf(),await _a.removeNatsConfig(Pr.PROCESS_DESCRIPTORS.CLUSTERING_HUB.toLowerCase()),await _a.removeNatsConfig(Pr.PROCESS_DESCRIPTORS.CLUSTERING_LEAF.toLowerCase())}a(xEe,"reloadClustering");function BEe(e){try{return Number.parseInt(pj.readFileSync(e,"utf8"),10)}catch{return null}}a(BEe,"readPidFile");function FEe(e){try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}}a(FEe,"isProcessRunning")});var aL={};ye(aL,{compactOnStart:()=>kEe,copyDb:()=>Ij});async function kEe(){ga.notify("Running compact on start"),console.log("Running compact on start");let e=(0,iL.get)(x.ROOTPATH),t=new Map,r=lt();(0,oL.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,Dy.join)(e,"backup",n+".mdb"),o=(0,Dy.join)(e,el,n+"-copy.mdb"),c=0;try{c=await Tj(n),console.log("Database",n,"before compact has a total record count of",c)}catch(l){ga.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 Ij(n,o),console.log("Backing up",n,"to",i);try{await(0,au.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,au.move)(o,s,{overwrite:!0}),await(0,au.remove)((0,Dy.join)(e,el,`${n}-copy.mdb-lock`))}try{Ud()}catch(n){ga.error("Error resetting databases after backup",n),console.error("Error resetting databases after backup",n)}try{Ud()}catch(n){ga.error("Error resetting databases after backup",n),console.error("Error resetting databases after backup",n),process.exit(0)}}catch(n){ga.error("Error compacting database, rolling back operation",n),console.error("Error compacting database, rolling back operation",n),(0,oL.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,au.move)(o,i,{overwrite:!0})}catch(c){console.error(c)}}throw Ud(),n}for(let[n,{backupDest:s,recordCount:i}]of t){let o=await Tj(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}`;ga.warn(c),console.warn(c)}(0,iL.get)(x.STORAGE_COMPACTONSTARTKEEPBACKUP)!==!0&&(console.log("Removing backup",s),await(0,au.remove)(s))}}async function Tj(e){let t=await(0,Aj.describeSchema)({database:e}),r=0;for(let n in t)r+=t[n].record_count;return r}function Pf(){}async function Ij(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,yj.open)(new Rj.default(t)),c=o.openDB(vy.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 bj.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(vy.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 yj,Dy,au,iL,Rj,bj,vy,Aj,oL,ga,cL=se(()=>{Oe();yj=require("lmdb"),Dy=require("path"),au=require("fs-extra"),iL=b(fe()),Rj=b(fp()),bj=b(dp()),vy=b(Jt());G();Vi();Aj=b(Kl()),oL=b(_t()),ga=b(Q());a(kEe,"compactOnStart");a(Tj,"getTotalDBRecordCount");a(Pf,"noop");a(Ij,"copyDb")});var uL=M((Fke,wj)=>{"use strict";var Zh=fe();Zh.initSync();var Lf=require("fs-extra"),lL=require("path"),Df=(G(),D(j)),HEe=require("crypto"),GEe=require("uuid").v4;wj.exports=qEe;function qEe(){if(Zh.getHdbBasePath()!==void 0){let e=lL.join(Zh.getHdbBasePath(),Df.LICENSE_KEY_DIR_NAME,Df.JWT_ENUM.JWT_PRIVATE_KEY_NAME),t=lL.join(Zh.getHdbBasePath(),Df.LICENSE_KEY_DIR_NAME,Df.JWT_ENUM.JWT_PUBLIC_KEY_NAME),r=lL.join(Zh.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=GEe(),i=HEe.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(qEe,"checkJWTTokenExist")});var Cj=M((Hke,Nj)=>{"use strict";var dL=class{static{a(this,"HdbInfoInsertObject")}constructor(t,r,n){this.info_id=t,this.data_version_num=r,this.hdb_version_num=n}};Nj.exports={HdbInfoInsertObject:dL}});var Lj=M((qke,Pj)=>{"use strict";var Oj=(G(),D(j)),fL=class{static{a(this,"UpgradeObject")}constructor(t,r){this[Oj.UPGRADE_JSON_FIELD_NAMES_ENUM.DATA_VERSION]=t,this[Oj.UPGRADE_JSON_FIELD_NAMES_ENUM.UPGRADE_VERSION]=r}};Pj.exports={UpgradeObject:fL}});var My=M((Vke,vj)=>{"use strict";var js=require("prompt"),vf=require("chalk"),Dj=Q(),Ii=require("os"),mL=tl(),pL=["yes","y"];async function $Ee(e){let t=`${Ii.EOL}`+vf.bold.green("Your current HarperDB version requires that we complete an update process.")+`${Ii.EOL}If a backup of your data has not been created, we recommend you cancel this process and backup before proceeding.${Ii.EOL}${Ii.EOL}You can read more about the changes in this upgrade at https://harperdb.io/developers/release-notes/${Ii.EOL}`;js.override=mL(["CONFIRM_UPGRADE"]),js.start(),js.message=t;let r={properties:{CONFIRM_UPGRADE:{description:vf.magenta(`${Ii.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 Dj.error("There was an error when prompting user about an upgrade."),Dj.error(s),!1}return pL.includes(n.CONFIRM_UPGRADE)}a($Ee,"forceUpdatePrompt");async function VEe(e){let t=`${Ii.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.${Ii.EOL}`);js.override=mL(["CONFIRM_DOWNGRADE"]),js.start(),js.message=t;let r={properties:{CONFIRM_DOWNGRADE:{description:vf.magenta(`${Ii.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 pL.includes(n.CONFIRM_DOWNGRADE)}a(VEe,"forceDowngradePrompt");async function KEe(){let e=`${Ii.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=mL(["GENERATE_CERTS"]),js.start(),js.message=e;let t={properties:{GENERATE_CERTS:{description:vf.magenta(`${Ii.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 pL.includes(r.GENERATE_CERTS)}a(KEe,"upgradeCertsPrompt");vj.exports={forceUpdatePrompt:$Ee,forceDowngradePrompt:VEe,upgradeCertsPrompt:KEe}});var Uy=M((Yke,Mj)=>{"use strict";var hL=class{static{a(this,"UpgradeDirective")}constructor(t){this.version=t,this.sync_functions=[],this.async_functions=[]}};Mj.exports=hL});var xj=M((Xke,Uj)=>{"use strict";var YEe=ae(),WEe=_t(),jke=Q(),zke=require("path"),Jke=require("fs"),Qke=(G(),D(j));Uj.exports={getOldPropsValue:jEe};function jEe(e,t,r=!1){let n=t.getRaw(e);return YEe.isNotEmptyAndHasValue(n)?n:r?WEe.getDefaultConfig(e):""}a(jEe,"getOldPropsValue")});var Hj=M((eHe,kj)=>{"use strict";var Lc=require("path"),Dc=require("fs-extra"),zEe=require("properties-reader"),JEe=Uy(),Tr=Q(),{getOldPropsValue:St}=xj(),{HDB_SETTINGS_NAMES:be,CONFIG_PARAMS:cu}=(G(),D(j)),lu=_t(),xy=fe(),Bj=ae(),To=(G(),D(j)),EL=new JEe("3.1.0"),Fj=[];function QEe(){let e=zEe(xy.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.
|