harperdb 4.6.24 → 4.6.25
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 +4 -4
- package/bin/lite.js +3 -3
- package/launchServiceScripts/launchNatsIngestService.js +4 -4
- package/launchServiceScripts/launchNatsReplyService.js +4 -4
- package/launchServiceScripts/launchUpdateNodes4-0-0.js +4 -4
- package/npm-shrinkwrap.json +363 -345
- package/package.json +1 -1
- package/server/jobs/jobProcess.js +24 -24
- package/server/threads/threadServer.js +2 -2
- package/studio/build-local/asset-manifest.json +2 -2
- package/studio/build-local/index.html +1 -1
- package/studio/build-local/static/js/{main.5e611ac2.js → main.0cabc3aa.js} +2 -2
- package/utility/scripts/restartHdb.js +23 -23
- /package/studio/build-local/static/js/{main.5e611ac2.js.LICENSE.txt → main.0cabc3aa.js.LICENSE.txt} +0 -0
package/bin/harperdb.js
CHANGED
|
@@ -31,7 +31,7 @@ Host ${s}
|
|
|
31
31
|
IdentitiesOnly yes`;await Ie.pathExists(l)?await Ie.appendFile(l,`
|
|
32
32
|
`+u):await Ie.outputFile(l,u);let d="";if(await Ie.pathExists(ca)||(await Ie.writeFile(ca,""),await Ie.chmod(ca,"0600")),i=="github.com"&&!(await Ie.readFile(ca,"utf8")).includes("github.com"))try{let E=(await(await fetch("https://api.github.com/meta")).json()).ssh_keys;for(let g of E)Ie.appendFile(ca,"github.com "+g+`
|
|
33
33
|
`)}catch{d=". Unable to get known hosts from github.com. Set your known hosts manually using set_ssh_known_hosts."}a&&await Ie.appendFile(ca,a);let f=await Li(e);return f.message=`Added ssh key: ${r}${d}`,f}o(B_e,"addSSHKey");async function F_e(e){let t=Vn.updateSSHKeyValidator(e);if(t)throw jt(t,t.message,Jt.BAD_REQUEST);let{name:r,key:n}=e;zt.trace("updating ssh key",r);let s=Oe.join(Ic,r+".key");if(!await Ie.pathExists(s))throw new Error("Key does not exist. Use add_ssh_key");await Ie.outputFile(s,n);let i=await Li(e);return i.message=`Updated ssh key: ${r}`,i}o(F_e,"updateSSHKey");async function H_e(e){let t=Vn.deleteSSHKeyValidator(e);if(t)throw jt(t,t.message,Jt.BAD_REQUEST);let{name:r}=e;zt.trace("deleting ssh key",r);let n=Oe.join(Ic,r+".key"),s=Oe.join(Ic,"config");if(!await Ie.pathExists(n))throw new Error("Key does not exist");let i=await Ie.readFile(s,"utf8"),a=new RegExp(`#${r}[\\S\\s]*?IdentitiesOnly yes`,"g");i=i.replace(a,""),await Ie.outputFile(s,i),Ie.removeSync(n);let c=await Li(e);return c.message=`Deleted ssh key: ${r}`,c}o(H_e,"deleteSSHKey");async function k_e(e){let t=[];return await Ie.pathExists(Ic)&&(await Ie.readdir(Ic)).forEach(r=>{r!="known_hosts"&&r!="config"&&t.push({name:r.split(".")[0]})}),t}o(k_e,"listSSHKeys");async function q_e(e){let t=Vn.setSSHKnownHostsValidator(e);if(t)throw jt(t,t.message,Jt.BAD_REQUEST);let{known_hosts:r}=e;await Ie.outputFile(ca,r);let n=await Li(e);return n.message="Known hosts successfully set",n}o(q_e,"setSSHKnownHosts");async function G_e(e){return await Ie.pathExists(ca)?{known_hosts:await Ie.readFile(ca,"utf8")}:{known_hosts:null}}o(G_e,"getSSHKnownHosts");ar.customFunctionsStatus=A_e;ar.getCustomFunctions=b_e;ar.getCustomFunction=I_e;ar.setCustomFunction=N_e;ar.dropCustomFunction=w_e;ar.addComponent=O_e;ar.dropCustomFunctionProject=C_e;ar.packageComponent=P_e;ar.deployComponent=D_e;ar.getComponents=M_e;ar.getComponentFile=v_e;ar.setComponentFile=U_e;ar.dropComponent=x_e;ar.addSSHKey=B_e;ar.updateSSHKey=F_e;ar.deleteSSHKey=H_e;ar.listSSHKeys=k_e;ar.setSSHKnownHosts=q_e;ar.getSSHKnownHosts=G_e});var zC=M((qBe,wY)=>{"use strict";var Vs=require("joi"),NY=lt();wY.exports={readTransactionLogValidator:$_e,deleteTransactionLogsBeforeValidator:V_e};function $_e(e){let t=Vs.object({schema:Vs.string(),database:Vs.string(),table:Vs.string().required(),from:Vs.date().timestamp(),to:Vs.date().timestamp(),limit:Vs.number().min(1)});return NY.validateBySchema(e,t)}o($_e,"readTransactionLogValidator");function V_e(e){let t=Vs.object({schema:Vs.string(),database:Vs.string(),table:Vs.string().required(),timestamp:Vs.date().timestamp().required()});return NY.validateBySchema(e,t)}o(V_e,"deleteTransactionLogsBeforeValidator")});var YT=M(($Be,MY)=>{"use strict";var jC=(H(),v(W)),Bp=sr(),OY=se(),CY=oe(),PY=Zi(),DY=j(),{handleHDBError:VT,hdbErrors:K_e}=ge(),{HTTP_STATUS_CODES:KT}=K_e,{readTransactionLogValidator:Y_e,deleteTransactionLogsBeforeValidator:W_e}=zC(),LY=is(),z_e="Logs successfully deleted from transaction log.",j_e="All logs successfully deleted from transaction log.";MY.exports={readTransactionLog:J_e,deleteTransactionLogsBefore:X_e};async function J_e(e){let t=Y_e(e);if(t)throw VT(t,t.message,KT.BAD_REQUEST,void 0,void 0,!0);e.database=e.database??e.schema??"data";let r=OY.checkSchemaTableExist(e.database,e.table);if(r)throw VT(new Error,r,KT.NOT_FOUND,void 0,void 0,!0);return CY.get(jC.CONFIG_PARAMS.CLUSTERING_ENABLED)?await Q_e(e):(DY.info("Reading HarperDB logs used by Plexus"),(e.from||e.to)&&(e.search_type="timestamp",e.search_values=[e.from??0],e.to&&(e.search_values[1]=e.to)),LY.readAuditLog(e))}o(J_e,"readTransactionLog");async function*Q_e(e){let t=PY.createNatsTableStreamName(e.database,e.table),r=await Bp.viewStreamIterator(t,parseInt(e.from),e.limit);for await(let n of r){let s=Math.floor(n?.nats_timestamp/1e6);if(e.to&&s>e.to)break;let i={operation:n?.entry?.operation,user:n?.entry?.__origin?.user,timestamp:s,records:n?.entry?.records,attributes:n?.entry?.attributes};n?.entry?.operation===jC.OPERATIONS_ENUM.DELETE&&(i.hash_values=n?.entry?.hash_values),yield i}}o(Q_e,"readTransactionLogNats");async function X_e(e){let t=W_e(e);if(t)throw VT(t,t.message,KT.BAD_REQUEST,void 0,void 0,!0);if(e.database=e.database??e.schema??"data",!CY.get(jC.CONFIG_PARAMS.CLUSTERING_ENABLED))return DY.info("Delete transaction logs called for Plexus"),LY.deleteAuditLogsBefore(e);let{database:r,table:n,timestamp:s}=e,i=OY.checkSchemaTableExist(r,n);if(i)throw VT(new Error,i,KT.NOT_FOUND,void 0,void 0,!0);let a=PY.createNatsTableStreamName(r,n),{jsm:c}=await Bp.getNATSReferences(),l=await Bp.getStreamInfo(a),u=new Date(l.state.first_ts).getTime();if(s<=u)return`No transactions exist before: ${s}`;let d=z_e,f,m=new Date(l.state.last_ts).getTime();return s>m?(f=l.state.last_seq+1,d=j_e):f=(await Bp.viewStream(a,parseInt(s),1))[0].nats_sequence,await Bp.purgeTableStream(r,n,{seq:f}),d}o(X_e,"deleteTransactionLogsBefore")});var ZC={};we(ZC,{describeMetric:()=>HY,describeMetricOp:()=>XC,get:()=>BY,getOp:()=>JC,listMetrics:()=>FY,listMetricsOp:()=>QC});async function eEe(e){return(await qg().get(e)).hostname}function vY(e,t){return e.length===0||e.includes(t)}function JC(e){return Fp.trace?.("get_analytics request:",e),BY(e.metric,e.get_attributes,e.start_time,e.end_time,e.conditions)}function xY(e){return"conditions"in e?{...e,conditions:e.conditions.map(xY)}:{attribute:e.search_attribute??e.attribute,comparator:e.search_type??e.comparator,value:e.search_value??e.value}}async function BY(e,t,r,n,s){let i=[{attribute:"metric",comparator:"equals",value:e}];s&&i.push(...s.map(xY));let a=t??[];vY(a,"id")||a.push("id"),r&&i.push({attribute:"id",comparator:"greater_than_equal",value:r}),n&&i.push({attribute:"id",comparator:"less_than",value:n});let c={conditions:i,allowConditionsOnDynamicAttributes:!0};return a.length>0&&(c.select=a),Fp.trace?.("get_analytics hdb_analytics.search request:",JSON.stringify(c)),(await databases.system.hdb_analytics.search(c)).map(async u=>{let d=u.id[1];return u.id=u.id[0],vY(a,"node")&&(Fp.trace?.(`get_analytics lookup hostname for nodeId: ${d}`),u.node=await eEe(d)),Fp.trace?.("get_analytics result:",JSON.stringify(u)),u})}function QC(e){return FY(e.metric_types,e.custom_metrics_window)}async function FY(e=["builtin"],t=Z_e){let r=[],n=Object.values(Wo);if(e.includes("builtin")&&(r=n),e.includes("custom")){let i=[{attribute:"id",comparator:"greater_than",value:Date.now()-t}],a=n.map(d=>({attribute:"metric",comparator:"not_equal",value:d}));i.push(...a);let c={select:["metric"],conditions:i},l=new Set,u=await databases.system.hdb_analytics.search(c);for await(let d of u)l.add(d.metric);r.push(...Array.from(l.values()))}return r}function XC(e){return HY(e.metric)}async function HY(e){let t={conditions:[{attribute:"metric",comparator:"equals",value:e}],sort:{attribute:"id",descending:!0},limit:1},r=databases.system.hdb_analytics.search(t),n=[{name:"node",type:"string"}];for await(let s of r){for(let a in s)n.push({name:a,type:typeof s[a]});let i={attributes:n};return Fp.trace?.("describe_metric result:",JSON.stringify(i)),i}return{}}var UY,Z_e,Fp,eP=ce(()=>{UY=w(j());JN();QN();Z_e=1e3*60*60*24*7,Fp=(0,UY.forComponent)("analytics").conditional;o(eEe,"lookupHostname");o(vY,"isSelected");o(JC,"getOp");o(xY,"conformCondition");o(BY,"get");o(QC,"listMetricsOp");o(FY,"listMetrics");o(XC,"describeMetricOp");o(HY,"describeMetric")});var WT,zT,Hp,jT=ce(()=>{WT={primary:{allowedValues:null},maintenance:{allowedValues:null},availability:{allowedValues:["Available","Unavailable"]}},zT=Object.keys(WT),Hp="primary"});function qY(e){return kY.validateBySchema(e,sEe)}var kp,kY,tEe,rEe,nEe,sEe,GY=ce(()=>{kp=w(require("joi")),kY=w(lt());jT();tEe=zT,rEe=Object.entries(WT).reduce((e,[t,r])=>(r.allowedValues&&(e[t]=`Status "${t}" only accepts these values: ${r.allowedValues.join(", ")}`),e),{}),nEe=o(()=>{let e=kp.default.string().min(1).max(512);return Object.entries(WT).forEach(([t,r])=>{r.allowedValues&&(e=e.when("id",{is:t,then:kp.default.string().valid(...r.allowedValues).messages({"any.only":rEe[t]})}))}),e.required()},"createStatusValidationSchema"),sEe=kp.default.object({id:kp.default.string().valid(...tEe).required(),status:nEe()});o(qY,"validateStatus")});var QT={};we(QT,{DEFAULT_STATUS_ID:()=>Hp,STATUS_IDS:()=>zT,Status:()=>la,clear:()=>rP,get:()=>nP,set:()=>sP});function Gp(){return tP||(tP=ze({database:"system",table:"hdb_status",replicate:!1,attributes:[{name:"id",isPrimaryKey:!0},{name:"status"},{name:"__createdtime__"},{name:"__updatedtime__"}]})),tP}function rP({id:e}){return qp.debug?.("clearStatus",e),Gp().delete(e)}function oEe(){return qp.debug?.("getAllStatus"),Gp().get({})}function nP({id:e}){return e?(qp.debug?.("getStatus",e),Gp().get(e)):(qp.debug?.("getStatus","all"),oEe())}function sP({status:e,id:t=Hp}){let r=qY({status:e,id:t});if(r)throw(0,JT.handleHDBError)(r,r.message,iEe.BAD_REQUEST);return qp.debug?.("setStatus",t,e),Gp().put(t,{status:e})}var JT,$Y,iEe,tP,la,qp,Sf=ce(()=>{Pe();JT=w(ge()),$Y=w(hi());GY();jT();jT();({HTTP_STATUS_CODES:iEe}=JT.hdbErrors);o(Gp,"getStatusTable");la={get primaryStore(){return Gp().primaryStore}},qp=(0,$Y.loggerWithTag)("status");o(rP,"clearStatus");o(oEe,"getAllStatus");o(nP,"getStatus");o(sP,"setStatus")});var KY=M((aFe,VY)=>{"use strict";var iP=class{static{o(this,"PermissionTableResponseObject")}constructor(t,r,n=[],s=[]){this.schema=t,this.table=r,this.required_table_permissions=n,this.required_attribute_permissions=s}};VY.exports=iP});var WY=M((lFe,YY)=>{"use strict";var oP=class{static{o(this,"PermissionAttributeResponseObject")}constructor(t,r=[]){this.attribute_name=t,this.required_permissions=r}};YY.exports=oP});var cP=M((dFe,jY)=>{"use strict";var zY=KY(),aEe=WY(),{HDB_ERROR_MSGS:cEe}=Vr(),aP=class{static{o(this,"PermissionResponseObject")}constructor(){this.error=cEe.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 zY(t,r,n),i=`${t}_${r}`;this.unauthorized_access[i]=s}addUnauthorizedAttributes(t,r,n,s){let i=[];t.forEach(c=>{let l=new aEe(c,s[c]);i.push(l)});let a=`${r}_${n}`;if(this.unauthorized_access[a])this.unauthorized_access[a].required_attribute_permissions=i;else{let c=new zY(r,n,[],i);this.unauthorized_access[a]=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}};jY.exports=aP});var tR=M((mFe,fW)=>{"use strict";var lP=Bn(),XT=an(),Ks=op(),Kp=za(),uP=Rl(),lEe=EO(),uEe=tV(),Yp=xn(),ZT=Oh(),Nr=j(),dEe=yO(),fEe=Zd(),mEe=jO(),hEe=aT(),pEe=XO(),_Ee=ZO(),EEe=dT(),gEe=mT(),dP=hT(),ua=se(),SEe=M1(),fP=ST(),XY=yc(),Rn=(H(),v(W)),ZY=WK(),TEe=Zo(),eW=(wd(),v(Hh)),tW=(FT(),v(Cp)),rW=gt(),gr=KC(),REe=require("alasql"),nW=YT(),sW=Mp(),Tf=pn(),iW=(Xd(),v(Qd)),mP=(eP(),v(ZC)),hP=(Sf(),v(QT)),oW=cP(),{handleHDBError:Kn,hdbErrors:aW}=ge(),{HDB_ERROR_MSGS:Zr,HTTP_STATUS_CODES:$p}=aW,{cleanupOrphanBlobs:yEe}=op(),X=new Map,cW="delete",Nc="insert",Ys="read",uu="update",Vp="describe",JY=Kp.describeSchema.name,QY=Kp.describeTable.name,lW={delete:!0,deleteRecord:!0,update:!0,updateData:!0,dropAttribute:!0,dropTable:!0,dropSchema:!0,upsert:!0,upsertData:!0},AEe={insert:!0,delete:!0,deleteRecord:!0,update:!0,updateData:!0,upsert:!0,upsertData:!0},bEe="catchup",IEe="handleGetJob",NEe="handleGetJobsByStartDate",eR={CSV_DATA_LOAD:"csvDataLoad",CSV_URL_LOAD:"csvURLLoad",CSV_FILE_LOAD:"csvFileLoad",IMPORT_FROM_S3:"importFromS3"},wEe=[Ks.createTable.name,Ks.createAttribute.name,Ks.dropTable.name,Ks.dropAttribute.name],uW={EXPORT_TO_S3:"export_to_s3",EXPORT_LOCAL:"export_local"},te=class{static{o(this,"permission")}constructor(t,r){this.requires_su=t,this.perms=r}};X.set(lP.insert.name,new te(!1,[Nc]));X.set(lP.update.name,new te(!1,[uu]));X.set(lP.upsert.name,new te(!1,[Nc,uu]));X.set(XT.searchByConditions.name,new te(!1,[Ys]));X.set(XT.searchByHash.name,new te(!1,[Ys]));X.set(XT.searchByValue.name,new te(!1,[Ys]));X.set(XT.search.name,new te(!1,[Ys]));X.set(Ks.createSchema.name,new te(!0,[]));X.set(Ks.createTable.name,new te(!0,[]));X.set(Ks.createAttribute.name,new te(!1,[Nc]));X.set(Ks.dropSchema.name,new te(!0,[]));X.set(Ks.dropTable.name,new te(!0,[]));X.set(Ks.dropAttribute.name,new te(!0,[]));X.set(Kp.describeSchema.name,new te(!1,[Ys]));X.set(Kp.describeTable.name,new te(!1,[Ys]));X.set(uP.deleteRecord.name,new te(!1,[cW]));X.set(Yp.addUser.name,new te(!0,[]));X.set(Yp.alterUser.name,new te(!0,[]));X.set(Yp.dropUser.name,new te(!0,[]));X.set(Yp.listUsersExternal.name,new te(!0,[]));X.set(ZT.listRoles.name,new te(!0,[]));X.set(ZT.addRole.name,new te(!0,[]));X.set(ZT.alterRole.name,new te(!0,[]));X.set(ZT.dropRole.name,new te(!0,[]));X.set(dEe.name,new te(!0,[]));X.set(fEe.name,new te(!0,[]));X.set(mEe.name,new te(!0,[]));X.set(hEe.name,new te(!0,[]));X.set(pEe.name,new te(!0,[]));X.set(_Ee.name,new te(!0,[]));X.set(dP.setRoutes.name,new te(!0,[]));X.set(dP.getRoutes.name,new te(!0,[]));X.set(dP.deleteRoutes.name,new te(!0,[]));X.set(rW.setConfiguration.name,new te(!0,[]));X.set(EEe.clusterStatus.name,new te(!0,[]));X.set(gEe.name,new te(!0,[]));X.set(fP.getFingerprint.name,new te(!0,[]));X.set(fP.setLicense.name,new te(!0,[]));X.set(uP.deleteFilesBefore.name,new te(!0,[]));X.set(uP.deleteAuditLogsBefore.name,new te(!0,[]));X.set(XY.restart.name,new te(!0,[]));X.set(XY.restartService.name,new te(!0,[]));X.set(lEe.name,new te(!0,[]));X.set(uEe.name,new te(!0,[Ys]));X.set(yEe.name,new te(!0,[]));X.set(TEe.systemInformation.name,new te(!0,[]));X.set(rW.getConfiguration.name,new te(!0,[]));X.set(nW.readTransactionLog.name,new te(!0,[]));X.set(nW.deleteTransactionLogsBefore.name,new te(!0,[]));X.set(sW.installModules.name,new te(!0,[]));X.set(sW.auditModules.name,new te(!0,[]));X.set(Tf.createCsr.name,new te(!0,[]));X.set(Tf.signCertificate.name,new te(!0,[]));X.set(Tf.listCertificates.name,new te(!0,[]));X.set(Tf.addCertificate.name,new te(!0,[]));X.set(Tf.removeCertificate.name,new te(!0,[]));X.set(Tf.getKey.name,new te(!0,[]));X.set(iW.addNodeBack.name,new te(!0,[]));X.set(iW.removeNodeBack.name,new te(!0,[]));X.set(mP.getOp.name,new te(!1,[Ys]));X.set(mP.listMetricsOp.name,new te(!1,[Ys]));X.set(mP.describeMetricOp.name,new te(!1,[Ys]));X.set(hP.clear.name,new te(!0,[]));X.set(hP.get.name,new te(!0,[]));X.set(hP.set.name,new te(!0,[]));X.set(eW.createTokens.name,new te(!1,[]));X.set(eW.refreshOperationToken.name,new te(!1,[]));X.set(tW.login.name,new te(!1,[]));X.set(tW.logout.name,new te(!1,[]));X.set(gr.customFunctionsStatus.name,new te(!0,[]));X.set(gr.getCustomFunctions.name,new te(!0,[]));X.set(gr.getComponents.name,new te(!0,[]));X.set(gr.getComponentFile.name,new te(!0,[]));X.set(gr.setComponentFile.name,new te(!0,[]));X.set(gr.dropComponent.name,new te(!0,[]));X.set(gr.getCustomFunction.name,new te(!0,[]));X.set(gr.setCustomFunction.name,new te(!0,[]));X.set(gr.dropCustomFunction.name,new te(!0,[]));X.set(gr.addComponent.name,new te(!0,[]));X.set(gr.dropCustomFunctionProject.name,new te(!0,[]));X.set(gr.packageComponent.name,new te(!0,[]));X.set(gr.deployComponent.name,new te(!0,[]));X.set(gr.addSSHKey.name,new te(!0,[]));X.set(gr.updateSSHKey.name,new te(!0,[]));X.set(gr.deleteSSHKey.name,new te(!0,[]));X.set(gr.listSSHKeys.name,new te(!0,[]));X.set(gr.setSSHKnownHosts.name,new te(!0,[]));X.set(gr.getSSHKnownHosts.name,new te(!0,[]));X.set(fP.getRegistrationInfo.name,new te(!1,[]));X.set(Yp.userInfo.name,new te(!1,[]));X.set(Kp.describeAll.name,new te(!1,[]));X.set(IEe,new te(!1,[]));X.set(NEe,new te(!0,[]));X.set(bEe,new te(!0,[]));X.set(eR.CSV_DATA_LOAD,new te(!1,[Nc,uu]));X.set(eR.CSV_URL_LOAD,new te(!1,[Nc,uu]));X.set(eR.CSV_FILE_LOAD,new te(!1,[Nc,uu]));X.set(eR.IMPORT_FROM_S3,new te(!1,[Nc,uu]));X.set(uW.EXPORT_TO_S3,new te(!0,[]));X.set(uW.EXPORT_LOCAL,new te(!0,[]));X.set(Rn.VALID_SQL_OPS_ENUM.DELETE,new te(!1,[cW]));X.set(Rn.VALID_SQL_OPS_ENUM.SELECT,new te(!1,[Ys]));X.set(Rn.VALID_SQL_OPS_ENUM.INSERT,new te(!1,[Nc]));X.set(Rn.VALID_SQL_OPS_ENUM.UPDATE,new te(!1,[uu]));fW.exports={verifyPerms:CEe,verifyPermsAst:OEe,verifyBulkLoadAttributePerms:DEe};function OEe(e,t,r){if(ua.isEmptyOrZeroLength(e))throw Nr.info("verify_perms_ast has an empty user parameter"),Kn(new Error);if(ua.isEmptyOrZeroLength(t))throw Nr.info("verify_perms_ast has an empty user parameter"),Kn(new Error);if(ua.isEmptyOrZeroLength(r))throw Nr.info("verify_perms_ast has a null operation parameter"),Kn(new Error);try{let n=new oW,s=new SEe(e),i=s.getSchemas(),a=new Map;if((!i||i.length===0)&&s.affected_attributes&&s.affected_attributes.size>0)throw Nr.info("No schemas defined in verifyPermsAst(), will not continue."),Kn(new Error);let c=!!t.role.permission.super_user,l=i.includes("system");if(l&&lW[r])throw Kn(new Error,Zr.DROP_SYSTEM,$p.FORBIDDEN);if(c&&!l)return null;let u=ZY.getRolePermissions(t.role);t.role.permission=u,!c&&e instanceof REe.yy.Select&&(e=s.updateAttributeWildcardsForRolePerms(u));for(let f=0;f<i.length;f++){let m=s.getTablesBySchemaName(i[f]);m&&a.set(i[f],m)}let d=dW(t,r,a,n);return d||(a.forEach((f,m)=>{for(let h=0;h<f.length;h++){let p=s.getAttributesBySchemaTableName(m,f[h]),E=_P(t.role.permission,m,f[h]);pP(p,E,r,f[h],m,n)}}),n.getPermsResponse())}catch(n){throw Kn(n)}}o(OEe,"verifyPermsAst");function CEe(e,t){if(e===null||t===null||e.hdb_user===void 0||e.hdb_user===null)throw Nr.info("null required parameter in verifyPerms"),Kn(new Error,Zr.DEFAULT_INVALID_REQUEST,$p.BAD_REQUEST);let r;t instanceof Function?r=t.name:r=t;let n=e.action,s=e.schema??e.database,i=e.table,a=new Map;s&&i&&a.set(s,[i]);let c=new oW;if(ua.isEmptyOrZeroLength(e.hdb_user?.role)||ua.isEmptyOrZeroLength(e.hdb_user?.role?.permission))return Nr.info(`User ${e.hdb_user?.username} has no role or permissions. Please assign the user a valid role.`),c.handleUnauthorizedItem(Zr.USER_HAS_NO_PERMS(e.hdb_user?.username));let l=!!e.hdb_user?.role?.permission?.super_user,u=e.hdb_user?.role?.permission?.structure_user,d=a.has(Rn.SYSTEM_SCHEMA_NAME)||s===Rn.SYSTEM_SCHEMA_NAME;if(l&&d&&AEe[e.operation]&&(i===Rn.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME||i===Rn.SYSTEM_TABLE_NAMES.ROLE_TABLE_NAME||i===Rn.SYSTEM_TABLE_NAMES.USER_TABLE_NAME))return null;if(d&&lW[r])throw Kn(new Error,Zr.DROP_SYSTEM,$p.FORBIDDEN);if(l&&!d||u===!0&&(r===Ks.createSchema.name||r===Ks.dropSchema.name))return null;if(wEe.indexOf(r)>=0&&(u===!0||Array.isArray(u)))return u===!0||u.indexOf(s)>=0?null:c.handleUnauthorizedItem(`User does not have access to perform '${e.operation}' against schema '${s}'`);let f=ZY.getRolePermissions(e.hdb_user?.role);if(e.hdb_user?.role&&(e.hdb_user.role.permission=f),(r===JY||r===QY)&&!f.super_user){if(s===Rn.SYSTEM_SCHEMA_NAME)return c.handleUnauthorizedItem(Zr.SCHEMA_PERM_ERROR(s));if(r===JY&&(!f[s]||!f[s][Vp]))return c.handleInvalidItem(Zr.SCHEMA_NOT_FOUND(s));if(r===QY&&(!f[s]||!f[s].tables[i]||!f[s].tables[i][Vp]))return c.handleInvalidItem(Zr.TABLE_NOT_FOUND(s,i))}let m=dW(e.hdb_user,r,a,c,n);if(m)return m;if(X.get(r)&&X.get(r).perms.length===0)return null;if(!l&&e.get_attributes&&Rn.SEARCH_WILDCARDS.includes(e.get_attributes[0])){let E=[],g=f[s].tables[i];g[Rn.PERMS_CRUD_ENUM.READ]&&(g.attribute_permissions.length>0?g.attribute_permissions.filter(T=>T[Rn.PERMS_CRUD_ENUM.READ]).forEach(T=>{E.push(T.attribute_name)}):E=global.hdb_schema[s][i].attributes.map(R=>R.attribute),e.get_attributes=E)}let h=PEe(e),p=_P(e.hdb_user?.role?.permission,s,i);return pP(h,p,r,i,s,c,n),c.getPermsResponse()}o(CEe,"verifyPerms");function dW(e,t,r,n,s){if(ua.arrayHasEmptyValues([e,t,r]))throw Nr.info("hasPermissions has an invalid parameter"),Kn(new Error);let i=r.has("system"),a=e.role.permission;if(a.super_user&&(!i||X.get(t).requires_su))return null;if(!X.get(t))throw Nr.info(`operation ${t} not found.`),Kn(new Error,Zr.OP_NOT_FOUND(t),$p.BAD_REQUEST);if(X.get(t)&&X.get(t).requires_su)return Nr.info(`operation ${t} requires SU permissions.`),n.handleUnauthorizedItem(Zr.OP_IS_SU_ONLY(t));let c=r.keys();for(let l of c){try{if(l&&!a[l]||a[l][Vp]===!1){n.addInvalidItem(Zr.SCHEMA_NOT_FOUND(l));continue}}catch{n.addInvalidItem(Zr.SCHEMA_NOT_FOUND(l));continue}let u=r.get(l);for(let d of u){let f=a[l].tables[d];if(!f||f[Vp]===!1)n.addInvalidItem(Zr.TABLE_NOT_FOUND(l,d));else try{let m=[],h=X.get(t).perms;!ua.isEmpty(s)&&h.includes(s)&&(h=[s]);for(let p=0;p<h.length;p++){let E=h[p],g=f[E];(g==null||g===!1)&&(Nr.info(`Required ${E} permission not found for ${t} ${s?`${s} `:""}operation in role ${e.role.id}`),m.push(E))}m.length>0&&n.addUnauthorizedTable(l,d,m)}catch(m){let h=Zr.UNKNOWN_OP_AUTH_ERROR(t,l,d);throw Nr.error(h),Nr.error(m),Kn(aW.CHECK_LOGS_WRAPPER(h))}}}return r.size<2?n.getPermsResponse():null}o(dW,"hasPermissions");function pP(e,t,r,n,s,i,a){if(!e||!t)throw Nr.info("no attributes specified in checkAttributePerms."),Kn(new Error);let c=X.get(r).perms;if(!c||c==="")throw Nr.info(`no permissions found for ${r} in checkAttributePerms().`),Kn(new Error);if(ua.isEmptyOrZeroLength(t))return Nr.info("No role permissions set (this is OK)."),null;a&&c.includes(a)&&(c=[a]);let l={};for(let d of e){let f=t.get(d);if(f){if(f[Vp]===!1){i.addInvalidItem(Zr.ATTR_NOT_FOUND(s,n,d),s,n);continue}if(c)for(let m of c){if(Rn.TIME_STAMP_NAMES.includes(f.attribute_name)&&m!==Ys)throw Kn(new Error,Zr.SYSTEM_TIMESTAMP_PERMS_ERR,$p.FORBIDDEN);f[m]===!1&&(l[f.attribute_name]?l[f.attribute_name].push(m):l[f.attribute_name]=[m])}}else i.addInvalidItem(Zr.ATTR_NOT_FOUND(s,n,d),s,n)}let u=Object.keys(l);u.length>0&&i.addUnauthorizedAttributes(u,s,n,l)}o(pP,"checkAttributePerms");function PEe(e){let t=new Set;try{if(e.action)return t;if(e.operation===Rn.OPERATIONS_ENUM.SEARCH_BY_CONDITIONS&&e.conditions.forEach(r=>{t.add(r.search_attribute)}),e&&e.search_attribute&&t.add(e.search_attribute),!e.records||e.records.length===0){if(!e.get_attributes||!e.get_attributes.length===0)return t;for(let r=0;r<e.get_attributes.length;r++)t.add(e.get_attributes[r])}else for(let r=0;r<e.records.length;r++){let n=Object.keys(e.records[r]);for(let s=0;s<n.length;s++)t.add(n[s])}}catch(r){Nr.info(r)}return t}o(PEe,"getRecordAttributes");function _P(e,t,r){let n=new Map;if(ua.isEmpty(e))return Nr.info("no hdb_user specified in getAttributePermissions"),n;if(e.super_user||!t||!r)return n;try{e[t].tables[r].attribute_permissions.forEach(s=>{n.has(s.attribute_name)||n.set(s.attribute_name,s)})}catch{Nr.info(`No attribute permissions found for schema ${t} and table ${r}.`)}return n}o(_P,"getAttributePermissions");function DEe(e,t,r,n,s,i,a){let c=new Set(i),l=_P(e,n,s);pP(c,l,t,s,n,a,r)}o(DEe,"verifyBulkLoadAttributePerms")});var nR=M((pFe,EW)=>{"use strict";EW.exports={evaluateSQL:VEe,processAST:_W,convertSQLToAST:pW,checkASTPermissions:hW};var LEe=Bn(),mW=require("util"),MEe=mW.callbackify(LEe.insert),vEe=an().search,UEe=qq().update,xEe=mW.callbackify(UEe),BEe=$q().convertDelete,wc=require("alasql"),FEe=tR(),rR=j(),HEe=eg(),kEe=se(),Wp=(H(),v(W)),{hdbErrors:qEe,handleHDBError:EP}=ge(),{HTTP_STATUS_CODES:gP}=qEe;HEe(wc);var GEe=403,$Ee="There was a problem performing this insert. Please check the logs and try again.",SP=class{static{o(this,"ParsedSQLObject")}constructor(){this.ast=void 0,this.variant=void 0,this.permissions_checked=!1}};function VEe(e,t){let r=e.parsed_sql_object;if(!r){r=pW(e.sql);let n,s=r.ast.statements[0];if(s instanceof wc.yy.Insert?n=s.into.databaseid:s instanceof wc.yy.Select?n=s.from?s.from[0].databaseid:null:s instanceof wc.yy.Update||s instanceof wc.yy.Delete?n=s.table.databaseid:rR.error("AST in evaluateSQL is not a valid SQL type."),!(s instanceof wc.yy.Select)&&kEe.isEmptyOrZeroLength(n))return t("No schema specified",null)}_W(e,r,(n,s)=>{if(n)return t(n);t(null,s)})}o(VEe,"evaluateSQL");function hW(e,t){let r;try{r=FEe.verifyPermsAst(t.ast.statements[0],e.hdb_user,t.variant),t.permissions_checked=!0}catch(n){throw n}return r||null}o(hW,"checkASTPermissions");function pW(e){let t=new SP;if(!e)throw EP(new Error,"The 'sql' parameter is missing from the request body",gP.BAD_REQUEST);try{let r=e.trim(),n=wc.parse(r),s=r.split(" ")[0].toLowerCase();t.ast=n,t.variant=s}catch(r){let n=r.message.split(`
|
|
34
|
-
`);throw n[1]?EP(r,`Invalid SQL at: ${n[1]}. Please ensure your SQL is valid. Try adding backticks to reserved words and schema table references.`,gP.BAD_REQUEST):EP(r,"We had trouble parsing your request. Please ensure your SQL is valid. Try adding backticks to reserved words and schema table references.",gP.BAD_REQUEST)}return t}o(pW,"convertSQLToAST");function _W(e,t,r){try{let n=KEe;if(!e.bypass_auth&&!t.permissions_checked){let i=hW(e,t);if(i&&i.length>0)return r(GEe,i)}let s={statement:t.ast.statements[0],hdb_user:e.hdb_user};switch(t.variant){case Wp.VALID_SQL_OPS_ENUM.SELECT:n=vEe,s=t.ast.statements[0];break;case Wp.VALID_SQL_OPS_ENUM.INSERT:n=YEe;break;case Wp.VALID_SQL_OPS_ENUM.UPDATE:n=xEe;break;case Wp.VALID_SQL_OPS_ENUM.DELETE:n=BEe;break;default:throw new Error(`unsupported SQL type ${t.variant} in SQL: ${e}`)}n(s,(i,a)=>{if(i){r(i);return}r(null,a)})}catch(n){return r(n)}}o(_W,"processAST");function KEe(e,t){rR.info(e),t("unknown sql statement")}o(KEe,"nullFunction");function YEe({statement:e,hdb_user:t},r){let n=e.into,s={schema:n.databaseid,table:n.tableid,operation:"insert",hdb_user:t},i=e.columns.map(a=>a.columnid);try{s.records=WEe(i,e.values)}catch(a){return r(a)}MEe(s,(a,c)=>{if(a)return r(a);try{delete c.new_attributes,delete c.txn_time}catch(l){rR.error(`Error delete new_attributes from insert response: ${l}`)}r(null,c)})}o(YEe,"convertInsert");function WEe(e,t){try{return t.map(r=>{if(e.length!==r.length)throw"number of values do not match number of columns in insert";let n={};return r.forEach((s,i)=>{if(s.columnid)throw"cannot use a column in insert value";"value"in s?n[e[i]]=s.value:n[e[i]]=wc.compile(`SELECT ${s.toString()} AS [${Wp.FUNC_VAL}] FROM ?`)}),n})}catch(r){throw rR.error(r),new Error($Ee)}}o(WEe,"createDataObjects")});var IP=M((SFe,RW)=>{var aR=require("clone"),cR=lt(),zEe=se(),iR=(H(),v(W)),EFe=j(),TP=require("fs"),yP=require("joi"),{string:oR}=yP.types(),{hdbErrors:jEe,handleHDBError:sR}=ge(),{HDB_ERROR_MSGS:gFe,HTTP_STATUS_CODES:RP}=jEe,{commonValidators:Rf}=Ji(),gW=" is required",JEe=["insert","update","upsert"],AP={database:{presence:!1,format:Rf.schema_format,length:Rf.schema_length},schema:{presence:!1,format:Rf.schema_format,length:Rf.schema_length},table:{presence:!0,format:Rf.schema_format,length:Rf.schema_length},action:{inclusion:{within:JEe,message:"is required and must be either insert, update, or upsert"}},file_path:{},csv_url:{url:{allowLocal:!0}},data:{},passthrough_headers:{}},QEe={schema:oR.required(),table:oR.required(),action:oR.valid("insert","update","upsert")},{AWS_ACCESS_KEY:XEe,AWS_SECRET:ZEe,AWS_BUCKET:ege,AWS_FILE_KEY:tge,REGION:rge}=iR.S3_BUCKET_AUTH_KEYS,nge={s3:{presence:!0},[`s3.${XEe}`]:{presence:!0,type:"String"},[`s3.${ZEe}`]:{presence:!0,type:"String"},[`s3.${ege}`]:{presence:!0,type:"String"},[`s3.${tge}`]:{presence:!0,type:"String",hasValidFileExt:[".csv",".json"]},[`s3.${rge}`]:{presence:!0,type:"String"}},SW=aR(AP);SW.data.presence={message:gW};var TW=aR(AP);TW.file_path.presence={message:gW};var sge=Object.assign(aR(AP),nge),bP=aR(QEe);bP.csv_url=oR.uri().messages({"string.uri":"'csv_url' must be a valid url"}).required();bP.passthrough_headers=yP.object();function ige(e){let t=cR.validateObject(e,SW);return lR(e,t)}o(ige,"dataObject");function oge(e){let t=cR.validateBySchema(e,yP.object(bP));return lR(e,t)}o(oge,"urlObject");function age(e){let t=cR.validateObject(e,TW);return lR(e,t)}o(age,"fileObject");function cge(e){let t=cR.validateObject(e,sge);return lR(e,t)}o(cge,"s3FileObject");function lR(e,t){if(!t){let r=zEe.checkGlobalSchemaTable(e.schema,e.table);if(r)return sR(new Error,r,RP.BAD_REQUEST);if(e.operation===iR.OPERATIONS_ENUM.CSV_FILE_LOAD)try{TP.accessSync(e.file_path,TP.constants.R_OK|TP.constants.F_OK)}catch(n){return n.code===iR.NODE_ERROR_CODES.ENOENT?sR(n,`No such file or directory ${n.path}`,RP.BAD_REQUEST):n.code===iR.NODE_ERROR_CODES.EACCES?sR(n,`Permission denied ${n.path}`,RP.BAD_REQUEST):sR(n)}}return t}o(lR,"postValidateChecks");RW.exports={dataObject:ige,urlObject:oge,fileObject:age,s3FileObject:cge}});var NP=M((RFe,yW)=>{"use strict";var zp=j(),uR=(H(),v(W));async function lge(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===uR.OPERATIONS_ENUM.INSERT||t.operation===uR.OPERATIONS_ENUM.UPDATE||t.operation===uR.OPERATIONS_ENUM.UPSERT?(delete s.new_attributes,delete s.txn_time):t.operation===uR.OPERATIONS_ENUM.DELETE&&delete s.txn_time,s}catch(i){throw i.message&&typeof i.message=="string"&&i.message.includes("already exists")?(zp.info(i.message),i):i.http_resp_msg?(zp.error(`Error calling operation: ${e.name}`),zp.error(i.http_resp_msg),i):(zp.error(`Error calling operation: ${e.name}`),zp.error(i),i)}}o(lge,"callOperationFunctionAsAwait");yW.exports={callOperationFunctionAsAwait:lge}});var wP=M((AFe,bW)=>{"use strict";var{S3:uge,GetObjectCommand:dge}=require("@aws-sdk/client-s3");bW.exports={getFileStreamFromS3:fge,getS3AuthObj:AW};async function fge(e){let{s3:t}=e,r={Bucket:t.bucket,Key:t.key};return(await AW(t.aws_access_key_id,t.aws_secret_access_key,t.region).send(new dge(r))).Body}o(fge,"getFileStreamFromS3");function AW(e,t,r){return new uge({credentials:{accessKeyId:e,secretAccessKey:t},region:r})}o(AW,"getS3AuthObj")});var NW=M((IFe,IW)=>{"use strict";var OP=class{static{o(this,"BulkLoadFileObject")}constructor(t,r,n,s,i,a,c=null){this.op=t,this.action=r,this.schema=n,this.table=s,this.file_path=i,this.file_type=a,this.role_perms=c}},CP=class{static{o(this,"BulkLoadDataObject")}constructor(t,r,n,s){this.action=t,this.schema=r,this.table=n,this.data=s}};IW.exports={BulkLoadFileObject:OP,BulkLoadDataObject:CP}});var DP=M((wFe,wW)=>{"use strict";var PP=class{static{o(this,"ClusteringOriginObject")}constructor(t,r,n){this.timestamp=t,this.user=r,this.node_name=n}};wW.exports=PP});var BP=M((MFe,VW)=>{"use strict";var dR=Bn(),mR=IP(),mge=require("needle"),Mi=(H(),v(W)),CFe=Ot(),yf=se(),{handleHDBError:Qt,hdbErrors:xW}=ge(),{HTTP_STATUS_CODES:en,HDB_ERROR_MSGS:wr,CHECK_LOGS_WRAPPER:fu}=xW,Af=j(),LP=require("papaparse");yf.promisifyPapaParse();var vi=require("fs-extra"),hge=require("path"),{chain:OW}=require("stream-chain"),CW=require("stream-json/streamers/StreamArray"),PW=require("stream-json/utils/Batch"),DW=require("stream-chain/utils/comp"),{finished:LW}=require("stream"),pge=oe(),BW=NP(),_ge=wP(),{BulkLoadFileObject:vP,BulkLoadDataObject:Ege}=NW(),UP=cP(),{verifyBulkLoadAttributePerms:FW}=tR(),PFe=DP(),DFe=sr(),LFe=Zi(),{databases:gge}=(Pe(),v(ut)),{coerceType:Sge}=(hR(),v(KW)),MW="No records parsed from csv file.",du=`${pge.get("HDB_ROOT")}/tmp`,{schemaRegex:Tge}=Ji(),vW=1024*1024*2,UW=5e3,Rge={"text/csv":!0,"application/octet-stream":!0,"text/plain":!0,"application/vnd.ms-excel":!0};VW.exports={csvDataLoad:yge,csvURLLoad:Age,csvFileLoad:bge,importFromS3:Ige};async function yge(e,t){let r=mR.dataObject(e);if(r)throw Qt(r,r.message,en.BAD_REQUEST,void 0,void 0,!0);let n={};try{let s=qW(e.schema,e.table),i=LP.parse(e.data,{header:!0,skipEmptyLines:!0,transform:MP.bind(null,s),dynamicTyping:!1}),a=new UP;e.hdb_user&&e.hdb_user?.role&&e.hdb_user?.role?.permission&&e.hdb_user?.role?.permission?.super_user!==!0&&FW(e.hdb_user?.role?.permission,this.job_operation_function.name,e.action,e.schema,e.table,i.meta.fields,a);let c=a.getPermsResponse();if(c)throw Qt(new Error,c,en.BAD_REQUEST,void 0,void 0,!0);let l=new Ege(e.action,e.schema,e.table,i.data);return n=await BW.callOperationFunctionAsAwait(GW,l,null),n.message===MW?MW:$W(n.records,n.number_written)}catch(s){throw mu(s)}}o(yge,"csvDataLoad");async function Age(e){let t=mR.urlObject(e);if(t)throw Qt(t,t.message,en.BAD_REQUEST,void 0,void 0,!0);let r=`${Date.now()}.csv`,n=`${du}/${r}`;try{await Nge(e,r)}catch(s){throw Af.error(wr.DOWNLOAD_FILE_ERR(r)+" - "+s),Qt(s,fu(wr.DOWNLOAD_FILE_ERR(r)))}try{let s=new vP(this.job_operation_function.name,e.action,e.schema,e.table,n,Mi.VALID_S3_FILE_TYPES.CSV,e.hdb_user?.role?.permission),i=await xP(s);return await fR(n),i}catch(s){throw await fR(n),mu(s)}}o(Age,"csvURLLoad");async function bge(e){let t=mR.fileObject(e);if(t)throw Qt(t,t.message,en.BAD_REQUEST,void 0,void 0,!0);let r=new vP(this.job_operation_function.name,e.action,e.schema,e.table,e.file_path,Mi.VALID_S3_FILE_TYPES.CSV,e.hdb_user?.role?.permission);try{return await xP(r)}catch(n){throw mu(n)}}o(bge,"csvFileLoad");async function Ige(e){let t=mR.s3FileObject(e);if(t)throw Qt(t,t.message,en.BAD_REQUEST,void 0,void 0,!0);let r;try{let n=hge.extname(e.s3.key),s=`${Date.now()}${n}`;r=`${du}/${s}`;let i=new vP(this.job_operation_function.name,e.action,e.schema,e.table,r,n,e.hdb_user?.role?.permission);await wge(s,e);let a=await xP(i);return await fR(r),a}catch(n){throw await fR(r),mu(n)}}o(Ige,"importFromS3");async function Nge(e,t){let r;try{let n=e.passthrough_headers?{headers:e.passthrough_headers}:void 0;r=await mge("get",e.csv_url,n)}catch(n){let s=`Error downloading CSV file from ${e.csv_url}, status code: ${n.statusCode}. Check the log for more information.`;throw Qt(n,s,n.statusCode,Mi.LOG_LEVELS.ERROR,"Error downloading CSV file - "+n)}Cge(r,e.csv_url),await Oge(t,r.raw)}o(Nge,"downloadCSVFile");async function wge(e,t){try{let r=`${du}/${e}`;await vi.mkdirp(du),await vi.writeFile(`${du}/${e}`,"",{flag:"a+"});let n=await vi.createWriteStream(r),s=await _ge.getFileStreamFromS3(t);await new Promise((i,a)=>{s.on("error",function(c){a(c)}),s.pipe(n).on("error",function(c){a(c)}).on("close",function(){Af.info(`${t.s3.key} successfully downloaded to ${r}`),i()})})}catch(r){throw Af.error(wr.S3_DOWNLOAD_ERR+" - "+r),Qt(r,fu(wr.S3_DOWNLOAD_ERR))}}o(wge,"downloadFileFromS3");async function Oge(e,t){try{await vi.mkdirp(du),await vi.writeFile(`${du}/${e}`,t)}catch(r){throw Af.error(wr.WRITE_TEMP_FILE_ERR),Qt(r,fu(wr.DEFAULT_BULK_LOAD_ERR))}}o(Oge,"writeFileToTempFolder");async function fR(e){if(e)try{await vi.access(e),await vi.unlink(e)}catch{Af.warn(`could not delete temp csv file at ${e}, file does not exist`)}}o(fR,"deleteTempFile");function Cge(e,t){if(e.statusCode!==xW.HTTP_STATUS_CODES.OK)throw Qt(new Error,`CSV Load failed from URL: ${t}, status code: ${e.statusCode}, message: ${e.statusMessage}`,en.BAD_REQUEST);if(!Rge[e.headers["content-type"]])throw Qt(new Error,`CSV Load failed from URL: ${t}, unsupported content type: ${e.headers["content-type"]}`,en.BAD_REQUEST);if(!e.raw)throw Qt(new Error,`CSV Load failed from URL: ${t}, no csv found at url`,en.BAD_REQUEST)}o(Cge,"validateURLResponse");async function xP(e){try{let t;switch(e.file_type){case Mi.VALID_S3_FILE_TYPES.CSV:t=await Pge(e);break;case Mi.VALID_S3_FILE_TYPES.JSON:t=await Dge(e);break;default:throw Qt(new Error,wr.DEFAULT_BULK_LOAD_ERR,en.BAD_REQUEST,Mi.LOG_LEVELS.ERROR,wr.INVALID_FILE_EXT_ERR(e))}return $W(t.records,t.number_written)}catch(t){throw mu(t)}}o(xP,"fileLoad");async function HW(e,t,r,n,s){let i=n.data?n.data:n;if(i.length===0)return;s&&s.pause();let a={operation:e.action,schema:e.schema,table:e.table,records:i};try{let{attributes:c}=await dR.validation(a);e.role_perms&&e.role_perms.super_user!==!0&&FW(e.role_perms,e.op,e.action,e.schema,e.table,c,t),s&&s.resume()}catch(c){let l=Qt(c);r(l)}}o(HW,"validateChunk");async function kW(e,t,r,n,s){let i=n.data?n.data:n;if(i.length===0)return;yf.autoCastJSONDeep(i),s&&s.pause();let a=n.meta?n.meta.fields:null;if(a)i.forEach(c=>{!yf.isEmpty(c)&&!yf.isEmpty(c.__parsed_extra)&&delete c.__parsed_extra});else{let c=new Set;i.forEach(l=>{Object.keys(l).forEach(u=>c.add(u))}),a=[...c]}try{let c={schema:e.schema,table:e.table,action:e.action,data:i},l=await BW.callOperationFunctionAsAwait(GW,c,null);t.records+=l.records,t.number_written+=l.number_written,s&&s.resume()}catch(c){let l=Qt(c,fu(wr.INSERT_CSV_ERR),en.INTERNAL_SERVER_ERROR,Mi.LOG_LEVELS.ERROR,wr.INSERT_CSV_ERR+" - "+c);r(l)}}o(kW,"insertChunk");async function Pge(e){let t={records:0,number_written:0},r=qW(e.schema,e.table);try{let n=new UP,s=vi.createReadStream(e.file_path,{highWaterMark:vW});s.setEncoding("utf8"),await LP.parsePromise(s,HW.bind(null,e,n),MP.bind(null,r));let i=n.getPermsResponse();if(i)throw Qt(new Error,i,en.BAD_REQUEST);return s=vi.createReadStream(e.file_path,{highWaterMark:vW}),s.setEncoding("utf8"),await LP.parsePromise(s,kW.bind(null,e,t),MP.bind(null,r)),s.destroy(),t}catch(n){throw Qt(n,fu(wr.PAPA_PARSE_ERR),en.INTERNAL_SERVER_ERROR,Mi.LOG_LEVELS.ERROR,wr.PAPA_PARSE_ERR+n)}}o(Pge,"callPapaParse");function qW(e,t){let r=gge[e][t].attributes,n=new Map;for(let s of r)s.type&&!s.computed&&!s.relationship&&n.set(s.name,i=>Sge(i,s));return n}o(qW,"createTransformMap");function MP(e,t,r){let n=e.get(r);return n?n(t):yf.autoCast(t)}o(MP,"typeFunction");async function Dge(e){let t={records:0,number_written:0},r=o(n=>{throw n},"throwErr");try{let n=new UP,s=OW([vi.createReadStream(e.file_path,{encoding:"utf-8"}),CW.withParser(),c=>c.value,new PW({batchSize:UW}),DW(async c=>{await HW(e,n,r,c)})]);await new Promise((c,l)=>{LW(s,u=>{u?l(u):c()}),s.resume()});let i=n.getPermsResponse();if(i)throw Qt(new Error,i,en.BAD_REQUEST);let a=OW([vi.createReadStream(e.file_path,{encoding:"utf-8"}),CW.withParser(),c=>c.value,new PW({batchSize:UW}),DW(async c=>{await kW(e,t,r,c)})]);return await new Promise((c,l)=>{LW(a,u=>{u?l(u):c()}),a.resume()}),t}catch(n){throw Qt(n,fu(wr.INSERT_JSON_ERR),en.INTERNAL_SERVER_ERROR,Mi.LOG_LEVELS.ERROR,wr.INSERT_JSON_ERR+n)}}o(Dge,"insertJson");async function GW(e){let t={};try{e.data&&e.data.length>0&&Lge(e.data[0])?t=await Mge(e.data,e.schema,e.table,e.action):(t.message="No records parsed from csv file.",Af.info(t.message))}catch(r){throw mu(r)}return t}o(GW,"callBulkFileLoad");function Lge(e){let t=Object.keys(e);for(let r of t)if(!Tge.test(r))throw new Error(`Invalid column name '${r}', cancelling load operation`);return!0}o(Lge,"validateColumnNames");async function Mge(e,t,r,n){n||(n="insert");let s={operation:n,schema:t,table:r,records:e},i;switch(n){case"insert":i=dR.insert;break;case"update":i=dR.update;break;case"upsert":i=dR.upsert;break;default:throw Qt(new Error,wr.INVALID_ACTION_PARAM_ERR(n),en.BAD_REQUEST,Mi.LOG_LEVELS.ERROR,wr.INVALID_ACTION_PARAM_ERR(n))}try{let a=await i(s),c;switch(n){case"insert":c=a.inserted_hashes;break;case"update":c=a.update_hashes;break;case"upsert":c=a.upserted_hashes;break;default:break}if(Array.isArray(a.skipped_hashes)&&a.skipped_hashes.length>0){let d=global.hdb_schema[t][r].hash_attribute,f=e.length;for(;f--;)a.skipped_hashes.indexOf(e[f][d])>=0&&e.splice(f,1)}let l=yf.isEmptyOrZeroLength(c)?0:c.length;return{records:e.length,number_written:l,new_attributes:a.new_attributes}}catch(a){throw mu(a)}}o(Mge,"bulkFileLoad");function $W(e,t){return`successfully loaded ${t} of ${e} records`}o($W,"buildResponseMsg");function mu(e){return Qt(e,fu(wr.DEFAULT_BULK_LOAD_ERR),en.INTERNAL_SERVER_ERROR,Mi.LOG_LEVELS.ERROR,wr.DEFAULT_BULK_LOAD_ERR+" - "+e)}o(mu,"buildTopLevelErrMsg")});var kP=M((UFe,ZW)=>{"use strict";var HP=an(),vge=wP(),{AsyncParser:Uge}=require("json2csv"),pR=require("stream"),_s=se(),FP=require("fs-extra"),xge=require("path"),Ws=j(),{promisify:zW}=require("util"),jp=se(),{handleHDBError:Sr,hdbErrors:Bge}=ge(),{HDB_ERROR_MSGS:Yn,HTTP_STATUS_CODES:Tr}=Bge,{streamAsJSON:Fge}=(pb(),v(bU)),{Upload:Hge}=require("@aws-sdk/lib-storage"),{toCsvStream:kge}=(Uo(),v(VU)),YW=["search_by_value","search_by_hash","sql","search_by_conditions"],WW=["json","csv"],jW="json",JW="csv",qge="Successfully exported JSON locally.",Gge="Successfully exported CSV locally.",$ge=1e3,Vge=HP.searchByHash,Kge=HP.searchByValue,Yge=zW(pR.finished);ZW.exports={export_to_s3:Jge,export_local:Wge};async function Wge(e){Ws.trace(`export_local request to path: ${e.path}, filename: ${e.filename}, format: ${e.format}`);let t=QW(e);if(!_s.isEmpty(t))throw Ws.error(t),Sr(new Error,t,Tr.BAD_REQUEST,void 0,void 0,!0);if(_s.isEmpty(e.path))throw Ws.error(Yn.MISSING_VALUE("path")),Sr(new Error,Yn.MISSING_VALUE("path"),Tr.BAD_REQUEST,void 0,void 0,!0);let r=(_s.isEmpty(e.filename)?new Date().getTime():e.filename)+"."+e.format;e.path.endsWith(xge.sep)&&(e.path=e.path.substring(0,e.path.length-1));let n=_s.buildFolderPath(e.path,r);await zge(e.path);let s=await XW(e);return await jge(n,e.format,s)}o(Wge,"export_local");async function zge(e){if(Ws.trace("in confirmPath"),_s.isEmptyOrZeroLength(e))throw Sr(new Error,`Invalid path: ${e}`,Tr.BAD_REQUEST,void 0,void 0,!0);let t;try{t=await FP.stat(e)}catch(r){let n;throw r.code==="ENOENT"?n=`path '${e}' does not exist`:r.code==="EACCES"?n=`access to path '${e}' is denied`:n=r.message,Ws.error(n),Sr(new Error,n,Tr.BAD_REQUEST,void 0,void 0,!0)}if(!t.isDirectory()){let r=`path '${e}' is not a directory, please supply a valid folder path`;throw Ws.error(r),Sr(new Error,r,Tr.BAD_REQUEST,void 0,void 0,!0)}return!0}o(zge,"confirmPath");async function jge(e,t,r){if(Ws.trace("in saveToLocal"),jp.isEmptyOrZeroLength(e))throw Sr(new Error,Yn.INVALID_VALUE("file_path"),Tr.BAD_REQUEST,void 0,void 0,!0);if(jp.isEmptyOrZeroLength(t))throw Sr(new Error,Yn.INVALID_VALUE("Source format"),Tr.BAD_REQUEST,void 0,void 0,!0);if(jp.isEmpty(r))throw Sr(new Error,Yn.NOT_FOUND("Data"),Tr.BAD_REQUEST,void 0,void 0,!0);if(t===jW){let n=FP.createWriteStream(e);return Fge(r).pipe(n),await Yge(n),{message:qge,path:e}}else if(t===JW){let n=FP.createWriteStream(e),s=pR.Readable.from(r),i={},a=r.getColumns?.();a&&(i.fields=a.map(d=>({label:d,value:d})));let c={objectMode:!0};return await new Uge(i,c).fromInput(s).toOutput(n).promise(!1),{message:Gge,path:e}}throw Sr(new Error,Yn.INVALID_VALUE("format"),Tr.BAD_REQUEST)}o(jge,"saveToLocal");async function Jge(e){if(!e.s3||Object.keys(e.s3).length===0)throw Sr(new Error,Yn.MISSING_VALUE("S3 object"),Tr.BAD_REQUEST);if(_s.isEmptyOrZeroLength(e.s3.aws_access_key_id))throw Sr(new Error,Yn.MISSING_VALUE("aws_access_key_id"),Tr.BAD_REQUEST);if(_s.isEmptyOrZeroLength(e.s3.aws_secret_access_key))throw Sr(new Error,Yn.MISSING_VALUE("aws_secret_access_key"),Tr.BAD_REQUEST);if(_s.isEmptyOrZeroLength(e.s3.bucket))throw Sr(new Error,Yn.MISSING_VALUE("bucket"),Tr.BAD_REQUEST);if(_s.isEmptyOrZeroLength(e.s3.key))throw Sr(new Error,Yn.MISSING_VALUE("key"),Tr.BAD_REQUEST);if(_s.isEmptyOrZeroLength(e.s3.region))throw Sr(new Error,Yn.MISSING_VALUE("region"),Tr.BAD_REQUEST);let t=QW(e);if(!_s.isEmpty(t))throw Sr(new Error,t,Tr.BAD_REQUEST);Ws.trace(`called export_to_s3 to bucket: ${e.s3.bucket} and query ${e.search_operation.sql}`);let r;try{r=await XW(e)}catch(l){throw Ws.error(l),l}let n,s=await vge.getS3AuthObj(e.s3.aws_access_key_id,e.s3.aws_secret_access_key,e.s3.region),i,a=new pR.PassThrough;if(e.format===JW){i=e.s3.key+".csv";let l=kge(r,r.getColumns?.());l.on("error",u=>{throw u}),l.pipe(a)}else if(e.format===jW){i=e.s3.key+".json";let l=new pR.Readable;l.pipe(a),l.on("error",f=>{throw f}),l.push("[");let u=r.length,d="";for(let[f,m]of r.entries()){let h=f===u-1?JSON.stringify(m):JSON.stringify(m)+",";d+=h,f!==0&&f%$ge===0&&(l.push(d),d="")}d.length!==0&&l.push(d),l.push("]"),l.push(null)}else throw Sr(new Error,Yn.INVALID_VALUE("format"),Tr.BAD_REQUEST);return new Hge({client:s,params:{Bucket:e.s3.bucket,Key:i,Body:a}}).done()}o(Jge,"export_to_s3");function QW(e){if(Ws.trace("in exportCoreValidation"),_s.isEmpty(e.format))return"format missing";if(WW.indexOf(e.format)<0)return`format invalid. must be one of the following values: ${WW.join(", ")}`;let t=e.search_operation.operation;if(_s.isEmpty(t))return"search_operation.operation missing";if(YW.indexOf(t)<0)return`searchOperation.operation must be one of the following values: ${YW.join(", ")}`}o(QW,"exportCoreValidation");async function XW(e){Ws.trace("in getRecords");let t,r;if(jp.isEmpty(e.search_operation)||jp.isEmptyOrZeroLength(e.search_operation.operation))throw Sr(new Error,Yn.INVALID_VALUE("Search operation"),Tr.BAD_REQUEST);switch(e.search_operation.operation){case"search_by_value":t=Kge;break;case"search_by_hash":t=Vge;break;case"search_by_conditions":t=HP.searchByConditions;break;case"sql":{let n=nR();t=zW(n.evaluateSQL);break}default:throw r=`Operation ${e.search_operation.operation} is not support by export.`,Ws.error(r),Sr(new Error,r,Tr.BAD_REQUEST)}return e.search_operation.hdb_user=e.hdb_user,t(e.search_operation)}o(XW,"getRecords")});var tz=M((BFe,ez)=>{"use strict";var qP=class{static{o(this,"SqlSearchObject")}constructor(t,r){this.operation="sql",this.sql=t,this.hdb_user=r}};ez.exports=qP});var sz=M((HFe,nz)=>{"use strict";var Qge=(H(),v(W)),rz=require("moment"),Xge=require("uuid").v4,GP=class{static{o(this,"JobObject")}constructor(){this.id=Xge(),this.type=void 0,this.start_datetime=rz().valueOf(),this.created_datetime=rz().valueOf(),this.end_datetime=void 0,this.status=Qge.JOB_STATUS_ENUM.CREATED,this.message=void 0,this.user=void 0,this.request=void 0}};nz.exports=GP});var $P=M((qFe,fz)=>{"use strict";var Zge=require("uuid").v4,lz=Bn(),uz=an(),eSe=Ri(),tSe=pd(),rSe=tz(),Lt=(H(),v(W)),nSe=sz(),sSe=eS(),Ui=j(),iSe=Dm(),bf=se(),{promisify:oSe}=require("util"),hu=require("moment"),aSe=nR(),_R=IP(),iz=mI(),{deleteTransactionLogsBeforeValidator:cSe}=zC(),{handleHDBError:oz,hdbErrors:lSe,ClientError:uSe}=ge(),{HTTP_STATUS_CODES:az}=lSe,cz=uz.searchByValue,dSe=uz.searchByHash,fSe=lz.insert,mSe=oSe(aSe.evaluateSQL),hSe=lz.update;fz.exports={addJob:ESe,updateJob:SSe,handleGetJob:pSe,handleGetJobsByStartDate:_Se,getJobById:dz};async function pSe(e){if(e.id===void 0)throw new uSe("'id' is required");let t=await dz(e.id);return bf.isEmptyOrZeroLength(t)||(t[0]={...t[0]},t[0].request!==void 0&&delete t[0].request,delete t[0].__createdtime__,delete t[0].__updatedtime__),t}o(pSe,"handleGetJob");async function _Se(e){try{let t=await gSe(e);if(Ui.trace(`Searching for jobs from ${e.from_date} to ${e.to_date}`),t&&t.length>0)for(let r of t)r.start_datetime&&(r.start_datetime_converted=hu(r.start_datetime)),r.end_datetime&&(r.end_datetime_converted=hu(r.end_datetime)),r.request!==void 0&&delete r.request,delete r.__createdtime__,delete r.__updatedtime__;return t}catch(t){let r=`There was an error searching jobs by date: ${t}`;throw Ui.error(r),new Error(r)}}o(_Se,"handleGetJobsByStartDate");async function ESe(e){let t={message:"",error:"",success:!1,createdJob:void 0};if(!e||Object.keys(e).length===0||bf.isEmptyOrZeroLength(e.operation)){let d="job parameter is invalid";return Ui.info(d),t.error=d,t}if(!Lt.JOB_TYPE_ENUM[e.operation])return Ui.info(`invalid job type specified: ${e.operation}.`),t;let r=e.operation,n;switch(r){case Lt.OPERATIONS_ENUM.CSV_FILE_LOAD:n=_R.fileObject(e);break;case Lt.OPERATIONS_ENUM.CSV_URL_LOAD:n=_R.urlObject(e);break;case Lt.OPERATIONS_ENUM.CSV_DATA_LOAD:n=_R.dataObject(e);break;case Lt.OPERATIONS_ENUM.IMPORT_FROM_S3:n=_R.s3FileObject(e);break;case Lt.OPERATIONS_ENUM.DELETE_FILES_BEFORE:case Lt.OPERATIONS_ENUM.DELETE_RECORDS_BEFORE:n=iz(e,"date");break;case Lt.OPERATIONS_ENUM.DELETE_AUDIT_LOGS_BEFORE:n=iz(e,"timestamp");break;case Lt.OPERATIONS_ENUM.DELETE_TRANSACTION_LOGS_BEFORE:n=cSe(e);break;case Lt.OPERATIONS_ENUM.RESTART_SERVICE:if(Lt.HDB_PROCESS_SERVICES[e.service]===void 0)throw oz(new Error,"Invalid service",az.BAD_REQUEST,void 0,void 0,!0);break;default:break}if(n)throw oz(n,n.message,az.BAD_REQUEST,void 0,void 0,!0);let s=new nSe;s.type=e.operation===Lt.OPERATIONS_ENUM.DELETE_RECORDS_BEFORE?Lt.OPERATIONS_ENUM.DELETE_FILES_BEFORE:e.operation,s.type=e.operation,s.user=e.hdb_user?.username;let i=new eSe(Lt.SYSTEM_SCHEMA_NAME,Lt.SYSTEM_TABLE_NAMES.JOB_TABLE_NAME,"id",s.id,"id",["id"]),a;try{a=Array.from(await cz(i))}catch(d){let f=`There was an error inserting a new job: ${d}`;return Ui.error(f),t}let c=Array.isArray(a)?a:Object.keys(a);if(c&&c.length>0){s.id=Zge();try{a=await cz(i)}catch(d){let f=`There was an error inserting a new job: ${d}`;return Ui.error(f),t}if(c=Array.isArray(a)?a:Object.keys(a),c&&c.length>0)return Ui.error("Error creating a job, could not find a unique job id."),t}s.request=e;let l=new iSe(Lt.SYSTEM_SCHEMA_NAME,Lt.SYSTEM_TABLE_NAMES.JOB_TABLE_NAME,"id",[s]),u;try{u=await fSe(l)}catch(d){return Ui.error(`There was an error inserting a job for job type: ${e.operation} -- ${d}`),t.success=!1,t}if(u.inserted_hashes.length===0)t.message=`Had a problem creating a job with type ${s.operation} and id ${s.id}`;else{let d=`Created a job with type ${s.type} and id ${s.id}`;t.message=d,t.createdJob=s,t.success=!0,Ui.trace(d)}return t}o(ESe,"addJob");async function gSe(e){let t=hu(e.from_date,hu.ISO_8601),r=hu(e.to_date,hu.ISO_8601);if(!t.isValid())throw new Error("Invalid 'from' date, must be in ISO-8601 format (YYYY-MM-DD).");if(!r.isValid())throw new Error("Invalid 'to' date, must be in ISO-8601 format (YYYY-MM-DD)");let n=`select * from system.hdb_job where start_datetime > '${t.valueOf()}' and start_datetime < '${r.valueOf()}'`,s=new rSe(n,e.hdb_user);try{return await mSe(s)}catch(i){throw Ui.error(`there was a problem searching for jobs from date ${e.from_date} to date ${e.to_date} ${i}`),new Error("there was an error searching for jobs. Please check the log for details.")}}o(gSe,"getJobsInDateRange");async function dz(e){if(bf.isEmptyOrZeroLength(e))return bf.errorizeMessage("Invalid job ID specified.");let t=new tSe(Lt.SYSTEM_SCHEMA_NAME,Lt.SYSTEM_TABLE_NAMES.JOB_TABLE_NAME,[e],["*"]);try{return await dSe(t)}catch(r){let n=`There was an error searching for a job by id: ${e} ${r}`;return Ui.error(n),bf.errorizeMessage("there was an error searching for jobs. Please check the log for details.")}}o(dz,"getJobById");async function SSe(e){if(Object.keys(e).length===0)throw new Error("invalid job object passed to updateJob");if(bf.isEmptyOrZeroLength(e.id))throw new Error("invalid ID passed to updateJob");(e.status===Lt.JOB_STATUS_ENUM.COMPLETE||e.status===Lt.JOB_STATUS_ENUM.ERROR)&&(e.end_datetime=hu().valueOf());let t=new sSe(Lt.SYSTEM_SCHEMA_NAME,Lt.SYSTEM_TABLE_NAMES.JOB_TABLE_NAME,[e]),r;return r=await hSe(t),r}o(SSe,"updateJob")});var Tz=M(($Fe,Sz)=>{"use strict";var mz=se(),Or=(H(),v(W)),TSe=require("moment"),ER=BP(),Jp=j(),hz=$P(),pz=kP(),_z=Rl(),Ez=rt(),RSe=YT(),ySe=yc(),{parentPort:ASe,isMainThread:gz}=require("worker_threads"),{onMessageByType:bSe}=rt(),VP=class{static{o(this,"RunnerMessage")}constructor(t,r){this.job=t,this.json=r}};async function ISe(e){if(!e||Object.keys(e).length===0)throw new Error("Empty runner passed to parseMessage");if(!e.json||Object.keys(e.json).length===0)throw new Error("Empty JSON passed to parseMessage");if(!e.job||Object.keys(e.job).length===0)throw new Error("Empty job passed to parseMessage");if(mz.isEmptyOrZeroLength(e.json.operation))throw new Error("Invalid operation");if(mz.isEmptyOrZeroLength(e.job.id))throw new Error("Empty job id specified");switch(e.json.operation){case Or.JOB_TYPE_ENUM.csv_file_load:await ho(e,ER.csvFileLoad);break;case Or.JOB_TYPE_ENUM.csv_url_load:await ho(e,ER.csvURLLoad);break;case Or.JOB_TYPE_ENUM.csv_data_load:await ho(e,ER.csvDataLoad);break;case Or.JOB_TYPE_ENUM.import_from_s3:await ho(e,ER.importFromS3);break;case Or.JOB_TYPE_ENUM.empty_trash:break;case Or.JOB_TYPE_ENUM.export_local:await ho(e,pz.export_local);break;case Or.JOB_TYPE_ENUM.export_to_s3:await ho(e,pz.export_to_s3);break;case Or.JOB_TYPE_ENUM.delete_files_before:case Or.JOB_TYPE_ENUM.delete_records_before:await ho(e,_z.deleteFilesBefore);break;case Or.JOB_TYPE_ENUM.delete_audit_logs_before:await ho(e,_z.deleteAuditLogsBefore);break;case Or.JOB_TYPE_ENUM.delete_transaction_logs_before:await ho(e,RSe.deleteTransactionLogsBefore);break;case Or.JOB_TYPE_ENUM.restart_service:return await ho(e,ySe.restartService),`Restarting ${e.json.service}`;break;default:return`Invalid operation ${e.json.operation} specified`}}o(ISe,"parseMessage");async function ho(e,t){try{e.job.status=Or.JOB_STATUS_ENUM.IN_PROGRESS,e.job.start_datetime=TSe().valueOf(),await hz.updateJob(e.job),await NSe(e.job.id)}catch(r){let n=r.message!==void 0?r.message:r;typeof n=="string"?(n=`There was an error running ${t.name} job with id ${e.job.id} - ${n}`,r.message=n):Jp.error(`There was an error running ${t.name} job with id ${e.job.id}`),Jp.error(n),e.job.message=n,e.job.status=Or.JOB_STATUS_ENUM.ERROR;try{await hz.updateJob(e.job)}catch(s){throw Jp.error(`Unable to update job with id ${e.job.id}`),s}throw r}}o(ho,"runJob");async function NSe(e){Jp.trace("launching job thread:",e),gz?Ez.startWorker("server/jobs/jobProcess.js",{autoRestart:!1,name:"job",env:{...process.env,[Or.PROCESS_NAME_ENV_PROP]:`JOB-${e}`}}):ASe.postMessage({type:Or.ITC_EVENT_TYPES.START_JOB,jobId:e})}o(NSe,"launchJobThread");gz&&bSe(Or.ITC_EVENT_TYPES.START_JOB,async(e,t)=>{try{Ez.startWorker("server/jobs/jobProcess.js",{autoRestart:!1,name:"job",env:{...process.env,[Or.PROCESS_NAME_ENV_PROP]:`JOB-${e.jobId}`}})}catch(r){Jp.error(r)}});Sz.exports={parseMessage:ISe,RunnerMessage:VP}});var yz=M((KFe,Rz)=>{"use strict";var wSe=se(),KP=oe(),Oc=(H(),v(W)),OSe=Ot(),CSe=sr(),po=j(),PSe=DP(),DSe=Zi();KP.initSync();Rz.exports={postOperationHandler:MSe,sendOperationTransaction:Qp};async function Qp(e,t,r,n){if(e.schema===Oc.SYSTEM_SCHEMA_NAME)return;let s=LSe(e,t,r);s&&(po.trace(`sendOperationTransaction publishing to schema ${e.schema} following transaction:`,s),await CSe.publishToStream(`${OSe.SUBJECT_PREFIXES.TXN}.${e.schema}`,DSe.createNatsTableStreamName(e.schema,e.table),n,s))}o(Qp,"sendOperationTransaction");function LSe(e,t,r){if(wSe.isEmptyOrZeroLength(t))return null;let n={operation:e.operation,schema:e.schema,table:e.table,__origin:r};return e.operation===Oc.OPERATIONS_ENUM.DELETE?n.hash_values=t:n.records=e.records,n}o(LSe,"convertCRUDOperationToTransaction");async function MSe(e,t,r){if(!KP.get(Oc.CONFIG_PARAMS.CLUSTERING_ENABLED))return;po.trace(`postOperationHandler called for operation ${e.operation} on schema.table: ${e.schema}.${e.table}`);let n=e.hdb_user?.username,s=KP.get(Oc.CONFIG_PARAMS.CLUSTERING_NODENAME),i=new PSe(t.txn_time,n,s);switch(e.operation){case Oc.OPERATIONS_ENUM.INSERT:try{await Qp(e,t.inserted_hashes,i,r)}catch(a){po.error("There was an error calling clustering postOperationHandler for insert."),po.error(a)}break;case Oc.OPERATIONS_ENUM.DELETE:try{await Qp(e,t.deleted_hashes,i,r)}catch(a){po.error("There was an error calling clustering postOperationHandler for delete."),po.error(a)}break;case Oc.OPERATIONS_ENUM.UPDATE:try{await Qp(e,t.update_hashes,i,r)}catch(a){po.error("There was an error calling clustering postOperationHandler for update."),po.error(a)}break;case Oc.OPERATIONS_ENUM.UPSERT:try{await Qp(e,t.upserted_hashes,i,r)}catch(a){po.error("There was an error calling clustering postOperationHandler for upsert."),po.error(a)}break;default:break}return t}o(MSe,"postOperationHandler")});var Q,Az=ce(()=>{Q=class{static{o(this,"OperationFunctionObject")}operation_function;job_operation_function;constructor(t,r=void 0){this.operation_function=t,this.job_operation_function=r}}});var YC={};we(YC,{chooseOperation:()=>Gz,executeJob:()=>zs,getOperationFunction:()=>$z,operation:()=>eD,processLocalTransaction:()=>qz});async function qz(e,t){try{if(e.body.operation!=="read_log"&&(t_.default.log_level===ym.INFO||t_.default.log_level===ym.DEBUG||t_.default.log_level===ym.TRACE)){let{hdb_user:n,hdbAuthHeader:s,password:i,payload:a,...c}=e.body;yn.info(c)}}catch(n){yn.error(n)}let r=await Hz.default.callOperationFunctionAsAwait(t,e.body,null);if(typeof r!="object"&&(r={message:r}),r instanceof Error)throw r;return xSe[e.body.operation]&&Uz.default.setSchemaDataToGlobal(n=>{n&&yn.error(n)}),r}function Gz(e){let t;try{t=$z(e)}catch(s){throw yn.error(`Error when selecting operation function - ${s}`),s}let{operation_function:r,job_operation_function:n}=t;try{if(e.operation==="sql"||e.search_operation&&e.search_operation.operation==="sql"){let s=e.operation==="sql"?e.sql:e.search_operation.sql,i=TR.default.convertSQLToAST(s);if(e.parsed_sql_object=i,!e.bypass_auth){let a=TR.default.checkASTPermissions(e,i);if(a)throw yn.error(`${bz.FORBIDDEN} from operation ${e.operation}`),yn.warn(`User '${e.hdb_user?.username}' is not permitted to ${e.operation}`),(0,js.handleHDBError)(new Error,a,js.hdbErrors.HTTP_STATUS_CODES.FORBIDDEN,void 0,void 0,!0)}}else if(!e.bypass_auth&&e.operation!==G.CREATE_AUTHENTICATION_TOKENS&&e.operation!==G.LOGIN&&e.operation!==G.LOGOUT){let s=n===void 0?r:n,i=e.search_operation?e.search_operation:e;i.hdb_user||(i.hdb_user=e.hdb_user);let a=vz.default.verifyPerms(i,s);if(a)throw yn.error(`${bz.FORBIDDEN} from operation ${e.operation}`),yn.warn(`User '${i.hdb_user?.username}' is not permitted to ${i.operation}`),(0,js.handleHDBError)(new Error,a,js.hdbErrors.HTTP_STATUS_CODES.FORBIDDEN,void 0,!1,!0)}}catch(s){throw(0,js.handleHDBError)(s,"There was an error when trying to choose an operation path")}return r}function $z(e){if(yn.trace(`getOperationFunction with operation: ${e.operation}`),Iz.has(e.operation))return Iz.get(e.operation);throw(0,js.handleHDBError)(new Error,js.hdbErrors.HDB_ERROR_MSGS.OP_NOT_FOUND(e.operation),js.hdbErrors.HTTP_STATUS_CODES.BAD_REQUEST,void 0,void 0,!0)}function eD(e,t,r){e.hdb_user=t?.user,e.bypass_auth=!r;let n=Gz(e);return qz({body:e},n)}async function BSe(e){yn.trace("In serverUtils.catchup");let t=e.transaction,r=t.channel.split(":"),n=r[0],s=r[1];for(let i of t.transactions)try{i.schema=n,i.table=s,i[jA]=!0;let a;switch(i.operation){case G.INSERT:a=await _u.default.insert(i);break;case G.UPDATE:a=await _u.default.update(i);break;case G.UPSERT:a=await _u.default.upsert(i);break;case G.DELETE:a=await wf.default.deleteRecord(i);break;default:yn.warn("invalid operation in catchup");break}await kz.transactToClusteringUtils.postOperationHandler(i,a,e)}catch(a){yn.info("Invalid operation in transaction"),yn.error(a)}}async function zs(e){(0,Fz.transformReq)(e);let t,r;try{if(r=await RR.default.addJob(e),r){t=r.createdJob,yn.info("addJob result",r);let n=new jP.default.RunnerMessage(t,e);return{message:await jP.default.parseMessage(n)??`Starting job with id ${t.id}`,job_id:t.id}}}catch(n){let s=n instanceof Error?n:null,i=`There was an error executing job: ${s&&"http_resp_msg"in s?s.http_resp_msg:n}`;throw yn.error(i),(0,js.handleHDBError)(n,i)}}function FSe(){let e=new Map;return e.set(G.INSERT,new Q(_u.default.insert)),e.set(G.UPDATE,new Q(_u.default.update)),e.set(G.UPSERT,new Q(_u.default.upsert)),e.set(G.SEARCH_BY_CONDITIONS,new Q(Nf.default.searchByConditions)),e.set(G.SEARCH_BY_HASH,new Q(Nf.default.searchByHash)),e.set(G.SEARCH_BY_ID,new Q(Nf.default.searchByHash)),e.set(G.SEARCH_BY_VALUE,new Q(Nf.default.searchByValue)),e.set(G.SEARCH,new Q(vSe)),e.set(G.SQL,new Q(USe)),e.set(G.CSV_DATA_LOAD,new Q(zs,Xp.default.csvDataLoad)),e.set(G.CSV_FILE_LOAD,new Q(zs,Xp.default.csvFileLoad)),e.set(G.CSV_URL_LOAD,new Q(zs,Xp.default.csvURLLoad)),e.set(G.IMPORT_FROM_S3,new Q(zs,Xp.default.importFromS3)),e.set(G.CREATE_SCHEMA,new Q(xi.default.createSchema)),e.set(G.CREATE_DATABASE,new Q(xi.default.createSchema)),e.set(G.CREATE_TABLE,new Q(xi.default.createTable)),e.set(G.CREATE_ATTRIBUTE,new Q(xi.default.createAttribute)),e.set(G.DROP_SCHEMA,new Q(xi.default.dropSchema)),e.set(G.DROP_DATABASE,new Q(xi.default.dropSchema)),e.set(G.DROP_TABLE,new Q(xi.default.dropTable)),e.set(G.DROP_ATTRIBUTE,new Q(xi.default.dropAttribute)),e.set(G.DESCRIBE_SCHEMA,new Q(Zp.default.describeSchema)),e.set(G.DESCRIBE_DATABASE,new Q(Zp.default.describeSchema)),e.set(G.DESCRIBE_TABLE,new Q(Zp.default.describeTable)),e.set(G.DESCRIBE_ALL,new Q(Zp.default.describeAll)),e.set(G.DELETE,new Q(wf.default.deleteRecord)),e.set(G.ADD_USER,new Q(If.default.addUser)),e.set(G.ALTER_USER,new Q(If.default.alterUser)),e.set(G.DROP_USER,new Q(If.default.dropUser)),e.set(G.LIST_USERS,new Q(If.default.listUsersExternal)),e.set(G.LIST_ROLES,new Q(e_.default.listRoles)),e.set(G.ADD_ROLE,new Q(e_.default.addRole)),e.set(G.ALTER_ROLE,new Q(e_.default.alterRole)),e.set(G.DROP_ROLE,new Q(e_.default.dropRole)),e.set(G.USER_INFO,new Q(If.default.userInfo)),e.set(G.READ_LOG,new Q(wz.default)),e.set(G.ADD_NODE,new Q(Oz.default)),e.set(G.UPDATE_NODE,new Q(YP.default)),e.set(G.SET_NODE_REPLICATION,new Q(YP.default)),e.set(G.REMOVE_NODE,new Q(Cz.default)),e.set(G.CONFIGURE_CLUSTER,new Q(Pz.default)),e.set(G.PURGE_STREAM,new Q(Dz.default)),e.set(G.SET_CONFIGURATION,new Q(JP.default.setConfiguration)),e.set(G.CLUSTER_STATUS,new Q(Lz.default.clusterStatus)),e.set(G.CLUSTER_NETWORK,new Q(Mz.default)),e.set(G.CLUSTER_SET_ROUTES,new Q(gR.default.setRoutes)),e.set(G.CLUSTER_GET_ROUTES,new Q(gR.default.getRoutes)),e.set(G.CLUSTER_DELETE_ROUTES,new Q(gR.default.deleteRoutes)),e.set(G.EXPORT_TO_S3,new Q(zs,WP.default.export_to_s3)),e.set(G.CREATE_CSR,new Q(pu.default.createCsr)),e.set(G.SIGN_CERTIFICATE,new Q(pu.default.signCertificate)),e.set(G.LIST_CERTIFICATES,new Q(pu.default.listCertificates)),e.set(G.ADD_CERTIFICATES,new Q(pu.default.addCertificate)),e.set(G.REMOVE_CERTIFICATE,new Q(pu.default.removeCertificate)),e.set(G.GET_KEY,new Q(pu.default.getKey)),e.set(G.ADD_NODE_BACK,new Q($O)),e.set(G.REMOVE_NODE_BACK,new Q(VO)),e.set(G.DELETE_FILES_BEFORE,new Q(zs,wf.default.deleteFilesBefore)),e.set(G.DELETE_RECORDS_BEFORE,new Q(zs,wf.default.deleteFilesBefore)),e.set(G.EXPORT_LOCAL,new Q(zs,WP.default.export_local)),e.set(G.SEARCH_JOBS_BY_START_DATE,new Q(RR.default.handleGetJobsByStartDate)),e.set(G.GET_JOB,new Q(RR.default.handleGetJob)),e.set(G.GET_FINGERPRINT,new Q(SR.default.getFingerprint)),e.set(G.SET_LICENSE,new Q(SR.default.setLicense)),e.set(G.GET_REGISTRATION_INFO,new Q(SR.default.getRegistrationInfo)),e.set(G.RESTART,new Q(zP.default.restart)),e.set(G.RESTART_SERVICE,new Q(zs,zP.default.restartService)),e.set(G.CATCHUP,new Q(BSe)),e.set(G.SYSTEM_INFORMATION,new Q(xz.default.systemInformation)),e.set(G.DELETE_AUDIT_LOGS_BEFORE,new Q(zs,wf.default.deleteAuditLogsBefore)),e.set(G.READ_AUDIT_LOG,new Q(Nz.default)),e.set(G.CREATE_AUTHENTICATION_TOKENS,new Q(_w)),e.set(G.REFRESH_OPERATION_TOKEN,new Q(Ew)),e.set(G.LOGIN,new Q(xC)),e.set(G.LOGOUT,new Q(BC)),e.set(G.GET_CONFIGURATION,new Q(JP.default.getConfiguration)),e.set(G.CUSTOM_FUNCTIONS_STATUS,new Q(Mt.default.customFunctionsStatus)),e.set(G.GET_CUSTOM_FUNCTIONS,new Q(Mt.default.getCustomFunctions)),e.set(G.GET_COMPONENT_FILE,new Q(Mt.default.getComponentFile)),e.set(G.GET_COMPONENTS,new Q(Mt.default.getComponents)),e.set(G.SET_COMPONENT_FILE,new Q(Mt.default.setComponentFile)),e.set(G.DROP_COMPONENT,new Q(Mt.default.dropComponent)),e.set(G.GET_CUSTOM_FUNCTION,new Q(Mt.default.getCustomFunction)),e.set(G.SET_CUSTOM_FUNCTION,new Q(Mt.default.setCustomFunction)),e.set(G.DROP_CUSTOM_FUNCTION,new Q(Mt.default.dropCustomFunction)),e.set(G.ADD_CUSTOM_FUNCTION_PROJECT,new Q(Mt.default.addComponent)),e.set(G.ADD_COMPONENT,new Q(Mt.default.addComponent)),e.set(G.DROP_CUSTOM_FUNCTION_PROJECT,new Q(Mt.default.dropCustomFunctionProject)),e.set(G.PACKAGE_CUSTOM_FUNCTION_PROJECT,new Q(Mt.default.packageComponent)),e.set(G.PACKAGE_COMPONENT,new Q(Mt.default.packageComponent)),e.set(G.DEPLOY_CUSTOM_FUNCTION_PROJECT,new Q(Mt.default.deployComponent)),e.set(G.DEPLOY_COMPONENT,new Q(Mt.default.deployComponent)),e.set(G.READ_TRANSACTION_LOG,new Q(QP.default.readTransactionLog)),e.set(G.DELETE_TRANSACTION_LOGS_BEFORE,new Q(zs,QP.default.deleteTransactionLogsBefore)),e.set(G.INSTALL_NODE_MODULES,new Q(XP.default.installModules)),e.set(G.AUDIT_NODE_MODULES,new Q(XP.default.auditModules)),e.set(G.GET_BACKUP,new Q(xi.default.getBackup)),e.set(G.CLEANUP_ORPHAN_BLOBS,new Q(xi.default.cleanupOrphanBlobs)),e.set(G.ADD_SSH_KEY,new Q(Mt.default.addSSHKey)),e.set(G.UPDATE_SSH_KEY,new Q(Mt.default.updateSSHKey)),e.set(G.DELETE_SSH_KEY,new Q(Mt.default.deleteSSHKey)),e.set(G.LIST_SSH_KEYS,new Q(Mt.default.listSSHKeys)),e.set(G.SET_SSH_KNOWN_HOSTS,new Q(Mt.default.setSSHKnownHosts)),e.set(G.GET_SSH_KNOWN_HOSTS,new Q(Mt.default.getSSHKnownHosts)),e.set(G.GET_ANALYTICS,new Q(JC)),e.set(G.LIST_METRICS,new Q(QC)),e.set(G.DESCRIBE_METRIC,new Q(XC)),e.set(G.GET_STATUS,new Q(nP)),e.set(G.SET_STATUS,new Q(sP)),e.set(G.CLEAR_STATUS,new Q(rP)),e}var Nf,TR,Xp,xi,Zp,wf,Nz,If,e_,Mt,t_,wz,Oz,YP,Cz,Pz,Dz,Lz,Mz,gR,WP,vz,RR,js,SR,zP,ZP,_u,Uz,xz,jP,JP,QP,XP,Bz,Fz,pu,Hz,kz,bz,yn,vSe,USe,xSe,Iz,WC=ce(()=>{Nf=w(an()),TR=w(nR()),Xp=w(BP()),xi=w(op()),Zp=w(za()),wf=w(Rl()),Nz=w(EO()),If=w(xn()),e_=w(Oh()),Mt=w(KC()),t_=w(j()),wz=w(yO()),Oz=w(Zd()),YP=w(jO()),Cz=w(aT()),Pz=w(XO()),Dz=w(ZO()),Lz=w(dT()),Mz=w(mT()),gR=w(hT()),WP=w(kP()),vz=w(tR()),RR=w($P());H();js=w(ge()),SR=w(ST()),zP=w(yc()),ZP=w(require("util")),_u=w(Bn()),Uz=w(Us()),xz=w(Zo()),jP=w(Tz());wd();FT();JP=w(gt()),QP=w(YT()),XP=w(Mp()),Bz=w(mi()),Fz=w(se());vr();pu=w(pn());Xd();eP();Hz=w(NP()),kz=w(yz());Sf();Az();({HTTP_STATUS_CODES:bz}=js.hdbErrors),yn=t_.default.loggerWithTag("operation"),vSe=ZP.promisify(Nf.default.search),USe=ZP.promisify(TR.default.evaluateSQL),xSe={[G.CREATE_ATTRIBUTE]:!0,[G.CREATE_TABLE]:!0,[G.CREATE_SCHEMA]:!0,[G.DROP_ATTRIBUTE]:!0,[G.DROP_TABLE]:!0,[G.DROP_SCHEMA]:!0};o(qz,"processLocalTransaction");Iz=FSe();Le.operation=eD;o(Gz,"chooseOperation");o($z,"getOperationFunction");(0,Bz._assignPackageExport)("operation",eD);o(eD,"operation");o(BSe,"catchup");o(zs,"executeJob");o(FSe,"initializeOperationFunctionMap")});var bR=M((XFe,Yz)=>{"use strict";var yR=(H(),v(W)),HSe=se(),r_=j(),{handleHDBError:tD,hdbErrors:AR}=ge(),{isMainThread:kSe}=require("worker_threads"),{Readable:qSe}=require("stream"),Vz=require("os"),GSe=require("util"),$Se=Sw(),VSe=GSe.promisify($Se.authorize),Kz=(WC(),v(YC)),{createGzip:KSe,constants:YSe}=require("zlib"),WSe=[yR.OPERATIONS_ENUM.CREATE_AUTHENTICATION_TOKENS,yR.OPERATIONS_ENUM.LOGIN,yR.OPERATIONS_ENUM.LOGOUT];function zSe(e){let t=`Found an uncaught exception with message: ${e.message}. ${Vz.EOL}Stack: ${e.stack} ${Vz.EOL}Terminating ${kSe?"HDB":"thread"}.`;console.error(t),r_.fatal(t),process.exit(1)}o(zSe,"handleServerUncaughtException");function jSe(e,t,r){if(r_[e.logLevel||"error"](e),e.statusCode)return typeof e.http_resp_msg!="object"?r.code(e.statusCode).send({error:e.http_resp_msg||e.message}):r.code(e.statusCode).send(e.http_resp_msg);let n=e.statusCode?e.statusCode:AR.HTTP_STATUS_CODES.INTERNAL_SERVER_ERROR;return typeof e=="string"?r.code(n).send({error:e}):r.code(n).send(e.message?{error:e.message}:e)}o(jSe,"serverErrorHandler");function JSe(e,t,r){if(!e.body||Object.keys(e.body).length===0||typeof e.body!="object"){let n=tD(new Error,"Invalid JSON.",AR.HTTP_STATUS_CODES.BAD_REQUEST);r(n,null)}if(HSe.isEmpty(e.body.operation)){let n=tD(new Error,"Request body must include an 'operation' property.",AR.HTTP_STATUS_CODES.BAD_REQUEST);r(n,null)}r()}o(JSe,"reqBodyValidationHandler");function QSe(e,t,r){let n;!WSe.includes(e.body.operation)||e.body.operation===yR.OPERATIONS_ENUM.CREATE_AUTHENTICATION_TOKENS&&!e.body.username&&!e.body.password?VSe(e,t).then(i=>{n=i,e.body.hdb_user=n,r()}).catch(i=>{r_.warn(i),r_.warn(`{"ip":"${e.socket.remoteAddress}", "error":"${i.stack}"`);let a=typeof i=="string"?{error:i}:{error:i.message};r(tD(i,a,AR.HTTP_STATUS_CODES.UNAUTHORIZED),null)}):(e.body.hdb_user=null,e.body.baseRequest=e.raw?.baseRequest,e.body.baseResponse=t.raw?.baseResponse,e.body.fastifyResponse=t,r())}o(QSe,"authHandler");async function XSe(e,t,r=!1){let n;try{e.body.bypass_auth&&delete e.body.bypass_auth,n=Kz.chooseOperation(e.body);let s=await Kz.processLocalTransaction(e,n);if(s instanceof qSe&&s.headers){for(let[i,a]of s.headers)t.header(i,a);e.headers["accept-encoding"]?.includes("gzip")&&(t.header("content-encoding","gzip"),s=s.pipe(KSe({level:YSe.Z_BEST_SPEED})))}return s}catch(s){throw r_.error(s),s}}o(XSe,"handlePostRequest");Yz.exports={authHandler:QSe,handlePostRequest:XSe,handleServerUncaughtException:zSe,serverErrorHandler:jSe,reqBodyValidationHandler:JSe}});var Jz=M((eHe,jz)=>{"use strict";var ZSe=require("fastify-plugin"),{handlePostRequest:Wz,authHandler:eTe,reqBodyValidationHandler:tTe}=bR();async function rTe(e){e.decorate("hdbCore",{preValidation:[tTe,eTe],request:o((t,r)=>zz(Wz(t,r)),"request"),requestWithoutAuthentication:o((t,r)=>zz(Wz(t,r,!0)),"requestWithoutAuthentication")})}o(rTe,"hdbCore");async function zz(e){if(e=await e,e?.[Symbol.asyncIterator]&&!e[Symbol.iterator]){let t=[];for await(let r of e)t.push(r);return t}return e}o(zz,"convertAsyncIterators");jz.exports=ZSe(rTe)});var Xz=M((nHe,Qz)=>{"use strict";var rHe=require("fs"),IR=oe();IR.initSync();var{CONFIG_PARAMS:rD}=(H(),v(W)),nTe=1024*1024*1024;function sTe(e){let t=IR.get(rD.HTTP_TIMEOUT),r=IR.get(rD.HTTP_KEEPALIVETIMEOUT);return{bodyLimit:nTe,connectionTimeout:t,keepAliveTimeout:r,return503OnClosing:!1,forceCloseConnections:!0,ignoreTrailingSlash:!0,maxParamLength:IR.get(rD.HTTP_MAXPARAMLENGTH)??1e3,https:e}}o(sTe,"getServerOptions");Qz.exports=sTe});var tj=M((iHe,ej)=>{"use strict";var nD=oe();nD.initSync();var{CONFIG_PARAMS:Zz}=(H(),v(W));function iTe(){let e=nD.get(Zz.HTTP_CORSACCESSLIST),t=nD.get(Zz.HTTP_CORS),r;return t&&(r={origin:!0,allowedHeaders:["Content-Type","Authorization","Accept"],credentials:!1},e&&e.length>0&&e[0]!==null&&e[0]!=="*"&&(r.origin=(n,s)=>s(null,e.indexOf(n)!==-1))),r}o(iTe,"getCORSOptions");ej.exports=iTe});var sj=M((aHe,nj)=>{"use strict";var rj=oe();rj.initSync();var oTe=(H(),v(W));function aTe(){return rj.get(oTe.CONFIG_PARAMS.HTTP_HEADERSTIMEOUT)??6e4}o(aTe,"getHeaderTimeoutConfig");nj.exports=aTe});var iD={};we(iD,{customFunctionsServer:()=>uTe,ready:()=>gj,start:()=>lTe});function lTe(e){let t=e.securePort>0;return{async handleFile(r,n,s,i){da||(da=Ej(t),Le.http((await da).server));let a=await da,c=(0,sD.dirname)(s),l=(0,sD.dirname)(n);if(l.startsWith("/")&&(l=l.slice(1)),!ij.has(c)){ij.add(c);try{a.register(fTe(c,l))}catch(u){if(u.message==="Root plugin has already booted")bt.warn(`Could not load root fastify route for ${s}, this may require a restart to install properly`);else throw u}}},ready:gj}}async function uTe(){try{bt.info("In Custom Functions Fastify server"+process.cwd()),bt.info(`Custom Functions Running with NODE_ENV set as: ${process.env.NODE_ENV}`),bt.debug(`Custom Functions server process ${process.pid} starting up.`),await dTe();let e=dj.get(U.HTTP_SECUREPORT)>0,t;try{t=da=await Ej(e)}catch(r){throw bt.error(`Custom Functions buildServer error: ${r}`),r}try{await t.ready()}catch(r){throw bt.error(`Custom Functions server.ready() error: ${r}`),r}t.server.cantCleanupProperly=!0}catch(e){bt.error(`Custom Functions ${process.pid} Error: ${e}`),bt.error(e),process.exit(1)}}async function dTe(){try{bt.info("Custom Functions starting configuration."),await fj.setUsersWithRolesCache(),bt.info("Custom Functions completed configuration.")}catch(e){bt.error(e)}}function fTe(e,t){return async function(r){try{bt.info("Custom Functions starting buildRoutes"),bt.trace("Loading fastify routes folder "+e),(0,oj.existsSync)(e)&&r.register(uj.default,s=>({dir:e,dirNameRoutePrefix:!1,options:{hdbCore:s.hdbCore,logger:bt.loggerWithTag("custom-function"),prefix:`/${t}`}})).after((s,i,a)=>{s?.message?bt.error(s.message):s&&bt.error(s),a()})}catch(n){bt.error(`Custom Functions errored buildRoutes: ${n}`)}}}async function Ej(e){bt.info("Custom Functions starting buildServer.");let t=(0,mj.default)(e),r=(0,aj.default)(t);r.server.headersTimeout=(0,pj.default)(),r.setErrorHandler(_j.serverErrorHandler);let n=(0,hj.default)();return n&&r.register(cj.default,n),r.register(function(s,i,a){s.setNotFoundHandler(function(c,l){r.server.emit("unhandled",c.raw,l.raw)}),a()}),r.register(lj.default),await r.register(cTe),await r.after(),Vm(r),bt.info("Custom Functions completed buildServer."),r}function gj(){if(da)return da.then?da.then(e=>e.ready()):da.ready()}var sD,oj,aj,cj,lj,uj,dj,bt,cTe,fj,mj,hj,pj,_j,da,ij,Sj=ce(()=>{sD=require("path"),oj=require("fs"),aj=w(require("fastify")),cj=w(require("@fastify/cors")),lj=w(fw()),uj=w(require("@fastify/autoload")),dj=w(oe());H();bt=w(j()),cTe=w(Jz()),fj=w(xn()),mj=w(Xz()),hj=w(tj()),pj=w(sj()),_j=w(bR());Uo();vr();ij=new Set;o(lTe,"start");o(uTe,"customFunctionsServer");o(dTe,"setUp");o(fTe,"buildRouteFolder");o(Ej,"buildServer");o(gj,"ready")});var oD={};we(oD,{start:()=>mTe});function mTe(e){return{handleDirectory(t,r){if(t==="/"){let n=(0,bj.default)(r,e);return e.server.http(async(s,i)=>{if(!s.isWebSocket)return new Promise(a=>n(s._nodeRequest,s._nodeResponse,()=>{a(i(s))}))}),!0}},handleFile(t,r,n){Rj||(Rj=!0,e.server.http(async(s,i)=>{if(!s.isWebSocket){let a=Tj.get(s.pathname);if(a)return{handlesHeaders:!0,body:(0,yj.default)(s,(0,Aj.realpathSync)(a))}}return i(s)},{runFirst:!0})),Tj.set(r,n)}}}var yj,Aj,bj,Tj,Rj,Ij=ce(()=>{yj=w(require("send")),Aj=require("fs"),bj=w(require("serve-static")),Tj=new Map;o(mTe,"start")});var aD={};we(aD,{start:()=>hTe});function hTe({override:e}){return{handleFile:o((t,r,n)=>{NR.default.debug(`Loading env file: ${n}`);for(let[s,i]of Object.entries((0,Nj.parse)(t))){if(process.env[s]!==void 0)if(NR.default.warn(`Environment variable conflict: ${s} from ${n} is already set on process.env`),e)NR.default.debug(`override option enabled. overriding environment variable: ${s}`);else continue;process.env[s]=i}},"handleFile")}}var Nj,NR,wj=ce(()=>{Nj=require("dotenv"),NR=w(j());o(hTe,"start")});var uD={};we(uD,{DataLoaderError:()=>Es,DataLoaderResult:()=>Of,EmptyFileError:()=>PR,FileParseError:()=>CR,InvalidPropertyTypeError:()=>DR,MissingRequiredPropertyError:()=>n_,RecordProcessingError:()=>s_,SystemDatabaseError:()=>LR,UnsupportedFileExtensionError:()=>OR,computeRecordHash:()=>lD,handleApplication:()=>ETe,loadDataFile:()=>Uj,suppressHandleApplicationWarning:()=>_Te});function lD(e){let t=Object.keys(e).sort(),r={};for(let s of t)r[s]=e[s];let n=JSON.stringify(r);return(0,Cj.createHash)("sha256").update(n).digest("hex")}function vj(e){return e.system&&e.system[cD]?e.system[cD]:wR||(wR=ze({database:"system",table:cD,attributes:[{name:"id",type:"string",isPrimaryKey:!0},{name:"hash",type:"string"}]}),wR)}async function pTe(e,t,r,n){try{let s=vj(n),i=e?`${e}:${t}:${r}`:`${t}:${r}`;return(await s.get(i))?.hash||null}catch(s){return Js.error?.(`Failed to get stored hash: ${s.message}`),null}}async function Oj(e,t,r,n,s){try{let i=vj(s),a=e?`${e}:${t}:${r}`:`${t}:${r}`;await i.put({id:a,hash:n})}catch(i){Js.error?.(`Failed to store hash: ${i.message}`)}}function ETe(e){if((0,Dj.getWorkerIndex)()!==0){Js.debug?.("Skipping data loader initialization on non-primary worker");return}e.handleEntry(t=>{t.entryType!=="file"||t.eventType==="unlink"||Uj(t,fn,He).then(r=>{Js.debug?.("Data loader processed file: %s: %s",(0,fa.basename)(t.absolutePath),r.message)})})}async function Uj({contents:e,absolutePath:t,stats:r},n,s){let i=(0,fa.extname)(t)||"unknown",a;try{if(i===".yaml"||i===".yml")a=(0,Pj.parseDocument)(e.toString()).toJSON();else if(i===".json")a=JSON.parse(e.toString());else throw new OR(t,i)}catch(f){throw f instanceof Es?f:new CR(t,f)}if(!a)throw new PR(t);let{database:c,table:l,records:u}=a;if(!l)throw new n_(t,"table");if(!u)throw new n_(t,"records");if(!Array.isArray(u))throw new DR(t,"records","array");let d=c?`${c}.${l}`:l;if(c?.toLowerCase()==="system")throw new LR(c,l);try{let f;if(c&&s[c]&&s[c][l])Js.debug?.(`Using existing table ${d} from database tables`),f=s[c][l];else if(n&&n[l])Js.debug?.(`Using existing table ${d} from global tables`),f=n[l];else{Js.debug?.(`Table ${d} not found, creating new table`);let R=[];if(u.length>0){let T=u[0];Object.keys(T).map(y=>{let N={name:y,type:typeof T[y]};return y==="id"&&(N.isPrimaryKey=!0),N}).forEach(y=>{R.push(y)})}f=await ze({database:c,table:l,attributes:R})}let m=u.length,h=0,p=0,E=0,g=100;for(let R=0;R<u.length;R+=g){let T=u.slice(R,R+g),y=[];for(let N of T)y.push(async()=>{try{let O=null,F=N.id;F!==void 0&&(O=await f.get(F));let Z=lD(N);if(!O){h++;let $=await f.put(N);return await Oj(c,l,F,Z,s),$}let q=await pTe(c,l,F,s);if(!q)return E++,Promise.resolve({inserted:0,updated:0});let Y={};for(let $ of Object.keys(N))$ in O&&(Y[$]=O[$]);return lD(Y)!==q?(E++,Promise.resolve({inserted:0,updated:0})):Z!==q?(p++,await f.patch(F,N),await Oj(c,l,F,Z,s),{updated:1}):(E++,Promise.resolve({inserted:0,updated:0}))}catch(O){if(O instanceof Es)Js.error?.(`Record processing error: ${O.message}`);else{let F=new s_(d,O);Js.error?.(`Record processing error: ${F.message}`)}return Promise.resolve({inserted:0,updated:0,error:O.message})}});await Promise.all(y.map(N=>N()))}if(h>0||p>0){let R=`Loaded ${h} new and updated ${p} records in ${d}`;return E>0&&(R+=` (${E} records skipped)`),Js.info?.(R),new Of(t,c,l,"success",h+p,R)}else if(E>0){let R=`All ${E} records in ${d} already up-to-date`;return Js.info?.(R),new Of(t,c,l,"skipped",m,R)}else{let R=`No records to process in ${d}`;return Js.info?.(R),new Of(t,c,l,"success",0,R)}}catch(f){throw f instanceof Es?f:new s_(d,f)}}var fa,Cj,Pj,Dj,ma,Lj,Mj,Js,cD,wR,_Te,Es,OR,CR,PR,n_,DR,LR,s_,Of,xj=ce(()=>{fa=require("node:path"),Cj=require("node:crypto"),Pj=require("yaml");Pe();Dj=w(rt()),ma=w(Vr()),Lj=w(ge()),Mj=w(j()),Js=Mj.default.forComponent("dataLoader"),cD="hdb_dataloader_hash";o(lD,"computeRecordHash");o(vj,"getHashTrackingTable");o(pTe,"getStoredHash");o(Oj,"storeHash");_Te=!0;o(ETe,"handleApplication");o(Uj,"loadDataFile");Es=class extends Lj.ClientError{static{o(this,"DataLoaderError")}constructor(t,r=ma.HTTP_STATUS_CODES.BAD_REQUEST){super(t,r),this.name="DataLoaderError"}},OR=class extends Es{static{o(this,"UnsupportedFileExtensionError")}constructor(t,r){super(`Unsupported file extension in ${(0,fa.basename)(t)}: ${r}. Only YAML and JSON files are supported.`,ma.HTTP_STATUS_CODES.BAD_REQUEST),this.name="UnsupportedFileExtensionError"}},CR=class extends Es{static{o(this,"FileParseError")}constructor(t,r){super(`Failed to parse data file ${(0,fa.basename)(t)}: ${r.message}`,ma.HTTP_STATUS_CODES.BAD_REQUEST),this.name="FileParseError"}},PR=class extends Es{static{o(this,"EmptyFileError")}constructor(t){super(`Data file ${(0,fa.basename)(t)} is empty or invalid`,ma.HTTP_STATUS_CODES.BAD_REQUEST),this.name="EmptyFileError"}},n_=class extends Es{static{o(this,"MissingRequiredPropertyError")}constructor(t,r){super(`Data file ${(0,fa.basename)(t)} is missing required "${r}" property`,ma.HTTP_STATUS_CODES.BAD_REQUEST),this.name="MissingRequiredPropertyError"}},DR=class extends Es{static{o(this,"InvalidPropertyTypeError")}constructor(t,r,n){super(`Data file ${(0,fa.basename)(t)} has invalid "${r}" property, expected ${n}`,ma.HTTP_STATUS_CODES.BAD_REQUEST),this.name="InvalidPropertyTypeError"}},LR=class extends Es{static{o(this,"SystemDatabaseError")}constructor(t,r){super(`Cannot load data into system database: ${t}.${r}`,ma.HTTP_STATUS_CODES.FORBIDDEN),this.name="SystemDatabaseError"}},s_=class extends Es{static{o(this,"RecordProcessingError")}constructor(t,r){super(`Failed to process record in ${t}: ${r.message}`,ma.HTTP_STATUS_CODES.INTERNAL_SERVER_ERROR),this.name="RecordProcessingError"}},Of=class{static{o(this,"DataLoaderResult")}#e;#t;#r;#n;#s;#i;constructor(t,r,n,s,i,a){this.#e=t,this.#t=r||"unknown",this.#r=n||"unknown",this.#n=s,this.#s=i,this.#i=a}get filePath(){return this.#e}get database(){return this.#t}get table(){return this.#r}get status(){return this.#n}get count(){return this.#s}get message(){return this.#i}toJSON(){return{filePath:this.#e,database:this.#t,table:this.#r,status:this.#n,count:this.#s,message:this.#i}}}});var fD=M((SHe,Bj)=>{"use strict";var i_=oe();i_.initSync();var Cf=require("fs-extra"),dD=require("path"),Pf=(H(),v(W)),gTe=require("crypto"),STe=require("uuid").v4;Bj.exports=TTe;function TTe(){if(i_.getHdbBasePath()!==void 0){let e=dD.join(i_.getHdbBasePath(),Pf.LICENSE_KEY_DIR_NAME,Pf.JWT_ENUM.JWT_PRIVATE_KEY_NAME),t=dD.join(i_.getHdbBasePath(),Pf.LICENSE_KEY_DIR_NAME,Pf.JWT_ENUM.JWT_PUBLIC_KEY_NAME),r=dD.join(i_.getHdbBasePath(),Pf.LICENSE_KEY_DIR_NAME,Pf.JWT_ENUM.JWT_PASSPHRASE_NAME);try{Cf.accessSync(r),Cf.accessSync(e),Cf.accessSync(t)}catch(n){if(n.code==="ENOENT"){let s=STe(),i=gTe.generateKeyPairSync("rsa",{modulusLength:4096,publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs8",format:"pem",cipher:"aes-256-cbc",passphrase:s}});Cf.writeFileSync(r,s),Cf.writeFileSync(e,i.privateKey),Cf.writeFileSync(t,i.publicKey)}else throw n}}}o(TTe,"checkJWTTokenExist")});var Hj=M((RHe,Fj)=>{"use strict";var mD=class{static{o(this,"HdbInfoInsertObject")}constructor(t,r,n){this.info_id=t,this.data_version_num=r,this.hdb_version_num=n}};Fj.exports={HdbInfoInsertObject:mD}});var Gj=M((AHe,qj)=>{"use strict";var kj=(H(),v(W)),hD=class{static{o(this,"UpgradeObject")}constructor(t,r){this[kj.UPGRADE_JSON_FIELD_NAMES_ENUM.DATA_VERSION]=t,this[kj.UPGRADE_JSON_FIELD_NAMES_ENUM.UPGRADE_VERSION]=r}};qj.exports={UpgradeObject:hD}});var MR=M((IHe,Vj)=>{"use strict";var Qs=require("prompt"),Df=require("chalk"),$j=j(),Bi=require("os"),pD=qa(),_D=["yes","y"];async function RTe(e){let t=`${Bi.EOL}`+Df.bold.green("Your current HarperDB version requires that we complete an update process.")+`${Bi.EOL}If a backup of your data has not been created, we recommend you cancel this process and backup before proceeding.${Bi.EOL}${Bi.EOL}You can read more about the changes in this upgrade at https://harperdb.io/developers/release-notes/${Bi.EOL}`;Qs.override=pD(["CONFIRM_UPGRADE"]),Qs.start(),Qs.message=t;let r={properties:{CONFIRM_UPGRADE:{description:Df.magenta(`${Bi.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 Qs.get([r])}catch(s){return $j.error("There was an error when prompting user about an upgrade."),$j.error(s),!1}return _D.includes(n.CONFIRM_UPGRADE)}o(RTe,"forceUpdatePrompt");async function yTe(e){let t=`${Bi.EOL}`+Df.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.${Bi.EOL}`);Qs.override=pD(["CONFIRM_DOWNGRADE"]),Qs.start(),Qs.message=t;let r={properties:{CONFIRM_DOWNGRADE:{description:Df.magenta(`${Bi.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 Qs.get([r]);return _D.includes(n.CONFIRM_DOWNGRADE)}o(yTe,"forceDowngradePrompt");async function ATe(){let e=`${Bi.EOL}`+Df.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");Qs.override=pD(["GENERATE_CERTS"]),Qs.start(),Qs.message=e;let t={properties:{GENERATE_CERTS:{description:Df.magenta(`${Bi.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 Qs.get([t]);return _D.includes(r.GENERATE_CERTS)}o(ATe,"upgradeCertsPrompt");Vj.exports={forceUpdatePrompt:RTe,forceDowngradePrompt:yTe,upgradeCertsPrompt:ATe}});var gD=M((wHe,Kj)=>{"use strict";var ED=class{static{o(this,"UpgradeDirective")}constructor(t){this.version=t,this.sync_functions=[],this.async_functions=[]}};Kj.exports=ED});var Wj=M((MHe,Yj)=>{"use strict";var bTe=se(),ITe=gt(),CHe=j(),PHe=require("path"),DHe=require("fs"),LHe=(H(),v(W));Yj.exports={getOldPropsValue:NTe};function NTe(e,t,r=!1){let n=t.getRaw(e);return bTe.isNotEmptyAndHasValue(n)?n:r?ITe.getDefaultConfig(e):""}o(NTe,"getOldPropsValue")});var Qj=M((UHe,Jj)=>{"use strict";var Cc=require("path"),Pc=require("fs-extra"),wTe=require("properties-reader"),OTe=gD(),Rr=j(),{getOldPropsValue:It}=Wj(),{HDB_SETTINGS_NAMES:ye,CONFIG_PARAMS:Eu}=(H(),v(W)),gu=gt(),vR=oe(),zj=se(),_o=(H(),v(W)),SD=new OTe("3.1.0"),jj=[];function CTe(){let e=wTe(vR.get(ye.SETTINGS_PATH_KEY)),t="Updating settings file for version 3.1.0";console.log(t),Rr.info(t);let r=` ;Settings for the HarperDB process.
|
|
34
|
+
`);throw n[1]?EP(r,`Invalid SQL at: ${n[1]}. Please ensure your SQL is valid. Try adding backticks to reserved words and schema table references.`,gP.BAD_REQUEST):EP(r,"We had trouble parsing your request. Please ensure your SQL is valid. Try adding backticks to reserved words and schema table references.",gP.BAD_REQUEST)}return t}o(pW,"convertSQLToAST");function _W(e,t,r){try{let n=KEe;if(!e.bypass_auth&&!t.permissions_checked){let i=hW(e,t);if(i&&i.length>0)return r(GEe,i)}let s={statement:t.ast.statements[0],hdb_user:e.hdb_user};switch(t.variant){case Wp.VALID_SQL_OPS_ENUM.SELECT:n=vEe,s=t.ast.statements[0];break;case Wp.VALID_SQL_OPS_ENUM.INSERT:n=YEe;break;case Wp.VALID_SQL_OPS_ENUM.UPDATE:n=xEe;break;case Wp.VALID_SQL_OPS_ENUM.DELETE:n=BEe;break;default:throw new Error(`unsupported SQL type ${t.variant} in SQL: ${e}`)}n(s,(i,a)=>{if(i){r(i);return}r(null,a)})}catch(n){return r(n)}}o(_W,"processAST");function KEe(e,t){rR.info(e),t("unknown sql statement")}o(KEe,"nullFunction");function YEe({statement:e,hdb_user:t},r){let n=e.into,s={schema:n.databaseid,table:n.tableid,operation:"insert",hdb_user:t},i=e.columns.map(a=>a.columnid);try{s.records=WEe(i,e.values)}catch(a){return r(a)}MEe(s,(a,c)=>{if(a)return r(a);try{delete c.new_attributes,delete c.txn_time}catch(l){rR.error(`Error delete new_attributes from insert response: ${l}`)}r(null,c)})}o(YEe,"convertInsert");function WEe(e,t){try{return t.map(r=>{if(e.length!==r.length)throw"number of values do not match number of columns in insert";let n={};return r.forEach((s,i)=>{if(s.columnid)throw"cannot use a column in insert value";"value"in s?n[e[i]]=s.value:n[e[i]]=wc.compile(`SELECT ${s.toString()} AS [${Wp.FUNC_VAL}] FROM ?`)}),n})}catch(r){throw rR.error(r),new Error($Ee)}}o(WEe,"createDataObjects")});var IP=M((SFe,RW)=>{var aR=require("clone"),cR=lt(),zEe=se(),iR=(H(),v(W)),EFe=j(),TP=require("fs"),yP=require("joi"),{string:oR}=yP.types(),{hdbErrors:jEe,handleHDBError:sR}=ge(),{HDB_ERROR_MSGS:gFe,HTTP_STATUS_CODES:RP}=jEe,{commonValidators:Rf}=Ji(),gW=" is required",JEe=["insert","update","upsert"],AP={database:{presence:!1,format:Rf.schema_format,length:Rf.schema_length},schema:{presence:!1,format:Rf.schema_format,length:Rf.schema_length},table:{presence:!0,format:Rf.schema_format,length:Rf.schema_length},action:{inclusion:{within:JEe,message:"is required and must be either insert, update, or upsert"}},file_path:{},csv_url:{url:{allowLocal:!0}},data:{},passthrough_headers:{}},QEe={schema:oR.required(),table:oR.required(),action:oR.valid("insert","update","upsert")},{AWS_ACCESS_KEY:XEe,AWS_SECRET:ZEe,AWS_BUCKET:ege,AWS_FILE_KEY:tge,REGION:rge}=iR.S3_BUCKET_AUTH_KEYS,nge={s3:{presence:!0},[`s3.${XEe}`]:{presence:!0,type:"String"},[`s3.${ZEe}`]:{presence:!0,type:"String"},[`s3.${ege}`]:{presence:!0,type:"String"},[`s3.${tge}`]:{presence:!0,type:"String",hasValidFileExt:[".csv",".json"]},[`s3.${rge}`]:{presence:!0,type:"String"}},SW=aR(AP);SW.data.presence={message:gW};var TW=aR(AP);TW.file_path.presence={message:gW};var sge=Object.assign(aR(AP),nge),bP=aR(QEe);bP.csv_url=oR.uri().messages({"string.uri":"'csv_url' must be a valid url"}).required();bP.passthrough_headers=yP.object();function ige(e){let t=cR.validateObject(e,SW);return lR(e,t)}o(ige,"dataObject");function oge(e){let t=cR.validateBySchema(e,yP.object(bP));return lR(e,t)}o(oge,"urlObject");function age(e){let t=cR.validateObject(e,TW);return lR(e,t)}o(age,"fileObject");function cge(e){let t=cR.validateObject(e,sge);return lR(e,t)}o(cge,"s3FileObject");function lR(e,t){if(!t){let r=zEe.checkGlobalSchemaTable(e.schema,e.table);if(r)return sR(new Error,r,RP.BAD_REQUEST);if(e.operation===iR.OPERATIONS_ENUM.CSV_FILE_LOAD)try{TP.accessSync(e.file_path,TP.constants.R_OK|TP.constants.F_OK)}catch(n){return n.code===iR.NODE_ERROR_CODES.ENOENT?sR(n,`No such file or directory ${n.path}`,RP.BAD_REQUEST):n.code===iR.NODE_ERROR_CODES.EACCES?sR(n,`Permission denied ${n.path}`,RP.BAD_REQUEST):sR(n)}}return t}o(lR,"postValidateChecks");RW.exports={dataObject:ige,urlObject:oge,fileObject:age,s3FileObject:cge}});var NP=M((RFe,yW)=>{"use strict";var zp=j(),uR=(H(),v(W));async function lge(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===uR.OPERATIONS_ENUM.INSERT||t.operation===uR.OPERATIONS_ENUM.UPDATE||t.operation===uR.OPERATIONS_ENUM.UPSERT?(delete s.new_attributes,delete s.txn_time):t.operation===uR.OPERATIONS_ENUM.DELETE&&delete s.txn_time,s}catch(i){throw i.message&&typeof i.message=="string"&&i.message.includes("already exists")?(zp.info(i.message),i):i.http_resp_msg?(zp.error(`Error calling operation: ${e.name}`),zp.error(i.http_resp_msg),i):(zp.error(`Error calling operation: ${e.name}`),zp.error(i),i)}}o(lge,"callOperationFunctionAsAwait");yW.exports={callOperationFunctionAsAwait:lge}});var wP=M((AFe,bW)=>{"use strict";var{S3:uge,GetObjectCommand:dge}=require("@aws-sdk/client-s3");bW.exports={getFileStreamFromS3:fge,getS3AuthObj:AW};async function fge(e){let{s3:t}=e,r={Bucket:t.bucket,Key:t.key};return(await AW(t.aws_access_key_id,t.aws_secret_access_key,t.region).send(new dge(r))).Body}o(fge,"getFileStreamFromS3");function AW(e,t,r){return new uge({credentials:{accessKeyId:e,secretAccessKey:t},region:r})}o(AW,"getS3AuthObj")});var NW=M((IFe,IW)=>{"use strict";var OP=class{static{o(this,"BulkLoadFileObject")}constructor(t,r,n,s,i,a,c=null){this.op=t,this.action=r,this.schema=n,this.table=s,this.file_path=i,this.file_type=a,this.role_perms=c}},CP=class{static{o(this,"BulkLoadDataObject")}constructor(t,r,n,s){this.action=t,this.schema=r,this.table=n,this.data=s}};IW.exports={BulkLoadFileObject:OP,BulkLoadDataObject:CP}});var DP=M((wFe,wW)=>{"use strict";var PP=class{static{o(this,"ClusteringOriginObject")}constructor(t,r,n){this.timestamp=t,this.user=r,this.node_name=n}};wW.exports=PP});var BP=M((MFe,VW)=>{"use strict";var dR=Bn(),mR=IP(),mge=require("needle"),Mi=(H(),v(W)),CFe=Ot(),yf=se(),{handleHDBError:Qt,hdbErrors:xW}=ge(),{HTTP_STATUS_CODES:en,HDB_ERROR_MSGS:wr,CHECK_LOGS_WRAPPER:fu}=xW,Af=j(),LP=require("papaparse");yf.promisifyPapaParse();var vi=require("fs-extra"),hge=require("path"),{chain:OW}=require("stream-chain"),CW=require("stream-json/streamers/StreamArray"),PW=require("stream-json/utils/Batch"),DW=require("stream-chain/utils/comp"),{finished:LW}=require("stream"),pge=oe(),BW=NP(),_ge=wP(),{BulkLoadFileObject:vP,BulkLoadDataObject:Ege}=NW(),UP=cP(),{verifyBulkLoadAttributePerms:FW}=tR(),PFe=DP(),DFe=sr(),LFe=Zi(),{databases:gge}=(Pe(),v(ut)),{coerceType:Sge}=(hR(),v(KW)),MW="No records parsed from csv file.",du=`${pge.get("HDB_ROOT")}/tmp`,{schemaRegex:Tge}=Ji(),vW=1024*1024*2,UW=5e3,Rge={"text/csv":!0,"application/octet-stream":!0,"text/plain":!0,"application/vnd.ms-excel":!0};VW.exports={csvDataLoad:yge,csvURLLoad:Age,csvFileLoad:bge,importFromS3:Ige};async function yge(e,t){let r=mR.dataObject(e);if(r)throw Qt(r,r.message,en.BAD_REQUEST,void 0,void 0,!0);let n={};try{let s=qW(e.schema,e.table),i=LP.parse(e.data,{header:!0,skipEmptyLines:!0,transform:MP.bind(null,s),dynamicTyping:!1}),a=new UP;e.hdb_user&&e.hdb_user?.role&&e.hdb_user?.role?.permission&&e.hdb_user?.role?.permission?.super_user!==!0&&FW(e.hdb_user?.role?.permission,this.job_operation_function.name,e.action,e.schema,e.table,i.meta.fields,a);let c=a.getPermsResponse();if(c)throw Qt(new Error,c,en.BAD_REQUEST,void 0,void 0,!0);let l=new Ege(e.action,e.schema,e.table,i.data);return n=await BW.callOperationFunctionAsAwait(GW,l,null),n.message===MW?MW:$W(n.records,n.number_written)}catch(s){throw mu(s)}}o(yge,"csvDataLoad");async function Age(e){let t=mR.urlObject(e);if(t)throw Qt(t,t.message,en.BAD_REQUEST,void 0,void 0,!0);let r=`${Date.now()}.csv`,n=`${du}/${r}`;try{await Nge(e,r)}catch(s){throw Af.error(wr.DOWNLOAD_FILE_ERR(r)+" - "+s),Qt(s,fu(wr.DOWNLOAD_FILE_ERR(r)))}try{let s=new vP(this.job_operation_function.name,e.action,e.schema,e.table,n,Mi.VALID_S3_FILE_TYPES.CSV,e.hdb_user?.role?.permission),i=await xP(s);return await fR(n),i}catch(s){throw await fR(n),mu(s)}}o(Age,"csvURLLoad");async function bge(e){let t=mR.fileObject(e);if(t)throw Qt(t,t.message,en.BAD_REQUEST,void 0,void 0,!0);let r=new vP(this.job_operation_function.name,e.action,e.schema,e.table,e.file_path,Mi.VALID_S3_FILE_TYPES.CSV,e.hdb_user?.role?.permission);try{return await xP(r)}catch(n){throw mu(n)}}o(bge,"csvFileLoad");async function Ige(e){let t=mR.s3FileObject(e);if(t)throw Qt(t,t.message,en.BAD_REQUEST,void 0,void 0,!0);let r;try{let n=hge.extname(e.s3.key),s=`${Date.now()}${n}`;r=`${du}/${s}`;let i=new vP(this.job_operation_function.name,e.action,e.schema,e.table,r,n,e.hdb_user?.role?.permission);await wge(s,e);let a=await xP(i);return await fR(r),a}catch(n){throw await fR(r),mu(n)}}o(Ige,"importFromS3");async function Nge(e,t){let r;try{let n=e.passthrough_headers?{headers:e.passthrough_headers}:void 0;r=await mge("get",e.csv_url,n)}catch(n){let s=`Error downloading CSV file from ${e.csv_url}, status code: ${n.statusCode}. Check the log for more information.`;throw Qt(n,s,n.statusCode,Mi.LOG_LEVELS.ERROR,"Error downloading CSV file - "+n)}Cge(r,e.csv_url),await Oge(t,r.raw)}o(Nge,"downloadCSVFile");async function wge(e,t){try{let r=`${du}/${e}`;await vi.mkdirp(du),await vi.writeFile(`${du}/${e}`,"",{flag:"a+"});let n=await vi.createWriteStream(r),s=await _ge.getFileStreamFromS3(t);await new Promise((i,a)=>{s.on("error",function(c){a(c)}),s.pipe(n).on("error",function(c){a(c)}).on("close",function(){Af.info(`${t.s3.key} successfully downloaded to ${r}`),i()})})}catch(r){throw Af.error(wr.S3_DOWNLOAD_ERR+" - "+r),Qt(r,fu(wr.S3_DOWNLOAD_ERR))}}o(wge,"downloadFileFromS3");async function Oge(e,t){try{await vi.mkdirp(du),await vi.writeFile(`${du}/${e}`,t)}catch(r){throw Af.error(wr.WRITE_TEMP_FILE_ERR),Qt(r,fu(wr.DEFAULT_BULK_LOAD_ERR))}}o(Oge,"writeFileToTempFolder");async function fR(e){if(e)try{await vi.access(e),await vi.unlink(e)}catch{Af.warn(`could not delete temp csv file at ${e}, file does not exist`)}}o(fR,"deleteTempFile");function Cge(e,t){if(e.statusCode!==xW.HTTP_STATUS_CODES.OK)throw Qt(new Error,`CSV Load failed from URL: ${t}, status code: ${e.statusCode}, message: ${e.statusMessage}`,en.BAD_REQUEST);if(!Rge[e.headers["content-type"]])throw Qt(new Error,`CSV Load failed from URL: ${t}, unsupported content type: ${e.headers["content-type"]}`,en.BAD_REQUEST);if(!e.raw)throw Qt(new Error,`CSV Load failed from URL: ${t}, no csv found at url`,en.BAD_REQUEST)}o(Cge,"validateURLResponse");async function xP(e){try{let t;switch(e.file_type){case Mi.VALID_S3_FILE_TYPES.CSV:t=await Pge(e);break;case Mi.VALID_S3_FILE_TYPES.JSON:t=await Dge(e);break;default:throw Qt(new Error,wr.DEFAULT_BULK_LOAD_ERR,en.BAD_REQUEST,Mi.LOG_LEVELS.ERROR,wr.INVALID_FILE_EXT_ERR(e))}return $W(t.records,t.number_written)}catch(t){throw mu(t)}}o(xP,"fileLoad");async function HW(e,t,r,n,s){let i=n.data?n.data:n;if(i.length===0)return;s&&s.pause();let a={operation:e.action,schema:e.schema,table:e.table,records:i};try{let{attributes:c}=await dR.validation(a);e.role_perms&&e.role_perms.super_user!==!0&&FW(e.role_perms,e.op,e.action,e.schema,e.table,c,t),s&&s.resume()}catch(c){let l=Qt(c);r(l)}}o(HW,"validateChunk");async function kW(e,t,r,n,s){let i=n.data?n.data:n;if(i.length===0)return;yf.autoCastJSONDeep(i),s&&s.pause();let a=n.meta?n.meta.fields:null;if(a)i.forEach(c=>{!yf.isEmpty(c)&&!yf.isEmpty(c.__parsed_extra)&&delete c.__parsed_extra});else{let c=new Set;i.forEach(l=>{Object.keys(l).forEach(u=>c.add(u))}),a=[...c]}try{let c={schema:e.schema,table:e.table,action:e.action,data:i},l=await BW.callOperationFunctionAsAwait(GW,c,null);t.records+=l.records,t.number_written+=l.number_written,s&&s.resume()}catch(c){let l=Qt(c,fu(wr.INSERT_CSV_ERR),en.INTERNAL_SERVER_ERROR,Mi.LOG_LEVELS.ERROR,wr.INSERT_CSV_ERR+" - "+c);r(l)}}o(kW,"insertChunk");async function Pge(e){let t={records:0,number_written:0},r=qW(e.schema,e.table);try{let n=new UP,s=vi.createReadStream(e.file_path,{highWaterMark:vW});s.setEncoding("utf8"),await LP.parsePromise(s,HW.bind(null,e,n),MP.bind(null,r));let i=n.getPermsResponse();if(i)throw Qt(new Error,i,en.BAD_REQUEST);return s=vi.createReadStream(e.file_path,{highWaterMark:vW}),s.setEncoding("utf8"),await LP.parsePromise(s,kW.bind(null,e,t),MP.bind(null,r)),s.destroy(),t}catch(n){throw Qt(n,fu(wr.PAPA_PARSE_ERR),en.INTERNAL_SERVER_ERROR,Mi.LOG_LEVELS.ERROR,wr.PAPA_PARSE_ERR+n)}}o(Pge,"callPapaParse");function qW(e,t){let r=gge[e][t].attributes,n=new Map;for(let s of r)s.type&&!s.computed&&!s.relationship&&n.set(s.name,i=>Sge(i,s));return n}o(qW,"createTransformMap");function MP(e,t,r){let n=e.get(r);return n?n(t):yf.autoCast(t)}o(MP,"typeFunction");async function Dge(e){let t={records:0,number_written:0},r=o(n=>{throw n},"throwErr");try{let n=new UP,s=OW([vi.createReadStream(e.file_path,{encoding:"utf-8"}),CW.withParser(),c=>c.value,new PW({batchSize:UW}),DW(async c=>{await HW(e,n,r,c)})]);await new Promise((c,l)=>{LW(s,u=>{u?l(u):c()}),s.resume()});let i=n.getPermsResponse();if(i)throw Qt(new Error,i,en.BAD_REQUEST);let a=OW([vi.createReadStream(e.file_path,{encoding:"utf-8"}),CW.withParser(),c=>c.value,new PW({batchSize:UW}),DW(async c=>{await kW(e,t,r,c)})]);return await new Promise((c,l)=>{LW(a,u=>{u?l(u):c()}),a.resume()}),t}catch(n){throw Qt(n,fu(wr.INSERT_JSON_ERR),en.INTERNAL_SERVER_ERROR,Mi.LOG_LEVELS.ERROR,wr.INSERT_JSON_ERR+n)}}o(Dge,"insertJson");async function GW(e){let t={};try{e.data&&e.data.length>0&&Lge(e.data[0])?t=await Mge(e.data,e.schema,e.table,e.action):(t.message="No records parsed from csv file.",Af.info(t.message))}catch(r){throw mu(r)}return t}o(GW,"callBulkFileLoad");function Lge(e){let t=Object.keys(e);for(let r of t)if(!Tge.test(r))throw new Error(`Invalid column name '${r}', cancelling load operation`);return!0}o(Lge,"validateColumnNames");async function Mge(e,t,r,n){n||(n="insert");let s={operation:n,schema:t,table:r,records:e},i;switch(n){case"insert":i=dR.insert;break;case"update":i=dR.update;break;case"upsert":i=dR.upsert;break;default:throw Qt(new Error,wr.INVALID_ACTION_PARAM_ERR(n),en.BAD_REQUEST,Mi.LOG_LEVELS.ERROR,wr.INVALID_ACTION_PARAM_ERR(n))}try{let a=await i(s),c;switch(n){case"insert":c=a.inserted_hashes;break;case"update":c=a.update_hashes;break;case"upsert":c=a.upserted_hashes;break;default:break}if(Array.isArray(a.skipped_hashes)&&a.skipped_hashes.length>0){let d=global.hdb_schema[t][r].hash_attribute,f=e.length;for(;f--;)a.skipped_hashes.indexOf(e[f][d])>=0&&e.splice(f,1)}let l=yf.isEmptyOrZeroLength(c)?0:c.length;return{records:e.length,number_written:l,new_attributes:a.new_attributes}}catch(a){throw mu(a)}}o(Mge,"bulkFileLoad");function $W(e,t){return`successfully loaded ${t} of ${e} records`}o($W,"buildResponseMsg");function mu(e){return Qt(e,fu(wr.DEFAULT_BULK_LOAD_ERR),en.INTERNAL_SERVER_ERROR,Mi.LOG_LEVELS.ERROR,wr.DEFAULT_BULK_LOAD_ERR+" - "+e)}o(mu,"buildTopLevelErrMsg")});var kP=M((UFe,ZW)=>{"use strict";var HP=an(),vge=wP(),{AsyncParser:Uge}=require("json2csv"),pR=require("stream"),_s=se(),FP=require("fs-extra"),xge=require("path"),Ws=j(),{promisify:zW}=require("util"),jp=se(),{handleHDBError:Sr,hdbErrors:Bge}=ge(),{HDB_ERROR_MSGS:Yn,HTTP_STATUS_CODES:Tr}=Bge,{streamAsJSON:Fge}=(pb(),v(bU)),{Upload:Hge}=require("@aws-sdk/lib-storage"),{toCsvStream:kge}=(Uo(),v(VU)),YW=["search_by_value","search_by_hash","sql","search_by_conditions"],WW=["json","csv"],jW="json",JW="csv",qge="Successfully exported JSON locally.",Gge="Successfully exported CSV locally.",$ge=1e3,Vge=HP.searchByHash,Kge=HP.searchByValue,Yge=zW(pR.finished);ZW.exports={export_to_s3:Jge,export_local:Wge};async function Wge(e){Ws.trace(`export_local request to path: ${e.path}, filename: ${e.filename}, format: ${e.format}`);let t=QW(e);if(!_s.isEmpty(t))throw Ws.error(t),Sr(new Error,t,Tr.BAD_REQUEST,void 0,void 0,!0);if(_s.isEmpty(e.path))throw Ws.error(Yn.MISSING_VALUE("path")),Sr(new Error,Yn.MISSING_VALUE("path"),Tr.BAD_REQUEST,void 0,void 0,!0);let r=(_s.isEmpty(e.filename)?new Date().getTime():e.filename)+"."+e.format;e.path.endsWith(xge.sep)&&(e.path=e.path.substring(0,e.path.length-1));let n=_s.buildFolderPath(e.path,r);await zge(e.path);let s=await XW(e);return await jge(n,e.format,s)}o(Wge,"export_local");async function zge(e){if(Ws.trace("in confirmPath"),_s.isEmptyOrZeroLength(e))throw Sr(new Error,`Invalid path: ${e}`,Tr.BAD_REQUEST,void 0,void 0,!0);let t;try{t=await FP.stat(e)}catch(r){let n;throw r.code==="ENOENT"?n=`path '${e}' does not exist`:r.code==="EACCES"?n=`access to path '${e}' is denied`:n=r.message,Ws.error(n),Sr(new Error,n,Tr.BAD_REQUEST,void 0,void 0,!0)}if(!t.isDirectory()){let r=`path '${e}' is not a directory, please supply a valid folder path`;throw Ws.error(r),Sr(new Error,r,Tr.BAD_REQUEST,void 0,void 0,!0)}return!0}o(zge,"confirmPath");async function jge(e,t,r){if(Ws.trace("in saveToLocal"),jp.isEmptyOrZeroLength(e))throw Sr(new Error,Yn.INVALID_VALUE("file_path"),Tr.BAD_REQUEST,void 0,void 0,!0);if(jp.isEmptyOrZeroLength(t))throw Sr(new Error,Yn.INVALID_VALUE("Source format"),Tr.BAD_REQUEST,void 0,void 0,!0);if(jp.isEmpty(r))throw Sr(new Error,Yn.NOT_FOUND("Data"),Tr.BAD_REQUEST,void 0,void 0,!0);if(t===jW){let n=FP.createWriteStream(e);return Fge(r).pipe(n),await Yge(n),{message:qge,path:e}}else if(t===JW){let n=FP.createWriteStream(e),s=pR.Readable.from(r),i={},a=r.getColumns?.();a&&(i.fields=a.map(d=>({label:d,value:d})));let c={objectMode:!0};return await new Uge(i,c).fromInput(s).toOutput(n).promise(!1),{message:Gge,path:e}}throw Sr(new Error,Yn.INVALID_VALUE("format"),Tr.BAD_REQUEST)}o(jge,"saveToLocal");async function Jge(e){if(!e.s3||Object.keys(e.s3).length===0)throw Sr(new Error,Yn.MISSING_VALUE("S3 object"),Tr.BAD_REQUEST);if(_s.isEmptyOrZeroLength(e.s3.aws_access_key_id))throw Sr(new Error,Yn.MISSING_VALUE("aws_access_key_id"),Tr.BAD_REQUEST);if(_s.isEmptyOrZeroLength(e.s3.aws_secret_access_key))throw Sr(new Error,Yn.MISSING_VALUE("aws_secret_access_key"),Tr.BAD_REQUEST);if(_s.isEmptyOrZeroLength(e.s3.bucket))throw Sr(new Error,Yn.MISSING_VALUE("bucket"),Tr.BAD_REQUEST);if(_s.isEmptyOrZeroLength(e.s3.key))throw Sr(new Error,Yn.MISSING_VALUE("key"),Tr.BAD_REQUEST);if(_s.isEmptyOrZeroLength(e.s3.region))throw Sr(new Error,Yn.MISSING_VALUE("region"),Tr.BAD_REQUEST);let t=QW(e);if(!_s.isEmpty(t))throw Sr(new Error,t,Tr.BAD_REQUEST);Ws.trace(`called export_to_s3 to bucket: ${e.s3.bucket} and query ${e.search_operation.sql}`);let r;try{r=await XW(e)}catch(l){throw Ws.error(l),l}let n,s=await vge.getS3AuthObj(e.s3.aws_access_key_id,e.s3.aws_secret_access_key,e.s3.region),i,a=new pR.PassThrough;if(e.format===JW){i=e.s3.key+".csv";let l=kge(r,r.getColumns?.());l.on("error",u=>{throw u}),l.pipe(a)}else if(e.format===jW){i=e.s3.key+".json";let l=new pR.Readable;l.pipe(a),l.on("error",f=>{throw f}),l.push("[");let u=r.length,d="";for(let[f,m]of r.entries()){let h=f===u-1?JSON.stringify(m):JSON.stringify(m)+",";d+=h,f!==0&&f%$ge===0&&(l.push(d),d="")}d.length!==0&&l.push(d),l.push("]"),l.push(null)}else throw Sr(new Error,Yn.INVALID_VALUE("format"),Tr.BAD_REQUEST);return new Hge({client:s,params:{Bucket:e.s3.bucket,Key:i,Body:a}}).done()}o(Jge,"export_to_s3");function QW(e){if(Ws.trace("in exportCoreValidation"),_s.isEmpty(e.format))return"format missing";if(WW.indexOf(e.format)<0)return`format invalid. must be one of the following values: ${WW.join(", ")}`;let t=e.search_operation.operation;if(_s.isEmpty(t))return"search_operation.operation missing";if(YW.indexOf(t)<0)return`searchOperation.operation must be one of the following values: ${YW.join(", ")}`}o(QW,"exportCoreValidation");async function XW(e){Ws.trace("in getRecords");let t,r;if(jp.isEmpty(e.search_operation)||jp.isEmptyOrZeroLength(e.search_operation.operation))throw Sr(new Error,Yn.INVALID_VALUE("Search operation"),Tr.BAD_REQUEST);switch(e.search_operation.operation){case"search_by_value":t=Kge;break;case"search_by_hash":t=Vge;break;case"search_by_conditions":t=HP.searchByConditions;break;case"sql":{let n=nR();t=zW(n.evaluateSQL);break}default:throw r=`Operation ${e.search_operation.operation} is not support by export.`,Ws.error(r),Sr(new Error,r,Tr.BAD_REQUEST)}return e.search_operation.hdb_user=e.hdb_user,t(e.search_operation)}o(XW,"getRecords")});var tz=M((BFe,ez)=>{"use strict";var qP=class{static{o(this,"SqlSearchObject")}constructor(t,r){this.operation="sql",this.sql=t,this.hdb_user=r}};ez.exports=qP});var sz=M((HFe,nz)=>{"use strict";var Qge=(H(),v(W)),rz=require("moment"),Xge=require("uuid").v4,GP=class{static{o(this,"JobObject")}constructor(){this.id=Xge(),this.type=void 0,this.start_datetime=rz().valueOf(),this.created_datetime=rz().valueOf(),this.end_datetime=void 0,this.status=Qge.JOB_STATUS_ENUM.CREATED,this.message=void 0,this.user=void 0,this.request=void 0}};nz.exports=GP});var $P=M((qFe,fz)=>{"use strict";var Zge=require("uuid").v4,lz=Bn(),uz=an(),eSe=Ri(),tSe=pd(),rSe=tz(),Lt=(H(),v(W)),nSe=sz(),sSe=eS(),Ui=j(),iSe=Dm(),bf=se(),{promisify:oSe}=require("util"),hu=require("moment"),aSe=nR(),_R=IP(),iz=mI(),{deleteTransactionLogsBeforeValidator:cSe}=zC(),{handleHDBError:oz,hdbErrors:lSe,ClientError:uSe}=ge(),{HTTP_STATUS_CODES:az}=lSe,cz=uz.searchByValue,dSe=uz.searchByHash,fSe=lz.insert,mSe=oSe(aSe.evaluateSQL),hSe=lz.update;fz.exports={addJob:ESe,updateJob:SSe,handleGetJob:pSe,handleGetJobsByStartDate:_Se,getJobById:dz};async function pSe(e){if(e.id===void 0)throw new uSe("'id' is required");let t=await dz(e.id);return bf.isEmptyOrZeroLength(t)||(t[0]={...t[0]},t[0].request!==void 0&&delete t[0].request,delete t[0].__createdtime__,delete t[0].__updatedtime__),t}o(pSe,"handleGetJob");async function _Se(e){try{let t=await gSe(e);if(Ui.trace(`Searching for jobs from ${e.from_date} to ${e.to_date}`),t&&t.length>0)for(let r of t)r.start_datetime&&(r.start_datetime_converted=hu(r.start_datetime)),r.end_datetime&&(r.end_datetime_converted=hu(r.end_datetime)),r.request!==void 0&&delete r.request,delete r.__createdtime__,delete r.__updatedtime__;return t}catch(t){let r=`There was an error searching jobs by date: ${t}`;throw Ui.error(r),new Error(r)}}o(_Se,"handleGetJobsByStartDate");async function ESe(e){let t={message:"",error:"",success:!1,createdJob:void 0};if(!e||Object.keys(e).length===0||bf.isEmptyOrZeroLength(e.operation)){let d="job parameter is invalid";return Ui.info(d),t.error=d,t}if(!Lt.JOB_TYPE_ENUM[e.operation])return Ui.info(`invalid job type specified: ${e.operation}.`),t;let r=e.operation,n;switch(r){case Lt.OPERATIONS_ENUM.CSV_FILE_LOAD:n=_R.fileObject(e);break;case Lt.OPERATIONS_ENUM.CSV_URL_LOAD:n=_R.urlObject(e);break;case Lt.OPERATIONS_ENUM.CSV_DATA_LOAD:n=_R.dataObject(e);break;case Lt.OPERATIONS_ENUM.IMPORT_FROM_S3:n=_R.s3FileObject(e);break;case Lt.OPERATIONS_ENUM.DELETE_FILES_BEFORE:case Lt.OPERATIONS_ENUM.DELETE_RECORDS_BEFORE:n=iz(e,"date");break;case Lt.OPERATIONS_ENUM.DELETE_AUDIT_LOGS_BEFORE:n=iz(e,"timestamp");break;case Lt.OPERATIONS_ENUM.DELETE_TRANSACTION_LOGS_BEFORE:n=cSe(e);break;case Lt.OPERATIONS_ENUM.RESTART_SERVICE:if(Lt.HDB_PROCESS_SERVICES[e.service]===void 0)throw oz(new Error,"Invalid service",az.BAD_REQUEST,void 0,void 0,!0);break;default:break}if(n)throw oz(n,n.message,az.BAD_REQUEST,void 0,void 0,!0);let s=new nSe;s.type=e.operation===Lt.OPERATIONS_ENUM.DELETE_RECORDS_BEFORE?Lt.OPERATIONS_ENUM.DELETE_FILES_BEFORE:e.operation,s.type=e.operation,s.user=e.hdb_user?.username;let i=new eSe(Lt.SYSTEM_SCHEMA_NAME,Lt.SYSTEM_TABLE_NAMES.JOB_TABLE_NAME,"id",s.id,"id",["id"]),a;try{a=Array.from(await cz(i))}catch(d){let f=`There was an error inserting a new job: ${d}`;return Ui.error(f),t}let c=Array.isArray(a)?a:Object.keys(a);if(c&&c.length>0){s.id=Zge();try{a=await cz(i)}catch(d){let f=`There was an error inserting a new job: ${d}`;return Ui.error(f),t}if(c=Array.isArray(a)?a:Object.keys(a),c&&c.length>0)return Ui.error("Error creating a job, could not find a unique job id."),t}s.request=e;let l=new iSe(Lt.SYSTEM_SCHEMA_NAME,Lt.SYSTEM_TABLE_NAMES.JOB_TABLE_NAME,"id",[s]),u;try{u=await fSe(l)}catch(d){return Ui.error(`There was an error inserting a job for job type: ${e.operation} -- ${d}`),t.success=!1,t}if(u.inserted_hashes.length===0)t.message=`Had a problem creating a job with type ${s.operation} and id ${s.id}`;else{let d=`Created a job with type ${s.type} and id ${s.id}`;t.message=d,t.createdJob=s,t.success=!0,Ui.trace(d)}return t}o(ESe,"addJob");async function gSe(e){let t=hu(e.from_date,hu.ISO_8601),r=hu(e.to_date,hu.ISO_8601);if(!t.isValid())throw new Error("Invalid 'from' date, must be in ISO-8601 format (YYYY-MM-DD).");if(!r.isValid())throw new Error("Invalid 'to' date, must be in ISO-8601 format (YYYY-MM-DD)");let n=`select * from system.hdb_job where start_datetime > '${t.valueOf()}' and start_datetime < '${r.valueOf()}'`,s=new rSe(n,e.hdb_user);try{return await mSe(s)}catch(i){throw Ui.error(`there was a problem searching for jobs from date ${e.from_date} to date ${e.to_date} ${i}`),new Error("there was an error searching for jobs. Please check the log for details.")}}o(gSe,"getJobsInDateRange");async function dz(e){if(bf.isEmptyOrZeroLength(e))return bf.errorizeMessage("Invalid job ID specified.");let t=new tSe(Lt.SYSTEM_SCHEMA_NAME,Lt.SYSTEM_TABLE_NAMES.JOB_TABLE_NAME,[e],["*"]);try{return await dSe(t)}catch(r){let n=`There was an error searching for a job by id: ${e} ${r}`;return Ui.error(n),bf.errorizeMessage("there was an error searching for jobs. Please check the log for details.")}}o(dz,"getJobById");async function SSe(e){if(Object.keys(e).length===0)throw new Error("invalid job object passed to updateJob");if(bf.isEmptyOrZeroLength(e.id))throw new Error("invalid ID passed to updateJob");(e.status===Lt.JOB_STATUS_ENUM.COMPLETE||e.status===Lt.JOB_STATUS_ENUM.ERROR)&&(e.end_datetime=hu().valueOf());let t=new sSe(Lt.SYSTEM_SCHEMA_NAME,Lt.SYSTEM_TABLE_NAMES.JOB_TABLE_NAME,[e]),r;return r=await hSe(t),r}o(SSe,"updateJob")});var Tz=M(($Fe,Sz)=>{"use strict";var mz=se(),Or=(H(),v(W)),TSe=require("moment"),ER=BP(),Jp=j(),hz=$P(),pz=kP(),_z=Rl(),Ez=rt(),RSe=YT(),ySe=yc(),{parentPort:ASe,isMainThread:gz}=require("worker_threads"),{onMessageByType:bSe}=rt(),VP=class{static{o(this,"RunnerMessage")}constructor(t,r){this.job=t,this.json=r}};async function ISe(e){if(!e||Object.keys(e).length===0)throw new Error("Empty runner passed to parseMessage");if(!e.json||Object.keys(e.json).length===0)throw new Error("Empty JSON passed to parseMessage");if(!e.job||Object.keys(e.job).length===0)throw new Error("Empty job passed to parseMessage");if(mz.isEmptyOrZeroLength(e.json.operation))throw new Error("Invalid operation");if(mz.isEmptyOrZeroLength(e.job.id))throw new Error("Empty job id specified");switch(e.json.operation){case Or.JOB_TYPE_ENUM.csv_file_load:await ho(e,ER.csvFileLoad);break;case Or.JOB_TYPE_ENUM.csv_url_load:await ho(e,ER.csvURLLoad);break;case Or.JOB_TYPE_ENUM.csv_data_load:await ho(e,ER.csvDataLoad);break;case Or.JOB_TYPE_ENUM.import_from_s3:await ho(e,ER.importFromS3);break;case Or.JOB_TYPE_ENUM.empty_trash:break;case Or.JOB_TYPE_ENUM.export_local:await ho(e,pz.export_local);break;case Or.JOB_TYPE_ENUM.export_to_s3:await ho(e,pz.export_to_s3);break;case Or.JOB_TYPE_ENUM.delete_files_before:case Or.JOB_TYPE_ENUM.delete_records_before:await ho(e,_z.deleteFilesBefore);break;case Or.JOB_TYPE_ENUM.delete_audit_logs_before:await ho(e,_z.deleteAuditLogsBefore);break;case Or.JOB_TYPE_ENUM.delete_transaction_logs_before:await ho(e,RSe.deleteTransactionLogsBefore);break;case Or.JOB_TYPE_ENUM.restart_service:return await ho(e,ySe.restartService),`Restarting ${e.json.service}`;break;default:return`Invalid operation ${e.json.operation} specified`}}o(ISe,"parseMessage");async function ho(e,t){try{e.job.status=Or.JOB_STATUS_ENUM.IN_PROGRESS,e.job.start_datetime=TSe().valueOf(),await hz.updateJob(e.job),await NSe(e.job.id)}catch(r){let n=r.message!==void 0?r.message:r;typeof n=="string"?(n=`There was an error running ${t.name} job with id ${e.job.id} - ${n}`,r.message=n):Jp.error(`There was an error running ${t.name} job with id ${e.job.id}`),Jp.error(n),e.job.message=n,e.job.status=Or.JOB_STATUS_ENUM.ERROR;try{await hz.updateJob(e.job)}catch(s){throw Jp.error(`Unable to update job with id ${e.job.id}`),s}throw r}}o(ho,"runJob");async function NSe(e){Jp.trace("launching job thread:",e),gz?Ez.startWorker("server/jobs/jobProcess.js",{autoRestart:!1,name:"job",env:{...process.env,[Or.PROCESS_NAME_ENV_PROP]:`JOB-${e}`}}):ASe.postMessage({type:Or.ITC_EVENT_TYPES.START_JOB,jobId:e})}o(NSe,"launchJobThread");gz&&bSe(Or.ITC_EVENT_TYPES.START_JOB,async(e,t)=>{try{Ez.startWorker("server/jobs/jobProcess.js",{autoRestart:!1,name:"job",env:{...process.env,[Or.PROCESS_NAME_ENV_PROP]:`JOB-${e.jobId}`}})}catch(r){Jp.error(r)}});Sz.exports={parseMessage:ISe,RunnerMessage:VP}});var yz=M((KFe,Rz)=>{"use strict";var wSe=se(),KP=oe(),Oc=(H(),v(W)),OSe=Ot(),CSe=sr(),po=j(),PSe=DP(),DSe=Zi();KP.initSync();Rz.exports={postOperationHandler:MSe,sendOperationTransaction:Qp};async function Qp(e,t,r,n){if(e.schema===Oc.SYSTEM_SCHEMA_NAME)return;let s=LSe(e,t,r);s&&(po.trace(`sendOperationTransaction publishing to schema ${e.schema} following transaction:`,s),await CSe.publishToStream(`${OSe.SUBJECT_PREFIXES.TXN}.${e.schema}`,DSe.createNatsTableStreamName(e.schema,e.table),n,s))}o(Qp,"sendOperationTransaction");function LSe(e,t,r){if(wSe.isEmptyOrZeroLength(t))return null;let n={operation:e.operation,schema:e.schema,table:e.table,__origin:r};return e.operation===Oc.OPERATIONS_ENUM.DELETE?n.hash_values=t:n.records=e.records,n}o(LSe,"convertCRUDOperationToTransaction");async function MSe(e,t,r){if(!KP.get(Oc.CONFIG_PARAMS.CLUSTERING_ENABLED))return;po.trace(`postOperationHandler called for operation ${e.operation} on schema.table: ${e.schema}.${e.table}`);let n=e.hdb_user?.username,s=KP.get(Oc.CONFIG_PARAMS.CLUSTERING_NODENAME),i=new PSe(t.txn_time,n,s);switch(e.operation){case Oc.OPERATIONS_ENUM.INSERT:try{await Qp(e,t.inserted_hashes,i,r)}catch(a){po.error("There was an error calling clustering postOperationHandler for insert."),po.error(a)}break;case Oc.OPERATIONS_ENUM.DELETE:try{await Qp(e,t.deleted_hashes,i,r)}catch(a){po.error("There was an error calling clustering postOperationHandler for delete."),po.error(a)}break;case Oc.OPERATIONS_ENUM.UPDATE:try{await Qp(e,t.update_hashes,i,r)}catch(a){po.error("There was an error calling clustering postOperationHandler for update."),po.error(a)}break;case Oc.OPERATIONS_ENUM.UPSERT:try{await Qp(e,t.upserted_hashes,i,r)}catch(a){po.error("There was an error calling clustering postOperationHandler for upsert."),po.error(a)}break;default:break}return t}o(MSe,"postOperationHandler")});var Q,Az=ce(()=>{Q=class{static{o(this,"OperationFunctionObject")}operation_function;job_operation_function;constructor(t,r=void 0){this.operation_function=t,this.job_operation_function=r}}});var YC={};we(YC,{chooseOperation:()=>Gz,executeJob:()=>zs,getOperationFunction:()=>$z,operation:()=>eD,processLocalTransaction:()=>qz});async function qz(e,t){try{if(e.body.operation!=="read_log"&&(t_.default.log_level===ym.INFO||t_.default.log_level===ym.DEBUG||t_.default.log_level===ym.TRACE)){let{hdb_user:n,hdbAuthHeader:s,password:i,payload:a,...c}=e.body;yn.info(c)}}catch(n){yn.error(n)}let r=await Hz.default.callOperationFunctionAsAwait(t,e.body,null);if(typeof r!="object"&&(r={message:r}),r instanceof Error)throw r;return xSe[e.body.operation]&&Uz.default.setSchemaDataToGlobal(n=>{n&&yn.error(n)}),r}function Gz(e){let t;try{t=$z(e)}catch(s){throw yn.error(`Error when selecting operation function - ${s}`),s}let{operation_function:r,job_operation_function:n}=t;try{if(e.operation==="sql"||e.search_operation&&e.search_operation.operation==="sql"){let s=e.operation==="sql"?e.sql:e.search_operation.sql,i=TR.default.convertSQLToAST(s);if(e.parsed_sql_object=i,!e.bypass_auth){let a=TR.default.checkASTPermissions(e,i);if(a)throw yn.error(`${bz.FORBIDDEN} from operation ${e.operation}`),yn.warn(`User '${e.hdb_user?.username}' is not permitted to ${e.operation}`),(0,js.handleHDBError)(new Error,a,js.hdbErrors.HTTP_STATUS_CODES.FORBIDDEN,void 0,void 0,!0)}}else if(!e.bypass_auth&&e.operation!==G.CREATE_AUTHENTICATION_TOKENS&&e.operation!==G.LOGIN&&e.operation!==G.LOGOUT){let s=n===void 0?r:n,i=e.search_operation?e.search_operation:e;i.hdb_user||(i.hdb_user=e.hdb_user);let a=vz.default.verifyPerms(i,s);if(a)throw yn.error(`${bz.FORBIDDEN} from operation ${e.operation}`),yn.warn(`User '${i.hdb_user?.username}' is not permitted to ${i.operation}`),(0,js.handleHDBError)(new Error,a,js.hdbErrors.HTTP_STATUS_CODES.FORBIDDEN,void 0,!1,!0)}}catch(s){throw(0,js.handleHDBError)(s,"There was an error when trying to choose an operation path")}return r}function $z(e){if(yn.trace(`getOperationFunction with operation: ${e.operation}`),Iz.has(e.operation))return Iz.get(e.operation);throw(0,js.handleHDBError)(new Error,js.hdbErrors.HDB_ERROR_MSGS.OP_NOT_FOUND(e.operation),js.hdbErrors.HTTP_STATUS_CODES.BAD_REQUEST,void 0,void 0,!0)}function eD(e,t,r){e.hdb_user=t?.user,e.bypass_auth=!r;let n=Gz(e);return qz({body:e},n)}async function BSe(e){yn.trace("In serverUtils.catchup");let t=e.transaction,r=t.channel.split(":"),n=r[0],s=r[1];for(let i of t.transactions)try{i.schema=n,i.table=s,i[jA]=!0;let a;switch(i.operation){case G.INSERT:a=await _u.default.insert(i);break;case G.UPDATE:a=await _u.default.update(i);break;case G.UPSERT:a=await _u.default.upsert(i);break;case G.DELETE:a=await wf.default.deleteRecord(i);break;default:yn.warn("invalid operation in catchup");break}await kz.transactToClusteringUtils.postOperationHandler(i,a,e)}catch(a){yn.info("Invalid operation in transaction"),yn.error(a)}}async function zs(e){(0,Fz.transformReq)(e);let t,r;try{if(r=await RR.default.addJob(e),r){t=r.createdJob,yn.info("addJob result",r);let n=new jP.default.RunnerMessage(t,e);return{message:await jP.default.parseMessage(n)??`Starting job with id ${t.id}`,job_id:t.id}}}catch(n){let s=n instanceof Error?n:null,i=`There was an error executing job: ${s&&"http_resp_msg"in s?s.http_resp_msg:n}`;throw yn.error(i),(0,js.handleHDBError)(n,i)}}function FSe(){let e=new Map;return e.set(G.INSERT,new Q(_u.default.insert)),e.set(G.UPDATE,new Q(_u.default.update)),e.set(G.UPSERT,new Q(_u.default.upsert)),e.set(G.SEARCH_BY_CONDITIONS,new Q(Nf.default.searchByConditions)),e.set(G.SEARCH_BY_HASH,new Q(Nf.default.searchByHash)),e.set(G.SEARCH_BY_ID,new Q(Nf.default.searchByHash)),e.set(G.SEARCH_BY_VALUE,new Q(Nf.default.searchByValue)),e.set(G.SEARCH,new Q(vSe)),e.set(G.SQL,new Q(USe)),e.set(G.CSV_DATA_LOAD,new Q(zs,Xp.default.csvDataLoad)),e.set(G.CSV_FILE_LOAD,new Q(zs,Xp.default.csvFileLoad)),e.set(G.CSV_URL_LOAD,new Q(zs,Xp.default.csvURLLoad)),e.set(G.IMPORT_FROM_S3,new Q(zs,Xp.default.importFromS3)),e.set(G.CREATE_SCHEMA,new Q(xi.default.createSchema)),e.set(G.CREATE_DATABASE,new Q(xi.default.createSchema)),e.set(G.CREATE_TABLE,new Q(xi.default.createTable)),e.set(G.CREATE_ATTRIBUTE,new Q(xi.default.createAttribute)),e.set(G.DROP_SCHEMA,new Q(xi.default.dropSchema)),e.set(G.DROP_DATABASE,new Q(xi.default.dropSchema)),e.set(G.DROP_TABLE,new Q(xi.default.dropTable)),e.set(G.DROP_ATTRIBUTE,new Q(xi.default.dropAttribute)),e.set(G.DESCRIBE_SCHEMA,new Q(Zp.default.describeSchema)),e.set(G.DESCRIBE_DATABASE,new Q(Zp.default.describeSchema)),e.set(G.DESCRIBE_TABLE,new Q(Zp.default.describeTable)),e.set(G.DESCRIBE_ALL,new Q(Zp.default.describeAll)),e.set(G.DELETE,new Q(wf.default.deleteRecord)),e.set(G.ADD_USER,new Q(If.default.addUser)),e.set(G.ALTER_USER,new Q(If.default.alterUser)),e.set(G.DROP_USER,new Q(If.default.dropUser)),e.set(G.LIST_USERS,new Q(If.default.listUsersExternal)),e.set(G.LIST_ROLES,new Q(e_.default.listRoles)),e.set(G.ADD_ROLE,new Q(e_.default.addRole)),e.set(G.ALTER_ROLE,new Q(e_.default.alterRole)),e.set(G.DROP_ROLE,new Q(e_.default.dropRole)),e.set(G.USER_INFO,new Q(If.default.userInfo)),e.set(G.READ_LOG,new Q(wz.default)),e.set(G.ADD_NODE,new Q(Oz.default)),e.set(G.UPDATE_NODE,new Q(YP.default)),e.set(G.SET_NODE_REPLICATION,new Q(YP.default)),e.set(G.REMOVE_NODE,new Q(Cz.default)),e.set(G.CONFIGURE_CLUSTER,new Q(Pz.default)),e.set(G.PURGE_STREAM,new Q(Dz.default)),e.set(G.SET_CONFIGURATION,new Q(JP.default.setConfiguration)),e.set(G.CLUSTER_STATUS,new Q(Lz.default.clusterStatus)),e.set(G.CLUSTER_NETWORK,new Q(Mz.default)),e.set(G.CLUSTER_SET_ROUTES,new Q(gR.default.setRoutes)),e.set(G.CLUSTER_GET_ROUTES,new Q(gR.default.getRoutes)),e.set(G.CLUSTER_DELETE_ROUTES,new Q(gR.default.deleteRoutes)),e.set(G.EXPORT_TO_S3,new Q(zs,WP.default.export_to_s3)),e.set(G.CREATE_CSR,new Q(pu.default.createCsr)),e.set(G.SIGN_CERTIFICATE,new Q(pu.default.signCertificate)),e.set(G.LIST_CERTIFICATES,new Q(pu.default.listCertificates)),e.set(G.ADD_CERTIFICATES,new Q(pu.default.addCertificate)),e.set(G.REMOVE_CERTIFICATE,new Q(pu.default.removeCertificate)),e.set(G.GET_KEY,new Q(pu.default.getKey)),e.set(G.ADD_NODE_BACK,new Q($O)),e.set(G.REMOVE_NODE_BACK,new Q(VO)),e.set(G.DELETE_FILES_BEFORE,new Q(zs,wf.default.deleteFilesBefore)),e.set(G.DELETE_RECORDS_BEFORE,new Q(zs,wf.default.deleteFilesBefore)),e.set(G.EXPORT_LOCAL,new Q(zs,WP.default.export_local)),e.set(G.SEARCH_JOBS_BY_START_DATE,new Q(RR.default.handleGetJobsByStartDate)),e.set(G.GET_JOB,new Q(RR.default.handleGetJob)),e.set(G.GET_FINGERPRINT,new Q(SR.default.getFingerprint)),e.set(G.SET_LICENSE,new Q(SR.default.setLicense)),e.set(G.GET_REGISTRATION_INFO,new Q(SR.default.getRegistrationInfo)),e.set(G.RESTART,new Q(zP.default.restart)),e.set(G.RESTART_SERVICE,new Q(zs,zP.default.restartService)),e.set(G.CATCHUP,new Q(BSe)),e.set(G.SYSTEM_INFORMATION,new Q(xz.default.systemInformation)),e.set(G.DELETE_AUDIT_LOGS_BEFORE,new Q(zs,wf.default.deleteAuditLogsBefore)),e.set(G.READ_AUDIT_LOG,new Q(Nz.default)),e.set(G.CREATE_AUTHENTICATION_TOKENS,new Q(_w)),e.set(G.REFRESH_OPERATION_TOKEN,new Q(Ew)),e.set(G.LOGIN,new Q(xC)),e.set(G.LOGOUT,new Q(BC)),e.set(G.GET_CONFIGURATION,new Q(JP.default.getConfiguration)),e.set(G.CUSTOM_FUNCTIONS_STATUS,new Q(Mt.default.customFunctionsStatus)),e.set(G.GET_CUSTOM_FUNCTIONS,new Q(Mt.default.getCustomFunctions)),e.set(G.GET_COMPONENT_FILE,new Q(Mt.default.getComponentFile)),e.set(G.GET_COMPONENTS,new Q(Mt.default.getComponents)),e.set(G.SET_COMPONENT_FILE,new Q(Mt.default.setComponentFile)),e.set(G.DROP_COMPONENT,new Q(Mt.default.dropComponent)),e.set(G.GET_CUSTOM_FUNCTION,new Q(Mt.default.getCustomFunction)),e.set(G.SET_CUSTOM_FUNCTION,new Q(Mt.default.setCustomFunction)),e.set(G.DROP_CUSTOM_FUNCTION,new Q(Mt.default.dropCustomFunction)),e.set(G.ADD_CUSTOM_FUNCTION_PROJECT,new Q(Mt.default.addComponent)),e.set(G.ADD_COMPONENT,new Q(Mt.default.addComponent)),e.set(G.DROP_CUSTOM_FUNCTION_PROJECT,new Q(Mt.default.dropCustomFunctionProject)),e.set(G.PACKAGE_CUSTOM_FUNCTION_PROJECT,new Q(Mt.default.packageComponent)),e.set(G.PACKAGE_COMPONENT,new Q(Mt.default.packageComponent)),e.set(G.DEPLOY_CUSTOM_FUNCTION_PROJECT,new Q(Mt.default.deployComponent)),e.set(G.DEPLOY_COMPONENT,new Q(Mt.default.deployComponent)),e.set(G.READ_TRANSACTION_LOG,new Q(QP.default.readTransactionLog)),e.set(G.DELETE_TRANSACTION_LOGS_BEFORE,new Q(zs,QP.default.deleteTransactionLogsBefore)),e.set(G.INSTALL_NODE_MODULES,new Q(XP.default.installModules)),e.set(G.AUDIT_NODE_MODULES,new Q(XP.default.auditModules)),e.set(G.GET_BACKUP,new Q(xi.default.getBackup)),e.set(G.CLEANUP_ORPHAN_BLOBS,new Q(xi.default.cleanupOrphanBlobs)),e.set(G.ADD_SSH_KEY,new Q(Mt.default.addSSHKey)),e.set(G.UPDATE_SSH_KEY,new Q(Mt.default.updateSSHKey)),e.set(G.DELETE_SSH_KEY,new Q(Mt.default.deleteSSHKey)),e.set(G.LIST_SSH_KEYS,new Q(Mt.default.listSSHKeys)),e.set(G.SET_SSH_KNOWN_HOSTS,new Q(Mt.default.setSSHKnownHosts)),e.set(G.GET_SSH_KNOWN_HOSTS,new Q(Mt.default.getSSHKnownHosts)),e.set(G.GET_ANALYTICS,new Q(JC)),e.set(G.LIST_METRICS,new Q(QC)),e.set(G.DESCRIBE_METRIC,new Q(XC)),e.set(G.GET_STATUS,new Q(nP)),e.set(G.SET_STATUS,new Q(sP)),e.set(G.CLEAR_STATUS,new Q(rP)),e}var Nf,TR,Xp,xi,Zp,wf,Nz,If,e_,Mt,t_,wz,Oz,YP,Cz,Pz,Dz,Lz,Mz,gR,WP,vz,RR,js,SR,zP,ZP,_u,Uz,xz,jP,JP,QP,XP,Bz,Fz,pu,Hz,kz,bz,yn,vSe,USe,xSe,Iz,WC=ce(()=>{Nf=w(an()),TR=w(nR()),Xp=w(BP()),xi=w(op()),Zp=w(za()),wf=w(Rl()),Nz=w(EO()),If=w(xn()),e_=w(Oh()),Mt=w(KC()),t_=w(j()),wz=w(yO()),Oz=w(Zd()),YP=w(jO()),Cz=w(aT()),Pz=w(XO()),Dz=w(ZO()),Lz=w(dT()),Mz=w(mT()),gR=w(hT()),WP=w(kP()),vz=w(tR()),RR=w($P());H();js=w(ge()),SR=w(ST()),zP=w(yc()),ZP=w(require("util")),_u=w(Bn()),Uz=w(Us()),xz=w(Zo()),jP=w(Tz());wd();FT();JP=w(gt()),QP=w(YT()),XP=w(Mp()),Bz=w(mi()),Fz=w(se());vr();pu=w(pn());Xd();eP();Hz=w(NP()),kz=w(yz());Sf();Az();({HTTP_STATUS_CODES:bz}=js.hdbErrors),yn=t_.default.loggerWithTag("operation"),vSe=ZP.promisify(Nf.default.search),USe=ZP.promisify(TR.default.evaluateSQL),xSe={[G.CREATE_ATTRIBUTE]:!0,[G.CREATE_TABLE]:!0,[G.CREATE_SCHEMA]:!0,[G.DROP_ATTRIBUTE]:!0,[G.DROP_TABLE]:!0,[G.DROP_SCHEMA]:!0};o(qz,"processLocalTransaction");Iz=FSe();Le.operation=eD;o(Gz,"chooseOperation");o($z,"getOperationFunction");(0,Bz._assignPackageExport)("operation",eD);o(eD,"operation");o(BSe,"catchup");o(zs,"executeJob");o(FSe,"initializeOperationFunctionMap")});var bR=M((XFe,Yz)=>{"use strict";var yR=(H(),v(W)),HSe=se(),r_=j(),{handleHDBError:tD,hdbErrors:AR}=ge(),{isMainThread:kSe}=require("worker_threads"),{Readable:qSe}=require("stream"),Vz=require("os"),GSe=require("util"),$Se=Sw(),VSe=GSe.promisify($Se.authorize),Kz=(WC(),v(YC)),{createGzip:KSe,constants:YSe}=require("zlib"),WSe=[yR.OPERATIONS_ENUM.CREATE_AUTHENTICATION_TOKENS,yR.OPERATIONS_ENUM.LOGIN,yR.OPERATIONS_ENUM.LOGOUT];function zSe(e){let t=`Found an uncaught exception with message: ${e.message}. ${Vz.EOL}Stack: ${e.stack} ${Vz.EOL}Terminating ${kSe?"HDB":"thread"}.`;console.error(t),r_.fatal(t),process.exit(1)}o(zSe,"handleServerUncaughtException");function jSe(e,t,r){if(r_[e.logLevel||"error"](e),e.statusCode)return typeof e.http_resp_msg!="object"?r.code(e.statusCode).send({error:e.http_resp_msg||e.message}):r.code(e.statusCode).send(e.http_resp_msg);let n=e.statusCode?e.statusCode:AR.HTTP_STATUS_CODES.INTERNAL_SERVER_ERROR;return typeof e=="string"?r.code(n).send({error:e}):r.code(n).send(e.message?{error:e.message}:e)}o(jSe,"serverErrorHandler");function JSe(e,t,r){if(!e.body||Object.keys(e.body).length===0||typeof e.body!="object"){let n=tD(new Error,"Invalid JSON.",AR.HTTP_STATUS_CODES.BAD_REQUEST);r(n,null)}if(HSe.isEmpty(e.body.operation)){let n=tD(new Error,"Request body must include an 'operation' property.",AR.HTTP_STATUS_CODES.BAD_REQUEST);r(n,null)}r()}o(JSe,"reqBodyValidationHandler");function QSe(e,t,r){let n;!WSe.includes(e.body.operation)||e.body.operation===yR.OPERATIONS_ENUM.CREATE_AUTHENTICATION_TOKENS&&!e.body.username&&!e.body.password?VSe(e,t).then(i=>{n=i,e.body.hdb_user=n,r()}).catch(i=>{r_.warn(i),r_.warn(`{"ip":"${e.socket.remoteAddress}", "error":"${i.stack}"`);let a=typeof i=="string"?{error:i}:{error:i.message};r(tD(i,a,AR.HTTP_STATUS_CODES.UNAUTHORIZED),null)}):(e.body.hdb_user=null,e.body.baseRequest=e.raw?.baseRequest,e.body.baseResponse=t.raw?.baseResponse,e.body.fastifyResponse=t,r())}o(QSe,"authHandler");async function XSe(e,t,r=!1){let n;try{e.body.bypass_auth&&delete e.body.bypass_auth,n=Kz.chooseOperation(e.body);let s=await Kz.processLocalTransaction(e,n);if(s instanceof qSe&&s.headers){for(let[i,a]of s.headers)t.header(i,a);e.headers["accept-encoding"]?.includes("gzip")&&(t.header("content-encoding","gzip"),s=s.pipe(KSe({level:YSe.Z_BEST_SPEED})))}return s}catch(s){throw r_.error(s),s}}o(XSe,"handlePostRequest");Yz.exports={authHandler:QSe,handlePostRequest:XSe,handleServerUncaughtException:zSe,serverErrorHandler:jSe,reqBodyValidationHandler:JSe}});var Jz=M((eHe,jz)=>{"use strict";var ZSe=require("fastify-plugin"),{handlePostRequest:Wz,authHandler:eTe,reqBodyValidationHandler:tTe}=bR();async function rTe(e){e.decorate("hdbCore",{preValidation:[tTe,eTe],request:o((t,r)=>zz(Wz(t,r)),"request"),requestWithoutAuthentication:o((t,r)=>zz(Wz(t,r,!0)),"requestWithoutAuthentication")})}o(rTe,"hdbCore");async function zz(e){if(e=await e,e?.[Symbol.asyncIterator]&&!e[Symbol.iterator]){let t=[];for await(let r of e)t.push(r);return t}return e}o(zz,"convertAsyncIterators");jz.exports=ZSe(rTe)});var Xz=M((nHe,Qz)=>{"use strict";var rHe=require("fs"),IR=oe();IR.initSync();var{CONFIG_PARAMS:rD}=(H(),v(W)),nTe=1024*1024*1024;function sTe(e){let t=IR.get(rD.HTTP_TIMEOUT),r=IR.get(rD.HTTP_KEEPALIVETIMEOUT);return{bodyLimit:nTe,connectionTimeout:t,keepAliveTimeout:r,return503OnClosing:!1,forceCloseConnections:!0,ignoreTrailingSlash:!0,maxParamLength:IR.get(rD.HTTP_MAXPARAMLENGTH)??1e3,https:e}}o(sTe,"getServerOptions");Qz.exports=sTe});var tj=M((iHe,ej)=>{"use strict";var nD=oe();nD.initSync();var{CONFIG_PARAMS:Zz}=(H(),v(W));function iTe(){let e=nD.get(Zz.HTTP_CORSACCESSLIST),t=nD.get(Zz.HTTP_CORS),r;return t&&(r={origin:!0,allowedHeaders:["Content-Type","Authorization","Accept"],credentials:!1},e&&e.length>0&&e[0]!==null&&e[0]!=="*"&&(r.origin=(n,s)=>s(null,e.indexOf(n)!==-1))),r}o(iTe,"getCORSOptions");ej.exports=iTe});var sj=M((aHe,nj)=>{"use strict";var rj=oe();rj.initSync();var oTe=(H(),v(W));function aTe(){return rj.get(oTe.CONFIG_PARAMS.HTTP_HEADERSTIMEOUT)??6e4}o(aTe,"getHeaderTimeoutConfig");nj.exports=aTe});var iD={};we(iD,{customFunctionsServer:()=>uTe,ready:()=>gj,start:()=>lTe});function lTe(e){let t=e.securePort>0;return{async handleFile(r,n,s,i){da||(da=Ej(t),Le.http((await da).server));let a=await da,c=(0,sD.dirname)(s),l=(0,sD.dirname)(n);if(l.startsWith("/")&&(l=l.slice(1)),!ij.has(c)){ij.add(c);try{a.register(fTe(c,l))}catch(u){if(u.message==="Root plugin has already booted")bt.warn(`Could not load root fastify route for ${s}, this may require a restart to install properly`);else throw u}}},ready:gj}}async function uTe(){try{bt.info("In Custom Functions Fastify server"+process.cwd()),bt.info(`Custom Functions Running with NODE_ENV set as: ${process.env.NODE_ENV}`),bt.debug(`Custom Functions server process ${process.pid} starting up.`),await dTe();let e=dj.get(U.HTTP_SECUREPORT)>0,t;try{t=da=await Ej(e)}catch(r){throw bt.error(`Custom Functions buildServer error: ${r}`),r}try{await t.ready()}catch(r){throw bt.error(`Custom Functions server.ready() error: ${r}`),r}t.server.cantCleanupProperly=!0}catch(e){bt.error(`Custom Functions ${process.pid} Error: ${e}`),bt.error(e),process.exit(1)}}async function dTe(){try{bt.info("Custom Functions starting configuration."),await fj.setUsersWithRolesCache(),bt.info("Custom Functions completed configuration.")}catch(e){bt.error(e)}}function fTe(e,t){return async function(r){try{bt.info("Custom Functions starting buildRoutes"),bt.trace("Loading fastify routes folder "+e),(0,oj.existsSync)(e)&&r.register(uj.default,s=>({dir:e,dirNameRoutePrefix:!1,options:{hdbCore:s.hdbCore,logger:bt.loggerWithTag("custom-function"),prefix:`/${t}`}})).after((s,i,a)=>{s?.message?bt.error(s.message):s&&bt.error(s),a()})}catch(n){bt.error(`Custom Functions errored buildRoutes: ${n}`)}}}async function Ej(e){bt.info("Custom Functions starting buildServer.");let t=(0,mj.default)(e),r=(0,aj.default)(t);r.server.headersTimeout=(0,pj.default)(),r.setErrorHandler(_j.serverErrorHandler);let n=(0,hj.default)();return n&&r.register(cj.default,n),r.register(function(s,i,a){s.setNotFoundHandler(function(c,l){l.sent||l.raw.headersSent||l.raw.writableEnded||r.server.emit("unhandled",c.raw,l.raw)}),a()}),r.register(lj.default),await r.register(cTe),await r.after(),Vm(r),bt.info("Custom Functions completed buildServer."),r}function gj(){if(da)return da.then?da.then(e=>e.ready()):da.ready()}var sD,oj,aj,cj,lj,uj,dj,bt,cTe,fj,mj,hj,pj,_j,da,ij,Sj=ce(()=>{sD=require("path"),oj=require("fs"),aj=w(require("fastify")),cj=w(require("@fastify/cors")),lj=w(fw()),uj=w(require("@fastify/autoload")),dj=w(oe());H();bt=w(j()),cTe=w(Jz()),fj=w(xn()),mj=w(Xz()),hj=w(tj()),pj=w(sj()),_j=w(bR());Uo();vr();ij=new Set;o(lTe,"start");o(uTe,"customFunctionsServer");o(dTe,"setUp");o(fTe,"buildRouteFolder");o(Ej,"buildServer");o(gj,"ready")});var oD={};we(oD,{start:()=>mTe});function mTe(e){return{handleDirectory(t,r){if(t==="/"){let n=(0,bj.default)(r,e);return e.server.http(async(s,i)=>{if(!s.isWebSocket)return new Promise(a=>n(s._nodeRequest,s._nodeResponse,()=>{a(i(s))}))}),!0}},handleFile(t,r,n){Rj||(Rj=!0,e.server.http(async(s,i)=>{if(!s.isWebSocket){let a=Tj.get(s.pathname);if(a)return{handlesHeaders:!0,body:(0,yj.default)(s,(0,Aj.realpathSync)(a))}}return i(s)},{runFirst:!0})),Tj.set(r,n)}}}var yj,Aj,bj,Tj,Rj,Ij=ce(()=>{yj=w(require("send")),Aj=require("fs"),bj=w(require("serve-static")),Tj=new Map;o(mTe,"start")});var aD={};we(aD,{start:()=>hTe});function hTe({override:e}){return{handleFile:o((t,r,n)=>{NR.default.debug(`Loading env file: ${n}`);for(let[s,i]of Object.entries((0,Nj.parse)(t))){if(process.env[s]!==void 0)if(NR.default.warn(`Environment variable conflict: ${s} from ${n} is already set on process.env`),e)NR.default.debug(`override option enabled. overriding environment variable: ${s}`);else continue;process.env[s]=i}},"handleFile")}}var Nj,NR,wj=ce(()=>{Nj=require("dotenv"),NR=w(j());o(hTe,"start")});var uD={};we(uD,{DataLoaderError:()=>Es,DataLoaderResult:()=>Of,EmptyFileError:()=>PR,FileParseError:()=>CR,InvalidPropertyTypeError:()=>DR,MissingRequiredPropertyError:()=>n_,RecordProcessingError:()=>s_,SystemDatabaseError:()=>LR,UnsupportedFileExtensionError:()=>OR,computeRecordHash:()=>lD,handleApplication:()=>ETe,loadDataFile:()=>Uj,suppressHandleApplicationWarning:()=>_Te});function lD(e){let t=Object.keys(e).sort(),r={};for(let s of t)r[s]=e[s];let n=JSON.stringify(r);return(0,Cj.createHash)("sha256").update(n).digest("hex")}function vj(e){return e.system&&e.system[cD]?e.system[cD]:wR||(wR=ze({database:"system",table:cD,attributes:[{name:"id",type:"string",isPrimaryKey:!0},{name:"hash",type:"string"}]}),wR)}async function pTe(e,t,r,n){try{let s=vj(n),i=e?`${e}:${t}:${r}`:`${t}:${r}`;return(await s.get(i))?.hash||null}catch(s){return Js.error?.(`Failed to get stored hash: ${s.message}`),null}}async function Oj(e,t,r,n,s){try{let i=vj(s),a=e?`${e}:${t}:${r}`:`${t}:${r}`;await i.put({id:a,hash:n})}catch(i){Js.error?.(`Failed to store hash: ${i.message}`)}}function ETe(e){if((0,Dj.getWorkerIndex)()!==0){Js.debug?.("Skipping data loader initialization on non-primary worker");return}e.handleEntry(t=>{t.entryType!=="file"||t.eventType==="unlink"||Uj(t,fn,He).then(r=>{Js.debug?.("Data loader processed file: %s: %s",(0,fa.basename)(t.absolutePath),r.message)})})}async function Uj({contents:e,absolutePath:t,stats:r},n,s){let i=(0,fa.extname)(t)||"unknown",a;try{if(i===".yaml"||i===".yml")a=(0,Pj.parseDocument)(e.toString()).toJSON();else if(i===".json")a=JSON.parse(e.toString());else throw new OR(t,i)}catch(f){throw f instanceof Es?f:new CR(t,f)}if(!a)throw new PR(t);let{database:c,table:l,records:u}=a;if(!l)throw new n_(t,"table");if(!u)throw new n_(t,"records");if(!Array.isArray(u))throw new DR(t,"records","array");let d=c?`${c}.${l}`:l;if(c?.toLowerCase()==="system")throw new LR(c,l);try{let f;if(c&&s[c]&&s[c][l])Js.debug?.(`Using existing table ${d} from database tables`),f=s[c][l];else if(n&&n[l])Js.debug?.(`Using existing table ${d} from global tables`),f=n[l];else{Js.debug?.(`Table ${d} not found, creating new table`);let R=[];if(u.length>0){let T=u[0];Object.keys(T).map(y=>{let N={name:y,type:typeof T[y]};return y==="id"&&(N.isPrimaryKey=!0),N}).forEach(y=>{R.push(y)})}f=await ze({database:c,table:l,attributes:R})}let m=u.length,h=0,p=0,E=0,g=100;for(let R=0;R<u.length;R+=g){let T=u.slice(R,R+g),y=[];for(let N of T)y.push(async()=>{try{let O=null,F=N.id;F!==void 0&&(O=await f.get(F));let Z=lD(N);if(!O){h++;let $=await f.put(N);return await Oj(c,l,F,Z,s),$}let q=await pTe(c,l,F,s);if(!q)return E++,Promise.resolve({inserted:0,updated:0});let Y={};for(let $ of Object.keys(N))$ in O&&(Y[$]=O[$]);return lD(Y)!==q?(E++,Promise.resolve({inserted:0,updated:0})):Z!==q?(p++,await f.patch(F,N),await Oj(c,l,F,Z,s),{updated:1}):(E++,Promise.resolve({inserted:0,updated:0}))}catch(O){if(O instanceof Es)Js.error?.(`Record processing error: ${O.message}`);else{let F=new s_(d,O);Js.error?.(`Record processing error: ${F.message}`)}return Promise.resolve({inserted:0,updated:0,error:O.message})}});await Promise.all(y.map(N=>N()))}if(h>0||p>0){let R=`Loaded ${h} new and updated ${p} records in ${d}`;return E>0&&(R+=` (${E} records skipped)`),Js.info?.(R),new Of(t,c,l,"success",h+p,R)}else if(E>0){let R=`All ${E} records in ${d} already up-to-date`;return Js.info?.(R),new Of(t,c,l,"skipped",m,R)}else{let R=`No records to process in ${d}`;return Js.info?.(R),new Of(t,c,l,"success",0,R)}}catch(f){throw f instanceof Es?f:new s_(d,f)}}var fa,Cj,Pj,Dj,ma,Lj,Mj,Js,cD,wR,_Te,Es,OR,CR,PR,n_,DR,LR,s_,Of,xj=ce(()=>{fa=require("node:path"),Cj=require("node:crypto"),Pj=require("yaml");Pe();Dj=w(rt()),ma=w(Vr()),Lj=w(ge()),Mj=w(j()),Js=Mj.default.forComponent("dataLoader"),cD="hdb_dataloader_hash";o(lD,"computeRecordHash");o(vj,"getHashTrackingTable");o(pTe,"getStoredHash");o(Oj,"storeHash");_Te=!0;o(ETe,"handleApplication");o(Uj,"loadDataFile");Es=class extends Lj.ClientError{static{o(this,"DataLoaderError")}constructor(t,r=ma.HTTP_STATUS_CODES.BAD_REQUEST){super(t,r),this.name="DataLoaderError"}},OR=class extends Es{static{o(this,"UnsupportedFileExtensionError")}constructor(t,r){super(`Unsupported file extension in ${(0,fa.basename)(t)}: ${r}. Only YAML and JSON files are supported.`,ma.HTTP_STATUS_CODES.BAD_REQUEST),this.name="UnsupportedFileExtensionError"}},CR=class extends Es{static{o(this,"FileParseError")}constructor(t,r){super(`Failed to parse data file ${(0,fa.basename)(t)}: ${r.message}`,ma.HTTP_STATUS_CODES.BAD_REQUEST),this.name="FileParseError"}},PR=class extends Es{static{o(this,"EmptyFileError")}constructor(t){super(`Data file ${(0,fa.basename)(t)} is empty or invalid`,ma.HTTP_STATUS_CODES.BAD_REQUEST),this.name="EmptyFileError"}},n_=class extends Es{static{o(this,"MissingRequiredPropertyError")}constructor(t,r){super(`Data file ${(0,fa.basename)(t)} is missing required "${r}" property`,ma.HTTP_STATUS_CODES.BAD_REQUEST),this.name="MissingRequiredPropertyError"}},DR=class extends Es{static{o(this,"InvalidPropertyTypeError")}constructor(t,r,n){super(`Data file ${(0,fa.basename)(t)} has invalid "${r}" property, expected ${n}`,ma.HTTP_STATUS_CODES.BAD_REQUEST),this.name="InvalidPropertyTypeError"}},LR=class extends Es{static{o(this,"SystemDatabaseError")}constructor(t,r){super(`Cannot load data into system database: ${t}.${r}`,ma.HTTP_STATUS_CODES.FORBIDDEN),this.name="SystemDatabaseError"}},s_=class extends Es{static{o(this,"RecordProcessingError")}constructor(t,r){super(`Failed to process record in ${t}: ${r.message}`,ma.HTTP_STATUS_CODES.INTERNAL_SERVER_ERROR),this.name="RecordProcessingError"}},Of=class{static{o(this,"DataLoaderResult")}#e;#t;#r;#n;#s;#i;constructor(t,r,n,s,i,a){this.#e=t,this.#t=r||"unknown",this.#r=n||"unknown",this.#n=s,this.#s=i,this.#i=a}get filePath(){return this.#e}get database(){return this.#t}get table(){return this.#r}get status(){return this.#n}get count(){return this.#s}get message(){return this.#i}toJSON(){return{filePath:this.#e,database:this.#t,table:this.#r,status:this.#n,count:this.#s,message:this.#i}}}});var fD=M((SHe,Bj)=>{"use strict";var i_=oe();i_.initSync();var Cf=require("fs-extra"),dD=require("path"),Pf=(H(),v(W)),gTe=require("crypto"),STe=require("uuid").v4;Bj.exports=TTe;function TTe(){if(i_.getHdbBasePath()!==void 0){let e=dD.join(i_.getHdbBasePath(),Pf.LICENSE_KEY_DIR_NAME,Pf.JWT_ENUM.JWT_PRIVATE_KEY_NAME),t=dD.join(i_.getHdbBasePath(),Pf.LICENSE_KEY_DIR_NAME,Pf.JWT_ENUM.JWT_PUBLIC_KEY_NAME),r=dD.join(i_.getHdbBasePath(),Pf.LICENSE_KEY_DIR_NAME,Pf.JWT_ENUM.JWT_PASSPHRASE_NAME);try{Cf.accessSync(r),Cf.accessSync(e),Cf.accessSync(t)}catch(n){if(n.code==="ENOENT"){let s=STe(),i=gTe.generateKeyPairSync("rsa",{modulusLength:4096,publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs8",format:"pem",cipher:"aes-256-cbc",passphrase:s}});Cf.writeFileSync(r,s),Cf.writeFileSync(e,i.privateKey),Cf.writeFileSync(t,i.publicKey)}else throw n}}}o(TTe,"checkJWTTokenExist")});var Hj=M((RHe,Fj)=>{"use strict";var mD=class{static{o(this,"HdbInfoInsertObject")}constructor(t,r,n){this.info_id=t,this.data_version_num=r,this.hdb_version_num=n}};Fj.exports={HdbInfoInsertObject:mD}});var Gj=M((AHe,qj)=>{"use strict";var kj=(H(),v(W)),hD=class{static{o(this,"UpgradeObject")}constructor(t,r){this[kj.UPGRADE_JSON_FIELD_NAMES_ENUM.DATA_VERSION]=t,this[kj.UPGRADE_JSON_FIELD_NAMES_ENUM.UPGRADE_VERSION]=r}};qj.exports={UpgradeObject:hD}});var MR=M((IHe,Vj)=>{"use strict";var Qs=require("prompt"),Df=require("chalk"),$j=j(),Bi=require("os"),pD=qa(),_D=["yes","y"];async function RTe(e){let t=`${Bi.EOL}`+Df.bold.green("Your current HarperDB version requires that we complete an update process.")+`${Bi.EOL}If a backup of your data has not been created, we recommend you cancel this process and backup before proceeding.${Bi.EOL}${Bi.EOL}You can read more about the changes in this upgrade at https://harperdb.io/developers/release-notes/${Bi.EOL}`;Qs.override=pD(["CONFIRM_UPGRADE"]),Qs.start(),Qs.message=t;let r={properties:{CONFIRM_UPGRADE:{description:Df.magenta(`${Bi.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 Qs.get([r])}catch(s){return $j.error("There was an error when prompting user about an upgrade."),$j.error(s),!1}return _D.includes(n.CONFIRM_UPGRADE)}o(RTe,"forceUpdatePrompt");async function yTe(e){let t=`${Bi.EOL}`+Df.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.${Bi.EOL}`);Qs.override=pD(["CONFIRM_DOWNGRADE"]),Qs.start(),Qs.message=t;let r={properties:{CONFIRM_DOWNGRADE:{description:Df.magenta(`${Bi.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 Qs.get([r]);return _D.includes(n.CONFIRM_DOWNGRADE)}o(yTe,"forceDowngradePrompt");async function ATe(){let e=`${Bi.EOL}`+Df.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");Qs.override=pD(["GENERATE_CERTS"]),Qs.start(),Qs.message=e;let t={properties:{GENERATE_CERTS:{description:Df.magenta(`${Bi.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 Qs.get([t]);return _D.includes(r.GENERATE_CERTS)}o(ATe,"upgradeCertsPrompt");Vj.exports={forceUpdatePrompt:RTe,forceDowngradePrompt:yTe,upgradeCertsPrompt:ATe}});var gD=M((wHe,Kj)=>{"use strict";var ED=class{static{o(this,"UpgradeDirective")}constructor(t){this.version=t,this.sync_functions=[],this.async_functions=[]}};Kj.exports=ED});var Wj=M((MHe,Yj)=>{"use strict";var bTe=se(),ITe=gt(),CHe=j(),PHe=require("path"),DHe=require("fs"),LHe=(H(),v(W));Yj.exports={getOldPropsValue:NTe};function NTe(e,t,r=!1){let n=t.getRaw(e);return bTe.isNotEmptyAndHasValue(n)?n:r?ITe.getDefaultConfig(e):""}o(NTe,"getOldPropsValue")});var Qj=M((UHe,Jj)=>{"use strict";var Cc=require("path"),Pc=require("fs-extra"),wTe=require("properties-reader"),OTe=gD(),Rr=j(),{getOldPropsValue:It}=Wj(),{HDB_SETTINGS_NAMES:ye,CONFIG_PARAMS:Eu}=(H(),v(W)),gu=gt(),vR=oe(),zj=se(),_o=(H(),v(W)),SD=new OTe("3.1.0"),jj=[];function CTe(){let e=wTe(vR.get(ye.SETTINGS_PATH_KEY)),t="Updating settings file for version 3.1.0";console.log(t),Rr.info(t);let r=` ;Settings for the HarperDB process.
|
|
35
35
|
|
|
36
36
|
;The directory selected during install where the database files reside.
|
|
37
37
|
${ye.HDB_ROOT_KEY} = ${It(ye.HDB_ROOT_KEY,e)}
|
|
@@ -120,11 +120,11 @@ Reindexing upgrade started for transaction logs`),ha.notify("Reindexing upgrade
|
|
|
120
120
|
`;let l=[],u=qD.getConfigObj();for(let h in u)u[h].package&&l.push(h);let d={},f=`${r("REST:")}`;for(let[h,p]of e)for(let E of p){let g=E.name;g==="rest"&&(f+=`${E.protocol_name}: ${h}, `),l.includes(g)&&(d[g]?d[g]+=`${E.protocol_name}: ${h}, `:d[g]=`${E.protocol_name}: ${h}, `)}f.length>21&&(f=f.slice(0,-2),n+=`${f}
|
|
121
121
|
`);let m=Ae.get(ve.HTTP_PORT)?`HTTP: ${Ae.get(ve.HTTP_PORT)}, `:"";m+=Ae.get(ve.HTTP_SECUREPORT)?`HTTPS: ${Ae.get(ve.HTTP_SECUREPORT)}, `:"",m.length>21&&(m=m.slice(0,-2));for(let h of l)d[h]?n+=`${r(h+": ")}${d[h].slice(0,-2)}
|
|
122
122
|
`:n+=`${r(h+": ")}${m}
|
|
123
|
-
`;console.log(n),Ae.get(ve.LOGGING_STDSTREAMS)&&Rs.logsAtLevel("info")&&Rs.suppressLogging(()=>{console.log(`Note that log messages are being sent to the console (stdout and stderr) in addition to the log file ${s}. This can be disabled by setting logging.stdStreams to false, and the log file can be directly monitored/tailed.`)})}o(Xye,"startupLog");function Zye(e){try{return Number.parseInt(Ta.readFileSync(e,"utf8"),10)}catch{return null}}o(Zye,"readPidFile");function eAe(e){try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}}o(eAe,"isProcessRunning")});var Q2={};we(Q2,{SERVERS:()=>Uf,portServer:()=>$D,setPortServerMap:()=>WR});function WR(e,t){let r=$D.get(e)??[];$D.set(e,[...r,t])}var Uf,$D,VD=ce(()=>{Uf={},$D=new Map;o(WR,"setPortServerMap")});function zR(e,t,r=rAe){let n;return function(...i){return n?n.length*KD>r?t(...i):new Promise((a,c)=>{n.push({args:i,fn(){try{let l=e(...i);a(l)}catch(l){c(l)}}})}):(n=[],s(performance.now(),i),e(...i))};function s(i,a){setImmediate(()=>{let c=performance.now();KD=(KD*4+c-i)/5;let l=n.shift();if(l){let{args:u,fn:d}=l;d(),s(c,u)}else n=null})}}var eJ,tAe,rAe,X2,nAe,YD,Z2,KD,WD=ce(()=>{eJ=w(hi()),tAe=3e3,rAe=2e4,X2=0,nAe=3e4,YD=3e3,Z2=performance.now()+YD,KD=0;o(zR,"throttle");setInterval(()=>{let e=performance.now();e-Z2-YD>tAe&&X2+nAe<e&&(eJ.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"),X2=e),Z2=e},YD).unref()});var ey={};we(ey,{deliverSocket:()=>mJ,getHttpOptions:()=>aAe,getRequestId:()=>EJ,handleApplication:()=>oAe,httpServer:()=>tL,logRequest:()=>S_,proxyRequest:()=>cAe,registerServer:()=>ZD,suppressHandleApplicationWarning:()=>iAe});function oAe(e){T_=e.options.getAll(),e.options.on("change",t=>{T_=e.options.getAll()})}function aAe(){return T_}function mJ(e,t,r){let n=e?.read?e:new iJ.Socket({fd:e,readable:!0,writable:!0,allowHalfOpen:!0}),s=Uf[t];if(s.isSecure&&(n.startTime=performance.now()),s)typeof s=="function"?s(n):s.emit("connection",n),r&&n.emit("data",r);else{let i=o(a=>{setTimeout(()=>{let c=Uf[t];c?(typeof c=="function"?c(n):c.emit("connection",n),r&&n.emit("data",r)):a<5?i(a+1):(Aa.default.error(`Server on port ${t} was not registered`),n.destroy())},1e3)},"retry");i(1)}return n}function cAe(e){let{port:t,event:r,data:n,requestId:s}=e,i;switch(i=tJ.get(s),r){case"connection":i=mJ(void 0,t),tJ.set(s,i),i.write=(c,l,u)=>(JR.parentPort.postMessage({requestId:s,event:"data",data:c.toString("latin1")}),u&&u(),!0),i.end=(c,l,u)=>(JR.parentPort.postMessage({requestId:s,event:"end",data:c?.toString("latin1")}),u&&u(),!0);let a=i.destroy;i.destroy=()=>{a.call(i),JR.parentPort.postMessage({requestId:s,event:"destroy"})};break;case"data":i._readableState.destroyed||i.emit("data",Buffer.from(n,"latin1"));break;case"drain":i._readableState.destroyed||i.emit("drain",{});break;case"end":i._readableState.destroyed||i.emit("end",{});break;case"error":i._readableState.destroyed||i.emit("error",{});break}}function ZD(e,t,r=!0){t||(t=Cr.default.get(U.HTTP_PORT));let n=Uf[t];if(n){let s=n.lastServer||n;if(s===e)throw new Error(`Can not register the same server twice for the same port ${t}`);if(r&&!!s.sessionIdContext!=!!e.sessionIdContext&&+t)throw new Error(`Can not mix secure HTTPS and insecure HTTP on the same port ${t}`);s.off("unhandled",sJ),s.on("unhandled",(i,a)=>{e.cantCleanupProperly&&(n.cantCleanupProperly=!0),e.emit("request",i,a)}),n.lastServer=e}else Uf[t]=e;e.on("unhandled",sJ)}function eL(e){let t=[],r=e?.securePort;return r&&t.push({port:r,secure:!0}),r=e?.port,r&&t.push({port:r,secure:!1}),t.length===0&&(t=[],Cr.default.get(U.HTTP_PORT)!=null&&t.push({port:Cr.default.get(U.HTTP_PORT),secure:Cr.default.get(U.CUSTOMFUNCTIONS_NETWORK_HTTPS)}),Cr.default.get(U.HTTP_SECUREPORT)!=null&&t.push({port:Cr.default.get(U.HTTP_SECUREPORT),secure:!0})),e?.isOperationsServer&&Cr.default.get(U.OPERATIONSAPI_NETWORK_DOMAINSOCKET)&&t.push({port:(0,oJ.resolvePath)(Cr.default.get(U.OPERATIONSAPI_NETWORK_DOMAINSOCKET)),secure:!1}),t}function tL(e,t){let r=[];for(let{port:n,secure:s}of eL(t))r.push(hJ(n,s,t?.isOperationsServer,t?.mtls)),typeof e=="function"?QD[t?.runFirst?"unshift":"push"]({listener:e,port:t?.port||n}):(e.isSecure=s,ZD(e,n,!1)),QR[n]=XR(QD,n);return r}function hJ(e,t,r,n){if(WR(e,{protocol_name:t?"HTTPS":"HTTP",name:ty()}),!jR[e]){let s=r?"operationsApi_network":"http",i=Cr.default.get(s+"_keepAliveTimeout"),a=Cr.default.get(s+"_timeout"),c=Cr.default.get(s+"_headersTimeout"),l={keepAliveTimeout:i,headersTimeout:c,requestTimeout:a,highWaterMark:128*1024,noDelay:!0,keepAlive:!0,keepAliveInitialDelay:600,maxHeaderSize:Cr.default.get(U.HTTP_MAXHEADERSIZE)},u=Cr.default.get(s+"_mtls"),d=Cr.default.get(s+"_mtls_required"),f;if(t){let g=Cr.default.get("tls");f=Cr.default.get(s+"_http2"),Object.assign(l,{allowHTTP1:!0,rejectUnauthorized:!!d,requestCert:!!(u||n),ticketKeys:(0,aJ.getTicketKeys)(),SNICallback:(0,cJ.createTLSSelector)(r?"operations-api":"server",u),ciphers:g.ciphers??g[0]?.ciphers})}let m=(0,lJ.checkMemoryLimit)(),h=o(async(g,R)=>{let T=performance.now(),y=0;try{let O=new sc(g,R);r&&(O.isOperationsServer=!0),T_.logging?.id&&(O.requestId=y=EJ());let F=await QR[e](O);if(!F){if(O._nodeResponse.statusCode){S_(g,O._nodeResponse.statusCode,y,performance.now()-T);return}F=pJ(O)}if(F.headers?.set||(F.headers=new Bs(F.headers)),m?F.headers?.set?.("Server","Unlicensed HarperDB, this should only be used for educational and development purposes"):F.headers?.set?.("Server","HarperDB"),F.status===-1){for(let me of F.headers||[])R.setHeader(me[0],me[1]);return g.baseRequest=O,R.baseResponse=F,jR[e].emit("unhandled",g,R)}let Z=F.status||200,q=performance.now(),Y=q-T,K=F.body,$,le=!1;if(!F.handlesHeaders){let me=F.headers||new Bs;K?K.length>=0?(typeof K=="string"?me.set("Content-Length",Buffer.byteLength(K)):me.set("Content-Length",K.length),$=!0):K instanceof Ds&&(K.size?me.set("Content-Length",K.size):K.on&&(le=!0,K.on("size",Me=>{R.headersSent||R.setHeader("Content-Length",Me)})),K=K.stream()):(me.set("Content-Length","0"),$=!0);let De=`hdb;dur=${Y.toFixed(2)}`;if(F.wasCacheMiss&&(De+=", miss"),Mh(me,"Server-Timing",De,!0),!R.headersSent)if(le){if(R.statusCode=Z,me)if(me[Symbol.iterator])for(let[Me,ft]of me)R.setHeader(Me,ft);else for(let Me in me)R.setHeader(Me,me[Me])}else R.writeHead(Z,me&&(me[Symbol.iterator]?Array.from(me):me));$&&R.end(K)}let ue=O.handlerPath,ie=O.method;if(it(Y,"duration",ue,ie,F.wasCacheMiss==null?void 0:F.wasCacheMiss?"cache-miss":"cache-hit"),jr(Z<400,"success",ue,ie),jr(1,"response_"+Z,ue,ie),S_(g,Z,y,Y),!$)if(K instanceof ReadableStream&&(K=JD.Readable.fromWeb(K)),(K[Symbol.iterator]||K[Symbol.asyncIterator])&&(K=JD.Readable.from(K)),K?.pipe){K.pipe(R),K.destroy&&R.on("close",()=>{K.destroy()});let me=0;K.on("data",De=>{me+=De.length}),K.on("end",()=>{it(performance.now()-q,"transfer",ue,ie),it(me,"bytes-sent",ue,ie)})}else K?.then?K.then(me=>{R.end(me)},N):R.end(K)}catch(O){N(O)}function N(O){let F=O.headers,Z=O.statusCode||500;R.writeHead(Z,F&&(F[Symbol.iterator]?Array.from(F):F)),R.end(sAe(O)),S_(g,Z,y,performance.now()-T),O.statusCode?O.statusCode===500?Aa.default.warn(O):Aa.default.info(O):Aa.default.error(O)}o(N,"onError")},"requestHandler"),p=zR(h,(g,R)=>{R.statusCode=503,R.end("Service unavailable, exceeded request queue limit"),it(!0,"service-unavailable",e)},Cr.default.get(s+"_requestQueueLimit")),E=jR[e]=(t?f?uJ.createSecureServer:dJ.createServer:ZR.createServer)(l,(g,R)=>{let T=g.method;T==="GET"||T==="OPTIONS"||T==="HEAD"?h(g,R):p(g,R)});i>=0&&(E.keepAliveTimeout=i),c>=0&&(E.headersTimeout=c),t&&(E.ports||(E.ports=[]),E.ports.push(e),l.SNICallback.initialize(E),u&&(E.mtlsConfig=u),E.on("secureConnection",g=>{g._parent.startTime&&it(performance.now()-g._parent.startTime,"tls-handshake",e),it(g.isSessionReused(),"tls-reused",e)}),E.isSecure=!0),ZD(E,e)}return jR[e]}function XR(e,t){let r=pJ;for(let n=e.length;n>0;){let{listener:s,port:i}=e[--n];if(i===t||i==="all"){let a=r;r=o((...c)=>s(...c,a),"nextCallback")}}return r}function pJ(e){return e.user&&(e._nodeRequest.user=e.user),{status:-1,body:"Not found",headers:new Bs}}function lAe(e,t){tL(e,{requestOnly:!0,...t})}function _J(e,t){for(let{port:r}of eL(t))rJ[t?.runFirst?"unshift":"push"]({listener:e,port:r}),XD[r]=XR(rJ,r)}function uAe(e,t){let r=[];for(let{port:n,secure:s}of eL(t)){WR(n,{protocol_name:s?"WSS":"WS",name:ty()});let i=hJ(n,s,t?.isOperationsServer,t?.mtls);E_[n]||(E_[n]=new fJ.WebSocketServer({noServer:!0,maxPayload:t.maxPayload??100*1024*1024}),E_[n].on("connection",(a,c)=>{try{let l=new sc(c);l.isWebSocket=!0;let u=QR[n](l);Aa.default.debug("Received WS connection, calling listeners",zD),nJ[n](a,l,u)}catch(l){Aa.default.warn("Error in handling WS connection",l)}}),_J((a,c,l,u)=>a.__harperdbRequestUpgraded?u(a,c,l):E_[n].handleUpgrade(a,c,l,d=>{a.__harperdbRequestUpgraded=!0,u(a,c,l),E_[n].emit("connection",d,a)}),{port:n}),i.on("upgrade",(a,c,l)=>{XD[n]&&XD[n](a,c,l)})),r.push(i),zD[t?.runFirst?"unshift":"push"]({listener:e,port:n}),nJ[n]=XR(zD,n),QR[n]=XR(QD,n)}return r}function sJ(e,t){t.writeHead(404),t.end(`Not found
|
|
124
|
-
`),S_(e,404,0,e.requestId)}function S_(e,t,r,n){let s=T_.logging;if(s){jD||(jD=Aa.default.forComponent("http"));let i=t<400?"info":t===500?"error":"warn";jD[i]?.(`${e.method} ${e.url} ${e.socket.encrypted?"HTTPS":"HTTP"}/${e.httpVersion}${s.headers?" "+dAe(e.headers):""} ${t}${s.timing&&n?" "+n.toFixed(2)+"ms":""}${r?" id: "+r:""}`)}}function dAe(e){let t=[];for(let r in e)t.push(`${r}: ${e[r]}`);return t.join(", ")}function EJ(){return g_||(g_=new BigInt64Array([1n]),g_=new BigInt64Array(databases.system.hdb_analytics.primaryStore.getUserSharedBuffer("next-request-id",g_.buffer))),Number(Atomics.add(g_,0,1n))}var iJ,Aa,JR,Cr,oJ,aJ,cJ,lJ,uJ,dJ,ZR,JD,fJ,sAe,E_,jR,QR,QD,T_,iAe,tJ,rJ,XD,zD,nJ,jD,g_,rL=ce(()=>{iJ=require("node:net"),Aa=w(j()),JR=require("node:worker_threads"),Cr=w(oe());H();oJ=w(gt()),aJ=w(rt()),cJ=w(pn()),lJ=w(of()),uJ=require("node:http2"),dJ=require("node:https"),ZR=require("node:http");Uh();vh();ts();io();JD=require("node:stream");vr();VD();gf();WD();fJ=require("ws"),{errorToString:sAe}=Aa.default;Le.http=tL;Le.request=lAe;Le.ws=uAe;Le.upgrade=_J;E_={},jR={},QR={},QD=[],T_={},iAe=!0;o(oAe,"handleApplication");o(aAe,"getHttpOptions");o(mJ,"deliverSocket");tJ=new Map;o(cAe,"proxyRequest");o(ZD,"registerServer");o(eL,"getPorts");o(tL,"httpServer");o(hJ,"getHTTPServer");o(XR,"makeCallbackChain");o(pJ,"unhandled");o(lAe,"onRequest");Object.defineProperty(ZR.IncomingMessage.prototype,"upgrade",{get(){return"connection"in this.headers&&"upgrade"in this.headers&&this.headers.connection.toLowerCase().includes("upgrade")&&this.headers.upgrade.toLowerCase()=="websocket"},set(e){}});rJ=[],XD={};o(_J,"onUpgrade");zD=[],nJ={};o(uAe,"onWebSocket");o(sJ,"defaultNotFound");o(S_,"logRequest");o(dAe,"headersToString");o(EJ,"getRequestId")});var sL=M(y_=>{"use strict";pE();var{isMainThread:nL,parentPort:gJ,threadId:ry,workerData:fAe}=require("node:worker_threads"),{createServer:mAe}=require("node:net"),{unlinkSync:RJ,existsSync:hAe}=require("fs"),yJ;y_.whenComponentsLoaded=new Promise(e=>{yJ=e});var Hi=j(),ei=oe(),ys=(H(),v(W)),{server:pAe}=(vr(),v(Um)),{createServer:_Ae}=require("node:tls"),{restartNumber:EAe,getWorkerIndex:xf}=rt(),{createReuseportFd:R_}=(Uh(),v(_q)),{createTLSSelector:gAe}=pn(),{resolvePath:SAe}=gt(),{startupLog:TAe}=vf(),{SERVERS:Bf,setPortServerMap:SJ,portServer:RAe}=(VD(),v(Q2)),TJ=(rL(),v(ey)),yAe=mi(),AJ=ei.get(ys.CONFIG_PARAMS.THREADS_DEBUG),AAe=ei.get(ys.CONFIG_PARAMS.HTTP_SESSIONAFFINITY);pAe.socket=bAe;if(AJ){let e;if(nL)e=ei.get(ys.CONFIG_PARAMS.THREADS_DEBUG_PORT)??9229,process.on(["SIGINT","SIGTERM","SIGQUIT","exit"],()=>{try{require("inspector").close()}catch(t){Hi.info("Could not close debugger",t)}});else{let t=ei.get(ys.CONFIG_PARAMS.THREADS_DEBUG_STARTINGPORT);t&&xf()>=0&&(e=t+xf())}if(e){let t=ei.get(ys.CONFIG_PARAMS.THREADS_DEBUG_HOST),r=ei.get(ys.CONFIG_PARAMS.THREADS_DEBUG_WAITFORDEBUGGER);try{require("inspector").open(e,t,r)}catch(n){Hi.trace(`Could not start debugging on port ${e}, you may already be debugging:`,n.message)}}}else if(process.env.DEV_MODE&&nL)try{require("inspector").open(9229)}catch(e){EAe<=1&&Hi.trace("Could not start debugging on port 9229, you may already be debugging:",e.message)}process.on("uncaughtException",e=>{e.isHandled||e.code==="ECONNRESET"||e.code==="ECONNREFUSED"||e.message!=="write EIO"&&Hi.error("uncaughtException",e)});var{HDB_SETTINGS_NAMES:yke,CONFIG_PARAMS:Ake}=ys;ei.initSync();y_.globals=yAe;y_.listenOnPorts=IJ;y_.startServers=bJ;function bJ(){let e=ei.get(ys.CONFIG_PARAMS.ROOTPATH);if(e)try{process.chdir(e)}catch{}let t=ny().loadRootComponents(!0).then(()=>{gJ?.on("message",n=>{let{port:s,fd:i,data:a}=n;if(i)TJ.deliverSocket(i,s,a);else if(n.requestId)TJ.proxyRequest(n);else if(n.type===ys.ITC_EVENT_TYPES.SHUTDOWN){Hi.trace("received shutdown request",ry);for(let c in Bf){let l=Bf[c],u;if(l.closeIdleConnections){let f=Object.getOwnPropertySymbols(l).find(p=>p.description.includes("connections")),m=0,h=setInterval(()=>{m++;let p=m>=100;if(!l[f]){p&&l.closeAllConnections?.(),clearInterval(h);return}let E=l[f][p?"all":"idle"]?.()||[];if(E.length===0){p&&clearInterval(h);return}m===1?Hi.info(`Closing ${E.length} idle connections`):p&&Hi.warn(`Forcefully closing ${E.length} active connections`);for(let g=0,R=E.length;g<R;g++){let T=E[g].socket;T._httpMessage&&!T._httpMessage.finished&&!p||(p?T.destroySoon():T.end(`HTTP/1.1 408 Request Timeout\r
|
|
123
|
+
`;console.log(n),Ae.get(ve.LOGGING_STDSTREAMS)&&Rs.logsAtLevel("info")&&Rs.suppressLogging(()=>{console.log(`Note that log messages are being sent to the console (stdout and stderr) in addition to the log file ${s}. This can be disabled by setting logging.stdStreams to false, and the log file can be directly monitored/tailed.`)})}o(Xye,"startupLog");function Zye(e){try{return Number.parseInt(Ta.readFileSync(e,"utf8"),10)}catch{return null}}o(Zye,"readPidFile");function eAe(e){try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}}o(eAe,"isProcessRunning")});var Q2={};we(Q2,{SERVERS:()=>Uf,portServer:()=>$D,setPortServerMap:()=>WR});function WR(e,t){let r=$D.get(e)??[];$D.set(e,[...r,t])}var Uf,$D,VD=ce(()=>{Uf={},$D=new Map;o(WR,"setPortServerMap")});function zR(e,t,r=rAe){let n;return function(...i){return n?n.length*KD>r?t(...i):new Promise((a,c)=>{n.push({args:i,fn(){try{let l=e(...i);a(l)}catch(l){c(l)}}})}):(n=[],s(performance.now(),i),e(...i))};function s(i,a){setImmediate(()=>{let c=performance.now();KD=(KD*4+c-i)/5;let l=n.shift();if(l){let{args:u,fn:d}=l;d(),s(c,u)}else n=null})}}var eJ,tAe,rAe,X2,nAe,YD,Z2,KD,WD=ce(()=>{eJ=w(hi()),tAe=3e3,rAe=2e4,X2=0,nAe=3e4,YD=3e3,Z2=performance.now()+YD,KD=0;o(zR,"throttle");setInterval(()=>{let e=performance.now();e-Z2-YD>tAe&&X2+nAe<e&&(eJ.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"),X2=e),Z2=e},YD).unref()});var ey={};we(ey,{deliverSocket:()=>mJ,getHttpOptions:()=>aAe,getRequestId:()=>EJ,handleApplication:()=>oAe,httpServer:()=>tL,logRequest:()=>S_,proxyRequest:()=>cAe,registerServer:()=>ZD,suppressHandleApplicationWarning:()=>iAe});function oAe(e){T_=e.options.getAll(),e.options.on("change",t=>{T_=e.options.getAll()})}function aAe(){return T_}function mJ(e,t,r){let n=e?.read?e:new iJ.Socket({fd:e,readable:!0,writable:!0,allowHalfOpen:!0}),s=Uf[t];if(s.isSecure&&(n.startTime=performance.now()),s)typeof s=="function"?s(n):s.emit("connection",n),r&&n.emit("data",r);else{let i=o(a=>{setTimeout(()=>{let c=Uf[t];c?(typeof c=="function"?c(n):c.emit("connection",n),r&&n.emit("data",r)):a<5?i(a+1):(Aa.default.error(`Server on port ${t} was not registered`),n.destroy())},1e3)},"retry");i(1)}return n}function cAe(e){let{port:t,event:r,data:n,requestId:s}=e,i;switch(i=tJ.get(s),r){case"connection":i=mJ(void 0,t),tJ.set(s,i),i.write=(c,l,u)=>(JR.parentPort.postMessage({requestId:s,event:"data",data:c.toString("latin1")}),u&&u(),!0),i.end=(c,l,u)=>(JR.parentPort.postMessage({requestId:s,event:"end",data:c?.toString("latin1")}),u&&u(),!0);let a=i.destroy;i.destroy=()=>{a.call(i),JR.parentPort.postMessage({requestId:s,event:"destroy"})};break;case"data":i._readableState.destroyed||i.emit("data",Buffer.from(n,"latin1"));break;case"drain":i._readableState.destroyed||i.emit("drain",{});break;case"end":i._readableState.destroyed||i.emit("end",{});break;case"error":i._readableState.destroyed||i.emit("error",{});break}}function ZD(e,t,r=!0){t||(t=Cr.default.get(U.HTTP_PORT));let n=Uf[t];if(n){let s=n.lastServer||n;if(s===e)throw new Error(`Can not register the same server twice for the same port ${t}`);if(r&&!!s.sessionIdContext!=!!e.sessionIdContext&&+t)throw new Error(`Can not mix secure HTTPS and insecure HTTP on the same port ${t}`);s.off("unhandled",sJ),s.on("unhandled",(i,a)=>{e.cantCleanupProperly&&(n.cantCleanupProperly=!0),e.emit("request",i,a)}),n.lastServer=e}else Uf[t]=e;e.on("unhandled",sJ)}function eL(e){let t=[],r=e?.securePort;return r&&t.push({port:r,secure:!0}),r=e?.port,r&&t.push({port:r,secure:!1}),t.length===0&&(t=[],Cr.default.get(U.HTTP_PORT)!=null&&t.push({port:Cr.default.get(U.HTTP_PORT),secure:Cr.default.get(U.CUSTOMFUNCTIONS_NETWORK_HTTPS)}),Cr.default.get(U.HTTP_SECUREPORT)!=null&&t.push({port:Cr.default.get(U.HTTP_SECUREPORT),secure:!0})),e?.isOperationsServer&&Cr.default.get(U.OPERATIONSAPI_NETWORK_DOMAINSOCKET)&&t.push({port:(0,oJ.resolvePath)(Cr.default.get(U.OPERATIONSAPI_NETWORK_DOMAINSOCKET)),secure:!1}),t}function tL(e,t){let r=[];for(let{port:n,secure:s}of eL(t))r.push(hJ(n,s,t?.isOperationsServer,t?.mtls)),typeof e=="function"?QD[t?.runFirst?"unshift":"push"]({listener:e,port:t?.port||n}):(e.isSecure=s,ZD(e,n,!1)),QR[n]=XR(QD,n);return r}function hJ(e,t,r,n){if(WR(e,{protocol_name:t?"HTTPS":"HTTP",name:ty()}),!jR[e]){let s=r?"operationsApi_network":"http",i=Cr.default.get(s+"_keepAliveTimeout"),a=Cr.default.get(s+"_timeout"),c=Cr.default.get(s+"_headersTimeout"),l={keepAliveTimeout:i,headersTimeout:c,requestTimeout:a,highWaterMark:128*1024,noDelay:!0,keepAlive:!0,keepAliveInitialDelay:600,maxHeaderSize:Cr.default.get(U.HTTP_MAXHEADERSIZE)},u=Cr.default.get(s+"_mtls"),d=Cr.default.get(s+"_mtls_required"),f;if(t){let g=Cr.default.get("tls");f=Cr.default.get(s+"_http2"),Object.assign(l,{allowHTTP1:!0,rejectUnauthorized:!!d,requestCert:!!(u||n),ticketKeys:(0,aJ.getTicketKeys)(),SNICallback:(0,cJ.createTLSSelector)(r?"operations-api":"server",u),ciphers:g.ciphers??g[0]?.ciphers})}let m=(0,lJ.checkMemoryLimit)(),h=o(async(g,R)=>{let T=performance.now(),y=0;try{let O=new sc(g,R);r&&(O.isOperationsServer=!0),T_.logging?.id&&(O.requestId=y=EJ());let F=await QR[e](O);if(!F){if(O._nodeResponse.statusCode){S_(g,O._nodeResponse.statusCode,y,performance.now()-T);return}F=pJ(O)}if(F.headers?.set||(F.headers=new Bs(F.headers)),m?F.headers?.set?.("Server","Unlicensed HarperDB, this should only be used for educational and development purposes"):F.headers?.set?.("Server","HarperDB"),F.status===-1){for(let me of F.headers||[])R.setHeader(me[0],me[1]);return g.baseRequest=O,R.baseResponse=F,jR[e].emit("unhandled",g,R)}let Z=F.status||200,q=performance.now(),Y=q-T,K=F.body,$,le=!1;if(!F.handlesHeaders){let me=F.headers||new Bs;K?K.length>=0?(typeof K=="string"?me.set("Content-Length",Buffer.byteLength(K)):me.set("Content-Length",K.length),$=!0):K instanceof Ds&&(K.size?me.set("Content-Length",K.size):K.on&&(le=!0,K.on("size",Me=>{R.headersSent||R.setHeader("Content-Length",Me)})),K=K.stream()):(me.set("Content-Length","0"),$=!0);let De=`hdb;dur=${Y.toFixed(2)}`;if(F.wasCacheMiss&&(De+=", miss"),Mh(me,"Server-Timing",De,!0),!R.headersSent)if(le){if(R.statusCode=Z,me)if(me[Symbol.iterator])for(let[Me,ft]of me)R.setHeader(Me,ft);else for(let Me in me)R.setHeader(Me,me[Me])}else R.writeHead(Z,me&&(me[Symbol.iterator]?Array.from(me):me));$&&R.end(K)}let ue=O.handlerPath,ie=O.method;if(it(Y,"duration",ue,ie,F.wasCacheMiss==null?void 0:F.wasCacheMiss?"cache-miss":"cache-hit"),jr(Z<400,"success",ue,ie),jr(1,"response_"+Z,ue,ie),S_(g,Z,y,Y),!$)if(K instanceof ReadableStream&&(K=JD.Readable.fromWeb(K)),(K[Symbol.iterator]||K[Symbol.asyncIterator])&&(K=JD.Readable.from(K)),K?.pipe){K.pipe(R),K.destroy&&R.on("close",()=>{K.destroy()});let me=0;K.on("data",De=>{me+=De.length}),K.on("end",()=>{it(performance.now()-q,"transfer",ue,ie),it(me,"bytes-sent",ue,ie)})}else K?.then?K.then(me=>{R.end(me)},N):R.end(K)}catch(O){N(O)}function N(O){let F=O.headers,Z=O.statusCode||500;R.writeHead(Z,F&&(F[Symbol.iterator]?Array.from(F):F)),R.end(sAe(O)),S_(g,Z,y,performance.now()-T),O.statusCode?O.statusCode===500?Aa.default.warn(O):Aa.default.info(O):Aa.default.error(O)}o(N,"onError")},"requestHandler"),p=zR(h,(g,R)=>{R.statusCode=503,R.end("Service unavailable, exceeded request queue limit"),it(!0,"service-unavailable",e)},Cr.default.get(s+"_requestQueueLimit")),E=jR[e]=(t?f?uJ.createSecureServer:dJ.createServer:ZR.createServer)(l,(g,R)=>{let T=g.method;T==="GET"||T==="OPTIONS"||T==="HEAD"?h(g,R):p(g,R)});i>=0&&(E.keepAliveTimeout=i),c>=0&&(E.headersTimeout=c),t&&(E.ports||(E.ports=[]),E.ports.push(e),l.SNICallback.initialize(E),u&&(E.mtlsConfig=u),E.on("secureConnection",g=>{g._parent.startTime&&it(performance.now()-g._parent.startTime,"tls-handshake",e),it(g.isSessionReused(),"tls-reused",e)}),E.isSecure=!0),ZD(E,e)}return jR[e]}function XR(e,t){let r=pJ;for(let n=e.length;n>0;){let{listener:s,port:i}=e[--n];if(i===t||i==="all"){let a=r;r=o((...c)=>s(...c,a),"nextCallback")}}return r}function pJ(e){return e.user&&(e._nodeRequest.user=e.user),{status:-1,body:"Not found",headers:new Bs}}function lAe(e,t){tL(e,{requestOnly:!0,...t})}function _J(e,t){for(let{port:r}of eL(t))rJ[t?.runFirst?"unshift":"push"]({listener:e,port:r}),XD[r]=XR(rJ,r)}function uAe(e,t){let r=[];for(let{port:n,secure:s}of eL(t)){WR(n,{protocol_name:s?"WSS":"WS",name:ty()});let i=hJ(n,s,t?.isOperationsServer,t?.mtls);E_[n]||(E_[n]=new fJ.WebSocketServer({noServer:!0,maxPayload:t.maxPayload??100*1024*1024}),E_[n].on("connection",(a,c)=>{try{let l=new sc(c);l.isWebSocket=!0;let u=QR[n](l);Aa.default.debug("Received WS connection, calling listeners",zD),nJ[n](a,l,u)}catch(l){Aa.default.warn("Error in handling WS connection",l)}}),_J((a,c,l,u)=>a.__harperdbRequestUpgraded?u(a,c,l):E_[n].handleUpgrade(a,c,l,d=>{a.__harperdbRequestUpgraded=!0,u(a,c,l),E_[n].emit("connection",d,a)}),{port:n}),i.on("upgrade",(a,c,l)=>{XD[n]&&XD[n](a,c,l)})),r.push(i),zD[t?.runFirst?"unshift":"push"]({listener:e,port:n}),nJ[n]=XR(zD,n),QR[n]=XR(QD,n)}return r}function sJ(e,t){t.headersSent||t.writableEnded||(t.writeHead(404),t.end(`Not found
|
|
124
|
+
`),S_(e,404,0,e.requestId))}function S_(e,t,r,n){let s=T_.logging;if(s){jD||(jD=Aa.default.forComponent("http"));let i=t<400?"info":t===500?"error":"warn";jD[i]?.(`${e.method} ${e.url} ${e.socket.encrypted?"HTTPS":"HTTP"}/${e.httpVersion}${s.headers?" "+dAe(e.headers):""} ${t}${s.timing&&n?" "+n.toFixed(2)+"ms":""}${r?" id: "+r:""}`)}}function dAe(e){let t=[];for(let r in e)t.push(`${r}: ${e[r]}`);return t.join(", ")}function EJ(){return g_||(g_=new BigInt64Array([1n]),g_=new BigInt64Array(databases.system.hdb_analytics.primaryStore.getUserSharedBuffer("next-request-id",g_.buffer))),Number(Atomics.add(g_,0,1n))}var iJ,Aa,JR,Cr,oJ,aJ,cJ,lJ,uJ,dJ,ZR,JD,fJ,sAe,E_,jR,QR,QD,T_,iAe,tJ,rJ,XD,zD,nJ,jD,g_,rL=ce(()=>{iJ=require("node:net"),Aa=w(j()),JR=require("node:worker_threads"),Cr=w(oe());H();oJ=w(gt()),aJ=w(rt()),cJ=w(pn()),lJ=w(of()),uJ=require("node:http2"),dJ=require("node:https"),ZR=require("node:http");Uh();vh();ts();io();JD=require("node:stream");vr();VD();gf();WD();fJ=require("ws"),{errorToString:sAe}=Aa.default;Le.http=tL;Le.request=lAe;Le.ws=uAe;Le.upgrade=_J;E_={},jR={},QR={},QD=[],T_={},iAe=!0;o(oAe,"handleApplication");o(aAe,"getHttpOptions");o(mJ,"deliverSocket");tJ=new Map;o(cAe,"proxyRequest");o(ZD,"registerServer");o(eL,"getPorts");o(tL,"httpServer");o(hJ,"getHTTPServer");o(XR,"makeCallbackChain");o(pJ,"unhandled");o(lAe,"onRequest");Object.defineProperty(ZR.IncomingMessage.prototype,"upgrade",{get(){return"connection"in this.headers&&"upgrade"in this.headers&&this.headers.connection.toLowerCase().includes("upgrade")&&this.headers.upgrade.toLowerCase()=="websocket"},set(e){}});rJ=[],XD={};o(_J,"onUpgrade");zD=[],nJ={};o(uAe,"onWebSocket");o(sJ,"defaultNotFound");o(S_,"logRequest");o(dAe,"headersToString");o(EJ,"getRequestId")});var sL=M(y_=>{"use strict";pE();var{isMainThread:nL,parentPort:gJ,threadId:ry,workerData:fAe}=require("node:worker_threads"),{createServer:mAe}=require("node:net"),{unlinkSync:RJ,existsSync:hAe}=require("fs"),yJ;y_.whenComponentsLoaded=new Promise(e=>{yJ=e});var Hi=j(),ei=oe(),ys=(H(),v(W)),{server:pAe}=(vr(),v(Um)),{createServer:_Ae}=require("node:tls"),{restartNumber:EAe,getWorkerIndex:xf}=rt(),{createReuseportFd:R_}=(Uh(),v(_q)),{createTLSSelector:gAe}=pn(),{resolvePath:SAe}=gt(),{startupLog:TAe}=vf(),{SERVERS:Bf,setPortServerMap:SJ,portServer:RAe}=(VD(),v(Q2)),TJ=(rL(),v(ey)),yAe=mi(),AJ=ei.get(ys.CONFIG_PARAMS.THREADS_DEBUG),AAe=ei.get(ys.CONFIG_PARAMS.HTTP_SESSIONAFFINITY);pAe.socket=bAe;if(AJ){let e;if(nL)e=ei.get(ys.CONFIG_PARAMS.THREADS_DEBUG_PORT)??9229,process.on(["SIGINT","SIGTERM","SIGQUIT","exit"],()=>{try{require("inspector").close()}catch(t){Hi.info("Could not close debugger",t)}});else{let t=ei.get(ys.CONFIG_PARAMS.THREADS_DEBUG_STARTINGPORT);t&&xf()>=0&&(e=t+xf())}if(e){let t=ei.get(ys.CONFIG_PARAMS.THREADS_DEBUG_HOST),r=ei.get(ys.CONFIG_PARAMS.THREADS_DEBUG_WAITFORDEBUGGER);try{require("inspector").open(e,t,r)}catch(n){Hi.trace(`Could not start debugging on port ${e}, you may already be debugging:`,n.message)}}}else if(process.env.DEV_MODE&&nL)try{require("inspector").open(9229)}catch(e){EAe<=1&&Hi.trace("Could not start debugging on port 9229, you may already be debugging:",e.message)}process.on("uncaughtException",e=>{e.isHandled||e.code==="ECONNRESET"||e.code==="ECONNREFUSED"||e.message!=="write EIO"&&Hi.error("uncaughtException",e)});var{HDB_SETTINGS_NAMES:yke,CONFIG_PARAMS:Ake}=ys;ei.initSync();y_.globals=yAe;y_.listenOnPorts=IJ;y_.startServers=bJ;function bJ(){let e=ei.get(ys.CONFIG_PARAMS.ROOTPATH);if(e)try{process.chdir(e)}catch{}let t=ny().loadRootComponents(!0).then(()=>{gJ?.on("message",n=>{let{port:s,fd:i,data:a}=n;if(i)TJ.deliverSocket(i,s,a);else if(n.requestId)TJ.proxyRequest(n);else if(n.type===ys.ITC_EVENT_TYPES.SHUTDOWN){Hi.trace("received shutdown request",ry);for(let c in Bf){let l=Bf[c],u;if(l.closeIdleConnections){let f=Object.getOwnPropertySymbols(l).find(p=>p.description.includes("connections")),m=0,h=setInterval(()=>{m++;let p=m>=100;if(!l[f]){p&&l.closeAllConnections?.(),clearInterval(h);return}let E=l[f][p?"all":"idle"]?.()||[];if(E.length===0){p&&clearInterval(h);return}m===1?Hi.info(`Closing ${E.length} idle connections`):p&&Hi.warn(`Forcefully closing ${E.length} active connections`);for(let g=0,R=E.length;g<R;g++){let T=E[g].socket;T._httpMessage&&!T._httpMessage.finished&&!p||(p?T.destroySoon():T.end(`HTTP/1.1 408 Request Timeout\r
|
|
125
125
|
Connection: close\r
|
|
126
126
|
\r
|
|
127
|
-
`))}},25).unref()}l.close?.(()=>{if(ei.get(ys.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_DOMAINSOCKET)&&xf()==0)try{RJ(SAe(ei.get(ys.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_DOMAINSOCKET)))}catch{}clearInterval(u),setTimeout(()=>{console.log("forced close server",c,ry),l.cantCleanupProperly||Hi.warn("Had to forcefully exit the thread",ry),process.exit(0)},5e3).unref()})}if(AJ||process.env.DEV_MODE)try{require("inspector").close()}catch(c){Hi.info("Could not close debugger",c)}}}).ref();let r;R_&&!AAe&&(r=IJ()),Promise.resolve(r).then(()=>{if(xf()===0)try{TAe(RAe)}catch(n){console.error("Error displaying start-up log",n)}gJ?.postMessage({type:ys.ITC_EVENT_TYPES.CHILD_STARTED})})});return yJ(t),t}o(bJ,"startServers");function IJ(){let e=[];for(let t in Bf){let r=Bf[t];if(t.includes?.("/")&&xf()==0){hAe(t)&&RJ(t),e.push(new Promise((a,c)=>{r.listen({path:t},()=>{a({port:t,name:r.name,protocol_name:r.protocol_name}),Hi.info("Domain socket listening on "+t)}).on("error",c)}));continue}let n,s=ei.get(ys.CONFIG_PARAMS.HTTP_THREADRANGE);if(s){let a=typeof s=="string"?s.split("-"):s,c=xf();if(c<a[0]||c>a[1])continue}let i;try{let a=t.lastIndexOf(":");a>0?R_?n={fd:R_(+t.slice(a+1).replace(/[\[\]]/g,""),t.slice(0,a))}:n={host:+t.slice(a+1).replace(/[\[\]]/g,""),port:t.slice(0,a)}:R_?n={fd:R_(+t,"::")}:n={port:t}}catch(a){console.error(`Unable to bind to port ${t}`,a);continue}e.push(new Promise((a,c)=>{r.listen(n,()=>{a({port:t,name:r.name,protocol_name:r.protocol_name}),Hi.trace("Listening on port "+t,ry)}).on("error",c)}))}return Promise.all(e)}o(IJ,"listenOnPorts");!nL&&!fAe?.noServerStart&&bJ();function bAe(e,t){let r=(gf(),v(xp)).getComponentName,n;if(t.securePort){SJ(t.securePort,{protocol_name:"TLS",name:r()});let s=gAe("server",t.mtls),i=ei.get("tls");n=_Ae({rejectUnauthorized:!!t.mtls?.required,requestCert:!!t.mtls,noDelay:!0,keepAlive:!0,keepAliveInitialDelay:600,ciphers:i.ciphers??i[0]?.ciphers,SNICallback:s},e),s.initialize(n),Bf[t.securePort]=n}return t.port&&(SJ(t.port,{protocol_name:"TCP",name:r()}),n=mAe(e,{noDelay:!0,keepAlive:!0,keepAliveInitialDelay:600}),Bf[t.port]=n),n}o(bAe,"onSocket")});var J2={};we(J2,{startHTTPThreads:()=>NAe,startSocketServer:()=>lL,updateWorkerIdleness:()=>vJ});async function NAe(e=2,t){ew().catch(r=>Gf.error?.("Error recording hostname for analytics:",r));try{if(t)aL(0,1,!0);else{let{loadRootComponents:r}=ny();if(e===0)return(0,ti.setMainIsWorker)(!0),await sL().startServers(),Promise.resolve([]);await r()}MJ();for(let r=0;r<e;r++)aL(r,e);return Promise.all(LJ)}finally{(0,ti.threadsHaveStarted)()}}function MJ(){let e=(0,CJ.checkMemoryLimit)();e&&!process.env.DEV_MODE&&(console.error(e),oL=setInterval(()=>{Gf.notify(e)},IAe).unref())}function aL(e,t=1,r){if(iL++,(0,ti.startWorker)("server/threads/threadServer.js",{name:XA.HTTP,workerIndex:e,threadCount:t,async onStarted(n){let s=new Promise((a,c)=>{function l(u){u.type===zA.CHILD_STARTED&&(n.removeListener("message",l),a(n))}o(l,"onMessage"),n.on("message",l),n.on("error",c)});LJ.push(s),await s,Ff.push(n),n.expectedIdle=1,n.lastIdle=0,n.requests=1,n.on("message",a=>{if(a.requestId){let c=iy.get(a.requestId);c&&c(a)}}),n.on("exit",i),n.on("shutdown",i);function i(){let a=Ff.indexOf(n);a>-1&&Ff.splice(a,1)}if(o(i,"removeWorker"),Hf){let a=Hf;Hf=[];for(let c of a)DJ[c.localPort](null,c)}}}),r){let n=setInterval(()=>{cL?cL=!1:(clearInterval(n),console.log("shut down dynamic thread due to inactivity"),(0,ti.shutdownWorkers)(),iL=0,setTimeout(()=>{global.gc?.()},5e3))},1e4)}}function lL(e=0,t){if(typeof e=="string")try{(0,oy.existsSync)(e)&&(0,oy.unlinkSync)(e)}catch{}let r;t?t==="ip"?r=wAe:r=OAe(t):r=uL;let n=(0,kf.createServer)({allowHalfOpen:!0,pauseOnConnect:!r.readsData}).listen(e);return n._handle&&(n._handle.onconnection=DJ[e]=function(s,i){r.readsData||(i.reading=!1,i.readStop()),cL=!0,r(i,(a,c)=>{if(!a){if(NJ){let u=i._socket||new kf.Socket({handle:i,writable:!0,readable:!0});NJ.deliverSocket(u,e,c),u.resume()}else iL>0?(Hf.length===0&&setTimeout(()=>{Hf.length>0&&console.warn("Incoming sockets/requests have been queued for workers to start, and no workers have handled them. Check to make sure an error is not preventing workers from starting")},1e4).unref(),i.localPort=e,Hf.push(i)):(console.log("start up a dynamic thread to handle request"),aL(0));it(!1,"socket-routed");return}a.requests++;let l=i.fd;if(l>=0)a.postMessage({port:e,fd:l,data:c});else{let u=i._socket||new kf.Socket({handle:i,writable:!0,readable:!0});DAe(u,a,e)}it(!0,"socket-routed")})},Gf.info(`HarperDB ${PJ.packageJson.version} Server running on port ${e}`)),n.on("error",s=>{console.error("Error in socket server",s)}),process.env._UNREF_SERVER&&n.unref(),n}function uL(e,t){let r,n=0;for(let s of Ff){if(s.threadId===-1)continue;let i=s.expectedIdle/s.requests;if(i>n)r=s;else if(n>=sy)return sy=i,t(r);n=i}sy=0,t(r)}function wAe(e,t){let r={};e.getpeername(r);let n=r.address,s=qf.get(n),i=Date.now();if(s&&s.worker.threadId!==-1)return s.lastUsed=i,t(s.worker);uL(e,a=>{qf.set(n,{worker:a,lastUsed:i}),t(a)})}function OAe(e){let t=new RegExp(`${e}:\\s*(.+)`,"i");return r.readsData=!0,r;function r(n,s){let i=new kf.Socket({handle:n,readable:!0,writable:!0});n._socket=i,i.on("data",a=>{n.readStop();let l=a.toString("latin1").match(t)?.[1],u=qf.get(l),d=Date.now();if(u&&u.worker.threadId!==-1)return u.lastUsed=d,s(u.worker);uL(n,f=>{qf.set(l,{worker:f,lastUsed:d}),s(f,a)})})}o(r,"findByHeaderAffinity")}function vJ(){sy=0;for(let e of Ff)e.expectedIdle=e.recentELU.idle+CAe,e.requests=1;Ff.sort((e,t)=>e.expectedIdle>t.expectedIdle?-1:1)}function DAe(e,t,r){let n=PAe++;t.postMessage({port:r,requestId:n,event:"connection"}),e.on("data",s=>{let i=s.toString("latin1");t.postMessage({port:r,requestId:n,data:i,event:"data"})}).on("close",s=>{t.postMessage({port:r,requestId:n,event:"close",hadError:s})}).on("error",s=>{t.postMessage({port:r,requestId:n,event:"error",error:s})}).on("drain",s=>{t.postMessage({port:r,requestId:n,event:"drain",error:s})}).on("end",()=>{t.postMessage({port:r,requestId:n,event:"end"})}).resume(),iy.set(n,s=>{s.event=="data"&&e.write(Buffer.from(s.data,"latin1")),s.event=="end"&&(e.end(s.data&&Buffer.from(s.data,"latin1")),iy.delete(n)),s.event=="destroy"&&(e.destroy(),iy.delete(n))})}var ti,kf,Gf,oy,OJ,CJ,PJ,Ff,Hf,DJ,NJ,iL,LJ,oL,IAe,cL,sy,wJ,qf,CAe,iy,PAe,GD=ce(()=>{ti=w(rt()),kf=require("net");H();Gf=w(j()),oy=require("fs");io();OJ=require("worker_threads"),CJ=w(of()),PJ=w(ht()),Ff=[],Hf=[],DJ=[],iL=0,LJ=[];OJ.isMainThread&&(process.on("uncaughtException",e=>{e.code==="ECONNRESET"||e.code==="ECONNREFUSED"||e.message!=="write EIO"&&console.error("uncaughtException",e)}),(0,ti.onMessageFromWorkers)(e=>{e.type===QA.RESTART&&oL&&(clearInterval(oL),MJ())}));IAe=6e5;o(NAe,"startHTTPThreads");o(MJ,"licenseWarning");o(aL,"startHTTPWorker");o(lL,"startSocketServer");sy=0;o(uL,"findMostIdleWorker");wJ=36e5,qf=new Map;o(wAe,"findByRemoteAddressAffinity");o(OAe,"makeFindByHeaderAffinity");setInterval(()=>{let e=Date.now();for(let[t,r]of qf)r.lastUsed+wJ<e&&qf.delete(t)},wJ).unref();CAe=1e3;o(vJ,"updateWorkerIdleness");(0,ti.setMonitorListener)(vJ);iy=new Map,PAe=1;o(DAe,"proxySocket")});var dL={};we(dL,{hdbServer:()=>UAe,start:()=>UAe});async function UAe(e){try{Ro.default.debug("In Fastify server"+process.cwd()),Ro.default.debug(`Running with NODE_ENV set as: ${process.env.NODE_ENV}`),Ro.default.debug(`HarperDB server process ${process.pid} starting up.`),global.clustering_on=!1,global.isMaster=UJ.default.isMaster,await xAe();let t=e.securePort>0;$f=BAe(t),await $f.ready(),e||(e={}),e.isOperationsServer=!0;try{Le.http($f.server,e),$f.server.closeIdleConnections||await $f.listen({port:0,host:"::"})}catch(r){throw $f.close(),Ro.default.error(r),Ro.default.error("Error configuring operations server"),r}}catch(t){console.error(`Failed to build server on ${process.pid}`,t),Ro.default.fatal(t),process.exit(1)}}async function xAe(){Ro.default.trace("Configuring HarperDB process."),$J.default.setSchemaDataToGlobal(),await KJ.default.setUsersWithRolesCache(),await YJ.default.getLicense()}function BAe(e){Ro.default.debug(`HarperDB process starting to build ${e?"HTTPS":"HTTP"} server.`);let t=FAe(e),r=(0,xJ.default)(t);r.server.headersTimeout=kAe(),r.setErrorHandler(Fc.serverErrorHandler);let n=HAe();n&&r.register(BJ.default,n),r.register(function(i,a,c){i.setNotFoundHandler(function(l,u){r.server.emit("unhandled",l.raw,u.raw)}),c()}),r.register(kJ.default),r.register(FJ.default),r.register(HJ.default,{root:qJ.default.join(GJ.PACKAGE_ROOT,"studio/build-local")}),Vm(r);let s=Bc.default.get(WA.LOCAL_STUDIO_ON);return r.get("/",function(i,a){return!VJ.default.isEmpty(s)&&s.toString().toLowerCase()==="true"?a.sendFile("index.html"):a.sendFile("running.html")}),r.post("/",{preValidation:[Fc.reqBodyValidationHandler,Fc.authHandler],config:{isOperation:!0}},async function(i,a){return i.body?.operation?.startsWith("restart")&&a.header("Connection","close"),(0,Fc.handlePostRequest)(i,a)}),r.get("/health",()=>"HarperDB is running."),Ro.default.debug(`HarperDB process starting up ${e?"HTTPS":"HTTP"} server listener.`),r}function FAe(e){let t=Bc.default.get(A_.OPERATIONSAPI_NETWORK_TIMEOUT),r=Bc.default.get(A_.OPERATIONSAPI_NETWORK_KEEPALIVETIMEOUT);return{bodyLimit:MAe,connectionTimeout:t,keepAliveTimeout:r,forceCloseConnections:!0,return503OnClosing:!1,https:e}}function HAe(){let e=Bc.default.get(A_.OPERATIONSAPI_NETWORK_CORS),t=Bc.default.get(A_.OPERATIONSAPI_NETWORK_CORSACCESSLIST),r;return e&&(e===!0||e.toUpperCase()===vAe)&&(r={origin:!0,allowedHeaders:["Content-Type","Authorization","Accept"],credentials:!1},t&&t.length>0&&t[0]!==null&&t[0]!=="*"&&(r.origin=(n,s)=>s(null,t.indexOf(n)!==-1))),r}function kAe(){return Bc.default.get(A_.OPERATIONSAPI_NETWORK_HEADERSTIMEOUT)??LAe}var UJ,Bc,Ro,xJ,BJ,FJ,HJ,kJ,qJ,GJ,$J,VJ,KJ,YJ,Fc,LAe,MAe,vAe,A_,$f,WJ=ce(()=>{UJ=w(require("cluster")),Bc=w(oe());H();Ro=w(j()),xJ=w(require("fastify")),BJ=w(require("@fastify/cors")),FJ=w(require("@fastify/compress")),HJ=w(require("@fastify/static")),kJ=w(fw()),qJ=w(require("path")),GJ=w(ht()),$J=w(Us()),VJ=w(se()),KJ=w(xn()),YJ=w(of());vr();Fc=w(bR());Uo();Bc.default.initSync();LAe=6e4,MAe=1024*1024*1024,vAe="TRUE",{CONFIG_PARAMS:A_}=W;o(UAe,"operationsServer");o(xAe,"setUp");o(BAe,"buildServer");o(FAe,"getServerOptions");o(HAe,"getCORSOpts");o(kAe,"getHeaderTimeoutConfig")});var EL={};we(EL,{disableNATS:()=>GAe,publishToStream:()=>ly,setNATSReplicator:()=>fL,setPublishToStream:()=>$Ae,setSubscription:()=>_L,start:()=>qAe});function qAe(){b_.default.get(U.CLUSTERING_ENABLED)&&KAe()}function GAe(e=!0){XJ=e}function $Ae(e,t){ly=e,_L=t}function KAe(){if(XJ||process.env._DISABLE_NATS)return;let e=st(),t=Object.keys(e);t.push("system");for(let r of t){let n=e[r];for(let s in n){let i=n[s];fL(s,r,i)}}jl((r,n)=>{fL(r.tableName,r.databaseName,r),n&&eQ(r)}),!zJ&&(zJ=!0)}function fL(e,t,r){if(t==="system"&&YAe.includes(e))return;if(!r)return console.error(`Attempt to replicate non-existent table ${e} from database ${t}`);if(r.sources.some(s=>s?.isNATSReplicator))return;r.sourcedFrom(class extends Hr{static{o(this,"NATSReplicator")}put(i){return n(this.getContext()).addWrite(t,{operation:"put",table:e,id:this.getId(),record:i})}delete(){return n(this.getContext()).addWrite(t,{operation:"delete",table:e,id:this.getId()})}publish(i){return n(this.getContext()).addWrite(t,{operation:"publish",table:e,id:this.getId(),record:i})}patch(i){return n(this.getContext()).addWrite(t,{operation:"patch",table:e,id:this.getId(),record:i})}invalidate(){n(this.getContext()).addWrite(t,{operation:"invalidate",table:e,id:this.getId()})}static defineSchema(i){eQ(i)}static subscribe(){let i=new es;return _L(t,e,i),i}static subscribeOnThisThread(i){return i<(b_.default.get(U.CLUSTERING_LEAFSERVER_STREAMS_MAXINGESTTHREADS)??VAe)}static isEqual(i){return i.isNATSReplicator}static isNATSReplicator=!0;static shouldReceiveInvalidations=!0},{intermediateSource:!0});function n(s){let i=s?.transaction?.nats;if(!i)if(s?.transaction){s.transaction.nats=i=new ay(s.transaction,s);let a=s.transaction;for(;a.next;)a=a.next;a.next=s.transaction.nats,i.user=s.user,i.context=s}else i=ZJ;return i}o(n,"getNATSTransaction")}function eQ(e){let t=b_.default.get(U.CLUSTERING_NODENAME);ly(`${hL.SUBJECT_PREFIXES.TXN}.${e.databaseName}.${e.tableName}`,(0,pL.createNatsTableStreamName)(e.databaseName,e.tableName),void 0,{operation:"define_schema",schema:e.databaseName,table:e.tableName,attributes:e.attributes,__origin:{timestamp:Date.now(),node_name:t}})}var jJ,hL,pL,JJ,QJ,b_,cy,XJ,ly,_L,VAe,ZJ,zJ,YAe,ay,mL,tQ=ce(()=>{Pe();tc();jJ=w(sr()),hL=w(Ot()),pL=w(Zi());zu();JJ=w(Ow()),QJ=w(Cn()),b_=w(oe());H();cy=w(j());o(qAe,"start");o(GAe,"disableNATS");ly=jJ.publishToStream,_L=JJ.setSubscription;o($Ae,"setPublishToStream");VAe=2;o(KAe,"assignReplicationSource");YAe=["hdb_job","hdb_raw_analytics","hdb_info","hdb_license"];o(fL,"setNATSReplicator");o(eQ,"publishSchema");ay=class{constructor(t,r){this.transaction=t;this.options=r}static{o(this,"NATSTransaction")}user;writesByDb=new Map;addWrite(t,r){r.expiresAt=this.context?.expiresAt;let n=this.writesByDb.get(t);n||this.writesByDb.set(t,n=[]),n.push(r)}commit({timestamp:t}){let r=b_.default.get(U.CLUSTERING_NODENAME),n=[];for(let[s,i]of this.writesByDb){let a=[],c=[],l,u;for(let d of i){let f=d.table,m=d.operation=="put"?"upsert":d.operation;l||(cy.trace(`Sending transaction event ${m}`),u=l={operation:m,schema:s,table:f,__origin:{user:this.user?.username,timestamp:t,node_name:r}},l.hash_values=c,m!=="delete"&&m!=="invalidate"&&(l.records=a)),l.table===f&&l.operation===m?(a.push(d.record),c.push(d.id)):u=u.next={operation:m,table:f,id:d.id,record:d.record},d.expiresAt&&(u.expiresAt=d.expiresAt)}l&&n.push(ly(`${hL.SUBJECT_PREFIXES.TXN}.${s}.${l.table}`,(0,pL.createNatsTableStreamName)(s,l.table),void 0,l)?.catch(d=>{throw cy.error("An error has occurred trying to replicate transaction",l,d),d.statusCode=504,d}))}return Promise.all(n)}},mL=class extends ay{static{o(this,"ImmmediateNATSTransaction")}constructor(){super({get timestamp(){return(0,QJ.getNextMonotonicTime)()}})}addWrite(t,r){super.addWrite(t,r),this.commit({})}};ZJ=new mL});async function oQ({clientId:e,user:t,clean:r,will:n,keepalive:s}){let i;if(e&&!r){let a=await gL.get(e,{returnNonexistent:!0});i=new RL(e,t,a),a&&(i.sessionWasPresent=!0)}else{if(e){let a=await gL.get(e);a&&a.delete()}i=new dy(e,t)}return n&&(n.id=e,n.user={username:t?.username},I_.put(n)),s&&(i.keepalive=s,i.receivedPacket()),i}function SL(){return uy++,uy>65500&&(uy=1),uy}function TL(e,t,r){let{topic:n,retain:s}=e;e.data=t,e.async=!0,r.authorize=!0;let i=Ls.getMatch(n,"mqtt");if(!i)throw new Error(`Can not publish to topic ${n} as it does not exist, no resource has been defined to handle this topic`);e.url=i.relativeURL;let a=new Ai(i.relativeURL);a.checkPermission=r.user?.role?.permission??{};let c=i.Resource;return Ft(r,()=>s?t===void 0?c.delete(a,r):c.put(a,e.data,r):c.publish(a,e.data,r))}var nQ,Hc,sQ,iQ,rQ,gL,I_,uy,dy,RL,aQ=ce(()=>{Pe();td();nQ=w(Cn()),Hc=w(j());ol();sQ=w(rt()),iQ=w(sL());vr();zg();rQ=100,gL=ze({database:"system",table:"hdb_durable_session",attributes:[{name:"id",isPrimaryKey:!0},{name:"subscriptions",type:"array",elements:{attributes:[{name:"topic"},{name:"qos"},{name:"startTime"},{name:"acks"}]}}]}),I_=ze({database:"system",table:"hdb_session_will",attributes:[{name:"id",isPrimaryKey:!0},{name:"topic",type:"string"},{name:"data"},{name:"qos",type:"number"},{name:"retain",type:"boolean"},{name:"user",type:"any"}]});(0,sQ.getWorkerIndex)()===0&&(async()=>{await iQ.whenComponentsLoaded,await new Promise(e=>setTimeout(e,2e3));for await(let e of I_.search({})){let t=e.data,r={...e};r.user?.username&&(r.user=await Le.getUser(r.user.username));try{await TL(r,t,r)}catch{(0,Hc.warn)("Failed to publish will",t)}I_.delete(e.id)}})();o(oQ,"getSession");uy=1;o(SL,"getNextMessageId");dy=class{static{o(this,"SubscriptionsSession")}listener;sessionId;user;request;socket;subscriptions=[];awaitingAcks;sessionWasPresent;keepalive;keepaliveTimer;constructor(t,r){this.sessionId=t,this.user=r}async addSubscription(t,r,n){let{topic:s,rh:i,startTime:a}=t,c=s.indexOf("?"),l,u;if(c>-1?(l=s.slice(c),u=s.slice(0,c)):u=s,!u)throw new Error("No topic provided");if(u.indexOf(".")>-1)throw new Error("Dots are not allowed in topic names");let d=this.subscriptions.find(T=>T.topic===s),f;d?(f=i>0,d.end(),this.subscriptions.splice(this.subscriptions.indexOf(d),1)):f=i===2;let m={search:l,async:!0,user:this.user,startTime:a,omitCurrent:f,target:"",checkPermission:this.user?.role?.permission??{}};a&&(0,Hc.trace)("Resuming subscription from",s,"from",a);let h=Ls.getMatch(u,"mqtt");if(!h){let T=new Error(`The topic ${s} does not exist, no resource has been defined to handle this topic`);throw T.statusCode=404,T}m.url=h.relativeURL;let p;if(m.url.indexOf("+")>-1||(p=m.url.indexOf("#"))>-1){let T=m.url.slice(1);if(p--,p>-1&&p!==T.length-1)throw new Error("Multi-level wildcards can only be used at the end of a topic");if(m.isCollection=!0,T.indexOf("+")===T.length-1)m.onlyChildren=!0,m.url="/"+T.slice(0,T.length-1);else{let y=T.split("/"),N;for(let Z=0;Z<y.length;Z++)if(y[Z].indexOf("+")>-1)if(y[Z]==="+")N=!0;else throw new Error("Single-level wildcards can only be used as a topic level (between or after slashes)");if(n&&N)throw new Error("Filters can not be combined");let O=!0;y[y.length-1]==="#"&&(y.length--,O=!1),N&&(n=o(Z=>{let q=Z.id;if(!Array.isArray(q))if(q?.indexOf?.("/")>-1)q=q.split("/");else return!1;if(O&&q.length!==y.length)return!1;for(let Y=0;Y<y.length;Y++)if(y[Y]!=="+"&&y[Y]!==q[Y])return!1;return!0},"filter"));let F=y.indexOf("+");m.url="/"+(F>-1?y.slice(0,F):y).concat("").join("/")}}else m.isCollection=!1;let E=h.path,g=h.Resource,R=await Ft(m,async()=>{let T=this.createContext();T.topic=s,T.retainHandling=i,T.isCollection=m.isCollection;let y=await g.subscribe(m,T);if(!y)return;if(!y[Symbol.asyncIterator])throw new Error(`Subscription is not (async) iterable for topic ${s}`);let N=(async()=>{for await(let O of y)try{let F;if(O.type&&O.type!=="put"&&O.type!=="delete"&&O.type!=="message"&&O.type!=="patch"||n&&!n(O))continue;r?(O.topic=s,F=this.needsAcknowledge(O)):(O.acknowledge?.(),F=SL());let Z=O.id;if(Array.isArray(Z)&&(Z=ed(Z)),Z==null&&(Z=""),await this.listener(E+"/"+Z,O.value,F,t)===!1)break;this.awaitingAcks?.size>rQ?await new Promise(Y=>setTimeout(Y,this.awaitingAcks.size-rQ)):await new Promise(setImmediate)}catch(F){(0,Hc.warn)(F)}})();return y});if(R)return R.topic=s,R.qos=t.qos,this.subscriptions.push(R),R}resume(){}needsAcknowledge(t){let r=SL();return t.acknowledge&&(this.awaitingAcks||(this.awaitingAcks=new Map),this.awaitingAcks.set(r,{acknowledge:t.acknowledge})),r}acknowledge(t){let r=this.awaitingAcks?.get(t);r&&(this.awaitingAcks.delete(t),r.acknowledge())}async removeSubscription(t){let r=this.subscriptions.find(n=>n.topic===t);if(r)return r.end(),this.subscriptions.splice(this.subscriptions.indexOf(r),1),!0}async publish(t,r){return TL(t,r,this.createContext())}createContext(){let t={session:this,socket:this.socket,user:this.user,authorize:!0};return this.request&&(t.request=this.request,t.url=this.request.url,t.headers=this.request.headers),t}setListener(t){this.listener=t}disconnect(t){this.keepaliveTimer&&clearTimeout(this.keepaliveTimer);let r=this.createContext();Ft(r,async()=>{try{if(!t){let n=await I_.get(this.sessionId);n?.doesExist()&&await TL(n,n.data,r)}}finally{await I_.delete(this.sessionId)}}).catch(n=>{(0,Hc.warn)(`Error publishing MQTT will for ${this.sessionId}`,n)});for(let n of this.subscriptions)n.end();this.subscriptions=[]}receivedPacket(){this.keepalive&&(clearTimeout(this.keepaliveTimer),this.keepaliveTimer=setTimeout(()=>{this.socket?.destroy?this.socket.destroy(new Error("Keepalive timeout")):this.socket?.terminate()},this.keepalive*1500))}};o(TL,"publish");RL=class extends dy{static{o(this,"DurableSubscriptionsSession")}sessionRecord;constructor(t,r,n){super(t,r),this.sessionRecord=n||{id:t,subscriptions:[]}}async resume(){for(let t of this.sessionRecord.subscriptions||[])await this.resumeSubscription({omitCurrent:!0,topic:t.topic,qos:t.qos,startTime:t.startTime},!0,t.acks?r=>!t.acks.includes(r.localTime):null)}resumeSubscription(t,r,n){return super.addSubscription(t,r,n)}needsAcknowledge(t){this.awaitingAcks||(this.awaitingAcks=new Map);let r=SL(),n={topic:t.topic,timestamp:t.localTime};return t.acknowledge&&(n.acknowledge=t.acknowledge),this.awaitingAcks.set(r,n),r}acknowledge(t){let r=this.awaitingAcks?.get(t);if(!r)return;this.awaitingAcks?.delete(t),r.acknowledge?.();let n=r.topic;for(let[,s]of this.awaitingAcks)if(s.topic===n&&s.timestamp<r.timestamp){for(let i of this.sessionRecord.subscriptions)if(i.topic===n){i.acks||(i.acks=[]),i.acks.push(r.timestamp),(0,Hc.trace)("Received ack",n,r.timestamp),this.sessionRecord.update();return}}for(let s of this.sessionRecord.subscriptions)s.topic===n&&(s.startTime=r.timestamp);this.sessionRecord.update()}async addSubscription(t,r){await this.resumeSubscription(t,r);let{qos:n,startTime:s}=t;return n>0&&!s&&this.saveSubscriptions(),t.qos}removeSubscription(t){let r=this.subscriptions.find(s=>s.topic===t),n=super.removeSubscription(t);return r.qos>0&&this.saveSubscriptions(),n}saveSubscriptions(){this.sessionRecord.subscriptions=this.subscriptions.map(t=>{let r=t.startTime;return r||(r=t.startTime=(0,nQ.getNextMonotonicTime)()),(0,Hc.trace)("Added durable subscription",t.topic,r),{qos:t.qos,topic:t.topic,startTime:r}}),gL.put(this.sessionRecord)}}});var yL={};we(yL,{bypassAuth:()=>WAe,start:()=>jAe});function WAe(){hQ=!0}function jAe({server:e,port:t,network:r,webSocket:n,securePort:s,requireAuthentication:i}){e.mqtt||(e.mqtt={requireAuthentication:i,sessions:new Set,events:new mQ.EventEmitter},e.mqtt.events.on("error",()=>{}));let a=e.mqtt,c=[],l=r?.mtls;return n&&(c=e.ws((u,d,f,m)=>{if(d.headers.get("sec-websocket-protocol")!=="mqtt")return m(u,d,f);a.events.emit("connection",u),lr.debug?.("Received WebSocket connection for MQTT from",u._socket.remoteAddress);let{onMessage:h,onClose:p}=lQ(u,E=>{u.send(E)},d,Promise.resolve(f).then(()=>d?.user),a);u.on("message",h),u.on("close",p),u.on("error",E=>{lr.info?.("WebSocket error",E)})},{...n})),(t||s)&&c.push(e.socket(async u=>{let d;if(a.events.emit("connection",u),lr.debug?.(`Received ${u.getCertificate?"SSL":"TCP"} connection for MQTT from ${u.remoteAddress}`),l){if(u.authorized)try{let h=l.user;if(h!==null){(h===void 0||h==="Common Name"||h==="CN")&&(h=u.getPeerCertificate().subject.CN);try{d=await e.getUser(h,null,null),(0,Vf.get)(U.LOGGING_AUDITAUTHEVENTS_LOGSUCCESSFUL)&&my.notify?.({username:d?.username,status:fi.SUCCESS,type:ka.AUTHENTICATION,authStrategy:"MQTT mTLS",remoteAddress:u.remoteAddress})}catch(p){throw(0,Vf.get)(U.LOGGING_AUDITAUTHEVENTS_LOGFAILED)&&my.error?.({username:h,status:fi.FAILURE,type:ka.AUTHENTICATION,authStrategy:"mqtt",remoteAddress:u.remoteAddress}),p}}else lr.debug?.("MQTT mTLS authorized connection (mTLS did not authorize a user)","from",u.remoteAddress)}catch(h){a.events.emit("error",h,u),lr.error?.(h)}else if(l.required)return lr.info?.(`Unauthorized connection attempt, no authorized client certificate provided, error: ${u.authorizationError}`),u.end()}!d&&zAe(u.remoteAddress)&&(d=await(0,uQ.getSuperUser)(),lr.debug?.("Auto-authorizing local connection",d?.username));let{onMessage:f,onClose:m}=lQ(u,h=>u.write(h),null,d,a);u.on("data",f),u.on("close",m),u.on("error",h=>{lr.info?.("Socket error",h)})},{port:t,securePort:s,mtls:l})),c}function lQ(e,t,r,n,s){cQ||(cQ=!0,Lh(f=>{fy>0&&f.push({metric:"mqtt-connections",connections:fy,byThread:!0})}));let i;fy++;let a,c={protocolVersion:4},l=(0,hy.parser)({protocolVersion:5});function u(f){l.parse(f)}o(u,"onMessage");function d(){fy--,i||(i=!0,a?.disconnect?.(),s.events.emit("disconnected",a,e),s.sessions.delete(a),jr(!1,"connection","mqtt","disconnect"),lr.debug?.("MQTT connection was closed",e.remoteAddress))}return o(d,"onClose"),l.on("packet",async f=>{try{n?.then&&(n=await n)}catch(y){e.close?.(1008,"Unauthorized"),lr.info?.(y);return}let m=f.cmd;if(a)a.then&&await a;else if(m!=="connect"){lr.info?.("Received packet before connection was established, closing connection"),e?.destroy?e.destroy():e?.terminate();return}let h=f.topic,p=h?.indexOf("/",1),E=p>0?h.slice(0,p):h;it(f.length,"bytes-received",E,R(f),"mqtt");try{switch(a?.receivedPacket?.(),m){case"connect":if(c.protocolVersion=f.protocolVersion,f.username)try{n=await Le.getUser(f.username,f.password.toString(),r),(0,Vf.get)(U.LOGGING_AUDITAUTHEVENTS_LOGSUCCESSFUL)&&my.notify?.({username:n?.username,status:fi.SUCCESS,type:ka.AUTHENTICATION,authStrategy:"MQTT",remoteAddress:e.remoteAddress})}catch(K){return(0,Vf.get)(U.LOGGING_AUDITAUTHEVENTS_LOGFAILED)&&my.error?.({username:f.username,status:fi.FAILURE,type:ka.AUTHENTICATION,authStrategy:"mqtt",remoteAddress:e.remoteAddress}),s.events.emit("auth-failed",f,e,K),jr(!1,"connection","mqtt","connect"),g({cmd:"connack",reasonCode:4,returnCode:134})}if(!n&&s.requireAuthentication)return s.events.emit("auth-failed",f,e),jr(!1,"connection","mqtt","connect"),g({cmd:"connack",reasonCode:4,returnCode:134});try{if(s.authorizeClient?.(f,n),f.will){let K=e.deserialize||(e.deserialize=Fo(r?.headers.get?.("content-type")));f.will.data=f.will.payload?.length>0?K(f.will.payload):void 0,delete f.will.payload}a=oQ({user:n,...f}),a=await a,a.socket=e,r&&(a.request=r),s.sessions.add(a)}catch(K){return lr.error?.(K),s.events.emit("auth-failed",f,e,K),jr(!1,"connection","mqtt","connect"),g({cmd:"connack",reasonCode:K.code||5,returnCode:K.code||128})}s.events.emit("connected",a,e),jr(!0,"connection","mqtt","connect"),g({cmd:"connack",sessionPresent:a.sessionWasPresent,reasonCode:0,returnCode:0});let y=o(async(K,$,le,ue)=>{try{if(i)throw new Error("Session disconnected while trying to send message to",K);let ie=K.indexOf("/",1),me=ie>0?K.slice(0,ie):K;g({cmd:"publish",topic:K,payload:await T($),messageId:le||Math.floor(Math.random()*1e8),qos:ue.qos},me);let De=e._socket??e;return De.writableNeedDrain?new Promise(Me=>De.once("drain",Me)):!De.closed}catch(ie){return lr.error?.(ie),a?.disconnect(),s.sessions.delete(a),!1}},"listener");a.setListener(y),a.sessionWasPresent&&await a.resume();break;case"subscribe":let N=[];for(let K of f.subscriptions){let $;try{let le=await a.addSubscription(K,K.qos>=1);$=le?le.qos||0:c.protocolVersion<5?128:143}catch(le){s.events.emit("error",le,e,K,a),le.statusCode?le.statusCode===500?lr.warn?.(le):lr.info?.(le):lr.error?.(le),$=c.protocolVersion<5?128:le.statusCode===403?135:le.statusCode===404?143:128}N.push($)}await a.committed,g({cmd:"suback",granted:N,messageId:f.messageId});break;case"unsubscribe":{let K=[];for(let $ of f.unsubscriptions)K.push(a.removeSubscription($)?0:17);g({cmd:"unsuback",granted:K,messageId:f.messageId});break}case"pubrel":g({cmd:"pubcomp",messageId:f.messageId,reasonCode:0});return;case"publish":let O=f.qos===2?"pubrec":"puback",F=e.deserialize||(e.deserialize=Fo(r?.headers.get?.("content-type"))),q=(f.payload?.length||0)>0?F(f.payload):void 0,Y;try{Y=await a.publish(f,q)}catch(K){s.events.emit("error",K,e,f,a),lr.warn?.(K),f.qos>0&&g({cmd:O,messageId:f.messageId,reasonCode:128},f.topic);break}f.qos>0&&g({cmd:O,messageId:f.messageId,reasonCode:Y===!1?144:0},f.topic);break;case"pubrec":g({cmd:"pubrel",messageId:f.messageId,reasonCode:0});break;case"pubcomp":case"puback":a.acknowledge(f.messageId);break;case"pingreq":g({cmd:"pingresp"});break;case"disconnect":i=!0,a?.disconnect(!0),s.events.emit("disconnected",a,e),s.sessions.delete(a),jr(!0,"connection","mqtt","disconnect"),lr.debug?.("Received disconnect command, closing MQTT session",e.remoteAddress),e.close?e.close():e.end();break}}catch(y){s.events.emit("error",y,e,f,a),lr.error?.(y),g({cmd:"disconnect"})}function g(y,N){let O=(0,hy.generate)(y,c);t(O),it(O.length,"bytes-sent",N,R(y),"mqtt")}o(g,"sendPacket");function R(y){return y.qos>0?y.cmd+",qos="+y.qos:y.cmd}o(R,"packetMethodName");function T(y){return Ka(y,r)}o(T,"serialize")}),l.on("error",f=>{lr.warn("MQTT parsing error, closing connection:",f.message),e?.destroy?e.destroy():e?.terminate()}),{onMessage:u,onClose:d}}var hy,uQ,Vf,dQ,fQ,mQ,my,lr,hQ,zAe,cQ,fy,pQ=ce(()=>{hy=require("mqtt-packet");aQ();uQ=w(xn());Uo();io();vr();Vf=w(oe());H();dQ=w(hi()),fQ=w(j()),mQ=require("events"),my=(0,dQ.loggerWithTag)("auth-event"),lr=(0,fQ.forComponent)("mqtt"),hQ=(0,Vf.get)(U.AUTHENTICATION_AUTHORIZELOCAL)??process.env.DEV_MODE;o(WAe,"bypassAuth");zAe=o(e=>hQ&&(e.includes("127.0.0.")||e==="::1"),"authorizeLocal");o(jAe,"start");fy=0;o(lQ,"onSocket")});function py(e,t){if(t?.includes(".."))throw new AL(t);let r=t||"/";return(r==="."||r.startsWith("./"))&&(r=`/${e}${r.slice(1)}`),r.startsWith("/")||(r=`/${r}`),r.endsWith("/")||(r=`${r}/`),r}var AL,bL=ce(()=>{AL=class extends Error{static{o(this,"InvalidBaseURLPathError")}constructor(t){super(`urlPath must not contain '..'. Received: '${t}'`)}};o(py,"resolveBaseURLPath")});function _Q(e){if(e.length===0)return".";if(e.length===1)return e[0];let t=e.map(s=>s.split("/")),r=Math.min(...t.map(s=>s.length)),n=[];for(let s=0;s<r;s++){let i=t[0][s];if(t.every(a=>a[s]===i))n.push(i);else break}return n.length===0?".":n.join("/")}var EQ=ce(()=>{o(_Q,"deriveCommonPatternBase")});function _y(e){let t={source:[],onlyFiles:!1,onlyDirectories:!1,ignore:[]},r=o((n,s)=>{typeof s=="string"?n.push(s):Array.isArray(s)&&n.push(...s)},"addToArray");return typeof e=="string"||Array.isArray(e)?r(t.source,e):(r(t.source,e.source),r(t.ignore,e.ignore),t.onlyFiles=e.only==="files",t.onlyDirectories=e.only==="directories"),t}var IL=ce(()=>{o(_y,"deriveGlobOptions")});var gQ,NL,N_,SQ=ce(()=>{bL();EQ();IL();gQ=require("micromatch"),NL=class extends Error{static{o(this,"ComponentInvalidPatternError")}constructor(t){super(`Config 'files' option glob pattern must not contain '..' or start with '/'. Received: '${t}'`),this.name="ComponentInvalidPatternError"}},N_=class{static{o(this,"Component")}globOptions;baseURLPath;patternBases;directory;name;config;commonPatternBase;constructor(t,r,n){this.name=t,this.directory=r,this.config=n,this.baseURLPath=py(this.name,this.config.urlPath),this.globOptions=_y(this.config.files),this.globOptions.source=this.globOptions.source.map(s=>{if(s.includes("..")||s.startsWith("/"))throw new NL(s);return s==="."||s==="./"?"**/*":s}),this.patternBases=this.globOptions.source.map(s=>(0,gQ.scan)(s).base),this.commonPatternBase=_Q(this.patternBases)}}});function TQ(e,t){return new RegExp(`^${e}(/|$)`).test(t)}function Iu(e,t,r){t.startsWith("./")&&(t=t.slice(2));for(let n of e.patternBases)if(n.startsWith("./")&&(n=n.slice(2)),n!==""){if(r==="file"){if(t===n){let s=t.split("/");t=s[s.length-1];break}else if(TQ(n,t)){t=t.slice(n.length+1);break}}if(r==="directory"){if(t===n){t="";break}else if(TQ(n,t)){t=t.slice(n.length+1);break}}}return(0,RQ.join)(e.baseURLPath,t)}var RQ,wL=ce(()=>{RQ=require("node:path");o(TQ,"pathStartsWithBase");o(Iu,"deriveURLPath")});function yQ(e){return typeof e=="string"||Array.isArray(e)||!("files"in e)?{files:e}:e}var gy,AQ,bQ,OL,IQ,NQ,Ey,wQ=ce(()=>{gy=require("node:events");SQ();AQ=w(j()),bQ=w(require("chokidar")),OL=require("node:path"),IQ=require("node:fs/promises");wL();NQ=require("micromatch"),Ey=class extends gy.EventEmitter{static{o(this,"EntryHandler")}#e;#t;#r;ready;constructor(t,r,n,s){super(),this.#e=new N_(t,r,yQ(n)),this.#r=s||AQ.default.loggerWithTag(t),this.ready=(0,gy.once)(this,"ready"),this.#a()}get name(){return this.#e.name}get directory(){return this.#e.directory}#n(...[t,r,n]){if(r===""&&(r="/"),!(0,NQ.isMatch)(r,this.#e.globOptions.source,{ignore:this.#e.globOptions.ignore}))return;let s=(0,OL.join)(this.directory,r);switch(t){case"add":case"change":{let i=Iu(this.#e,r,"file");(0,IQ.readFile)(s).then(a=>{let c={eventType:t,entryType:"file",contents:a,stats:n,absolutePath:s,urlPath:i};this.emit("all",c),this.emit(t,c)});break}case"unlink":{let i=Iu(this.#e,r,"file"),a={eventType:t,entryType:"file",stats:n,absolutePath:s,urlPath:i};this.emit("all",a),this.emit(t,a);break}case"addDir":case"unlinkDir":{let i=Iu(this.#e,r,"directory"),a={eventType:t,entryType:"directory",stats:n,absolutePath:s,urlPath:i};this.emit("all",a),this.emit(t,a);break}}}#s(t){this.emit("error",t)}#i(){this.emit("ready")}async#a(){await this.#t?.close(),this.#t=void 0;let t=this.#e.patternBases.map(r=>(0,OL.join)(this.#e.directory,r));return this.#t=bQ.default.watch(this.#e.commonPatternBase,{cwd:this.#e.directory,persistent:!1,ignored:o(r=>{let n=r.replace(/\\/g,"/"),s=t.map(i=>i.replace(/\\/g,"/"));return n!==this.#e.directory.replace(/\\/g,"/")&&s.every(i=>!n.startsWith(i))},"ignored")}).on("all",this.#n.bind(this)).on("error",this.#s.bind(this)).on("ready",this.#i.bind(this)),this.ready}close(){return this.#t?.close(),this.#t=void 0,this.emit("close"),this.removeAllListeners(),this}update(t){return this.#e=new N_(this.name,this.directory,yQ(t)),this.#a()}};o(yQ,"castConfig")});var Sy,CL=ce(()=>{Sy={rest:!0,graphqlSchema:{files:"*.graphql"},roles:{files:"roles.yaml"},jsResource:{files:"resources.js"},fastifyRoutes:{files:"routes/*.js"},static:{files:"web/**"}}});var Ry,OQ,CQ,PQ,DQ,LQ,PL,DL,LL,ML,vL,Ty,MQ=ce(()=>{Ry=require("events"),OQ=w(require("yaml")),CQ=w(require("chokidar")),PQ=require("node:fs/promises"),DQ=require("util"),LQ=w(j());CL();PL=class extends Error{static{o(this,"OptionsWatcherConfigFileError")}constructor(t,r){super(`Error watching config file ${t}: ${typeof r=="object"&&r!==null&&"message"in r?r.message:r}`),this.name="OptionsWatcherConfigFileError"}},DL=class extends Error{static{o(this,"InvariantUninitializedOptionsWatcherError")}constructor(){super("Invariant: OptionsWatcher has not been initialized yet. This should never happen."),this.name="InvariantUninitializedOptionsWatcherError"}},LL=class extends Error{static{o(this,"InvalidValueTypeError")}constructor(t,r){super(`Invalid value type for key ${t.join(".")}. Expected object, string, array, number, boolean, or undefined. Received ${typeof r}.`),this.name="InvalidValueTypeError"}},ML=class extends Error{static{o(this,"KeyDoesNotExistError")}constructor(t,r){super(`Cannot set property ${t.join(".")} as ${r} does not exist.`),this.name="KeyDoesNotExistError"}},vL=class extends Error{static{o(this,"CannotSetPropertyError")}constructor(t){super(`Cannot set property ${t.join(".")} as parent is not an object.`),this.name="CannotSetPropertyError"}},Ty=class extends Ry.EventEmitter{static{o(this,"OptionsWatcher")}#e;#t;#r;#n;#s;#i;ready;constructor(t,r,n){super(),this.#s=t,this.#e=r,this.#i=n||LQ.default.loggerWithTag(t),this.ready=(0,Ry.once)(this,"ready"),this.#t=CQ.default.watch(r,{persistent:!1}).on("add",this.#a.bind(this)).on("change",this.#a.bind(this)).on("error",this.#d.bind(this)).on("unlink",this.#c.bind(this)).on("ready",this.#a.bind(this))}#a(){(0,PQ.readFile)(this.#e,"utf-8").then(t=>{this.#n=OQ.default.parse(t),this.#n&&this.#s in this.#n?this.#r?this.#f(this.#n[this.#s],this.#r):(this.#r=this.#n[this.#s],this.emit("ready",this.#r)):this.#r&&(this.#r=void 0,this.emit("remove"))}).catch(t=>{if(t instanceof Error&&"code"in t&&t.code==="ENOENT"){this.#n?(this.#o(),this.emit("remove")):(this.#o(),this.emit("ready"));return}this.emit("error",t)})}#d(t){this.emit("error",new PL(this.#e,t))}#c(t){this.#i.warn(`Configuration file ${t} was deleted. Reverting to default configuration. Recreate it to restore the options watcher.`),this.#o(),this.emit("remove")}#o(){this.#n=Sy,this.#r=this.#n[this.#s]}#f(t,r,n=[]){if(!this.#l(r)||!this.#l(t)){this.#u(n,t);return}for(let s of Object.keys(r))s in t||this.#u(n.concat(s),void 0);for(let[s,i]of Object.entries(t)){let a=n.concat(s),c=this.#m(a);if(typeof i!=typeof c||Array.isArray(i)&&!Array.isArray(c)||!Array.isArray(i)&&Array.isArray(c)){this.#u(a,i);continue}if(!Array.isArray(i)&&typeof i=="object"&&i!==null){this.#l(c)?this.#f(i,c,a):this.#u(a,i);continue}(0,DQ.isDeepStrictEqual)(i,c)||this.#u(a,i)}}#l(t){return typeof t=="object"&&t!==null&&t!==void 0&&!Array.isArray(t)}#m(t){let r=this.#r;for(let n of t){if(r==null||typeof r!="object"||!(n in r))return;r=r[n]}return structuredClone(r)}#u(t,r){if(!this.#r)throw new DL;if(!["object","string","array","number","boolean","undefined"].includes(typeof r))throw new LL(t,r);let n=this.#r;for(let s of t.slice(0,-1)){if(n==null||typeof n!="object"||!(s in n))throw new ML(t,s);n=n[s]}if(n==null||typeof n!="object")throw new vL(t);n[t[t.length-1]]=r,this.emit("change",t,r,this.#r)}close(){return this.#t.close(),this.emit("close"),this.removeAllListeners(),this}get(t){return this.#r?this.#m(t):void 0}getAll(){return structuredClone(this.#r)}getRoot(){return this.#n}}});function vQ(){QAe[0]=1}var JAe,QAe,UQ=ce(()=>{Sf();JAe=la.primaryStore.getUserSharedBuffer("restart-needed",new ArrayBuffer(1)),QAe=new Uint8Array(JAe);o(vQ,"requestRestart")});var by,xQ,yy,Ay,BQ=ce(()=>{by=require("node:events");wQ();MQ();xQ=w(j());UQ();yy=class extends Error{static{o(this,"MissingDefaultFilesOptionError")}constructor(){super("No default files option exists. Ensure `files` is specified in config.yaml"),this.name="MissingDefaultFilesOptionError"}},Ay=class extends by.EventEmitter{static{o(this,"Scope")}#e;#t;#r;#n;#s;#i;options;resources;server;ready;constructor(t,r,n,s,i){super(),this.#r=t,this.#t=r,this.#e=n,this.#i=xQ.default.forComponent(this.#r),this.resources=s,this.server=i,this.#s=[],this.ready=(0,by.once)(this,"ready"),this.options=new Ty(t,n,this.#i).on("error",this.#d.bind(this)).on("change",this.#f.bind(this)()).on("ready",this.#a.bind(this))}get logger(){return this.#i}get name(){return this.#r}get directory(){return this.#t}#a(){this.emit("ready")}#d(t){this.emit("error",t)}close(){for(let t of this.#s)t.close();return this.options.close(),this.emit("close"),this.removeAllListeners(),this}#c(t){let r=new Ey(this.#r,this.#t,t,this.#i).on("error",this.#d.bind(this)).on("add",this.#o("add")).on("change",this.#o("change")).on("unlink",this.#o("unlink")).on("addDir",this.#o("addDir")).on("unlinkDir",this.#o("unlinkDir"));return this.#s.push(r),r}#o(t){let r=this;return function(){this.listenerCount("all")>0||this.listenerCount(t)>1||r.requestRestart()}}#f(){let t=this;return o(function(...[n,s,i]){if(n[0]==="files"||n[0]==="urlPath"){if(!t.#n){t.#n=t.#c(i);return}t.#n.update(i);return}this.listenerCount("change")>1||(t.#i.debug(`Options changed: ${n.join(".")}, requesting restart`),t.requestRestart())},"handleOptionsWatcherChange")}#l(){let t=this.options.getAll();if(t&&typeof t=="object"&&t!==null&&!Array.isArray(t)&&"files"in t)return{files:t.files,urlPath:t.urlPath}}handleEntry(t,r){if(t===void 0){if(this.#n)return this.#n;let s=this.#l();if(s)return this.#n=this.#c(s),this.#n;this.emit("error",new yy);return}if(typeof t=="function"){if(this.#n)return this.#n.on("all",t);let s=this.#l();if(s)return this.#n=this.#c(s),this.#n.on("all",t);this.emit("error",new yy);return}let n=this.#c(t);return r?n.on("all",r):n}requestRestart(){this.#i.debug(`Restart requested from ${this.name} scope for ${this.directory}`),vQ()}}});function Nu(e){return typeof e=="string"&&e.trim()!==""}function UL(e){return Array.isArray(e)&&e.length!==0&&e.every(t=>Nu(t))}function qQ(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}async function XAe(e){e.config.root&&w_.default.warn("Resource extension 'root' option is deprecated. Due to backwards compatibility reasons it does not act as assumed. The glob pattern will always be evaluated from the component directory root. The option is only used for the initial root directory handling. Please remove and modify the 'files' glob pattern instead.");let t=[];if(e.config.root&&typeof e.config.files!="string")throw new GL(e);let r=e.config.root;r&&(r.startsWith("/")&&(r=r.slice(1)),r.endsWith("/")||(r+="/"));let n=e.config.files;if(typeof n=="string"&&!n.includes("**/*")&&(n.indexOf("/*")>-1?r=n.slice(0,n.indexOf("/*")+1):n.indexOf("/")>-1&&(r=n.slice(0,n.lastIndexOf("/")+1))),r&&t.push(r),t.length===0){if(qQ(e.config.files)&&e.config.files.only==="files")return!1;t=e.patternBases}let s=!1;for(let i of t){let a=(0,O_.join)(e.directory,i);Iy.isMainThread&&e.module.setupDirectory&&(s=await e.module.setupDirectory(e.baseURLPath,a,e.resources)),e.resources.isWorker&&e.module.handleDirectory&&(s=await e.module.handleDirectory(e.baseURLPath,a,e.resources))}return s}async function GQ(e){let t=!1;if(t=await XAe(e),t)return t;let r=await(0,FQ.default)(e.globOptions.source,{cwd:e.directory,objectMode:!0,onlyFiles:e.globOptions.onlyFiles,onlyDirectories:e.globOptions.onlyDirectories,ignore:e.globOptions.ignore});for(let n of r){let s=(0,O_.join)(e.directory,n.path);if(n.dirent.isDirectory()){let i=Iu(e,n.path,"directory");Iy.isMainThread&&e.module.setupDirectory&&(await e.module.setupDirectory(i,s,e.resources),t=!0),e.resources.isWorker&&e.module.handleDirectory&&(await e.module.handleDirectory(i,s,e.resources),t=!0)}else if(n.dirent.isFile()){let i=Iu(e,n.path,"file"),a=await(0,HQ.readFile)(s);Iy.isMainThread&&e.module.setupFile?(await e.module.setupFile(a,i,s,e.resources),t=!0):e.resources.isWorker&&e.module.handleFile&&(await e.module.handleFile(a,i,s,e.resources),t=!0)}else w_.default.error(`Entry received from glob pattern match for component ${e.name} is neither a file nor a directory:`,n)}return t}var Iy,FQ,w_,O_,HQ,kQ,Ny,ki,xL,BL,FL,HL,kL,qL,GL,$L,VL,$Q=ce(()=>{Iy=require("node:worker_threads"),FQ=w(require("fast-glob")),w_=w(j());bL();IL();O_=require("node:path"),HQ=require("node:fs/promises");wL();kQ=require("micromatch"),Ny=class{static{o(this,"ComponentV1")}config;name;directory;module;resources;globOptions;patternBases;baseURLPath;constructor(t){if(this.config=t.config,this.name=t.name,this.directory=t.directory,this.module=t.module,this.resources=t.resources,!Nu(this.config.files)&&!UL(this.config.files)&&!qQ(this.config.files))throw new xL(this);if(typeof this.config.files=="object"&&!Array.isArray(this.config.files)){if(this.config.files.source===void 0||!UL(this.config.files.source)&&!Nu(this.config.files.source))throw new BL(this);if(this.config.files.only!==void 0&&(typeof this.config.files.only!="string"||!["all","files","directories"].includes(this.config.files.only)))throw new FL(this);if(this.config.files.ignore!==void 0&&!UL(this.config.files.ignore)&&!Nu(this.config.files.ignore))throw new HL(this)}if(this.config.root!==void 0&&!Nu(this.config.root))throw new qL(this);if(this.config.path!==void 0&&!Nu(this.config.path))throw new $L(this);if(this.config.path&&(w_.default.warn("Resource extension 'path' option is deprecated. Please replace with 'urlPath'."),this.config.urlPath=this.config.path),this.config.urlPath!==void 0&&(!Nu(this.config.urlPath)||typeof this.config.urlPath=="string"&&this.config.urlPath.includes("..")))throw new VL(this);this.globOptions=_y(this.config.files),this.globOptions.source=this.globOptions.source.map(r=>{if(r.includes(".."))throw new kL(this,r);return r.startsWith("/")&&(w_.default.warn("Leading '/' in 'files' glob pattern is deprecated. For backwards compatibility purposes, it is currently transformed to the relative path of the component, but in the future will result in an error. Paths are automatically derived from the root of the component directory. Please remove (e.g. '/web/*' -> 'web/*')."),r=r==="/"?".":r.slice(1)),r}),this.patternBases=this.globOptions.source.map(r=>(0,kQ.scan)(r).base),this.baseURLPath=py(this.name,this.config.urlPath)}},ki=class extends Error{static{o(this,"ComponentV1ProcessingError")}constructor(t,r){super(`Component ${r.name} (from ${(0,O_.basename)(r.directory)}) ${t}`)}},xL=class extends ki{static{o(this,"InvalidFilesOptionError")}constructor(t){super("'files' option must be a non-empty string, an array of non-empty strings, or an object.",t)}},BL=class extends ki{static{o(this,"InvalidFilesSourceOptionError")}constructor(t){super("'files' object must have a non-empty 'source' property.",t)}},FL=class extends ki{static{o(this,"InvalidFilesOnlyOptionError")}constructor(t){super("'files.only' option must be one of 'all', 'files', or 'directories'.",t)}},HL=class extends ki{static{o(this,"InvalidFileIgnoreOptionError")}constructor(t){super("'files.ignore' option must be a non-empty string or an array of non-empty strings.",t)}},kL=class extends ki{static{o(this,"InvalidGlobPattern")}constructor(t,r){super(`'files' glob pattern must not contain '..'. Received: '${r}'`,t)}},qL=class extends ki{static{o(this,"InvalidRootOptionError")}constructor(t){super("deprecated 'root' option must be a non-empty string. Consider removing and updating 'files' glob pattern instead.",t)}},GL=class extends ki{static{o(this,"InvalidRootOptionUseError")}constructor(t){super("the 'root' option is deprecated and only supported if 'files' is a singular, non-empty string. Please remove the 'root' option and modify the 'files' glob pattern instead.",t)}},$L=class extends ki{static{o(this,"InvalidPathOptionError")}constructor(t){super("deprecated 'path' option must be a non-empty string. Consider replacing with 'urlPath'.",t)}},VL=class extends ki{static{o(this,"InvalidURLPathOptionError")}constructor(t){super("'urlPath' option must be a non-empty string that must not contain '..'.",t)}};o(Nu,"isNonEmptyString");o(UL,"isArrayOfNonEmptyStrings");o(qQ,"isObject");o(XAe,"handleRoots");o(GQ,"processResourceExtensionComponent")});var xp={};we(xp,{componentErrors:()=>C_,getComponentName:()=>ty,loadComponent:()=>Py,loadComponentDirectories:()=>YQ,setErrorReporter:()=>ebe});function YQ(e,t){t&&(YL=t),e&&(JL=e);let r=[];if((0,vt.existsSync)(KL)){let s=(0,vt.readdirSync)(KL,{withFileTypes:!0});for(let i of s){if(!i.isDirectory()&&!i.isSymbolicLink())continue;let a=i.name,c=(0,qr.join)(KL,a);r.push(Py(c,YL,$A,!1))}}let n=process.env.RUN_HDB_APP;return n&&r.push(Py(n,YL,n,!1,void 0,!!process.env.DEV_MODE)),Promise.all(r).then(()=>{KQ=!0})}function ebe(e){Oy=e}function tbe(e,t){return new Promise((r,n)=>{let s=setTimeout(()=>{la.primaryStore.unlock(e,0),n(new Error("symlinking harperdb module timed out"))},1e4);if(la.primaryStore.attemptLock(e,0,()=>{clearTimeout(s),r()}))try{(0,vt.rmSync)(t,{recursive:!0,force:!0}),(0,vt.existsSync)((0,qr.join)(e,"node_modules"))||(0,vt.mkdirSync)((0,qr.join)(e,"node_modules")),(0,vt.symlinkSync)(XL.PACKAGE_ROOT,t,"dir"),r()}finally{la.primaryStore.unlock(e,0)}})}function WQ(e,t){return e.ready.then(()=>{let r=e.options.get(["timeout"])||t.defaultTimeout||3e4;if(typeof r!="number")throw new Error(`Invalid timeout value for ${e.name}. Expected a number, received: ${typeof r}`);let n,s;if(!la.primaryStore.attemptLock(e.name,0,()=>{clearTimeout(s),n(WQ(e,t))}))return new Promise((a,c)=>{n=a,s=setTimeout(()=>{c(new Error(`Timeout waiting for lock on ${e.name}`))},r+5e3)});let i;return Promise.race([t.handleApplication(e),new Promise((a,c)=>i=setTimeout(()=>c(new Error(`handleApplication timed out after ${r}ms for ${e.name}`)),r))]).finally(()=>{la.primaryStore.unlock(e.name,0),clearTimeout(i)})})}async function Py(e,t,r,n,s,i){let a=(0,vt.realpathSync)(e);if(wy.has(a))return wy.get(a);wy.set(a,!0),s&&(JL=s);try{let c;n&&(C_=new Map);let l=(0,qr.join)(e,"harperdb-config.yaml");(0,vt.existsSync)(l)?c=n?(0,Dy.getConfigObj)():(0,zL.parseDocument)((0,vt.readFileSync)(l,"utf8")).toJSON():!n&&(0,vt.existsSync)(l=(0,qr.join)(e,"config.yaml"))?c=(0,zL.parseDocument)((0,vt.readFileSync)(l,"utf8")).toJSON():c=Sy;try{let m=(0,qr.join)(e,"node_modules","harperdb");(n||((0,vt.existsSync)(m)||!e.startsWith((0,jL.getHdbBasePath)()))&&(!(0,vt.existsSync)(m)||(0,vt.realpathSync)(XL.PACKAGE_ROOT)!==(0,vt.realpathSync)(m)))&&await tbe(e,m)}catch(m){ba.default.error("Error symlinking harperdb module",m),m.code=="EPERM"&&process.platform==="win32"&&ba.default.error('You may need to enable developer mode in "Settings" / "System" (or "Update & Security") / "For developers", in order to enable symlinks so components can use `import from "harperdb"`')}let u=Cy,d={};for(let m in c){Cy=m;let h=c[m];if(C_.set(n?m:(0,qr.basename)(e),!1),!h)continue;let p,E=h.package;try{if(E){let N=e,O;for(;!(0,vt.existsSync)(O=(0,qr.join)(N,"node_modules",m));)if(N=(0,qr.dirname)(N),N.length<(0,jL.getHdbBasePath)().length){O=null;break}if(O)p=await Py(O,t,r,!1),d[m]=!0;else throw new Error(`Unable to find package ${m}:${E}`)}else p=ZAe[m];if(!p)continue;let g=o(N=>(N.origin=r,ze(N)),"ensureTable"),R=h.network||(h.port||h.securePort)&&h,T=R?.securePort||R?.https&&R.port,y=!R?.https&&R?.port;if("handleApplication"in p&&("start"in p||"startOnMainThread"in p||"handleFile"in p||"handleDirectory"in p||"setupFile"in p||"setupDirectory"in p))throw new Error(`Component ${m} has both 'handleComponent' and 'start' or 'startOnMainThread' methods. Please use only one of them.`);if(t.isWorker&&p.handleApplication){p.suppressHandleApplicationWarning!==!0&&ba.default.warn(`Plugin ${m} is using the experimental handleApplication API`);let N=new Ay(m,e,l,t,Le);await WQ(N,p);continue}if(WL.isMainThread&&(p=await p.startOnMainThread?.({server:Le,ensureTable:g,port:y,securePort:T,resources:t,...h})||p,n&&R))for(let N of[y,T])try{if(+N&&!VQ.includes(N)){let O=QL.get(U.HTTP_SESSIONAFFINITY);O&&ba.default.warn("Session affinity is not recommended and may cause memory leaks"),(O||!Wg)&&(VQ.push(N),lL(N,O))}}catch(O){console.error("Error listening on socket",N,O,m)}if(t.isWorker&&(p=await p.start?.({server:Le,ensureTable:g,port:y,securePort:T,resources:t,...h})||p),JL.set(p,!0),(p.handleFile||p.handleDirectory||p.setupFile||p.setupDirectory)&&h.files!=null){let N=new Ny({config:h,name:m,directory:e,module:p,resources:t});d[m]=await GQ(N)}}catch(g){g.message=`Could not load component '${m}' for application '${(0,qr.basename)(e)}' due to: ${g.message}`,Oy?.(g),((0,P_.getWorkerIndex)()===0?console:ba.default).error(g),t.set(h.path||"/",new fl(g),null,!0),C_.set(n?m:(0,qr.basename)(e),g.message)}}if(Cy=u,WL.isMainThread&&!KQ&&i&&(0,P_.watchDir)(e,async()=>YQ()),c.extensionModule||c.pluginModule){let m=await kg((0,qr.join)(e,c.extensionModule||c.pluginModule));return wy.set(a,m),m}let f=Object.values(d);if(f.length>0&&f.every(m=>!m)&&t.isWorker){let m=`${e} did not load any modules, resources, or files, is this a valid component?`;Oy?.(new Error(m)),((0,P_.getWorkerIndex)()===0?console:ba.default).error(m),C_.set((0,qr.basename)(e),m)}for(let[m,h]of Object.entries(d))h||ba.default.warn(`Component ${m} from (${(0,qr.basename)(e)}) did not load any functionality.`)}catch(c){console.error(`Could not load application directory ${e}`,c),c.message=`Could not load application due to ${c.message}`,Oy?.(c),t.set("",new fl(c))}}var vt,qr,WL,zL,QL,XL,ba,P_,jL,Dy,KL,JL,KQ,YL,C_,ZAe,VQ,wy,Oy,Cy,ty,gf=ce(()=>{vt=require("node:fs"),qr=require("node:path"),WL=require("node:worker_threads"),zL=require("yaml"),QL=w(oe()),XL=w(ht());H();EU();n0();wk();vk();Uk();yq();Sj();Ij();wj();ba=w(j());xj();P_=w(rt());$N();vr();Pe();GD();jL=w(oe());WJ();FT();tQ();kn();pQ();Dy=w(gt());Uh();Ob();BQ();$Q();rL();Sf();CL();KL=(0,Dy.resolvePath)(QL.get(U.COMPONENTSROOT)),JL=new Map,C_=new Map;o(YQ,"loadComponentDirectories");ZAe={REST:Jg,rest:Jg,graphql:Pb,graphqlSchema:db,roles:GN,jsResource:VN,fastifyRoutes:iD,login:YN,static:oD,operationsApi:dL,customFunctions:{},http:ey,clustering:EL,replication:uo,authentication:Cp,mqtt:yL,loadEnv:aD,logging:ba.default,dataLoader:uD},VQ=[],wy=new Map;o(ebe,"setErrorReporter");ty=o(()=>Cy,"getComponentName");o(tbe,"symlinkHarperModule");o(WQ,"sequentiallyHandleApplication");o(Py,"loadComponent")});var ny=M((eGe,jQ)=>{var{isMainThread:zQ}=require("worker_threads"),{getTables:rbe,getDatabases:Xqe,table:Zqe}=(Pe(),v(ut)),{loadComponentDirectories:nbe,loadComponent:sbe}=(gf(),v(xp)),{resetResources:ibe}=(td(),v(WU)),obe=kC(),abe=gt(),{dirname:cbe}=require("path"),{getConnection:lbe}=sr(),ube=oe(),{CONFIG_PARAMS:dbe}=(H(),v(W)),{loadCertificates:fbe}=pn(),ZL=new Map;async function mbe(e=!1){!zQ&&ube.get(dbe.CLUSTERING_ENABLED)&&lbe();try{zQ&&await obe()}catch(n){console.error(n)}let t=ibe();rbe(),t.isWorker=e,await fbe(),await sbe(cbe(abe.getConfigFilePath()),t,"hdb",!0,ZL),await nbe(ZL,t);let r=[];for(let[n]of ZL)n.ready&&r.push(n.ready());r.length>0&&await Promise.all(r)}o(mbe,"loadRootComponents");jQ.exports.loadRootComponents=mbe});var rt=M((rGe,Gi)=>{"use strict";pE();var{Worker:hbe,MessageChannel:pbe,parentPort:yo,isMainThread:sM,threadId:_be,workerData:Ao}=require("worker_threads"),{PACKAGE_ROOT:Ebe}=ht(),{join:ZQ,isAbsolute:gbe,extname:Sbe}=require("path"),{server:e4}=(vr(),v(Um)),{watch:Tbe,readdir:Rbe}=require("fs/promises"),{totalmem:JQ}=require("os"),{setHeapSnapshotNearHeapLimit:ybe}=require("v8"),kc=(H(),v(W)),vy=oe(),qi=j(),{randomBytes:Abe}=require("crypto"),{_assignPackageExport:bbe}=mi(),QQ=1024*1024,qc=[],ri=[],Ibe=50,iM=1e4,Nbe="restart",t4="request_thread_info",r4="resource_report",n4="thread_info",s4="added-port",wbe="ack",eM;bbe("threads",ri);Gi.exports={startWorker:tM,restartWorkers:aM,shutdownWorkers:Lbe,workers:qc,setMonitorListener:kbe,onMessageFromWorkers:Mbe,onMessageByType:d4,broadcast:Ube,broadcastWithAcknowledgement:Bbe,setChildListenerByType:Dbe,getWorkerIndex:i4,getWorkerCount:o4,getTicketKeys:c4,setMainIsWorker:Cbe,setTerminateTimeout:Obe,restartNumber:Ao?.restartNumber||1};ri.onMessageByType=d4;ri.sendToThread=function(e,t){if(!t?.type)throw new Error("A message with a type must be provided");let r=ri.find(n=>n.threadId===e);if(r)return r.postMessage(t),!0};Gi.exports.whenThreadsStarted=new Promise(e=>{Gi.exports.threadsHaveStarted=e});vy.get(kc.CONFIG_PARAMS.THREADS_HEAPSNAPSHOTNEARLIMIT)&&ybe(1);var oM;function Obe(e){iM=e}o(Obe,"setTerminateTimeout");function i4(){return Ao?Ao.workerIndex:oM?0:void 0}o(i4,"getWorkerIndex");function o4(){return Ao?Ao.workerCount:oM?1:void 0}o(o4,"getWorkerCount");function Cbe(e){oM=e,Gi.exports.threadsHaveStarted()}o(Cbe,"setMainIsWorker");var a4=1,Ly;function c4(){return Ly||(Ly=sM?Abe(48):Ao.ticketKeys,Ly)}o(c4,"getTicketKeys");Object.defineProperty(e4,"workerIndex",{get(){return i4()}});Object.defineProperty(e4,"workerCount",{get(){return o4()}});var l4={[t4](e,t){Fbe(t)},[r4](e,t){Hbe(t,e)}};function tM(e,t={}){let r=process.constrainedMemory?.()||JQ();r=Math.min(r,JQ(),2e4*QQ);let n=vy.get(kc.CONFIG_PARAMS.THREADS_MAXHEAPMEMORY)??Math.max(Math.floor(r/QQ/(10+(t.threadCount||1)/4)),512),s=Math.min(Math.max(n>>6,16),64),i=[],a=[];for(let u of ri){let d=new pbe;d.existingPort=u,i.push(d),a.push(d.port2)}Sbe(e)||(e+=".js");let c=["--enable-source-maps","--expose-internals"];vy.get(kc.CONFIG_PARAMS.THREADS_HEAPSNAPSHOTNEARLIMIT)&&c.push("--heapsnapshot-near-heap-limit=1");let l=new hbe(gbe(e)?e:ZQ(Ebe,e),{resourceLimits:{maxOldGenerationSizeMb:n,maxYoungGenerationSizeMb:s},execArgv:c,argv:process.argv.slice(2),workerData:{addPorts:a,addThreadIds:i.map(u=>u.existingPort.threadId),workerIndex:t.workerIndex,workerCount:a4=t.threadCount,name:t.name,restartNumber:Gi.exports.restartNumber,ticketKeys:c4()},transferList:a,...t});for(let{port1:u,existingPort:d}of i)d.postMessage({type:s4,port:u,threadId:l.threadId},[u]);return Uy(l,!0),l.unexpectedRestarts=t.unexpectedRestarts||0,l.startCopy=()=>tM(e,t),l.on("error",u=>{qi.error(`Worker index ${t.workerIndex} error:`,u)}),l.on("exit",u=>{qc.splice(qc.indexOf(l),1),!l.wasShutdown&&t.autoRestart!==!1&&(l.unexpectedRestarts<Ibe?(t.unexpectedRestarts=l.unexpectedRestarts+1,tM(e,t)):qi.error(`Thread has been restarted ${l.restarts} times and will not be restarted`))}),l.on("message",u=>{l4[u.type]?.(u,l)}),qc.push(l),Gbe(),t.onStarted&&t.onStarted(l),l.name=t.name,l}o(tM,"startWorker");var Pbe=[kc.THREAD_TYPES.HTTP];async function aM(e=null,t=Math.max(a4>3,1),r=!0){if(sM){try{process.chdir(process.cwd())}catch(a){qi.error("Unable to reestablish current working directory",a)}if(r){let{loadRootComponents:a}=ny();await a()}Gi.exports.restartNumber++,t<1&&(t=t*qc.length);let n=[],s=[];for(let a of qc.slice(0)){if(e&&a.name!==e||a.wasShutdown)continue;qi.trace("sending shutdown request to ",a.threadId),a.postMessage({restartNumber:Gi.exports.restartNumber,type:kc.ITC_EVENT_TYPES.SHUTDOWN}),a.wasShutdown=!0,a.emit("shutdown",{});let c=Pbe.indexOf(a.name)>-1,l=new Promise(u=>{let d=setTimeout(()=>{qi.warn("Thread did not voluntarily terminate, terminating from the outside",a.threadId),a.terminate()},iM*2).unref();a.on("exit",()=>{clearTimeout(d),n.splice(n.indexOf(l)),!c&&r&&a.startCopy(),u()})});if(n.push(l),c&&r){let u=a.startCopy(),d=new Promise(f=>{let m=o(h=>{h.type===kc.ITC_EVENT_TYPES.CHILD_STARTED&&(qi.trace("Worker has started",u.threadId),f(),s.splice(s.indexOf(d)),u.off("message",m))},"startListener");qi.trace("Waiting for worker to start",u.threadId),u.on("message",m)});s.push(d),n.length>=t&&await Promise.race(n),s.length>=t&&await Promise.race(s)}}await Promise.all(n),await Promise.all(s);let{restartService:i}=yc();r&&(e==="http"||!e)&&vy.get(kc.CONFIG_PARAMS.CLUSTERING_ENABLED)&&await i({service:"clustering"})}else yo.postMessage({type:Nbe,workerType:e})}o(aM,"restartWorkers");function Dbe(e,t){l4[e]=t}o(Dbe,"setChildListenerByType");function Lbe(e){return aM(e,1/0,!1)}o(Lbe,"shutdownWorkers");var u4=[];function Mbe(e){u4.push(e)}o(Mbe,"onMessageFromWorkers");var rM=new Map;function d4(e,t){let r=rM.get(e);r||rM.set(e,r=[]),r.push(t)}o(d4,"onMessageByType");var vbe=10;async function Ube(e,t){let r=0;for(let n of ri)try{n.postMessage(e),r++>vbe&&(r=0,await new Promise(setImmediate))}catch(s){qi.error("Unable to send message to worker",s)}t&&m4(e,null)}o(Ube,"broadcast");var My=new Map,xbe=1;function Bbe(e){return new Promise(t=>{let r=0;for(let n of ri)try{let s=xbe++,i=o(()=>{My.delete(s),--r===0&&t(),n!==yo&&--n.refCount===0&&n.unref()},"ackHandler");i.port=n,n.ref(),n.refCount=(n.refCount||0)+1,My.set(e.requestId=s,i),n.hasAckCloseListener||(n.hasAckCloseListener=!0,n.on(n.close?"close":"exit",()=>{for(let[,a]of My)a.port===n&&a()})),n.postMessage(e),r++}catch(s){qi.error("Unable to send message to worker",s)}r===0&&t()})}o(Bbe,"broadcastWithAcknowledgement");function Fbe(e){e.postMessage({type:n4,workers:f4()})}o(Fbe,"sendThreadInfo");function f4(){let e=Date.now();return qc.map(t=>({threadId:t.threadId,name:t.name,heapTotal:t.resources?.heapTotal,heapUsed:t.resources?.heapUsed,externalMemory:t.resources?.external,arrayBuffers:t.resources?.arrayBuffers,sinceLastUpdate:e-t.resources?.updated,...t.recentELU}))}o(f4,"getChildWorkerInfo");function Hbe(e,t){e.resources=t,e.resources.updated=Date.now()}o(Hbe,"recordResourceReport");var nM;function kbe(e){nM=e}o(kbe,"setMonitorListener");var qbe=1e3,XQ=!1;function Gbe(){XQ||(XQ=!0,setInterval(()=>{for(let e of qc){let t=e.performance.eventLoopUtilization(),r;e.lastTotalELU?r=e.performance.eventLoopUtilization(t,e.lastTotalELU):r=t,e.lastTotalELU=t,e.recentELU=r}nM&&nM()},qbe).unref())}o(Gbe,"startMonitoring");var $be=1e3;if(yo&&Ao?.addPorts){Uy(yo);for(let e=0,t=Ao.addPorts.length;e<t;e++){let r=Ao.addPorts[e];r.threadId=Ao.addThreadIds[e],Uy(r)}setInterval(()=>{let e=process.memoryUsage();yo.postMessage({type:r4,heapTotal:e.heapTotal,heapUsed:e.heapUsed,external:e.external,arrayBuffers:e.arrayBuffers})},$be).unref(),eM=o(()=>new Promise((e,t)=>{yo.on("message",r),yo.postMessage({type:t4});function r(n){n.type===n4&&(yo.off("message",r),e(n.workers))}o(r,"receiveThreadInfo")}),"getThreadInfo")}else eM=f4;Gi.exports.getThreadInfo=eM;function Uy(e,t){ri.push(e),e.on("message",r=>{if(r.type===s4)r.port.threadId=r.threadId,Uy(r.port);else if(r.type===wbe){let n=My.get(r.id);n&&n()}else m4(r,e)}).on("close",()=>{ri.splice(ri.indexOf(e),1)}).on("exit",()=>{ri.splice(ri.indexOf(e),1)}),t?e.refCount=100:e.unref()}o(Uy,"addPort");function m4(e,t){for(let n of u4)n(e,t);let r=rM.get(e.type);if(r)for(let n of r)try{n(e,t)}catch(s){qi.error(s)}}o(m4,"notifyMessageListeners");if(sM){let e,t,r=new Set,n=o(async(s,i)=>{i&&(e=i);for(let a of await Rbe(s,{withFileTypes:!0}))a.isDirectory()&&a.name!=="node_modules"&&n(ZQ(s,a.name));try{for await(let{filename:a}of Tbe(s,{persistent:!1}))r.add(a),t&&clearTimeout(t),t=setTimeout(async()=>{e&&await e(),await aM(),console.log("Reloaded HarperDB components, changed files:",Array.from(r)),r.clear()},100)}catch(a){console.warn("Error trying to watch component directory",s,a)}},"watchDir");Gi.exports.watchDir=n,process.env.WATCH_DIR&&n(process.env.WATCH_DIR)}else yo.on("message",async e=>{let{type:t}=e;t===kc.ITC_EVENT_TYPES.SHUTDOWN&&(Gi.exports.restartNumber=e.restartNumber,yo.unref(),setTimeout(()=>{qi.warn("Thread did not voluntarily terminate",_be),process.exit(0)},iM).unref())})});var g4={};we(g4,{onStorageReclamation:()=>D_,runReclamationHandlers:()=>dM,setAvailableSpaceRatioGetter:()=>Kbe});function D_(e,t,r){(r||(0,By.getWorkerIndex)()===(0,By.getWorkerCount)()-1)&&(xy.has(e)||xy.set(e,[]),xy.get(e).push({priority:0,handler:t}),uM||(uM=setTimeout(dM,p4).unref()))}async function dM(){for(let[e,t]of xy)try{let r=await E4(e),n=Vbe/r;for(let s of t){let{priority:i,handler:a}=s;if(s.priority=n,n>1||i>1){let c=a(n>1?n:0);c&&(lM.default.info?.(`Running storage reclamation handler for ${e} with priority ${n}`),await c)}}}catch(r){lM.default.error?.("Error running storage reclamation handlers",r)}uM=setTimeout(dM,p4).unref()}function Kbe(e){E4=e??_4}var cM,By,lM,Fy,h4,xy,Vbe,p4,uM,_4,E4,Hy=ce(()=>{cM=require("node:fs/promises"),By=w(rt()),lM=w(hi());H();Fy=w(oe()),h4=w(se());Fy.default.initSync();xy=new Map,Vbe=Fy.default.get(U.STORAGE_RECLAMATION_THRESHOLD)??.4,p4=(0,h4.convertToMS)(Fy.default.get(U.STORAGE_RECLAMATION_INTERVAL))||36e5;o(D_,"onStorageReclamation");_4=o(async e=>{if(cM.statfs){let t=await(0,cM.statfs)(e);return t.bavail/t.blocks}else return new Promise((t,r)=>{import("hdd-space").then(n=>{n.default(s=>{for(let i of s.parts)if(e.startsWith(i.place))return t(i.free/i.size);return t(1)})})})},"defaultGetAvailableSpaceRatio"),E4=_4;o(dM,"runReclamationHandlers");o(Kbe,"setAvailableSpaceRatioGetter")});var VH={};we(VH,{ACTION_32_BIT:()=>Vy,ACTION_64_BIT:()=>jbe,AUDIT_STORE_OPTIONS:()=>bp,Decoder:()=>zl,HAS_BLOBS:()=>Yr,HAS_CURRENT_RESIDENCY_ID:()=>Yl,HAS_EXPIRATION_EXTENDED_TYPE:()=>x_,HAS_ORIGINATING_OPERATION:()=>U_,HAS_PREVIOUS_RESIDENCY_ID:()=>Wl,REMOTE_SEQUENCE_UPDATE:()=>US,createAuditEntry:()=>Vl,getLastRemoved:()=>Wbe,openAuditStore:()=>Gy,readAuditEntry:()=>wt,removeAuditEntry:()=>$y,setAuditRetention:()=>zbe,transactionKeyEncoder:()=>w4});function Gy(e){let t=e.auditStore=e.openDB(fM.AUDIT_STORE_NAME,{create:!1,...bp});t||(t=e.auditStore=e.openDB(fM.AUDIT_STORE_NAME,bp),T4(t,1)),t.rootStore=e,t.tableStores=[];let r=[];t.addDeleteRemovalCallback=function(l,u,d){return r[l]=d,t.tableStores[l]=u,t.deleteCallbacks=r,{remove(){delete r[l]}}};let n=null,s,i=0,a=hM;D_(t.env.path,l=>{if(i=l,l)return c(100)});function c(l){l&&(a=l),clearTimeout(n);let u=new Promise(d=>{n=setTimeout(async()=>{if(await s,s=u,t.rootStore.status==="closed"||t.rootStore.status==="closing")return;let f=0,m,h;try{for(let{key:p,value:E}of t.getRange({start:1,snapshot:!1,end:Date.now()-mM/(1+i*i)})){try{m=$y(t,p,E)}catch(g){Kf.warn("Error removing audit entry",g)}if(h=p,await new Promise(setImmediate),++f>=Ybe){a=10;break}}await m}finally{f===0?a=Math.min(a<<1,mM/10):(T4(t,h),a>100&&(a=a>>1)),d(void 0),c()}},a).unref()});return u}if(o(c,"scheduleAuditCleanup"),t.scheduleAuditCleanup=c,(0,M_.getWorkerIndex)()===(0,M_.getWorkerCount)()-1&&c(),(0,M_.getWorkerIndex)()===0&&!S4)for(let l of t.getKeys({reverse:!0,limit:1}))l>Date.now()&&(S4=!0,Kf.error("The current time is before the last recorded entry in the audit log. Time reversal can undermine the integrity of data tracking and certificate validation and the time must be corrected."));return t}function $y(e,t,r){let n=Jbe(r),s;if(n&Yr){s=wt(r);let i=e.tableStores[s.tableId];if(i){let a=s.type==="message"?null:i?.getEntry(s.recordId);(!a||a.version!==s.version||!a.value)&&vo(()=>Va(s.getValue(i)),i.rootStore)}}if((n&15)===pM){s=s||wt(r);let i=s.tableId;e.tableStores[s.tableId]?.getEntry(s.recordId)?.version===s.version&&e.deleteCallbacks?.[i]?.(s.recordId,s.version)}return e.remove(t)}function T4(e,t){_M[0]=t,e.put(Symbol.for("last-removed"),O4)}function Wbe(e){let t=e.get(Symbol.for("last-removed"));if(t)return O4.set(t),_M[0]}function zbe(e,t=hM){mM=e,hM=t}function Vl(e,t,r,n,s,i,a,c,l,u,d,f,m){let h=C4[a];if(!h)throw new Error(`Invalid audit entry type ${a}`);let p=1;if(n&&(n>1?Gc.setFloat64(0,n):ni.set(EM),p=9),l){if(l&255)throw new Error("Illegal extended type");p+=3}R(s),R(t),g(r),Gc.setFloat64(p,e),p+=8,l&Yl&&R(u),l&Wl&&R(d),l&x_&&(Gc.setFloat64(p,f),p+=8),l&U_&&R(P4[m]),i?g(i):ni[p++]=0,l?Gc.setUint32(n?8:0,h|l|3221225472):ni[n?8:0]=h;let E=ni.subarray(0,p);if(c)return Buffer.concat([E,c]);return E;function g(T){let y=p;p+=1,p=(0,wu.writeKey)(T,ni,p);let N=p-y-1;N>127?N>16383?(Kf.error("Key or username was too large for audit entry",T),p=y+1,ni[y]=0):(ni.copyWithin(y+2,y+1,p),Gc.setUint16(y,N|32768),p++):ni[y]=N}function R(T){T<128?ni[p++]=T:T<16384?(Gc.setUint16(p,T|32768),p+=2):T<1056964608?(Gc.setUint32(p,T|3221225472),p+=4):(ni[p]=255,Gc.setUint32(p+1,T),p+=5)}}function Jbe(e){let t=0;e[0]==66&&(t=8);let r=e[t];if(r<128)return r;let n=e.dataView||(e.dataView=new zl(e.buffer,e.byteOffset,e.byteLength));return n.position=t,n.readInt()}function wt(e,t=0,r=void 0){try{let n=e.dataView||(e.dataView=new zl(e.buffer,e.byteOffset,e.byteLength));n.position=t;let s;e[n.position]==66&&(s=n.readFloat64());let i=n.readInt(),a=n.readInt(),c=n.readInt(),l=n.readInt(),u=n.position,d=n.position+=l,f=n.readFloat64(),m,h,p,E;if(i&Yl&&(m=n.readInt()),i&Wl&&(h=n.readInt()),i&x_&&(p=n.readFloat64()),i&U_){let y=n.readInt();E=P4[y]}l=n.readInt();let g=n.position,R=n.position+=l,T;return{type:C4[i&7],tableId:c,nodeId:a,get recordId(){return(0,wu.readKey)(e,u,d)},getBinaryRecordId(){return e.subarray(u,d)},version:f,previousLocalTime:s,get user(){return R>g?(0,wu.readKey)(e,g,R):void 0},get encoded(){return t?e.subarray(t,r):e},getValue(y,N,O){if(i&ky||i&L_&&!N)return T||(T=vo(()=>y.decoder.decode(e.subarray(n.position,r)),y.rootStore)),T;if(i&L_&&O)return wN(y.getEntry(this.recordId),O,y)},getBinaryValue(){return i&(ky|L_)?e.subarray(n.position,r):void 0},extendedType:i,residencyId:m,previousResidencyId:h,expiresAt:p,originatingOperation:E}}catch(n){return Kf.error("Reading audit entry error",n,e),{}}}var wu,qy,fM,M_,N4,Kf,ni,Gc,w4,bp,mM,Ybe,_M,O4,hM,S4,ky,L_,R4,pM,y4,A4,b4,I4,Vy,jbe,US,Yl,Wl,U_,x_,Yr,C4,P4,zl,Yi=ce(()=>{wu=require("ordered-binary"),qy=w(oe()),fM=w(Kt());H();M_=w(rt()),N4=w(se());ml();Kf=w(j());Cg();ts();Hy();(0,qy.initSync)();ni=Buffer.alloc(2816),Gc=new DataView(ni.buffer,ni.byteOffset,2816),w4={writeKey(e,t,r){return e===v_?(t.set(v_,r),r+8):typeof e=="number"?((t.dataView||(t.dataView=new DataView(t.buffer,t.byteOffset,t.byteLength))).setFloat64(r,e),r+8):(0,wu.writeKey)(e,t,r)},readKey(e,t,r){return e[t]===66?(e.dataView||(e.dataView=new DataView(e.buffer,e.byteOffset,e.byteLength))).getFloat64(t):(0,wu.readKey)(e,t,r)}},bp={encoding:"binary",keyEncoder:w4},mM=(0,N4.convertToMS)((0,qy.get)(U.LOGGING_AUDITRETENTION))||86400*3,Ybe=1e3,_M=new Float64Array(1),O4=new Uint8Array(_M.buffer),hM=1e4,S4=!1;o(Gy,"openAuditStore");o($y,"removeAuditEntry");o(T4,"updateLastRemoved");o(Wbe,"getLastRemoved");o(zbe,"setAuditRetention");ky=16,L_=32,R4=1,pM=2,y4=3,A4=4,b4=5,I4=6,Vy=14,jbe=15,US=11,Yl=512,Wl=1024,U_=2048,x_=4096,Yr=8192,C4={put:R4|ky,[R4]:"put",delete:pM,[pM]:"delete",message:y4|ky,[y4]:"message",invalidate:A4|L_,[A4]:"invalidate",patch:b4|L_,[b4]:"patch",relocate:I4,[I4]:"relocate"},P4={insert:1,update:2,upsert:3,1:"insert",2:"update",3:"upsert"};o(Vl,"createAuditEntry");o(Jbe,"readAction");o(wt,"readAuditEntry");zl=class extends DataView{static{o(this,"Decoder")}position=0;readInt(){let t;return t=this.getUint8(this.position++),t>=128?t>=192?t===255?(t=this.getUint32(this.position),this.position+=4,t):(t=this.getUint32(this.position-1)&1073741823,this.position+=3,t):(t=this.getUint16(this.position-1)&32767,this.position++,t):t}readFloat64(){try{let t=this.getFloat64(this.position);return this.position+=8,t}catch(t){throw t.message=`Error reading float64: ${t.message} at position ${this.position}`,t}}}});var _0={};we(_0,{ENTRY:()=>Xbe,HAS_EXPIRATION:()=>zy,HAS_RESIDENCY_ID:()=>yM,HAS_STRUCTURE_UPDATE:()=>HS,LAST_TIMESTAMP_PLACEHOLDER:()=>v_,LOCAL_TIMESTAMP:()=>Qbe,METADATA:()=>$d,NEW_TIMESTAMP_PLACEHOLDER:()=>L4,NO_TIMESTAMP:()=>Yy,PENDING_LOCAL_TIME:()=>AM,PREVIOUS_TIMESTAMP_PLACEHOLDER:()=>EM,RecordEncoder:()=>RM,TIMESTAMP_ASSIGN_LAST:()=>eIe,TIMESTAMP_ASSIGN_NEW:()=>M4,TIMESTAMP_ASSIGN_PREVIOUS:()=>v4,TIMESTAMP_PLACEHOLDER:()=>Ky,TIMESTAMP_RECORD_PREVIOUS:()=>gM,entryMap:()=>$c,handleLocalTimeForGets:()=>jy,lastMetadata:()=>dt,recordUpdater:()=>bM,removeEntry:()=>Pu});function rIe(){return H_[0]=H_[0]^64,Zbe.getFloat64(0)}function jy(e,t){let r=e.getEntry;e.readCount=0,e.cachePuts=!1,e.rootStore=t,e.encoder.rootStore=t,e.getEntry=function(a,c){e.readCount++,dt=null;let l=r.call(this,a,c);return l&&(dt&&(l.metadataFlags=dt[$d],l.localTime=dt.localTime,l.residencyId=dt.residencyId,dt.expiresAt>=0&&(l.expiresAt=dt.expiresAt),dt=null),l.value&&$c.set(l.value,l),l.key=a),l};let n=e.get;e.get=function(a,c){dt=null;let l=n.call(this,a,c);return dt&&l&&($c.set(l,dt),dt=null),l};let s=e.getRange;e.getRange=function(a){let c=s.call(this,a);return a.valuesForKey?c.map(l=>l?.value):a.values===!1||a.onlyCount?c:c.map(l=>(dt&&(l.metadataFlags=dt[$d],l.localTime=dt.localTime,l.residencyId=dt.residencyId,dt.expiresAt>=0&&(l.expiresAt=dt.expiresAt),dt=null),l))};let i=e.useReadTransaction();if(i.done(),!i.done.isTracked){let a=i.constructor,c=i.use,l=i.done;a.prototype.use=function(){this.timerTracked||(this.timerTracked=!0,Cu.push(new WeakRef(this))),c.call(this)},a.prototype.done=function(){if(l.call(this),this.isDone)for(let u=0;u<Cu.length;u++){let d=Cu[u].deref();(!d||d.isDone||d.isCommitted)&&Cu.splice(u--,1)}},a.prototype.done.isTracked=!0}return e}function bM(e,t,r){return function(n,s,i,a,c=-1,l,u,d="put",f,m){l==null?Ou=Yy:f?Ou=i?.localTime?gM|v4:Yy:Ou=l?i?.localTime?gM|16384:M4|16384:Yy;let h=u?.expiresAt;if(h>=0&&(c|=zy),F_=c,SM=h,i?.version===a&&l===!1)throw new Error("Must retain local time if version is not changed");let p={version:a,instructedWrite:Ou>0},E,g=0;try{let R=i?.residencyId,T=u?.residencyId;T&&(TM=T,F_|=yM,g|=Yl),R!==T&&(g|=Wl,R||(R=0)),c&zy&&(g|=x_),u?.originatingOperation&&(g|=U_),f&&(p.ifVersion=E=i?.version??null),i&&i.value&&d!=="message"&&i.metadataFlags&Yr&&(!i.localTime||!r.getBinaryFast(i.localTime))&&Va(i.value);let y;if(s!==void 0&&(y=BE(()=>e.put(n,s,p),n,e.rootStore),ll&&(g|=Yr)),l){let N=u?.user?.username;if(m&&(BE(()=>e.encoder.encode(m),n,e.rootStore),ll&&(g|=Yr)),e.encoder.hasStructureUpdate&&(g|=HS,e.encoder.hasStructureUpdate=!1),f&&i?.localTime){let O=i?.localTime,F=r.get(O);if(F){let Z=wt(F).previousLocalTime;return y=r.put(O,Vl(a,t,n,Z,u?.nodeId??server.replication.getThisNodeId(r)??0,N,d,B_,g,T,R,h),{ifVersion:E}),y}}y=r.put(s===void 0?L4:v_,Vl(a,t,n,i?.localTime?1:0,u?.nodeId??server.replication?.getThisNodeId(r)??0,N,d,B_,g,T,R,h,u?.originatingOperation),{instructedWrite:!0,ifVersion:E})}return y}catch(R){throw R.message+=" id: "+n+" options: "+p,R}}}function Pu(e,t,r){if(t)return t.value&&t.metadataFlags&Yr&&!e.auditStore?.getBinaryFast(t.localTime)&&Va(t.value),e.remove(t.key,r)}var D4,Wy,Ky,v_,EM,L4,Qbe,$d,Xbe,H_,Zbe,Yy,M4,eIe,v4,gM,zy,yM,AM,HS,$c,tIe,B_,Ou,F_,SM,TM,dt,RM,Cu,ml=ce(()=>{D4=require("msgpackr");Yi();Wy=w(j());ts();ts();Ky=new Uint8Array([1,1,1,1,4,64,0,0]),v_=new Uint8Array([1,1,1,1,1,0,0,0]),EM=new Uint8Array([1,1,1,1,3,64,0,0]),L4=new Uint8Array([1,1,1,1,0,64,0,0]),Qbe=Symbol("local-timestamp"),$d=Symbol("metadata"),Xbe=Symbol("entry"),H_=new Uint8Array(8),Zbe=new DataView(H_.buffer,0,8),Yy=0,M4=0,eIe=1,v4=3,gM=4,zy=16,yM=32,AM=1,HS=256,$c=new WeakMap,Ou=0,F_=-1,SM=-1,TM=0,dt=null,RM=class extends D4.Encoder{static{o(this,"RecordEncoder")}constructor(t){t.useBigIntExtension=!0;class r{static{o(this,"RecordObject")}getUpdatedTime(){return $c.get(this)?.version}getExpiresAt(){return $c.get(this)?.expiresAt}}t.structPrototype=r.prototype,super(t);let n=this.encode;this.encode=function(i,a){if(Ou||F_>=0){let c=0,l=Ou;l&&(c+=8,Ou=0);let u=F_,d=SM,f=TM;u>=0&&(c+=4,F_=-1,d>=0&&(c+=8,SM=-1),f&&(c+=4,TM=0));let m=tIe=n.call(this,i,a|2048|c);B_=m.subarray((m.start||0)+c,m.end);let h=m.start||0;return l&&(Ky[4]=l,Ky[5]=l>>8,m.set(Ky,h),h+=8),ll&&(u|=Yr),u>=0&&((m.dataView||(m.dataView=new DataView(m.buffer,m.byteOffset,m.byteLength))).setUint32(h,u|Vy<<24),h+=4,d>=0&&((m.dataView||(m.dataView=new DataView(m.buffer,m.byteOffset,m.byteLength))).setFloat64(h,d),h+=8),f&&(m.dataView||(m.dataView=new DataView(m.buffer,m.byteOffset,m.byteLength))).setUint32(h,f)),m}else return B_=n.call(this,i,a),B_};let s=this.saveStructures;this.saveStructures=function(i,a){let c=s.call(this,i,a);return this.hasStructureUpdate=!0,c}}decode(t,r){dt=null;let n=r?.start||0,s=r>-1?r:r?.end||t.length,i=t[n],a=0;try{if(i<32&&s>2){let c=n,l;if(i===2){if(t.copy)t.copy(H_,0,c),c+=8;else for(let m=0;m<8;m++)H_[m]=t[c++];l=rIe(),i=t[c]}let u,d;i<32&&(i===Vy?(a=(t.dataView||(t.dataView=new DataView(t.buffer,t.byteOffset,t.byteLength))).getUint32(c),c+=4):(a=i|t[c+1]<<5,c+=2),a&zy&&(u=(t.dataView||(t.dataView=new DataView(t.buffer,t.byteOffset,t.byteLength))).getFloat64(c),c+=8),a&yM&&(d=(t.dataView||(t.dataView=new DataView(t.buffer,t.byteOffset,t.byteLength))).getUint32(c),c+=4));let f=vo(()=>r?.valueAsBuffer?t.subarray(c,s):super.decode(t.subarray(c,s),s-c),this.rootStore);return dt={localTime:l,[$d]:a,expiresAt:u,residencyId:d},f}return r?.valueAsBuffer?t:vo(()=>super.decode(t,r),this.rootStore)}catch(c){return Wy.error("Error decoding record",c,"data: "+t.slice(0,40).toString("hex")),null}}};o(rIe,"getTimestamp");o(jy,"handleLocalTimeForGets");Cu=[];setInterval(()=>{for(let e=0;e<Cu.length;e++){let t=Cu[e].deref();!t||t.isDone||t.isCommitted?Cu.splice(e--,1):t.notCurrent&&(t.openTimer?(t.openTimer>3&&(t.openTimer>60?(Wy.error("Read transaction detected that has been open too long (over 15 minutes), ending transaction",t),t.done()):Wy.error("Read transaction detected that has been open too long (over one minute), make sure read transactions are quickly closed",t)),t.openTimer++):t.openTimer=1)}},15e3).unref();o(bM,"recordUpdater");o(Pu,"removeEntry")});function wM(e,t,r,n,s,i,a,c){let l=e[0];if(t==="or"){let f=u(l);for(let h=1;h<e.length;h++){let p=e[h],E=u(p);f=f.concat(E)}let m=new Set;return f.filter(h=>{let p=h.key??h;return m.has(p)?!1:(m.add(p),!0)})}else{let f=u(l),m=d(e.slice(1),!0,l.estimated_count);return m.length>0?a(f,m):f}function u(f){return f.conditions?wM(f.conditions,f.operator,r,n,s,i,a,c):jf(f,n,f.descending||s.reverse===!0,r,s.allowFullScan,c,i)}o(u,"executeCondition");function d(f,m,h){return f.map((p,E)=>{if(p.conditions){let T=p.operator==="or",y=d(p.conditions,!T,h);return T?(N,O)=>y.some(F=>F(N,O)):(N,O)=>y.every(F=>F(N,O))}let g=(p.attribute||p[0])===r.primaryKey,R=q_(p,r,i,c,g,h);return m&&E<f.length-1&&h&&(h=dIe(r.primaryStore,p.estimated_count,h)),R}).filter(Boolean)}o(d,"mapConditionsToFilters")}function jf(e,t,r,n,s,i,a){let c=e[0]??e.attribute,l=e[1]??e.value,u=e.comparator;if(l===void 0&&u!=="sort")throw new nn.ClientError(`Search condition for ${c} must have a value`);if(Array.isArray(c)){let y=c[0],N=Io(n.attributes,y);if(N.relationship){if(c.length<2)throw new nn.ClientError("Can not directly query a relational attribute, must query an attribute within the target table");let O=N.definition?.tableClass||N.elements?.definition?.tableClass,F=new Map,Z=jf({attribute:c.length>2?c.slice(1):c[1],value:l,comparator:u},t,r,O,s,F);if(N.relationship.to){i[c[0]]=F;let q=!!Io(O.attributes,N.relationship.to)?.elements;Z=aIe(Z,N,O.primaryStore,q,F)}if(N.relationship.from){let q=o(Y=>(Y?.key!==void 0&&(Y=Y.key),jf({attribute:N.relationship.from,value:Y},t,r,n,s,F)),"searchEntry");N.elements?(i[c[0]]=F,Z=cIe(Z,N,O.primaryStore,F,q)):Z=Z.flatMap(q)}return Z}else if(c.length===1)c=c[0];else throw new nn.ClientError("Unable to query by attribute "+JSON.stringify(c))}let d=c===n.primaryKey||c==null,f=d?n.primaryStore:n.indices[c],m,h,p,E;l instanceof Date&&(l=l.getTime());let g;switch(OM[u]||u){case"lt":m=!0,h=l;break;case"le":m=!0,h=l,p=!0;break;case"gt":m=l,E=!0;break;case"ge":m=l;break;case"prefix":Array.isArray(l)?l[l.length-1]!=null&&(l=l.concat(null)):l=[l,null],m=l,h=l.slice(0),h[h.length-1]=bo.MAXIMUM_KEY;break;case"starts_with":m=l.toString(),h=l+"\uFFFF";break;case"between":case"gele":case"gelt":case"gtlt":case"gtle":m=l[0],m instanceof Date&&(m=m.getTime()),h=l[1],h instanceof Date&&(h=h.getTime()),p=u==="gele"||u==="gtle"||u==="between",E=u==="gtlt"||u==="gtle";break;case"equals":case void 0:m=l,h=l,p=!0;break;case"ne":if(l===null){m=l,E=!0;break}case"sort":case"contains":case"ends_with":m=!0,g=!0;break;default:throw new nn.ClientError(`Unknown query comparator "${u}"`)}let R;if(typeof m=="string"&&m.length>si.MAX_SEARCH_KEY_LENGTH&&(m=m.slice(0,si.MAX_SEARCH_KEY_LENGTH)+si.OVERFLOW_MARKER,E=!1,R=q_(e,n,null,i,d)),typeof h=="string"&&h.length>si.MAX_SEARCH_KEY_LENGTH&&(h=h.slice(0,si.MAX_SEARCH_KEY_LENGTH)+si.OVERFLOW_MARKER,p=!0,R=R??q_(e,n,null,i,d)),r){let y=m;m=h,h=y,y=!E,E=!p,p=y}if(!f||f.isIndexing||g||l===null&&!f.indexNulls){if(s===!1&&!f)throw new nn.ClientError(`"${c}" is not indexed, can not search for this attribute`,404);if(s===!1&&g)throw new nn.ClientError(`Can not use ${u||"equal"} operator without combining with a condition that uses an index, can not search for attribute ${c}`,403);if(f?.isIndexing)throw new nn.ServerError(`"${c}" is not indexed yet, can not search for this attribute`,503);if(l===null&&f&&!f.indexNulls)throw new nn.ClientError(`"${c}" is not indexed for nulls, index needs to be rebuilt to search for nulls, can not search for this attribute`,400);if(R=R??q_(e,n,null,i,d),!R)throw new nn.ClientError(`Unknown search operator ${e.comparator}`)}let T={start:m,end:h,inclusiveEnd:p,exclusiveStart:E,values:!0,versions:d,transaction:t,reverse:r};if(d){let y=f.getRange(T).map(R?function({key:N,value:O}){return this?.isSync?O&&R(O)?N:Vc.SKIP:new Promise((F,Z)=>setImmediate(()=>{try{F(O&&R(O)?N:Vc.SKIP)}catch(q){Z(q)}}))}:N=>N.value==null&&!(N.metadataFlags&(Wn|Du))?Vc.SKIP:(a?._freezeRecords&&Object.freeze(N.value),N));return y.hasEntries=!0,y}else return f?f.customIndex?f.customIndex.search(e,a).map(y=>{if(typeof y=="object"&&y){let{key:N,...O}=y,F=n.primaryStore.getEntry(N);return a?._freezeRecords&&Object.freeze(F?.value),{...O,...F}}return y}):f.getRange(T).map(R?function({key:y,value:N}){let O;return typeof y=="string"&&y.length>si.MAX_SEARCH_KEY_LENGTH?O=n.primaryStore.get(N):O={[c]:y},this.isSync?R(O)?N:Vc.SKIP:new Promise((F,Z)=>setImmediate(()=>{try{F(R(O)?N:Vc.SKIP)}catch(q){Z(q)}}))}:({value:y})=>y):n.primaryStore.getRange(r?{end:!0,transaction:t,reverse:!0}:{start:!0,transaction:t}).map(function({key:y,value:N}){return this.isSync?N&&R(N)?y:Vc.SKIP:new Promise((O,F)=>setImmediate(()=>{try{O(N&&R(N)?y:Vc.SKIP)}catch(Z){F(Z)}}))})}function Io(e,t){if(Array.isArray(t))if(t.length>1){let r=Io(e,t[0]),n=(r?.definition?.tableClass||r?.elements?.definition?.tableClass)?.attributes??r?.properties;return n?Io(n,t.slice(1)):void 0}else t=t.toString();else typeof t!="string"&&(t=t.toString());return e.find(r=>r.name===t)}function aIe(e,t,r,n,s){return new e.constructor({[Symbol.iterator](){let i;return s.hasMappings=!0,{next(){if(!i){let c=t.relationship.to,l=o((u,d)=>{let f=s.get(u);f?f.push(d):s.set(u,f=[d])},"addEntry");for(let u of e){let d=u.value??r.get(u.key??u),f=d?.[c];if(f!=null&&!s.filters?.some(m=>!m(d)))if(n)for(let m=0;m<f.length;m++)l(f[m],u);else l(f,u)}return i=s.keys()[Symbol.iterator](),this.next()}let a=i.next();return a.done?a:{value:a.value}},return(){if(i?.return)return i.return()}}}})}function cIe(e,t,r,n,s){return new e.constructor({[Symbol.iterator](){let i,a,c=new Set;return{next(){let l;if(a)for(;l=a.next(),!l.done;){let u=l.value;if(!c.has(u))return c.add(u),l}if(!i){let u=new Set;n.fromRecord=d=>d[t.relationship.from]?.filter?.(f=>u.has(f));for(let d of e){if(n.filters){let f=r.get(d);if(n.filters.some(m=>!m(f)))continue}u.add(d)}return i=u[Symbol.iterator](),this.next()}do{let u=i.next();return u.done?u:(a=s(u.value)[Symbol.iterator](),this.next())}while(!0)},return(){return a?.return?.()},throw(){return a?.throw?.()}}}})}function q_(e,t,r,n,s,i){let a=e.comparator,c=e[0]??e.attribute,l=e[1]??e.value;if(Array.isArray(c)){if(c.length===0)return()=>!0;if(c.length===1)c=c[0];else if(c.length>1){let d=c[0],f=Io(t.attributes,d),m=f.definition?.tableClass||f.elements.definition?.tableClass,h=n?.[d],p=q_({attribute:c.length>2?c.slice(1):c[1],value:l,comparator:a},m,r,h?.[d]?.joined,c[1]===m.primaryKey,i);if(!p)return;if(h){h.filters||(h.filters=[]),h.filters.push(p);return}let E=t.propertyResolvers?.[d];E.to&&(p.to=E.to);let g,R=o((y,N)=>{let O,F;return E?E.returnDirect?(O=E(y,r,N),F=dt):(F=E(y,r,N,!0),Array.isArray(F)?(O=F.map(Z=>Z.value),F=null):O=F?.value):O=y[d],{subObject:O,subEntry:F}},"getSubObject"),T=o((y,N)=>{if(E&&p.idFilter){if(!g)if(p.idFilter.idSet?.size===1){for(let Y of p.idFilter.idSet)e={attribute:E.from??t.primaryKey,value:Y};g=u(E.from??t.primaryKey,p.idFilter,!0,!0)}else g=u(E.from??t.primaryKey,p.idFilter,!1,!0);let q=g(y);return g.idFilter&&(T.idFilter=g.idFilter),q}let{subObject:O,subEntry:F}=R(y,N);return O?Array.isArray(O)?(!n?.[d]&&n&&(n[d]={fromRecord(q){let Y=R(q).subObject;return Array.isArray(Y)?Y.filter(p).map(K=>K[m.primaryKey]):Y}}),O.some(p)):p(O,F):!1},"recordFilter");return T}}switch(l instanceof Date&&(l=l.getTime()),OM[a]||a){case si.SEARCH_TYPES.EQUALS:case void 0:return u(c,d=>d===l,!0);case"contains":return u(c,d=>d?.toString().includes(l));case"ends_with":return u(c,d=>d?.toString().endsWith(l));case"starts_with":return u(c,d=>typeof d=="string"&&d.startsWith(l),!0);case"prefix":return Array.isArray(l)?l[l.length-1]==null&&(l=l.slice(0,-1)):l=[l],u(c,d=>{if(!Array.isArray(d))return!1;for(let f=0,m=l.length;f<m;f++)if(d[f]!==l[f])return!1;return!0},!0);case"between":return l[0]instanceof Date&&(l[0]=l[0].getTime()),l[1]instanceof Date&&(l[1]=l[1].getTime()),u(c,d=>(0,bo.compareKeys)(d,l[0])>=0&&(0,bo.compareKeys)(d,l[1])<=0,!0);case"gt":return u(c,d=>(0,bo.compareKeys)(d,l)>0);case"ge":return u(c,d=>(0,bo.compareKeys)(d,l)>=0);case"lt":return u(c,d=>(0,bo.compareKeys)(d,l)<0);case"le":return u(c,d=>(0,bo.compareKeys)(d,l)<=0);case"ne":return u(c,d=>(0,bo.compareKeys)(d,l)!==0,!1,!0);case"sort":return()=>!0;default:throw new nn.ClientError(`Unknown query comparator "${a}"`)}function u(d,f,m,h){let p;m=m&&!s&&t?.indices[d]&&i>3,m&&(e.estimated_count==null&&Qy(t)(e),p=e.estimated_count>>4,(isNaN(p)||p>=i)&&(m=!1));let E=0,g=3;function R(T){let y=T[d],N;if(typeof y!="object"||!y||h?N=f(y):Array.isArray(y)?N=y.some(f):y instanceof Date&&(N=f(y.getTime())),m&&(g++,!N&&!R.idFilter&&++E/g*i>p)){let O=jf(e,r.transaction.getReadTxn(),!1,t),F;R.to?F=O.flatMap(q=>t.primaryStore.get(q)[R.to]):F=O.map(Jf);let Z=new Set(F);R.idFilter=q=>Z.has(Jf(q)),R.idFilter.idSet=Z}return N}return o(R,"recordFilter"),s&&(R.idFilter=f),R}o(u,"attributeComparator")}function Qy(e){function t(r){if(r.estimated_count===void 0){if(r.conditions){let s;if(r.operator==="or"){s=0;for(let i of r.conditions)t(i),s+=i.estimated_count}else{s=1/0;for(let i of r.conditions)t(i),s=isFinite(s)?s*i.estimated_count/Ia(e.primaryStore):i.estimated_count}return r.estimated_count=s,r.estimated_count}let n=r.comparator||r.search_type;if(n=OM[n]||n,n===si.SEARCH_TYPES.EQUALS||!n){let s=r[0]??r.attribute;if(s==null||s===e.primaryKey)r.estimated_count=1;else if(Array.isArray(s)&&s.length>1){let i=Io(e.attributes,s[0]),a=i.definition?.tableClass||i.elements.definition?.tableClass,c=Qy(a)({value:r.value,attribute:s.length>2?s.slice(1):s[1],comparator:"equals"}),l=e.indices[i.relationship.from];r.estimated_count=c+(l?c*Ia(e.indices[i.relationship.from])/(Ia(a.primaryStore)||1):c)}else{let i=e.indices[s];r.estimated_count=i?i.getValuesCount(r[1]??r.value):1/0}}else if(n==="contains"||n==="ends_with"||n==="ne"){let s=r[0]??r.attribute,i=e.indices[s];r.value===null&&n==="ne"?r.estimated_count=Ia(e.primaryStore)-(i?i.getValuesCount(null):0):r.estimated_count=1/0}else if(n==="starts_with"||n==="prefix")r.estimated_count=iIe*Ia(e.primaryStore)+1;else if(n==="between")r.estimated_count=sIe*Ia(e.primaryStore)+1;else if(n==="sort"){let s=r[0]??r.attribute,i=e.indices[s];i?.customIndex?.estimateCountAsSort?r.estimated_count=i.customIndex.estimateCountAsSort(r):r.estimated_count=Ia(e.primaryStore)+1}else{let s=r[0]??r.attribute,i=e.indices[s];i?.customIndex?.estimateCount?r.estimated_count=i.customIndex.estimateCount(r.value):r.estimated_count=nIe*Ia(e.primaryStore)+1}typeof r.descending=="boolean"&&(r.estimated_count/=2)}return r.estimated_count}return o(t,"estimateConditionForTable"),t}function Qg(e,t){if(e)if(Na=e,Yf.lastIndex=0,lIe.test(e))try{if(t&&(t.conditions=[]),$i=t??new zf,k_($i,""),Gr!==Na.length&&Xt("Unable to parse query, unexpected end of query"),$i.parseErrorMessage&&($i.parseError=new IM(t.parseErrorMessage),!t))throw $i.parseError;return $i}catch(r){if(r.statusCode=400,r.message=`Unable to parse query, ${r.message} at position ${Gr} in '${Na}'`,$i.parseErrorMessage&&(r.message+=", "+$i.parseErrorMessage),t)t.parseError=r;else throw r}else return t??new URLSearchParams(e)}function Xt(e){let t=`${e} at position ${Gr}`;$i.parseErrorMessage=$i.parseErrorMessage?$i.parseErrorMessage+", "+t:t}function k_(e,t){let r=Yf,n,s,i,a,c,l=decodeURIComponent,u;for(;n=r.exec(Na);){Gr=r.lastIndex;let[,d,f]=n;a?(d&&Xt(`expected operator, but encountered '${d}'`),a=!1,c=!1):c=!0;let m;switch(f){case"=":s!=null?(d.length<=2?i=d:Xt(`invalid FIQL operator ${d}`),l=U4):(l=decodeURIComponent,i="equals",d||Xt("attribute must be specified before equality comparator"),s=Wf(d));break;case"==":case"!=":case"<":case"<=":case">":case">=":case"===":case"!==":i=oIe[f],l=NM[i]?U4:decodeURIComponent,d||Xt(`attribute must be specified before comparator ${f}`),s=Wf(d);break;case"&=":case"|=":case"|":case"&":case"":case void 0:if(s==null)s===void 0&&(t&&Xt(`expected '${t}', but encountered ${f[0]?"'"+f[0]+"'":"end of string"}}`),Xt(`no comparison specified before ${f?"'"+f+"'":"end of string"}`));else{e.conditions||Xt("conditions/comparisons are not allowed in a property list");let p={comparator:i,attribute:s||null,value:l(d)};if(i==="eq"&&x4(p,d),s===""){let E=e.conditions[e.conditions.length-1];E.chainedConditions=E.chainedConditions||[],E.chainedConditions.push(p),E.operator=u}else Jy(e,u),e.conditions.push(p)}f==="&"?(u="and",s=void 0):f==="|"?(u="or",s=void 0):f==="&="?(u="and",s=""):f==="|="&&(u="or",s="");break;case",":e.conditions?Xt("conditions/comparisons are not allowed in a property list"):e.push(Wf(d)),s=void 0;break;case"(":Yf.lastIndex=Gr;let h=k_(d?[]:new zf,")");switch(d){case"":Jy(e,u),e.conditions.push(h);break;case"limit":switch(h.length){case 1:e.limit=+h[0];break;case 2:e.offset=+h[0],e.limit=h[1]-e.offset;break;default:Xt("limit must have 1 or 2 arguments")}break;case"select":Array.isArray(h[0])&&h.length===1&&!h[0].name?(e.select=h[0],e.select.asArray=!0):h.length===1?e.select=h[0]:h.length===2&&h[1]===""?e.select=h.slice(0,1):e.select=h;break;case"group-by":Xt("group by is not implemented yet");case"sort":e.sort=B4(h);break;default:Xt(`unknown query function call ${d}`)}Na[Gr]===","?r.lastIndex=++Gr:a=!0,s=null;break;case"{":e.conditions&&Xt("property sets are not allowed in a queries"),d||Xt("property sets must have a defined parent property name"),Yf.lastIndex=Gr,m=k_([],"}"),m.name=d,e.push(m),Na[Gr]===","?r.lastIndex=++Gr:a=!0;break;case"[":if(Yf.lastIndex=Gr,d?(m=k_(new zf,"]"),m.name=d):m=k_(e.conditions?new zf:[],"]"),e.conditions)if(Jy(e,u),Na[Gr]==="="){l=decodeURIComponent,i="equals",s=Wf(d),r.lastIndex=++Gr;break}else e.conditions.push(m),s=null;else e.push(m);Na[Gr]===","?r.lastIndex=++Gr:a=!0;break;case")":case"]":case"}":if(t===f[0]){if(e.conditions)if(s){let p={comparator:i||"equals",attribute:s,value:l(d)};i==="eq"&&x4(p,d),Jy(e,u),e.conditions.push(p)}else d&&Xt("no attribute or comparison specified");else(d||e.length>0&&c)&&e.push(Wf(d));return e}else Xt(t?`expected '${t}', but encountered '${f[0]}'`:`unexpected token '${f[0]}'`);default:Xt(`unexpected operator '${f}'`)}if(t!==")"&&(r=s?uIe:Yf,r.lastIndex=Gr),Gr===Na.length)return e}t&&Xt(`expected '${t}', but encountered end of string`)}function Jy(e,t){e.conditions.length>0&&(e.operator?e.operator!==t&&Xt("Can not mix operators within a condition grouping"):e.operator=t)}function Wf(e){return e.indexOf(".")>-1?e.split(".").map(Wf):decodeURIComponent(e)}function U4(e){if(e==="null")return null;if(e.indexOf(":")>-1){let[t,r]=e.split(":");if(t==="number")return r[0]==="$"?parseInt(r.slice(1),36):+r;if(t==="boolean")return r==="true";if(t==="date")return new Date(isNaN(r)?decodeURIComponent(r):+r);if(t==="string")return decodeURIComponent(r);throw new nn.ClientError(`Unknown type ${t}`)}return decodeURIComponent(e)}function x4(e,t){if(t.indexOf("*")>-1)if(t.endsWith("*"))e.comparator="starts_with",e.value=decodeURIComponent(t.slice(0,-1));else throw new nn.ClientError("wildcard can only be used at the end of a string")}function B4(e){let t=F4(e[0]);return e.length>1&&(t.next=B4(e.slice(1))),t}function F4(e){if(Array.isArray(e)){let t=F4(e[0]);return e[0]=t.attribute,t.attribute=e,t}if(typeof e=="string")switch(e[0]){case"-":return{attribute:e.slice(1),descending:!0};case"+":return{attribute:e.slice(1),descending:!1};default:return{attribute:e,descending:!1}}Xt(`Unknown sort type ${e}`)}function Jf(e){return Array.isArray(e)?e.join("\0"):e}function Ia(e){let t=Date.now();return(e.estimatedEntryCountExpires||0)<t&&(e.estimatedEntryCount=e.getStats().entryCount,e.estimatedEntryCountExpires=t+1e4),e.estimatedEntryCount}function dIe(e,t,r){return t*r/Ia(e)}var nn,si,bo,Vc,nIe,sIe,iIe,oIe,NM,OM,IM,lIe,Yf,uIe,Gr,$i,Na,zf,Xg=ce(()=>{nn=w(ge()),si=w(Kt()),bo=require("ordered-binary"),Vc=require("lmdb");hR();ml();nIe=.3,sIe=.1,iIe=.05,oIe={"<":"lt","<=":"le",">":"gt",">=":"ge","!=":"ne","==":"eq","===":"equals","!==":"not_equal"},NM={lt:!0,le:!0,gt:!0,ge:!0,ne:!0,eq:!0};o(wM,"executeConditions");o(jf,"searchByIndex");o(Io,"findAttribute");o(aIe,"joinTo");o(cIe,"joinFrom");OM={eq:"equals",greater_than:"gt",greaterThan:"gt",greater_than_equal:"ge",greaterThanEqual:"ge",less_than:"lt",lessThan:"lt",less_than_equal:"le",lessThanEqual:"le",not_equal:"ne",notEqual:"ne",equal:"equals",sw:"starts_with",startsWith:"starts_with",ew:"ends_with",endsWith:"ends_with",ct:"contains",">":"gt",">=":"ge","<":"lt","<=":"le","...":"between"};o(q_,"filterByType");o(Qy,"estimateCondition");IM=class extends nn.Violation{static{o(this,"SyntaxViolation")}},lIe=/[()[\]|!<>.]|(=\w*=)/,Yf=/([^?&|=<>!([{}\]),]*)([([{}\])|,&]|[=<>!]*)/g,uIe=/([^&|=[\]{}]+)([[\]{}]|[&|=]*)/g;o(Qg,"parseQuery");o(Xt,"recordError");o(k_,"parseBlock");o(Jy,"assignOperator");o(Wf,"decodeProperty");o(U4,"typedDecoding");o(x4,"wildcardDecoding");o(B4,"toSortObject");o(F4,"toSortEntry");zf=class{static{o(this,"Query")}constructor(){this.conditions=[]}[Symbol.iterator](){return this.conditions[Symbol.iterator]()}get(t){for(let r=0;r<this.conditions.length;r++){let n=this.conditions[r];if(n.attribute===t)return n.value}}getAll(){let t=[];for(let r=0,n=this.conditions.length;r<n;r++){let s=this.conditions[r];s.attribute&&t.push(s.value)}return t}};o(Jf,"flattenKey");o(Ia,"estimatedEntryCount");o(dIe,"intersectionEstimate")});var zF={};we(zF,{MultiPartId:()=>Xy,Resource:()=>Hr,contextStorage:()=>Xf,snakeCase:()=>mIe,transformForSelect:()=>Zf});function mIe(e){return e[0].toLowerCase()+e.slice(1).replace(/[a-z][A-Z][a-z]/g,t=>t[0]+"_"+t.slice(1))}function H4(e,t){if(Lu=!1,e==="")return null;if(e=e.slice(1),t.splitSegments){if(e.indexOf("/")===-1)return e===""?(Lu=!0,null):t.coerceId(decodeURIComponent(e));let r=e.split("/"),n=new Xy;for(let s=0;s<r.length;s++){let i=r[s];if(!i&&s===r.length-1){Lu=!0;break}n[s]=t.coerceId(decodeURIComponent(i))}return n}else{if(e==="")return Lu=!0,null;e[e.length-1]==="/"&&(Lu=!0)}return t.coerceId(decodeURIComponent(e))}function zn(e,t){n.reliesOnPrototype=!0;let r=t.hasContent;return n;function n(s,i,a){let c,l,u,d;if(r){if(a)d=i,a=a.getContext?.()||a;else if(i)typeof s=="object"&&s&&(!Array.isArray(s)||typeof s[0]=="object")?(d=s,c=d[this.primaryKey]??null,a=i.getContext?.()||i):i?.transaction instanceof Lo?a=i:d=i;else if(s&&typeof s=="object")d=s,s=void 0,c=d.getId?.()??d[this.primaryKey];else throw new Qf.ClientError(`Invalid argument for data, must be an object, but got ${s}`);c===null&&(u=!0)}else i?a=i.getContext?.()||i:s&&typeof s=="object"&&!Array.isArray(s)&&(a=s);if(c===void 0)if(typeof s=="object"&&s){if(l=s,c=s instanceof URLSearchParams?s.toString():s.url,s.conditions)c=s.id;else if(typeof c=="string")if(this.directURLMapping)c=c.slice(1),l.id=c;else{let E=c.indexOf("?");E>-1&&(l=this.parseQuery(c.slice(E+1),s),c=c.slice(0,E),c===""&&(u=!0));let g=this.parsePath(c,a,l);g?.id!==void 0?(g.query&&(l?l=Object.assign(g.query,l):l=g.query),u=g.isCollection,c=g.id):c=g,c&&(l.id=c)}else if(s[Symbol.iterator]){c=[],u=!0;for(let E of s){if(typeof E=="object"&&E)break;c.push(E)}c.length===0?c=null:(c.length===1&&(c=c[0]),l.slice&&(l=l.slice(c.length,l.length),l.length===0&&(l=new Ai,l.id=c,u=!1)))}c===void 0&&(c=s.id??null,c==null&&(u=!0))}else c=s,l=new Ai,l.id=c,c==null&&(u=!0);l||(l=new Ai,l.id=c),u&&(l.isCollection=!0);let f;a||(a=Xf.getStore()??{}),l.ensureLoaded!=null||l.async||u?(f={...t},l.ensureLoaded!=null&&(f.ensureLoaded=l.ensureLoaded),l.async&&(f.async=l.async),u&&(f.isCollection=!0)):f=t;let m=this.loadAsInstance,h=p;if((m===!1?!this.explicitContext:this.explicitContext===!1)&&(h=o(E=>Xf.run(a,()=>p(E)),"runAction")),a?.transaction){let E=this.getResource(c,a,f);return E.then?E.then(h):h(E)}else return Ft(a,()=>{let E=this.getResource(c,a,f);return E.then?E.then(h):h(E)},f);function p(E){if(m!==!1&&a.authorize){a.authorize=!1;let g=t.type==="read"?E.allowRead(a.user,l,a):t.type==="update"?E.doesExist?.()===!1?E.allowCreate(a.user,d,a):E.allowUpdate(a.user,d,a):t.type==="create"?E.allowCreate(a.user,d,a):E.allowDelete(a.user,l,a);if(g?.then)return g.then(R=>{if(!R)throw new Qf.AccessViolation(a.user);return typeof d?.then=="function"?d.then(T=>e(E,l,a,T)):e(E,l,a,d)});if(!g)throw new Qf.AccessViolation(a.user)}return typeof d?.then=="function"?d.then(g=>e(E,l,a,g)):e(E,l,a,d)}o(p,"authorizeActionOnResource")}}function As(e,t){let r=new Qf.ClientError(`The ${e.constructor.name} does not have a ${t} method implemented`,405);r.allow=[],r.method=t;for(let n of["get","put","post","delete","query","move","copy"])typeof e[n]=="function"&&r.allow.push(n);throw r}function CM(e,t,r){let n=e.getRecord?.();if(n){let s=e.getChanges?.();return i=>{let a,c;return e.hasOwnProperty(i)&&typeof(a=e[i])!="function"?a:s&&i in s?s[i]:(c=t?.[i])?c(e,r):n[i]}}else return t?s=>{let i=t[s];return i?i(e,r):e[s]}:s=>e[s]}function Zf(e,t){let r=t.propertyResolvers,n=t.getContext?.(),s;if(typeof e=="string")return o(function a(c){return c.then?c.then(a):Array.isArray(c)?c.map(a):CM(c,r,n)(e)},"transform");if(typeof e=="object"){if(e.asArray)return o(function c(l){if(l.then)return l.then(c);if(Array.isArray(l))return l.map(c);let u=[],d=i(CM(l,r,n));for(let f of e)u.push(d(f));return u},"transform");let a=e.forceNulls;return o(function c(l){if(l.then)return l.then(c);if(Array.isArray(l))return l.map(m=>m&&typeof m=="object"?c(m):m);let u={},d=i(CM(l,r,n)),f;for(let m of e){let h=d(m);h===void 0&&a&&(h=null),h?.then?(f||(f=[]),f.push(h.then(p=>u[m.name||m]=p))):u[m.name||m]=h}return f?Promise.all(f).then(()=>u):u},"transform")}else throw new Error("Invalid select argument type "+typeof e);function i(a){return c=>{if(typeof c=="string")return a(c);if(typeof c=="object")if(c.name){s||(s={});let l=s[c.name];if(!l){let d=r[c.name]?.definition?.tableClass;l=s[c.name]=Zf(c.select||c,d)}let u=a(c.name);return l(u)}else return a(c);else return c}}o(i,"handleProperty")}var k4,q4,Qf,G4,Xf,fIe,Hr,Lu,Xy,tc=ce(()=>{k4=require("crypto");vm();zu();q4=w(mi()),Qf=w(ge());ol();Xg();G4=require("async_hooks");zg();Xf=new G4.AsyncLocalStorage,fIe={json:"application/json",cbor:"application/cbor",msgpack:"application/x-msgpack",csv:"text/csv"},Hr=class{static{o(this,"Resource")}#e;#t;#r;static transactions;static directURLMapping=!1;static loadAsInstance;constructor(t,r){this.#e=t;let n=r?.getContext?r.getContext()??null:void 0;this.#t=n!==void 0?n:r||null}static get=zn(function(t,r,n,s){let i=t.get?.(r);if(t.constructor.loadAsInstance===!1)return i;if(i?.then)return i.then(a);return a(i);function a(c){let l;if((l=r?.select)&&c!=null&&!c.selectApplied){let u=Zf(l,t.constructor);return typeof c?.map=="function"?c.map(u):u(c)}return c}},{type:"read",letItLinger:!0,ensureLoaded:!0,async:!0});static put=zn(function(t,r,n,s){if(Array.isArray(s)&&t.#r&&t.constructor.loadAsInstance!==!1){let i=[];for(let a of s){let c=t.constructor,l=a[c.primaryKey],u=c.getResource(l,n,{async:!0});u.then?i.push(u.then(d=>d.put(a,n))):i.push(u.put(a,n))}return Promise.all(i)}return t.put?t.constructor.loadAsInstance===!1?t.put(r,s):t.put(s,r):As(t,"put")},{hasContent:!0,type:"update"});static patch=zn(function(t,r,n,s){return t.patch?t.constructor.loadAsInstance===!1?t.patch(r,s):t.patch(s,r):As(t,"patch")},{hasContent:!0,type:"update"});static delete=zn(function(t,r,n,s){return t.delete?t.delete(r):As(t,"delete")},{hasContent:!1,type:"delete"});static getNewId(){return(0,k4.randomUUID)()}static create(t,r,n){n?n.getContext&&(n=n.getContext()):n=Xf.getStore()??{};let s;return this.loadAsInstance===!1?s=t:t==null?s=r?.[this.primaryKey]??this.getNewId():Array.isArray(t)&&typeof t[0]!="object"?s=r?.[this.primaryKey]??[...t,this.getNewId()]:typeof t!="object"?s=r?.[this.primaryKey]??[t,this.getNewId()]:(s=t?.[this.primaryKey]??this.getNewId(),n=r||{},r=t),Ft(n,async()=>{let i=new this(s,n),a=await i.create?i.create(s,r):As(i,"create");return n.newLocation=s??a?.[this.primaryKey],n.createdResource=!0,this.loadAsInstance===!1?a:i})}static invalidate=zn(function(t,r,n,s){return t.invalidate?t.invalidate(r):As(t,"delete")},{hasContent:!1,type:"update"});static post=zn(function(t,r,n,s){return t.#e!=null&&t.update?.(),t.constructor.loadAsInstance===!1?t.post(r,s):t.post(s,r)},{hasContent:!0,type:"create"});static update=zn(function(t,r,n,s){return t.update(r,s)},{hasContent:!0,type:"create"});static connect=zn(function(t,r,n,s){return t.connect?t.constructor.loadAsInstance===!1?t.connect(r,s):t.connect(s,r):As(t,"connect")},{hasContent:!0,type:"read"});static subscribe=zn(function(t,r,n,s){return t.subscribe?t.subscribe(r):As(t,"subscribe")},{type:"read"});static publish=zn(function(t,r,n,s){return t.#e!=null&&t.update?.(),t.publish?t.constructor.loadAsInstance===!1?t.publish(r,s):t.publish(s,r):As(t,"publish")},{hasContent:!0,type:"create"});static search=zn(function(t,r,n){let s=t.search?t.search(r):As(t,"search"),i=n.select;if(i&&n.hasOwnProperty("select")&&s!=null&&!s.selectApplied){let a=Zf(i,t.constructor);return s.map(a)}return s},{type:"read"});static query=zn(function(t,r,n,s){return t.search?t.constructor.loadAsInstance===!1?t.search(r,s):t.search(s,r):As(t,"search")},{hasContent:!0,type:"read"});static copy=zn(function(t,r,n,s){return t.copy?t.constructor.loadAsInstance===!1?t.copy(r,s):t.copy(s,r):As(t,"copy")},{hasContent:!0,type:"create"});static move=zn(function(t,r,n,s){return t.move?t.constructor.loadAsInstance===!1?t.move(r,s):t.move(s,r):As(t,"move")},{hasContent:!0,type:"delete"});async post(t){if(this.#r)return(await this.constructor.create(this.#e,t,this.#t)).#e;As(this,"post")}static isCollection(t){return t&&t.#r}get isCollection(){return this.#r}static coerceId(t){return t}static parseQuery(t,r){return Qg(t,r)}static parsePath(t,r,n){let s=t.indexOf(".");if(s>-1){let a=t.slice(s+1),c=r?.headers&&fIe[a];if(c)r.requestedContentType=c,t=t.slice(0,s);else if(this.attributes?.find(l=>l.name===a))if(t=t.slice(0,s),n)n.property=a;else return{query:{property:a},id:H4(t,this),isCollection:Lu}}let i=H4(t,this);return Lu?{id:i,isCollection:!0}:i}static getResource(t,r,n){let s,i=r.getContext?.(),a;typeof r.isCollection=="boolean"&&r.hasOwnProperty("isCollection")?a=r.isCollection:a=n?.isCollection;let c=a&&this.Collection||this;if(i||(i=i===void 0?r:{}),i.transaction){let l;if(i.resourceCache?l=i.resourceCache:l=i.resourceCache=[],l.asMap){let u=l.asMap.get(t);if(s=u?.find(d=>d.constructor===c),s)return s;u||l.asMap.set(t,u=[]),u.push(s=new c(t,i))}else{if(s=l.find(u=>u.#e===t&&u.constructor===c),s)return s;if(l.push(s=new c(t,i)),l.length>10){let u=new Map;for(let d of l){let f=d.#e,m=u.get(f);m?m.push(d):u.set(f,[d])}i.resourceCache.length=0,i.resourceCache.asMap=u}}}else s=new c(t,i);return a&&(s.#r=!0),s}subscribe(t){return new es}connect(t,r){return r?.subscribe!==!1?this.subscribe?.(r):new es}allowRead(t,r){return t?.role.permission.super_user}allowUpdate(t,r,n){return t?.role.permission.super_user}allowCreate(t,r,n){return t?.role.permission.super_user}allowDelete(t,r){return t?.role.permission.super_user}getId(){return this.#e}getContext(){return this.#t}};(0,q4._assignPackageExport)("Resource",Hr);o(mIe,"snakeCase");o(H4,"pathToId");Xy=class extends Array{static{o(this,"MultiPartId")}toString(){return this.join("/")}};o(zn,"transactional");o(As,"missingMethod");o(CM,"selectFromObject");o(Zf,"transformForSelect")});var KW={};we(KW,{EVICTED:()=>Du,INVALIDATED:()=>Wn,coerceType:()=>eA,makeTable:()=>rA});function rA(e){let{primaryKey:t,indices:r,tableId:n,tableName:s,primaryStore:i,databasePath:a,databaseName:c,auditStore:l,schemaDefined:u,dbisDB:d,sealed:f,splitSegments:m,replicate:h}=e,{expirationMS:p,evictionMS:E,audit:g,trackDeletes:R}=e;E??=0;let{attributes:T}=e;T||(T=[]);let y=bM(i,n,l),N,O,F={},Z=Promise.resolve(),q,Y,K;for(let V of T)(V.assignCreatedTime||V.name==="__createdtime__")&&(q=V),(V.assignUpdatedTime||V.name==="__updatedtime__")&&(Y=V),V.expiresAt&&(K=V),V.isPrimaryKey&&(F=V);let $,le=[],ue=[],ie=1,me=2,De={},Me={},ft=864e5,Ye=0,Xn,nt,_t,Zc=!1,el,Vt,mm,hm=vu.get(U.REPLICATION_DATABASES);if(Array.isArray(hm)){for(let V of hm)if(V.name===c&&V.replicateTo>=0){mm=V.replicateTo;break}}let lE=i.getRange({start:!1,end:!1}).constructor,uE=10,xA=6;g&&gm(),D_(i.env.path,V=>{if(O)return Fa(V)});class pm extends Pl{static{o(this,"Updatable")}getUpdatedTime(){return $c.get(this.getRecord())?.version}getExpiresAt(){return $c.get(this.getRecord())?.expiresAt}addTo(_,S){if(typeof S=="number"||typeof S=="bigint")this.set(_,new Ih(S));else throw new Error("Can not add or subtract a non-numeric value")}subtractFrom(_,S){return this.addTo(_,-S)}}class Ce extends Hr{#e;#t;#r;#n;#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=g;static databasePath=a;static databaseName=c;static attributes=T;static replicate=h;static sealed=f;static splitSegments=m??!0;static createdTimeProperty=q;static updatedTimeProperty=Y;static propertyResolvers;static userResolvers={};static sources=[];static getResidencyById;static get expirationMS(){return p}static dbisDB=d;static schemaDefined=u;static sourcedFrom(_,S){if(S&&(this.sourceOptions=S,(S.expiration||S.eviction||S.scanInterval)&&this.setTTLExpiration(S)),S?.intermediateSource)_.intermediateSource=!0,this.sources.unshift(_);else{if(this.sources.some(D=>!D.intermediateSource)){if(this.sources.some(D=>D.name===_.name))return;throw new Error("Can not have multiple canonical (non-intermediate) sources")}this.sources.push(_)}O=O||_.get&&(!_.get.reliesOnPrototype||_.prototype.get),N=N||_.load;let A=o(D=>{let L=this.sources;if(L=L.filter(k=>k.intermediateSource&&k[D]&&(!k[D].reliesOnPrototype||k.prototype[D])),L.length>0)if(L.length===1){let k=L[0];return(C,x,z)=>{if(C?.source!==k)return k[D](x,z,C)}}else return(k,C,x)=>{let z=[];for(let ne of L){if(k?.source===ne)break;z.push(ne[D](C,x,k))}return Promise.all(z)}},"getApplyToIntermediateSource"),b=this.sources[this.sources.length-1];b.intermediateSource&&(b={});let I=o(D=>{if(b[D]&&(!b[D].reliesOnPrototype||b.prototype[D]))return(L,k,C)=>{if(!L?.source)return b[D](k,C,L)}},"getApplyToCanonicalSource");De={put:I("put"),patch:I("patch"),delete:I("delete"),publish:I("publish")},Me={put:A("put"),patch:A("patch"),delete:A("delete"),publish:A("publish"),invalidate:A("invalidate")};let P=b.shouldRevalidateEvents;return(async()=>{let D=!1,L,k=o(async(C,x)=>{let z=C.value,ne=C.table?He[c][C.table]:Ce;if(c===Am&&(C.table===Ku.ROLE_TABLE_NAME||C.table===Ku.USER_TABLE_NAME)&&(D=!0),C.id===void 0&&(C.id=z[ne.primaryKey],C.id===void 0))throw new Error("Replication message without an id "+JSON.stringify(C));C.source=_;let re={residencyId:nl(C.residencyList),isNotification:!0,ensureLoaded:!1,nodeId:C.nodeId,async:!0},B=C.id,de=await ne.getResource(B,x,re);switch(C.finished&&await C.finished,C.type){case"put":return P?de._writeInvalidate(B,z,re):de._writeUpdate(B,z,!0,re);case"patch":return P?de._writeInvalidate(B,z,re):de._writeUpdate(B,z,!1,re);case"delete":return de._writeDelete(B,re);case"publish":case"message":return de._writePublish(B,z,re);case"invalidate":return de._writeInvalidate(B,z,re);case"relocate":return de._writeRelocate(B,re);default:Ue.default.error?.("Unknown operation",C.type,C.id)}},"writeUpdate");try{let C=_.subscribe;C&&R==null&&(R=!0);let x={crossThreads:!1,inTransactionUpdates:!0,supportsTransactions:!0,omitCurrent:!0},z=_.subscribeOnThisThread?_.subscribeOnThisThread((0,Mu.getWorkerIndex)(),x):(0,Mu.getWorkerIndex)()===0,ne=C&&z&&await _.subscribe?.(x);if(ne){let re;for await(let B of ne)try{if(!(B.type==="transaction"?B.writes[0]:B)){Ue.default.error?.("Bad subscription event",B);continue}if(B.source=_,B.type==="end_txn"){if(re?.resolve(),B.localTime&&L!==B.localTime){if(B.remoteNodeIds?.length>0){let Se=[Symbol.for("seq"),B.remoteNodeIds[0]],ee=d.get(Se),J=ee?.nodes;J||(J=[]);for(let Te of B.remoteNodeIds.slice(1)){let fe=J.find(We=>We.id===Te);J=J.filter(We=>We.id!==Te||We===fe),fe||(fe={id:Te,seqId:0},J.push(fe)),fe.seqId=Math.max(ee?.seqId??1,B.localTime),Te===re?.nodeId&&(fe.lastTxnTime=B.timestamp)}let pe=Math.max(ee?.seqId??1,B.localTime);Ue.default.trace?.("Received txn",c,pe,new Date(pe),B.localTime,new Date(B.localTime),B.remoteNodeIds),d.put(Se,{seqId:pe,nodes:J})}L=B.localTime}B.onCommit&&re?.committed.then(B.onCommit);continue}if(re)if(B.beginTxn)re.resolve();else{re.write_promises.push(k(B,re));continue}!B.timestamp&&B.version&&(B.timestamp=B.version);let he=Ft(B,()=>{if(B.type==="transaction"){let Se=[];for(let ee of B.writes)try{Se.push(k(ee,B))}catch(J){throw J.message+=" writing "+JSON.stringify(ee)+" of event "+JSON.stringify(B),J}return Promise.all(Se)}else if(B.type==="define_schema"){let Se=this.attributes.slice(0),ee=!1;for(let J of B.attributes)Se.find(pe=>pe.name===J.name)||(Se.push(J),ee=!0);ee&&(ze({table:s,database:c,attributes:Se,origin:"cluster"}),$_.signalSchemaChange(new V_.SchemaEventMsg(process.pid,G.CREATE_TABLE,c,s)))}else return B.beginTxn?(re=B,re.write_promises=[k(B,B)],new Promise(Se=>{re.resolve=()=>Se(Promise.all(re.write_promises))})):k(B,B)});re&&(re.committed=he),D&&he&&!he?.waitingForUserChange&&(he.then(()=>$_.signalUserChange(new V_.UserEventMsg(process.pid))),he.waitingForUserChange=!0),B.onCommit&&(he?he.then(B.onCommit):B.onCommit())}catch(de){Ue.default.error?.("error in subscription handler",de)}}}catch(C){Ue.default.error?.(C)}})(),this}static get isCaching(){return O}static get shouldRevalidateEvents(){return this.prototype.get!==Ce.prototype.get}static getResource(_,S,A){let b=super.getResource(_,S,A);if(this.loadAsInstance===!1&&(S._freezeRecords=!0),_!=null&&this.loadAsInstance!==!1){Lr(_);try{if(b.getRecord?.())return b;if(typeof _=="object"&&_&&!Array.isArray(_))throw new Error(`Invalid id ${JSON.stringify(_)}`);let I=!A?.async||i.cache?.get?.(_),P=Mr(S),D=P.getReadTxn();if(D?.isDone)throw new Error("You can not read from a transaction that has already been committed/aborted");return va(_,S,{transaction:D,ensureLoaded:A?.ensureLoaded},I,L=>{if(L?Ce._updateResource(b,L):b.#e=null,S.onlyIfCached){if(!b.doesExist())throw new ct.ServerError("Entry is not cached",504)}else if(A?.ensureLoaded){let k=tl(_,L,S,b);if(k)return P?.disregardReadTxn(),b.#i=!0,S.loadedFromSource=!0,ii(k,C=>(Ce._updateResource(b,C),b))}return b})}catch(I){throw I.message.includes("Unable to serialize object")&&(I.message+=": "+JSON.stringify(_)),I}}return b}static _updateResource(_,S){_.#n=S,_.#e=S?.value??null,_.#r=S?.version}ensureLoaded(){let _=tl(this.getId(),this.#n,this.getContext());if(_)return this.#i=!0,this.getContext().loadedFromSource=!0,ii(_,S=>{this.#n=S,this.#e=S.value,this.#r=S.version})}static getNewId(){let _=F?.type;if(_==="String"||_==="ID")return super.getNewId();if(!Vt){let I=i.getEntry(Symbol.for("id_allocation")),P=I?.value,D;if(P&&P.nodeName===server.hostname&&(!bIe(i)||P.pid===process.pid)){let L=P.start,k=P.end;D=L;for(let C of i.getKeys({start:k,end:L,limit:1,reverse:!0}))D=C}else P=b(I?.version??null),D=P.start;Vt=new BigInt64Array([BigInt(D)+1n]),Vt=new BigInt64Array(i.getUserSharedBuffer("id",Vt.buffer)),Vt.maxSafeId=P.end}let S=Number(Atomics.add(Vt,0,1n)),A=_==="Int"?512:1048576;if(S+A>=Vt.maxSafeId){let I=o(P=>{Vt.maxSafeId=S+(_==="Int"?1023:4194303);let D=(_==="Int"?Math.pow(2,31):Math.pow(2,49))-1,L=P?void 0:i.useReadTransaction(),k=Number(Vt[0]);for(let z of i.getKeys({start:k+1,end:D,limit:1,transaction:L}))D=z;L?.done();let{value:C,version:x}=i.getEntry(Symbol.for("id_allocation"));if(Vt.maxSafeId<D){if(C.end>Vt.maxSafeId-100)return;Ue.default.info?.("New id allocation",S,Vt.maxSafeId,x),i.put(Symbol.for("id_allocation"),{start:C.start,end:Vt.maxSafeId,nodeName:server.hostname,pid:process.pid},Date.now(),x)}else{Ue.default.warn?.(`Id conflict detected, starting new id allocation range, attempting to allocate to ${Vt.maxSafeId}, but id of ${D} detected`);let z=b(x);z.alreadyUpdated||Atomics.store(Vt,0,BigInt(z.start+1)),Vt.maxSafeId=z.end}},"updateEnd");S+A===Vt.maxSafeId?setImmediate(I):S+100>=Vt.maxSafeId&&(Ue.default.warn?.(`Synchronous id allocation required on table ${s}${_=="Int"?", it is highly recommended that you use Long or Float as the type for auto-incremented primary keys":""}`),i.transactionSync(()=>I(!0)))}return S;function b(I){let P=(_==="Int"?Math.pow(2,31):Math.pow(2,49))-1,D=P/4,L,k,C=!1,x,z;do{x=Math.floor(Math.random()*P),z={start:x,end:x+(_==="Int"?1024:4194304),nodeName:server.hostname,pid:process.pid},L=0;for(let ne of i.getKeys({start:x,limit:1,reverse:!0}))L=ne;k=P;for(let ne of i.getKeys({start:x+1,end:P,limit:1}))k=ne;D*=.875,D<1e3&&!C&&(C=!0,Ue.default.error?.(`Id allocation in table ${s} is very dense, limited safe range of numbers to allocate ids in${_==="Int"?", it is highly recommended that you use Long or Float as the type for auto-incremented primary keys":""}`,x,L,k,D))}while(!(D<k-x&&(D<x-L||L===0)));return i.transactionSync(()=>{let ne=i.getEntry(Symbol.for("id_allocation"));return(ne?.version??null)==I?(Ue.default.info?.("Allocated new id range",z),i.put(Symbol.for("id_allocation"),z,Date.now()),z):(Ue.default.debug?.("Looks like ids were already allocated"),{alreadyUpdated:!0,...ne.value})})}}static setTTLExpiration(_){if(typeof _=="number")p=_*1e3,E||(E=0);else if(_&&typeof _=="object")p=_.expiration*1e3,E=(_.eviction||0)*1e3,ft=_.scanInterval*1e3;else throw new Error("Invalid expiration value type");if(p<0)throw new Error("Expiration can not be negative");ft=ft||(p+E)/4,Fa()}static getResidencyRecord(_){return d.get([Symbol.for("residency_by_id"),_])}static setResidency(_){Ce.getResidency=_&&((S,A)=>{try{return _(S,A)}catch(b){throw b.message+=` in residency function for table ${s}`,b}})}static setResidencyById(_){Ce.getResidencyById=_&&(S=>{try{return _(S)}catch(A){throw A.message+=` in residency function for table ${s}`,A}})}static getResidency(_,S){if(Ce.getResidencyById)return Ce.getResidencyById(_[t]);let A=mm;if(S.replicateTo!=null){if(Array.isArray(S.replicateTo))return S.replicateTo.includes(server.hostname)?S.replicateTo:[server.hostname,...S.replicateTo];S.replicateTo>=0&&(A=S.replicateTo)}if(A>=0&&server.nodes){let b=[server.hostname];if(S.previousResidency)b.push(...S.previousResidency.slice(0,A));else{let I=server.nodes.map(L=>L.name),P=Math.floor(I.length*Math.random());b.push(...I.slice(P,P+A));let D=P+A-I.length;D>0&&b.push(...I.slice(0,D))}return b}}static enableAuditing(_=!0){g=_,_&&gm(),Ce.audit=_}static coerceId(_){return _===""?null:eA(_,F)}static async dropTable(){delete He[c][s];for(let _ of i.getRange({versions:!0,snapshot:!1,lazy:!0}))_.metadataFlags&Yr&&_.value&&Va(_.value);if(c===a){for(let _ of T)d.remove(Ce.tableName+"/"+_.name),r[_.name]?.drop();d.remove(Ce.tableName+"/"),i.drop(),await d.committed}else console.log("legacy dropTable"),await i.close(),DM.default.unlinkSync(i.env.path);$_.signalSchemaChange(new V_.SchemaEventMsg(process.pid,G.DROP_TABLE,c,s))}get(_){let S=this.constructor;if(typeof _=="string"&&S.loadAsInstance!==!1)return this.getProperty(_);if(Em(_))return this.search(_);if(_&&_.id===void 0&&!_.toString()){let A={records:"./",name:s,database:c,auditSize:l?.getStats().entryCount,attributes:T,recordCount:void 0,estimatedRecordRange:void 0};return this.getContext()?.includeExpensiveRecordCountEstimates?Ce.getRecordCount().then(b=>(A.recordCount=b.recordCount,A.estimatedRecordRange=b.estimatedRange,A)):A}if(_!==void 0&&S.loadAsInstance===!1){let A=this.getContext(),b=Mr(A),I=b.getReadTxn();if(I?.isDone)throw new Error("You can not read from a transaction that has already been committed/aborted");let P=Ar(_);Lr(P);let D=!0;return _.checkPermission&&(D=this.allowRead(A.user,_)),ii(ii(D,L=>{if(!L)throw new ct.AccessViolation(A.user);let k=!0;return va(P,A,{transaction:I,ensureLoaded:k},!1,C=>{if(A.onlyIfCached){if(!C?.value)throw new ct.ServerError("Entry is not cached",504)}else if(k){let x=tl(P,C,A);if(x)return b?.disregardReadTxn(),A.loadedFromSource=!0,x.then(z=>z?.value)}return C?.value})}),L=>{let k=_?.select;return k&&L!=null?Zf(k,this.constructor)(L):L})}if(_?.property)return this.getProperty(_.property);if(this.doesExist()||_?.ensureLoaded===!1||this.getContext()?.returnNonexistent)return this}allowRead(_,S){let A=Ua(_,S);if(A?.read){if(A.isSuperUser)return!0;let b=A.attribute_permissions,I=S?.select;if(b?.length>0||Zc&&I){if(S||(S={}),I){let P=Array.isArray(I)?I:[I],D=b?.length>0&&PM(b,"read");S.select=P.map(L=>{let k=L.name||L;if(!D||D[k]){let C=_t[k]?.definition?.tableClass;if(C){if(L.name||(L={name:L}),!L.checkPermission&&S.checkPermission&&(L.checkPermission=S.checkPermission),!C.prototype.allowRead.call(null,_,L))return!1;if(!L.select)return L.name}return L}}).filter(Boolean)}else S.select=b.filter(P=>P.read&&!_t[P.attribute_name]).map(P=>P.attribute_name);return S}else return!0}}allowUpdate(_,S,A){let b=Ua(_,A);if(b?.update){let I=b.attribute_permissions;if(I?.length>0){let P=PM(I,"update");for(let D in S)if(!P[D])return!1;for(let D of I){let L=D.attribute_name;!D.update&&!(L in S)&&(S[L]=this.getProperty(L))}}return Ba(this.getContext())}}allowCreate(_,S,A){if(this.isCollection){let b=Ua(_,A);if(b?.insert){let I=b.attribute_permissions;if(I?.length>0){let P=PM(I,"insert");for(let D in S)if(!P[D])return!1;return Ba(this.getContext())}else return Ba(this.getContext())}}else return this.allowUpdate(_,{})}allowDelete(_,S){return Ua(_,S)?.delete&&Ba(this.getContext())}update(_,S){let A,b=typeof S=="boolean"||S===void 0&&(_==null||typeof _=="object"&&!(_ instanceof URLSearchParams)),I=!1;b?(I=S,S=_,A=this.getId()):A=Ar(_);let P=this.getContext();if(!Mr(P))throw new Error("Can not update a table resource outside of a transaction");if(S===!1)return this;if(typeof S=="object"&&S)if(I)Object.isFrozen(S)&&(S={...S}),this.#e={},this.#t=S;else if(b){let L=this.#t;L&&(S=Object.assign(L,S)),this.#t=S}else{let L=!0;if(_==null)throw new TypeError("Can not put a record without a target");return _.checkPermission&&(L=this.allowUpdate(P.user,S,_)),ii(L,k=>{if(!k)throw new ct.AccessViolation(P.user);return ii(i.get(Ar(_)),C=>{let x=new pm(C);return x._setChanges(S),this._writeUpdate(A,x.getChanges(),!1),x})})}return this._writeUpdate(A,this.#t,I),this}addTo(_,S){if(typeof S=="number"||typeof S=="bigint")this.#s===V4?this.set(_,(+this.getProperty(_)||0)+S):(this.#s||this.update(),this.set(_,new Ih(S)));else throw new Error("Can not add a non-numeric value")}subtractFrom(_,S){if(typeof S=="number")return this.addTo(_,-S);throw new Error("Can not subtract a non-numeric value")}getMetadata(){return this.#n}getRecord(){return this.#e}getChanges(){return this.#t}_setChanges(_){this.#t=_}setRecord(_){this.#e=_}invalidate(_){let S=!0,A=this.getContext();return _?.checkPermission&&(S=this.allowDelete(A.user,_,A)),ii(S,b=>{if(!b)throw new ct.AccessViolation(A.user);this._writeInvalidate(_?Ar(_):this.getId())})}_writeInvalidate(_,S,A){let b=this.getContext();Lr(_),Mr(this.getContext()).addWrite({key:_,store:i,invalidated:!0,entry:this.#n,before:De.invalidate?.bind(this,b,_),beforeIntermediate:Ha(S,Me.invalidate?.bind(this,b,_)),commit:o((P,D)=>{if(!(xa(P,D,A?.nodeId)<=0)){S??=null;for(let L in r)S||(S={}),S[L]===void 0&&(S[L]=this.getProperty(L));Ue.default.trace?.(`Invalidating entry in ${s} id: ${_}, timestamp: ${new Date(P).toISOString()}`),y(_,S,D,P,Wn,g,{user:b?.user,residencyId:A?.residencyId,nodeId:A?.nodeId},"invalidate")}},"commit")})}_writeRelocate(_,S){let A=this.getContext();Lr(_),Mr(this.getContext()).addWrite({key:_,store:i,invalidated:!0,entry:this.#n,before:De.relocate?.bind(this,A,_),beforeIntermediate:Me.relocate?.bind(this,A,_),commit:o((I,P)=>{if(xa(I,P,S?.nodeId)<=0)return;let D=Ce.getResidencyRecord(S.residencyId),L=0,k=null,C=P?.value;if(D&&!D.includes(server.hostname)){for(let x in r)k||(k={}),k[x]=C[x];L=Wn}else k=C;Ue.default.trace?.(`Relocating entry id: ${_}, timestamp: ${new Date(I).toISOString()}`),y(_,k,P,I,L,g,{user:A.user,residencyId:S.residencyId,nodeId:S.nodeId,expiresAt:S.expiresAt},"relocate",!1,null)},"commit")})}static _recordRelocate(_,S){if(this.getResidencyById)return!1;let A={previousResidency:this.getResidencyRecord(_.residencyId),isRelocation:!0},b=rl(this.getResidency(S.value,A)),I;if(b){if(!b.includes(server.hostname))return!1;I=nl(b)}let P=0;Ue.default.debug?.("Performing a relocate of an entry",_.key,S.value,b);let D=y(_.key,S.value,_,_.version,P,!0,{residencyId:I,expiresAt:S.expiresAt},"relocate",!1,null);return!0}static evict(_,S,A){let b=this.Source,I;if(!((O||g)&&(!S||(I=i.getEntry(_),!I||!S)||I.version!==A))){if(O){if(i.hasLock(_,I.version))return;let P;for(let D in r)P||(P={}),P[D]=S[D];if(P)return y(_,P,I,A,Du,null,null,null,!0)}return i.ifVersion(_,A,()=>{Po(_,S,null)}),Pu(i,I??i.getEntry(_),A)}}lock(){throw new Error("Not yet implemented")}static operation(_,S){return _.table||=s,_.schema||=c,global.operation(_,S)}put(_,S){if(S===void 0||S instanceof URLSearchParams)this.update(_,!0);else{let A=!0;if(_==null)throw new TypeError("Can not put a record without a target");let b=this.getContext();return _.checkPermission&&(A=this.allowUpdate(b.user,S,_)),ii(A,I=>{if(!I)throw new ct.AccessViolation(b.user);if(Array.isArray(S))for(let P of S){let D=P[t];this._writeUpdate(D,P,!0)}else{let P=Ar(_);this._writeUpdate(P,S,!0)}})}}create(_,S){let A=!0,b=this.getContext();if(!S&&!(_ instanceof URLSearchParams)&&(S=_,_=void 0),!S||typeof S!="object"||Array.isArray(S))throw new TypeError("Can not create a record without an object");return _?.checkPermission&&(A=this.allowCreate(b.user,S,_)),ii(A,I=>{if(!I)throw new ct.AccessViolation(b.user);let P=Ar(_)??S[t];if(P===void 0)P=this.constructor.getNewId();else if(i.get(P))throw new ct.ClientError("Record already exists",409);return this._writeUpdate(P,S,!0),S})}patch(_,S){if(S===void 0||S instanceof URLSearchParams)this.update(_,!1);else{let A=this.update(_,S);if(A?.then)return A.then(()=>{})}}_writeUpdate(_,S,A,b){let I=this.getContext(),P=Mr(I);Lr(_);let D=this.#n??i.getEntry(_);this.#s=A?V4:TIe;let L=o(C=>A?C.put?()=>C.put(I,_,S):null:C.patch?()=>C.patch(I,_,S):C.put?()=>C.put(I,_,Dl(this)):null,"writeToSources"),k={key:_,store:i,entry:D,nodeName:I?.nodeName,validate:o(C=>{S||(S=this.#t),A||S&&Pg(this.#t===S?this:S)?I?.source||(P.checkOverloaded(),this.validate(S,!A),Y&&(S[Y.name]=Y.type==="Date"?new Date(C):Y.type==="String"?new Date(C).toISOString():C),A&&(t&&S[t]!==_&&(S[t]=_),q&&(D?.value?S[q.name]=D?.value[q.name]:S[q.name]=q.type==="Date"?new Date(C):q.type==="String"?new Date(C).toISOString():C),S=Dl(S))):P.removeWrite(k)},"validate"),before:L(De),beforeIntermediate:Ha(S,L(Me)),commit:o((C,x,z)=>{if(z){if(I&&x?.version>(I.lastModified||0)&&(I.lastModified=x.version),this.#n=x,x?.value&&x.value.getRecord)throw new Error("Can not assign a record to a record, check for circular references");A||(this.#e=x?.value??null)}this.#t=void 0,this.#r=C;let ne=x?.value,re=S;this.#s=0;let B=!1,de=xa(C,x,b?.nodeId),he,Se=A?"put":"patch",ee;b?.residencyId!=null&&(ee=b.residencyId);let J=I?.expiresAt??(p?p+Date.now():-1);if(de<=0){if(g){let fe=x.localTime,We=x.version;Ue.default.trace?.("Applying CRDT update to record with id: ",_,"txn time",new Date(C),"applying later update from:",new Date(We),"local recorded time",new Date(fe));let Rt=[];for(;fe>C||We>=C&&fe>0;){let mt=l.get(fe);if(!mt)break;let _e=wt(mt);if(We=_e.version,We>=C){if(We===C){if(de=xa(C,{version:We,localTime:fe},b?.nodeId),de===0)return Te(!1);if(de>0)continue}if(_e.type==="patch")Rt.push(_e),he=S;else if(_e.type==="put"||_e.type==="delete")return Te(!1)}fe=_e.previousLocalTime}fe||Ue.default.debug?.("No further audit history, applying incremental updates based on available history",_,"existing version preserved",x),Rt.sort((mt,_e)=>mt.version-_e.version);for(let mt of Rt){let _e=mt.getValue(i);if(Ue.default.debug?.("Rebuilding update with future patch:",new Date(mt.version),_e,mt),re=Og(re,_e,A),!re)return Te(!1)}}else{if(A)return Te(!1);re=Og(re,ne,A),Ue.default.debug?.("Rebuilding update without audit:",re)}Ue.default.trace?.("Rebuilt record to save:",re," is full update:",A)}let pe;if(A?pe=re:this.constructor.loadAsInstance===!1?pe=Dl(ne,re):(this.#e=ne,pe=Dl(this,re)),this.#e=pe,pe&&pe.getRecord)throw new Error("Can not assign a record to a record, check for circular references");if(ee==null){D?.residencyId&&(I.previousResidency=Ce.getResidencyRecord(D.residencyId));let fe=rl(Ce.getResidency(pe,I));if(fe&&!fe.includes(server.hostname))if(he??=pe,B=!0,Ce.getResidencyById)pe=void 0;else{pe=null;for(let We in r)pe||(pe={}),pe[We]=he[We]}ee=nl(fe)}A||(he=S),Ue.default.trace?.(`Saving record with id: ${_}, timestamp: ${new Date(C).toISOString()}${J?", expires at: "+new Date(J).toISOString():""}${x?", replaces entry from: "+new Date(x.version).toISOString():", new entry"}`,(()=>{try{return JSON.stringify(pe).slice(0,100)}catch{return""}})()),Po(_,ne,pe),Te(!0),I.expiresAt&&Fa();function Te(fe){y(_,fe?pe:void 0,fe?x:{...x,value:void 0},C,B?Wn:0,g,{omitLocalRecord:B,user:I?.user,residencyId:ee,expiresAt:J,nodeId:b?.nodeId,originatingOperation:I?.originatingOperation},Se,!1,fe?he:he??S)}o(Te,"writeCommit")},"commit")};P.addWrite(k)}async delete(_){if(Em(_)){_.select=["$id"];for await(let S of this.search(_))this._writeDelete(S.$id);return!0}if(_){let S=!0,A=this.getContext();return _.checkPermission&&(S=this.allowDelete(A.user,_,A)),ii(S,b=>{if(!b)throw new ct.AccessViolation(A.user);let I=Ar(_);return this._writeDelete(I),!0})}return this._writeDelete(this.getId()),!!this.#e}_writeDelete(_,S){let A=Mr(this.getContext());Lr(_);let b=this.getContext();return A.addWrite({key:_,store:i,entry:this.#n,nodeName:b?.nodeName,before:De.delete?.bind(this,b,_),beforeIntermediate:Me.delete?.bind(this,b,_),commit:o((I,P,D)=>{let L=P?.value;D&&(b&&P?.version>(b.lastModified||0)&&(b.lastModified=P.version),Ce._updateResource(this,P)),!(xa(I,P,S?.nodeId)<=0)&&(Po(this.getId(),L),Ue.default.trace?.(`Deleting record with id: ${_}, txn timestamp: ${new Date(I).toISOString()}`),g||R?(y(_,null,P,I,0,g,{user:b?.user,nodeId:S?.nodeId},"delete"),g||Fa()):Pu(i,P))},"commit")}),!0}search(_){let S=this.getContext(),A=Mr(S);if(!_)throw new Error("No query provided");if(_.parseError)throw _.parseError;if(_.checkPermission&&!this.allowRead(S.user,_))throw new ct.AccessViolation(S.user);let b=_.conditions;b?b.length===void 0&&(b=b[Symbol.iterator]?Array.from(b):[b]):b=Array.isArray(_)?_:_[Symbol.iterator]?Array.from(_):[];let I=_.id??this.getId();I&&(b=[{attribute:null,comparator:Array.isArray(I)?"prefix":"starts_with",value:I}].concat(b));let P,D={};function L(J,pe){let Te;switch(pe){case"and":case void 0:if(J.length<1)throw new Error('An "and" operator requires at least one condition');Te=!0;break;case"or":if(J.length<2)throw new Error('An "or" operator requires at least two conditions');break;default:throw new Error("Invalid operator "+pe)}for(let fe of J){if(fe.conditions){fe.conditions=L(fe.conditions,fe.operator);continue}let We=fe[0]??fe.attribute,Rt=We==null?F:Io(T,We);if(Rt)(Rt.type||NM[fe.comparator])&&(fe[1]===void 0?fe.value=C(fe.value,Rt):fe[1]=C(fe[1],Rt));else if(We!=null&&!_.allowConditionsOnDynamicAttributes)throw(0,ct.handleHDBError)(new Error,`${We} is not a defined attribute`,404);if(fe.chainedConditions)if(fe.chainedConditions.length===1&&(!fe.operator||fe.operator=="and")){let mt=fe.chainedConditions[0],_e,Et;if(mt.comparator==="gt"||mt.comparator==="greater_than"||mt.comparator==="ge"||mt.comparator==="greater_than_equal"?(_e=fe,Et=mt):(_e=mt,Et=fe),_e.comparator!=="lt"&&_e.comparator!=="less_than"&&_e.comparator!=="le"&&_e.comparator!=="less_than_equal")throw new Error("Invalid chained condition, only less than and greater than conditions can be chained together");let tt=Et.comparator==="ge"||Et.comparator==="greater_than_equal",dr=_e.comparator==="le"||_e.comparator==="less_than_equal";fe.comparator=(tt?"ge":"gt")+(dr?"le":"lt"),fe.value=[Et.value,_e.value]}else throw new Error("Multiple chained conditions are not currently supported")}return J}o(L,"prepareConditions");function k(J,pe){if(_.enforceExecutionOrder)return J;for(let Te of J)Te.conditions&&(Te.conditions=k(Te.conditions,Te.operator));return J.length>1&&pe!=="or"?hIe(J,Qy(Ce)):J}o(k,"orderConditions");function C(J,pe){return Array.isArray(J)?J.map(Te=>eA(Te,pe)):eA(J,pe)}o(C,"coerceTypedValues");let x=_.operator;(b.length>0||x)&&(b=L(b,x));let z=typeof _.sort=="object"&&_.sort,ne;if(z&&x!=="or"){let J=z.attribute;if(J==null)throw new ct.ClientError("Sort requires an attribute");if(P=b.find(pe=>Jf(pe.attribute)===Jf(J)),!P){let pe=Io(T,J);if(!pe)throw(0,ct.handleHDBError)(new Error,`${Array.isArray(J)?J.join("."):J} is not a defined attribute`,404);if(pe.indexed)P={...z,comparator:"sort"},b.push(P);else if(b.length===0&&!_.allowFullScan)throw(0,ct.handleHDBError)(new Error,`${Array.isArray(J)?J.join("."):J} is not indexed and not combined with any other conditions`,404)}P&&(P.descending=!!z.descending)}b=k(b,x),z&&(P&&b[0]===P?z.next&&(ne={dbOrderedAttribute:z.attribute,attribute:z.next.attribute,descending:z.next.descending,next:z.next.next}):(P&&b.splice(b.indexOf(P),1),ne=z));let re=_.select;if(b.length===0&&(b=[{attribute:t,comparator:"greater_than",value:!0}]),_.explain)return{conditions:b,operator:x,postOrdering:ne,selectApplied:!!re};let B=A.useReadTxn(),de=wM(b,x,Ce,B,_,S,(J,pe)=>Gu(J,re,S,B,pe),D),he=_.ensureLoaded!==!1,Se=Ce.transformEntryForSelect(re,S,B,D,he,!0),ee=Ce.transformToOrderedSelect(de,re,ne,S,B,Se);return(_.offset||_.limit!==void 0)&&(ee=ee.slice(_.offset,_.limit!==void 0?(_.offset||0)+_.limit:void 0)),ee.onDone=()=>{ee.onDone=null,A.doneReadTxn()},ee.selectApplied=!0,ee.getColumns=()=>{if(re){let J=[];for(let pe of re)pe==="*"?J.push(...T.map(Te=>Te.name)):J.push(pe.name||pe);return J}return T.filter(J=>!J.computed&&!J.relationship).map(J=>J.name)},ee}static transformToOrderedSelect(_,S,A,b,I,P){let D=new lE;if(A){_=Gu(_,S,b,I,null);let L;D.iterate=function(){let C,x=_[Symbol.asyncIterator]?_[Symbol.asyncIterator]():_[Symbol.iterator](),z,ne=A.dbOrderedAttribute,re,B,de=!0;function he(ee){let J=ee.next&&he(ee.next),pe=ee.descending;return b.sort=ee,(Te,fe)=>{let We=qu(Te,ee.attribute,b),Rt=qu(fe,ee.attribute,b),mt=pe?(0,Uu.compareKeys)(Rt,We):(0,Uu.compareKeys)(We,Rt);return mt===0?J?.(Te,fe)||0:mt}}o(he,"createComparator");let Se=he(A);return{async next(){let ee;if(C)if(ee=C.next(),ee.done){if(z)return D.onDone&&D.onDone(),ee}else return{value:await P.call(this,ee.value)};L=[],re&&L.push(re);do if(ee=await x.next(),ee.done){if(z=!0,L.length)break;return D.onDone&&D.onDone(),ee}else{let J=ee.value;if(J?.then&&(J=await J),ne){let pe=qu(J,ne,b);if(de)de=!1,B=pe;else if(pe!==B){B=pe,re=J;break}}L.push(J)}while(!0);return A.isGrouped,L.sort(Se),C=L[Symbol.iterator](),ee=C.next(),ee.done?(D.onDone&&D.onDone(),ee):{value:await P.call(this,ee.value)}},return(){D.onDone&&D.onDone(),x.return()},throw(){D.onDone&&D.onDone(),x.throw()}}};let k=o(C=>{if(typeof S=="object"&&Array.isArray(C.attribute))for(let x=0;x<S.length;x++){let z=S[x],ne;if(z.name===C.attribute[0]){for(ne=z.sort||(z.sort={});ne.next;)ne=ne.next;ne.attribute=C.attribute.slice(1),ne.descending=C.descending}else z===C.attribute[0]&&(S[x]=ne={name:z,sort:{attribute:C.attribute.slice(1),descending:C.descending}})}C.next&&k(C.next)},"applySortingOnSelect");k(A)}else D.iterate=(_[Symbol.asyncIterator]||_[Symbol.iterator]).bind(_),D=D.map(function(L){try{let k=P.call(this,L);return typeof k?.catch=="function"?k.catch(C=>{throw C.partialObject={[t]:L.key},C}):k}catch(k){throw k.partialObject={[t]:L.key},k}});return D}static transformEntryForSelect(_,S,A,b,I,P){let D;I&&O&&!(typeof _=="string"?[_]:_)?.every(C=>{let x;return typeof C=="object"?x=C.name:x=C,r[x]||x===t})&&(D=!0);let L,k=o(function(C){let x;if(S?.transaction?.stale&&(S.transaction.stale=!1),C!=null){if(x=C.deref?C.deref():C.value,!x&&(C.key===void 0||C.deref)||C.metadataFlags&Wn){if(C.metadataFlags&Wn&&S.replicateFrom===!1&&P&&C.residencyId)return Yc.SKIP;if(C=va(C.key??C,S,{transaction:A,lazy:_?.length<4,ensureLoaded:I},this?.isSync,z=>z),C?.then)return C.then(k.bind(this));x=C?.value}if(D&&C?.metadataFlags&(Wn|Du)||C?.expiresAt!=null&&C?.expiresAt<Date.now()){if(S.onlyIfCached)return{[t]:C.key,message:"This entry has expired"};let z=tl(C.key??C,C,S);if(z?.then)return z.then(k)}}if(x==null)return P?Yc.SKIP:x;if(_&&!(_[0]==="*"&&_.length===1)){let z,ne=o((B,de)=>{let he;typeof B=="object"?he=B.name:he=B;let Se=_t?.[he],ee;if(Se){let J=b?.[he];if(J)if(J.hasMappings){let Te=Se.from?x[Se.from]:Jf(C.key);ee=J.get(Te),ee||(ee=[])}else ee=J.fromRecord?.(x);else ee=Se(x,S,C,!0);let pe=o(Te=>{if(Se.directReturn)return de(Te,he);if(Te&&typeof Te=="object"){let fe=Se.definition?.tableClass||Ce;L||(L={});let We=L[he]||(L[he]=fe.transformEntryForSelect(he===B?null:B.select||(Array.isArray(B)?B:null),S,A,J,I));if(Array.isArray(Te)){let Rt=[],mt=fe.transformToOrderedSelect(Te,B.select,typeof B.sort=="object"&&B.sort,S,A,We)[this.isSync?Symbol.iterator:Symbol.asyncIterator](),_e=o(tt=>{for(;!tt.done;){if(tt?.then)return tt.then(_e);Rt.push(tt.value),tt=mt.next()}de(Rt,he)},"nextValue"),Et=_e(mt.next());Et&&(z||(z=[]),z.push(Et));return}else if(Te=We.call(this,Te),Te?.then){z||(z=[]),z.push(Te.then(Rt=>de(Rt,he)));return}}de(Te,he)},"handleResolvedValue");ee?.then?(z||(z=[]),z.push(ee.then(pe))):pe(ee);return}else ee=x[he],ee&&typeof ee=="object"&&he!==B&&(ee=Ce.transformEntryForSelect(B.select||B,S,A,null)({value:ee}));de(ee,he)},"selectAttribute"),re;if(typeof _=="string")ne(_,B=>{re=B});else if(Array.isArray(_))if(_.asArray)re=[],_.forEach((B,de)=>{B==="*"?_[de]=x:ne(B,he=>re[de]=he)});else{re={};let B=_.forceNulls;for(let de of _)if(de==="*")for(let he in x)re[he]=x[he];else ne(de,(he,Se)=>{he===void 0&&B&&(he=null),re[Se]=he})}else throw new ct.ClientError("Invalid select"+_);return z?Promise.all(z).then(()=>re):re}return x},"transform");return k}async subscribe(_){if(!l)throw new Error("Can not subscribe to a table without an audit log");g||ze({table:s,database:c,schemaDefined:u,attributes:T,audit:!0}),_||(_={});let S=!_.rawEvents,A=[],b=this,I=$w(Ce,this.getId()??null,function(D,L,k,C){try{let x=L.getValue?.(i,S),z=L.type;if(!x&&z==="patch"&&S){let re=i.getEntry(D);re?.version===L.version?x=re.value:x=L.getValue?.(i,!0,k),z="put"}let ne={id:D,localTime:k,value:x,version:L.version,type:z,beginTxn:C};A?A.push(ne):this.send(ne)}catch(x){Ue.default.error?.(x)}},_.startTime||0,_),P=(async()=>{this.isCollection&&(I.includeDescendants=!0,_.onlyChildren&&(I.onlyChildren=!0)),_.supportsTransactions&&(I.supportsTransactions=!0);let D=this.getId(),L=_.previousCount;L>1e3&&(L=1e3);let k=_.startTime;if(this.isCollection){if(k){if(L)throw new ct.ClientError("startTime and previousCount can not be combined for a table level subscription");for(let{key:C,value:x}of l.getRange({start:k,exclusiveStart:!0,snapshot:!1})){let z=wt(x);if(z.tableId!==n)continue;let ne=z.recordId;if(D==null||z4(D,ne)){let re=z.getValue(i,S,C);if(I.send({id:ne,localTime:C,value:re,version:z.version,type:z.type}),I.queue?.length>Y4&&await I.waitForDrain()===!1)return}I.startTime=C}}else if(L){let C=[];for(let{key:x,value:z}of l.getRange({start:"z",end:!1,reverse:!0}))try{let ne=wt(z);if(ne.tableId!==n)continue;let re=ne.recordId;if(D==null||z4(D,re)){let B=ne.getValue(i,S,x);if(C.push({id:re,localTime:x,value:B,version:ne.version,type:ne.type}),--L<=0)break}}catch(ne){Ue.default.error("Error getting history entry",x,ne)}for(let x=C.length;x>0;)I.send(C[--x]);C[0]&&(I.startTime=C[0].localTime)}else if(!_.omitCurrent){for(let{key:C,value:x,version:z,localTime:ne}of i.getRange({start:D??!1,end:D==null?void 0:[D,Uu.MAXIMUM_KEY],versions:!0,snapshot:!1}))if(x&&(I.send({id:C,localTime:ne,value:x,version:z,type:"put"}),I.queue?.length>Y4&&await I.waitForDrain()===!1))return}}else{L&&!k&&(k=0);let C=this.#n?.localTime;if(C===AM&&(i.cache?.delete(D),this.#n=i.getEntry(D),Ue.default.trace?.("re-retrieved record",C,this.#n?.localTime),C=this.#n?.localTime),Ue.default.trace?.("Subscription from",k,"from",D,C),k<C){let x=[],z=C;do{let ne=l.get(z);if(ne){_.omitCurrent=!0;let re=wt(ne),B=re.getValue(i,S,z);S&&(re.type="put"),x.push({id:D,value:B,localTime:z,...re}),z=re.previousLocalTime}else break;L&&L--}while(z>k&&L!==0);for(let ne=x.length;ne>0;)I.send(x[--ne]);I.startTime=C}!_.omitCurrent&&this.doesExist()&&I.send({id:D,localTime:C,value:this.#e,version:this.#r,type:"put"})}for(let C of A)I.send(C);A=null})();return _.listener&&I.on("data",_.listener),I}static subscribeOnThisThread(_,S){return _===0||S?.crossThreads===!1}doesExist(){return!!(this.#e||this.#s)}publish(_,S,A){if(S===void 0||S instanceof URLSearchParams)this._writePublish(this.getId(),_,S);else{let b=!0,I=this.getContext();return _.checkPermission&&(b=this.allowCreate(I.user,_,I)),ii(b,P=>{if(!P)throw new ct.AccessViolation(I.user);let D=Ar(_);this._writePublish(D,S,A)})}}_writePublish(_,S,A){let b=Mr(this.getContext());_??=null,_!==null&&Lr(_);let I=this.getContext();b.addWrite({key:_,store:i,entry:this.#n,nodeName:I?.nodeName,validate:o(()=>{I?.source||(b.checkOverloaded(),this.validate(S))},"validate"),before:De.publish?.bind(this,I,_,S),beforeIntermediate:Ha(S,Me.publish?.bind(this,I,_,S)),commit:o((P,D,L)=>{D===void 0&&R&&!g&&Fa(),Ue.default.trace?.(`Publishing message to id: ${_}, timestamp: ${new Date(P).toISOString()}`),y(_,D?.value??null,D,D?.version||P,0,!0,{user:I?.user,residencyId:A?.residencyId,expiresAt:I?.expiresAt,nodeId:A?.nodeId},"message",!1,S)},"commit")})}validate(_,S){let A,b=o((I,P,D)=>{if(P.type&&I!=null)if(S&&I.__op__&&(I=I.value),P.properties){typeof I!="object"&&(A||(A=[])).push(`Value ${oi(I)} in property ${D} must be an object${P.type?" ("+P.type+")":""}`);let L=P.properties;for(let k=0,C=L.length;k<C;k++){let x=L[k];if(x.relationship||x.computed){_.hasOwnProperty(x.name)&&(A||(A=[])).push(`Computed property ${D}.${x.name} may not be directly assigned a value`);continue}let z=b(I[x.name],x,D+"."+x.name);z&&(I[x.name]=z)}if(P.sealed&&I!=null&&typeof I=="object")for(let k in I)L.find(C=>C.name===k)||(A||(A=[])).push(`Property ${k} is not allowed within object in property ${D}`)}else switch(P.type){case"Int":(typeof I!="number"||I>>0!==I)&&(A||(A=[])).push(`Value ${oi(I)} in property ${D} must be an integer (from -2147483648 to 2147483647)`);break;case"Long":(typeof I!="number"||!(Math.floor(I)===I&&Math.abs(I)<=9007199254740992))&&(A||(A=[])).push(`Value ${oi(I)} in property ${D} must be an integer (from -9007199254740992 to 9007199254740992)`);break;case"Float":typeof I!="number"&&(A||(A=[])).push(`Value ${oi(I)} in property ${D} must be a number`);break;case"ID":typeof I=="string"||I?.length>0&&I.every?.(L=>typeof L=="string")||(A||(A=[])).push(`Value ${oi(I)} in property ${D} must be a string, or an array of strings`);break;case"String":typeof I!="string"&&(A||(A=[])).push(`Value ${oi(I)} in property ${D} must be a string`);break;case"Boolean":typeof I!="boolean"&&(A||(A=[])).push(`Value ${oi(I)} in property ${D} must be a boolean`);break;case"Date":if(!(I instanceof Date)){if(typeof I=="string"||typeof I=="number")return new Date(I);(A||(A=[])).push(`Value ${oi(I)} in property ${D} must be a Date`)}break;case"BigInt":if(typeof I!="bigint"){if(typeof I=="string"||typeof I=="number")return BigInt(I);(A||(A=[])).push(`Value ${oi(I)} in property ${D} must be a bigint`)}break;case"Bytes":if(!(I instanceof Uint8Array)){if(typeof I=="string")return Buffer.from(I);(A||(A=[])).push(`Value ${oi(I)} in property ${D} must be a Buffer or Uint8Array`)}break;case"Blob":if(!(I instanceof Ds)){if(typeof I=="string"&&(I=Buffer.from(I)),I instanceof Buffer)return createBlob(I,{type:"text/plain"});(A||(A=[])).push(`Value ${oi(I)} in property ${D} must be a Blob`)}break;case"array":if(Array.isArray(I)){if(P.elements)for(let L=0,k=I.length;L<k;L++){let C=I[L],x=b(C,P.elements,D+"[*]");x&&(I[L]=x)}}else(A||(A=[])).push(`Value ${oi(I)} in property ${D} must be an Array`);break}P.nullable===!1&&I==null&&(A||(A=[])).push(`Property ${D} is required (and not does not allow null values)`)},"validateValue");for(let I=0,P=T.length;I<P;I++){let D=T[I];if(D.relationship||D.computed){Object.hasOwn(_,D.name)&&(A||(A=[])).push(`Computed property ${D.name} may not be directly assigned a value`);continue}if(!S||D.name in _){let L=b(_[D.name],D,D.name);L!==void 0&&(_[D.name]=L)}}if(f)for(let I in _)T.find(P=>P.name===I)||(A||(A=[])).push(`Property ${I} is not allowed`);if(A)throw new ct.ClientError(A.join(". "))}getUpdatedTime(){return this.#r}wasLoadedFromSource(){return O?!!this.#i:void 0}static async addAttributes(_){let S=T.slice(0);for(let A of _){if(!A.name)throw new ct.ClientError("Attribute name is required");if(A.name.match(/[`/]/))throw new ct.ClientError("Attribute names cannot include backticks or forward slashes");pIe(A.name),S.push(A)}return ze({table:s,database:c,schemaDefined:u,attributes:S}),Ce.indexingOperation}static async removeAttributes(_){let S=T.filter(A=>!_.includes(A.name));return ze({table:s,database:c,schemaDefined:u,attributes:S}),Ce.indexingOperation}static getSize(){let _=i.getStats();return(_.treeBranchPageCount+_.treeLeafPageCount+_.overflowPages)*_.pageSize}static getAuditSize(){let _=l?.getStats();return _&&(_.treeBranchPageCount+_.treeLeafPageCount+_.overflowPages)*_.pageSize}static getStorageStats(){let _=i.env.path,S=DM.default.statfsSync?.(_)??{};return{available:S.bavail*S.bsize,free:S.bfree*S.bsize,size:S.blocks*S.bsize}}static async getRecordCount(_){let S=i.getStats().entryCount,A=1e3/2,b=performance.now(),I=Math.floor(S/2),P=_?.exactCount,D=0,L=0,k;for(let{value:C}of i.getRange({start:!0,lazy:!0,snapshot:!1}))if(C!=null&&D++,L++,await Kc(),!P&&L<I&&performance.now()-b>A){k=L;break}if(k){let C=D;D=0;for(let{value:ee}of i.getRange({start:"\uFFFF",reverse:!0,lazy:!0,limit:k,snapshot:!1}))ee!=null&&D++,await Kc();let x=k*2,z=(D+C)/x,ne=Math.pow((D-C+1)/k/2,2)+z*(1-z)/x,re=Math.max(Math.sqrt(ne)*S,1),B=Math.round(z*S),de=Math.max(B-1.96*re,D+C),he=Math.min(B+1.96*re,S),Se=Math.pow(10,Math.round(Math.log10(re)));return Se>B&&(Se=Se/10),D=Math.round(B/Se)*Se,{recordCount:D,estimatedRange:[Math.round(de),Math.round(he)]}}return{recordCount:D}}static updatedAttributes(){_t=this.propertyResolvers={$id:o((_,S,A)=>({value:A.key}),"$id"),$updatedtime:o((_,S,A)=>A.version,"$updatedtime"),$updatedTime:o((_,S,A)=>A.version,"$updatedTime"),$expiresAt:o((_,S,A)=>A.expiresAt,"$expiresAt"),$record:o((_,S,A)=>A?{value:_}:_,"$record"),$distance:o((_,S,A)=>A&&(A.distance??S?.vectorDistances?.get(A)),"$distance")};for(let _ of this.attributes){_.isPrimaryKey&&(F=_),_.resolve=null;let S=_.relationship,A=_.computed;if(S)if(_.indexed&&console.error("A relationship property can not be directly indexed, (but you may want to index the foreign key attribute)"),A&&console.error("A relationship property is already computed and can not be combined with a computed function (the relationship will be given precedence)"),Zc=!0,S.to)_.elements?.definition?(_t[_.name]=_.resolve=(b,I,P,D)=>{let L=b[S.from?S.from:t],k=_.elements.definition.tableClass;return D?jf({attribute:S.to,value:L},Mr(I).getReadTxn(),!1,k,!1).map(C=>C&&C.key!==void 0?C:k.primaryStore.getEntry(C,{transaction:Mr(I).getReadTxn()})).asArray:k.search([{attribute:S.to,value:L}],I).asArray},_.set=()=>{},_.resolve.definition=_.elements.definition,_.resolve.to=S.to,S.from&&(_.resolve.from=S.from)):console.error(`The one-to-many/many-to-many relationship property "${_.name}" in table "${s}" must have an array type referencing a table as the elements`);else if(S.from){let b=_.definition||_.elements?.definition;b?(_t[_.name]=_.resolve=(I,P,D,L)=>{let k=I[S.from];if(k===void 0)return;if(_.elements){let x,z=k?.map(ne=>{let re=b.tableClass.primaryStore[L?"getEntry":"get"](ne,{transaction:Mr(P).getReadTxn()});return re?.then&&(x=!0),Ce.loadAsInstance===!1&&Object.freeze(L?re?.value:re),re});return S.filterMissing?x?Promise.all(z).then(ne=>ne.filter(j4)):z.filter(j4):x?Promise.all(z):z}let C=b.tableClass.primaryStore[L?"getEntry":"get"](k,{transaction:Mr(P).getReadTxn()});return Ce.loadAsInstance===!1&&Object.freeze(L?C?.value:C),C},_.set=(I,P)=>{if(Array.isArray(P)){let D=P.map(L=>L.getId?.()||L[b.tableClass.primaryKey]);I[S.from]=D}else{let D=P.getId?.()||P[b.tableClass.primaryKey];I[S.from]=D}},_.resolve.definition=_.definition||_.elements?.definition,_.resolve.from=S.from):console.error(`The relationship property "${_.name}" in table "${s}" must be a type that references a table`)}else console.error(`The relationship directive on "${_.name}" in table "${s}" must use either "from" or "to" arguments`);else if(A)typeof A.from=="function"&&this.setComputedAttribute(_.name,A.from),_t[_.name]=_.resolve=(b,I,P)=>{let D=typeof A.from=="string"?b[A.from]:b,L=this.userResolvers[_.name];if(L)return L(D,I,P);Ue.default.warn(`Computed attribute "${_.name}" does not have a function assigned to it. Please use setComputedAttribute('${_.name}', resolver) to assign a resolver function.`),this.userResolvers[_.name]=()=>{}},_.resolve.directReturn=!0;else if(r[_.name]?.customIndex?.propertyResolver){let b=r[_.name].customIndex;_t[_.name]=(I,P,D)=>{let L=I[_.name];return b.propertyResolver(L,P,D)},_t[_.name].directReturn=!0}}Nh(this,this),Nh(pm,this,!0);for(let _ of T){let S=_.name;_.resolve&&Object.defineProperty(i.encoder.structPrototype,S,{get(){return _.resolve(this,Xf.getStore())},set(A){return _.set(this,A)},configurable:!0})}}static setComputedAttribute(_,S){let A=Io(T,_);if(!A){console.error(`The attribute "${_}" does not exist in the table "${s}"`);return}if(!A.computed){console.error(`The attribute "${_}" is not defined as computed in the table "${s}"`);return}this.userResolvers[_]=S}static async deleteHistory(_=0,S=!1){let A;for(let{key:b,value:I}of l.getRange({start:0,end:_}))await Kc(),wt(I).tableId===n&&(A=$y(l,b,I));if(S)for(let b of i.getRange({start:0,versions:!0})){let{key:I,value:P,localTime:D}=b;await Kc(),P===null&&D<_&&(A=Pu(i,b))}await A}static async*getHistory(_=0,S=1/0){for(let{key:A,value:b}of l.getRange({start:_||1,end:S})){await Kc();let I=wt(b);I.tableId===n&&(yield{id:I.recordId,localTime:A,version:I.version,type:I.type,value:I.getValue(i,!0,A),user:I.user,operation:I.originatingOperation})}}static async getHistoryOfRecord(_){let S=[];if(_==null)throw new Error("An id is required");let A=i.getEntry(_);if(!A)return S;let b=A.localTime;if(!b)throw new Error("The entry does not have a local audit time");let I=0;do{await Kc();let P=l.get(b);if(P){let D=wt(P);S.push({id:D.recordId,localTime:b,version:D.version,type:D.type,value:D.getValue(i,!0,b),user:D.user}),b=D.previousLocalTime}else break}while(I<1e3&&b);return S.reverse()}static cleanup(){$?.remove()}}let dE=zR(async(V,_,S)=>{for(let A of Ce.sources)if(A.get&&(!A.get.reliesOnPrototype||A.prototype.get)){if(A.available?.(S)===!1)continue;_.source=A;let b=await A.get(V,_);if(b)return b}},()=>{throw new ct.ServerError("Service unavailable, exceeded request queue limit for resolving cache record",503)});Ce.updatedAttributes();let _m=Ce.prototype;return p&&Ce.setTTLExpiration(p/1e3),K&&$u(),Ce;function Po(V,_,S){let A;for(let b in r){let I=r[b],P=I.isIndexing,D=_t[b],L=S&&(D?D(S):S[b]),k=_&&(D?D(_):_[b]);if(L===k&&!P)continue;if(I.customIndex){I.customIndex.index(V,L,k);continue}A=!0;let C=I.indexNulls,x=(0,G_.getIndexedValues)(L,C),z=(0,G_.getIndexedValues)(k,C);if(s==="OrganizationRole"&&Ue.default.error?.({tableName:s,id:V,key:b,valuesToAdd:x,valuesToRemove:z}),z?.length>0){let ne=new Set(z);if(x=x?x.filter(re=>{if(ne.has(re))ne.delete(re);else return!0}):[],z=Array.from(ne),(z.length>0||x.length>0)&&$4){let re=z.concat(x).map(B=>({key:B,value:V}));I.prefetch(re,W4)}for(let re=0,B=z.length;re<B;re++)I.remove(z[re],V)}else x?.length>0&&$4&&I.prefetch(x.map(ne=>({key:ne,value:V})),W4);if(x)for(let ne=0,re=x.length;ne<re;ne++)I.put(x[ne],V)}return A}o(Po,"updateIndices");function Lr(V){switch(typeof V){case"number":return!0;case"string":if(V.length<659)return!0;if(V.length>K4)throw new Error("Primary key size is too large: "+V.length);break;case"object":if(V===null)throw new Error("Invalid primary key of null");break;case"bigint":if(V<2n**64n&&V>-(2n**64n))return!0;break;default:throw new Error("Invalid primary key type: "+typeof V)}if((0,Uu.writeKey)(V,RIe,0)>K4)throw new Error("Primary key size is too large: "+V.length);return!0}o(Lr,"checkValidId");function Ar(V){return typeof V=="object"&&V?V.id:V}o(Ar,"requestTargetToId");function Em(V){return typeof V=="object"&&V&&V.isCollection}o(Em,"isSearchTarget");function Cs(V){}o(Cs,"isRequestTarget");function va(V,_,S,A,b){if(Ce.getResidencyById&&S.ensureLoaded&&_?.replicateFrom!==!1){let P=rl(Ce.getResidencyById(V));if(P&&!P.includes(server.hostname)&&N)return N({key:V,residency:P}).then(b)}let I=o(()=>{if(_?.transaction?.stale&&(_.transaction.stale=!1),S.transaction?.isDone)return b(null,V);let P=i.getEntry(V,S);return _?._freezeRecords&&Object.freeze(P?.value),P?.residencyId&&P.metadataFlags&Wn&&N&&S.ensureLoaded&&_?.replicateFrom!==!1?N(P).then(D=>b(D,V),D=>(Ue.default.error?.("Error loading remote record",V,P,S,D),b(null,V))):(P&&_&&(P?.version>(_.lastModified||0)&&(_.lastModified=P.version),P?.localTime&&!_.lastRefreshed&&(_.lastRefreshed=P.localTime)),b(P,V))},"whenPrefetched");return A?I():ie>0?(ie--,I()):new Promise((P,D)=>{ie===0?(ie--,i.prefetch([V],()=>{L(),k()})):(le.push(V),ue.push(k),le.length>xA&&(ie--,L()));function L(){if(le.length>0){let C=ue;i.prefetch(le,()=>{ie===-1?L():ie++;for(let x of C)x()}),le=[],ue=[],me>2&&me--}else ie=me,me<uE&&me++}o(L,"prefetch");function k(){try{P(I())}catch(C){D(C)}}o(k,"load")})}o(va,"loadLocalRecord");function Ua(V,_){let S=_?.checkPermission;if(typeof S!="object"){if(!V?.role)return;S=V.role.permission}if(S.super_user)return yIe;let A=S[c],b,I=A?.tables;if(I)return I[s];if(c==="data"&&(b=S[s])&&!b.tables)return b}o(Ua,"getTablePermissions");function tl(V,_,S,A){if(O){let b=!1;if(S.noCache?b=!0:(_?(!_.value||_.metadataFlags&(Wn|Du)||_.expiresAt!=null&&_.expiresAt<Date.now())&&(b=!0):b=!0,jr(!b,"cache-hit",s)),b){let I=fE(V,_,S).then(P=>(P?.value&&P?.value.getRecord?.()&&Ue.default.error?.("Can not assign a record that is already a resource"),S&&(P?.version>(S.lastModified||0)&&(S.lastModified=P.version),S.lastRefreshed=Date.now()),P));if(S?.onlyIfCached||_?.value&&A?.allowStaleWhileRevalidate?.(_,V)){if(I.catch(P=>Ue.default.warn?.(P)),S?.onlyIfCached&&!A.doesExist())throw new ct.ServerError("Entry is not cached",504);return}else return I}}else if(_?.value&&_.expiresAt!=null&&_.expiresAt<Date.now())return Ce.evict(_.key,_.value,_.version),_.value=null,{then(b){return b(_)}}}o(tl,"ensureLoadedFromSource");function Mr(V){let _=V?.transaction;if(_){if(!_.lmdbDb)return _.lmdbDb=i,_;do{if(_.lmdbDb?.path===i.path)return _;let S=_.next;if(!S)return _=_.next=new Lo,_.lmdbDb=i,_;_=S}while(!0)}else return new CE}o(Mr,"txnForContext");function qu(V,_,S){if(!V)return;let A=(V.deref?V.deref():V.value)??i.getEntry(V.key)?.value;if(typeof _=="object"){let I=_t,P=A;for(let D=0,L=_.length;D<L;D++){let k=_[D],C=I?.[k];P=C&&P?C(P,S,V):P?.[k],V=null,I=C?.definition?.tableClass?.propertyResolvers}return P}let b=_t[_];return b?b(A,S,V):A[_]}o(qu,"getAttributeValue");function Gu(V,_,S,A,b){let I=b?.length,P={transaction:A,lazy:I>0||typeof _=="string"||_?.length<4,alwaysPrefetch:!0},D;function L(k,C){let x=k?.value;if(!x)return Yc.SKIP;for(let z=0;z<I;z++)if(!D?.includes(z)&&!b[z](x,k))return Yc.SKIP;return C!==void 0&&(k.key=C),k}if(o(L,"processEntry"),I>0||!V.hasEntries){let k=V.map(C=>{if(D=null,typeof C=="object"&&C?.key!==void 0)return I>0?L(C):C;if(C==null)return Yc.SKIP;for(let x=0;x<I;x++){let ne=b[x].idFilter;if(ne){if(!ne(C))return Yc.SKIP;D||(D=[]),D.push(x)}}return va(C,S,P,!1,L)});return Array.isArray(V)&&(k=k.filter(C=>C!==Yc.SKIP)),k.hasEntries=!0,k}return V}o(Gu,"transformToEntries");function xa(V,_,S=server.replication?.getThisNodeId(l)){if(V<=_?.version){if(_?.version===V&&S!==void 0){let A=server.replication?.exportIdMapping(l),b=_.localTime,I=b&&l.get(b);if(I){let P,D,L=wt(I);for(let k in A)A[k]===S&&(P=k),A[k]===L.nodeId&&(D=k);if(P>D)return 1;if(P===D)return 0}}return-1}return 1}o(xa,"precedesExistingVersion");async function fE(V,_,S){let A=_?.metadataFlags,b=_?.version,I,P;if(!i.attemptLock(V,b,()=>{clearTimeout(P);let C=i.getEntry(V);!C||!C.value||C.metadataFlags&(Wn|Du)?I(fE(V,i.getEntry(V),S)):I(C)}))return new Promise(C=>{I=C,P=setTimeout(()=>{i.unlock(V,b)},SIe)});let D=_?.value,L={requestContext:S,replacingRecord:D,replacingEntry:_,replacingVersion:b,noCacheStore:!1,source:null,resourceCache:S?.resourceCache,transaction:void 0,expiresAt:void 0,lastModified:void 0},k=S?.responseHeaders;return new Promise((C,x)=>{let z;ii(Ft(L,async ne=>{let re=performance.now(),B,de,he;try{B=await dE(V,L,_),he=A&Wn;let ee=L.lastModified||he&&b;ee||(ee=(0,G_.getNextMonotonicTime)()),de=he||ee>b||!D;let J=performance.now()-re;if(it(J,"cache-resolution",s,null,"success"),k&&Mh(k,"Server-Timing",`cache-resolve;dur=${J.toFixed(2)}`,!0),ne.timestamp=ee,p&&L.expiresAt==null&&(L.expiresAt=Date.now()+p),B){if(typeof B!="object")throw new Error("Only objects can be cached and stored in tables");if(B.status>0&&B.headers)if(B.status>=300)if(B.status===304)B=D,ee=b;else throw new ct.ServerError(B.body||"Error from source",B.status);else B=B.body;typeof B.toJSON=="function"&&(B=B.toJSON()),t&&B[t]!==V&&(B[t]=V)}z=!0,C({key:V,version:ee,value:B})}catch(ee){ee.message+=` while resolving record ${V} for ${s}`,D&&((ee.code==="ECONNRESET"||ee.code==="ECONNREFUSED"||ee.code==="EAI_AGAIN")&&!S?.mustRevalidate||S?.staleIfError&&(ee.statusCode===500||ee.statusCode===502||ee.statusCode===503||ee.statusCode===504))?(C({key:V,version:b,value:D}),Ue.default.trace?.(ee.message,"(returned stale record)")):x(ee);let J=performance.now()-re;it(J,"cache-resolution",s,null,"fail"),k&&Mh(k,"Server-Timing",`cache-resolve;dur=${J.toFixed(2)}`,!0),L.transaction.abort();return}if(S?.noCacheStore||L.noCacheStore){L.transaction.abort();return}Mr(L).addWrite({key:V,store:i,entry:_,nodeName:"source",before:Ha(B),commit:o((ee,J)=>{if(J?.version!==b)return;let pe=Po(V,D,B);if(B){Me.put?.(L,V,B),J&&(S.previousResidency=Ce.getResidencyRecord(J.residencyId));let Te,fe=!1,We,Rt=rl(Ce.getResidency(B,S));if(Rt){if(!Rt.includes(server.hostname))if(Te=B,fe=!0,Ce.getResidencyById)B=void 0;else{B=null;for(let mt in r)B||(B={}),B[mt]=Te[mt]}We=nl(Rt)}Ue.default.trace?.(`Writing resolved record from source with id: ${V}, timestamp: ${new Date(ee).toISOString()}`),y(V,B,J,ee,fe?Wn:0,g&&(de||fe)||null,{user:L?.user,expiresAt:L.expiresAt,residencyId:We},"put",!!he,Te)}else J&&(Me.delete?.(L,V),Ue.default.trace?.(`Deleting resolved record from source with id: ${V}, timestamp: ${new Date(ee).toISOString()}`),g||R?y(V,null,J,ee,0,g&&de||null,{user:L?.user},"delete",!!he):Pu(i,J,b))},"commit")})}),()=>{i.unlock(V,b)},ne=>{i.unlock(V,b),z&&Ue.default.error?.("Error committing cache update",ne)})})}o(fE,"getFromSource");function Ba(V){if(!V||V.user?.role?.permission?.super_user)return!0;if(V.replicateTo)throw new ct.ClientError("Can not specify replication parameters without super user permissions",403);if(V.replicatedConfirmation)throw new ct.ClientError("Can not specify replication confirmation without super user permissions",403);return!0}o(Ba,"checkContextPermissions");function Fa(V){let _=!1;if(V&&(V-Ye>1&&(_=!0),Ye=V),!(ft===Xn&&!_)&&(Xn=ft,(0,Mu.getWorkerIndex)()===(0,Mu.getWorkerCount)()-1))return nt&&clearTimeout(nt),ft?new Promise(S=>{let A=new Date;A.setMonth(0),A.setDate(1),A.setHours(0),A.setMinutes(0),A.setSeconds(0);let b=ft/(1+Ye),I=_?Date.now():Math.ceil((Date.now()-A.getTime())/b)*b+A.getTime(),P=o(D=>{Ue.default.trace?.(`Scheduled next cleanup scan at ${new Date(D)}`),nt=setTimeout(()=>Z=Z.then(async()=>{if(P(Math.max(D+ft,Date.now())),i.rootStore.status!=="open"){clearTimeout(nt);return}let L=50,k=new Array(L),C=0,x=Math.pow(Ye,8)*(vu.get(U.STORAGE_RECLAMATION_EVICTIONFACTOR)??1e5),z=E/Math.pow(Math.max(Ye,1),4);Ue.default.info?.(`Starting cleanup scan for ${s}, evict threshold ${x}, adjusted eviction ${z}ms`);function ne(re,B,de,he){let Se=re+z-Date.now();if(Se<0)return!0;if(Ye){let ee=i.lastSize;return de&Yr&&cl(he,J=>{J.size&&(ee+=J.size)}),Ue.default.trace?.(`shouldEvict adjusted ${Se} ${ee}, ${Se*(re-B)/ee} < ${x}`),Se*(re-B)/ee<x}return!1}o(ne,"shouldEvict");try{let re=0;for(let B of i.getRange({start:!1,snapshot:!1,versions:!0,lazy:!0})){let{key:de,value:he,version:Se,expiresAt:ee,metadataFlags:J}=B,pe;he===null&&!g&&Se+gIe<Date.now()?pe=Pu(i,B,Se):ee!=null&&ne(ee,Se,J,he)&&(pe=Ce.evict(de,he,Se),re++),pe&&(await k[C],k[C]=pe.catch(Te=>{Ue.default.error?.("Cleanup error",Te)}),++C>=L&&(C=0)),await Kc()}Ue.default.info?.(`Finished cleanup scan for ${s}, evicted ${re} entries`)}catch(re){Ue.default.warn?.(`Error in cleanup scan for ${s}:`,re)}S(void 0),Ye=0}),Math.min(D-Date.now(),2147483647)).unref()},"startNextTimer");P(I)}):void 0}o(Fa,"scheduleCleanup");function gm(){$=l?.addDeleteRemovalCallback(n,i,(V,_)=>{i.remove(V,_)})}o(gm,"addDeleteRemoval");function $u(){(0,Mu.getWorkerIndex)()===0&&setInterval(async()=>{if(!el){el=!0;try{let V=K.name,_=r[V];if(!_)throw new Error(`expiresAt attribute ${K} must be indexed`);for(let S of _.getRange({start:!0,values:!1,end:Date.now(),snapshot:!1})){for(let A of _.getValues(S)){let b=i.getEntry(A);b?.value?b.value[V]<Date.now()&&Ce.evict(A,b.value,b.version):i.ifVersion(A,b?.version,()=>_.remove(S,A))}await Kc()}}catch(V){Ue.default.error?.("Error in evicting old records",V)}finally{el=!1}}},EIe).unref()}o($u,"runRecordExpirationEviction");function rl(V){if(V!=null){if(Array.isArray(V))return V;if(typeof V=="number"){if(V>=65536)throw new Error(`Shard id ${V} must be below 65536`);let _=server.shards?.get?.(V);if(_)return Ue.default.trace?.(`Shard ${V} mapped to ${_.map(S=>S.name).join(", ")}`),_.map(S=>S.name);throw new Error(`Shard ${V} is not defined`)}throw new Error(`Shard or residency list ${V} is not a valid type, must be a shard number or residency list of node hostnames`)}}o(rl,"residencyFromFunction");function nl(V){if(V){let _=V.join(","),S=d.get([Symbol.for("residency_by_set"),_]);return S||(d.put([Symbol.for("residency_by_set"),_],S=Math.floor(Math.random()*2147418112)+65535),d.put([Symbol.for("residency_by_id"),S],V),S)}}o(nl,"getResidencyId");function Ha(V,_){let S=Rb(V,i.rootStore);if(S){let A=_;return A?async()=>{await A(),await S()}:()=>S()}return _}o(Ha,"preCommitBlobsForRecordBefore")}function PM(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 W4(){}function eA(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 Zy(parseInt(e.slice(1),36));if(e==="null")return null;if(!/^-?[0-9]+$/.test(e)&&!(e instanceof Date))throw new SyntaxError;return Zy(+e);case"Float":return e==="null"?null:Zy(+e);case"BigInt":return e==="null"?null:BigInt(e);case"Boolean":return e==="true"?!0:e==="false"?!1:e;case"Date":if(isNaN(e)){if(e==="null")return null;AIe.test(e)||(e+="Z");let n=new Date(e);return Zy(n.getTime()),n}return new Date(+e);case void 0:case"Any":return(0,tA.autoCast)(e);default:return e}}catch(n){throw n.message=`Invalid value for attribute ${t.name}: "${e}", expecting ${r}`,n.statusCode=400,n}}function Zy(e){if(isNaN(e))throw new SyntaxError;return e}function z4(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 ii(e,t,r){return e?.then?e.then(t,r):t(e)}function j4(e){return e!=null}function oi(e){try{return JSON.stringify(e)}catch{return e}}function bIe(e){let t=process.pid;return e.env.readerList().slice(1).some(r=>+r.match(/\d+/)?.[0]!=t)}var Yc,G_,J4,Q4,vu,ct,$_,V_,Ue,Uu,Mu,tA,DM,hIe,pIe,_Ie,EIe,gIe,$4,SIe,V4,TIe,Wn,Du,RIe,K4,Y4,yIe,VGe,AIe,Kc,hR=ce(()=>{H();Yc=require("lmdb"),G_=w(Cn()),J4=w(require("lodash")),Q4=w(Lm());tc();vm();vu=w(oe());Vw();ct=w(ge()),$_=w(Vo()),V_=w(Ti());Pe();Xg();Ue=w(hi());PN();ol();Uu=require("ordered-binary"),Mu=w(rt());Yi();tA=w(se());ml();io();Cg();vh();DM=w(require("node:fs"));ts();Hy();WD();({sortBy:hIe}=J4.default),{validateAttribute:pIe}=Q4.default,_Ie=new Uint8Array(9);_Ie[8]=192;EIe=6e4,gIe=864e5;vu.initSync();$4=vu.get(U.STORAGE_PREFETCHWRITES),SIe=1e4,V4=1,TIe=2,Wn=1,Du=8,RIe=Buffer.allocUnsafeSlow(8192),K4=1978,Y4=100,yIe={read:!0,insert:!0,update:!0,delete:!0,isSuperUser:!0},VGe=(0,tA.convertToMS)(vu.get(U.CLUSTERING_LEAFSERVER_STREAMS_MAXAGE))||864e5;o(rA,"makeTable");o(PM,"attributesAsObject");o(W4,"noop");AIe=/[+-][0-9]{2}:[0-9]{2}|[a-zA-Z]$/;o(eA,"coerceType");o(Zy,"rejectNaN");o(z4,"isDescendantId");Kc=o(()=>new Promise(setImmediate),"rest");o(ii,"when");o(j4,"exists");o(oi,"stringify");o(bIe,"hasOtherProcesses")});function nA(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,a=t[s]||0,c=i-a;r+=c*c}return r}function sA(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 a=0;a<i;a++){let c=e[a]||0,l=t[a]||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 X4=ce(()=>{o(nA,"euclideanDistance");o(sA,"cosineDistance")});var Z4,e3,tm,No,em,IIe,NIe,iA,t3=ce(()=>{X4();Z4=require("msgpackr"),e3=w(hi()),tm=w(ge()),No=(0,e3.loggerWithTag)("HNSW"),em=Symbol.for("entryPoint"),IIe=Symbol.for("key"),NIe=10,iA=class{static{o(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=Z4.FLOAT32_OPTIONS.ALWAYS),this.distance=r?.distance==="euclidean"?nA:sA,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"?[IIe,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 a=new Map,c,l=this.indexStore.get(em);if(n?c={...this.indexStore.get(i)}:c={},r){let f=l&&this.indexStore.get(l);if(f===void 0){let E=Math.floor(-Math.log(Math.random())*this.mL),g={vector:r,level:E,primaryKey:t};for(let R=0;R<=E;R++)g[R]=[];if(this.indexStore.put(i,g),typeof i!="number")throw new Error("Invalid nodeId: "+i);No.debug?.("setting entry point to",i),this.indexStore.put(em,i);return}let m=c.level??Math.min(Math.floor(-Math.log(Math.random())*this.mL),NIe),h=f.level;if(m>=h){if(typeof i!="number")throw new Error("Invalid nodeId: "+i);No.debug?.("setting entry point to",i),this.indexStore.put(em,i)}for(;h>m;){let E=this.searchLayer(r,l,f,this.efConstruction,h);E.length>0&&(l=E[0].id,f=E[0].node),h--}let p=new Array(m+1);for(let E=0;E<=m;E++)p[E]=[];for(let E=Math.min(m,h);E>=0;E--){let g=this.searchLayer(r,l,f,this.efConstruction,E);g=g.slice(0,this.M<<1),g.length===0&&E===0&&No.info?.("should not have zero connections for",l);let R=p[E];for(let T=0;T<g.length;T++){let{id:y,distance:N,node:O}=g[T];if(y===i)continue;let F=[];if(this.optimizeRouting){let Y=!1,K=O[E],$=1+this.optimizeRouting*(1+.5*T/this.M);for(let le=0;le<K.length;le++){let{id:ue,distance:ie}=K[le],me=1+this.optimizeRouting*(1+.5*le/this.M);for(let De=0;De<R.length;De++){let{id:Me,distance:ft}=R[De];if(Me===ue){N*$>ft+ie?Y=!0:ie*me>N+ft&&(F.push({fromId:Me,toId:y}),F.push({fromId:y,toId:Me}));break}}if(Y)break}if(Y)continue}else if(T>=(E>0?this.M:this.M<<1))continue;R.push({id:y,distance:N});for(let{fromId:Y,toId:K}of F){let $=d(Y);$||($=d(Y,this.indexStore.get(Y)));for(let le=0;le<$[E].length;le++)if($[E][le].id===K){Object.isFrozen($[E])&&($[E]=$[E].slice()),$[E].splice(le,1);break}}let Z=c[E],q=Z?.find(({id:Y})=>Y===y);if(q){let Y=Z?.indexOf(q);Z.copied||(Z=[...Z],Z.copied=!0,c[E]=Z),Z.splice(Y,1)}else this.addConnection(y,d(y,O),i,E,N,d)}}this.indexStore.put(i,{vector:r,level:m,primaryKey:t,...p})}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:h,value:p}of this.indexStore.getRange({start:0,end:1/0}))if(p.level>m){if(l=h,p.level===f)break;m=p.level}}if(l===void 0)this.indexStore.remove(em);else{if(typeof l!="number")throw new Error("Invalid nodeId: "+l);No.debug?.("setting entry point to",l),this.indexStore.put(em,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:h}of m){let p=d(h,this.indexStore.get(h));for(let E=0;E<=f;E++)p[E]=p[E]?.filter(({id:g})=>g!==i),p[E].length===0&&(No.info?.("node was left orphaned, will reindex",h),u.set(p.primaryKey,p.vector))}}function d(f,m){let h=a.get(f);return!h&&m&&(h={...m},a.set(f,h)),h}o(d,"updateNode");for(let[f,m]of a)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(em);if(t===void 0)return;let r=this.indexStore.get(t);return{id:t,...r}}searchLayer(t,r,n,s,i,a=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((h,p)=>h.distance-p.distance);let d=l.shift(),f=u[u.length-1].distance;if(d.distance>f)break;let m=d.node;for(let{id:h}of m[i]||[]){if(c.has(h)||h===void 0)continue;c.add(h);let p=this.indexStore.get(h);if(!p)continue;this.nodesVisitedCount++;let E=a(t,p.vector);if(E<f||u.length<s){let g={id:h,distance:E,node:p};l.push(g),u.push(g)}}u.sort((h,p)=>h.distance-p.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 a=0;switch(i){case"lt":case"le":a=r;case"sort":break;default:throw new tm.ClientError(`Can not use "${i}" comparator with HNSW`)}if(n)throw new tm.ClientError("Can not use descending sort order with HNSW");let c;if(s==="cosine")c=sA;else if(s==="euclidean")c=nA;else{if(s)throw new tm.ClientError("Unknown distance function");c=this.distance}if(!t)throw new tm.ClientError("A target vector must be provided for an HNSW query");if(!Array.isArray(t))throw new tm.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 a&&(d=d.filter(f=>f.distance<a)),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 a=this.indexStore.get(i);if(!a){No.info?.("could not find neighbor node",a);continue}a[n]?.find(({id:l})=>l==t)||No.info?.("asymmetry detected",a[n])}n++}}addConnection(t,r,n,s,i,a){r[s]||(r[s]=[]);let c=s===0?this.M<<1:this.M;if(this.optimizeRouting&&(c<<=2),r[s].length>=c+(c>>2)){No.warn?.("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=a(f.id)??this.indexStore.get(f.id);m&&m[s]&&(m=a(f.id,m),m[s]=m[s].filter(({id:h})=>h!==t),s===0&&m[s].length===0&&No.info?.("should not remove last connection",t,n))}}r[s].find(({id:l})=>l===n)?No.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 a=s.shift(),c=this.indexStore.get(a);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 a=this.distance;s.type&&(a=s.distance==="euclidean"?nA:sA);let c=a(s.target,t);return i.set(n,c),c}return t}}});var LM,r3=ce(()=>{t3();LM={HNSW:iA}});var ut={};we(ut,{database:()=>Ed,databaseEnvs:()=>wa,databases:()=>He,dropDatabase:()=>UN,dropTableMeta:()=>DIe,getDatabases:()=>st,getDefaultCompression:()=>LT,getTables:()=>wIe,onRemovedDB:()=>np,onUpdatedTable:()=>jl,readMetaDb:()=>K_,resetDatabases:()=>mf,table:()=>ze,tables:()=>fn});function wIe(){return lA||st(),fn||{}}function st(){if(lA)return He;lA=!0,sm=new Map;let e=(0,Zt.getHdbBasePath)()&&(0,Gt.join)((0,Zt.getHdbBasePath)(),il),t=(0,Zt.get)(U.DATABASES)||{};if(process.env.SCHEMAS_DATA_PATH&&(t.data={path:process.env.SCHEMAS_DATA_PATH}),e=process.env.STORAGE_PATH||(0,Zt.get)(U.STORAGE_PATH)||e&&((0,bs.existsSync)(e)?e:(0,Gt.join)((0,Zt.getHdbBasePath)(),gE)),!e)return;if((0,bs.existsSync)(e))for(let n of(0,bs.readdirSync)(e,{withFileTypes:!0})){let s=(0,Gt.basename)(n.name,".mdb");n.isFile()&&(0,Gt.extname)(n.name).toLowerCase()===".mdb"&&!t[s]?.path&&K_((0,Gt.join)(e,n.name),null,s)}if((0,bs.existsSync)((0,nm.getBaseSchemaPath)())){for(let n of(0,bs.readdirSync)((0,nm.getBaseSchemaPath)(),{withFileTypes:!0}))if(!n.isFile()){let s=(0,Gt.join)((0,nm.getBaseSchemaPath)(),n.name),i=(0,Gt.join)((0,nm.getTransactionAuditStoreBasePath)(),n.name);for(let a of(0,bs.readdirSync)(s,{withFileTypes:!0}))if(a.isFile()&&(0,Gt.extname)(a.name).toLowerCase()===".mdb"){let c=(0,Gt.join)(i,a.name);K_((0,Gt.join)(s,a.name),(0,Gt.basename)(a.name,".mdb"),n.name,c,!0)}}}if(t)for(let n in t){let s=t[n],i=s.path;if((0,bs.existsSync)(i))for(let c of(0,bs.readdirSync)(i,{withFileTypes:!0}))c.isFile()&&(0,Gt.extname)(c.name).toLowerCase()===".mdb"&&K_((0,Gt.join)(i,c.name),(0,Gt.basename)(c.name,".mdb"),n);let a=s.tables;if(a)for(let c in a){let l=a[c],u=(0,Gt.join)(l.path,(0,Gt.basename)(c+".mdb"));(0,bs.existsSync)(u)&&K_(u,c,n,null,!0)}}for(let n in He){let s=sm.get(n);if(s){let i=He[n];n.includes("delete")&&Pr.trace(`defined tables ${Array.from(s.keys())}`);for(let a in i)s.has(a)||(Pr.trace(`delete table class ${a}`),delete i[a])}else if(delete He[n],n==="data"){for(let i in fn)delete fn[i];delete fn[uA]}}let r=["hdb_temp","hdb_certificate","hdb_raw_analytics","hdb_session_will","hdb_job","hdb_license","hdb_info"];if((0,Zt.get)(U.ANALYTICS_REPLICATE)===!1?r.push("hdb_analytics"):(He.system?.hdb_analytics?.enableAuditing(),He.system?.hdb_analytics_hostname?.enableAuditing()),He.system)for(let n of r)He.system[n]&&(He.system[n].replicate=!1);return sm=null,He}function mf(){lA=!1;for(let[,e]of wa)e.needsDeletion=!0;st();for(let[e,t]of wa)if(t.needsDeletion&&!e.endsWith("system.mdb")){t.close(),wa.delete(e);let r=He[t.databaseName];for(let n in r)if(r[n].primaryStore.path===e){delete He[t.databaseName],W_.forEach(i=>i(t.databaseName));break}}return He}function K_(e,t,r=UM,n,s){let i=new MM.default(e,!1);try{let a=wa.get(e);a?a.needsDeletion=!1:(a=(0,im.open)(i),wa.set(e,a));let c=new om.default(!1),l=a.dbisDb||(a.dbisDb=a.openDB(oA.INTERNAL_DBIS_NAME,c)),u=a.auditStore;u||(n?(0,bs.existsSync)(n)&&(i.path=n,u=(0,im.open)(i),u.isLegacy=!0):u=Gy(a));let d=a3(r),f=d[uA],m=new Map;for(let{key:h,value:p}of l.getRange({start:!1})){let[E,g]=h.toString().split("/");g===""?g=p.name:g||(g=E,E=t,p.name||(p.name=g,p.indexed=!p.is_hash_attribute)),f?.add(E);let R=m.get(E);R||m.set(E,R={attributes:[]}),(g==null||p.is_hash_attribute)&&(R.primary=p),g!=null&&R.attributes.push(p),Object.defineProperty(p,"key",{value:h,configurable:!0})}for(let[h,p]of m){let{attributes:E,primary:g}=p;if(!g){for(let ie of E)if(ie.is_hash_attribute||ie.isPrimaryKey){g=ie;break}if(!g){Pr.warn(`Unable to find a primary key attribute on table ${h}, with attributes: ${JSON.stringify(E)}`);continue}}let R=d[h],T={},y=[],N,O,F=typeof g.audit=="boolean"?g.audit:(0,Zt.get)(U.LOGGING_AUDITLOG),Z=g.trackDeletes,q=g.expiration,Y=g.eviction,K=g.sealed,$=g.splitSegments,le=g.replicate;if(R)T=R.indices,y=R.attributes,R.schemaVersion++;else{N=g.tableId,N?N>=(l.get(rm)||0)&&(l.putSync(rm,N+1),Pr.info(`Updating next table id (it was out of sync) to ${N+1} for ${h}`)):(g.tableId=N=l.get(rm),N||(N=1),Pr.debug("Table {tableName} missing an id, assigning {tableId}"),l.putSync(rm,N+1),l.putSync(g.key,g));let ie=new om.default(!g.is_hash_attribute,g.is_hash_attribute);if(ie.compression=g.compression,ie.compression){let me=(0,Zt.get)(U.STORAGE_COMPRESSION_THRESHOLD)||o3;ie.compression.threshold=me}O=jy(a.openDB(g.key,ie),a),a.databaseName=r,O.tableId=N}let ue;for(let ie of E){ie.attribute=ie.name;try{if(!ie.is_hash_attribute&&(ie.indexed||ie.attribute&&!ie.name)){if(!T[ie.name]){let De=l3(ie.key,a,ie);T[ie.name]=De,T[ie.name].indexNulls=ie.indexNulls}let me=y.find(De=>De.name===ie.name);me?y.splice(y.indexOf(me),1,ie):y.push(ie),ue=!0}}catch(me){Pr.error("Error trying to update attribute",ie,y,T,me)}}for(let ie of y)if(!E.find(De=>De.name===ie.name)){if(ie.is_hash_attribute){Pr.error("Unable to remove existing primary key attribute",ie);continue}ie.indexed&&(y.splice(y.indexOf(ie),1),ue=!0)}if(R)ue&&(R.schemaVersion++,R.updatedAttributes());else{R=c3(d,h,rA({primaryStore:O,auditStore:u,audit:F,sealed:K,splitSegments:$,replicate:le,expirationMS:q&&q*1e3,evictionMS:Y&&Y*1e3,trackDeletes:Z,tableName:h,tableId:N,primaryKey:g.name,databasePath:s?r+"/"+h:r,databaseName:r,indices:T,attributes:E,schemaDefined:g.schemaDefined,dbisDB:l})),R.schemaVersion=1;for(let ie of Y_)ie(R)}}return a}catch(a){throw a.message+=` opening database ${e}`,a}}function a3(e){let t=He[e];if(t||(e==="data"?t=He[e]=fn:e==="system"?Object.defineProperty(He,"system",{value:t=Object.create(null),configurable:!0}):t=He[e]=Object.create(null)),sm&&!sm.has(e)){let r=new Set;t[uA]=r,sm.set(e,r)}return t}function c3(e,t,r){return e[t]=r,r}function Ed({database:e,table:t}){e||(e=UM),st();let r=a3(e),n=(0,Gt.join)((0,Zt.getHdbBasePath)(),il),s=(0,Zt.get)(U.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)(U.STORAGE_PATH)||((0,bs.existsSync)(n)?n:(0,Gt.join)((0,Zt.getHdbBasePath)(),gE));let a=(0,Gt.join)(n,(i?t:e)+".mdb"),c=wa.get(a);if(!c||c.status==="closed"){let l=new MM.default(a,!1);c=(0,im.open)(l),wa.set(a,c)}return c.auditStore||(c.auditStore=Gy(c)),c}async function UN(e){if(!He[e])throw new Error("Schema does not exist");let t=He[e],r;for(let n in t)r=t[n].primaryStore.rootStore,wa.delete(r.path),r.status==="open"&&(await r.close(),await z_.remove(r.path));if(r||(r=Ed({database:e,table:null}),r.status==="open"&&(await r.close(),await z_.remove(r.path))),e==="data"){for(let n in fn)delete fn[n];delete fn[uA]}delete He[e],W_.forEach(n=>n(e)),await Tb(r)}function l3(e,t,r){let n=r.is_hash_attribute||r.indexed.type&&LM[r.indexed.type]?.useObjectStore,s=new om.default(!n,n),i=t.openDB(e,s);if(r.indexed.type){let a=LM[r.indexed.type];a?i.customIndex=new a(i,r.indexed):Pr.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:a,audit:c,sealed:l,splitSegments:u,replicate:d,trackDeletes:f,schemaDefined:m,origin:h}=e;r||(r=UM);let p=Ed({database:r,table:t}),E=He[r];Pr.trace(`Defining ${t} in ${r}`);let g=E?.[t];if(p.status==="closed")throw new Error(`Can not use a closed data store for ${t}`);let R,T,y;m==null&&(m=!0);let N=new om.default(!1);for(let $ of a)$.attribute&&!$.name?($.name=$.attribute,$.indexed=!0):$.attribute=$.name,$.expiresAt&&($.indexed=!0);let O,F;if(g){if(R=g.primaryKey,g.primaryStore.rootStore.status==="closed")throw new Error(`Can not use a closed data store from ${t} class`);u==null&&(u=g.splitSegments),g.attributes.splice(0,g.attributes.length,...a)}else{let $=p.auditStore;T=a.find(me=>me.isPrimaryKey)||{},R=T.name,T.is_hash_attribute=T.isPrimaryKey=!0,T.schemaDefined=m,T.compression=LT(),f&&(T.trackDeletes=!0),c=T.audit=typeof c=="boolean"?c:(0,Zt.get)(U.LOGGING_AUDITLOG),n&&(T.expiration=n),s&&(T.eviction=s),u??=!1,T.splitSegments=u,typeof l=="boolean"&&(T.sealed=l),typeof d=="boolean"&&(T.replicate=d),h&&(T.origins?T.origins.includes(h)||T.origins.push(h):T.origins=[h]),Pr.trace(`${t} table loading, opening primary store`);let le=new om.default(!1,!0);le.compression=T.compression;let ue=t+"/";if(y=p.dbisDb=p.openDB(oA.INTERNAL_DBIS_NAME,N),K(),y.get(ue))return F&&F(),mf(),ze(e);let ie=jy(p.openDB(ue,le),p);p.databaseName=r,ie.tableId=y.get(rm),Pr.trace(`Assigning new table id ${ie.tableId} for ${t}`),ie.tableId||(ie.tableId=1),y.put(rm,ie.tableId+1),T.tableId=ie.tableId,g=c3(E,t,rA({primaryStore:ie,auditStore:$,audit:c,sealed:l,splitSegments:u,replicate:d,trackDeletes:f,expirationMS:n&&n*1e3,evictionMS:s&&s*1e3,primaryKey:R,tableName:t,tableId:ie.tableId,databasePath:r,databaseName:r,indices:{},attributes:a,schemaDefined:m,dbisDB:y})),g.schemaVersion=1,O=!0,y.put(ue,T)}let Z=g.indices;y=y||(p.dbisDb=p.openDB(oA.INTERNAL_DBIS_NAME,N)),g.dbisDB=y;let q=[];for(let{key:$,value:le}of y.getRange({start:!0})){let[ue,ie]=$.toString().split("/");if(ie===""&&(ie=le.name),ie){if(ue!==t)continue}else continue;let me=a.find(Me=>Me.name===ie),De=!me?.indexed&&le.indexed&&!le.isPrimaryKey;if((!me||De)&&(K(),O=!0,me||y.remove($),De)){let Me=g.indices[ue];Me&&q.push(Me)}}let Y=[];try{for(let $ of a||[]){if(($.relationship||$.computed)&&(O=!0,$.relationship))continue;let le=t+"/"+($.name||"");Object.defineProperty($,"key",{value:le,configurable:!0});let ue=y.get(le);if($.isPrimaryKey){if(ue=ue||y.get(le=t+"/")||{},c!==void 0&&c!==g.audit||l!==void 0&&l!==g.sealed||d!==void 0&&d!==g.replicate||(+n||void 0)!==(+ue.expiration||void 0)||(+s||void 0)!==(+ue.eviction||void 0)||$.type!==ue.type){let me={...ue};typeof c=="boolean"&&(c&&g.enableAuditing(c),me.audit=c),n&&(me.expiration=+n),s&&(me.eviction=+s),l!==void 0&&(me.sealed=l),d!==void 0&&(me.replicate=d),$.type&&(me.type=$.type),O=!0,K(),y.put(le,me)}continue}ue?.attribute&&!ue.name&&(ue.indexed=!0);let ie=!ue||ue.type!==$.type||JSON.stringify(ue.indexed)!==JSON.stringify($.indexed)||ue.nullable!==$.nullable||ue.version!==$.version||JSON.stringify(ue.properties)!==JSON.stringify($.properties)||JSON.stringify(ue.elements)!==JSON.stringify($.elements);if($.indexed){let me=l3(le,p,$);(ie||ue.indexingPID&&ue.indexingPID!==process.pid||ue.restartNumber<j_.workerData?.restartNumber)&&(O=!0,K(),ue=y.get(le),(ie||ue.indexingPID&&ue.indexingPID!==process.pid||ue.restartNumber<j_.workerData?.restartNumber)&&(O=!0,$.indexNulls===void 0&&($.indexNulls=!0),g.primaryStore.getStats().entryCount>0&&($.lastIndexedKey=ue?.lastIndexedKey??void 0,$.indexingPID=process.pid,me.isIndexing=!0,Object.defineProperty($,"dbi",{value:me}),Y.push($))),y.put(le,$)),ue?.indexNulls&&$.indexNulls===void 0&&($.indexNulls=!0),me.indexNulls=$.indexNulls,Z[$.name]=me}else ie&&(O=!0,K(),y.put(le,$))}}finally{F&&F()}if(O&&(g.schemaVersion++,g.updatedAttributes()),Pr.trace(`${t} table loading, running index`),Y.length>0||q.length>0?g.indexingOperation=PIe(g,Y,q):O&&aA.signalSchemaChange(new cA.SchemaEventMsg(process.pid,"schema-change",g.databaseName,g.tableName)),g.origin=h,O)for(let $ of Y_)$(g,h!=="cluster");return(n||s||i)&&g.setTTLExpiration({expiration:n,eviction:s,scanInterval:i}),Pr.trace(`${t} table loaded`),g;function K(){F||p.transactionSync(()=>({then($){F=$}}))}o(K,"startTxn")}async function PIe(e,t,r){try{Pr.info(`Indexing ${e.tableName} attributes`,t);let n=e.schemaVersion;await aA.signalSchemaChange(new cA.SchemaEventMsg(process.pid,"schema-change",e.databaseName,e.tableName));let s;for(let u of r)s=u.drop();let i,a={},c=0,l=t.length;if(await new Promise(u=>setImmediate(u)),l>0){let u;for(let f of t)(0,im.compareKeys)(f.lastIndexedKey,u)<0&&(u=f.lastIndexedKey),f.lastIndexedKey==null&&f.dbi.clearAsync();let d=0;for(let{key:f,value:m,version:h}of e.primaryStore.getRange({start:u,lazy:l<4,versions:!0,snapshot:!1}))if(m){if(d++,s=e.primaryStore.ifVersion(f,h,()=>{for(let p=0;p<l;p++){let E=t[p],g=E.name,R=E.dbi;try{let T=E.resolve,y=m&&(T?T(m):m[g]);if(R.customIndex){R.customIndex.index(f,y);continue}let N=(0,n3.getIndexedValues)(y);if(N)for(let O=0,F=N.length;O<F;O++)R.put(N[O],f)}catch(T){a[g]||(a[g]=!0,Pr.error(`Error indexing attribute ${g}`,T))}}}),s.then(()=>d--,p=>{d--,Pr.error(p)}),j_.workerData&&j_.workerData.restartNumber!==i3.restartNumber&&(i=!0),++c%100===0||i){for(let p of t)p.lastIndexedKey=f,e.dbisDB.put(p.key,p);if(i)return}d>OIe?await s:d>CIe&&await new Promise(p=>setImmediate(p))}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 aA.signalSchemaChange(new cA.SchemaEventMsg(process.pid,"indexing-finished",e.databaseName,e.tableName)),Pr.info(`Finished indexing ${e.tableName} attributes`,t)}catch(n){Pr.error("Error in indexing",n)}}function DIe({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 jl(e){return Y_.push(e),{remove(){let t=Y_.indexOf(e);t>-1&&Y_.splice(t,1)}}}function np(e){return W_.push(e),{remove(){let t=W_.indexOf(e);t>-1&&W_.splice(t,1)}}}function LT(){let e=(0,Zt.get)(U.STORAGE_COMPRESSION),t=(0,Zt.get)(U.STORAGE_COMPRESSION_DICTIONARY),r=(0,Zt.get)(U.STORAGE_COMPRESSION_THRESHOLD)||o3,n={startingOffset:32};return t&&(n.dictionary=z_.readFileSync(t)),r&&(n.threshold=r),e&&n}var Zt,oA,im,Gt,bs,nm,om,MM,z_,vM,n3,aA,cA,j_,s3,i3,Pr,UM,uA,o3,fn,He,rm,Y_,W_,lA,wa,sm,OIe,CIe,Pe=ce(()=>{Zt=w(oe()),oA=w(Kt()),im=require("lmdb"),Gt=require("path"),bs=require("fs"),nm=w(Nt());hR();om=w(Ym()),MM=w(Wm());H();z_=w(require("fs-extra")),vM=w(mi()),n3=w(Cn()),aA=w(Vo()),cA=w(Ti()),j_=require("worker_threads"),s3=w(j()),i3=w(rt());Yi();ml();ts();r3();Pr=(0,s3.forComponent)("storage"),UM="data",uA=Symbol("defined-tables"),o3=((0,Zt.get)(U.STORAGE_PAGESIZE)||4096)-60;(0,Zt.initSync)();fn=Object.create(null),He=Object.create(null);(0,vM._assignPackageExport)("databases",He);(0,vM._assignPackageExport)("tables",fn);rm=Symbol.for("next-table-id"),Y_=[],W_=[],wa=new Map;o(wIe,"getTables");o(st,"getDatabases");o(mf,"resetDatabases");o(K_,"readMetaDb");o(a3,"ensureDB");o(c3,"setTable");o(Ed,"database");o(UN,"dropDatabase");o(l3,"openIndex");o(ze,"table");OIe=1e3,CIe=10;o(PIe,"runIndexing");o(DIe,"dropTableMeta");o(jl,"onUpdatedTable");o(np,"onRemovedDB");o(LT,"getDefaultCompression")});var se=M(be=>{"use strict";var Wc=require("path"),h3=require("fs-extra"),jn=j(),u3=require("fs-extra"),dA=require("os"),LIe=require("net"),MIe=require("recursive-iterator"),Dr=(H(),v(W)),{PACKAGE_ROOT:vIe}=ht(),UIe=ZA(),d3=require("papaparse"),fA=require("moment"),{inspect:xIe}=require("util"),f3=require("is-number"),BIe=require("minimist"),FIe=require("https"),HIe=require("http"),kIe=/^((\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d\.\d+([+-][0-2]\d:[0-5]\d|Z))|(\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d([+-][0-2]\d:[0-5]\d|Z))|(\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d([+-][0-2]\d:[0-5]\d|Z)))$/,p3=require("util").promisify(setTimeout),qIe=100,GIe=5,$Ie="",VIe=4,m3={true:!0,TRUE:!0,FALSE:!1,false:!1,undefined:null,null:null,NULL:null,NaN:NaN};be.isEmpty=Is;be.isEmptyOrZeroLength=wo;be.arrayHasEmptyValues=WIe;be.arrayHasEmptyOrZeroLengthValues=zIe;be.buildFolderPath=jIe;be.isBoolean=_3;be.errorizeMessage=KIe;be.stripFileExtension=QIe;be.autoCast=XIe;be.autoCastJSON=E3;be.autoCastJSONDeep=BM;be.removeDir=ZIe;be.compareVersions=eNe;be.isCompatibleDataVersion=tNe;be.escapeRawValue=rNe;be.unescapeValue=nNe;be.stringifyProps=sNe;be.timeoutPromise=oNe;be.isClusterOperation=cNe;be.getClusterUser=uNe;be.checkGlobalSchemaTable=lNe;be.getHomeDir=S3;be.getPropsFilePath=iNe;be.promisifyPapaParse=dNe;be.removeBOM=T3;be.createEventPromise=fNe;be.checkProcessRunning=mNe;be.checkSchemaTableExist=hNe;be.checkSchemaExists=R3;be.checkTableExists=y3;be.getStartOfTomorrowInSeconds=pNe;be.getLimitKey=_Ne;be.isObject=JIe;be.isNotEmptyAndHasValue=YIe;be.autoCasterIsNumberCheck=g3;be.backtickASTSchemaItems=ENe;be.isPortTaken=aNe;be.createForkArgs=gNe;be.autoCastBoolean=SNe;be.asyncSetTimeout=p3;be.getTableHashAttribute=TNe;be.doesSchemaExist=RNe;be.doesTableExist=yNe;be.stringifyObj=ANe;be.ms_to_time=bNe;be.changeExtension=INe;be.getEnvCliRootPath=FM;be.noBootFile=NNe;be.httpRequest=wNe;be.transformReq=ONe;be.convertToMS=CNe;be.PACKAGE_ROOT=vIe;function KIe(e){return e instanceof Error?e:new Error(e)}o(KIe,"errorizeMessage");function Is(e){return e==null}o(Is,"isEmpty");function YIe(e){return!Is(e)&&(e||e===0||e===""||_3(e))}o(YIe,"isNotEmptyAndHasValue");function wo(e){return Is(e)||e.length===0||e.size===0}o(wo,"isEmptyOrZeroLength");function WIe(e){if(Is(e))return!0;for(let t=0;t<e.length;t++)if(Is(e[t]))return!0;return!1}o(WIe,"arrayHasEmptyValues");function zIe(e){if(wo(e))return!0;for(let t=0;t<e.length;t++)if(wo(e[t]))return!0;return!1}o(zIe,"arrayHasEmptyOrZeroLengthValues");function jIe(...e){try{return e.join(Wc.sep)}catch{console.error(e)}}o(jIe,"buildFolderPath");function _3(e){return Is(e)?!1:e===!0||e===!1}o(_3,"isBoolean");function JIe(e){return Is(e)?!1:typeof e=="object"}o(JIe,"isObject");function QIe(e){return wo(e)?$Ie:e.slice(0,-VIe)}o(QIe,"stripFileExtension");function XIe(e){return Is(e)||e===""||typeof e!="string"?e:m3[e]!==void 0?m3[e]:g3(e)===!0?Number(e):kIe.test(e)?new Date(e):e}o(XIe,"autoCast");function E3(e){if(typeof e=="string"&&(e.startsWith("{")&&e.endsWith("}")||e.startsWith("[")&&e.endsWith("]")))try{return JSON.parse(e)}catch{}return e}o(E3,"autoCastJSON");function BM(e){if(e&&typeof e=="object"){if(Array.isArray(e))for(let t=0,r=e.length;t<r;t++){let n=e[t],s=BM(n);s!==n&&(e[t]=s)}else for(let t in e){let r=e[t],n=BM(r);n!==r&&(e[t]=n)}return e}else return E3(e)}o(BM,"autoCastJSONDeep");function g3(e){if(e.startsWith("0.")&&f3(e))return!0;let t=e.toUpperCase().includes("E");return!!((e!=="0"&&e.startsWith("0"))===!1&&t===!1&&f3(e))}o(g3,"autoCasterIsNumberCheck");async function ZIe(e){if(wo(e))throw new Error(`Directory path: ${e} does not exist`);try{await u3.emptyDir(e),await u3.remove(e)}catch(t){throw jn.error(`Error removing files in ${e} -- ${t}`),t}}o(ZIe,"removeDir");function eNe(e,t){if(wo(e)){jn.info("Invalid current version sent as parameter.");return}if(wo(t)){jn.info("Invalid upgrade version sent as parameter.");return}let r,n=/(\.0+)+$/,s=e.version?e.version:e,i=t.version?t.version:t,a=s.replace(n,"").split("."),c=i.replace(n,"").split("."),l=Math.min(a.length,c.length);for(let u=0;u<l;u++)if(r=parseInt(a[u],10)-parseInt(c[u],10),r)return r;return a.length-c.length}o(eNe,"compareVersions");function tNe(e,t,r=!1){let n=e.toString().split("."),s=t.toString().split(".");return n[0]===s[0]&&(!r||n[1]===s[1])}o(tNe,"isCompatibleDataVersion");function rNe(e){if(Is(e))return e;let t=String(e);return t==="."?Dr.UNICODE_PERIOD:t===".."?Dr.UNICODE_PERIOD+Dr.UNICODE_PERIOD:t.replace(Dr.FORWARD_SLASH_REGEX,Dr.UNICODE_FORWARD_SLASH)}o(rNe,"escapeRawValue");function nNe(e){if(Is(e))return e;let t=String(e);return t===Dr.UNICODE_PERIOD?".":t===Dr.UNICODE_PERIOD+Dr.UNICODE_PERIOD?"..":String(e).replace(Dr.ESCAPED_FORWARD_SLASH_REGEX,"/")}o(nNe,"unescapeValue");function sNe(e,t){if(Is(e))return jn.info("Properties object is null"),"";let r="";return e.each(function(n,s){try{if(t&&t[n]){let i=t[n];for(let a of i)r+=";"+a+dA.EOL}!wo(n)&&n[0]===";"?r+=" "+n+s+dA.EOL:wo(n)||(r+=n+"="+s+dA.EOL)}catch{jn.error(`Found bad property during upgrade with key ${n} and value: ${s}`)}}),r}o(sNe,"stringifyProps");function S3(){let e;try{e=dA.homedir()}catch{e=process.env.HOME}return e}o(S3,"getHomeDir");function iNe(){let e=Wc.join(S3(),Dr.HDB_HOME_DIR_NAME,Dr.BOOT_PROPS_FILE_NAME);return h3.existsSync(e)||(e=Wc.join(__dirname,"../","hdb_boot_properties.file")),e}o(iNe,"getPropsFilePath");function oNe(e,t){let r,n;return n=new Promise(function(s){r=setTimeout(function(){s(t)},e)}),{promise:n,cancel:o(function(){clearTimeout(r)},"cancel")}}o(oNe,"timeoutPromise");async function aNe(e){if(!e)throw new Error("Invalid port passed as parameter");return new Promise((t,r)=>{let n=LIe.createServer().once("error",s=>{s.code==="EADDRINUSE"?t(!0):r(s)}).once("listening",()=>n.once("close",()=>t(!1)).close()).listen(e)})}o(aNe,"isPortTaken");function cNe(e){try{return Dr.CLUSTER_OPERATIONS[e.toLowerCase()]!==void 0}catch(t){jn.error(`Error checking operation against cluster ops ${t}`)}return!1}o(cNe,"isClusterOperation");function lNe(e,t){let r=(Pe(),v(ut)).getDatabases();if(!r[e])return mA.HDB_ERROR_MSGS.SCHEMA_NOT_FOUND(e);if(!r[e][t])return mA.HDB_ERROR_MSGS.TABLE_NOT_FOUND(e,t)}o(lNe,"checkGlobalSchemaTable");function uNe(e,t){if(Is(t)){jn.warn("No CLUSTERING_USER defined, clustering disabled");return}if(Is(e)||wo(e)){jn.warn("No users to search.");return}let r;try{let n=e.get(t);n&&n.role.permission.cluster_user===!0&&n.active===!0&&(r=n)}catch(n){jn.error(`unable to find cluster_user due to: ${n.message}`);return}if(r===void 0){jn.warn(`CLUSTERING_USER: ${t} not found or is not active.`);return}return r}o(uNe,"getClusterUser");function dNe(){d3.parsePromise=function(e,t,r){return new Promise(function(n,s){d3.parse(e,{header:!0,transformHeader:T3,chunk:t.bind(null,s),skipEmptyLines:!0,transform:r,dynamicTyping:!1,error:s,complete:n})})}}o(dNe,"promisifyPapaParse");function T3(e){if(typeof e!="string")throw new TypeError(`Expected a string, got ${typeof e}`);return e.charCodeAt(0)===65279?e.slice(1):e}o(T3,"removeBOM");function fNe(e,t,r){return new Promise(n=>{t.once(e,s=>{let i=r;jn.info(`Got cluster status event response: ${xIe(s)}`);try{i.cancel()}catch{jn.error("Error trying to cancel timeout.")}n(s)})})}o(fNe,"createEventPromise");async function mNe(e){let t=!0,r=0;do await p3(qIe*r++),(await UIe.findPs(e)).length>0&&(t=!1);while(t&&r<GIe);if(t)throw new Error(`process ${e} was not started`)}o(mNe,"checkProcessRunning");function hNe(e,t){let r=R3(e);if(r)return r;let n=y3(e,t);if(n)return n}o(hNe,"checkSchemaTableExist");function R3(e){let{getDatabases:t}=(Pe(),v(ut));if(!t()[e])return mA.HDB_ERROR_MSGS.SCHEMA_NOT_FOUND(e)}o(R3,"checkSchemaExists");function y3(e,t){let{getDatabases:r}=(Pe(),v(ut));if(!r()[e][t])return mA.HDB_ERROR_MSGS.TABLE_NOT_FOUND(e,t)}o(y3,"checkTableExists");function pNe(){let e=fA().utc().add(1,"d").startOf("d").unix(),t=fA().utc().unix();return e-t}o(pNe,"getStartOfTomorrowInSeconds");function _Ne(){return fA().utc().format("DD-MM-YYYY")}o(_Ne,"getLimitKey");function ENe(e){try{let t=new MIe(e);for(let{node:r}of t)r&&(r.columnid&&typeof r.columnid!="string"&&(r.columnid=r.columnid.toString()),r.columnid&&!r.columnid.startsWith("`")&&(r.columnid_orig=r.columnid,r.columnid=`\`${r.columnid}\``),r.tableid&&!r.tableid.startsWith("`")&&(r.tableid_orig=r.tableid,r.tableid=`\`${r.tableid}\``),r.databaseid&&!r.databaseid.startsWith("`")&&(r.databaseid_orig=r.databaseid,r.databaseid=`\`${r.databaseid}\``),r.as&&typeof r.as=="string"&&!r.as.startsWith("[")&&(r.as_orig=r.as,r.as=`\`${r.as}\``))}catch(t){jn.error("Got an error back ticking items."),jn.error(t)}}o(ENe,"backtickASTSchemaItems");function gNe(e){return[e]}o(gNe,"createForkArgs");function SNe(e){return e===!0||typeof e=="string"&&e.toLowerCase()==="true"}o(SNe,"autoCastBoolean");function TNe(e,t){let{getDatabases:r}=(Pe(),v(ut)),n=r()[e]?.[t];return n?.primaryKey||n?.hash_attribute}o(TNe,"getTableHashAttribute");function RNe(e){let{getDatabases:t}=(Pe(),v(ut));return t()[e]!==void 0}o(RNe,"doesSchemaExist");function yNe(e,t){let{getDatabases:r}=(Pe(),v(ut));return r()[e]?.[t]!==void 0}o(yNe,"doesTableExist");function ANe(e){try{return JSON.stringify(e)}catch{return e}}o(ANe,"stringifyObj");function bNe(e){let t=fA.duration(e),r=t.seconds()>0?t.seconds()+"s":"",n=t.minutes()>0?t.minutes()+"m ":"",s=t.hours()>0?t.hours()+"h ":"",i=t.days()>0?t.days()+"d ":"";return(t.years()>0?t.years()+"y ":"")+i+s+n+r}o(bNe,"ms_to_time");function INe(e,t){let r=Wc.basename(e,Wc.extname(e));return Wc.join(Wc.dirname(e),r+t)}o(INe,"changeExtension");function FM(){if(process.env[Dr.CONFIG_PARAMS.ROOTPATH.toUpperCase()])return process.env[Dr.CONFIG_PARAMS.ROOTPATH.toUpperCase()];let e=BIe(process.argv);if(e[Dr.CONFIG_PARAMS.ROOTPATH.toUpperCase()])return e[Dr.CONFIG_PARAMS.ROOTPATH.toUpperCase()]}o(FM,"getEnvCliRootPath");var xM;function NNe(){if(xM)return xM;let e=FM();if(FM()&&h3.pathExistsSync(Wc.join(e,Dr.HDB_CONFIG_FILE)))return xM=!0,!0}o(NNe,"noBootFile");function wNe(e,t){let r;return e.protocol==="http:"?r=HIe:r=FIe,new Promise((n,s)=>{let i=r.request(e,a=>{a.setEncoding("utf8"),a.body="",a.on("data",c=>{a.body+=c}),a.on("end",()=>{n(a)})});i.on("error",a=>{s(a)}),i.write(t instanceof Buffer?t:JSON.stringify(t)),i.end()})}o(wNe,"httpRequest");function ONe(e){if(!e.schema&&!e.database){e.schema=Dr.DEFAULT_DATABASE_NAME;return}e.database&&(e.schema=e.database)}o(ONe,"transformReq");function CNe(e){let t=0;if(typeof e=="number"&&(t=e),typeof e=="string")switch(t=parseFloat(e),e.slice(-1)){case"M":t*=86400*30;break;case"D":case"d":t*=86400;break;case"H":case"h":t*=3600;break;case"m":t*=60;break}return t*1e3}o(CNe,"convertToMS");var mA=Vr()});var oe=M((N3,w3)=>{"use strict";var HM=require("fs-extra"),xu=require("path"),A3=require("os"),PNe=require("properties-reader"),Q_=j(),J_=se(),Be=(H(),v(W)),hA=gt(),DNe="Error initializing environment manager",pA="BOOT_PROPS_FILE_PATH",b3=!1,LNe={[Be.HDB_SETTINGS_NAMES.INSTALL_USER]:!0,[Be.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY]:!0,[Be.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]:!0,BOOT_PROPS_FILE_PATH:!0},Oa={};Object.assign(N3,w3.exports={BOOT_PROPS_FILE_PATH:pA,getHdbBasePath:MNe,setHdbBasePath:vNe,get:I3,initSync:xNe,setProperty:Qe,initTestEnvironment:BNe});function MNe(){return Oa[Be.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]}o(MNe,"getHdbBasePath");function vNe(e){Oa[Be.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]=e}o(vNe,"setHdbBasePath");function I3(e){let t=hA.getConfigValue(e);return t===void 0?Oa[e]:t}o(I3,"get");function Qe(e,t){LNe[e]&&(Oa[e]=t),hA.updateConfigObject(e,t)}o(Qe,"setProperty");function UNe(){let e;try{e=J_.getPropsFilePath(),HM.accessSync(e,HM.constants.F_OK|HM.constants.R_OK),b3=!0;let t=PNe(e);return Oa[Be.HDB_SETTINGS_NAMES.INSTALL_USER]=t.get(Be.HDB_SETTINGS_NAMES.INSTALL_USER),Oa[Be.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY]=t.get(Be.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY),Oa[pA]=e,!0}catch{return Q_.trace(`Environment manager found no properties file at ${e}`),!1}}o(UNe,"doesPropFileExist");function xNe(e=!1){try{(b3||UNe()||J_.noBootFile()||e)&&(hA.initConfig(e),Oa[Be.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]=hA.getConfigValue(Be.HDB_SETTINGS_NAMES.HDB_ROOT_KEY))}catch(t){Q_.error(DNe),Q_.error(t),console.error(t),process.exit(1)}}o(xNe,"initSync");function BNe(e={}){try{let{keep_alive_timeout:t,headers_timeout:r,server_timeout:n,https_enabled:s,cors_enabled:i,cors_accesslist:a,local_studio_on:c}=e,l=xu.join(__dirname,"../../","unitTests");Oa[pA]=xu.join(l,"hdb_boot_properties.file"),Qe(Be.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY,xu.join(l,"settings.test")),Qe(Be.HDB_SETTINGS_NAMES.INSTALL_USER,A3.userInfo()?A3.userInfo().username:void 0),Qe(Be.HDB_SETTINGS_NAMES.LOG_LEVEL_KEY,"debug"),Qe(Be.HDB_SETTINGS_NAMES.LOG_PATH_KEY,xu.join(l,"envDir","log")),Qe(Be.HDB_SETTINGS_NAMES.LOG_DAILY_ROTATE_KEY,!1),Qe(Be.HDB_SETTINGS_NAMES.CLUSTERING_ENABLED_KEY,!0),Qe(Be.HDB_SETTINGS_NAMES.CLUSTERING_NODE_NAME_KEY,"1231412de213"),Qe(Be.HDB_SETTINGS_NAMES.HDB_ROOT_KEY,xu.join(l,"envDir")),Qe(Be.CONFIG_PARAMS.STORAGE_PATH,xu.join(l,"envDir")),s&&(Qe(Be.CONFIG_PARAMS.HTTP_SECUREPORT,I3(Be.CONFIG_PARAMS.HTTP_PORT)),Qe(Be.CONFIG_PARAMS.HTTP_PORT,null)),Qe(Be.CONFIG_PARAMS.CUSTOMFUNCTIONS_NETWORK_HTTPS,!!s),Qe(Be.CONFIG_PARAMS.HTTP_PORT,9926),Qe(Be.HDB_SETTINGS_NAMES.SERVER_PORT_KEY,9925),Qe(Be.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_PORT,9925),Qe(Be.HDB_SETTINGS_NAMES.CORS_ENABLED_KEY,J_.isEmpty(i)?!1:i),Qe(Be.CONFIG_PARAMS.HTTP_CORS,J_.isEmpty(i)?!1:i),Qe(Be.HDB_SETTINGS_NAMES.MAX_CUSTOM_FUNCTION_PROCESSES,2),Qe(Be.HDB_SETTINGS_NAMES.MAX_HDB_PROCESSES,4),Qe(Be.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_PORT_KEY,9926),Qe(Be.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_ENABLED_KEY,!0),Qe(Be.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_DIRECTORY_KEY,xu.resolve(__dirname,"../../unitTests/server/fastifyRoutes/custom_functions")),Qe(Be.HDB_SETTINGS_NAMES.LOCAL_STUDIO_ON,J_.isEmpty(c)?!1:c),a&&(Qe("CORS_ACCESSLIST",a),Qe(Be.CONFIG_PARAMS.HTTP_CORSACCESSLIST,a)),n&&(Qe(Be.HDB_SETTINGS_NAMES.SERVER_TIMEOUT_KEY,n),Qe(Be.CONFIG_PARAMS.HTTP_TIMEOUT,n)),t&&(Qe(Be.HDB_SETTINGS_NAMES.SERVER_KEEP_ALIVE_TIMEOUT_KEY,t),Qe(Be.CONFIG_PARAMS.HTTP_KEEPALIVETIMEOUT,t)),r&&(Qe(Be.HDB_SETTINGS_NAMES.SERVER_HEADERS_TIMEOUT_KEY,r),Qe(Be.CONFIG_PARAMS.HTTP_HEADERSTIMEOUT,r))}catch(t){let r=`Error reading in HDB environment variables from path ${pA}. Please check your boot props and settings files`;Q_.fatal(r),Q_.error(t)}}o(BNe,"initTestEnvironment")});var M3=M((m$e,L3)=>{"use strict";var{promises:am,createReadStream:FNe,createWriteStream:HNe}=require("fs"),{createGzip:kNe}=require("zlib"),{promisify:qNe}=require("util"),{pipeline:GNe}=require("stream"),$Ne=qNe(GNe),qM=require("path"),D3=oe();D3.initSync();var _A=j(),{CONFIG_PARAMS:VNe,ITC_EVENT_TYPES:d$e}=(H(),v(W)),{onMessageFromWorkers:f$e}=rt(),{convertToMS:O3}=se(),{onStorageReclamation:KNe}=(Hy(),v(g4)),YNe=6e4,WNe="'interval' and 'maxSize' are both undefined, to enable logging rotation at least one of these values must be defined in harperdb-config.yaml",zNe="'logging.rotation.path' is undefined, to enable logging rotation set this value in harperdb-config.yaml",kM,C3;L3.exports=jNe;function jNe({logger:e,maxSize:t,interval:r,retention:n,enabled:s,path:i,auditInterval:a}){if(s===!1)return;let c=0;if(KNe(e.path,f=>{c=f},!0),!t&&!r)throw new Error(WNe);if(!i)throw new Error(zNe);let l;if(t){let f=t.slice(-1),m=t.slice(0,-1);f==="G"?l=m*1e9:f==="M"?l=m*1e6:l=m*1e3}let u;r&&(u=O3(r));let d;return kM=Date.now(),_A.trace("Log rotate enabled, maxSize:",t,"interval:",r),C3=setInterval(async()=>{if(l){let f;f=await am.stat(e.path),f.size>=l&&(d=await P3(e.path,i))}if(u&&Date.now()-kM>=u&&(d=await P3(e.path,i),kM=Date.now()),n||c){let f=O3(n??"1M")/(1+c);c=0;let m=await am.readdir(i);for(let h of m)try{let p=await am.stat(qM.join(i,h));Date.now()-p.mtimeMs>f&&await am.unlink(qM.join(i,h))}catch(p){_A.error("Error trying to remove log",h,p)}}},a??YNe).unref(),{end(){clearInterval(C3)},getLastRotatedLogPath(){return d}}}o(jNe,"logRotator");async function P3(e,t){let r=D3.get(VNe.LOGGING_ROTATION_COMPRESS),n=qM.join(t,`HDB-${new Date(Date.now()).toISOString().replaceAll(":","-")}.log`);return await am.rename(e,n),r&&(e=n,n+=".gz",await $Ne(FNe(e),kNe(),HNe(n)),await am.unlink(e)),_A.closeLogFile(),_A.notify(`hdb.log rotated, old log moved to ${n}`),n}o(P3,"moveLogFile")});var F3={};we(F3,{RootConfigWatcher:()=>GM});var v3,U3,x3,EA,B3,GM,H3=ce(()=>{v3=w(require("chokidar")),U3=require("node:fs/promises"),x3=w(gt()),EA=require("node:stream"),B3=require("yaml"),GM=class extends EA.EventEmitter{static{o(this,"RootConfigWatcher")}#e;#t;#r;constructor(){super(),this.#e=(0,x3.getConfigFilePath)(),this.#t=v3.default.watch(this.#e,{persistent:!1}).on("add",this.handleChange.bind(this)).on("change",this.handleChange.bind(this)).on("error",this.handleError.bind(this))}handleError(t){this.emit("error",t)}handleChange(){(0,U3.readFile)(this.#e,"utf-8").then(t=>{if(!t)return;let r=(0,B3.parse)(t);if(!this.#r){this.#r=r,this.emit("ready",this.#r);return}this.emit("change",this.#r=r)}).catch(t=>{})}ready(){return(0,EA.once)(this,"ready")}close(){return this.#t.close(),this.#r=void 0,this.emit("close"),this.removeAllListeners(),this}get config(){return this.#r}}});var j=M((g$e,IA)=>{"use strict";var Ca=require("fs-extra"),{workerData:JNe,threadId:QNe,isMainThread:Y3}=require("worker_threads"),eE=require("path"),W3=require("yaml"),z3=require("properties-reader"),$r=(H(),v(W)),k3=qa(),XNe=require("os"),{PACKAGE_ROOT:jM}=ht(),{_assignPackageExport:ZNe}=mi(),{Console:ewe}=require("console"),q3=process.stdout.nativeWrite||(process.stdout.nativeWrite=process.stdout.write),G3=new Map,{join:Pa}=eE,$3=1e4,ur={notify:7,fatal:6,error:5,warn:4,info:3,debug:2,trace:1},twe={STDOUT:"stdOut",STDERR:"stdErr"},E$e=Pa(jM,"logs"),rwe=Pa(jM,"config/yaml/",$r.HDB_DEFAULT_CONFIG_FILE),nwe=1e4,tE,rE,gA,Oo,VM,$M,TA,Ut,Jn,RA,yA,cm,Z_,X_;function SA(e,t,r){e.rotation=t.rotation;let n=t.path;n?t.root||(t.root=eE.dirname(n)):t.root?n=Pa(t.root,VM):(n=Ut.path,t.root||(t.root=eE.dirname(n))),n?e.path=n:console.error("No path for logger",t),e.level=ur[t.level]??Ut?.level??ur.info,j3(e),e.logToStdstreams=t.stdStreams??!1,e.tag=t.tag??(Ut.path===e.path&&r)}o(SA,"updateLogger");function j3(e){let t=e.conditional??(e.conditional={});t.notify=ur.notify>=e.level?e.notify.bind(e):void 0,t.fatal=ur.fatal>=e.level?e.fatal.bind(e):void 0,t.error=ur.error>=e.level?e.error.bind(e):void 0,t.warn=ur.warn>=e.level?e.warn.bind(e):void 0,t.info=ur.info>=e.level?e.info.bind(e):void 0,t.debug=ur.debug>=e.level?e.debug.bind(e):void 0,t.trace=ur.trace>=e.level?e.trace.bind(e):void 0}o(j3,"updateConditional");async function KM(){X_||(X_=new ywe,await X_.ready(),X_.on("change",KM));let e=X_.config,t=e.logging??{};SA(Ut,t),TA=Ut.path,tE=t.console??!1,t.external&&SA(Jn,t.external);for(let r in e){let n=e[r];n.logging?SA(Ut.forComponent(r),n.logging,r):Ut.hasComponent(r)&&SA(Ut.forComponent(r),t,r)}}o(KM,"updateLogSettings");var YM=class extends ewe{static{o(this,"HarperLogger")}constructor(t,r){t.stdout.removeListener=()=>{},t.stderr.removeListener=()=>{},t.stdout.listenerCount=()=>{},t.stderr.listenerCount=()=>{},super(t),this.level=r}trace(...t){bn="trace",this.level<=ur.trace&&super.info(...t),bn="info"}debug(...t){bn="debug",this.level<=ur.debug&&super.info(...t),bn="info"}info(...t){bn="info",this.level<=ur.info&&super.info(...t),bn="info"}warn(...t){bn="warn",this.level<=ur.warn&&super.warn(...t),bn="info"}error(...t){bn="error",this.level<=ur.error&&super.error(...t),bn="info"}fatal(...t){cm=!0;try{bn="fatal",this.level<=ur.fatal&&super.error(...t),bn="info"}finally{cm=!1}}notify(...t){cm=!0;try{bn="notify",this.level<=ur.notify&&super.info(...t),bn="info"}finally{cm=!1}}withTag(t){return Q3(t,!0,this)}forComponent(t){return this}hasComponent(t){return!1}};Z_===void 0&&J3();IA.exports={notify:dwe,fatal:fwe,error:zM,warn:mwe,info:cwe,debug:uwe,trace:lwe,logLevel:Oo,loggerWithTag:Q3,suppressLogging:owe,initLogSettings:J3,logCustomLevel:hwe,closeLogFile:X3,createLogger:bA,logsAtLevel:swe,getLogFilePath:o(()=>TA,"getLogFilePath"),forComponent:o(e=>Ut.forComponent(e),"forComponent"),setMainLogger:Twe,setLogLevel:_we,OUTPUTS:twe,AuthAuditLog:Rwe,start:KM,startOnMainThread:KM,errorToString:Swe};IA.exports.externalLogger={notify(...e){Jn.notify(...e)},fatal(...e){Jn.fatal(...e)},error(...e){Jn.error(...e)},warn(...e){Jn.warn(...e)},info(...e){Jn.info(...e)},debug(...e){Jn.debug(...e)},trace(...e){Jn.trace(...e)},withTag(e){return Jn.withTag(e)},loggerWithTag(e){return Jn.withTag(e)}};ZNe("logger",IA.exports.externalLogger);function swe(e){return ur[Oo]<=ur[e]}o(swe,"logsAtLevel");function J3(e=!1){try{if(Z_===void 0||e){X3();let t=pwe(),r=k3(["ROOTPATH"]);try{Z_=z3(t)}catch(s){if(!r.ROOTPATH||r.ROOTPATH&&!Ca.pathExistsSync(Pa(r.ROOTPATH,$r.HDB_CONFIG_FILE)))throw s}let n;if({level:Oo,configLogPath:$M,toFile:rE,logConsole:tE,rotation:n,toStream:gA}=Ewe(r.ROOTPATH?Pa(r.ROOTPATH,$r.HDB_CONFIG_FILE):Z_.get("settings_path")),VM=$r.LOG_NAMES.HDB,TA=Pa($M,VM),Ut=bA({path:TA,level:Oo,stdStreams:gA,rotation:n}),Jn=Ut.forComponent("external"),Jn.tag=null,Y3)try{require("segfault-handler").registerHandler(Pa($M,"crash.log"))}catch{}}}catch(t){if(Z_=void 0,t.code===$r.NODE_ERROR_CODES.ENOENT||t.code===$r.NODE_ERROR_CODES.ERR_INVALID_ARG_TYPE){let r=k3(Object.keys($r.CONFIG_PARAM_MAP),!0);for(let s in r){let i=$r.CONFIG_PARAM_MAP[s];i&&i.toLowerCase();let a=r[s];if(i===$r.CONFIG_PARAMS.LOGGING_LEVEL){Oo=a;continue}i===$r.CONFIG_PARAMS.LOGGING_CONSOLE&&(tE=i)}let{defaultLevel:n}=gwe();rE=!1,gA=!0,Oo=Oo===void 0?n:Oo,Ut=bA({level:Oo}),Jn=Ut.forComponent("external"),Jn.tag=null;return}throw zM("Error initializing log settings"),zM(t),t}process.env.DEV_MODE&&(gA=!0),iwe()}o(J3,"initLogSettings");var zc=!0;function iwe(){rE&&(process.stdout.write=function(e){return typeof e=="string"&&zc&&tE&&(e=e.toString(),e[e.length-1]===`
|
|
127
|
+
`))}},25).unref()}l.close?.(()=>{if(ei.get(ys.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_DOMAINSOCKET)&&xf()==0)try{RJ(SAe(ei.get(ys.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_DOMAINSOCKET)))}catch{}clearInterval(u),setTimeout(()=>{console.log("forced close server",c,ry),l.cantCleanupProperly||Hi.warn("Had to forcefully exit the thread",ry),process.exit(0)},5e3).unref()})}if(AJ||process.env.DEV_MODE)try{require("inspector").close()}catch(c){Hi.info("Could not close debugger",c)}}}).ref();let r;R_&&!AAe&&(r=IJ()),Promise.resolve(r).then(()=>{if(xf()===0)try{TAe(RAe)}catch(n){console.error("Error displaying start-up log",n)}gJ?.postMessage({type:ys.ITC_EVENT_TYPES.CHILD_STARTED})})});return yJ(t),t}o(bJ,"startServers");function IJ(){let e=[];for(let t in Bf){let r=Bf[t];if(t.includes?.("/")&&xf()==0){hAe(t)&&RJ(t),e.push(new Promise((a,c)=>{r.listen({path:t},()=>{a({port:t,name:r.name,protocol_name:r.protocol_name}),Hi.info("Domain socket listening on "+t)}).on("error",c)}));continue}let n,s=ei.get(ys.CONFIG_PARAMS.HTTP_THREADRANGE);if(s){let a=typeof s=="string"?s.split("-"):s,c=xf();if(c<a[0]||c>a[1])continue}let i;try{let a=t.lastIndexOf(":");a>0?R_?n={fd:R_(+t.slice(a+1).replace(/[\[\]]/g,""),t.slice(0,a))}:n={host:+t.slice(a+1).replace(/[\[\]]/g,""),port:t.slice(0,a)}:R_?n={fd:R_(+t,"::")}:n={port:t}}catch(a){console.error(`Unable to bind to port ${t}`,a);continue}e.push(new Promise((a,c)=>{r.listen(n,()=>{a({port:t,name:r.name,protocol_name:r.protocol_name}),Hi.trace("Listening on port "+t,ry)}).on("error",c)}))}return Promise.all(e)}o(IJ,"listenOnPorts");!nL&&!fAe?.noServerStart&&bJ();function bAe(e,t){let r=(gf(),v(xp)).getComponentName,n;if(t.securePort){SJ(t.securePort,{protocol_name:"TLS",name:r()});let s=gAe("server",t.mtls),i=ei.get("tls");n=_Ae({rejectUnauthorized:!!t.mtls?.required,requestCert:!!t.mtls,noDelay:!0,keepAlive:!0,keepAliveInitialDelay:600,ciphers:i.ciphers??i[0]?.ciphers,SNICallback:s},e),s.initialize(n),Bf[t.securePort]=n}return t.port&&(SJ(t.port,{protocol_name:"TCP",name:r()}),n=mAe(e,{noDelay:!0,keepAlive:!0,keepAliveInitialDelay:600}),Bf[t.port]=n),n}o(bAe,"onSocket")});var J2={};we(J2,{startHTTPThreads:()=>NAe,startSocketServer:()=>lL,updateWorkerIdleness:()=>vJ});async function NAe(e=2,t){ew().catch(r=>Gf.error?.("Error recording hostname for analytics:",r));try{if(t)aL(0,1,!0);else{let{loadRootComponents:r}=ny();if(e===0)return(0,ti.setMainIsWorker)(!0),await sL().startServers(),Promise.resolve([]);await r()}MJ();for(let r=0;r<e;r++)aL(r,e);return Promise.all(LJ)}finally{(0,ti.threadsHaveStarted)()}}function MJ(){let e=(0,CJ.checkMemoryLimit)();e&&!process.env.DEV_MODE&&(console.error(e),oL=setInterval(()=>{Gf.notify(e)},IAe).unref())}function aL(e,t=1,r){if(iL++,(0,ti.startWorker)("server/threads/threadServer.js",{name:XA.HTTP,workerIndex:e,threadCount:t,async onStarted(n){let s=new Promise((a,c)=>{function l(u){u.type===zA.CHILD_STARTED&&(n.removeListener("message",l),a(n))}o(l,"onMessage"),n.on("message",l),n.on("error",c)});LJ.push(s),await s,Ff.push(n),n.expectedIdle=1,n.lastIdle=0,n.requests=1,n.on("message",a=>{if(a.requestId){let c=iy.get(a.requestId);c&&c(a)}}),n.on("exit",i),n.on("shutdown",i);function i(){let a=Ff.indexOf(n);a>-1&&Ff.splice(a,1)}if(o(i,"removeWorker"),Hf){let a=Hf;Hf=[];for(let c of a)DJ[c.localPort](null,c)}}}),r){let n=setInterval(()=>{cL?cL=!1:(clearInterval(n),console.log("shut down dynamic thread due to inactivity"),(0,ti.shutdownWorkers)(),iL=0,setTimeout(()=>{global.gc?.()},5e3))},1e4)}}function lL(e=0,t){if(typeof e=="string")try{(0,oy.existsSync)(e)&&(0,oy.unlinkSync)(e)}catch{}let r;t?t==="ip"?r=wAe:r=OAe(t):r=uL;let n=(0,kf.createServer)({allowHalfOpen:!0,pauseOnConnect:!r.readsData}).listen(e);return n._handle&&(n._handle.onconnection=DJ[e]=function(s,i){r.readsData||(i.reading=!1,i.readStop()),cL=!0,r(i,(a,c)=>{if(!a){if(NJ){let u=i._socket||new kf.Socket({handle:i,writable:!0,readable:!0});NJ.deliverSocket(u,e,c),u.resume()}else iL>0?(Hf.length===0&&setTimeout(()=>{Hf.length>0&&console.warn("Incoming sockets/requests have been queued for workers to start, and no workers have handled them. Check to make sure an error is not preventing workers from starting")},1e4).unref(),i.localPort=e,Hf.push(i)):(console.log("start up a dynamic thread to handle request"),aL(0));it(!1,"socket-routed");return}a.requests++;let l=i.fd;if(l>=0)a.postMessage({port:e,fd:l,data:c});else{let u=i._socket||new kf.Socket({handle:i,writable:!0,readable:!0});DAe(u,a,e)}it(!0,"socket-routed")})},Gf.info(`HarperDB ${PJ.packageJson.version} Server running on port ${e}`)),n.on("error",s=>{console.error("Error in socket server",s)}),process.env._UNREF_SERVER&&n.unref(),n}function uL(e,t){let r,n=0;for(let s of Ff){if(s.threadId===-1)continue;let i=s.expectedIdle/s.requests;if(i>n)r=s;else if(n>=sy)return sy=i,t(r);n=i}sy=0,t(r)}function wAe(e,t){let r={};e.getpeername(r);let n=r.address,s=qf.get(n),i=Date.now();if(s&&s.worker.threadId!==-1)return s.lastUsed=i,t(s.worker);uL(e,a=>{qf.set(n,{worker:a,lastUsed:i}),t(a)})}function OAe(e){let t=new RegExp(`${e}:\\s*(.+)`,"i");return r.readsData=!0,r;function r(n,s){let i=new kf.Socket({handle:n,readable:!0,writable:!0});n._socket=i,i.on("data",a=>{n.readStop();let l=a.toString("latin1").match(t)?.[1],u=qf.get(l),d=Date.now();if(u&&u.worker.threadId!==-1)return u.lastUsed=d,s(u.worker);uL(n,f=>{qf.set(l,{worker:f,lastUsed:d}),s(f,a)})})}o(r,"findByHeaderAffinity")}function vJ(){sy=0;for(let e of Ff)e.expectedIdle=e.recentELU.idle+CAe,e.requests=1;Ff.sort((e,t)=>e.expectedIdle>t.expectedIdle?-1:1)}function DAe(e,t,r){let n=PAe++;t.postMessage({port:r,requestId:n,event:"connection"}),e.on("data",s=>{let i=s.toString("latin1");t.postMessage({port:r,requestId:n,data:i,event:"data"})}).on("close",s=>{t.postMessage({port:r,requestId:n,event:"close",hadError:s})}).on("error",s=>{t.postMessage({port:r,requestId:n,event:"error",error:s})}).on("drain",s=>{t.postMessage({port:r,requestId:n,event:"drain",error:s})}).on("end",()=>{t.postMessage({port:r,requestId:n,event:"end"})}).resume(),iy.set(n,s=>{s.event=="data"&&e.write(Buffer.from(s.data,"latin1")),s.event=="end"&&(e.end(s.data&&Buffer.from(s.data,"latin1")),iy.delete(n)),s.event=="destroy"&&(e.destroy(),iy.delete(n))})}var ti,kf,Gf,oy,OJ,CJ,PJ,Ff,Hf,DJ,NJ,iL,LJ,oL,IAe,cL,sy,wJ,qf,CAe,iy,PAe,GD=ce(()=>{ti=w(rt()),kf=require("net");H();Gf=w(j()),oy=require("fs");io();OJ=require("worker_threads"),CJ=w(of()),PJ=w(ht()),Ff=[],Hf=[],DJ=[],iL=0,LJ=[];OJ.isMainThread&&(process.on("uncaughtException",e=>{e.code==="ECONNRESET"||e.code==="ECONNREFUSED"||e.message!=="write EIO"&&console.error("uncaughtException",e)}),(0,ti.onMessageFromWorkers)(e=>{e.type===QA.RESTART&&oL&&(clearInterval(oL),MJ())}));IAe=6e5;o(NAe,"startHTTPThreads");o(MJ,"licenseWarning");o(aL,"startHTTPWorker");o(lL,"startSocketServer");sy=0;o(uL,"findMostIdleWorker");wJ=36e5,qf=new Map;o(wAe,"findByRemoteAddressAffinity");o(OAe,"makeFindByHeaderAffinity");setInterval(()=>{let e=Date.now();for(let[t,r]of qf)r.lastUsed+wJ<e&&qf.delete(t)},wJ).unref();CAe=1e3;o(vJ,"updateWorkerIdleness");(0,ti.setMonitorListener)(vJ);iy=new Map,PAe=1;o(DAe,"proxySocket")});var dL={};we(dL,{hdbServer:()=>UAe,start:()=>UAe});async function UAe(e){try{Ro.default.debug("In Fastify server"+process.cwd()),Ro.default.debug(`Running with NODE_ENV set as: ${process.env.NODE_ENV}`),Ro.default.debug(`HarperDB server process ${process.pid} starting up.`),global.clustering_on=!1,global.isMaster=UJ.default.isMaster,await xAe();let t=e.securePort>0;$f=BAe(t),await $f.ready(),e||(e={}),e.isOperationsServer=!0;try{Le.http($f.server,e),$f.server.closeIdleConnections||await $f.listen({port:0,host:"::"})}catch(r){throw $f.close(),Ro.default.error(r),Ro.default.error("Error configuring operations server"),r}}catch(t){console.error(`Failed to build server on ${process.pid}`,t),Ro.default.fatal(t),process.exit(1)}}async function xAe(){Ro.default.trace("Configuring HarperDB process."),$J.default.setSchemaDataToGlobal(),await KJ.default.setUsersWithRolesCache(),await YJ.default.getLicense()}function BAe(e){Ro.default.debug(`HarperDB process starting to build ${e?"HTTPS":"HTTP"} server.`);let t=FAe(e),r=(0,xJ.default)(t);r.server.headersTimeout=kAe(),r.setErrorHandler(Fc.serverErrorHandler);let n=HAe();n&&r.register(BJ.default,n),r.register(function(i,a,c){i.setNotFoundHandler(function(l,u){u.sent||u.raw.headersSent||u.raw.writableEnded||r.server.emit("unhandled",l.raw,u.raw)}),c()}),r.register(kJ.default),r.register(FJ.default),r.register(HJ.default,{root:qJ.default.join(GJ.PACKAGE_ROOT,"studio/build-local")}),Vm(r);let s=Bc.default.get(WA.LOCAL_STUDIO_ON);return r.get("/",function(i,a){return!VJ.default.isEmpty(s)&&s.toString().toLowerCase()==="true"?a.sendFile("index.html"):a.sendFile("running.html")}),r.post("/",{preValidation:[Fc.reqBodyValidationHandler,Fc.authHandler],config:{isOperation:!0}},async function(i,a){return i.body?.operation?.startsWith("restart")&&a.header("Connection","close"),(0,Fc.handlePostRequest)(i,a)}),r.get("/health",()=>"HarperDB is running."),Ro.default.debug(`HarperDB process starting up ${e?"HTTPS":"HTTP"} server listener.`),r}function FAe(e){let t=Bc.default.get(A_.OPERATIONSAPI_NETWORK_TIMEOUT),r=Bc.default.get(A_.OPERATIONSAPI_NETWORK_KEEPALIVETIMEOUT);return{bodyLimit:MAe,connectionTimeout:t,keepAliveTimeout:r,forceCloseConnections:!0,return503OnClosing:!1,https:e}}function HAe(){let e=Bc.default.get(A_.OPERATIONSAPI_NETWORK_CORS),t=Bc.default.get(A_.OPERATIONSAPI_NETWORK_CORSACCESSLIST),r;return e&&(e===!0||e.toUpperCase()===vAe)&&(r={origin:!0,allowedHeaders:["Content-Type","Authorization","Accept"],credentials:!1},t&&t.length>0&&t[0]!==null&&t[0]!=="*"&&(r.origin=(n,s)=>s(null,t.indexOf(n)!==-1))),r}function kAe(){return Bc.default.get(A_.OPERATIONSAPI_NETWORK_HEADERSTIMEOUT)??LAe}var UJ,Bc,Ro,xJ,BJ,FJ,HJ,kJ,qJ,GJ,$J,VJ,KJ,YJ,Fc,LAe,MAe,vAe,A_,$f,WJ=ce(()=>{UJ=w(require("cluster")),Bc=w(oe());H();Ro=w(j()),xJ=w(require("fastify")),BJ=w(require("@fastify/cors")),FJ=w(require("@fastify/compress")),HJ=w(require("@fastify/static")),kJ=w(fw()),qJ=w(require("path")),GJ=w(ht()),$J=w(Us()),VJ=w(se()),KJ=w(xn()),YJ=w(of());vr();Fc=w(bR());Uo();Bc.default.initSync();LAe=6e4,MAe=1024*1024*1024,vAe="TRUE",{CONFIG_PARAMS:A_}=W;o(UAe,"operationsServer");o(xAe,"setUp");o(BAe,"buildServer");o(FAe,"getServerOptions");o(HAe,"getCORSOpts");o(kAe,"getHeaderTimeoutConfig")});var EL={};we(EL,{disableNATS:()=>GAe,publishToStream:()=>ly,setNATSReplicator:()=>fL,setPublishToStream:()=>$Ae,setSubscription:()=>_L,start:()=>qAe});function qAe(){b_.default.get(U.CLUSTERING_ENABLED)&&KAe()}function GAe(e=!0){XJ=e}function $Ae(e,t){ly=e,_L=t}function KAe(){if(XJ||process.env._DISABLE_NATS)return;let e=st(),t=Object.keys(e);t.push("system");for(let r of t){let n=e[r];for(let s in n){let i=n[s];fL(s,r,i)}}jl((r,n)=>{fL(r.tableName,r.databaseName,r),n&&eQ(r)}),!zJ&&(zJ=!0)}function fL(e,t,r){if(t==="system"&&YAe.includes(e))return;if(!r)return console.error(`Attempt to replicate non-existent table ${e} from database ${t}`);if(r.sources.some(s=>s?.isNATSReplicator))return;r.sourcedFrom(class extends Hr{static{o(this,"NATSReplicator")}put(i){return n(this.getContext()).addWrite(t,{operation:"put",table:e,id:this.getId(),record:i})}delete(){return n(this.getContext()).addWrite(t,{operation:"delete",table:e,id:this.getId()})}publish(i){return n(this.getContext()).addWrite(t,{operation:"publish",table:e,id:this.getId(),record:i})}patch(i){return n(this.getContext()).addWrite(t,{operation:"patch",table:e,id:this.getId(),record:i})}invalidate(){n(this.getContext()).addWrite(t,{operation:"invalidate",table:e,id:this.getId()})}static defineSchema(i){eQ(i)}static subscribe(){let i=new es;return _L(t,e,i),i}static subscribeOnThisThread(i){return i<(b_.default.get(U.CLUSTERING_LEAFSERVER_STREAMS_MAXINGESTTHREADS)??VAe)}static isEqual(i){return i.isNATSReplicator}static isNATSReplicator=!0;static shouldReceiveInvalidations=!0},{intermediateSource:!0});function n(s){let i=s?.transaction?.nats;if(!i)if(s?.transaction){s.transaction.nats=i=new ay(s.transaction,s);let a=s.transaction;for(;a.next;)a=a.next;a.next=s.transaction.nats,i.user=s.user,i.context=s}else i=ZJ;return i}o(n,"getNATSTransaction")}function eQ(e){let t=b_.default.get(U.CLUSTERING_NODENAME);ly(`${hL.SUBJECT_PREFIXES.TXN}.${e.databaseName}.${e.tableName}`,(0,pL.createNatsTableStreamName)(e.databaseName,e.tableName),void 0,{operation:"define_schema",schema:e.databaseName,table:e.tableName,attributes:e.attributes,__origin:{timestamp:Date.now(),node_name:t}})}var jJ,hL,pL,JJ,QJ,b_,cy,XJ,ly,_L,VAe,ZJ,zJ,YAe,ay,mL,tQ=ce(()=>{Pe();tc();jJ=w(sr()),hL=w(Ot()),pL=w(Zi());zu();JJ=w(Ow()),QJ=w(Cn()),b_=w(oe());H();cy=w(j());o(qAe,"start");o(GAe,"disableNATS");ly=jJ.publishToStream,_L=JJ.setSubscription;o($Ae,"setPublishToStream");VAe=2;o(KAe,"assignReplicationSource");YAe=["hdb_job","hdb_raw_analytics","hdb_info","hdb_license"];o(fL,"setNATSReplicator");o(eQ,"publishSchema");ay=class{constructor(t,r){this.transaction=t;this.options=r}static{o(this,"NATSTransaction")}user;writesByDb=new Map;addWrite(t,r){r.expiresAt=this.context?.expiresAt;let n=this.writesByDb.get(t);n||this.writesByDb.set(t,n=[]),n.push(r)}commit({timestamp:t}){let r=b_.default.get(U.CLUSTERING_NODENAME),n=[];for(let[s,i]of this.writesByDb){let a=[],c=[],l,u;for(let d of i){let f=d.table,m=d.operation=="put"?"upsert":d.operation;l||(cy.trace(`Sending transaction event ${m}`),u=l={operation:m,schema:s,table:f,__origin:{user:this.user?.username,timestamp:t,node_name:r}},l.hash_values=c,m!=="delete"&&m!=="invalidate"&&(l.records=a)),l.table===f&&l.operation===m?(a.push(d.record),c.push(d.id)):u=u.next={operation:m,table:f,id:d.id,record:d.record},d.expiresAt&&(u.expiresAt=d.expiresAt)}l&&n.push(ly(`${hL.SUBJECT_PREFIXES.TXN}.${s}.${l.table}`,(0,pL.createNatsTableStreamName)(s,l.table),void 0,l)?.catch(d=>{throw cy.error("An error has occurred trying to replicate transaction",l,d),d.statusCode=504,d}))}return Promise.all(n)}},mL=class extends ay{static{o(this,"ImmmediateNATSTransaction")}constructor(){super({get timestamp(){return(0,QJ.getNextMonotonicTime)()}})}addWrite(t,r){super.addWrite(t,r),this.commit({})}};ZJ=new mL});async function oQ({clientId:e,user:t,clean:r,will:n,keepalive:s}){let i;if(e&&!r){let a=await gL.get(e,{returnNonexistent:!0});i=new RL(e,t,a),a&&(i.sessionWasPresent=!0)}else{if(e){let a=await gL.get(e);a&&a.delete()}i=new dy(e,t)}return n&&(n.id=e,n.user={username:t?.username},I_.put(n)),s&&(i.keepalive=s,i.receivedPacket()),i}function SL(){return uy++,uy>65500&&(uy=1),uy}function TL(e,t,r){let{topic:n,retain:s}=e;e.data=t,e.async=!0,r.authorize=!0;let i=Ls.getMatch(n,"mqtt");if(!i)throw new Error(`Can not publish to topic ${n} as it does not exist, no resource has been defined to handle this topic`);e.url=i.relativeURL;let a=new Ai(i.relativeURL);a.checkPermission=r.user?.role?.permission??{};let c=i.Resource;return Ft(r,()=>s?t===void 0?c.delete(a,r):c.put(a,e.data,r):c.publish(a,e.data,r))}var nQ,Hc,sQ,iQ,rQ,gL,I_,uy,dy,RL,aQ=ce(()=>{Pe();td();nQ=w(Cn()),Hc=w(j());ol();sQ=w(rt()),iQ=w(sL());vr();zg();rQ=100,gL=ze({database:"system",table:"hdb_durable_session",attributes:[{name:"id",isPrimaryKey:!0},{name:"subscriptions",type:"array",elements:{attributes:[{name:"topic"},{name:"qos"},{name:"startTime"},{name:"acks"}]}}]}),I_=ze({database:"system",table:"hdb_session_will",attributes:[{name:"id",isPrimaryKey:!0},{name:"topic",type:"string"},{name:"data"},{name:"qos",type:"number"},{name:"retain",type:"boolean"},{name:"user",type:"any"}]});(0,sQ.getWorkerIndex)()===0&&(async()=>{await iQ.whenComponentsLoaded,await new Promise(e=>setTimeout(e,2e3));for await(let e of I_.search({})){let t=e.data,r={...e};r.user?.username&&(r.user=await Le.getUser(r.user.username));try{await TL(r,t,r)}catch{(0,Hc.warn)("Failed to publish will",t)}I_.delete(e.id)}})();o(oQ,"getSession");uy=1;o(SL,"getNextMessageId");dy=class{static{o(this,"SubscriptionsSession")}listener;sessionId;user;request;socket;subscriptions=[];awaitingAcks;sessionWasPresent;keepalive;keepaliveTimer;constructor(t,r){this.sessionId=t,this.user=r}async addSubscription(t,r,n){let{topic:s,rh:i,startTime:a}=t,c=s.indexOf("?"),l,u;if(c>-1?(l=s.slice(c),u=s.slice(0,c)):u=s,!u)throw new Error("No topic provided");if(u.indexOf(".")>-1)throw new Error("Dots are not allowed in topic names");let d=this.subscriptions.find(T=>T.topic===s),f;d?(f=i>0,d.end(),this.subscriptions.splice(this.subscriptions.indexOf(d),1)):f=i===2;let m={search:l,async:!0,user:this.user,startTime:a,omitCurrent:f,target:"",checkPermission:this.user?.role?.permission??{}};a&&(0,Hc.trace)("Resuming subscription from",s,"from",a);let h=Ls.getMatch(u,"mqtt");if(!h){let T=new Error(`The topic ${s} does not exist, no resource has been defined to handle this topic`);throw T.statusCode=404,T}m.url=h.relativeURL;let p;if(m.url.indexOf("+")>-1||(p=m.url.indexOf("#"))>-1){let T=m.url.slice(1);if(p--,p>-1&&p!==T.length-1)throw new Error("Multi-level wildcards can only be used at the end of a topic");if(m.isCollection=!0,T.indexOf("+")===T.length-1)m.onlyChildren=!0,m.url="/"+T.slice(0,T.length-1);else{let y=T.split("/"),N;for(let Z=0;Z<y.length;Z++)if(y[Z].indexOf("+")>-1)if(y[Z]==="+")N=!0;else throw new Error("Single-level wildcards can only be used as a topic level (between or after slashes)");if(n&&N)throw new Error("Filters can not be combined");let O=!0;y[y.length-1]==="#"&&(y.length--,O=!1),N&&(n=o(Z=>{let q=Z.id;if(!Array.isArray(q))if(q?.indexOf?.("/")>-1)q=q.split("/");else return!1;if(O&&q.length!==y.length)return!1;for(let Y=0;Y<y.length;Y++)if(y[Y]!=="+"&&y[Y]!==q[Y])return!1;return!0},"filter"));let F=y.indexOf("+");m.url="/"+(F>-1?y.slice(0,F):y).concat("").join("/")}}else m.isCollection=!1;let E=h.path,g=h.Resource,R=await Ft(m,async()=>{let T=this.createContext();T.topic=s,T.retainHandling=i,T.isCollection=m.isCollection;let y=await g.subscribe(m,T);if(!y)return;if(!y[Symbol.asyncIterator])throw new Error(`Subscription is not (async) iterable for topic ${s}`);let N=(async()=>{for await(let O of y)try{let F;if(O.type&&O.type!=="put"&&O.type!=="delete"&&O.type!=="message"&&O.type!=="patch"||n&&!n(O))continue;r?(O.topic=s,F=this.needsAcknowledge(O)):(O.acknowledge?.(),F=SL());let Z=O.id;if(Array.isArray(Z)&&(Z=ed(Z)),Z==null&&(Z=""),await this.listener(E+"/"+Z,O.value,F,t)===!1)break;this.awaitingAcks?.size>rQ?await new Promise(Y=>setTimeout(Y,this.awaitingAcks.size-rQ)):await new Promise(setImmediate)}catch(F){(0,Hc.warn)(F)}})();return y});if(R)return R.topic=s,R.qos=t.qos,this.subscriptions.push(R),R}resume(){}needsAcknowledge(t){let r=SL();return t.acknowledge&&(this.awaitingAcks||(this.awaitingAcks=new Map),this.awaitingAcks.set(r,{acknowledge:t.acknowledge})),r}acknowledge(t){let r=this.awaitingAcks?.get(t);r&&(this.awaitingAcks.delete(t),r.acknowledge())}async removeSubscription(t){let r=this.subscriptions.find(n=>n.topic===t);if(r)return r.end(),this.subscriptions.splice(this.subscriptions.indexOf(r),1),!0}async publish(t,r){return TL(t,r,this.createContext())}createContext(){let t={session:this,socket:this.socket,user:this.user,authorize:!0};return this.request&&(t.request=this.request,t.url=this.request.url,t.headers=this.request.headers),t}setListener(t){this.listener=t}disconnect(t){this.keepaliveTimer&&clearTimeout(this.keepaliveTimer);let r=this.createContext();Ft(r,async()=>{try{if(!t){let n=await I_.get(this.sessionId);n?.doesExist()&&await TL(n,n.data,r)}}finally{await I_.delete(this.sessionId)}}).catch(n=>{(0,Hc.warn)(`Error publishing MQTT will for ${this.sessionId}`,n)});for(let n of this.subscriptions)n.end();this.subscriptions=[]}receivedPacket(){this.keepalive&&(clearTimeout(this.keepaliveTimer),this.keepaliveTimer=setTimeout(()=>{this.socket?.destroy?this.socket.destroy(new Error("Keepalive timeout")):this.socket?.terminate()},this.keepalive*1500))}};o(TL,"publish");RL=class extends dy{static{o(this,"DurableSubscriptionsSession")}sessionRecord;constructor(t,r,n){super(t,r),this.sessionRecord=n||{id:t,subscriptions:[]}}async resume(){for(let t of this.sessionRecord.subscriptions||[])await this.resumeSubscription({omitCurrent:!0,topic:t.topic,qos:t.qos,startTime:t.startTime},!0,t.acks?r=>!t.acks.includes(r.localTime):null)}resumeSubscription(t,r,n){return super.addSubscription(t,r,n)}needsAcknowledge(t){this.awaitingAcks||(this.awaitingAcks=new Map);let r=SL(),n={topic:t.topic,timestamp:t.localTime};return t.acknowledge&&(n.acknowledge=t.acknowledge),this.awaitingAcks.set(r,n),r}acknowledge(t){let r=this.awaitingAcks?.get(t);if(!r)return;this.awaitingAcks?.delete(t),r.acknowledge?.();let n=r.topic;for(let[,s]of this.awaitingAcks)if(s.topic===n&&s.timestamp<r.timestamp){for(let i of this.sessionRecord.subscriptions)if(i.topic===n){i.acks||(i.acks=[]),i.acks.push(r.timestamp),(0,Hc.trace)("Received ack",n,r.timestamp),this.sessionRecord.update();return}}for(let s of this.sessionRecord.subscriptions)s.topic===n&&(s.startTime=r.timestamp);this.sessionRecord.update()}async addSubscription(t,r){await this.resumeSubscription(t,r);let{qos:n,startTime:s}=t;return n>0&&!s&&this.saveSubscriptions(),t.qos}removeSubscription(t){let r=this.subscriptions.find(s=>s.topic===t),n=super.removeSubscription(t);return r.qos>0&&this.saveSubscriptions(),n}saveSubscriptions(){this.sessionRecord.subscriptions=this.subscriptions.map(t=>{let r=t.startTime;return r||(r=t.startTime=(0,nQ.getNextMonotonicTime)()),(0,Hc.trace)("Added durable subscription",t.topic,r),{qos:t.qos,topic:t.topic,startTime:r}}),gL.put(this.sessionRecord)}}});var yL={};we(yL,{bypassAuth:()=>WAe,start:()=>jAe});function WAe(){hQ=!0}function jAe({server:e,port:t,network:r,webSocket:n,securePort:s,requireAuthentication:i}){e.mqtt||(e.mqtt={requireAuthentication:i,sessions:new Set,events:new mQ.EventEmitter},e.mqtt.events.on("error",()=>{}));let a=e.mqtt,c=[],l=r?.mtls;return n&&(c=e.ws((u,d,f,m)=>{if(d.headers.get("sec-websocket-protocol")!=="mqtt")return m(u,d,f);a.events.emit("connection",u),lr.debug?.("Received WebSocket connection for MQTT from",u._socket.remoteAddress);let{onMessage:h,onClose:p}=lQ(u,E=>{u.send(E)},d,Promise.resolve(f).then(()=>d?.user),a);u.on("message",h),u.on("close",p),u.on("error",E=>{lr.info?.("WebSocket error",E)})},{...n})),(t||s)&&c.push(e.socket(async u=>{let d;if(a.events.emit("connection",u),lr.debug?.(`Received ${u.getCertificate?"SSL":"TCP"} connection for MQTT from ${u.remoteAddress}`),l){if(u.authorized)try{let h=l.user;if(h!==null){(h===void 0||h==="Common Name"||h==="CN")&&(h=u.getPeerCertificate().subject.CN);try{d=await e.getUser(h,null,null),(0,Vf.get)(U.LOGGING_AUDITAUTHEVENTS_LOGSUCCESSFUL)&&my.notify?.({username:d?.username,status:fi.SUCCESS,type:ka.AUTHENTICATION,authStrategy:"MQTT mTLS",remoteAddress:u.remoteAddress})}catch(p){throw(0,Vf.get)(U.LOGGING_AUDITAUTHEVENTS_LOGFAILED)&&my.error?.({username:h,status:fi.FAILURE,type:ka.AUTHENTICATION,authStrategy:"mqtt",remoteAddress:u.remoteAddress}),p}}else lr.debug?.("MQTT mTLS authorized connection (mTLS did not authorize a user)","from",u.remoteAddress)}catch(h){a.events.emit("error",h,u),lr.error?.(h)}else if(l.required)return lr.info?.(`Unauthorized connection attempt, no authorized client certificate provided, error: ${u.authorizationError}`),u.end()}!d&&zAe(u.remoteAddress)&&(d=await(0,uQ.getSuperUser)(),lr.debug?.("Auto-authorizing local connection",d?.username));let{onMessage:f,onClose:m}=lQ(u,h=>u.write(h),null,d,a);u.on("data",f),u.on("close",m),u.on("error",h=>{lr.info?.("Socket error",h)})},{port:t,securePort:s,mtls:l})),c}function lQ(e,t,r,n,s){cQ||(cQ=!0,Lh(f=>{fy>0&&f.push({metric:"mqtt-connections",connections:fy,byThread:!0})}));let i;fy++;let a,c={protocolVersion:4},l=(0,hy.parser)({protocolVersion:5});function u(f){l.parse(f)}o(u,"onMessage");function d(){fy--,i||(i=!0,a?.disconnect?.(),s.events.emit("disconnected",a,e),s.sessions.delete(a),jr(!1,"connection","mqtt","disconnect"),lr.debug?.("MQTT connection was closed",e.remoteAddress))}return o(d,"onClose"),l.on("packet",async f=>{try{n?.then&&(n=await n)}catch(y){e.close?.(1008,"Unauthorized"),lr.info?.(y);return}let m=f.cmd;if(a)a.then&&await a;else if(m!=="connect"){lr.info?.("Received packet before connection was established, closing connection"),e?.destroy?e.destroy():e?.terminate();return}let h=f.topic,p=h?.indexOf("/",1),E=p>0?h.slice(0,p):h;it(f.length,"bytes-received",E,R(f),"mqtt");try{switch(a?.receivedPacket?.(),m){case"connect":if(c.protocolVersion=f.protocolVersion,f.username)try{n=await Le.getUser(f.username,f.password.toString(),r),(0,Vf.get)(U.LOGGING_AUDITAUTHEVENTS_LOGSUCCESSFUL)&&my.notify?.({username:n?.username,status:fi.SUCCESS,type:ka.AUTHENTICATION,authStrategy:"MQTT",remoteAddress:e.remoteAddress})}catch(K){return(0,Vf.get)(U.LOGGING_AUDITAUTHEVENTS_LOGFAILED)&&my.error?.({username:f.username,status:fi.FAILURE,type:ka.AUTHENTICATION,authStrategy:"mqtt",remoteAddress:e.remoteAddress}),s.events.emit("auth-failed",f,e,K),jr(!1,"connection","mqtt","connect"),g({cmd:"connack",reasonCode:4,returnCode:134})}if(!n&&s.requireAuthentication)return s.events.emit("auth-failed",f,e),jr(!1,"connection","mqtt","connect"),g({cmd:"connack",reasonCode:4,returnCode:134});try{if(s.authorizeClient?.(f,n),f.will){let K=e.deserialize||(e.deserialize=Fo(r?.headers.get?.("content-type")));f.will.data=f.will.payload?.length>0?K(f.will.payload):void 0,delete f.will.payload}a=oQ({user:n,...f}),a=await a,a.socket=e,r&&(a.request=r),s.sessions.add(a)}catch(K){return lr.error?.(K),s.events.emit("auth-failed",f,e,K),jr(!1,"connection","mqtt","connect"),g({cmd:"connack",reasonCode:K.code||5,returnCode:K.code||128})}s.events.emit("connected",a,e),jr(!0,"connection","mqtt","connect"),g({cmd:"connack",sessionPresent:a.sessionWasPresent,reasonCode:0,returnCode:0});let y=o(async(K,$,le,ue)=>{try{if(i)throw new Error("Session disconnected while trying to send message to",K);let ie=K.indexOf("/",1),me=ie>0?K.slice(0,ie):K;g({cmd:"publish",topic:K,payload:await T($),messageId:le||Math.floor(Math.random()*1e8),qos:ue.qos},me);let De=e._socket??e;return De.writableNeedDrain?new Promise(Me=>De.once("drain",Me)):!De.closed}catch(ie){return lr.error?.(ie),a?.disconnect(),s.sessions.delete(a),!1}},"listener");a.setListener(y),a.sessionWasPresent&&await a.resume();break;case"subscribe":let N=[];for(let K of f.subscriptions){let $;try{let le=await a.addSubscription(K,K.qos>=1);$=le?le.qos||0:c.protocolVersion<5?128:143}catch(le){s.events.emit("error",le,e,K,a),le.statusCode?le.statusCode===500?lr.warn?.(le):lr.info?.(le):lr.error?.(le),$=c.protocolVersion<5?128:le.statusCode===403?135:le.statusCode===404?143:128}N.push($)}await a.committed,g({cmd:"suback",granted:N,messageId:f.messageId});break;case"unsubscribe":{let K=[];for(let $ of f.unsubscriptions)K.push(a.removeSubscription($)?0:17);g({cmd:"unsuback",granted:K,messageId:f.messageId});break}case"pubrel":g({cmd:"pubcomp",messageId:f.messageId,reasonCode:0});return;case"publish":let O=f.qos===2?"pubrec":"puback",F=e.deserialize||(e.deserialize=Fo(r?.headers.get?.("content-type"))),q=(f.payload?.length||0)>0?F(f.payload):void 0,Y;try{Y=await a.publish(f,q)}catch(K){s.events.emit("error",K,e,f,a),lr.warn?.(K),f.qos>0&&g({cmd:O,messageId:f.messageId,reasonCode:128},f.topic);break}f.qos>0&&g({cmd:O,messageId:f.messageId,reasonCode:Y===!1?144:0},f.topic);break;case"pubrec":g({cmd:"pubrel",messageId:f.messageId,reasonCode:0});break;case"pubcomp":case"puback":a.acknowledge(f.messageId);break;case"pingreq":g({cmd:"pingresp"});break;case"disconnect":i=!0,a?.disconnect(!0),s.events.emit("disconnected",a,e),s.sessions.delete(a),jr(!0,"connection","mqtt","disconnect"),lr.debug?.("Received disconnect command, closing MQTT session",e.remoteAddress),e.close?e.close():e.end();break}}catch(y){s.events.emit("error",y,e,f,a),lr.error?.(y),g({cmd:"disconnect"})}function g(y,N){let O=(0,hy.generate)(y,c);t(O),it(O.length,"bytes-sent",N,R(y),"mqtt")}o(g,"sendPacket");function R(y){return y.qos>0?y.cmd+",qos="+y.qos:y.cmd}o(R,"packetMethodName");function T(y){return Ka(y,r)}o(T,"serialize")}),l.on("error",f=>{lr.warn("MQTT parsing error, closing connection:",f.message),e?.destroy?e.destroy():e?.terminate()}),{onMessage:u,onClose:d}}var hy,uQ,Vf,dQ,fQ,mQ,my,lr,hQ,zAe,cQ,fy,pQ=ce(()=>{hy=require("mqtt-packet");aQ();uQ=w(xn());Uo();io();vr();Vf=w(oe());H();dQ=w(hi()),fQ=w(j()),mQ=require("events"),my=(0,dQ.loggerWithTag)("auth-event"),lr=(0,fQ.forComponent)("mqtt"),hQ=(0,Vf.get)(U.AUTHENTICATION_AUTHORIZELOCAL)??process.env.DEV_MODE;o(WAe,"bypassAuth");zAe=o(e=>hQ&&(e.includes("127.0.0.")||e==="::1"),"authorizeLocal");o(jAe,"start");fy=0;o(lQ,"onSocket")});function py(e,t){if(t?.includes(".."))throw new AL(t);let r=t||"/";return(r==="."||r.startsWith("./"))&&(r=`/${e}${r.slice(1)}`),r.startsWith("/")||(r=`/${r}`),r.endsWith("/")||(r=`${r}/`),r}var AL,bL=ce(()=>{AL=class extends Error{static{o(this,"InvalidBaseURLPathError")}constructor(t){super(`urlPath must not contain '..'. Received: '${t}'`)}};o(py,"resolveBaseURLPath")});function _Q(e){if(e.length===0)return".";if(e.length===1)return e[0];let t=e.map(s=>s.split("/")),r=Math.min(...t.map(s=>s.length)),n=[];for(let s=0;s<r;s++){let i=t[0][s];if(t.every(a=>a[s]===i))n.push(i);else break}return n.length===0?".":n.join("/")}var EQ=ce(()=>{o(_Q,"deriveCommonPatternBase")});function _y(e){let t={source:[],onlyFiles:!1,onlyDirectories:!1,ignore:[]},r=o((n,s)=>{typeof s=="string"?n.push(s):Array.isArray(s)&&n.push(...s)},"addToArray");return typeof e=="string"||Array.isArray(e)?r(t.source,e):(r(t.source,e.source),r(t.ignore,e.ignore),t.onlyFiles=e.only==="files",t.onlyDirectories=e.only==="directories"),t}var IL=ce(()=>{o(_y,"deriveGlobOptions")});var gQ,NL,N_,SQ=ce(()=>{bL();EQ();IL();gQ=require("micromatch"),NL=class extends Error{static{o(this,"ComponentInvalidPatternError")}constructor(t){super(`Config 'files' option glob pattern must not contain '..' or start with '/'. Received: '${t}'`),this.name="ComponentInvalidPatternError"}},N_=class{static{o(this,"Component")}globOptions;baseURLPath;patternBases;directory;name;config;commonPatternBase;constructor(t,r,n){this.name=t,this.directory=r,this.config=n,this.baseURLPath=py(this.name,this.config.urlPath),this.globOptions=_y(this.config.files),this.globOptions.source=this.globOptions.source.map(s=>{if(s.includes("..")||s.startsWith("/"))throw new NL(s);return s==="."||s==="./"?"**/*":s}),this.patternBases=this.globOptions.source.map(s=>(0,gQ.scan)(s).base),this.commonPatternBase=_Q(this.patternBases)}}});function TQ(e,t){return new RegExp(`^${e}(/|$)`).test(t)}function Iu(e,t,r){t.startsWith("./")&&(t=t.slice(2));for(let n of e.patternBases)if(n.startsWith("./")&&(n=n.slice(2)),n!==""){if(r==="file"){if(t===n){let s=t.split("/");t=s[s.length-1];break}else if(TQ(n,t)){t=t.slice(n.length+1);break}}if(r==="directory"){if(t===n){t="";break}else if(TQ(n,t)){t=t.slice(n.length+1);break}}}return(0,RQ.join)(e.baseURLPath,t)}var RQ,wL=ce(()=>{RQ=require("node:path");o(TQ,"pathStartsWithBase");o(Iu,"deriveURLPath")});function yQ(e){return typeof e=="string"||Array.isArray(e)||!("files"in e)?{files:e}:e}var gy,AQ,bQ,OL,IQ,NQ,Ey,wQ=ce(()=>{gy=require("node:events");SQ();AQ=w(j()),bQ=w(require("chokidar")),OL=require("node:path"),IQ=require("node:fs/promises");wL();NQ=require("micromatch"),Ey=class extends gy.EventEmitter{static{o(this,"EntryHandler")}#e;#t;#r;ready;constructor(t,r,n,s){super(),this.#e=new N_(t,r,yQ(n)),this.#r=s||AQ.default.loggerWithTag(t),this.ready=(0,gy.once)(this,"ready"),this.#a()}get name(){return this.#e.name}get directory(){return this.#e.directory}#n(...[t,r,n]){if(r===""&&(r="/"),!(0,NQ.isMatch)(r,this.#e.globOptions.source,{ignore:this.#e.globOptions.ignore}))return;let s=(0,OL.join)(this.directory,r);switch(t){case"add":case"change":{let i=Iu(this.#e,r,"file");(0,IQ.readFile)(s).then(a=>{let c={eventType:t,entryType:"file",contents:a,stats:n,absolutePath:s,urlPath:i};this.emit("all",c),this.emit(t,c)});break}case"unlink":{let i=Iu(this.#e,r,"file"),a={eventType:t,entryType:"file",stats:n,absolutePath:s,urlPath:i};this.emit("all",a),this.emit(t,a);break}case"addDir":case"unlinkDir":{let i=Iu(this.#e,r,"directory"),a={eventType:t,entryType:"directory",stats:n,absolutePath:s,urlPath:i};this.emit("all",a),this.emit(t,a);break}}}#s(t){this.emit("error",t)}#i(){this.emit("ready")}async#a(){await this.#t?.close(),this.#t=void 0;let t=this.#e.patternBases.map(r=>(0,OL.join)(this.#e.directory,r));return this.#t=bQ.default.watch(this.#e.commonPatternBase,{cwd:this.#e.directory,persistent:!1,ignored:o(r=>{let n=r.replace(/\\/g,"/"),s=t.map(i=>i.replace(/\\/g,"/"));return n!==this.#e.directory.replace(/\\/g,"/")&&s.every(i=>!n.startsWith(i))},"ignored")}).on("all",this.#n.bind(this)).on("error",this.#s.bind(this)).on("ready",this.#i.bind(this)),this.ready}close(){return this.#t?.close(),this.#t=void 0,this.emit("close"),this.removeAllListeners(),this}update(t){return this.#e=new N_(this.name,this.directory,yQ(t)),this.#a()}};o(yQ,"castConfig")});var Sy,CL=ce(()=>{Sy={rest:!0,graphqlSchema:{files:"*.graphql"},roles:{files:"roles.yaml"},jsResource:{files:"resources.js"},fastifyRoutes:{files:"routes/*.js"},static:{files:"web/**"}}});var Ry,OQ,CQ,PQ,DQ,LQ,PL,DL,LL,ML,vL,Ty,MQ=ce(()=>{Ry=require("events"),OQ=w(require("yaml")),CQ=w(require("chokidar")),PQ=require("node:fs/promises"),DQ=require("util"),LQ=w(j());CL();PL=class extends Error{static{o(this,"OptionsWatcherConfigFileError")}constructor(t,r){super(`Error watching config file ${t}: ${typeof r=="object"&&r!==null&&"message"in r?r.message:r}`),this.name="OptionsWatcherConfigFileError"}},DL=class extends Error{static{o(this,"InvariantUninitializedOptionsWatcherError")}constructor(){super("Invariant: OptionsWatcher has not been initialized yet. This should never happen."),this.name="InvariantUninitializedOptionsWatcherError"}},LL=class extends Error{static{o(this,"InvalidValueTypeError")}constructor(t,r){super(`Invalid value type for key ${t.join(".")}. Expected object, string, array, number, boolean, or undefined. Received ${typeof r}.`),this.name="InvalidValueTypeError"}},ML=class extends Error{static{o(this,"KeyDoesNotExistError")}constructor(t,r){super(`Cannot set property ${t.join(".")} as ${r} does not exist.`),this.name="KeyDoesNotExistError"}},vL=class extends Error{static{o(this,"CannotSetPropertyError")}constructor(t){super(`Cannot set property ${t.join(".")} as parent is not an object.`),this.name="CannotSetPropertyError"}},Ty=class extends Ry.EventEmitter{static{o(this,"OptionsWatcher")}#e;#t;#r;#n;#s;#i;ready;constructor(t,r,n){super(),this.#s=t,this.#e=r,this.#i=n||LQ.default.loggerWithTag(t),this.ready=(0,Ry.once)(this,"ready"),this.#t=CQ.default.watch(r,{persistent:!1}).on("add",this.#a.bind(this)).on("change",this.#a.bind(this)).on("error",this.#d.bind(this)).on("unlink",this.#c.bind(this)).on("ready",this.#a.bind(this))}#a(){(0,PQ.readFile)(this.#e,"utf-8").then(t=>{this.#n=OQ.default.parse(t),this.#n&&this.#s in this.#n?this.#r?this.#f(this.#n[this.#s],this.#r):(this.#r=this.#n[this.#s],this.emit("ready",this.#r)):this.#r&&(this.#r=void 0,this.emit("remove"))}).catch(t=>{if(t instanceof Error&&"code"in t&&t.code==="ENOENT"){this.#n?(this.#o(),this.emit("remove")):(this.#o(),this.emit("ready"));return}this.emit("error",t)})}#d(t){this.emit("error",new PL(this.#e,t))}#c(t){this.#i.warn(`Configuration file ${t} was deleted. Reverting to default configuration. Recreate it to restore the options watcher.`),this.#o(),this.emit("remove")}#o(){this.#n=Sy,this.#r=this.#n[this.#s]}#f(t,r,n=[]){if(!this.#l(r)||!this.#l(t)){this.#u(n,t);return}for(let s of Object.keys(r))s in t||this.#u(n.concat(s),void 0);for(let[s,i]of Object.entries(t)){let a=n.concat(s),c=this.#m(a);if(typeof i!=typeof c||Array.isArray(i)&&!Array.isArray(c)||!Array.isArray(i)&&Array.isArray(c)){this.#u(a,i);continue}if(!Array.isArray(i)&&typeof i=="object"&&i!==null){this.#l(c)?this.#f(i,c,a):this.#u(a,i);continue}(0,DQ.isDeepStrictEqual)(i,c)||this.#u(a,i)}}#l(t){return typeof t=="object"&&t!==null&&t!==void 0&&!Array.isArray(t)}#m(t){let r=this.#r;for(let n of t){if(r==null||typeof r!="object"||!(n in r))return;r=r[n]}return structuredClone(r)}#u(t,r){if(!this.#r)throw new DL;if(!["object","string","array","number","boolean","undefined"].includes(typeof r))throw new LL(t,r);let n=this.#r;for(let s of t.slice(0,-1)){if(n==null||typeof n!="object"||!(s in n))throw new ML(t,s);n=n[s]}if(n==null||typeof n!="object")throw new vL(t);n[t[t.length-1]]=r,this.emit("change",t,r,this.#r)}close(){return this.#t.close(),this.emit("close"),this.removeAllListeners(),this}get(t){return this.#r?this.#m(t):void 0}getAll(){return structuredClone(this.#r)}getRoot(){return this.#n}}});function vQ(){QAe[0]=1}var JAe,QAe,UQ=ce(()=>{Sf();JAe=la.primaryStore.getUserSharedBuffer("restart-needed",new ArrayBuffer(1)),QAe=new Uint8Array(JAe);o(vQ,"requestRestart")});var by,xQ,yy,Ay,BQ=ce(()=>{by=require("node:events");wQ();MQ();xQ=w(j());UQ();yy=class extends Error{static{o(this,"MissingDefaultFilesOptionError")}constructor(){super("No default files option exists. Ensure `files` is specified in config.yaml"),this.name="MissingDefaultFilesOptionError"}},Ay=class extends by.EventEmitter{static{o(this,"Scope")}#e;#t;#r;#n;#s;#i;options;resources;server;ready;constructor(t,r,n,s,i){super(),this.#r=t,this.#t=r,this.#e=n,this.#i=xQ.default.forComponent(this.#r),this.resources=s,this.server=i,this.#s=[],this.ready=(0,by.once)(this,"ready"),this.options=new Ty(t,n,this.#i).on("error",this.#d.bind(this)).on("change",this.#f.bind(this)()).on("ready",this.#a.bind(this))}get logger(){return this.#i}get name(){return this.#r}get directory(){return this.#t}#a(){this.emit("ready")}#d(t){this.emit("error",t)}close(){for(let t of this.#s)t.close();return this.options.close(),this.emit("close"),this.removeAllListeners(),this}#c(t){let r=new Ey(this.#r,this.#t,t,this.#i).on("error",this.#d.bind(this)).on("add",this.#o("add")).on("change",this.#o("change")).on("unlink",this.#o("unlink")).on("addDir",this.#o("addDir")).on("unlinkDir",this.#o("unlinkDir"));return this.#s.push(r),r}#o(t){let r=this;return function(){this.listenerCount("all")>0||this.listenerCount(t)>1||r.requestRestart()}}#f(){let t=this;return o(function(...[n,s,i]){if(n[0]==="files"||n[0]==="urlPath"){if(!t.#n){t.#n=t.#c(i);return}t.#n.update(i);return}this.listenerCount("change")>1||(t.#i.debug(`Options changed: ${n.join(".")}, requesting restart`),t.requestRestart())},"handleOptionsWatcherChange")}#l(){let t=this.options.getAll();if(t&&typeof t=="object"&&t!==null&&!Array.isArray(t)&&"files"in t)return{files:t.files,urlPath:t.urlPath}}handleEntry(t,r){if(t===void 0){if(this.#n)return this.#n;let s=this.#l();if(s)return this.#n=this.#c(s),this.#n;this.emit("error",new yy);return}if(typeof t=="function"){if(this.#n)return this.#n.on("all",t);let s=this.#l();if(s)return this.#n=this.#c(s),this.#n.on("all",t);this.emit("error",new yy);return}let n=this.#c(t);return r?n.on("all",r):n}requestRestart(){this.#i.debug(`Restart requested from ${this.name} scope for ${this.directory}`),vQ()}}});function Nu(e){return typeof e=="string"&&e.trim()!==""}function UL(e){return Array.isArray(e)&&e.length!==0&&e.every(t=>Nu(t))}function qQ(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}async function XAe(e){e.config.root&&w_.default.warn("Resource extension 'root' option is deprecated. Due to backwards compatibility reasons it does not act as assumed. The glob pattern will always be evaluated from the component directory root. The option is only used for the initial root directory handling. Please remove and modify the 'files' glob pattern instead.");let t=[];if(e.config.root&&typeof e.config.files!="string")throw new GL(e);let r=e.config.root;r&&(r.startsWith("/")&&(r=r.slice(1)),r.endsWith("/")||(r+="/"));let n=e.config.files;if(typeof n=="string"&&!n.includes("**/*")&&(n.indexOf("/*")>-1?r=n.slice(0,n.indexOf("/*")+1):n.indexOf("/")>-1&&(r=n.slice(0,n.lastIndexOf("/")+1))),r&&t.push(r),t.length===0){if(qQ(e.config.files)&&e.config.files.only==="files")return!1;t=e.patternBases}let s=!1;for(let i of t){let a=(0,O_.join)(e.directory,i);Iy.isMainThread&&e.module.setupDirectory&&(s=await e.module.setupDirectory(e.baseURLPath,a,e.resources)),e.resources.isWorker&&e.module.handleDirectory&&(s=await e.module.handleDirectory(e.baseURLPath,a,e.resources))}return s}async function GQ(e){let t=!1;if(t=await XAe(e),t)return t;let r=await(0,FQ.default)(e.globOptions.source,{cwd:e.directory,objectMode:!0,onlyFiles:e.globOptions.onlyFiles,onlyDirectories:e.globOptions.onlyDirectories,ignore:e.globOptions.ignore});for(let n of r){let s=(0,O_.join)(e.directory,n.path);if(n.dirent.isDirectory()){let i=Iu(e,n.path,"directory");Iy.isMainThread&&e.module.setupDirectory&&(await e.module.setupDirectory(i,s,e.resources),t=!0),e.resources.isWorker&&e.module.handleDirectory&&(await e.module.handleDirectory(i,s,e.resources),t=!0)}else if(n.dirent.isFile()){let i=Iu(e,n.path,"file"),a=await(0,HQ.readFile)(s);Iy.isMainThread&&e.module.setupFile?(await e.module.setupFile(a,i,s,e.resources),t=!0):e.resources.isWorker&&e.module.handleFile&&(await e.module.handleFile(a,i,s,e.resources),t=!0)}else w_.default.error(`Entry received from glob pattern match for component ${e.name} is neither a file nor a directory:`,n)}return t}var Iy,FQ,w_,O_,HQ,kQ,Ny,ki,xL,BL,FL,HL,kL,qL,GL,$L,VL,$Q=ce(()=>{Iy=require("node:worker_threads"),FQ=w(require("fast-glob")),w_=w(j());bL();IL();O_=require("node:path"),HQ=require("node:fs/promises");wL();kQ=require("micromatch"),Ny=class{static{o(this,"ComponentV1")}config;name;directory;module;resources;globOptions;patternBases;baseURLPath;constructor(t){if(this.config=t.config,this.name=t.name,this.directory=t.directory,this.module=t.module,this.resources=t.resources,!Nu(this.config.files)&&!UL(this.config.files)&&!qQ(this.config.files))throw new xL(this);if(typeof this.config.files=="object"&&!Array.isArray(this.config.files)){if(this.config.files.source===void 0||!UL(this.config.files.source)&&!Nu(this.config.files.source))throw new BL(this);if(this.config.files.only!==void 0&&(typeof this.config.files.only!="string"||!["all","files","directories"].includes(this.config.files.only)))throw new FL(this);if(this.config.files.ignore!==void 0&&!UL(this.config.files.ignore)&&!Nu(this.config.files.ignore))throw new HL(this)}if(this.config.root!==void 0&&!Nu(this.config.root))throw new qL(this);if(this.config.path!==void 0&&!Nu(this.config.path))throw new $L(this);if(this.config.path&&(w_.default.warn("Resource extension 'path' option is deprecated. Please replace with 'urlPath'."),this.config.urlPath=this.config.path),this.config.urlPath!==void 0&&(!Nu(this.config.urlPath)||typeof this.config.urlPath=="string"&&this.config.urlPath.includes("..")))throw new VL(this);this.globOptions=_y(this.config.files),this.globOptions.source=this.globOptions.source.map(r=>{if(r.includes(".."))throw new kL(this,r);return r.startsWith("/")&&(w_.default.warn("Leading '/' in 'files' glob pattern is deprecated. For backwards compatibility purposes, it is currently transformed to the relative path of the component, but in the future will result in an error. Paths are automatically derived from the root of the component directory. Please remove (e.g. '/web/*' -> 'web/*')."),r=r==="/"?".":r.slice(1)),r}),this.patternBases=this.globOptions.source.map(r=>(0,kQ.scan)(r).base),this.baseURLPath=py(this.name,this.config.urlPath)}},ki=class extends Error{static{o(this,"ComponentV1ProcessingError")}constructor(t,r){super(`Component ${r.name} (from ${(0,O_.basename)(r.directory)}) ${t}`)}},xL=class extends ki{static{o(this,"InvalidFilesOptionError")}constructor(t){super("'files' option must be a non-empty string, an array of non-empty strings, or an object.",t)}},BL=class extends ki{static{o(this,"InvalidFilesSourceOptionError")}constructor(t){super("'files' object must have a non-empty 'source' property.",t)}},FL=class extends ki{static{o(this,"InvalidFilesOnlyOptionError")}constructor(t){super("'files.only' option must be one of 'all', 'files', or 'directories'.",t)}},HL=class extends ki{static{o(this,"InvalidFileIgnoreOptionError")}constructor(t){super("'files.ignore' option must be a non-empty string or an array of non-empty strings.",t)}},kL=class extends ki{static{o(this,"InvalidGlobPattern")}constructor(t,r){super(`'files' glob pattern must not contain '..'. Received: '${r}'`,t)}},qL=class extends ki{static{o(this,"InvalidRootOptionError")}constructor(t){super("deprecated 'root' option must be a non-empty string. Consider removing and updating 'files' glob pattern instead.",t)}},GL=class extends ki{static{o(this,"InvalidRootOptionUseError")}constructor(t){super("the 'root' option is deprecated and only supported if 'files' is a singular, non-empty string. Please remove the 'root' option and modify the 'files' glob pattern instead.",t)}},$L=class extends ki{static{o(this,"InvalidPathOptionError")}constructor(t){super("deprecated 'path' option must be a non-empty string. Consider replacing with 'urlPath'.",t)}},VL=class extends ki{static{o(this,"InvalidURLPathOptionError")}constructor(t){super("'urlPath' option must be a non-empty string that must not contain '..'.",t)}};o(Nu,"isNonEmptyString");o(UL,"isArrayOfNonEmptyStrings");o(qQ,"isObject");o(XAe,"handleRoots");o(GQ,"processResourceExtensionComponent")});var xp={};we(xp,{componentErrors:()=>C_,getComponentName:()=>ty,loadComponent:()=>Py,loadComponentDirectories:()=>YQ,setErrorReporter:()=>ebe});function YQ(e,t){t&&(YL=t),e&&(JL=e);let r=[];if((0,vt.existsSync)(KL)){let s=(0,vt.readdirSync)(KL,{withFileTypes:!0});for(let i of s){if(!i.isDirectory()&&!i.isSymbolicLink())continue;let a=i.name,c=(0,qr.join)(KL,a);r.push(Py(c,YL,$A,!1))}}let n=process.env.RUN_HDB_APP;return n&&r.push(Py(n,YL,n,!1,void 0,!!process.env.DEV_MODE)),Promise.all(r).then(()=>{KQ=!0})}function ebe(e){Oy=e}function tbe(e,t){return new Promise((r,n)=>{let s=setTimeout(()=>{la.primaryStore.unlock(e,0),n(new Error("symlinking harperdb module timed out"))},1e4);if(la.primaryStore.attemptLock(e,0,()=>{clearTimeout(s),r()}))try{(0,vt.rmSync)(t,{recursive:!0,force:!0}),(0,vt.existsSync)((0,qr.join)(e,"node_modules"))||(0,vt.mkdirSync)((0,qr.join)(e,"node_modules")),(0,vt.symlinkSync)(XL.PACKAGE_ROOT,t,"dir"),r()}finally{la.primaryStore.unlock(e,0)}})}function WQ(e,t){return e.ready.then(()=>{let r=e.options.get(["timeout"])||t.defaultTimeout||3e4;if(typeof r!="number")throw new Error(`Invalid timeout value for ${e.name}. Expected a number, received: ${typeof r}`);let n,s;if(!la.primaryStore.attemptLock(e.name,0,()=>{clearTimeout(s),n(WQ(e,t))}))return new Promise((a,c)=>{n=a,s=setTimeout(()=>{c(new Error(`Timeout waiting for lock on ${e.name}`))},r+5e3)});let i;return Promise.race([t.handleApplication(e),new Promise((a,c)=>i=setTimeout(()=>c(new Error(`handleApplication timed out after ${r}ms for ${e.name}`)),r))]).finally(()=>{la.primaryStore.unlock(e.name,0),clearTimeout(i)})})}async function Py(e,t,r,n,s,i){let a=(0,vt.realpathSync)(e);if(wy.has(a))return wy.get(a);wy.set(a,!0),s&&(JL=s);try{let c;n&&(C_=new Map);let l=(0,qr.join)(e,"harperdb-config.yaml");(0,vt.existsSync)(l)?c=n?(0,Dy.getConfigObj)():(0,zL.parseDocument)((0,vt.readFileSync)(l,"utf8")).toJSON():!n&&(0,vt.existsSync)(l=(0,qr.join)(e,"config.yaml"))?c=(0,zL.parseDocument)((0,vt.readFileSync)(l,"utf8")).toJSON():c=Sy;try{let m=(0,qr.join)(e,"node_modules","harperdb");(n||((0,vt.existsSync)(m)||!e.startsWith((0,jL.getHdbBasePath)()))&&(!(0,vt.existsSync)(m)||(0,vt.realpathSync)(XL.PACKAGE_ROOT)!==(0,vt.realpathSync)(m)))&&await tbe(e,m)}catch(m){ba.default.error("Error symlinking harperdb module",m),m.code=="EPERM"&&process.platform==="win32"&&ba.default.error('You may need to enable developer mode in "Settings" / "System" (or "Update & Security") / "For developers", in order to enable symlinks so components can use `import from "harperdb"`')}let u=Cy,d={};for(let m in c){Cy=m;let h=c[m];if(C_.set(n?m:(0,qr.basename)(e),!1),!h)continue;let p,E=h.package;try{if(E){let N=e,O;for(;!(0,vt.existsSync)(O=(0,qr.join)(N,"node_modules",m));)if(N=(0,qr.dirname)(N),N.length<(0,jL.getHdbBasePath)().length){O=null;break}if(O)p=await Py(O,t,r,!1),d[m]=!0;else throw new Error(`Unable to find package ${m}:${E}`)}else p=ZAe[m];if(!p)continue;let g=o(N=>(N.origin=r,ze(N)),"ensureTable"),R=h.network||(h.port||h.securePort)&&h,T=R?.securePort||R?.https&&R.port,y=!R?.https&&R?.port;if("handleApplication"in p&&("start"in p||"startOnMainThread"in p||"handleFile"in p||"handleDirectory"in p||"setupFile"in p||"setupDirectory"in p))throw new Error(`Component ${m} has both 'handleComponent' and 'start' or 'startOnMainThread' methods. Please use only one of them.`);if(t.isWorker&&p.handleApplication){p.suppressHandleApplicationWarning!==!0&&ba.default.warn(`Plugin ${m} is using the experimental handleApplication API`);let N=new Ay(m,e,l,t,Le);await WQ(N,p);continue}if(WL.isMainThread&&(p=await p.startOnMainThread?.({server:Le,ensureTable:g,port:y,securePort:T,resources:t,...h})||p,n&&R))for(let N of[y,T])try{if(+N&&!VQ.includes(N)){let O=QL.get(U.HTTP_SESSIONAFFINITY);O&&ba.default.warn("Session affinity is not recommended and may cause memory leaks"),(O||!Wg)&&(VQ.push(N),lL(N,O))}}catch(O){console.error("Error listening on socket",N,O,m)}if(t.isWorker&&(p=await p.start?.({server:Le,ensureTable:g,port:y,securePort:T,resources:t,...h})||p),JL.set(p,!0),(p.handleFile||p.handleDirectory||p.setupFile||p.setupDirectory)&&h.files!=null){let N=new Ny({config:h,name:m,directory:e,module:p,resources:t});d[m]=await GQ(N)}}catch(g){g.message=`Could not load component '${m}' for application '${(0,qr.basename)(e)}' due to: ${g.message}`,Oy?.(g),((0,P_.getWorkerIndex)()===0?console:ba.default).error(g),t.set(h.path||"/",new fl(g),null,!0),C_.set(n?m:(0,qr.basename)(e),g.message)}}if(Cy=u,WL.isMainThread&&!KQ&&i&&(0,P_.watchDir)(e,async()=>YQ()),c.extensionModule||c.pluginModule){let m=await kg((0,qr.join)(e,c.extensionModule||c.pluginModule));return wy.set(a,m),m}let f=Object.values(d);if(f.length>0&&f.every(m=>!m)&&t.isWorker){let m=`${e} did not load any modules, resources, or files, is this a valid component?`;Oy?.(new Error(m)),((0,P_.getWorkerIndex)()===0?console:ba.default).error(m),C_.set((0,qr.basename)(e),m)}for(let[m,h]of Object.entries(d))h||ba.default.warn(`Component ${m} from (${(0,qr.basename)(e)}) did not load any functionality.`)}catch(c){console.error(`Could not load application directory ${e}`,c),c.message=`Could not load application due to ${c.message}`,Oy?.(c),t.set("",new fl(c))}}var vt,qr,WL,zL,QL,XL,ba,P_,jL,Dy,KL,JL,KQ,YL,C_,ZAe,VQ,wy,Oy,Cy,ty,gf=ce(()=>{vt=require("node:fs"),qr=require("node:path"),WL=require("node:worker_threads"),zL=require("yaml"),QL=w(oe()),XL=w(ht());H();EU();n0();wk();vk();Uk();yq();Sj();Ij();wj();ba=w(j());xj();P_=w(rt());$N();vr();Pe();GD();jL=w(oe());WJ();FT();tQ();kn();pQ();Dy=w(gt());Uh();Ob();BQ();$Q();rL();Sf();CL();KL=(0,Dy.resolvePath)(QL.get(U.COMPONENTSROOT)),JL=new Map,C_=new Map;o(YQ,"loadComponentDirectories");ZAe={REST:Jg,rest:Jg,graphql:Pb,graphqlSchema:db,roles:GN,jsResource:VN,fastifyRoutes:iD,login:YN,static:oD,operationsApi:dL,customFunctions:{},http:ey,clustering:EL,replication:uo,authentication:Cp,mqtt:yL,loadEnv:aD,logging:ba.default,dataLoader:uD},VQ=[],wy=new Map;o(ebe,"setErrorReporter");ty=o(()=>Cy,"getComponentName");o(tbe,"symlinkHarperModule");o(WQ,"sequentiallyHandleApplication");o(Py,"loadComponent")});var ny=M((eGe,jQ)=>{var{isMainThread:zQ}=require("worker_threads"),{getTables:rbe,getDatabases:Xqe,table:Zqe}=(Pe(),v(ut)),{loadComponentDirectories:nbe,loadComponent:sbe}=(gf(),v(xp)),{resetResources:ibe}=(td(),v(WU)),obe=kC(),abe=gt(),{dirname:cbe}=require("path"),{getConnection:lbe}=sr(),ube=oe(),{CONFIG_PARAMS:dbe}=(H(),v(W)),{loadCertificates:fbe}=pn(),ZL=new Map;async function mbe(e=!1){!zQ&&ube.get(dbe.CLUSTERING_ENABLED)&&lbe();try{zQ&&await obe()}catch(n){console.error(n)}let t=ibe();rbe(),t.isWorker=e,await fbe(),await sbe(cbe(abe.getConfigFilePath()),t,"hdb",!0,ZL),await nbe(ZL,t);let r=[];for(let[n]of ZL)n.ready&&r.push(n.ready());r.length>0&&await Promise.all(r)}o(mbe,"loadRootComponents");jQ.exports.loadRootComponents=mbe});var rt=M((rGe,Gi)=>{"use strict";pE();var{Worker:hbe,MessageChannel:pbe,parentPort:yo,isMainThread:sM,threadId:_be,workerData:Ao}=require("worker_threads"),{PACKAGE_ROOT:Ebe}=ht(),{join:ZQ,isAbsolute:gbe,extname:Sbe}=require("path"),{server:e4}=(vr(),v(Um)),{watch:Tbe,readdir:Rbe}=require("fs/promises"),{totalmem:JQ}=require("os"),{setHeapSnapshotNearHeapLimit:ybe}=require("v8"),kc=(H(),v(W)),vy=oe(),qi=j(),{randomBytes:Abe}=require("crypto"),{_assignPackageExport:bbe}=mi(),QQ=1024*1024,qc=[],ri=[],Ibe=50,iM=1e4,Nbe="restart",t4="request_thread_info",r4="resource_report",n4="thread_info",s4="added-port",wbe="ack",eM;bbe("threads",ri);Gi.exports={startWorker:tM,restartWorkers:aM,shutdownWorkers:Lbe,workers:qc,setMonitorListener:kbe,onMessageFromWorkers:Mbe,onMessageByType:d4,broadcast:Ube,broadcastWithAcknowledgement:Bbe,setChildListenerByType:Dbe,getWorkerIndex:i4,getWorkerCount:o4,getTicketKeys:c4,setMainIsWorker:Cbe,setTerminateTimeout:Obe,restartNumber:Ao?.restartNumber||1};ri.onMessageByType=d4;ri.sendToThread=function(e,t){if(!t?.type)throw new Error("A message with a type must be provided");let r=ri.find(n=>n.threadId===e);if(r)return r.postMessage(t),!0};Gi.exports.whenThreadsStarted=new Promise(e=>{Gi.exports.threadsHaveStarted=e});vy.get(kc.CONFIG_PARAMS.THREADS_HEAPSNAPSHOTNEARLIMIT)&&ybe(1);var oM;function Obe(e){iM=e}o(Obe,"setTerminateTimeout");function i4(){return Ao?Ao.workerIndex:oM?0:void 0}o(i4,"getWorkerIndex");function o4(){return Ao?Ao.workerCount:oM?1:void 0}o(o4,"getWorkerCount");function Cbe(e){oM=e,Gi.exports.threadsHaveStarted()}o(Cbe,"setMainIsWorker");var a4=1,Ly;function c4(){return Ly||(Ly=sM?Abe(48):Ao.ticketKeys,Ly)}o(c4,"getTicketKeys");Object.defineProperty(e4,"workerIndex",{get(){return i4()}});Object.defineProperty(e4,"workerCount",{get(){return o4()}});var l4={[t4](e,t){Fbe(t)},[r4](e,t){Hbe(t,e)}};function tM(e,t={}){let r=process.constrainedMemory?.()||JQ();r=Math.min(r,JQ(),2e4*QQ);let n=vy.get(kc.CONFIG_PARAMS.THREADS_MAXHEAPMEMORY)??Math.max(Math.floor(r/QQ/(10+(t.threadCount||1)/4)),512),s=Math.min(Math.max(n>>6,16),64),i=[],a=[];for(let u of ri){let d=new pbe;d.existingPort=u,i.push(d),a.push(d.port2)}Sbe(e)||(e+=".js");let c=["--enable-source-maps","--expose-internals"];vy.get(kc.CONFIG_PARAMS.THREADS_HEAPSNAPSHOTNEARLIMIT)&&c.push("--heapsnapshot-near-heap-limit=1");let l=new hbe(gbe(e)?e:ZQ(Ebe,e),{resourceLimits:{maxOldGenerationSizeMb:n,maxYoungGenerationSizeMb:s},execArgv:c,argv:process.argv.slice(2),workerData:{addPorts:a,addThreadIds:i.map(u=>u.existingPort.threadId),workerIndex:t.workerIndex,workerCount:a4=t.threadCount,name:t.name,restartNumber:Gi.exports.restartNumber,ticketKeys:c4()},transferList:a,...t});for(let{port1:u,existingPort:d}of i)d.postMessage({type:s4,port:u,threadId:l.threadId},[u]);return Uy(l,!0),l.unexpectedRestarts=t.unexpectedRestarts||0,l.startCopy=()=>tM(e,t),l.on("error",u=>{qi.error(`Worker index ${t.workerIndex} error:`,u)}),l.on("exit",u=>{qc.splice(qc.indexOf(l),1),!l.wasShutdown&&t.autoRestart!==!1&&(l.unexpectedRestarts<Ibe?(t.unexpectedRestarts=l.unexpectedRestarts+1,tM(e,t)):qi.error(`Thread has been restarted ${l.restarts} times and will not be restarted`))}),l.on("message",u=>{l4[u.type]?.(u,l)}),qc.push(l),Gbe(),t.onStarted&&t.onStarted(l),l.name=t.name,l}o(tM,"startWorker");var Pbe=[kc.THREAD_TYPES.HTTP];async function aM(e=null,t=Math.max(a4>3,1),r=!0){if(sM){try{process.chdir(process.cwd())}catch(a){qi.error("Unable to reestablish current working directory",a)}if(r){let{loadRootComponents:a}=ny();await a()}Gi.exports.restartNumber++,t<1&&(t=t*qc.length);let n=[],s=[];for(let a of qc.slice(0)){if(e&&a.name!==e||a.wasShutdown)continue;qi.trace("sending shutdown request to ",a.threadId),a.postMessage({restartNumber:Gi.exports.restartNumber,type:kc.ITC_EVENT_TYPES.SHUTDOWN}),a.wasShutdown=!0,a.emit("shutdown",{});let c=Pbe.indexOf(a.name)>-1,l=new Promise(u=>{let d=setTimeout(()=>{qi.warn("Thread did not voluntarily terminate, terminating from the outside",a.threadId),a.terminate()},iM*2).unref();a.on("exit",()=>{clearTimeout(d),n.splice(n.indexOf(l)),!c&&r&&a.startCopy(),u()})});if(n.push(l),c&&r){let u=a.startCopy(),d=new Promise(f=>{let m=o(h=>{h.type===kc.ITC_EVENT_TYPES.CHILD_STARTED&&(qi.trace("Worker has started",u.threadId),f(),s.splice(s.indexOf(d)),u.off("message",m))},"startListener");qi.trace("Waiting for worker to start",u.threadId),u.on("message",m)});s.push(d),n.length>=t&&await Promise.race(n),s.length>=t&&await Promise.race(s)}}await Promise.all(n),await Promise.all(s);let{restartService:i}=yc();r&&(e==="http"||!e)&&vy.get(kc.CONFIG_PARAMS.CLUSTERING_ENABLED)&&await i({service:"clustering"})}else yo.postMessage({type:Nbe,workerType:e})}o(aM,"restartWorkers");function Dbe(e,t){l4[e]=t}o(Dbe,"setChildListenerByType");function Lbe(e){return aM(e,1/0,!1)}o(Lbe,"shutdownWorkers");var u4=[];function Mbe(e){u4.push(e)}o(Mbe,"onMessageFromWorkers");var rM=new Map;function d4(e,t){let r=rM.get(e);r||rM.set(e,r=[]),r.push(t)}o(d4,"onMessageByType");var vbe=10;async function Ube(e,t){let r=0;for(let n of ri)try{n.postMessage(e),r++>vbe&&(r=0,await new Promise(setImmediate))}catch(s){qi.error("Unable to send message to worker",s)}t&&m4(e,null)}o(Ube,"broadcast");var My=new Map,xbe=1;function Bbe(e){return new Promise(t=>{let r=0;for(let n of ri)try{let s=xbe++,i=o(()=>{My.delete(s),--r===0&&t(),n!==yo&&--n.refCount===0&&n.unref()},"ackHandler");i.port=n,n.ref(),n.refCount=(n.refCount||0)+1,My.set(e.requestId=s,i),n.hasAckCloseListener||(n.hasAckCloseListener=!0,n.on(n.close?"close":"exit",()=>{for(let[,a]of My)a.port===n&&a()})),n.postMessage(e),r++}catch(s){qi.error("Unable to send message to worker",s)}r===0&&t()})}o(Bbe,"broadcastWithAcknowledgement");function Fbe(e){e.postMessage({type:n4,workers:f4()})}o(Fbe,"sendThreadInfo");function f4(){let e=Date.now();return qc.map(t=>({threadId:t.threadId,name:t.name,heapTotal:t.resources?.heapTotal,heapUsed:t.resources?.heapUsed,externalMemory:t.resources?.external,arrayBuffers:t.resources?.arrayBuffers,sinceLastUpdate:e-t.resources?.updated,...t.recentELU}))}o(f4,"getChildWorkerInfo");function Hbe(e,t){e.resources=t,e.resources.updated=Date.now()}o(Hbe,"recordResourceReport");var nM;function kbe(e){nM=e}o(kbe,"setMonitorListener");var qbe=1e3,XQ=!1;function Gbe(){XQ||(XQ=!0,setInterval(()=>{for(let e of qc){let t=e.performance.eventLoopUtilization(),r;e.lastTotalELU?r=e.performance.eventLoopUtilization(t,e.lastTotalELU):r=t,e.lastTotalELU=t,e.recentELU=r}nM&&nM()},qbe).unref())}o(Gbe,"startMonitoring");var $be=1e3;if(yo&&Ao?.addPorts){Uy(yo);for(let e=0,t=Ao.addPorts.length;e<t;e++){let r=Ao.addPorts[e];r.threadId=Ao.addThreadIds[e],Uy(r)}setInterval(()=>{let e=process.memoryUsage();yo.postMessage({type:r4,heapTotal:e.heapTotal,heapUsed:e.heapUsed,external:e.external,arrayBuffers:e.arrayBuffers})},$be).unref(),eM=o(()=>new Promise((e,t)=>{yo.on("message",r),yo.postMessage({type:t4});function r(n){n.type===n4&&(yo.off("message",r),e(n.workers))}o(r,"receiveThreadInfo")}),"getThreadInfo")}else eM=f4;Gi.exports.getThreadInfo=eM;function Uy(e,t){ri.push(e),e.on("message",r=>{if(r.type===s4)r.port.threadId=r.threadId,Uy(r.port);else if(r.type===wbe){let n=My.get(r.id);n&&n()}else m4(r,e)}).on("close",()=>{ri.splice(ri.indexOf(e),1)}).on("exit",()=>{ri.splice(ri.indexOf(e),1)}),t?e.refCount=100:e.unref()}o(Uy,"addPort");function m4(e,t){for(let n of u4)n(e,t);let r=rM.get(e.type);if(r)for(let n of r)try{n(e,t)}catch(s){qi.error(s)}}o(m4,"notifyMessageListeners");if(sM){let e,t,r=new Set,n=o(async(s,i)=>{i&&(e=i);for(let a of await Rbe(s,{withFileTypes:!0}))a.isDirectory()&&a.name!=="node_modules"&&n(ZQ(s,a.name));try{for await(let{filename:a}of Tbe(s,{persistent:!1}))r.add(a),t&&clearTimeout(t),t=setTimeout(async()=>{e&&await e(),await aM(),console.log("Reloaded HarperDB components, changed files:",Array.from(r)),r.clear()},100)}catch(a){console.warn("Error trying to watch component directory",s,a)}},"watchDir");Gi.exports.watchDir=n,process.env.WATCH_DIR&&n(process.env.WATCH_DIR)}else yo.on("message",async e=>{let{type:t}=e;t===kc.ITC_EVENT_TYPES.SHUTDOWN&&(Gi.exports.restartNumber=e.restartNumber,yo.unref(),setTimeout(()=>{qi.warn("Thread did not voluntarily terminate",_be),process.exit(0)},iM).unref())})});var g4={};we(g4,{onStorageReclamation:()=>D_,runReclamationHandlers:()=>dM,setAvailableSpaceRatioGetter:()=>Kbe});function D_(e,t,r){(r||(0,By.getWorkerIndex)()===(0,By.getWorkerCount)()-1)&&(xy.has(e)||xy.set(e,[]),xy.get(e).push({priority:0,handler:t}),uM||(uM=setTimeout(dM,p4).unref()))}async function dM(){for(let[e,t]of xy)try{let r=await E4(e),n=Vbe/r;for(let s of t){let{priority:i,handler:a}=s;if(s.priority=n,n>1||i>1){let c=a(n>1?n:0);c&&(lM.default.info?.(`Running storage reclamation handler for ${e} with priority ${n}`),await c)}}}catch(r){lM.default.error?.("Error running storage reclamation handlers",r)}uM=setTimeout(dM,p4).unref()}function Kbe(e){E4=e??_4}var cM,By,lM,Fy,h4,xy,Vbe,p4,uM,_4,E4,Hy=ce(()=>{cM=require("node:fs/promises"),By=w(rt()),lM=w(hi());H();Fy=w(oe()),h4=w(se());Fy.default.initSync();xy=new Map,Vbe=Fy.default.get(U.STORAGE_RECLAMATION_THRESHOLD)??.4,p4=(0,h4.convertToMS)(Fy.default.get(U.STORAGE_RECLAMATION_INTERVAL))||36e5;o(D_,"onStorageReclamation");_4=o(async e=>{if(cM.statfs){let t=await(0,cM.statfs)(e);return t.bavail/t.blocks}else return new Promise((t,r)=>{import("hdd-space").then(n=>{n.default(s=>{for(let i of s.parts)if(e.startsWith(i.place))return t(i.free/i.size);return t(1)})})})},"defaultGetAvailableSpaceRatio"),E4=_4;o(dM,"runReclamationHandlers");o(Kbe,"setAvailableSpaceRatioGetter")});var VH={};we(VH,{ACTION_32_BIT:()=>Vy,ACTION_64_BIT:()=>jbe,AUDIT_STORE_OPTIONS:()=>bp,Decoder:()=>zl,HAS_BLOBS:()=>Yr,HAS_CURRENT_RESIDENCY_ID:()=>Yl,HAS_EXPIRATION_EXTENDED_TYPE:()=>x_,HAS_ORIGINATING_OPERATION:()=>U_,HAS_PREVIOUS_RESIDENCY_ID:()=>Wl,REMOTE_SEQUENCE_UPDATE:()=>US,createAuditEntry:()=>Vl,getLastRemoved:()=>Wbe,openAuditStore:()=>Gy,readAuditEntry:()=>wt,removeAuditEntry:()=>$y,setAuditRetention:()=>zbe,transactionKeyEncoder:()=>w4});function Gy(e){let t=e.auditStore=e.openDB(fM.AUDIT_STORE_NAME,{create:!1,...bp});t||(t=e.auditStore=e.openDB(fM.AUDIT_STORE_NAME,bp),T4(t,1)),t.rootStore=e,t.tableStores=[];let r=[];t.addDeleteRemovalCallback=function(l,u,d){return r[l]=d,t.tableStores[l]=u,t.deleteCallbacks=r,{remove(){delete r[l]}}};let n=null,s,i=0,a=hM;D_(t.env.path,l=>{if(i=l,l)return c(100)});function c(l){l&&(a=l),clearTimeout(n);let u=new Promise(d=>{n=setTimeout(async()=>{if(await s,s=u,t.rootStore.status==="closed"||t.rootStore.status==="closing")return;let f=0,m,h;try{for(let{key:p,value:E}of t.getRange({start:1,snapshot:!1,end:Date.now()-mM/(1+i*i)})){try{m=$y(t,p,E)}catch(g){Kf.warn("Error removing audit entry",g)}if(h=p,await new Promise(setImmediate),++f>=Ybe){a=10;break}}await m}finally{f===0?a=Math.min(a<<1,mM/10):(T4(t,h),a>100&&(a=a>>1)),d(void 0),c()}},a).unref()});return u}if(o(c,"scheduleAuditCleanup"),t.scheduleAuditCleanup=c,(0,M_.getWorkerIndex)()===(0,M_.getWorkerCount)()-1&&c(),(0,M_.getWorkerIndex)()===0&&!S4)for(let l of t.getKeys({reverse:!0,limit:1}))l>Date.now()&&(S4=!0,Kf.error("The current time is before the last recorded entry in the audit log. Time reversal can undermine the integrity of data tracking and certificate validation and the time must be corrected."));return t}function $y(e,t,r){let n=Jbe(r),s;if(n&Yr){s=wt(r);let i=e.tableStores[s.tableId];if(i){let a=s.type==="message"?null:i?.getEntry(s.recordId);(!a||a.version!==s.version||!a.value)&&vo(()=>Va(s.getValue(i)),i.rootStore)}}if((n&15)===pM){s=s||wt(r);let i=s.tableId;e.tableStores[s.tableId]?.getEntry(s.recordId)?.version===s.version&&e.deleteCallbacks?.[i]?.(s.recordId,s.version)}return e.remove(t)}function T4(e,t){_M[0]=t,e.put(Symbol.for("last-removed"),O4)}function Wbe(e){let t=e.get(Symbol.for("last-removed"));if(t)return O4.set(t),_M[0]}function zbe(e,t=hM){mM=e,hM=t}function Vl(e,t,r,n,s,i,a,c,l,u,d,f,m){let h=C4[a];if(!h)throw new Error(`Invalid audit entry type ${a}`);let p=1;if(n&&(n>1?Gc.setFloat64(0,n):ni.set(EM),p=9),l){if(l&255)throw new Error("Illegal extended type");p+=3}R(s),R(t),g(r),Gc.setFloat64(p,e),p+=8,l&Yl&&R(u),l&Wl&&R(d),l&x_&&(Gc.setFloat64(p,f),p+=8),l&U_&&R(P4[m]),i?g(i):ni[p++]=0,l?Gc.setUint32(n?8:0,h|l|3221225472):ni[n?8:0]=h;let E=ni.subarray(0,p);if(c)return Buffer.concat([E,c]);return E;function g(T){let y=p;p+=1,p=(0,wu.writeKey)(T,ni,p);let N=p-y-1;N>127?N>16383?(Kf.error("Key or username was too large for audit entry",T),p=y+1,ni[y]=0):(ni.copyWithin(y+2,y+1,p),Gc.setUint16(y,N|32768),p++):ni[y]=N}function R(T){T<128?ni[p++]=T:T<16384?(Gc.setUint16(p,T|32768),p+=2):T<1056964608?(Gc.setUint32(p,T|3221225472),p+=4):(ni[p]=255,Gc.setUint32(p+1,T),p+=5)}}function Jbe(e){let t=0;e[0]==66&&(t=8);let r=e[t];if(r<128)return r;let n=e.dataView||(e.dataView=new zl(e.buffer,e.byteOffset,e.byteLength));return n.position=t,n.readInt()}function wt(e,t=0,r=void 0){try{let n=e.dataView||(e.dataView=new zl(e.buffer,e.byteOffset,e.byteLength));n.position=t;let s;e[n.position]==66&&(s=n.readFloat64());let i=n.readInt(),a=n.readInt(),c=n.readInt(),l=n.readInt(),u=n.position,d=n.position+=l,f=n.readFloat64(),m,h,p,E;if(i&Yl&&(m=n.readInt()),i&Wl&&(h=n.readInt()),i&x_&&(p=n.readFloat64()),i&U_){let y=n.readInt();E=P4[y]}l=n.readInt();let g=n.position,R=n.position+=l,T;return{type:C4[i&7],tableId:c,nodeId:a,get recordId(){return(0,wu.readKey)(e,u,d)},getBinaryRecordId(){return e.subarray(u,d)},version:f,previousLocalTime:s,get user(){return R>g?(0,wu.readKey)(e,g,R):void 0},get encoded(){return t?e.subarray(t,r):e},getValue(y,N,O){if(i&ky||i&L_&&!N)return T||(T=vo(()=>y.decoder.decode(e.subarray(n.position,r)),y.rootStore)),T;if(i&L_&&O)return wN(y.getEntry(this.recordId),O,y)},getBinaryValue(){return i&(ky|L_)?e.subarray(n.position,r):void 0},extendedType:i,residencyId:m,previousResidencyId:h,expiresAt:p,originatingOperation:E}}catch(n){return Kf.error("Reading audit entry error",n,e),{}}}var wu,qy,fM,M_,N4,Kf,ni,Gc,w4,bp,mM,Ybe,_M,O4,hM,S4,ky,L_,R4,pM,y4,A4,b4,I4,Vy,jbe,US,Yl,Wl,U_,x_,Yr,C4,P4,zl,Yi=ce(()=>{wu=require("ordered-binary"),qy=w(oe()),fM=w(Kt());H();M_=w(rt()),N4=w(se());ml();Kf=w(j());Cg();ts();Hy();(0,qy.initSync)();ni=Buffer.alloc(2816),Gc=new DataView(ni.buffer,ni.byteOffset,2816),w4={writeKey(e,t,r){return e===v_?(t.set(v_,r),r+8):typeof e=="number"?((t.dataView||(t.dataView=new DataView(t.buffer,t.byteOffset,t.byteLength))).setFloat64(r,e),r+8):(0,wu.writeKey)(e,t,r)},readKey(e,t,r){return e[t]===66?(e.dataView||(e.dataView=new DataView(e.buffer,e.byteOffset,e.byteLength))).getFloat64(t):(0,wu.readKey)(e,t,r)}},bp={encoding:"binary",keyEncoder:w4},mM=(0,N4.convertToMS)((0,qy.get)(U.LOGGING_AUDITRETENTION))||86400*3,Ybe=1e3,_M=new Float64Array(1),O4=new Uint8Array(_M.buffer),hM=1e4,S4=!1;o(Gy,"openAuditStore");o($y,"removeAuditEntry");o(T4,"updateLastRemoved");o(Wbe,"getLastRemoved");o(zbe,"setAuditRetention");ky=16,L_=32,R4=1,pM=2,y4=3,A4=4,b4=5,I4=6,Vy=14,jbe=15,US=11,Yl=512,Wl=1024,U_=2048,x_=4096,Yr=8192,C4={put:R4|ky,[R4]:"put",delete:pM,[pM]:"delete",message:y4|ky,[y4]:"message",invalidate:A4|L_,[A4]:"invalidate",patch:b4|L_,[b4]:"patch",relocate:I4,[I4]:"relocate"},P4={insert:1,update:2,upsert:3,1:"insert",2:"update",3:"upsert"};o(Vl,"createAuditEntry");o(Jbe,"readAction");o(wt,"readAuditEntry");zl=class extends DataView{static{o(this,"Decoder")}position=0;readInt(){let t;return t=this.getUint8(this.position++),t>=128?t>=192?t===255?(t=this.getUint32(this.position),this.position+=4,t):(t=this.getUint32(this.position-1)&1073741823,this.position+=3,t):(t=this.getUint16(this.position-1)&32767,this.position++,t):t}readFloat64(){try{let t=this.getFloat64(this.position);return this.position+=8,t}catch(t){throw t.message=`Error reading float64: ${t.message} at position ${this.position}`,t}}}});var _0={};we(_0,{ENTRY:()=>Xbe,HAS_EXPIRATION:()=>zy,HAS_RESIDENCY_ID:()=>yM,HAS_STRUCTURE_UPDATE:()=>HS,LAST_TIMESTAMP_PLACEHOLDER:()=>v_,LOCAL_TIMESTAMP:()=>Qbe,METADATA:()=>$d,NEW_TIMESTAMP_PLACEHOLDER:()=>L4,NO_TIMESTAMP:()=>Yy,PENDING_LOCAL_TIME:()=>AM,PREVIOUS_TIMESTAMP_PLACEHOLDER:()=>EM,RecordEncoder:()=>RM,TIMESTAMP_ASSIGN_LAST:()=>eIe,TIMESTAMP_ASSIGN_NEW:()=>M4,TIMESTAMP_ASSIGN_PREVIOUS:()=>v4,TIMESTAMP_PLACEHOLDER:()=>Ky,TIMESTAMP_RECORD_PREVIOUS:()=>gM,entryMap:()=>$c,handleLocalTimeForGets:()=>jy,lastMetadata:()=>dt,recordUpdater:()=>bM,removeEntry:()=>Pu});function rIe(){return H_[0]=H_[0]^64,Zbe.getFloat64(0)}function jy(e,t){let r=e.getEntry;e.readCount=0,e.cachePuts=!1,e.rootStore=t,e.encoder.rootStore=t,e.getEntry=function(a,c){e.readCount++,dt=null;let l=r.call(this,a,c);return l&&(dt&&(l.metadataFlags=dt[$d],l.localTime=dt.localTime,l.residencyId=dt.residencyId,dt.expiresAt>=0&&(l.expiresAt=dt.expiresAt),dt=null),l.value&&$c.set(l.value,l),l.key=a),l};let n=e.get;e.get=function(a,c){dt=null;let l=n.call(this,a,c);return dt&&l&&($c.set(l,dt),dt=null),l};let s=e.getRange;e.getRange=function(a){let c=s.call(this,a);return a.valuesForKey?c.map(l=>l?.value):a.values===!1||a.onlyCount?c:c.map(l=>(dt&&(l.metadataFlags=dt[$d],l.localTime=dt.localTime,l.residencyId=dt.residencyId,dt.expiresAt>=0&&(l.expiresAt=dt.expiresAt),dt=null),l))};let i=e.useReadTransaction();if(i.done(),!i.done.isTracked){let a=i.constructor,c=i.use,l=i.done;a.prototype.use=function(){this.timerTracked||(this.timerTracked=!0,Cu.push(new WeakRef(this))),c.call(this)},a.prototype.done=function(){if(l.call(this),this.isDone)for(let u=0;u<Cu.length;u++){let d=Cu[u].deref();(!d||d.isDone||d.isCommitted)&&Cu.splice(u--,1)}},a.prototype.done.isTracked=!0}return e}function bM(e,t,r){return function(n,s,i,a,c=-1,l,u,d="put",f,m){l==null?Ou=Yy:f?Ou=i?.localTime?gM|v4:Yy:Ou=l?i?.localTime?gM|16384:M4|16384:Yy;let h=u?.expiresAt;if(h>=0&&(c|=zy),F_=c,SM=h,i?.version===a&&l===!1)throw new Error("Must retain local time if version is not changed");let p={version:a,instructedWrite:Ou>0},E,g=0;try{let R=i?.residencyId,T=u?.residencyId;T&&(TM=T,F_|=yM,g|=Yl),R!==T&&(g|=Wl,R||(R=0)),c&zy&&(g|=x_),u?.originatingOperation&&(g|=U_),f&&(p.ifVersion=E=i?.version??null),i&&i.value&&d!=="message"&&i.metadataFlags&Yr&&(!i.localTime||!r.getBinaryFast(i.localTime))&&Va(i.value);let y;if(s!==void 0&&(y=BE(()=>e.put(n,s,p),n,e.rootStore),ll&&(g|=Yr)),l){let N=u?.user?.username;if(m&&(BE(()=>e.encoder.encode(m),n,e.rootStore),ll&&(g|=Yr)),e.encoder.hasStructureUpdate&&(g|=HS,e.encoder.hasStructureUpdate=!1),f&&i?.localTime){let O=i?.localTime,F=r.get(O);if(F){let Z=wt(F).previousLocalTime;return y=r.put(O,Vl(a,t,n,Z,u?.nodeId??server.replication.getThisNodeId(r)??0,N,d,B_,g,T,R,h),{ifVersion:E}),y}}y=r.put(s===void 0?L4:v_,Vl(a,t,n,i?.localTime?1:0,u?.nodeId??server.replication?.getThisNodeId(r)??0,N,d,B_,g,T,R,h,u?.originatingOperation),{instructedWrite:!0,ifVersion:E})}return y}catch(R){throw R.message+=" id: "+n+" options: "+p,R}}}function Pu(e,t,r){if(t)return t.value&&t.metadataFlags&Yr&&!e.auditStore?.getBinaryFast(t.localTime)&&Va(t.value),e.remove(t.key,r)}var D4,Wy,Ky,v_,EM,L4,Qbe,$d,Xbe,H_,Zbe,Yy,M4,eIe,v4,gM,zy,yM,AM,HS,$c,tIe,B_,Ou,F_,SM,TM,dt,RM,Cu,ml=ce(()=>{D4=require("msgpackr");Yi();Wy=w(j());ts();ts();Ky=new Uint8Array([1,1,1,1,4,64,0,0]),v_=new Uint8Array([1,1,1,1,1,0,0,0]),EM=new Uint8Array([1,1,1,1,3,64,0,0]),L4=new Uint8Array([1,1,1,1,0,64,0,0]),Qbe=Symbol("local-timestamp"),$d=Symbol("metadata"),Xbe=Symbol("entry"),H_=new Uint8Array(8),Zbe=new DataView(H_.buffer,0,8),Yy=0,M4=0,eIe=1,v4=3,gM=4,zy=16,yM=32,AM=1,HS=256,$c=new WeakMap,Ou=0,F_=-1,SM=-1,TM=0,dt=null,RM=class extends D4.Encoder{static{o(this,"RecordEncoder")}constructor(t){t.useBigIntExtension=!0;class r{static{o(this,"RecordObject")}getUpdatedTime(){return $c.get(this)?.version}getExpiresAt(){return $c.get(this)?.expiresAt}}t.structPrototype=r.prototype,super(t);let n=this.encode;this.encode=function(i,a){if(Ou||F_>=0){let c=0,l=Ou;l&&(c+=8,Ou=0);let u=F_,d=SM,f=TM;u>=0&&(c+=4,F_=-1,d>=0&&(c+=8,SM=-1),f&&(c+=4,TM=0));let m=tIe=n.call(this,i,a|2048|c);B_=m.subarray((m.start||0)+c,m.end);let h=m.start||0;return l&&(Ky[4]=l,Ky[5]=l>>8,m.set(Ky,h),h+=8),ll&&(u|=Yr),u>=0&&((m.dataView||(m.dataView=new DataView(m.buffer,m.byteOffset,m.byteLength))).setUint32(h,u|Vy<<24),h+=4,d>=0&&((m.dataView||(m.dataView=new DataView(m.buffer,m.byteOffset,m.byteLength))).setFloat64(h,d),h+=8),f&&(m.dataView||(m.dataView=new DataView(m.buffer,m.byteOffset,m.byteLength))).setUint32(h,f)),m}else return B_=n.call(this,i,a),B_};let s=this.saveStructures;this.saveStructures=function(i,a){let c=s.call(this,i,a);return this.hasStructureUpdate=!0,c}}decode(t,r){dt=null;let n=r?.start||0,s=r>-1?r:r?.end||t.length,i=t[n],a=0;try{if(i<32&&s>2){let c=n,l;if(i===2){if(t.copy)t.copy(H_,0,c),c+=8;else for(let m=0;m<8;m++)H_[m]=t[c++];l=rIe(),i=t[c]}let u,d;i<32&&(i===Vy?(a=(t.dataView||(t.dataView=new DataView(t.buffer,t.byteOffset,t.byteLength))).getUint32(c),c+=4):(a=i|t[c+1]<<5,c+=2),a&zy&&(u=(t.dataView||(t.dataView=new DataView(t.buffer,t.byteOffset,t.byteLength))).getFloat64(c),c+=8),a&yM&&(d=(t.dataView||(t.dataView=new DataView(t.buffer,t.byteOffset,t.byteLength))).getUint32(c),c+=4));let f=vo(()=>r?.valueAsBuffer?t.subarray(c,s):super.decode(t.subarray(c,s),s-c),this.rootStore);return dt={localTime:l,[$d]:a,expiresAt:u,residencyId:d},f}return r?.valueAsBuffer?t:vo(()=>super.decode(t,r),this.rootStore)}catch(c){return Wy.error("Error decoding record",c,"data: "+t.slice(0,40).toString("hex")),null}}};o(rIe,"getTimestamp");o(jy,"handleLocalTimeForGets");Cu=[];setInterval(()=>{for(let e=0;e<Cu.length;e++){let t=Cu[e].deref();!t||t.isDone||t.isCommitted?Cu.splice(e--,1):t.notCurrent&&(t.openTimer?(t.openTimer>3&&(t.openTimer>60?(Wy.error("Read transaction detected that has been open too long (over 15 minutes), ending transaction",t),t.done()):Wy.error("Read transaction detected that has been open too long (over one minute), make sure read transactions are quickly closed",t)),t.openTimer++):t.openTimer=1)}},15e3).unref();o(bM,"recordUpdater");o(Pu,"removeEntry")});function wM(e,t,r,n,s,i,a,c){let l=e[0];if(t==="or"){let f=u(l);for(let h=1;h<e.length;h++){let p=e[h],E=u(p);f=f.concat(E)}let m=new Set;return f.filter(h=>{let p=h.key??h;return m.has(p)?!1:(m.add(p),!0)})}else{let f=u(l),m=d(e.slice(1),!0,l.estimated_count);return m.length>0?a(f,m):f}function u(f){return f.conditions?wM(f.conditions,f.operator,r,n,s,i,a,c):jf(f,n,f.descending||s.reverse===!0,r,s.allowFullScan,c,i)}o(u,"executeCondition");function d(f,m,h){return f.map((p,E)=>{if(p.conditions){let T=p.operator==="or",y=d(p.conditions,!T,h);return T?(N,O)=>y.some(F=>F(N,O)):(N,O)=>y.every(F=>F(N,O))}let g=(p.attribute||p[0])===r.primaryKey,R=q_(p,r,i,c,g,h);return m&&E<f.length-1&&h&&(h=dIe(r.primaryStore,p.estimated_count,h)),R}).filter(Boolean)}o(d,"mapConditionsToFilters")}function jf(e,t,r,n,s,i,a){let c=e[0]??e.attribute,l=e[1]??e.value,u=e.comparator;if(l===void 0&&u!=="sort")throw new nn.ClientError(`Search condition for ${c} must have a value`);if(Array.isArray(c)){let y=c[0],N=Io(n.attributes,y);if(N.relationship){if(c.length<2)throw new nn.ClientError("Can not directly query a relational attribute, must query an attribute within the target table");let O=N.definition?.tableClass||N.elements?.definition?.tableClass,F=new Map,Z=jf({attribute:c.length>2?c.slice(1):c[1],value:l,comparator:u},t,r,O,s,F);if(N.relationship.to){i[c[0]]=F;let q=!!Io(O.attributes,N.relationship.to)?.elements;Z=aIe(Z,N,O.primaryStore,q,F)}if(N.relationship.from){let q=o(Y=>(Y?.key!==void 0&&(Y=Y.key),jf({attribute:N.relationship.from,value:Y},t,r,n,s,F)),"searchEntry");N.elements?(i[c[0]]=F,Z=cIe(Z,N,O.primaryStore,F,q)):Z=Z.flatMap(q)}return Z}else if(c.length===1)c=c[0];else throw new nn.ClientError("Unable to query by attribute "+JSON.stringify(c))}let d=c===n.primaryKey||c==null,f=d?n.primaryStore:n.indices[c],m,h,p,E;l instanceof Date&&(l=l.getTime());let g;switch(OM[u]||u){case"lt":m=!0,h=l;break;case"le":m=!0,h=l,p=!0;break;case"gt":m=l,E=!0;break;case"ge":m=l;break;case"prefix":Array.isArray(l)?l[l.length-1]!=null&&(l=l.concat(null)):l=[l,null],m=l,h=l.slice(0),h[h.length-1]=bo.MAXIMUM_KEY;break;case"starts_with":m=l.toString(),h=l+"\uFFFF";break;case"between":case"gele":case"gelt":case"gtlt":case"gtle":m=l[0],m instanceof Date&&(m=m.getTime()),h=l[1],h instanceof Date&&(h=h.getTime()),p=u==="gele"||u==="gtle"||u==="between",E=u==="gtlt"||u==="gtle";break;case"equals":case void 0:m=l,h=l,p=!0;break;case"ne":if(l===null){m=l,E=!0;break}case"sort":case"contains":case"ends_with":m=!0,g=!0;break;default:throw new nn.ClientError(`Unknown query comparator "${u}"`)}let R;if(typeof m=="string"&&m.length>si.MAX_SEARCH_KEY_LENGTH&&(m=m.slice(0,si.MAX_SEARCH_KEY_LENGTH)+si.OVERFLOW_MARKER,E=!1,R=q_(e,n,null,i,d)),typeof h=="string"&&h.length>si.MAX_SEARCH_KEY_LENGTH&&(h=h.slice(0,si.MAX_SEARCH_KEY_LENGTH)+si.OVERFLOW_MARKER,p=!0,R=R??q_(e,n,null,i,d)),r){let y=m;m=h,h=y,y=!E,E=!p,p=y}if(!f||f.isIndexing||g||l===null&&!f.indexNulls){if(s===!1&&!f)throw new nn.ClientError(`"${c}" is not indexed, can not search for this attribute`,404);if(s===!1&&g)throw new nn.ClientError(`Can not use ${u||"equal"} operator without combining with a condition that uses an index, can not search for attribute ${c}`,403);if(f?.isIndexing)throw new nn.ServerError(`"${c}" is not indexed yet, can not search for this attribute`,503);if(l===null&&f&&!f.indexNulls)throw new nn.ClientError(`"${c}" is not indexed for nulls, index needs to be rebuilt to search for nulls, can not search for this attribute`,400);if(R=R??q_(e,n,null,i,d),!R)throw new nn.ClientError(`Unknown search operator ${e.comparator}`)}let T={start:m,end:h,inclusiveEnd:p,exclusiveStart:E,values:!0,versions:d,transaction:t,reverse:r};if(d){let y=f.getRange(T).map(R?function({key:N,value:O}){return this?.isSync?O&&R(O)?N:Vc.SKIP:new Promise((F,Z)=>setImmediate(()=>{try{F(O&&R(O)?N:Vc.SKIP)}catch(q){Z(q)}}))}:N=>N.value==null&&!(N.metadataFlags&(Wn|Du))?Vc.SKIP:(a?._freezeRecords&&Object.freeze(N.value),N));return y.hasEntries=!0,y}else return f?f.customIndex?f.customIndex.search(e,a).map(y=>{if(typeof y=="object"&&y){let{key:N,...O}=y,F=n.primaryStore.getEntry(N);return a?._freezeRecords&&Object.freeze(F?.value),{...O,...F}}return y}):f.getRange(T).map(R?function({key:y,value:N}){let O;return typeof y=="string"&&y.length>si.MAX_SEARCH_KEY_LENGTH?O=n.primaryStore.get(N):O={[c]:y},this.isSync?R(O)?N:Vc.SKIP:new Promise((F,Z)=>setImmediate(()=>{try{F(R(O)?N:Vc.SKIP)}catch(q){Z(q)}}))}:({value:y})=>y):n.primaryStore.getRange(r?{end:!0,transaction:t,reverse:!0}:{start:!0,transaction:t}).map(function({key:y,value:N}){return this.isSync?N&&R(N)?y:Vc.SKIP:new Promise((O,F)=>setImmediate(()=>{try{O(N&&R(N)?y:Vc.SKIP)}catch(Z){F(Z)}}))})}function Io(e,t){if(Array.isArray(t))if(t.length>1){let r=Io(e,t[0]),n=(r?.definition?.tableClass||r?.elements?.definition?.tableClass)?.attributes??r?.properties;return n?Io(n,t.slice(1)):void 0}else t=t.toString();else typeof t!="string"&&(t=t.toString());return e.find(r=>r.name===t)}function aIe(e,t,r,n,s){return new e.constructor({[Symbol.iterator](){let i;return s.hasMappings=!0,{next(){if(!i){let c=t.relationship.to,l=o((u,d)=>{let f=s.get(u);f?f.push(d):s.set(u,f=[d])},"addEntry");for(let u of e){let d=u.value??r.get(u.key??u),f=d?.[c];if(f!=null&&!s.filters?.some(m=>!m(d)))if(n)for(let m=0;m<f.length;m++)l(f[m],u);else l(f,u)}return i=s.keys()[Symbol.iterator](),this.next()}let a=i.next();return a.done?a:{value:a.value}},return(){if(i?.return)return i.return()}}}})}function cIe(e,t,r,n,s){return new e.constructor({[Symbol.iterator](){let i,a,c=new Set;return{next(){let l;if(a)for(;l=a.next(),!l.done;){let u=l.value;if(!c.has(u))return c.add(u),l}if(!i){let u=new Set;n.fromRecord=d=>d[t.relationship.from]?.filter?.(f=>u.has(f));for(let d of e){if(n.filters){let f=r.get(d);if(n.filters.some(m=>!m(f)))continue}u.add(d)}return i=u[Symbol.iterator](),this.next()}do{let u=i.next();return u.done?u:(a=s(u.value)[Symbol.iterator](),this.next())}while(!0)},return(){return a?.return?.()},throw(){return a?.throw?.()}}}})}function q_(e,t,r,n,s,i){let a=e.comparator,c=e[0]??e.attribute,l=e[1]??e.value;if(Array.isArray(c)){if(c.length===0)return()=>!0;if(c.length===1)c=c[0];else if(c.length>1){let d=c[0],f=Io(t.attributes,d),m=f.definition?.tableClass||f.elements.definition?.tableClass,h=n?.[d],p=q_({attribute:c.length>2?c.slice(1):c[1],value:l,comparator:a},m,r,h?.[d]?.joined,c[1]===m.primaryKey,i);if(!p)return;if(h){h.filters||(h.filters=[]),h.filters.push(p);return}let E=t.propertyResolvers?.[d];E.to&&(p.to=E.to);let g,R=o((y,N)=>{let O,F;return E?E.returnDirect?(O=E(y,r,N),F=dt):(F=E(y,r,N,!0),Array.isArray(F)?(O=F.map(Z=>Z.value),F=null):O=F?.value):O=y[d],{subObject:O,subEntry:F}},"getSubObject"),T=o((y,N)=>{if(E&&p.idFilter){if(!g)if(p.idFilter.idSet?.size===1){for(let Y of p.idFilter.idSet)e={attribute:E.from??t.primaryKey,value:Y};g=u(E.from??t.primaryKey,p.idFilter,!0,!0)}else g=u(E.from??t.primaryKey,p.idFilter,!1,!0);let q=g(y);return g.idFilter&&(T.idFilter=g.idFilter),q}let{subObject:O,subEntry:F}=R(y,N);return O?Array.isArray(O)?(!n?.[d]&&n&&(n[d]={fromRecord(q){let Y=R(q).subObject;return Array.isArray(Y)?Y.filter(p).map(K=>K[m.primaryKey]):Y}}),O.some(p)):p(O,F):!1},"recordFilter");return T}}switch(l instanceof Date&&(l=l.getTime()),OM[a]||a){case si.SEARCH_TYPES.EQUALS:case void 0:return u(c,d=>d===l,!0);case"contains":return u(c,d=>d?.toString().includes(l));case"ends_with":return u(c,d=>d?.toString().endsWith(l));case"starts_with":return u(c,d=>typeof d=="string"&&d.startsWith(l),!0);case"prefix":return Array.isArray(l)?l[l.length-1]==null&&(l=l.slice(0,-1)):l=[l],u(c,d=>{if(!Array.isArray(d))return!1;for(let f=0,m=l.length;f<m;f++)if(d[f]!==l[f])return!1;return!0},!0);case"between":return l[0]instanceof Date&&(l[0]=l[0].getTime()),l[1]instanceof Date&&(l[1]=l[1].getTime()),u(c,d=>(0,bo.compareKeys)(d,l[0])>=0&&(0,bo.compareKeys)(d,l[1])<=0,!0);case"gt":return u(c,d=>(0,bo.compareKeys)(d,l)>0);case"ge":return u(c,d=>(0,bo.compareKeys)(d,l)>=0);case"lt":return u(c,d=>(0,bo.compareKeys)(d,l)<0);case"le":return u(c,d=>(0,bo.compareKeys)(d,l)<=0);case"ne":return u(c,d=>(0,bo.compareKeys)(d,l)!==0,!1,!0);case"sort":return()=>!0;default:throw new nn.ClientError(`Unknown query comparator "${a}"`)}function u(d,f,m,h){let p;m=m&&!s&&t?.indices[d]&&i>3,m&&(e.estimated_count==null&&Qy(t)(e),p=e.estimated_count>>4,(isNaN(p)||p>=i)&&(m=!1));let E=0,g=3;function R(T){let y=T[d],N;if(typeof y!="object"||!y||h?N=f(y):Array.isArray(y)?N=y.some(f):y instanceof Date&&(N=f(y.getTime())),m&&(g++,!N&&!R.idFilter&&++E/g*i>p)){let O=jf(e,r.transaction.getReadTxn(),!1,t),F;R.to?F=O.flatMap(q=>t.primaryStore.get(q)[R.to]):F=O.map(Jf);let Z=new Set(F);R.idFilter=q=>Z.has(Jf(q)),R.idFilter.idSet=Z}return N}return o(R,"recordFilter"),s&&(R.idFilter=f),R}o(u,"attributeComparator")}function Qy(e){function t(r){if(r.estimated_count===void 0){if(r.conditions){let s;if(r.operator==="or"){s=0;for(let i of r.conditions)t(i),s+=i.estimated_count}else{s=1/0;for(let i of r.conditions)t(i),s=isFinite(s)?s*i.estimated_count/Ia(e.primaryStore):i.estimated_count}return r.estimated_count=s,r.estimated_count}let n=r.comparator||r.search_type;if(n=OM[n]||n,n===si.SEARCH_TYPES.EQUALS||!n){let s=r[0]??r.attribute;if(s==null||s===e.primaryKey)r.estimated_count=1;else if(Array.isArray(s)&&s.length>1){let i=Io(e.attributes,s[0]),a=i.definition?.tableClass||i.elements.definition?.tableClass,c=Qy(a)({value:r.value,attribute:s.length>2?s.slice(1):s[1],comparator:"equals"}),l=e.indices[i.relationship.from];r.estimated_count=c+(l?c*Ia(e.indices[i.relationship.from])/(Ia(a.primaryStore)||1):c)}else{let i=e.indices[s];r.estimated_count=i?i.getValuesCount(r[1]??r.value):1/0}}else if(n==="contains"||n==="ends_with"||n==="ne"){let s=r[0]??r.attribute,i=e.indices[s];r.value===null&&n==="ne"?r.estimated_count=Ia(e.primaryStore)-(i?i.getValuesCount(null):0):r.estimated_count=1/0}else if(n==="starts_with"||n==="prefix")r.estimated_count=iIe*Ia(e.primaryStore)+1;else if(n==="between")r.estimated_count=sIe*Ia(e.primaryStore)+1;else if(n==="sort"){let s=r[0]??r.attribute,i=e.indices[s];i?.customIndex?.estimateCountAsSort?r.estimated_count=i.customIndex.estimateCountAsSort(r):r.estimated_count=Ia(e.primaryStore)+1}else{let s=r[0]??r.attribute,i=e.indices[s];i?.customIndex?.estimateCount?r.estimated_count=i.customIndex.estimateCount(r.value):r.estimated_count=nIe*Ia(e.primaryStore)+1}typeof r.descending=="boolean"&&(r.estimated_count/=2)}return r.estimated_count}return o(t,"estimateConditionForTable"),t}function Qg(e,t){if(e)if(Na=e,Yf.lastIndex=0,lIe.test(e))try{if(t&&(t.conditions=[]),$i=t??new zf,k_($i,""),Gr!==Na.length&&Xt("Unable to parse query, unexpected end of query"),$i.parseErrorMessage&&($i.parseError=new IM(t.parseErrorMessage),!t))throw $i.parseError;return $i}catch(r){if(r.statusCode=400,r.message=`Unable to parse query, ${r.message} at position ${Gr} in '${Na}'`,$i.parseErrorMessage&&(r.message+=", "+$i.parseErrorMessage),t)t.parseError=r;else throw r}else return t??new URLSearchParams(e)}function Xt(e){let t=`${e} at position ${Gr}`;$i.parseErrorMessage=$i.parseErrorMessage?$i.parseErrorMessage+", "+t:t}function k_(e,t){let r=Yf,n,s,i,a,c,l=decodeURIComponent,u;for(;n=r.exec(Na);){Gr=r.lastIndex;let[,d,f]=n;a?(d&&Xt(`expected operator, but encountered '${d}'`),a=!1,c=!1):c=!0;let m;switch(f){case"=":s!=null?(d.length<=2?i=d:Xt(`invalid FIQL operator ${d}`),l=U4):(l=decodeURIComponent,i="equals",d||Xt("attribute must be specified before equality comparator"),s=Wf(d));break;case"==":case"!=":case"<":case"<=":case">":case">=":case"===":case"!==":i=oIe[f],l=NM[i]?U4:decodeURIComponent,d||Xt(`attribute must be specified before comparator ${f}`),s=Wf(d);break;case"&=":case"|=":case"|":case"&":case"":case void 0:if(s==null)s===void 0&&(t&&Xt(`expected '${t}', but encountered ${f[0]?"'"+f[0]+"'":"end of string"}}`),Xt(`no comparison specified before ${f?"'"+f+"'":"end of string"}`));else{e.conditions||Xt("conditions/comparisons are not allowed in a property list");let p={comparator:i,attribute:s||null,value:l(d)};if(i==="eq"&&x4(p,d),s===""){let E=e.conditions[e.conditions.length-1];E.chainedConditions=E.chainedConditions||[],E.chainedConditions.push(p),E.operator=u}else Jy(e,u),e.conditions.push(p)}f==="&"?(u="and",s=void 0):f==="|"?(u="or",s=void 0):f==="&="?(u="and",s=""):f==="|="&&(u="or",s="");break;case",":e.conditions?Xt("conditions/comparisons are not allowed in a property list"):e.push(Wf(d)),s=void 0;break;case"(":Yf.lastIndex=Gr;let h=k_(d?[]:new zf,")");switch(d){case"":Jy(e,u),e.conditions.push(h);break;case"limit":switch(h.length){case 1:e.limit=+h[0];break;case 2:e.offset=+h[0],e.limit=h[1]-e.offset;break;default:Xt("limit must have 1 or 2 arguments")}break;case"select":Array.isArray(h[0])&&h.length===1&&!h[0].name?(e.select=h[0],e.select.asArray=!0):h.length===1?e.select=h[0]:h.length===2&&h[1]===""?e.select=h.slice(0,1):e.select=h;break;case"group-by":Xt("group by is not implemented yet");case"sort":e.sort=B4(h);break;default:Xt(`unknown query function call ${d}`)}Na[Gr]===","?r.lastIndex=++Gr:a=!0,s=null;break;case"{":e.conditions&&Xt("property sets are not allowed in a queries"),d||Xt("property sets must have a defined parent property name"),Yf.lastIndex=Gr,m=k_([],"}"),m.name=d,e.push(m),Na[Gr]===","?r.lastIndex=++Gr:a=!0;break;case"[":if(Yf.lastIndex=Gr,d?(m=k_(new zf,"]"),m.name=d):m=k_(e.conditions?new zf:[],"]"),e.conditions)if(Jy(e,u),Na[Gr]==="="){l=decodeURIComponent,i="equals",s=Wf(d),r.lastIndex=++Gr;break}else e.conditions.push(m),s=null;else e.push(m);Na[Gr]===","?r.lastIndex=++Gr:a=!0;break;case")":case"]":case"}":if(t===f[0]){if(e.conditions)if(s){let p={comparator:i||"equals",attribute:s,value:l(d)};i==="eq"&&x4(p,d),Jy(e,u),e.conditions.push(p)}else d&&Xt("no attribute or comparison specified");else(d||e.length>0&&c)&&e.push(Wf(d));return e}else Xt(t?`expected '${t}', but encountered '${f[0]}'`:`unexpected token '${f[0]}'`);default:Xt(`unexpected operator '${f}'`)}if(t!==")"&&(r=s?uIe:Yf,r.lastIndex=Gr),Gr===Na.length)return e}t&&Xt(`expected '${t}', but encountered end of string`)}function Jy(e,t){e.conditions.length>0&&(e.operator?e.operator!==t&&Xt("Can not mix operators within a condition grouping"):e.operator=t)}function Wf(e){return e.indexOf(".")>-1?e.split(".").map(Wf):decodeURIComponent(e)}function U4(e){if(e==="null")return null;if(e.indexOf(":")>-1){let[t,r]=e.split(":");if(t==="number")return r[0]==="$"?parseInt(r.slice(1),36):+r;if(t==="boolean")return r==="true";if(t==="date")return new Date(isNaN(r)?decodeURIComponent(r):+r);if(t==="string")return decodeURIComponent(r);throw new nn.ClientError(`Unknown type ${t}`)}return decodeURIComponent(e)}function x4(e,t){if(t.indexOf("*")>-1)if(t.endsWith("*"))e.comparator="starts_with",e.value=decodeURIComponent(t.slice(0,-1));else throw new nn.ClientError("wildcard can only be used at the end of a string")}function B4(e){let t=F4(e[0]);return e.length>1&&(t.next=B4(e.slice(1))),t}function F4(e){if(Array.isArray(e)){let t=F4(e[0]);return e[0]=t.attribute,t.attribute=e,t}if(typeof e=="string")switch(e[0]){case"-":return{attribute:e.slice(1),descending:!0};case"+":return{attribute:e.slice(1),descending:!1};default:return{attribute:e,descending:!1}}Xt(`Unknown sort type ${e}`)}function Jf(e){return Array.isArray(e)?e.join("\0"):e}function Ia(e){let t=Date.now();return(e.estimatedEntryCountExpires||0)<t&&(e.estimatedEntryCount=e.getStats().entryCount,e.estimatedEntryCountExpires=t+1e4),e.estimatedEntryCount}function dIe(e,t,r){return t*r/Ia(e)}var nn,si,bo,Vc,nIe,sIe,iIe,oIe,NM,OM,IM,lIe,Yf,uIe,Gr,$i,Na,zf,Xg=ce(()=>{nn=w(ge()),si=w(Kt()),bo=require("ordered-binary"),Vc=require("lmdb");hR();ml();nIe=.3,sIe=.1,iIe=.05,oIe={"<":"lt","<=":"le",">":"gt",">=":"ge","!=":"ne","==":"eq","===":"equals","!==":"not_equal"},NM={lt:!0,le:!0,gt:!0,ge:!0,ne:!0,eq:!0};o(wM,"executeConditions");o(jf,"searchByIndex");o(Io,"findAttribute");o(aIe,"joinTo");o(cIe,"joinFrom");OM={eq:"equals",greater_than:"gt",greaterThan:"gt",greater_than_equal:"ge",greaterThanEqual:"ge",less_than:"lt",lessThan:"lt",less_than_equal:"le",lessThanEqual:"le",not_equal:"ne",notEqual:"ne",equal:"equals",sw:"starts_with",startsWith:"starts_with",ew:"ends_with",endsWith:"ends_with",ct:"contains",">":"gt",">=":"ge","<":"lt","<=":"le","...":"between"};o(q_,"filterByType");o(Qy,"estimateCondition");IM=class extends nn.Violation{static{o(this,"SyntaxViolation")}},lIe=/[()[\]|!<>.]|(=\w*=)/,Yf=/([^?&|=<>!([{}\]),]*)([([{}\])|,&]|[=<>!]*)/g,uIe=/([^&|=[\]{}]+)([[\]{}]|[&|=]*)/g;o(Qg,"parseQuery");o(Xt,"recordError");o(k_,"parseBlock");o(Jy,"assignOperator");o(Wf,"decodeProperty");o(U4,"typedDecoding");o(x4,"wildcardDecoding");o(B4,"toSortObject");o(F4,"toSortEntry");zf=class{static{o(this,"Query")}constructor(){this.conditions=[]}[Symbol.iterator](){return this.conditions[Symbol.iterator]()}get(t){for(let r=0;r<this.conditions.length;r++){let n=this.conditions[r];if(n.attribute===t)return n.value}}getAll(){let t=[];for(let r=0,n=this.conditions.length;r<n;r++){let s=this.conditions[r];s.attribute&&t.push(s.value)}return t}};o(Jf,"flattenKey");o(Ia,"estimatedEntryCount");o(dIe,"intersectionEstimate")});var zF={};we(zF,{MultiPartId:()=>Xy,Resource:()=>Hr,contextStorage:()=>Xf,snakeCase:()=>mIe,transformForSelect:()=>Zf});function mIe(e){return e[0].toLowerCase()+e.slice(1).replace(/[a-z][A-Z][a-z]/g,t=>t[0]+"_"+t.slice(1))}function H4(e,t){if(Lu=!1,e==="")return null;if(e=e.slice(1),t.splitSegments){if(e.indexOf("/")===-1)return e===""?(Lu=!0,null):t.coerceId(decodeURIComponent(e));let r=e.split("/"),n=new Xy;for(let s=0;s<r.length;s++){let i=r[s];if(!i&&s===r.length-1){Lu=!0;break}n[s]=t.coerceId(decodeURIComponent(i))}return n}else{if(e==="")return Lu=!0,null;e[e.length-1]==="/"&&(Lu=!0)}return t.coerceId(decodeURIComponent(e))}function zn(e,t){n.reliesOnPrototype=!0;let r=t.hasContent;return n;function n(s,i,a){let c,l,u,d;if(r){if(a)d=i,a=a.getContext?.()||a;else if(i)typeof s=="object"&&s&&(!Array.isArray(s)||typeof s[0]=="object")?(d=s,c=d[this.primaryKey]??null,a=i.getContext?.()||i):i?.transaction instanceof Lo?a=i:d=i;else if(s&&typeof s=="object")d=s,s=void 0,c=d.getId?.()??d[this.primaryKey];else throw new Qf.ClientError(`Invalid argument for data, must be an object, but got ${s}`);c===null&&(u=!0)}else i?a=i.getContext?.()||i:s&&typeof s=="object"&&!Array.isArray(s)&&(a=s);if(c===void 0)if(typeof s=="object"&&s){if(l=s,c=s instanceof URLSearchParams?s.toString():s.url,s.conditions)c=s.id;else if(typeof c=="string")if(this.directURLMapping)c=c.slice(1),l.id=c;else{let E=c.indexOf("?");E>-1&&(l=this.parseQuery(c.slice(E+1),s),c=c.slice(0,E),c===""&&(u=!0));let g=this.parsePath(c,a,l);g?.id!==void 0?(g.query&&(l?l=Object.assign(g.query,l):l=g.query),u=g.isCollection,c=g.id):c=g,c&&(l.id=c)}else if(s[Symbol.iterator]){c=[],u=!0;for(let E of s){if(typeof E=="object"&&E)break;c.push(E)}c.length===0?c=null:(c.length===1&&(c=c[0]),l.slice&&(l=l.slice(c.length,l.length),l.length===0&&(l=new Ai,l.id=c,u=!1)))}c===void 0&&(c=s.id??null,c==null&&(u=!0))}else c=s,l=new Ai,l.id=c,c==null&&(u=!0);l||(l=new Ai,l.id=c),u&&(l.isCollection=!0);let f;a||(a=Xf.getStore()??{}),l.ensureLoaded!=null||l.async||u?(f={...t},l.ensureLoaded!=null&&(f.ensureLoaded=l.ensureLoaded),l.async&&(f.async=l.async),u&&(f.isCollection=!0)):f=t;let m=this.loadAsInstance,h=p;if((m===!1?!this.explicitContext:this.explicitContext===!1)&&(h=o(E=>Xf.run(a,()=>p(E)),"runAction")),a?.transaction){let E=this.getResource(c,a,f);return E.then?E.then(h):h(E)}else return Ft(a,()=>{let E=this.getResource(c,a,f);return E.then?E.then(h):h(E)},f);function p(E){if(m!==!1&&a.authorize){a.authorize=!1;let g=t.type==="read"?E.allowRead(a.user,l,a):t.type==="update"?E.doesExist?.()===!1?E.allowCreate(a.user,d,a):E.allowUpdate(a.user,d,a):t.type==="create"?E.allowCreate(a.user,d,a):E.allowDelete(a.user,l,a);if(g?.then)return g.then(R=>{if(!R)throw new Qf.AccessViolation(a.user);return typeof d?.then=="function"?d.then(T=>e(E,l,a,T)):e(E,l,a,d)});if(!g)throw new Qf.AccessViolation(a.user)}return typeof d?.then=="function"?d.then(g=>e(E,l,a,g)):e(E,l,a,d)}o(p,"authorizeActionOnResource")}}function As(e,t){let r=new Qf.ClientError(`The ${e.constructor.name} does not have a ${t} method implemented`,405);r.allow=[],r.method=t;for(let n of["get","put","post","delete","query","move","copy"])typeof e[n]=="function"&&r.allow.push(n);throw r}function CM(e,t,r){let n=e.getRecord?.();if(n){let s=e.getChanges?.();return i=>{let a,c;return e.hasOwnProperty(i)&&typeof(a=e[i])!="function"?a:s&&i in s?s[i]:(c=t?.[i])?c(e,r):n[i]}}else return t?s=>{let i=t[s];return i?i(e,r):e[s]}:s=>e[s]}function Zf(e,t){let r=t.propertyResolvers,n=t.getContext?.(),s;if(typeof e=="string")return o(function a(c){return c.then?c.then(a):Array.isArray(c)?c.map(a):CM(c,r,n)(e)},"transform");if(typeof e=="object"){if(e.asArray)return o(function c(l){if(l.then)return l.then(c);if(Array.isArray(l))return l.map(c);let u=[],d=i(CM(l,r,n));for(let f of e)u.push(d(f));return u},"transform");let a=e.forceNulls;return o(function c(l){if(l.then)return l.then(c);if(Array.isArray(l))return l.map(m=>m&&typeof m=="object"?c(m):m);let u={},d=i(CM(l,r,n)),f;for(let m of e){let h=d(m);h===void 0&&a&&(h=null),h?.then?(f||(f=[]),f.push(h.then(p=>u[m.name||m]=p))):u[m.name||m]=h}return f?Promise.all(f).then(()=>u):u},"transform")}else throw new Error("Invalid select argument type "+typeof e);function i(a){return c=>{if(typeof c=="string")return a(c);if(typeof c=="object")if(c.name){s||(s={});let l=s[c.name];if(!l){let d=r[c.name]?.definition?.tableClass;l=s[c.name]=Zf(c.select||c,d)}let u=a(c.name);return l(u)}else return a(c);else return c}}o(i,"handleProperty")}var k4,q4,Qf,G4,Xf,fIe,Hr,Lu,Xy,tc=ce(()=>{k4=require("crypto");vm();zu();q4=w(mi()),Qf=w(ge());ol();Xg();G4=require("async_hooks");zg();Xf=new G4.AsyncLocalStorage,fIe={json:"application/json",cbor:"application/cbor",msgpack:"application/x-msgpack",csv:"text/csv"},Hr=class{static{o(this,"Resource")}#e;#t;#r;static transactions;static directURLMapping=!1;static loadAsInstance;constructor(t,r){this.#e=t;let n=r?.getContext?r.getContext()??null:void 0;this.#t=n!==void 0?n:r||null}static get=zn(function(t,r,n,s){let i=t.get?.(r);if(t.constructor.loadAsInstance===!1)return i;if(i?.then)return i.then(a);return a(i);function a(c){let l;if((l=r?.select)&&c!=null&&!c.selectApplied){let u=Zf(l,t.constructor);return typeof c?.map=="function"?c.map(u):u(c)}return c}},{type:"read",letItLinger:!0,ensureLoaded:!0,async:!0});static put=zn(function(t,r,n,s){if(Array.isArray(s)&&t.#r&&t.constructor.loadAsInstance!==!1){let i=[];for(let a of s){let c=t.constructor,l=a[c.primaryKey],u=c.getResource(l,n,{async:!0});u.then?i.push(u.then(d=>d.put(a,n))):i.push(u.put(a,n))}return Promise.all(i)}return t.put?t.constructor.loadAsInstance===!1?t.put(r,s):t.put(s,r):As(t,"put")},{hasContent:!0,type:"update"});static patch=zn(function(t,r,n,s){return t.patch?t.constructor.loadAsInstance===!1?t.patch(r,s):t.patch(s,r):As(t,"patch")},{hasContent:!0,type:"update"});static delete=zn(function(t,r,n,s){return t.delete?t.delete(r):As(t,"delete")},{hasContent:!1,type:"delete"});static getNewId(){return(0,k4.randomUUID)()}static create(t,r,n){n?n.getContext&&(n=n.getContext()):n=Xf.getStore()??{};let s;return this.loadAsInstance===!1?s=t:t==null?s=r?.[this.primaryKey]??this.getNewId():Array.isArray(t)&&typeof t[0]!="object"?s=r?.[this.primaryKey]??[...t,this.getNewId()]:typeof t!="object"?s=r?.[this.primaryKey]??[t,this.getNewId()]:(s=t?.[this.primaryKey]??this.getNewId(),n=r||{},r=t),Ft(n,async()=>{let i=new this(s,n),a=await i.create?i.create(s,r):As(i,"create");return n.newLocation=s??a?.[this.primaryKey],n.createdResource=!0,this.loadAsInstance===!1?a:i})}static invalidate=zn(function(t,r,n,s){return t.invalidate?t.invalidate(r):As(t,"delete")},{hasContent:!1,type:"update"});static post=zn(function(t,r,n,s){return t.#e!=null&&t.update?.(),t.constructor.loadAsInstance===!1?t.post(r,s):t.post(s,r)},{hasContent:!0,type:"create"});static update=zn(function(t,r,n,s){return t.update(r,s)},{hasContent:!0,type:"create"});static connect=zn(function(t,r,n,s){return t.connect?t.constructor.loadAsInstance===!1?t.connect(r,s):t.connect(s,r):As(t,"connect")},{hasContent:!0,type:"read"});static subscribe=zn(function(t,r,n,s){return t.subscribe?t.subscribe(r):As(t,"subscribe")},{type:"read"});static publish=zn(function(t,r,n,s){return t.#e!=null&&t.update?.(),t.publish?t.constructor.loadAsInstance===!1?t.publish(r,s):t.publish(s,r):As(t,"publish")},{hasContent:!0,type:"create"});static search=zn(function(t,r,n){let s=t.search?t.search(r):As(t,"search"),i=n.select;if(i&&n.hasOwnProperty("select")&&s!=null&&!s.selectApplied){let a=Zf(i,t.constructor);return s.map(a)}return s},{type:"read"});static query=zn(function(t,r,n,s){return t.search?t.constructor.loadAsInstance===!1?t.search(r,s):t.search(s,r):As(t,"search")},{hasContent:!0,type:"read"});static copy=zn(function(t,r,n,s){return t.copy?t.constructor.loadAsInstance===!1?t.copy(r,s):t.copy(s,r):As(t,"copy")},{hasContent:!0,type:"create"});static move=zn(function(t,r,n,s){return t.move?t.constructor.loadAsInstance===!1?t.move(r,s):t.move(s,r):As(t,"move")},{hasContent:!0,type:"delete"});async post(t){if(this.#r)return(await this.constructor.create(this.#e,t,this.#t)).#e;As(this,"post")}static isCollection(t){return t&&t.#r}get isCollection(){return this.#r}static coerceId(t){return t}static parseQuery(t,r){return Qg(t,r)}static parsePath(t,r,n){let s=t.indexOf(".");if(s>-1){let a=t.slice(s+1),c=r?.headers&&fIe[a];if(c)r.requestedContentType=c,t=t.slice(0,s);else if(this.attributes?.find(l=>l.name===a))if(t=t.slice(0,s),n)n.property=a;else return{query:{property:a},id:H4(t,this),isCollection:Lu}}let i=H4(t,this);return Lu?{id:i,isCollection:!0}:i}static getResource(t,r,n){let s,i=r.getContext?.(),a;typeof r.isCollection=="boolean"&&r.hasOwnProperty("isCollection")?a=r.isCollection:a=n?.isCollection;let c=a&&this.Collection||this;if(i||(i=i===void 0?r:{}),i.transaction){let l;if(i.resourceCache?l=i.resourceCache:l=i.resourceCache=[],l.asMap){let u=l.asMap.get(t);if(s=u?.find(d=>d.constructor===c),s)return s;u||l.asMap.set(t,u=[]),u.push(s=new c(t,i))}else{if(s=l.find(u=>u.#e===t&&u.constructor===c),s)return s;if(l.push(s=new c(t,i)),l.length>10){let u=new Map;for(let d of l){let f=d.#e,m=u.get(f);m?m.push(d):u.set(f,[d])}i.resourceCache.length=0,i.resourceCache.asMap=u}}}else s=new c(t,i);return a&&(s.#r=!0),s}subscribe(t){return new es}connect(t,r){return r?.subscribe!==!1?this.subscribe?.(r):new es}allowRead(t,r){return t?.role.permission.super_user}allowUpdate(t,r,n){return t?.role.permission.super_user}allowCreate(t,r,n){return t?.role.permission.super_user}allowDelete(t,r){return t?.role.permission.super_user}getId(){return this.#e}getContext(){return this.#t}};(0,q4._assignPackageExport)("Resource",Hr);o(mIe,"snakeCase");o(H4,"pathToId");Xy=class extends Array{static{o(this,"MultiPartId")}toString(){return this.join("/")}};o(zn,"transactional");o(As,"missingMethod");o(CM,"selectFromObject");o(Zf,"transformForSelect")});var KW={};we(KW,{EVICTED:()=>Du,INVALIDATED:()=>Wn,coerceType:()=>eA,makeTable:()=>rA});function rA(e){let{primaryKey:t,indices:r,tableId:n,tableName:s,primaryStore:i,databasePath:a,databaseName:c,auditStore:l,schemaDefined:u,dbisDB:d,sealed:f,splitSegments:m,replicate:h}=e,{expirationMS:p,evictionMS:E,audit:g,trackDeletes:R}=e;E??=0;let{attributes:T}=e;T||(T=[]);let y=bM(i,n,l),N,O,F={},Z=Promise.resolve(),q,Y,K;for(let V of T)(V.assignCreatedTime||V.name==="__createdtime__")&&(q=V),(V.assignUpdatedTime||V.name==="__updatedtime__")&&(Y=V),V.expiresAt&&(K=V),V.isPrimaryKey&&(F=V);let $,le=[],ue=[],ie=1,me=2,De={},Me={},ft=864e5,Ye=0,Xn,nt,_t,Zc=!1,el,Vt,mm,hm=vu.get(U.REPLICATION_DATABASES);if(Array.isArray(hm)){for(let V of hm)if(V.name===c&&V.replicateTo>=0){mm=V.replicateTo;break}}let lE=i.getRange({start:!1,end:!1}).constructor,uE=10,xA=6;g&&gm(),D_(i.env.path,V=>{if(O)return Fa(V)});class pm extends Pl{static{o(this,"Updatable")}getUpdatedTime(){return $c.get(this.getRecord())?.version}getExpiresAt(){return $c.get(this.getRecord())?.expiresAt}addTo(_,S){if(typeof S=="number"||typeof S=="bigint")this.set(_,new Ih(S));else throw new Error("Can not add or subtract a non-numeric value")}subtractFrom(_,S){return this.addTo(_,-S)}}class Ce extends Hr{#e;#t;#r;#n;#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=g;static databasePath=a;static databaseName=c;static attributes=T;static replicate=h;static sealed=f;static splitSegments=m??!0;static createdTimeProperty=q;static updatedTimeProperty=Y;static propertyResolvers;static userResolvers={};static sources=[];static getResidencyById;static get expirationMS(){return p}static dbisDB=d;static schemaDefined=u;static sourcedFrom(_,S){if(S&&(this.sourceOptions=S,(S.expiration||S.eviction||S.scanInterval)&&this.setTTLExpiration(S)),S?.intermediateSource)_.intermediateSource=!0,this.sources.unshift(_);else{if(this.sources.some(D=>!D.intermediateSource)){if(this.sources.some(D=>D.name===_.name))return;throw new Error("Can not have multiple canonical (non-intermediate) sources")}this.sources.push(_)}O=O||_.get&&(!_.get.reliesOnPrototype||_.prototype.get),N=N||_.load;let A=o(D=>{let L=this.sources;if(L=L.filter(k=>k.intermediateSource&&k[D]&&(!k[D].reliesOnPrototype||k.prototype[D])),L.length>0)if(L.length===1){let k=L[0];return(C,x,z)=>{if(C?.source!==k)return k[D](x,z,C)}}else return(k,C,x)=>{let z=[];for(let ne of L){if(k?.source===ne)break;z.push(ne[D](C,x,k))}return Promise.all(z)}},"getApplyToIntermediateSource"),b=this.sources[this.sources.length-1];b.intermediateSource&&(b={});let I=o(D=>{if(b[D]&&(!b[D].reliesOnPrototype||b.prototype[D]))return(L,k,C)=>{if(!L?.source)return b[D](k,C,L)}},"getApplyToCanonicalSource");De={put:I("put"),patch:I("patch"),delete:I("delete"),publish:I("publish")},Me={put:A("put"),patch:A("patch"),delete:A("delete"),publish:A("publish"),invalidate:A("invalidate")};let P=b.shouldRevalidateEvents;return(async()=>{let D=!1,L,k=o(async(C,x)=>{let z=C.value,ne=C.table?He[c][C.table]:Ce;if(c===Am&&(C.table===Ku.ROLE_TABLE_NAME||C.table===Ku.USER_TABLE_NAME)&&(D=!0),C.id===void 0&&(C.id=z[ne.primaryKey],C.id===void 0))throw new Error("Replication message without an id "+JSON.stringify(C));C.source=_;let re={residencyId:nl(C.residencyList),isNotification:!0,ensureLoaded:!1,nodeId:C.nodeId,async:!0},B=C.id,de=await ne.getResource(B,x,re);switch(C.finished&&await C.finished,C.type){case"put":return P?de._writeInvalidate(B,z,re):de._writeUpdate(B,z,!0,re);case"patch":return P?de._writeInvalidate(B,z,re):de._writeUpdate(B,z,!1,re);case"delete":return de._writeDelete(B,re);case"publish":case"message":return de._writePublish(B,z,re);case"invalidate":return de._writeInvalidate(B,z,re);case"relocate":return de._writeRelocate(B,re);default:Ue.default.error?.("Unknown operation",C.type,C.id)}},"writeUpdate");try{let C=_.subscribe;C&&R==null&&(R=!0);let x={crossThreads:!1,inTransactionUpdates:!0,supportsTransactions:!0,omitCurrent:!0},z=_.subscribeOnThisThread?_.subscribeOnThisThread((0,Mu.getWorkerIndex)(),x):(0,Mu.getWorkerIndex)()===0,ne=C&&z&&await _.subscribe?.(x);if(ne){let re;for await(let B of ne)try{if(!(B.type==="transaction"?B.writes[0]:B)){Ue.default.error?.("Bad subscription event",B);continue}if(B.source=_,B.type==="end_txn"){if(re?.resolve(),B.localTime&&L!==B.localTime){if(B.remoteNodeIds?.length>0){let Se=[Symbol.for("seq"),B.remoteNodeIds[0]],ee=d.get(Se),J=ee?.nodes;J||(J=[]);for(let Te of B.remoteNodeIds.slice(1)){let fe=J.find(We=>We.id===Te);J=J.filter(We=>We.id!==Te||We===fe),fe||(fe={id:Te,seqId:0},J.push(fe)),fe.seqId=Math.max(ee?.seqId??1,B.localTime),Te===re?.nodeId&&(fe.lastTxnTime=B.timestamp)}let pe=Math.max(ee?.seqId??1,B.localTime);Ue.default.trace?.("Received txn",c,pe,new Date(pe),B.localTime,new Date(B.localTime),B.remoteNodeIds),d.put(Se,{seqId:pe,nodes:J})}L=B.localTime}B.onCommit&&re?.committed.then(B.onCommit);continue}if(re)if(B.beginTxn)re.resolve();else{re.write_promises.push(k(B,re));continue}!B.timestamp&&B.version&&(B.timestamp=B.version);let he=Ft(B,()=>{if(B.type==="transaction"){let Se=[];for(let ee of B.writes)try{Se.push(k(ee,B))}catch(J){throw J.message+=" writing "+JSON.stringify(ee)+" of event "+JSON.stringify(B),J}return Promise.all(Se)}else if(B.type==="define_schema"){let Se=this.attributes.slice(0),ee=!1;for(let J of B.attributes)Se.find(pe=>pe.name===J.name)||(Se.push(J),ee=!0);ee&&(ze({table:s,database:c,attributes:Se,origin:"cluster"}),$_.signalSchemaChange(new V_.SchemaEventMsg(process.pid,G.CREATE_TABLE,c,s)))}else return B.beginTxn?(re=B,re.write_promises=[k(B,B)],new Promise(Se=>{re.resolve=()=>Se(Promise.all(re.write_promises))})):k(B,B)});re&&(re.committed=he),D&&he&&!he?.waitingForUserChange&&(he.then(()=>$_.signalUserChange(new V_.UserEventMsg(process.pid))),he.waitingForUserChange=!0),B.onCommit&&(he?he.then(B.onCommit):B.onCommit())}catch(de){Ue.default.error?.("error in subscription handler",de)}}}catch(C){Ue.default.error?.(C)}})(),this}static get isCaching(){return O}static get shouldRevalidateEvents(){return this.prototype.get!==Ce.prototype.get}static getResource(_,S,A){let b=super.getResource(_,S,A);if(this.loadAsInstance===!1&&(S._freezeRecords=!0),_!=null&&this.loadAsInstance!==!1){Lr(_);try{if(b.getRecord?.())return b;if(typeof _=="object"&&_&&!Array.isArray(_))throw new Error(`Invalid id ${JSON.stringify(_)}`);let I=!A?.async||i.cache?.get?.(_),P=Mr(S),D=P.getReadTxn();if(D?.isDone)throw new Error("You can not read from a transaction that has already been committed/aborted");return va(_,S,{transaction:D,ensureLoaded:A?.ensureLoaded},I,L=>{if(L?Ce._updateResource(b,L):b.#e=null,S.onlyIfCached){if(!b.doesExist())throw new ct.ServerError("Entry is not cached",504)}else if(A?.ensureLoaded){let k=tl(_,L,S,b);if(k)return P?.disregardReadTxn(),b.#i=!0,S.loadedFromSource=!0,ii(k,C=>(Ce._updateResource(b,C),b))}return b})}catch(I){throw I.message.includes("Unable to serialize object")&&(I.message+=": "+JSON.stringify(_)),I}}return b}static _updateResource(_,S){_.#n=S,_.#e=S?.value??null,_.#r=S?.version}ensureLoaded(){let _=tl(this.getId(),this.#n,this.getContext());if(_)return this.#i=!0,this.getContext().loadedFromSource=!0,ii(_,S=>{this.#n=S,this.#e=S.value,this.#r=S.version})}static getNewId(){let _=F?.type;if(_==="String"||_==="ID")return super.getNewId();if(!Vt){let I=i.getEntry(Symbol.for("id_allocation")),P=I?.value,D;if(P&&P.nodeName===server.hostname&&(!bIe(i)||P.pid===process.pid)){let L=P.start,k=P.end;D=L;for(let C of i.getKeys({start:k,end:L,limit:1,reverse:!0}))D=C}else P=b(I?.version??null),D=P.start;Vt=new BigInt64Array([BigInt(D)+1n]),Vt=new BigInt64Array(i.getUserSharedBuffer("id",Vt.buffer)),Vt.maxSafeId=P.end}let S=Number(Atomics.add(Vt,0,1n)),A=_==="Int"?512:1048576;if(S+A>=Vt.maxSafeId){let I=o(P=>{Vt.maxSafeId=S+(_==="Int"?1023:4194303);let D=(_==="Int"?Math.pow(2,31):Math.pow(2,49))-1,L=P?void 0:i.useReadTransaction(),k=Number(Vt[0]);for(let z of i.getKeys({start:k+1,end:D,limit:1,transaction:L}))D=z;L?.done();let{value:C,version:x}=i.getEntry(Symbol.for("id_allocation"));if(Vt.maxSafeId<D){if(C.end>Vt.maxSafeId-100)return;Ue.default.info?.("New id allocation",S,Vt.maxSafeId,x),i.put(Symbol.for("id_allocation"),{start:C.start,end:Vt.maxSafeId,nodeName:server.hostname,pid:process.pid},Date.now(),x)}else{Ue.default.warn?.(`Id conflict detected, starting new id allocation range, attempting to allocate to ${Vt.maxSafeId}, but id of ${D} detected`);let z=b(x);z.alreadyUpdated||Atomics.store(Vt,0,BigInt(z.start+1)),Vt.maxSafeId=z.end}},"updateEnd");S+A===Vt.maxSafeId?setImmediate(I):S+100>=Vt.maxSafeId&&(Ue.default.warn?.(`Synchronous id allocation required on table ${s}${_=="Int"?", it is highly recommended that you use Long or Float as the type for auto-incremented primary keys":""}`),i.transactionSync(()=>I(!0)))}return S;function b(I){let P=(_==="Int"?Math.pow(2,31):Math.pow(2,49))-1,D=P/4,L,k,C=!1,x,z;do{x=Math.floor(Math.random()*P),z={start:x,end:x+(_==="Int"?1024:4194304),nodeName:server.hostname,pid:process.pid},L=0;for(let ne of i.getKeys({start:x,limit:1,reverse:!0}))L=ne;k=P;for(let ne of i.getKeys({start:x+1,end:P,limit:1}))k=ne;D*=.875,D<1e3&&!C&&(C=!0,Ue.default.error?.(`Id allocation in table ${s} is very dense, limited safe range of numbers to allocate ids in${_==="Int"?", it is highly recommended that you use Long or Float as the type for auto-incremented primary keys":""}`,x,L,k,D))}while(!(D<k-x&&(D<x-L||L===0)));return i.transactionSync(()=>{let ne=i.getEntry(Symbol.for("id_allocation"));return(ne?.version??null)==I?(Ue.default.info?.("Allocated new id range",z),i.put(Symbol.for("id_allocation"),z,Date.now()),z):(Ue.default.debug?.("Looks like ids were already allocated"),{alreadyUpdated:!0,...ne.value})})}}static setTTLExpiration(_){if(typeof _=="number")p=_*1e3,E||(E=0);else if(_&&typeof _=="object")p=_.expiration*1e3,E=(_.eviction||0)*1e3,ft=_.scanInterval*1e3;else throw new Error("Invalid expiration value type");if(p<0)throw new Error("Expiration can not be negative");ft=ft||(p+E)/4,Fa()}static getResidencyRecord(_){return d.get([Symbol.for("residency_by_id"),_])}static setResidency(_){Ce.getResidency=_&&((S,A)=>{try{return _(S,A)}catch(b){throw b.message+=` in residency function for table ${s}`,b}})}static setResidencyById(_){Ce.getResidencyById=_&&(S=>{try{return _(S)}catch(A){throw A.message+=` in residency function for table ${s}`,A}})}static getResidency(_,S){if(Ce.getResidencyById)return Ce.getResidencyById(_[t]);let A=mm;if(S.replicateTo!=null){if(Array.isArray(S.replicateTo))return S.replicateTo.includes(server.hostname)?S.replicateTo:[server.hostname,...S.replicateTo];S.replicateTo>=0&&(A=S.replicateTo)}if(A>=0&&server.nodes){let b=[server.hostname];if(S.previousResidency)b.push(...S.previousResidency.slice(0,A));else{let I=server.nodes.map(L=>L.name),P=Math.floor(I.length*Math.random());b.push(...I.slice(P,P+A));let D=P+A-I.length;D>0&&b.push(...I.slice(0,D))}return b}}static enableAuditing(_=!0){g=_,_&&gm(),Ce.audit=_}static coerceId(_){return _===""?null:eA(_,F)}static async dropTable(){delete He[c][s];for(let _ of i.getRange({versions:!0,snapshot:!1,lazy:!0}))_.metadataFlags&Yr&&_.value&&Va(_.value);if(c===a){for(let _ of T)d.remove(Ce.tableName+"/"+_.name),r[_.name]?.drop();d.remove(Ce.tableName+"/"),i.drop(),await d.committed}else console.log("legacy dropTable"),await i.close(),DM.default.unlinkSync(i.env.path);$_.signalSchemaChange(new V_.SchemaEventMsg(process.pid,G.DROP_TABLE,c,s))}get(_){let S=this.constructor;if(typeof _=="string"&&S.loadAsInstance!==!1)return this.getProperty(_);if(Em(_))return this.search(_);if(_&&_.id===void 0&&!_.toString()){let A={records:"./",name:s,database:c,auditSize:l?.getStats().entryCount,attributes:T,recordCount:void 0,estimatedRecordRange:void 0};return this.getContext()?.includeExpensiveRecordCountEstimates?Ce.getRecordCount().then(b=>(A.recordCount=b.recordCount,A.estimatedRecordRange=b.estimatedRange,A)):A}if(_!==void 0&&S.loadAsInstance===!1){let A=this.getContext(),b=Mr(A),I=b.getReadTxn();if(I?.isDone)throw new Error("You can not read from a transaction that has already been committed/aborted");let P=Ar(_);Lr(P);let D=!0;return _.checkPermission&&(D=this.allowRead(A.user,_)),ii(ii(D,L=>{if(!L)throw new ct.AccessViolation(A.user);let k=!0;return va(P,A,{transaction:I,ensureLoaded:k},!1,C=>{if(A.onlyIfCached){if(!C?.value)throw new ct.ServerError("Entry is not cached",504)}else if(k){let x=tl(P,C,A);if(x)return b?.disregardReadTxn(),A.loadedFromSource=!0,x.then(z=>z?.value)}return C?.value})}),L=>{let k=_?.select;return k&&L!=null?Zf(k,this.constructor)(L):L})}if(_?.property)return this.getProperty(_.property);if(this.doesExist()||_?.ensureLoaded===!1||this.getContext()?.returnNonexistent)return this}allowRead(_,S){let A=Ua(_,S);if(A?.read){if(A.isSuperUser)return!0;let b=A.attribute_permissions,I=S?.select;if(b?.length>0||Zc&&I){if(S||(S={}),I){let P=Array.isArray(I)?I:[I],D=b?.length>0&&PM(b,"read");S.select=P.map(L=>{let k=L.name||L;if(!D||D[k]){let C=_t[k]?.definition?.tableClass;if(C){if(L.name||(L={name:L}),!L.checkPermission&&S.checkPermission&&(L.checkPermission=S.checkPermission),!C.prototype.allowRead.call(null,_,L))return!1;if(!L.select)return L.name}return L}}).filter(Boolean)}else S.select=b.filter(P=>P.read&&!_t[P.attribute_name]).map(P=>P.attribute_name);return S}else return!0}}allowUpdate(_,S,A){let b=Ua(_,A);if(b?.update){let I=b.attribute_permissions;if(I?.length>0){let P=PM(I,"update");for(let D in S)if(!P[D])return!1;for(let D of I){let L=D.attribute_name;!D.update&&!(L in S)&&(S[L]=this.getProperty(L))}}return Ba(this.getContext())}}allowCreate(_,S,A){if(this.isCollection){let b=Ua(_,A);if(b?.insert){let I=b.attribute_permissions;if(I?.length>0){let P=PM(I,"insert");for(let D in S)if(!P[D])return!1;return Ba(this.getContext())}else return Ba(this.getContext())}}else return this.allowUpdate(_,{})}allowDelete(_,S){return Ua(_,S)?.delete&&Ba(this.getContext())}update(_,S){let A,b=typeof S=="boolean"||S===void 0&&(_==null||typeof _=="object"&&!(_ instanceof URLSearchParams)),I=!1;b?(I=S,S=_,A=this.getId()):A=Ar(_);let P=this.getContext();if(!Mr(P))throw new Error("Can not update a table resource outside of a transaction");if(S===!1)return this;if(typeof S=="object"&&S)if(I)Object.isFrozen(S)&&(S={...S}),this.#e={},this.#t=S;else if(b){let L=this.#t;L&&(S=Object.assign(L,S)),this.#t=S}else{let L=!0;if(_==null)throw new TypeError("Can not put a record without a target");return _.checkPermission&&(L=this.allowUpdate(P.user,S,_)),ii(L,k=>{if(!k)throw new ct.AccessViolation(P.user);return ii(i.get(Ar(_)),C=>{let x=new pm(C);return x._setChanges(S),this._writeUpdate(A,x.getChanges(),!1),x})})}return this._writeUpdate(A,this.#t,I),this}addTo(_,S){if(typeof S=="number"||typeof S=="bigint")this.#s===V4?this.set(_,(+this.getProperty(_)||0)+S):(this.#s||this.update(),this.set(_,new Ih(S)));else throw new Error("Can not add a non-numeric value")}subtractFrom(_,S){if(typeof S=="number")return this.addTo(_,-S);throw new Error("Can not subtract a non-numeric value")}getMetadata(){return this.#n}getRecord(){return this.#e}getChanges(){return this.#t}_setChanges(_){this.#t=_}setRecord(_){this.#e=_}invalidate(_){let S=!0,A=this.getContext();return _?.checkPermission&&(S=this.allowDelete(A.user,_,A)),ii(S,b=>{if(!b)throw new ct.AccessViolation(A.user);this._writeInvalidate(_?Ar(_):this.getId())})}_writeInvalidate(_,S,A){let b=this.getContext();Lr(_),Mr(this.getContext()).addWrite({key:_,store:i,invalidated:!0,entry:this.#n,before:De.invalidate?.bind(this,b,_),beforeIntermediate:Ha(S,Me.invalidate?.bind(this,b,_)),commit:o((P,D)=>{if(!(xa(P,D,A?.nodeId)<=0)){S??=null;for(let L in r)S||(S={}),S[L]===void 0&&(S[L]=this.getProperty(L));Ue.default.trace?.(`Invalidating entry in ${s} id: ${_}, timestamp: ${new Date(P).toISOString()}`),y(_,S,D,P,Wn,g,{user:b?.user,residencyId:A?.residencyId,nodeId:A?.nodeId},"invalidate")}},"commit")})}_writeRelocate(_,S){let A=this.getContext();Lr(_),Mr(this.getContext()).addWrite({key:_,store:i,invalidated:!0,entry:this.#n,before:De.relocate?.bind(this,A,_),beforeIntermediate:Me.relocate?.bind(this,A,_),commit:o((I,P)=>{if(xa(I,P,S?.nodeId)<=0)return;let D=Ce.getResidencyRecord(S.residencyId),L=0,k=null,C=P?.value;if(D&&!D.includes(server.hostname)){for(let x in r)k||(k={}),k[x]=C[x];L=Wn}else k=C;Ue.default.trace?.(`Relocating entry id: ${_}, timestamp: ${new Date(I).toISOString()}`),y(_,k,P,I,L,g,{user:A.user,residencyId:S.residencyId,nodeId:S.nodeId,expiresAt:S.expiresAt},"relocate",!1,null)},"commit")})}static _recordRelocate(_,S){if(this.getResidencyById)return!1;let A={previousResidency:this.getResidencyRecord(_.residencyId),isRelocation:!0},b=rl(this.getResidency(S.value,A)),I;if(b){if(!b.includes(server.hostname))return!1;I=nl(b)}let P=0;Ue.default.debug?.("Performing a relocate of an entry",_.key,S.value,b);let D=y(_.key,S.value,_,_.version,P,!0,{residencyId:I,expiresAt:S.expiresAt},"relocate",!1,null);return!0}static evict(_,S,A){let b=this.Source,I;if(!((O||g)&&(!S||(I=i.getEntry(_),!I||!S)||I.version!==A))){if(O){if(i.hasLock(_,I.version))return;let P;for(let D in r)P||(P={}),P[D]=S[D];if(P)return y(_,P,I,A,Du,null,null,null,!0)}return i.ifVersion(_,A,()=>{Po(_,S,null)}),Pu(i,I??i.getEntry(_),A)}}lock(){throw new Error("Not yet implemented")}static operation(_,S){return _.table||=s,_.schema||=c,global.operation(_,S)}put(_,S){if(S===void 0||S instanceof URLSearchParams)this.update(_,!0);else{let A=!0;if(_==null)throw new TypeError("Can not put a record without a target");let b=this.getContext();return _.checkPermission&&(A=this.allowUpdate(b.user,S,_)),ii(A,I=>{if(!I)throw new ct.AccessViolation(b.user);if(Array.isArray(S))for(let P of S){let D=P[t];this._writeUpdate(D,P,!0)}else{let P=Ar(_);this._writeUpdate(P,S,!0)}})}}create(_,S){let A=!0,b=this.getContext();if(!S&&!(_ instanceof URLSearchParams)&&(S=_,_=void 0),!S||typeof S!="object"||Array.isArray(S))throw new TypeError("Can not create a record without an object");return _?.checkPermission&&(A=this.allowCreate(b.user,S,_)),ii(A,I=>{if(!I)throw new ct.AccessViolation(b.user);let P=Ar(_)??S[t];if(P===void 0)P=this.constructor.getNewId();else if(i.get(P))throw new ct.ClientError("Record already exists",409);return this._writeUpdate(P,S,!0),S})}patch(_,S){if(S===void 0||S instanceof URLSearchParams)this.update(_,!1);else{let A=this.update(_,S);if(A?.then)return A.then(()=>{})}}_writeUpdate(_,S,A,b){let I=this.getContext(),P=Mr(I);Lr(_);let D=this.#n??i.getEntry(_);this.#s=A?V4:TIe;let L=o(C=>A?C.put?()=>C.put(I,_,S):null:C.patch?()=>C.patch(I,_,S):C.put?()=>C.put(I,_,Dl(this)):null,"writeToSources"),k={key:_,store:i,entry:D,nodeName:I?.nodeName,validate:o(C=>{S||(S=this.#t),A||S&&Pg(this.#t===S?this:S)?I?.source||(P.checkOverloaded(),this.validate(S,!A),Y&&(S[Y.name]=Y.type==="Date"?new Date(C):Y.type==="String"?new Date(C).toISOString():C),A&&(t&&S[t]!==_&&(S[t]=_),q&&(D?.value?S[q.name]=D?.value[q.name]:S[q.name]=q.type==="Date"?new Date(C):q.type==="String"?new Date(C).toISOString():C),S=Dl(S))):P.removeWrite(k)},"validate"),before:L(De),beforeIntermediate:Ha(S,L(Me)),commit:o((C,x,z)=>{if(z){if(I&&x?.version>(I.lastModified||0)&&(I.lastModified=x.version),this.#n=x,x?.value&&x.value.getRecord)throw new Error("Can not assign a record to a record, check for circular references");A||(this.#e=x?.value??null)}this.#t=void 0,this.#r=C;let ne=x?.value,re=S;this.#s=0;let B=!1,de=xa(C,x,b?.nodeId),he,Se=A?"put":"patch",ee;b?.residencyId!=null&&(ee=b.residencyId);let J=I?.expiresAt??(p?p+Date.now():-1);if(de<=0){if(g){let fe=x.localTime,We=x.version;Ue.default.trace?.("Applying CRDT update to record with id: ",_,"txn time",new Date(C),"applying later update from:",new Date(We),"local recorded time",new Date(fe));let Rt=[];for(;fe>C||We>=C&&fe>0;){let mt=l.get(fe);if(!mt)break;let _e=wt(mt);if(We=_e.version,We>=C){if(We===C){if(de=xa(C,{version:We,localTime:fe},b?.nodeId),de===0)return Te(!1);if(de>0)continue}if(_e.type==="patch")Rt.push(_e),he=S;else if(_e.type==="put"||_e.type==="delete")return Te(!1)}fe=_e.previousLocalTime}fe||Ue.default.debug?.("No further audit history, applying incremental updates based on available history",_,"existing version preserved",x),Rt.sort((mt,_e)=>mt.version-_e.version);for(let mt of Rt){let _e=mt.getValue(i);if(Ue.default.debug?.("Rebuilding update with future patch:",new Date(mt.version),_e,mt),re=Og(re,_e,A),!re)return Te(!1)}}else{if(A)return Te(!1);re=Og(re,ne,A),Ue.default.debug?.("Rebuilding update without audit:",re)}Ue.default.trace?.("Rebuilt record to save:",re," is full update:",A)}let pe;if(A?pe=re:this.constructor.loadAsInstance===!1?pe=Dl(ne,re):(this.#e=ne,pe=Dl(this,re)),this.#e=pe,pe&&pe.getRecord)throw new Error("Can not assign a record to a record, check for circular references");if(ee==null){D?.residencyId&&(I.previousResidency=Ce.getResidencyRecord(D.residencyId));let fe=rl(Ce.getResidency(pe,I));if(fe&&!fe.includes(server.hostname))if(he??=pe,B=!0,Ce.getResidencyById)pe=void 0;else{pe=null;for(let We in r)pe||(pe={}),pe[We]=he[We]}ee=nl(fe)}A||(he=S),Ue.default.trace?.(`Saving record with id: ${_}, timestamp: ${new Date(C).toISOString()}${J?", expires at: "+new Date(J).toISOString():""}${x?", replaces entry from: "+new Date(x.version).toISOString():", new entry"}`,(()=>{try{return JSON.stringify(pe).slice(0,100)}catch{return""}})()),Po(_,ne,pe),Te(!0),I.expiresAt&&Fa();function Te(fe){y(_,fe?pe:void 0,fe?x:{...x,value:void 0},C,B?Wn:0,g,{omitLocalRecord:B,user:I?.user,residencyId:ee,expiresAt:J,nodeId:b?.nodeId,originatingOperation:I?.originatingOperation},Se,!1,fe?he:he??S)}o(Te,"writeCommit")},"commit")};P.addWrite(k)}async delete(_){if(Em(_)){_.select=["$id"];for await(let S of this.search(_))this._writeDelete(S.$id);return!0}if(_){let S=!0,A=this.getContext();return _.checkPermission&&(S=this.allowDelete(A.user,_,A)),ii(S,b=>{if(!b)throw new ct.AccessViolation(A.user);let I=Ar(_);return this._writeDelete(I),!0})}return this._writeDelete(this.getId()),!!this.#e}_writeDelete(_,S){let A=Mr(this.getContext());Lr(_);let b=this.getContext();return A.addWrite({key:_,store:i,entry:this.#n,nodeName:b?.nodeName,before:De.delete?.bind(this,b,_),beforeIntermediate:Me.delete?.bind(this,b,_),commit:o((I,P,D)=>{let L=P?.value;D&&(b&&P?.version>(b.lastModified||0)&&(b.lastModified=P.version),Ce._updateResource(this,P)),!(xa(I,P,S?.nodeId)<=0)&&(Po(this.getId(),L),Ue.default.trace?.(`Deleting record with id: ${_}, txn timestamp: ${new Date(I).toISOString()}`),g||R?(y(_,null,P,I,0,g,{user:b?.user,nodeId:S?.nodeId},"delete"),g||Fa()):Pu(i,P))},"commit")}),!0}search(_){let S=this.getContext(),A=Mr(S);if(!_)throw new Error("No query provided");if(_.parseError)throw _.parseError;if(_.checkPermission&&!this.allowRead(S.user,_))throw new ct.AccessViolation(S.user);let b=_.conditions;b?b.length===void 0&&(b=b[Symbol.iterator]?Array.from(b):[b]):b=Array.isArray(_)?_:_[Symbol.iterator]?Array.from(_):[];let I=_.id??this.getId();I&&(b=[{attribute:null,comparator:Array.isArray(I)?"prefix":"starts_with",value:I}].concat(b));let P,D={};function L(J,pe){let Te;switch(pe){case"and":case void 0:if(J.length<1)throw new Error('An "and" operator requires at least one condition');Te=!0;break;case"or":if(J.length<2)throw new Error('An "or" operator requires at least two conditions');break;default:throw new Error("Invalid operator "+pe)}for(let fe of J){if(fe.conditions){fe.conditions=L(fe.conditions,fe.operator);continue}let We=fe[0]??fe.attribute,Rt=We==null?F:Io(T,We);if(Rt)(Rt.type||NM[fe.comparator])&&(fe[1]===void 0?fe.value=C(fe.value,Rt):fe[1]=C(fe[1],Rt));else if(We!=null&&!_.allowConditionsOnDynamicAttributes)throw(0,ct.handleHDBError)(new Error,`${We} is not a defined attribute`,404);if(fe.chainedConditions)if(fe.chainedConditions.length===1&&(!fe.operator||fe.operator=="and")){let mt=fe.chainedConditions[0],_e,Et;if(mt.comparator==="gt"||mt.comparator==="greater_than"||mt.comparator==="ge"||mt.comparator==="greater_than_equal"?(_e=fe,Et=mt):(_e=mt,Et=fe),_e.comparator!=="lt"&&_e.comparator!=="less_than"&&_e.comparator!=="le"&&_e.comparator!=="less_than_equal")throw new Error("Invalid chained condition, only less than and greater than conditions can be chained together");let tt=Et.comparator==="ge"||Et.comparator==="greater_than_equal",dr=_e.comparator==="le"||_e.comparator==="less_than_equal";fe.comparator=(tt?"ge":"gt")+(dr?"le":"lt"),fe.value=[Et.value,_e.value]}else throw new Error("Multiple chained conditions are not currently supported")}return J}o(L,"prepareConditions");function k(J,pe){if(_.enforceExecutionOrder)return J;for(let Te of J)Te.conditions&&(Te.conditions=k(Te.conditions,Te.operator));return J.length>1&&pe!=="or"?hIe(J,Qy(Ce)):J}o(k,"orderConditions");function C(J,pe){return Array.isArray(J)?J.map(Te=>eA(Te,pe)):eA(J,pe)}o(C,"coerceTypedValues");let x=_.operator;(b.length>0||x)&&(b=L(b,x));let z=typeof _.sort=="object"&&_.sort,ne;if(z&&x!=="or"){let J=z.attribute;if(J==null)throw new ct.ClientError("Sort requires an attribute");if(P=b.find(pe=>Jf(pe.attribute)===Jf(J)),!P){let pe=Io(T,J);if(!pe)throw(0,ct.handleHDBError)(new Error,`${Array.isArray(J)?J.join("."):J} is not a defined attribute`,404);if(pe.indexed)P={...z,comparator:"sort"},b.push(P);else if(b.length===0&&!_.allowFullScan)throw(0,ct.handleHDBError)(new Error,`${Array.isArray(J)?J.join("."):J} is not indexed and not combined with any other conditions`,404)}P&&(P.descending=!!z.descending)}b=k(b,x),z&&(P&&b[0]===P?z.next&&(ne={dbOrderedAttribute:z.attribute,attribute:z.next.attribute,descending:z.next.descending,next:z.next.next}):(P&&b.splice(b.indexOf(P),1),ne=z));let re=_.select;if(b.length===0&&(b=[{attribute:t,comparator:"greater_than",value:!0}]),_.explain)return{conditions:b,operator:x,postOrdering:ne,selectApplied:!!re};let B=A.useReadTxn(),de=wM(b,x,Ce,B,_,S,(J,pe)=>Gu(J,re,S,B,pe),D),he=_.ensureLoaded!==!1,Se=Ce.transformEntryForSelect(re,S,B,D,he,!0),ee=Ce.transformToOrderedSelect(de,re,ne,S,B,Se);return(_.offset||_.limit!==void 0)&&(ee=ee.slice(_.offset,_.limit!==void 0?(_.offset||0)+_.limit:void 0)),ee.onDone=()=>{ee.onDone=null,A.doneReadTxn()},ee.selectApplied=!0,ee.getColumns=()=>{if(re){let J=[];for(let pe of re)pe==="*"?J.push(...T.map(Te=>Te.name)):J.push(pe.name||pe);return J}return T.filter(J=>!J.computed&&!J.relationship).map(J=>J.name)},ee}static transformToOrderedSelect(_,S,A,b,I,P){let D=new lE;if(A){_=Gu(_,S,b,I,null);let L;D.iterate=function(){let C,x=_[Symbol.asyncIterator]?_[Symbol.asyncIterator]():_[Symbol.iterator](),z,ne=A.dbOrderedAttribute,re,B,de=!0;function he(ee){let J=ee.next&&he(ee.next),pe=ee.descending;return b.sort=ee,(Te,fe)=>{let We=qu(Te,ee.attribute,b),Rt=qu(fe,ee.attribute,b),mt=pe?(0,Uu.compareKeys)(Rt,We):(0,Uu.compareKeys)(We,Rt);return mt===0?J?.(Te,fe)||0:mt}}o(he,"createComparator");let Se=he(A);return{async next(){let ee;if(C)if(ee=C.next(),ee.done){if(z)return D.onDone&&D.onDone(),ee}else return{value:await P.call(this,ee.value)};L=[],re&&L.push(re);do if(ee=await x.next(),ee.done){if(z=!0,L.length)break;return D.onDone&&D.onDone(),ee}else{let J=ee.value;if(J?.then&&(J=await J),ne){let pe=qu(J,ne,b);if(de)de=!1,B=pe;else if(pe!==B){B=pe,re=J;break}}L.push(J)}while(!0);return A.isGrouped,L.sort(Se),C=L[Symbol.iterator](),ee=C.next(),ee.done?(D.onDone&&D.onDone(),ee):{value:await P.call(this,ee.value)}},return(){D.onDone&&D.onDone(),x.return()},throw(){D.onDone&&D.onDone(),x.throw()}}};let k=o(C=>{if(typeof S=="object"&&Array.isArray(C.attribute))for(let x=0;x<S.length;x++){let z=S[x],ne;if(z.name===C.attribute[0]){for(ne=z.sort||(z.sort={});ne.next;)ne=ne.next;ne.attribute=C.attribute.slice(1),ne.descending=C.descending}else z===C.attribute[0]&&(S[x]=ne={name:z,sort:{attribute:C.attribute.slice(1),descending:C.descending}})}C.next&&k(C.next)},"applySortingOnSelect");k(A)}else D.iterate=(_[Symbol.asyncIterator]||_[Symbol.iterator]).bind(_),D=D.map(function(L){try{let k=P.call(this,L);return typeof k?.catch=="function"?k.catch(C=>{throw C.partialObject={[t]:L.key},C}):k}catch(k){throw k.partialObject={[t]:L.key},k}});return D}static transformEntryForSelect(_,S,A,b,I,P){let D;I&&O&&!(typeof _=="string"?[_]:_)?.every(C=>{let x;return typeof C=="object"?x=C.name:x=C,r[x]||x===t})&&(D=!0);let L,k=o(function(C){let x;if(S?.transaction?.stale&&(S.transaction.stale=!1),C!=null){if(x=C.deref?C.deref():C.value,!x&&(C.key===void 0||C.deref)||C.metadataFlags&Wn){if(C.metadataFlags&Wn&&S.replicateFrom===!1&&P&&C.residencyId)return Yc.SKIP;if(C=va(C.key??C,S,{transaction:A,lazy:_?.length<4,ensureLoaded:I},this?.isSync,z=>z),C?.then)return C.then(k.bind(this));x=C?.value}if(D&&C?.metadataFlags&(Wn|Du)||C?.expiresAt!=null&&C?.expiresAt<Date.now()){if(S.onlyIfCached)return{[t]:C.key,message:"This entry has expired"};let z=tl(C.key??C,C,S);if(z?.then)return z.then(k)}}if(x==null)return P?Yc.SKIP:x;if(_&&!(_[0]==="*"&&_.length===1)){let z,ne=o((B,de)=>{let he;typeof B=="object"?he=B.name:he=B;let Se=_t?.[he],ee;if(Se){let J=b?.[he];if(J)if(J.hasMappings){let Te=Se.from?x[Se.from]:Jf(C.key);ee=J.get(Te),ee||(ee=[])}else ee=J.fromRecord?.(x);else ee=Se(x,S,C,!0);let pe=o(Te=>{if(Se.directReturn)return de(Te,he);if(Te&&typeof Te=="object"){let fe=Se.definition?.tableClass||Ce;L||(L={});let We=L[he]||(L[he]=fe.transformEntryForSelect(he===B?null:B.select||(Array.isArray(B)?B:null),S,A,J,I));if(Array.isArray(Te)){let Rt=[],mt=fe.transformToOrderedSelect(Te,B.select,typeof B.sort=="object"&&B.sort,S,A,We)[this.isSync?Symbol.iterator:Symbol.asyncIterator](),_e=o(tt=>{for(;!tt.done;){if(tt?.then)return tt.then(_e);Rt.push(tt.value),tt=mt.next()}de(Rt,he)},"nextValue"),Et=_e(mt.next());Et&&(z||(z=[]),z.push(Et));return}else if(Te=We.call(this,Te),Te?.then){z||(z=[]),z.push(Te.then(Rt=>de(Rt,he)));return}}de(Te,he)},"handleResolvedValue");ee?.then?(z||(z=[]),z.push(ee.then(pe))):pe(ee);return}else ee=x[he],ee&&typeof ee=="object"&&he!==B&&(ee=Ce.transformEntryForSelect(B.select||B,S,A,null)({value:ee}));de(ee,he)},"selectAttribute"),re;if(typeof _=="string")ne(_,B=>{re=B});else if(Array.isArray(_))if(_.asArray)re=[],_.forEach((B,de)=>{B==="*"?_[de]=x:ne(B,he=>re[de]=he)});else{re={};let B=_.forceNulls;for(let de of _)if(de==="*")for(let he in x)re[he]=x[he];else ne(de,(he,Se)=>{he===void 0&&B&&(he=null),re[Se]=he})}else throw new ct.ClientError("Invalid select"+_);return z?Promise.all(z).then(()=>re):re}return x},"transform");return k}async subscribe(_){if(!l)throw new Error("Can not subscribe to a table without an audit log");g||ze({table:s,database:c,schemaDefined:u,attributes:T,audit:!0}),_||(_={});let S=!_.rawEvents,A=[],b=this,I=$w(Ce,this.getId()??null,function(D,L,k,C){try{let x=L.getValue?.(i,S),z=L.type;if(!x&&z==="patch"&&S){let re=i.getEntry(D);re?.version===L.version?x=re.value:x=L.getValue?.(i,!0,k),z="put"}let ne={id:D,localTime:k,value:x,version:L.version,type:z,beginTxn:C};A?A.push(ne):this.send(ne)}catch(x){Ue.default.error?.(x)}},_.startTime||0,_),P=(async()=>{this.isCollection&&(I.includeDescendants=!0,_.onlyChildren&&(I.onlyChildren=!0)),_.supportsTransactions&&(I.supportsTransactions=!0);let D=this.getId(),L=_.previousCount;L>1e3&&(L=1e3);let k=_.startTime;if(this.isCollection){if(k){if(L)throw new ct.ClientError("startTime and previousCount can not be combined for a table level subscription");for(let{key:C,value:x}of l.getRange({start:k,exclusiveStart:!0,snapshot:!1})){let z=wt(x);if(z.tableId!==n)continue;let ne=z.recordId;if(D==null||z4(D,ne)){let re=z.getValue(i,S,C);if(I.send({id:ne,localTime:C,value:re,version:z.version,type:z.type}),I.queue?.length>Y4&&await I.waitForDrain()===!1)return}I.startTime=C}}else if(L){let C=[];for(let{key:x,value:z}of l.getRange({start:"z",end:!1,reverse:!0}))try{let ne=wt(z);if(ne.tableId!==n)continue;let re=ne.recordId;if(D==null||z4(D,re)){let B=ne.getValue(i,S,x);if(C.push({id:re,localTime:x,value:B,version:ne.version,type:ne.type}),--L<=0)break}}catch(ne){Ue.default.error("Error getting history entry",x,ne)}for(let x=C.length;x>0;)I.send(C[--x]);C[0]&&(I.startTime=C[0].localTime)}else if(!_.omitCurrent){for(let{key:C,value:x,version:z,localTime:ne}of i.getRange({start:D??!1,end:D==null?void 0:[D,Uu.MAXIMUM_KEY],versions:!0,snapshot:!1}))if(x&&(I.send({id:C,localTime:ne,value:x,version:z,type:"put"}),I.queue?.length>Y4&&await I.waitForDrain()===!1))return}}else{L&&!k&&(k=0);let C=this.#n?.localTime;if(C===AM&&(i.cache?.delete(D),this.#n=i.getEntry(D),Ue.default.trace?.("re-retrieved record",C,this.#n?.localTime),C=this.#n?.localTime),Ue.default.trace?.("Subscription from",k,"from",D,C),k<C){let x=[],z=C;do{let ne=l.get(z);if(ne){_.omitCurrent=!0;let re=wt(ne),B=re.getValue(i,S,z);S&&(re.type="put"),x.push({id:D,value:B,localTime:z,...re}),z=re.previousLocalTime}else break;L&&L--}while(z>k&&L!==0);for(let ne=x.length;ne>0;)I.send(x[--ne]);I.startTime=C}!_.omitCurrent&&this.doesExist()&&I.send({id:D,localTime:C,value:this.#e,version:this.#r,type:"put"})}for(let C of A)I.send(C);A=null})();return _.listener&&I.on("data",_.listener),I}static subscribeOnThisThread(_,S){return _===0||S?.crossThreads===!1}doesExist(){return!!(this.#e||this.#s)}publish(_,S,A){if(S===void 0||S instanceof URLSearchParams)this._writePublish(this.getId(),_,S);else{let b=!0,I=this.getContext();return _.checkPermission&&(b=this.allowCreate(I.user,_,I)),ii(b,P=>{if(!P)throw new ct.AccessViolation(I.user);let D=Ar(_);this._writePublish(D,S,A)})}}_writePublish(_,S,A){let b=Mr(this.getContext());_??=null,_!==null&&Lr(_);let I=this.getContext();b.addWrite({key:_,store:i,entry:this.#n,nodeName:I?.nodeName,validate:o(()=>{I?.source||(b.checkOverloaded(),this.validate(S))},"validate"),before:De.publish?.bind(this,I,_,S),beforeIntermediate:Ha(S,Me.publish?.bind(this,I,_,S)),commit:o((P,D,L)=>{D===void 0&&R&&!g&&Fa(),Ue.default.trace?.(`Publishing message to id: ${_}, timestamp: ${new Date(P).toISOString()}`),y(_,D?.value??null,D,D?.version||P,0,!0,{user:I?.user,residencyId:A?.residencyId,expiresAt:I?.expiresAt,nodeId:A?.nodeId},"message",!1,S)},"commit")})}validate(_,S){let A,b=o((I,P,D)=>{if(P.type&&I!=null)if(S&&I.__op__&&(I=I.value),P.properties){typeof I!="object"&&(A||(A=[])).push(`Value ${oi(I)} in property ${D} must be an object${P.type?" ("+P.type+")":""}`);let L=P.properties;for(let k=0,C=L.length;k<C;k++){let x=L[k];if(x.relationship||x.computed){_.hasOwnProperty(x.name)&&(A||(A=[])).push(`Computed property ${D}.${x.name} may not be directly assigned a value`);continue}let z=b(I[x.name],x,D+"."+x.name);z&&(I[x.name]=z)}if(P.sealed&&I!=null&&typeof I=="object")for(let k in I)L.find(C=>C.name===k)||(A||(A=[])).push(`Property ${k} is not allowed within object in property ${D}`)}else switch(P.type){case"Int":(typeof I!="number"||I>>0!==I)&&(A||(A=[])).push(`Value ${oi(I)} in property ${D} must be an integer (from -2147483648 to 2147483647)`);break;case"Long":(typeof I!="number"||!(Math.floor(I)===I&&Math.abs(I)<=9007199254740992))&&(A||(A=[])).push(`Value ${oi(I)} in property ${D} must be an integer (from -9007199254740992 to 9007199254740992)`);break;case"Float":typeof I!="number"&&(A||(A=[])).push(`Value ${oi(I)} in property ${D} must be a number`);break;case"ID":typeof I=="string"||I?.length>0&&I.every?.(L=>typeof L=="string")||(A||(A=[])).push(`Value ${oi(I)} in property ${D} must be a string, or an array of strings`);break;case"String":typeof I!="string"&&(A||(A=[])).push(`Value ${oi(I)} in property ${D} must be a string`);break;case"Boolean":typeof I!="boolean"&&(A||(A=[])).push(`Value ${oi(I)} in property ${D} must be a boolean`);break;case"Date":if(!(I instanceof Date)){if(typeof I=="string"||typeof I=="number")return new Date(I);(A||(A=[])).push(`Value ${oi(I)} in property ${D} must be a Date`)}break;case"BigInt":if(typeof I!="bigint"){if(typeof I=="string"||typeof I=="number")return BigInt(I);(A||(A=[])).push(`Value ${oi(I)} in property ${D} must be a bigint`)}break;case"Bytes":if(!(I instanceof Uint8Array)){if(typeof I=="string")return Buffer.from(I);(A||(A=[])).push(`Value ${oi(I)} in property ${D} must be a Buffer or Uint8Array`)}break;case"Blob":if(!(I instanceof Ds)){if(typeof I=="string"&&(I=Buffer.from(I)),I instanceof Buffer)return createBlob(I,{type:"text/plain"});(A||(A=[])).push(`Value ${oi(I)} in property ${D} must be a Blob`)}break;case"array":if(Array.isArray(I)){if(P.elements)for(let L=0,k=I.length;L<k;L++){let C=I[L],x=b(C,P.elements,D+"[*]");x&&(I[L]=x)}}else(A||(A=[])).push(`Value ${oi(I)} in property ${D} must be an Array`);break}P.nullable===!1&&I==null&&(A||(A=[])).push(`Property ${D} is required (and not does not allow null values)`)},"validateValue");for(let I=0,P=T.length;I<P;I++){let D=T[I];if(D.relationship||D.computed){Object.hasOwn(_,D.name)&&(A||(A=[])).push(`Computed property ${D.name} may not be directly assigned a value`);continue}if(!S||D.name in _){let L=b(_[D.name],D,D.name);L!==void 0&&(_[D.name]=L)}}if(f)for(let I in _)T.find(P=>P.name===I)||(A||(A=[])).push(`Property ${I} is not allowed`);if(A)throw new ct.ClientError(A.join(". "))}getUpdatedTime(){return this.#r}wasLoadedFromSource(){return O?!!this.#i:void 0}static async addAttributes(_){let S=T.slice(0);for(let A of _){if(!A.name)throw new ct.ClientError("Attribute name is required");if(A.name.match(/[`/]/))throw new ct.ClientError("Attribute names cannot include backticks or forward slashes");pIe(A.name),S.push(A)}return ze({table:s,database:c,schemaDefined:u,attributes:S}),Ce.indexingOperation}static async removeAttributes(_){let S=T.filter(A=>!_.includes(A.name));return ze({table:s,database:c,schemaDefined:u,attributes:S}),Ce.indexingOperation}static getSize(){let _=i.getStats();return(_.treeBranchPageCount+_.treeLeafPageCount+_.overflowPages)*_.pageSize}static getAuditSize(){let _=l?.getStats();return _&&(_.treeBranchPageCount+_.treeLeafPageCount+_.overflowPages)*_.pageSize}static getStorageStats(){let _=i.env.path,S=DM.default.statfsSync?.(_)??{};return{available:S.bavail*S.bsize,free:S.bfree*S.bsize,size:S.blocks*S.bsize}}static async getRecordCount(_){let S=i.getStats().entryCount,A=1e3/2,b=performance.now(),I=Math.floor(S/2),P=_?.exactCount,D=0,L=0,k;for(let{value:C}of i.getRange({start:!0,lazy:!0,snapshot:!1}))if(C!=null&&D++,L++,await Kc(),!P&&L<I&&performance.now()-b>A){k=L;break}if(k){let C=D;D=0;for(let{value:ee}of i.getRange({start:"\uFFFF",reverse:!0,lazy:!0,limit:k,snapshot:!1}))ee!=null&&D++,await Kc();let x=k*2,z=(D+C)/x,ne=Math.pow((D-C+1)/k/2,2)+z*(1-z)/x,re=Math.max(Math.sqrt(ne)*S,1),B=Math.round(z*S),de=Math.max(B-1.96*re,D+C),he=Math.min(B+1.96*re,S),Se=Math.pow(10,Math.round(Math.log10(re)));return Se>B&&(Se=Se/10),D=Math.round(B/Se)*Se,{recordCount:D,estimatedRange:[Math.round(de),Math.round(he)]}}return{recordCount:D}}static updatedAttributes(){_t=this.propertyResolvers={$id:o((_,S,A)=>({value:A.key}),"$id"),$updatedtime:o((_,S,A)=>A.version,"$updatedtime"),$updatedTime:o((_,S,A)=>A.version,"$updatedTime"),$expiresAt:o((_,S,A)=>A.expiresAt,"$expiresAt"),$record:o((_,S,A)=>A?{value:_}:_,"$record"),$distance:o((_,S,A)=>A&&(A.distance??S?.vectorDistances?.get(A)),"$distance")};for(let _ of this.attributes){_.isPrimaryKey&&(F=_),_.resolve=null;let S=_.relationship,A=_.computed;if(S)if(_.indexed&&console.error("A relationship property can not be directly indexed, (but you may want to index the foreign key attribute)"),A&&console.error("A relationship property is already computed and can not be combined with a computed function (the relationship will be given precedence)"),Zc=!0,S.to)_.elements?.definition?(_t[_.name]=_.resolve=(b,I,P,D)=>{let L=b[S.from?S.from:t],k=_.elements.definition.tableClass;return D?jf({attribute:S.to,value:L},Mr(I).getReadTxn(),!1,k,!1).map(C=>C&&C.key!==void 0?C:k.primaryStore.getEntry(C,{transaction:Mr(I).getReadTxn()})).asArray:k.search([{attribute:S.to,value:L}],I).asArray},_.set=()=>{},_.resolve.definition=_.elements.definition,_.resolve.to=S.to,S.from&&(_.resolve.from=S.from)):console.error(`The one-to-many/many-to-many relationship property "${_.name}" in table "${s}" must have an array type referencing a table as the elements`);else if(S.from){let b=_.definition||_.elements?.definition;b?(_t[_.name]=_.resolve=(I,P,D,L)=>{let k=I[S.from];if(k===void 0)return;if(_.elements){let x,z=k?.map(ne=>{let re=b.tableClass.primaryStore[L?"getEntry":"get"](ne,{transaction:Mr(P).getReadTxn()});return re?.then&&(x=!0),Ce.loadAsInstance===!1&&Object.freeze(L?re?.value:re),re});return S.filterMissing?x?Promise.all(z).then(ne=>ne.filter(j4)):z.filter(j4):x?Promise.all(z):z}let C=b.tableClass.primaryStore[L?"getEntry":"get"](k,{transaction:Mr(P).getReadTxn()});return Ce.loadAsInstance===!1&&Object.freeze(L?C?.value:C),C},_.set=(I,P)=>{if(Array.isArray(P)){let D=P.map(L=>L.getId?.()||L[b.tableClass.primaryKey]);I[S.from]=D}else{let D=P.getId?.()||P[b.tableClass.primaryKey];I[S.from]=D}},_.resolve.definition=_.definition||_.elements?.definition,_.resolve.from=S.from):console.error(`The relationship property "${_.name}" in table "${s}" must be a type that references a table`)}else console.error(`The relationship directive on "${_.name}" in table "${s}" must use either "from" or "to" arguments`);else if(A)typeof A.from=="function"&&this.setComputedAttribute(_.name,A.from),_t[_.name]=_.resolve=(b,I,P)=>{let D=typeof A.from=="string"?b[A.from]:b,L=this.userResolvers[_.name];if(L)return L(D,I,P);Ue.default.warn(`Computed attribute "${_.name}" does not have a function assigned to it. Please use setComputedAttribute('${_.name}', resolver) to assign a resolver function.`),this.userResolvers[_.name]=()=>{}},_.resolve.directReturn=!0;else if(r[_.name]?.customIndex?.propertyResolver){let b=r[_.name].customIndex;_t[_.name]=(I,P,D)=>{let L=I[_.name];return b.propertyResolver(L,P,D)},_t[_.name].directReturn=!0}}Nh(this,this),Nh(pm,this,!0);for(let _ of T){let S=_.name;_.resolve&&Object.defineProperty(i.encoder.structPrototype,S,{get(){return _.resolve(this,Xf.getStore())},set(A){return _.set(this,A)},configurable:!0})}}static setComputedAttribute(_,S){let A=Io(T,_);if(!A){console.error(`The attribute "${_}" does not exist in the table "${s}"`);return}if(!A.computed){console.error(`The attribute "${_}" is not defined as computed in the table "${s}"`);return}this.userResolvers[_]=S}static async deleteHistory(_=0,S=!1){let A;for(let{key:b,value:I}of l.getRange({start:0,end:_}))await Kc(),wt(I).tableId===n&&(A=$y(l,b,I));if(S)for(let b of i.getRange({start:0,versions:!0})){let{key:I,value:P,localTime:D}=b;await Kc(),P===null&&D<_&&(A=Pu(i,b))}await A}static async*getHistory(_=0,S=1/0){for(let{key:A,value:b}of l.getRange({start:_||1,end:S})){await Kc();let I=wt(b);I.tableId===n&&(yield{id:I.recordId,localTime:A,version:I.version,type:I.type,value:I.getValue(i,!0,A),user:I.user,operation:I.originatingOperation})}}static async getHistoryOfRecord(_){let S=[];if(_==null)throw new Error("An id is required");let A=i.getEntry(_);if(!A)return S;let b=A.localTime;if(!b)throw new Error("The entry does not have a local audit time");let I=0;do{await Kc();let P=l.get(b);if(P){let D=wt(P);S.push({id:D.recordId,localTime:b,version:D.version,type:D.type,value:D.getValue(i,!0,b),user:D.user}),b=D.previousLocalTime}else break}while(I<1e3&&b);return S.reverse()}static cleanup(){$?.remove()}}let dE=zR(async(V,_,S)=>{for(let A of Ce.sources)if(A.get&&(!A.get.reliesOnPrototype||A.prototype.get)){if(A.available?.(S)===!1)continue;_.source=A;let b=await A.get(V,_);if(b)return b}},()=>{throw new ct.ServerError("Service unavailable, exceeded request queue limit for resolving cache record",503)});Ce.updatedAttributes();let _m=Ce.prototype;return p&&Ce.setTTLExpiration(p/1e3),K&&$u(),Ce;function Po(V,_,S){let A;for(let b in r){let I=r[b],P=I.isIndexing,D=_t[b],L=S&&(D?D(S):S[b]),k=_&&(D?D(_):_[b]);if(L===k&&!P)continue;if(I.customIndex){I.customIndex.index(V,L,k);continue}A=!0;let C=I.indexNulls,x=(0,G_.getIndexedValues)(L,C),z=(0,G_.getIndexedValues)(k,C);if(s==="OrganizationRole"&&Ue.default.error?.({tableName:s,id:V,key:b,valuesToAdd:x,valuesToRemove:z}),z?.length>0){let ne=new Set(z);if(x=x?x.filter(re=>{if(ne.has(re))ne.delete(re);else return!0}):[],z=Array.from(ne),(z.length>0||x.length>0)&&$4){let re=z.concat(x).map(B=>({key:B,value:V}));I.prefetch(re,W4)}for(let re=0,B=z.length;re<B;re++)I.remove(z[re],V)}else x?.length>0&&$4&&I.prefetch(x.map(ne=>({key:ne,value:V})),W4);if(x)for(let ne=0,re=x.length;ne<re;ne++)I.put(x[ne],V)}return A}o(Po,"updateIndices");function Lr(V){switch(typeof V){case"number":return!0;case"string":if(V.length<659)return!0;if(V.length>K4)throw new Error("Primary key size is too large: "+V.length);break;case"object":if(V===null)throw new Error("Invalid primary key of null");break;case"bigint":if(V<2n**64n&&V>-(2n**64n))return!0;break;default:throw new Error("Invalid primary key type: "+typeof V)}if((0,Uu.writeKey)(V,RIe,0)>K4)throw new Error("Primary key size is too large: "+V.length);return!0}o(Lr,"checkValidId");function Ar(V){return typeof V=="object"&&V?V.id:V}o(Ar,"requestTargetToId");function Em(V){return typeof V=="object"&&V&&V.isCollection}o(Em,"isSearchTarget");function Cs(V){}o(Cs,"isRequestTarget");function va(V,_,S,A,b){if(Ce.getResidencyById&&S.ensureLoaded&&_?.replicateFrom!==!1){let P=rl(Ce.getResidencyById(V));if(P&&!P.includes(server.hostname)&&N)return N({key:V,residency:P}).then(b)}let I=o(()=>{if(_?.transaction?.stale&&(_.transaction.stale=!1),S.transaction?.isDone)return b(null,V);let P=i.getEntry(V,S);return _?._freezeRecords&&Object.freeze(P?.value),P?.residencyId&&P.metadataFlags&Wn&&N&&S.ensureLoaded&&_?.replicateFrom!==!1?N(P).then(D=>b(D,V),D=>(Ue.default.error?.("Error loading remote record",V,P,S,D),b(null,V))):(P&&_&&(P?.version>(_.lastModified||0)&&(_.lastModified=P.version),P?.localTime&&!_.lastRefreshed&&(_.lastRefreshed=P.localTime)),b(P,V))},"whenPrefetched");return A?I():ie>0?(ie--,I()):new Promise((P,D)=>{ie===0?(ie--,i.prefetch([V],()=>{L(),k()})):(le.push(V),ue.push(k),le.length>xA&&(ie--,L()));function L(){if(le.length>0){let C=ue;i.prefetch(le,()=>{ie===-1?L():ie++;for(let x of C)x()}),le=[],ue=[],me>2&&me--}else ie=me,me<uE&&me++}o(L,"prefetch");function k(){try{P(I())}catch(C){D(C)}}o(k,"load")})}o(va,"loadLocalRecord");function Ua(V,_){let S=_?.checkPermission;if(typeof S!="object"){if(!V?.role)return;S=V.role.permission}if(S.super_user)return yIe;let A=S[c],b,I=A?.tables;if(I)return I[s];if(c==="data"&&(b=S[s])&&!b.tables)return b}o(Ua,"getTablePermissions");function tl(V,_,S,A){if(O){let b=!1;if(S.noCache?b=!0:(_?(!_.value||_.metadataFlags&(Wn|Du)||_.expiresAt!=null&&_.expiresAt<Date.now())&&(b=!0):b=!0,jr(!b,"cache-hit",s)),b){let I=fE(V,_,S).then(P=>(P?.value&&P?.value.getRecord?.()&&Ue.default.error?.("Can not assign a record that is already a resource"),S&&(P?.version>(S.lastModified||0)&&(S.lastModified=P.version),S.lastRefreshed=Date.now()),P));if(S?.onlyIfCached||_?.value&&A?.allowStaleWhileRevalidate?.(_,V)){if(I.catch(P=>Ue.default.warn?.(P)),S?.onlyIfCached&&!A.doesExist())throw new ct.ServerError("Entry is not cached",504);return}else return I}}else if(_?.value&&_.expiresAt!=null&&_.expiresAt<Date.now())return Ce.evict(_.key,_.value,_.version),_.value=null,{then(b){return b(_)}}}o(tl,"ensureLoadedFromSource");function Mr(V){let _=V?.transaction;if(_){if(!_.lmdbDb)return _.lmdbDb=i,_;do{if(_.lmdbDb?.path===i.path)return _;let S=_.next;if(!S)return _=_.next=new Lo,_.lmdbDb=i,_;_=S}while(!0)}else return new CE}o(Mr,"txnForContext");function qu(V,_,S){if(!V)return;let A=(V.deref?V.deref():V.value)??i.getEntry(V.key)?.value;if(typeof _=="object"){let I=_t,P=A;for(let D=0,L=_.length;D<L;D++){let k=_[D],C=I?.[k];P=C&&P?C(P,S,V):P?.[k],V=null,I=C?.definition?.tableClass?.propertyResolvers}return P}let b=_t[_];return b?b(A,S,V):A[_]}o(qu,"getAttributeValue");function Gu(V,_,S,A,b){let I=b?.length,P={transaction:A,lazy:I>0||typeof _=="string"||_?.length<4,alwaysPrefetch:!0},D;function L(k,C){let x=k?.value;if(!x)return Yc.SKIP;for(let z=0;z<I;z++)if(!D?.includes(z)&&!b[z](x,k))return Yc.SKIP;return C!==void 0&&(k.key=C),k}if(o(L,"processEntry"),I>0||!V.hasEntries){let k=V.map(C=>{if(D=null,typeof C=="object"&&C?.key!==void 0)return I>0?L(C):C;if(C==null)return Yc.SKIP;for(let x=0;x<I;x++){let ne=b[x].idFilter;if(ne){if(!ne(C))return Yc.SKIP;D||(D=[]),D.push(x)}}return va(C,S,P,!1,L)});return Array.isArray(V)&&(k=k.filter(C=>C!==Yc.SKIP)),k.hasEntries=!0,k}return V}o(Gu,"transformToEntries");function xa(V,_,S=server.replication?.getThisNodeId(l)){if(V<=_?.version){if(_?.version===V&&S!==void 0){let A=server.replication?.exportIdMapping(l),b=_.localTime,I=b&&l.get(b);if(I){let P,D,L=wt(I);for(let k in A)A[k]===S&&(P=k),A[k]===L.nodeId&&(D=k);if(P>D)return 1;if(P===D)return 0}}return-1}return 1}o(xa,"precedesExistingVersion");async function fE(V,_,S){let A=_?.metadataFlags,b=_?.version,I,P;if(!i.attemptLock(V,b,()=>{clearTimeout(P);let C=i.getEntry(V);!C||!C.value||C.metadataFlags&(Wn|Du)?I(fE(V,i.getEntry(V),S)):I(C)}))return new Promise(C=>{I=C,P=setTimeout(()=>{i.unlock(V,b)},SIe)});let D=_?.value,L={requestContext:S,replacingRecord:D,replacingEntry:_,replacingVersion:b,noCacheStore:!1,source:null,resourceCache:S?.resourceCache,transaction:void 0,expiresAt:void 0,lastModified:void 0},k=S?.responseHeaders;return new Promise((C,x)=>{let z;ii(Ft(L,async ne=>{let re=performance.now(),B,de,he;try{B=await dE(V,L,_),he=A&Wn;let ee=L.lastModified||he&&b;ee||(ee=(0,G_.getNextMonotonicTime)()),de=he||ee>b||!D;let J=performance.now()-re;if(it(J,"cache-resolution",s,null,"success"),k&&Mh(k,"Server-Timing",`cache-resolve;dur=${J.toFixed(2)}`,!0),ne.timestamp=ee,p&&L.expiresAt==null&&(L.expiresAt=Date.now()+p),B){if(typeof B!="object")throw new Error("Only objects can be cached and stored in tables");if(B.status>0&&B.headers)if(B.status>=300)if(B.status===304)B=D,ee=b;else throw new ct.ServerError(B.body||"Error from source",B.status);else B=B.body;typeof B.toJSON=="function"&&(B=B.toJSON()),t&&B[t]!==V&&(B[t]=V)}z=!0,C({key:V,version:ee,value:B})}catch(ee){ee.message+=` while resolving record ${V} for ${s}`,D&&((ee.code==="ECONNRESET"||ee.code==="ECONNREFUSED"||ee.code==="EAI_AGAIN")&&!S?.mustRevalidate||S?.staleIfError&&(ee.statusCode===500||ee.statusCode===502||ee.statusCode===503||ee.statusCode===504))?(C({key:V,version:b,value:D}),Ue.default.trace?.(ee.message,"(returned stale record)")):x(ee);let J=performance.now()-re;it(J,"cache-resolution",s,null,"fail"),k&&Mh(k,"Server-Timing",`cache-resolve;dur=${J.toFixed(2)}`,!0),L.transaction.abort();return}if(S?.noCacheStore||L.noCacheStore){L.transaction.abort();return}Mr(L).addWrite({key:V,store:i,entry:_,nodeName:"source",before:Ha(B),commit:o((ee,J)=>{if(J?.version!==b)return;let pe=Po(V,D,B);if(B){Me.put?.(L,V,B),J&&(S.previousResidency=Ce.getResidencyRecord(J.residencyId));let Te,fe=!1,We,Rt=rl(Ce.getResidency(B,S));if(Rt){if(!Rt.includes(server.hostname))if(Te=B,fe=!0,Ce.getResidencyById)B=void 0;else{B=null;for(let mt in r)B||(B={}),B[mt]=Te[mt]}We=nl(Rt)}Ue.default.trace?.(`Writing resolved record from source with id: ${V}, timestamp: ${new Date(ee).toISOString()}`),y(V,B,J,ee,fe?Wn:0,g&&(de||fe)||null,{user:L?.user,expiresAt:L.expiresAt,residencyId:We},"put",!!he,Te)}else J&&(Me.delete?.(L,V),Ue.default.trace?.(`Deleting resolved record from source with id: ${V}, timestamp: ${new Date(ee).toISOString()}`),g||R?y(V,null,J,ee,0,g&&de||null,{user:L?.user},"delete",!!he):Pu(i,J,b))},"commit")})}),()=>{i.unlock(V,b)},ne=>{i.unlock(V,b),z&&Ue.default.error?.("Error committing cache update",ne)})})}o(fE,"getFromSource");function Ba(V){if(!V||V.user?.role?.permission?.super_user)return!0;if(V.replicateTo)throw new ct.ClientError("Can not specify replication parameters without super user permissions",403);if(V.replicatedConfirmation)throw new ct.ClientError("Can not specify replication confirmation without super user permissions",403);return!0}o(Ba,"checkContextPermissions");function Fa(V){let _=!1;if(V&&(V-Ye>1&&(_=!0),Ye=V),!(ft===Xn&&!_)&&(Xn=ft,(0,Mu.getWorkerIndex)()===(0,Mu.getWorkerCount)()-1))return nt&&clearTimeout(nt),ft?new Promise(S=>{let A=new Date;A.setMonth(0),A.setDate(1),A.setHours(0),A.setMinutes(0),A.setSeconds(0);let b=ft/(1+Ye),I=_?Date.now():Math.ceil((Date.now()-A.getTime())/b)*b+A.getTime(),P=o(D=>{Ue.default.trace?.(`Scheduled next cleanup scan at ${new Date(D)}`),nt=setTimeout(()=>Z=Z.then(async()=>{if(P(Math.max(D+ft,Date.now())),i.rootStore.status!=="open"){clearTimeout(nt);return}let L=50,k=new Array(L),C=0,x=Math.pow(Ye,8)*(vu.get(U.STORAGE_RECLAMATION_EVICTIONFACTOR)??1e5),z=E/Math.pow(Math.max(Ye,1),4);Ue.default.info?.(`Starting cleanup scan for ${s}, evict threshold ${x}, adjusted eviction ${z}ms`);function ne(re,B,de,he){let Se=re+z-Date.now();if(Se<0)return!0;if(Ye){let ee=i.lastSize;return de&Yr&&cl(he,J=>{J.size&&(ee+=J.size)}),Ue.default.trace?.(`shouldEvict adjusted ${Se} ${ee}, ${Se*(re-B)/ee} < ${x}`),Se*(re-B)/ee<x}return!1}o(ne,"shouldEvict");try{let re=0;for(let B of i.getRange({start:!1,snapshot:!1,versions:!0,lazy:!0})){let{key:de,value:he,version:Se,expiresAt:ee,metadataFlags:J}=B,pe;he===null&&!g&&Se+gIe<Date.now()?pe=Pu(i,B,Se):ee!=null&&ne(ee,Se,J,he)&&(pe=Ce.evict(de,he,Se),re++),pe&&(await k[C],k[C]=pe.catch(Te=>{Ue.default.error?.("Cleanup error",Te)}),++C>=L&&(C=0)),await Kc()}Ue.default.info?.(`Finished cleanup scan for ${s}, evicted ${re} entries`)}catch(re){Ue.default.warn?.(`Error in cleanup scan for ${s}:`,re)}S(void 0),Ye=0}),Math.min(D-Date.now(),2147483647)).unref()},"startNextTimer");P(I)}):void 0}o(Fa,"scheduleCleanup");function gm(){$=l?.addDeleteRemovalCallback(n,i,(V,_)=>{i.remove(V,_)})}o(gm,"addDeleteRemoval");function $u(){(0,Mu.getWorkerIndex)()===0&&setInterval(async()=>{if(!el){el=!0;try{let V=K.name,_=r[V];if(!_)throw new Error(`expiresAt attribute ${K} must be indexed`);for(let S of _.getRange({start:!0,values:!1,end:Date.now(),snapshot:!1})){for(let A of _.getValues(S)){let b=i.getEntry(A);b?.value?b.value[V]<Date.now()&&Ce.evict(A,b.value,b.version):i.ifVersion(A,b?.version,()=>_.remove(S,A))}await Kc()}}catch(V){Ue.default.error?.("Error in evicting old records",V)}finally{el=!1}}},EIe).unref()}o($u,"runRecordExpirationEviction");function rl(V){if(V!=null){if(Array.isArray(V))return V;if(typeof V=="number"){if(V>=65536)throw new Error(`Shard id ${V} must be below 65536`);let _=server.shards?.get?.(V);if(_)return Ue.default.trace?.(`Shard ${V} mapped to ${_.map(S=>S.name).join(", ")}`),_.map(S=>S.name);throw new Error(`Shard ${V} is not defined`)}throw new Error(`Shard or residency list ${V} is not a valid type, must be a shard number or residency list of node hostnames`)}}o(rl,"residencyFromFunction");function nl(V){if(V){let _=V.join(","),S=d.get([Symbol.for("residency_by_set"),_]);return S||(d.put([Symbol.for("residency_by_set"),_],S=Math.floor(Math.random()*2147418112)+65535),d.put([Symbol.for("residency_by_id"),S],V),S)}}o(nl,"getResidencyId");function Ha(V,_){let S=Rb(V,i.rootStore);if(S){let A=_;return A?async()=>{await A(),await S()}:()=>S()}return _}o(Ha,"preCommitBlobsForRecordBefore")}function PM(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 W4(){}function eA(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 Zy(parseInt(e.slice(1),36));if(e==="null")return null;if(!/^-?[0-9]+$/.test(e)&&!(e instanceof Date))throw new SyntaxError;return Zy(+e);case"Float":return e==="null"?null:Zy(+e);case"BigInt":return e==="null"?null:BigInt(e);case"Boolean":return e==="true"?!0:e==="false"?!1:e;case"Date":if(isNaN(e)){if(e==="null")return null;AIe.test(e)||(e+="Z");let n=new Date(e);return Zy(n.getTime()),n}return new Date(+e);case void 0:case"Any":return(0,tA.autoCast)(e);default:return e}}catch(n){throw n.message=`Invalid value for attribute ${t.name}: "${e}", expecting ${r}`,n.statusCode=400,n}}function Zy(e){if(isNaN(e))throw new SyntaxError;return e}function z4(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 ii(e,t,r){return e?.then?e.then(t,r):t(e)}function j4(e){return e!=null}function oi(e){try{return JSON.stringify(e)}catch{return e}}function bIe(e){let t=process.pid;return e.env.readerList().slice(1).some(r=>+r.match(/\d+/)?.[0]!=t)}var Yc,G_,J4,Q4,vu,ct,$_,V_,Ue,Uu,Mu,tA,DM,hIe,pIe,_Ie,EIe,gIe,$4,SIe,V4,TIe,Wn,Du,RIe,K4,Y4,yIe,VGe,AIe,Kc,hR=ce(()=>{H();Yc=require("lmdb"),G_=w(Cn()),J4=w(require("lodash")),Q4=w(Lm());tc();vm();vu=w(oe());Vw();ct=w(ge()),$_=w(Vo()),V_=w(Ti());Pe();Xg();Ue=w(hi());PN();ol();Uu=require("ordered-binary"),Mu=w(rt());Yi();tA=w(se());ml();io();Cg();vh();DM=w(require("node:fs"));ts();Hy();WD();({sortBy:hIe}=J4.default),{validateAttribute:pIe}=Q4.default,_Ie=new Uint8Array(9);_Ie[8]=192;EIe=6e4,gIe=864e5;vu.initSync();$4=vu.get(U.STORAGE_PREFETCHWRITES),SIe=1e4,V4=1,TIe=2,Wn=1,Du=8,RIe=Buffer.allocUnsafeSlow(8192),K4=1978,Y4=100,yIe={read:!0,insert:!0,update:!0,delete:!0,isSuperUser:!0},VGe=(0,tA.convertToMS)(vu.get(U.CLUSTERING_LEAFSERVER_STREAMS_MAXAGE))||864e5;o(rA,"makeTable");o(PM,"attributesAsObject");o(W4,"noop");AIe=/[+-][0-9]{2}:[0-9]{2}|[a-zA-Z]$/;o(eA,"coerceType");o(Zy,"rejectNaN");o(z4,"isDescendantId");Kc=o(()=>new Promise(setImmediate),"rest");o(ii,"when");o(j4,"exists");o(oi,"stringify");o(bIe,"hasOtherProcesses")});function nA(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,a=t[s]||0,c=i-a;r+=c*c}return r}function sA(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 a=0;a<i;a++){let c=e[a]||0,l=t[a]||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 X4=ce(()=>{o(nA,"euclideanDistance");o(sA,"cosineDistance")});var Z4,e3,tm,No,em,IIe,NIe,iA,t3=ce(()=>{X4();Z4=require("msgpackr"),e3=w(hi()),tm=w(ge()),No=(0,e3.loggerWithTag)("HNSW"),em=Symbol.for("entryPoint"),IIe=Symbol.for("key"),NIe=10,iA=class{static{o(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=Z4.FLOAT32_OPTIONS.ALWAYS),this.distance=r?.distance==="euclidean"?nA:sA,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"?[IIe,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 a=new Map,c,l=this.indexStore.get(em);if(n?c={...this.indexStore.get(i)}:c={},r){let f=l&&this.indexStore.get(l);if(f===void 0){let E=Math.floor(-Math.log(Math.random())*this.mL),g={vector:r,level:E,primaryKey:t};for(let R=0;R<=E;R++)g[R]=[];if(this.indexStore.put(i,g),typeof i!="number")throw new Error("Invalid nodeId: "+i);No.debug?.("setting entry point to",i),this.indexStore.put(em,i);return}let m=c.level??Math.min(Math.floor(-Math.log(Math.random())*this.mL),NIe),h=f.level;if(m>=h){if(typeof i!="number")throw new Error("Invalid nodeId: "+i);No.debug?.("setting entry point to",i),this.indexStore.put(em,i)}for(;h>m;){let E=this.searchLayer(r,l,f,this.efConstruction,h);E.length>0&&(l=E[0].id,f=E[0].node),h--}let p=new Array(m+1);for(let E=0;E<=m;E++)p[E]=[];for(let E=Math.min(m,h);E>=0;E--){let g=this.searchLayer(r,l,f,this.efConstruction,E);g=g.slice(0,this.M<<1),g.length===0&&E===0&&No.info?.("should not have zero connections for",l);let R=p[E];for(let T=0;T<g.length;T++){let{id:y,distance:N,node:O}=g[T];if(y===i)continue;let F=[];if(this.optimizeRouting){let Y=!1,K=O[E],$=1+this.optimizeRouting*(1+.5*T/this.M);for(let le=0;le<K.length;le++){let{id:ue,distance:ie}=K[le],me=1+this.optimizeRouting*(1+.5*le/this.M);for(let De=0;De<R.length;De++){let{id:Me,distance:ft}=R[De];if(Me===ue){N*$>ft+ie?Y=!0:ie*me>N+ft&&(F.push({fromId:Me,toId:y}),F.push({fromId:y,toId:Me}));break}}if(Y)break}if(Y)continue}else if(T>=(E>0?this.M:this.M<<1))continue;R.push({id:y,distance:N});for(let{fromId:Y,toId:K}of F){let $=d(Y);$||($=d(Y,this.indexStore.get(Y)));for(let le=0;le<$[E].length;le++)if($[E][le].id===K){Object.isFrozen($[E])&&($[E]=$[E].slice()),$[E].splice(le,1);break}}let Z=c[E],q=Z?.find(({id:Y})=>Y===y);if(q){let Y=Z?.indexOf(q);Z.copied||(Z=[...Z],Z.copied=!0,c[E]=Z),Z.splice(Y,1)}else this.addConnection(y,d(y,O),i,E,N,d)}}this.indexStore.put(i,{vector:r,level:m,primaryKey:t,...p})}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:h,value:p}of this.indexStore.getRange({start:0,end:1/0}))if(p.level>m){if(l=h,p.level===f)break;m=p.level}}if(l===void 0)this.indexStore.remove(em);else{if(typeof l!="number")throw new Error("Invalid nodeId: "+l);No.debug?.("setting entry point to",l),this.indexStore.put(em,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:h}of m){let p=d(h,this.indexStore.get(h));for(let E=0;E<=f;E++)p[E]=p[E]?.filter(({id:g})=>g!==i),p[E].length===0&&(No.info?.("node was left orphaned, will reindex",h),u.set(p.primaryKey,p.vector))}}function d(f,m){let h=a.get(f);return!h&&m&&(h={...m},a.set(f,h)),h}o(d,"updateNode");for(let[f,m]of a)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(em);if(t===void 0)return;let r=this.indexStore.get(t);return{id:t,...r}}searchLayer(t,r,n,s,i,a=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((h,p)=>h.distance-p.distance);let d=l.shift(),f=u[u.length-1].distance;if(d.distance>f)break;let m=d.node;for(let{id:h}of m[i]||[]){if(c.has(h)||h===void 0)continue;c.add(h);let p=this.indexStore.get(h);if(!p)continue;this.nodesVisitedCount++;let E=a(t,p.vector);if(E<f||u.length<s){let g={id:h,distance:E,node:p};l.push(g),u.push(g)}}u.sort((h,p)=>h.distance-p.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 a=0;switch(i){case"lt":case"le":a=r;case"sort":break;default:throw new tm.ClientError(`Can not use "${i}" comparator with HNSW`)}if(n)throw new tm.ClientError("Can not use descending sort order with HNSW");let c;if(s==="cosine")c=sA;else if(s==="euclidean")c=nA;else{if(s)throw new tm.ClientError("Unknown distance function");c=this.distance}if(!t)throw new tm.ClientError("A target vector must be provided for an HNSW query");if(!Array.isArray(t))throw new tm.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 a&&(d=d.filter(f=>f.distance<a)),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 a=this.indexStore.get(i);if(!a){No.info?.("could not find neighbor node",a);continue}a[n]?.find(({id:l})=>l==t)||No.info?.("asymmetry detected",a[n])}n++}}addConnection(t,r,n,s,i,a){r[s]||(r[s]=[]);let c=s===0?this.M<<1:this.M;if(this.optimizeRouting&&(c<<=2),r[s].length>=c+(c>>2)){No.warn?.("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=a(f.id)??this.indexStore.get(f.id);m&&m[s]&&(m=a(f.id,m),m[s]=m[s].filter(({id:h})=>h!==t),s===0&&m[s].length===0&&No.info?.("should not remove last connection",t,n))}}r[s].find(({id:l})=>l===n)?No.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 a=s.shift(),c=this.indexStore.get(a);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 a=this.distance;s.type&&(a=s.distance==="euclidean"?nA:sA);let c=a(s.target,t);return i.set(n,c),c}return t}}});var LM,r3=ce(()=>{t3();LM={HNSW:iA}});var ut={};we(ut,{database:()=>Ed,databaseEnvs:()=>wa,databases:()=>He,dropDatabase:()=>UN,dropTableMeta:()=>DIe,getDatabases:()=>st,getDefaultCompression:()=>LT,getTables:()=>wIe,onRemovedDB:()=>np,onUpdatedTable:()=>jl,readMetaDb:()=>K_,resetDatabases:()=>mf,table:()=>ze,tables:()=>fn});function wIe(){return lA||st(),fn||{}}function st(){if(lA)return He;lA=!0,sm=new Map;let e=(0,Zt.getHdbBasePath)()&&(0,Gt.join)((0,Zt.getHdbBasePath)(),il),t=(0,Zt.get)(U.DATABASES)||{};if(process.env.SCHEMAS_DATA_PATH&&(t.data={path:process.env.SCHEMAS_DATA_PATH}),e=process.env.STORAGE_PATH||(0,Zt.get)(U.STORAGE_PATH)||e&&((0,bs.existsSync)(e)?e:(0,Gt.join)((0,Zt.getHdbBasePath)(),gE)),!e)return;if((0,bs.existsSync)(e))for(let n of(0,bs.readdirSync)(e,{withFileTypes:!0})){let s=(0,Gt.basename)(n.name,".mdb");n.isFile()&&(0,Gt.extname)(n.name).toLowerCase()===".mdb"&&!t[s]?.path&&K_((0,Gt.join)(e,n.name),null,s)}if((0,bs.existsSync)((0,nm.getBaseSchemaPath)())){for(let n of(0,bs.readdirSync)((0,nm.getBaseSchemaPath)(),{withFileTypes:!0}))if(!n.isFile()){let s=(0,Gt.join)((0,nm.getBaseSchemaPath)(),n.name),i=(0,Gt.join)((0,nm.getTransactionAuditStoreBasePath)(),n.name);for(let a of(0,bs.readdirSync)(s,{withFileTypes:!0}))if(a.isFile()&&(0,Gt.extname)(a.name).toLowerCase()===".mdb"){let c=(0,Gt.join)(i,a.name);K_((0,Gt.join)(s,a.name),(0,Gt.basename)(a.name,".mdb"),n.name,c,!0)}}}if(t)for(let n in t){let s=t[n],i=s.path;if((0,bs.existsSync)(i))for(let c of(0,bs.readdirSync)(i,{withFileTypes:!0}))c.isFile()&&(0,Gt.extname)(c.name).toLowerCase()===".mdb"&&K_((0,Gt.join)(i,c.name),(0,Gt.basename)(c.name,".mdb"),n);let a=s.tables;if(a)for(let c in a){let l=a[c],u=(0,Gt.join)(l.path,(0,Gt.basename)(c+".mdb"));(0,bs.existsSync)(u)&&K_(u,c,n,null,!0)}}for(let n in He){let s=sm.get(n);if(s){let i=He[n];n.includes("delete")&&Pr.trace(`defined tables ${Array.from(s.keys())}`);for(let a in i)s.has(a)||(Pr.trace(`delete table class ${a}`),delete i[a])}else if(delete He[n],n==="data"){for(let i in fn)delete fn[i];delete fn[uA]}}let r=["hdb_temp","hdb_certificate","hdb_raw_analytics","hdb_session_will","hdb_job","hdb_license","hdb_info"];if((0,Zt.get)(U.ANALYTICS_REPLICATE)===!1?r.push("hdb_analytics"):(He.system?.hdb_analytics?.enableAuditing(),He.system?.hdb_analytics_hostname?.enableAuditing()),He.system)for(let n of r)He.system[n]&&(He.system[n].replicate=!1);return sm=null,He}function mf(){lA=!1;for(let[,e]of wa)e.needsDeletion=!0;st();for(let[e,t]of wa)if(t.needsDeletion&&!e.endsWith("system.mdb")){t.close(),wa.delete(e);let r=He[t.databaseName];for(let n in r)if(r[n].primaryStore.path===e){delete He[t.databaseName],W_.forEach(i=>i(t.databaseName));break}}return He}function K_(e,t,r=UM,n,s){let i=new MM.default(e,!1);try{let a=wa.get(e);a?a.needsDeletion=!1:(a=(0,im.open)(i),wa.set(e,a));let c=new om.default(!1),l=a.dbisDb||(a.dbisDb=a.openDB(oA.INTERNAL_DBIS_NAME,c)),u=a.auditStore;u||(n?(0,bs.existsSync)(n)&&(i.path=n,u=(0,im.open)(i),u.isLegacy=!0):u=Gy(a));let d=a3(r),f=d[uA],m=new Map;for(let{key:h,value:p}of l.getRange({start:!1})){let[E,g]=h.toString().split("/");g===""?g=p.name:g||(g=E,E=t,p.name||(p.name=g,p.indexed=!p.is_hash_attribute)),f?.add(E);let R=m.get(E);R||m.set(E,R={attributes:[]}),(g==null||p.is_hash_attribute)&&(R.primary=p),g!=null&&R.attributes.push(p),Object.defineProperty(p,"key",{value:h,configurable:!0})}for(let[h,p]of m){let{attributes:E,primary:g}=p;if(!g){for(let ie of E)if(ie.is_hash_attribute||ie.isPrimaryKey){g=ie;break}if(!g){Pr.warn(`Unable to find a primary key attribute on table ${h}, with attributes: ${JSON.stringify(E)}`);continue}}let R=d[h],T={},y=[],N,O,F=typeof g.audit=="boolean"?g.audit:(0,Zt.get)(U.LOGGING_AUDITLOG),Z=g.trackDeletes,q=g.expiration,Y=g.eviction,K=g.sealed,$=g.splitSegments,le=g.replicate;if(R)T=R.indices,y=R.attributes,R.schemaVersion++;else{N=g.tableId,N?N>=(l.get(rm)||0)&&(l.putSync(rm,N+1),Pr.info(`Updating next table id (it was out of sync) to ${N+1} for ${h}`)):(g.tableId=N=l.get(rm),N||(N=1),Pr.debug("Table {tableName} missing an id, assigning {tableId}"),l.putSync(rm,N+1),l.putSync(g.key,g));let ie=new om.default(!g.is_hash_attribute,g.is_hash_attribute);if(ie.compression=g.compression,ie.compression){let me=(0,Zt.get)(U.STORAGE_COMPRESSION_THRESHOLD)||o3;ie.compression.threshold=me}O=jy(a.openDB(g.key,ie),a),a.databaseName=r,O.tableId=N}let ue;for(let ie of E){ie.attribute=ie.name;try{if(!ie.is_hash_attribute&&(ie.indexed||ie.attribute&&!ie.name)){if(!T[ie.name]){let De=l3(ie.key,a,ie);T[ie.name]=De,T[ie.name].indexNulls=ie.indexNulls}let me=y.find(De=>De.name===ie.name);me?y.splice(y.indexOf(me),1,ie):y.push(ie),ue=!0}}catch(me){Pr.error("Error trying to update attribute",ie,y,T,me)}}for(let ie of y)if(!E.find(De=>De.name===ie.name)){if(ie.is_hash_attribute){Pr.error("Unable to remove existing primary key attribute",ie);continue}ie.indexed&&(y.splice(y.indexOf(ie),1),ue=!0)}if(R)ue&&(R.schemaVersion++,R.updatedAttributes());else{R=c3(d,h,rA({primaryStore:O,auditStore:u,audit:F,sealed:K,splitSegments:$,replicate:le,expirationMS:q&&q*1e3,evictionMS:Y&&Y*1e3,trackDeletes:Z,tableName:h,tableId:N,primaryKey:g.name,databasePath:s?r+"/"+h:r,databaseName:r,indices:T,attributes:E,schemaDefined:g.schemaDefined,dbisDB:l})),R.schemaVersion=1;for(let ie of Y_)ie(R)}}return a}catch(a){throw a.message+=` opening database ${e}`,a}}function a3(e){let t=He[e];if(t||(e==="data"?t=He[e]=fn:e==="system"?Object.defineProperty(He,"system",{value:t=Object.create(null),configurable:!0}):t=He[e]=Object.create(null)),sm&&!sm.has(e)){let r=new Set;t[uA]=r,sm.set(e,r)}return t}function c3(e,t,r){return e[t]=r,r}function Ed({database:e,table:t}){e||(e=UM),st();let r=a3(e),n=(0,Gt.join)((0,Zt.getHdbBasePath)(),il),s=(0,Zt.get)(U.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)(U.STORAGE_PATH)||((0,bs.existsSync)(n)?n:(0,Gt.join)((0,Zt.getHdbBasePath)(),gE));let a=(0,Gt.join)(n,(i?t:e)+".mdb"),c=wa.get(a);if(!c||c.status==="closed"){let l=new MM.default(a,!1);c=(0,im.open)(l),wa.set(a,c)}return c.auditStore||(c.auditStore=Gy(c)),c}async function UN(e){if(!He[e])throw new Error("Schema does not exist");let t=He[e],r;for(let n in t)r=t[n].primaryStore.rootStore,wa.delete(r.path),r.status==="open"&&(await r.close(),await z_.remove(r.path));if(r||(r=Ed({database:e,table:null}),r.status==="open"&&(await r.close(),await z_.remove(r.path))),e==="data"){for(let n in fn)delete fn[n];delete fn[uA]}delete He[e],W_.forEach(n=>n(e)),await Tb(r)}function l3(e,t,r){let n=r.is_hash_attribute||r.indexed.type&&LM[r.indexed.type]?.useObjectStore,s=new om.default(!n,n),i=t.openDB(e,s);if(r.indexed.type){let a=LM[r.indexed.type];a?i.customIndex=new a(i,r.indexed):Pr.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:a,audit:c,sealed:l,splitSegments:u,replicate:d,trackDeletes:f,schemaDefined:m,origin:h}=e;r||(r=UM);let p=Ed({database:r,table:t}),E=He[r];Pr.trace(`Defining ${t} in ${r}`);let g=E?.[t];if(p.status==="closed")throw new Error(`Can not use a closed data store for ${t}`);let R,T,y;m==null&&(m=!0);let N=new om.default(!1);for(let $ of a)$.attribute&&!$.name?($.name=$.attribute,$.indexed=!0):$.attribute=$.name,$.expiresAt&&($.indexed=!0);let O,F;if(g){if(R=g.primaryKey,g.primaryStore.rootStore.status==="closed")throw new Error(`Can not use a closed data store from ${t} class`);u==null&&(u=g.splitSegments),g.attributes.splice(0,g.attributes.length,...a)}else{let $=p.auditStore;T=a.find(me=>me.isPrimaryKey)||{},R=T.name,T.is_hash_attribute=T.isPrimaryKey=!0,T.schemaDefined=m,T.compression=LT(),f&&(T.trackDeletes=!0),c=T.audit=typeof c=="boolean"?c:(0,Zt.get)(U.LOGGING_AUDITLOG),n&&(T.expiration=n),s&&(T.eviction=s),u??=!1,T.splitSegments=u,typeof l=="boolean"&&(T.sealed=l),typeof d=="boolean"&&(T.replicate=d),h&&(T.origins?T.origins.includes(h)||T.origins.push(h):T.origins=[h]),Pr.trace(`${t} table loading, opening primary store`);let le=new om.default(!1,!0);le.compression=T.compression;let ue=t+"/";if(y=p.dbisDb=p.openDB(oA.INTERNAL_DBIS_NAME,N),K(),y.get(ue))return F&&F(),mf(),ze(e);let ie=jy(p.openDB(ue,le),p);p.databaseName=r,ie.tableId=y.get(rm),Pr.trace(`Assigning new table id ${ie.tableId} for ${t}`),ie.tableId||(ie.tableId=1),y.put(rm,ie.tableId+1),T.tableId=ie.tableId,g=c3(E,t,rA({primaryStore:ie,auditStore:$,audit:c,sealed:l,splitSegments:u,replicate:d,trackDeletes:f,expirationMS:n&&n*1e3,evictionMS:s&&s*1e3,primaryKey:R,tableName:t,tableId:ie.tableId,databasePath:r,databaseName:r,indices:{},attributes:a,schemaDefined:m,dbisDB:y})),g.schemaVersion=1,O=!0,y.put(ue,T)}let Z=g.indices;y=y||(p.dbisDb=p.openDB(oA.INTERNAL_DBIS_NAME,N)),g.dbisDB=y;let q=[];for(let{key:$,value:le}of y.getRange({start:!0})){let[ue,ie]=$.toString().split("/");if(ie===""&&(ie=le.name),ie){if(ue!==t)continue}else continue;let me=a.find(Me=>Me.name===ie),De=!me?.indexed&&le.indexed&&!le.isPrimaryKey;if((!me||De)&&(K(),O=!0,me||y.remove($),De)){let Me=g.indices[ue];Me&&q.push(Me)}}let Y=[];try{for(let $ of a||[]){if(($.relationship||$.computed)&&(O=!0,$.relationship))continue;let le=t+"/"+($.name||"");Object.defineProperty($,"key",{value:le,configurable:!0});let ue=y.get(le);if($.isPrimaryKey){if(ue=ue||y.get(le=t+"/")||{},c!==void 0&&c!==g.audit||l!==void 0&&l!==g.sealed||d!==void 0&&d!==g.replicate||(+n||void 0)!==(+ue.expiration||void 0)||(+s||void 0)!==(+ue.eviction||void 0)||$.type!==ue.type){let me={...ue};typeof c=="boolean"&&(c&&g.enableAuditing(c),me.audit=c),n&&(me.expiration=+n),s&&(me.eviction=+s),l!==void 0&&(me.sealed=l),d!==void 0&&(me.replicate=d),$.type&&(me.type=$.type),O=!0,K(),y.put(le,me)}continue}ue?.attribute&&!ue.name&&(ue.indexed=!0);let ie=!ue||ue.type!==$.type||JSON.stringify(ue.indexed)!==JSON.stringify($.indexed)||ue.nullable!==$.nullable||ue.version!==$.version||JSON.stringify(ue.properties)!==JSON.stringify($.properties)||JSON.stringify(ue.elements)!==JSON.stringify($.elements);if($.indexed){let me=l3(le,p,$);(ie||ue.indexingPID&&ue.indexingPID!==process.pid||ue.restartNumber<j_.workerData?.restartNumber)&&(O=!0,K(),ue=y.get(le),(ie||ue.indexingPID&&ue.indexingPID!==process.pid||ue.restartNumber<j_.workerData?.restartNumber)&&(O=!0,$.indexNulls===void 0&&($.indexNulls=!0),g.primaryStore.getStats().entryCount>0&&($.lastIndexedKey=ue?.lastIndexedKey??void 0,$.indexingPID=process.pid,me.isIndexing=!0,Object.defineProperty($,"dbi",{value:me}),Y.push($))),y.put(le,$)),ue?.indexNulls&&$.indexNulls===void 0&&($.indexNulls=!0),me.indexNulls=$.indexNulls,Z[$.name]=me}else ie&&(O=!0,K(),y.put(le,$))}}finally{F&&F()}if(O&&(g.schemaVersion++,g.updatedAttributes()),Pr.trace(`${t} table loading, running index`),Y.length>0||q.length>0?g.indexingOperation=PIe(g,Y,q):O&&aA.signalSchemaChange(new cA.SchemaEventMsg(process.pid,"schema-change",g.databaseName,g.tableName)),g.origin=h,O)for(let $ of Y_)$(g,h!=="cluster");return(n||s||i)&&g.setTTLExpiration({expiration:n,eviction:s,scanInterval:i}),Pr.trace(`${t} table loaded`),g;function K(){F||p.transactionSync(()=>({then($){F=$}}))}o(K,"startTxn")}async function PIe(e,t,r){try{Pr.info(`Indexing ${e.tableName} attributes`,t);let n=e.schemaVersion;await aA.signalSchemaChange(new cA.SchemaEventMsg(process.pid,"schema-change",e.databaseName,e.tableName));let s;for(let u of r)s=u.drop();let i,a={},c=0,l=t.length;if(await new Promise(u=>setImmediate(u)),l>0){let u;for(let f of t)(0,im.compareKeys)(f.lastIndexedKey,u)<0&&(u=f.lastIndexedKey),f.lastIndexedKey==null&&f.dbi.clearAsync();let d=0;for(let{key:f,value:m,version:h}of e.primaryStore.getRange({start:u,lazy:l<4,versions:!0,snapshot:!1}))if(m){if(d++,s=e.primaryStore.ifVersion(f,h,()=>{for(let p=0;p<l;p++){let E=t[p],g=E.name,R=E.dbi;try{let T=E.resolve,y=m&&(T?T(m):m[g]);if(R.customIndex){R.customIndex.index(f,y);continue}let N=(0,n3.getIndexedValues)(y);if(N)for(let O=0,F=N.length;O<F;O++)R.put(N[O],f)}catch(T){a[g]||(a[g]=!0,Pr.error(`Error indexing attribute ${g}`,T))}}}),s.then(()=>d--,p=>{d--,Pr.error(p)}),j_.workerData&&j_.workerData.restartNumber!==i3.restartNumber&&(i=!0),++c%100===0||i){for(let p of t)p.lastIndexedKey=f,e.dbisDB.put(p.key,p);if(i)return}d>OIe?await s:d>CIe&&await new Promise(p=>setImmediate(p))}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 aA.signalSchemaChange(new cA.SchemaEventMsg(process.pid,"indexing-finished",e.databaseName,e.tableName)),Pr.info(`Finished indexing ${e.tableName} attributes`,t)}catch(n){Pr.error("Error in indexing",n)}}function DIe({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 jl(e){return Y_.push(e),{remove(){let t=Y_.indexOf(e);t>-1&&Y_.splice(t,1)}}}function np(e){return W_.push(e),{remove(){let t=W_.indexOf(e);t>-1&&W_.splice(t,1)}}}function LT(){let e=(0,Zt.get)(U.STORAGE_COMPRESSION),t=(0,Zt.get)(U.STORAGE_COMPRESSION_DICTIONARY),r=(0,Zt.get)(U.STORAGE_COMPRESSION_THRESHOLD)||o3,n={startingOffset:32};return t&&(n.dictionary=z_.readFileSync(t)),r&&(n.threshold=r),e&&n}var Zt,oA,im,Gt,bs,nm,om,MM,z_,vM,n3,aA,cA,j_,s3,i3,Pr,UM,uA,o3,fn,He,rm,Y_,W_,lA,wa,sm,OIe,CIe,Pe=ce(()=>{Zt=w(oe()),oA=w(Kt()),im=require("lmdb"),Gt=require("path"),bs=require("fs"),nm=w(Nt());hR();om=w(Ym()),MM=w(Wm());H();z_=w(require("fs-extra")),vM=w(mi()),n3=w(Cn()),aA=w(Vo()),cA=w(Ti()),j_=require("worker_threads"),s3=w(j()),i3=w(rt());Yi();ml();ts();r3();Pr=(0,s3.forComponent)("storage"),UM="data",uA=Symbol("defined-tables"),o3=((0,Zt.get)(U.STORAGE_PAGESIZE)||4096)-60;(0,Zt.initSync)();fn=Object.create(null),He=Object.create(null);(0,vM._assignPackageExport)("databases",He);(0,vM._assignPackageExport)("tables",fn);rm=Symbol.for("next-table-id"),Y_=[],W_=[],wa=new Map;o(wIe,"getTables");o(st,"getDatabases");o(mf,"resetDatabases");o(K_,"readMetaDb");o(a3,"ensureDB");o(c3,"setTable");o(Ed,"database");o(UN,"dropDatabase");o(l3,"openIndex");o(ze,"table");OIe=1e3,CIe=10;o(PIe,"runIndexing");o(DIe,"dropTableMeta");o(jl,"onUpdatedTable");o(np,"onRemovedDB");o(LT,"getDefaultCompression")});var se=M(be=>{"use strict";var Wc=require("path"),h3=require("fs-extra"),jn=j(),u3=require("fs-extra"),dA=require("os"),LIe=require("net"),MIe=require("recursive-iterator"),Dr=(H(),v(W)),{PACKAGE_ROOT:vIe}=ht(),UIe=ZA(),d3=require("papaparse"),fA=require("moment"),{inspect:xIe}=require("util"),f3=require("is-number"),BIe=require("minimist"),FIe=require("https"),HIe=require("http"),kIe=/^((\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d\.\d+([+-][0-2]\d:[0-5]\d|Z))|(\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d([+-][0-2]\d:[0-5]\d|Z))|(\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d([+-][0-2]\d:[0-5]\d|Z)))$/,p3=require("util").promisify(setTimeout),qIe=100,GIe=5,$Ie="",VIe=4,m3={true:!0,TRUE:!0,FALSE:!1,false:!1,undefined:null,null:null,NULL:null,NaN:NaN};be.isEmpty=Is;be.isEmptyOrZeroLength=wo;be.arrayHasEmptyValues=WIe;be.arrayHasEmptyOrZeroLengthValues=zIe;be.buildFolderPath=jIe;be.isBoolean=_3;be.errorizeMessage=KIe;be.stripFileExtension=QIe;be.autoCast=XIe;be.autoCastJSON=E3;be.autoCastJSONDeep=BM;be.removeDir=ZIe;be.compareVersions=eNe;be.isCompatibleDataVersion=tNe;be.escapeRawValue=rNe;be.unescapeValue=nNe;be.stringifyProps=sNe;be.timeoutPromise=oNe;be.isClusterOperation=cNe;be.getClusterUser=uNe;be.checkGlobalSchemaTable=lNe;be.getHomeDir=S3;be.getPropsFilePath=iNe;be.promisifyPapaParse=dNe;be.removeBOM=T3;be.createEventPromise=fNe;be.checkProcessRunning=mNe;be.checkSchemaTableExist=hNe;be.checkSchemaExists=R3;be.checkTableExists=y3;be.getStartOfTomorrowInSeconds=pNe;be.getLimitKey=_Ne;be.isObject=JIe;be.isNotEmptyAndHasValue=YIe;be.autoCasterIsNumberCheck=g3;be.backtickASTSchemaItems=ENe;be.isPortTaken=aNe;be.createForkArgs=gNe;be.autoCastBoolean=SNe;be.asyncSetTimeout=p3;be.getTableHashAttribute=TNe;be.doesSchemaExist=RNe;be.doesTableExist=yNe;be.stringifyObj=ANe;be.ms_to_time=bNe;be.changeExtension=INe;be.getEnvCliRootPath=FM;be.noBootFile=NNe;be.httpRequest=wNe;be.transformReq=ONe;be.convertToMS=CNe;be.PACKAGE_ROOT=vIe;function KIe(e){return e instanceof Error?e:new Error(e)}o(KIe,"errorizeMessage");function Is(e){return e==null}o(Is,"isEmpty");function YIe(e){return!Is(e)&&(e||e===0||e===""||_3(e))}o(YIe,"isNotEmptyAndHasValue");function wo(e){return Is(e)||e.length===0||e.size===0}o(wo,"isEmptyOrZeroLength");function WIe(e){if(Is(e))return!0;for(let t=0;t<e.length;t++)if(Is(e[t]))return!0;return!1}o(WIe,"arrayHasEmptyValues");function zIe(e){if(wo(e))return!0;for(let t=0;t<e.length;t++)if(wo(e[t]))return!0;return!1}o(zIe,"arrayHasEmptyOrZeroLengthValues");function jIe(...e){try{return e.join(Wc.sep)}catch{console.error(e)}}o(jIe,"buildFolderPath");function _3(e){return Is(e)?!1:e===!0||e===!1}o(_3,"isBoolean");function JIe(e){return Is(e)?!1:typeof e=="object"}o(JIe,"isObject");function QIe(e){return wo(e)?$Ie:e.slice(0,-VIe)}o(QIe,"stripFileExtension");function XIe(e){return Is(e)||e===""||typeof e!="string"?e:m3[e]!==void 0?m3[e]:g3(e)===!0?Number(e):kIe.test(e)?new Date(e):e}o(XIe,"autoCast");function E3(e){if(typeof e=="string"&&(e.startsWith("{")&&e.endsWith("}")||e.startsWith("[")&&e.endsWith("]")))try{return JSON.parse(e)}catch{}return e}o(E3,"autoCastJSON");function BM(e){if(e&&typeof e=="object"){if(Array.isArray(e))for(let t=0,r=e.length;t<r;t++){let n=e[t],s=BM(n);s!==n&&(e[t]=s)}else for(let t in e){let r=e[t],n=BM(r);n!==r&&(e[t]=n)}return e}else return E3(e)}o(BM,"autoCastJSONDeep");function g3(e){if(e.startsWith("0.")&&f3(e))return!0;let t=e.toUpperCase().includes("E");return!!((e!=="0"&&e.startsWith("0"))===!1&&t===!1&&f3(e))}o(g3,"autoCasterIsNumberCheck");async function ZIe(e){if(wo(e))throw new Error(`Directory path: ${e} does not exist`);try{await u3.emptyDir(e),await u3.remove(e)}catch(t){throw jn.error(`Error removing files in ${e} -- ${t}`),t}}o(ZIe,"removeDir");function eNe(e,t){if(wo(e)){jn.info("Invalid current version sent as parameter.");return}if(wo(t)){jn.info("Invalid upgrade version sent as parameter.");return}let r,n=/(\.0+)+$/,s=e.version?e.version:e,i=t.version?t.version:t,a=s.replace(n,"").split("."),c=i.replace(n,"").split("."),l=Math.min(a.length,c.length);for(let u=0;u<l;u++)if(r=parseInt(a[u],10)-parseInt(c[u],10),r)return r;return a.length-c.length}o(eNe,"compareVersions");function tNe(e,t,r=!1){let n=e.toString().split("."),s=t.toString().split(".");return n[0]===s[0]&&(!r||n[1]===s[1])}o(tNe,"isCompatibleDataVersion");function rNe(e){if(Is(e))return e;let t=String(e);return t==="."?Dr.UNICODE_PERIOD:t===".."?Dr.UNICODE_PERIOD+Dr.UNICODE_PERIOD:t.replace(Dr.FORWARD_SLASH_REGEX,Dr.UNICODE_FORWARD_SLASH)}o(rNe,"escapeRawValue");function nNe(e){if(Is(e))return e;let t=String(e);return t===Dr.UNICODE_PERIOD?".":t===Dr.UNICODE_PERIOD+Dr.UNICODE_PERIOD?"..":String(e).replace(Dr.ESCAPED_FORWARD_SLASH_REGEX,"/")}o(nNe,"unescapeValue");function sNe(e,t){if(Is(e))return jn.info("Properties object is null"),"";let r="";return e.each(function(n,s){try{if(t&&t[n]){let i=t[n];for(let a of i)r+=";"+a+dA.EOL}!wo(n)&&n[0]===";"?r+=" "+n+s+dA.EOL:wo(n)||(r+=n+"="+s+dA.EOL)}catch{jn.error(`Found bad property during upgrade with key ${n} and value: ${s}`)}}),r}o(sNe,"stringifyProps");function S3(){let e;try{e=dA.homedir()}catch{e=process.env.HOME}return e}o(S3,"getHomeDir");function iNe(){let e=Wc.join(S3(),Dr.HDB_HOME_DIR_NAME,Dr.BOOT_PROPS_FILE_NAME);return h3.existsSync(e)||(e=Wc.join(__dirname,"../","hdb_boot_properties.file")),e}o(iNe,"getPropsFilePath");function oNe(e,t){let r,n;return n=new Promise(function(s){r=setTimeout(function(){s(t)},e)}),{promise:n,cancel:o(function(){clearTimeout(r)},"cancel")}}o(oNe,"timeoutPromise");async function aNe(e){if(!e)throw new Error("Invalid port passed as parameter");return new Promise((t,r)=>{let n=LIe.createServer().once("error",s=>{s.code==="EADDRINUSE"?t(!0):r(s)}).once("listening",()=>n.once("close",()=>t(!1)).close()).listen(e)})}o(aNe,"isPortTaken");function cNe(e){try{return Dr.CLUSTER_OPERATIONS[e.toLowerCase()]!==void 0}catch(t){jn.error(`Error checking operation against cluster ops ${t}`)}return!1}o(cNe,"isClusterOperation");function lNe(e,t){let r=(Pe(),v(ut)).getDatabases();if(!r[e])return mA.HDB_ERROR_MSGS.SCHEMA_NOT_FOUND(e);if(!r[e][t])return mA.HDB_ERROR_MSGS.TABLE_NOT_FOUND(e,t)}o(lNe,"checkGlobalSchemaTable");function uNe(e,t){if(Is(t)){jn.warn("No CLUSTERING_USER defined, clustering disabled");return}if(Is(e)||wo(e)){jn.warn("No users to search.");return}let r;try{let n=e.get(t);n&&n.role.permission.cluster_user===!0&&n.active===!0&&(r=n)}catch(n){jn.error(`unable to find cluster_user due to: ${n.message}`);return}if(r===void 0){jn.warn(`CLUSTERING_USER: ${t} not found or is not active.`);return}return r}o(uNe,"getClusterUser");function dNe(){d3.parsePromise=function(e,t,r){return new Promise(function(n,s){d3.parse(e,{header:!0,transformHeader:T3,chunk:t.bind(null,s),skipEmptyLines:!0,transform:r,dynamicTyping:!1,error:s,complete:n})})}}o(dNe,"promisifyPapaParse");function T3(e){if(typeof e!="string")throw new TypeError(`Expected a string, got ${typeof e}`);return e.charCodeAt(0)===65279?e.slice(1):e}o(T3,"removeBOM");function fNe(e,t,r){return new Promise(n=>{t.once(e,s=>{let i=r;jn.info(`Got cluster status event response: ${xIe(s)}`);try{i.cancel()}catch{jn.error("Error trying to cancel timeout.")}n(s)})})}o(fNe,"createEventPromise");async function mNe(e){let t=!0,r=0;do await p3(qIe*r++),(await UIe.findPs(e)).length>0&&(t=!1);while(t&&r<GIe);if(t)throw new Error(`process ${e} was not started`)}o(mNe,"checkProcessRunning");function hNe(e,t){let r=R3(e);if(r)return r;let n=y3(e,t);if(n)return n}o(hNe,"checkSchemaTableExist");function R3(e){let{getDatabases:t}=(Pe(),v(ut));if(!t()[e])return mA.HDB_ERROR_MSGS.SCHEMA_NOT_FOUND(e)}o(R3,"checkSchemaExists");function y3(e,t){let{getDatabases:r}=(Pe(),v(ut));if(!r()[e][t])return mA.HDB_ERROR_MSGS.TABLE_NOT_FOUND(e,t)}o(y3,"checkTableExists");function pNe(){let e=fA().utc().add(1,"d").startOf("d").unix(),t=fA().utc().unix();return e-t}o(pNe,"getStartOfTomorrowInSeconds");function _Ne(){return fA().utc().format("DD-MM-YYYY")}o(_Ne,"getLimitKey");function ENe(e){try{let t=new MIe(e);for(let{node:r}of t)r&&(r.columnid&&typeof r.columnid!="string"&&(r.columnid=r.columnid.toString()),r.columnid&&!r.columnid.startsWith("`")&&(r.columnid_orig=r.columnid,r.columnid=`\`${r.columnid}\``),r.tableid&&!r.tableid.startsWith("`")&&(r.tableid_orig=r.tableid,r.tableid=`\`${r.tableid}\``),r.databaseid&&!r.databaseid.startsWith("`")&&(r.databaseid_orig=r.databaseid,r.databaseid=`\`${r.databaseid}\``),r.as&&typeof r.as=="string"&&!r.as.startsWith("[")&&(r.as_orig=r.as,r.as=`\`${r.as}\``))}catch(t){jn.error("Got an error back ticking items."),jn.error(t)}}o(ENe,"backtickASTSchemaItems");function gNe(e){return[e]}o(gNe,"createForkArgs");function SNe(e){return e===!0||typeof e=="string"&&e.toLowerCase()==="true"}o(SNe,"autoCastBoolean");function TNe(e,t){let{getDatabases:r}=(Pe(),v(ut)),n=r()[e]?.[t];return n?.primaryKey||n?.hash_attribute}o(TNe,"getTableHashAttribute");function RNe(e){let{getDatabases:t}=(Pe(),v(ut));return t()[e]!==void 0}o(RNe,"doesSchemaExist");function yNe(e,t){let{getDatabases:r}=(Pe(),v(ut));return r()[e]?.[t]!==void 0}o(yNe,"doesTableExist");function ANe(e){try{return JSON.stringify(e)}catch{return e}}o(ANe,"stringifyObj");function bNe(e){let t=fA.duration(e),r=t.seconds()>0?t.seconds()+"s":"",n=t.minutes()>0?t.minutes()+"m ":"",s=t.hours()>0?t.hours()+"h ":"",i=t.days()>0?t.days()+"d ":"";return(t.years()>0?t.years()+"y ":"")+i+s+n+r}o(bNe,"ms_to_time");function INe(e,t){let r=Wc.basename(e,Wc.extname(e));return Wc.join(Wc.dirname(e),r+t)}o(INe,"changeExtension");function FM(){if(process.env[Dr.CONFIG_PARAMS.ROOTPATH.toUpperCase()])return process.env[Dr.CONFIG_PARAMS.ROOTPATH.toUpperCase()];let e=BIe(process.argv);if(e[Dr.CONFIG_PARAMS.ROOTPATH.toUpperCase()])return e[Dr.CONFIG_PARAMS.ROOTPATH.toUpperCase()]}o(FM,"getEnvCliRootPath");var xM;function NNe(){if(xM)return xM;let e=FM();if(FM()&&h3.pathExistsSync(Wc.join(e,Dr.HDB_CONFIG_FILE)))return xM=!0,!0}o(NNe,"noBootFile");function wNe(e,t){let r;return e.protocol==="http:"?r=HIe:r=FIe,new Promise((n,s)=>{let i=r.request(e,a=>{a.setEncoding("utf8"),a.body="",a.on("data",c=>{a.body+=c}),a.on("end",()=>{n(a)})});i.on("error",a=>{s(a)}),i.write(t instanceof Buffer?t:JSON.stringify(t)),i.end()})}o(wNe,"httpRequest");function ONe(e){if(!e.schema&&!e.database){e.schema=Dr.DEFAULT_DATABASE_NAME;return}e.database&&(e.schema=e.database)}o(ONe,"transformReq");function CNe(e){let t=0;if(typeof e=="number"&&(t=e),typeof e=="string")switch(t=parseFloat(e),e.slice(-1)){case"M":t*=86400*30;break;case"D":case"d":t*=86400;break;case"H":case"h":t*=3600;break;case"m":t*=60;break}return t*1e3}o(CNe,"convertToMS");var mA=Vr()});var oe=M((N3,w3)=>{"use strict";var HM=require("fs-extra"),xu=require("path"),A3=require("os"),PNe=require("properties-reader"),Q_=j(),J_=se(),Be=(H(),v(W)),hA=gt(),DNe="Error initializing environment manager",pA="BOOT_PROPS_FILE_PATH",b3=!1,LNe={[Be.HDB_SETTINGS_NAMES.INSTALL_USER]:!0,[Be.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY]:!0,[Be.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]:!0,BOOT_PROPS_FILE_PATH:!0},Oa={};Object.assign(N3,w3.exports={BOOT_PROPS_FILE_PATH:pA,getHdbBasePath:MNe,setHdbBasePath:vNe,get:I3,initSync:xNe,setProperty:Qe,initTestEnvironment:BNe});function MNe(){return Oa[Be.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]}o(MNe,"getHdbBasePath");function vNe(e){Oa[Be.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]=e}o(vNe,"setHdbBasePath");function I3(e){let t=hA.getConfigValue(e);return t===void 0?Oa[e]:t}o(I3,"get");function Qe(e,t){LNe[e]&&(Oa[e]=t),hA.updateConfigObject(e,t)}o(Qe,"setProperty");function UNe(){let e;try{e=J_.getPropsFilePath(),HM.accessSync(e,HM.constants.F_OK|HM.constants.R_OK),b3=!0;let t=PNe(e);return Oa[Be.HDB_SETTINGS_NAMES.INSTALL_USER]=t.get(Be.HDB_SETTINGS_NAMES.INSTALL_USER),Oa[Be.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY]=t.get(Be.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY),Oa[pA]=e,!0}catch{return Q_.trace(`Environment manager found no properties file at ${e}`),!1}}o(UNe,"doesPropFileExist");function xNe(e=!1){try{(b3||UNe()||J_.noBootFile()||e)&&(hA.initConfig(e),Oa[Be.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]=hA.getConfigValue(Be.HDB_SETTINGS_NAMES.HDB_ROOT_KEY))}catch(t){Q_.error(DNe),Q_.error(t),console.error(t),process.exit(1)}}o(xNe,"initSync");function BNe(e={}){try{let{keep_alive_timeout:t,headers_timeout:r,server_timeout:n,https_enabled:s,cors_enabled:i,cors_accesslist:a,local_studio_on:c}=e,l=xu.join(__dirname,"../../","unitTests");Oa[pA]=xu.join(l,"hdb_boot_properties.file"),Qe(Be.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY,xu.join(l,"settings.test")),Qe(Be.HDB_SETTINGS_NAMES.INSTALL_USER,A3.userInfo()?A3.userInfo().username:void 0),Qe(Be.HDB_SETTINGS_NAMES.LOG_LEVEL_KEY,"debug"),Qe(Be.HDB_SETTINGS_NAMES.LOG_PATH_KEY,xu.join(l,"envDir","log")),Qe(Be.HDB_SETTINGS_NAMES.LOG_DAILY_ROTATE_KEY,!1),Qe(Be.HDB_SETTINGS_NAMES.CLUSTERING_ENABLED_KEY,!0),Qe(Be.HDB_SETTINGS_NAMES.CLUSTERING_NODE_NAME_KEY,"1231412de213"),Qe(Be.HDB_SETTINGS_NAMES.HDB_ROOT_KEY,xu.join(l,"envDir")),Qe(Be.CONFIG_PARAMS.STORAGE_PATH,xu.join(l,"envDir")),s&&(Qe(Be.CONFIG_PARAMS.HTTP_SECUREPORT,I3(Be.CONFIG_PARAMS.HTTP_PORT)),Qe(Be.CONFIG_PARAMS.HTTP_PORT,null)),Qe(Be.CONFIG_PARAMS.CUSTOMFUNCTIONS_NETWORK_HTTPS,!!s),Qe(Be.CONFIG_PARAMS.HTTP_PORT,9926),Qe(Be.HDB_SETTINGS_NAMES.SERVER_PORT_KEY,9925),Qe(Be.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_PORT,9925),Qe(Be.HDB_SETTINGS_NAMES.CORS_ENABLED_KEY,J_.isEmpty(i)?!1:i),Qe(Be.CONFIG_PARAMS.HTTP_CORS,J_.isEmpty(i)?!1:i),Qe(Be.HDB_SETTINGS_NAMES.MAX_CUSTOM_FUNCTION_PROCESSES,2),Qe(Be.HDB_SETTINGS_NAMES.MAX_HDB_PROCESSES,4),Qe(Be.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_PORT_KEY,9926),Qe(Be.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_ENABLED_KEY,!0),Qe(Be.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_DIRECTORY_KEY,xu.resolve(__dirname,"../../unitTests/server/fastifyRoutes/custom_functions")),Qe(Be.HDB_SETTINGS_NAMES.LOCAL_STUDIO_ON,J_.isEmpty(c)?!1:c),a&&(Qe("CORS_ACCESSLIST",a),Qe(Be.CONFIG_PARAMS.HTTP_CORSACCESSLIST,a)),n&&(Qe(Be.HDB_SETTINGS_NAMES.SERVER_TIMEOUT_KEY,n),Qe(Be.CONFIG_PARAMS.HTTP_TIMEOUT,n)),t&&(Qe(Be.HDB_SETTINGS_NAMES.SERVER_KEEP_ALIVE_TIMEOUT_KEY,t),Qe(Be.CONFIG_PARAMS.HTTP_KEEPALIVETIMEOUT,t)),r&&(Qe(Be.HDB_SETTINGS_NAMES.SERVER_HEADERS_TIMEOUT_KEY,r),Qe(Be.CONFIG_PARAMS.HTTP_HEADERSTIMEOUT,r))}catch(t){let r=`Error reading in HDB environment variables from path ${pA}. Please check your boot props and settings files`;Q_.fatal(r),Q_.error(t)}}o(BNe,"initTestEnvironment")});var M3=M((m$e,L3)=>{"use strict";var{promises:am,createReadStream:FNe,createWriteStream:HNe}=require("fs"),{createGzip:kNe}=require("zlib"),{promisify:qNe}=require("util"),{pipeline:GNe}=require("stream"),$Ne=qNe(GNe),qM=require("path"),D3=oe();D3.initSync();var _A=j(),{CONFIG_PARAMS:VNe,ITC_EVENT_TYPES:d$e}=(H(),v(W)),{onMessageFromWorkers:f$e}=rt(),{convertToMS:O3}=se(),{onStorageReclamation:KNe}=(Hy(),v(g4)),YNe=6e4,WNe="'interval' and 'maxSize' are both undefined, to enable logging rotation at least one of these values must be defined in harperdb-config.yaml",zNe="'logging.rotation.path' is undefined, to enable logging rotation set this value in harperdb-config.yaml",kM,C3;L3.exports=jNe;function jNe({logger:e,maxSize:t,interval:r,retention:n,enabled:s,path:i,auditInterval:a}){if(s===!1)return;let c=0;if(KNe(e.path,f=>{c=f},!0),!t&&!r)throw new Error(WNe);if(!i)throw new Error(zNe);let l;if(t){let f=t.slice(-1),m=t.slice(0,-1);f==="G"?l=m*1e9:f==="M"?l=m*1e6:l=m*1e3}let u;r&&(u=O3(r));let d;return kM=Date.now(),_A.trace("Log rotate enabled, maxSize:",t,"interval:",r),C3=setInterval(async()=>{if(l){let f;f=await am.stat(e.path),f.size>=l&&(d=await P3(e.path,i))}if(u&&Date.now()-kM>=u&&(d=await P3(e.path,i),kM=Date.now()),n||c){let f=O3(n??"1M")/(1+c);c=0;let m=await am.readdir(i);for(let h of m)try{let p=await am.stat(qM.join(i,h));Date.now()-p.mtimeMs>f&&await am.unlink(qM.join(i,h))}catch(p){_A.error("Error trying to remove log",h,p)}}},a??YNe).unref(),{end(){clearInterval(C3)},getLastRotatedLogPath(){return d}}}o(jNe,"logRotator");async function P3(e,t){let r=D3.get(VNe.LOGGING_ROTATION_COMPRESS),n=qM.join(t,`HDB-${new Date(Date.now()).toISOString().replaceAll(":","-")}.log`);return await am.rename(e,n),r&&(e=n,n+=".gz",await $Ne(FNe(e),kNe(),HNe(n)),await am.unlink(e)),_A.closeLogFile(),_A.notify(`hdb.log rotated, old log moved to ${n}`),n}o(P3,"moveLogFile")});var F3={};we(F3,{RootConfigWatcher:()=>GM});var v3,U3,x3,EA,B3,GM,H3=ce(()=>{v3=w(require("chokidar")),U3=require("node:fs/promises"),x3=w(gt()),EA=require("node:stream"),B3=require("yaml"),GM=class extends EA.EventEmitter{static{o(this,"RootConfigWatcher")}#e;#t;#r;constructor(){super(),this.#e=(0,x3.getConfigFilePath)(),this.#t=v3.default.watch(this.#e,{persistent:!1}).on("add",this.handleChange.bind(this)).on("change",this.handleChange.bind(this)).on("error",this.handleError.bind(this))}handleError(t){this.emit("error",t)}handleChange(){(0,U3.readFile)(this.#e,"utf-8").then(t=>{if(!t)return;let r=(0,B3.parse)(t);if(!this.#r){this.#r=r,this.emit("ready",this.#r);return}this.emit("change",this.#r=r)}).catch(t=>{})}ready(){return(0,EA.once)(this,"ready")}close(){return this.#t.close(),this.#r=void 0,this.emit("close"),this.removeAllListeners(),this}get config(){return this.#r}}});var j=M((g$e,IA)=>{"use strict";var Ca=require("fs-extra"),{workerData:JNe,threadId:QNe,isMainThread:Y3}=require("worker_threads"),eE=require("path"),W3=require("yaml"),z3=require("properties-reader"),$r=(H(),v(W)),k3=qa(),XNe=require("os"),{PACKAGE_ROOT:jM}=ht(),{_assignPackageExport:ZNe}=mi(),{Console:ewe}=require("console"),q3=process.stdout.nativeWrite||(process.stdout.nativeWrite=process.stdout.write),G3=new Map,{join:Pa}=eE,$3=1e4,ur={notify:7,fatal:6,error:5,warn:4,info:3,debug:2,trace:1},twe={STDOUT:"stdOut",STDERR:"stdErr"},E$e=Pa(jM,"logs"),rwe=Pa(jM,"config/yaml/",$r.HDB_DEFAULT_CONFIG_FILE),nwe=1e4,tE,rE,gA,Oo,VM,$M,TA,Ut,Jn,RA,yA,cm,Z_,X_;function SA(e,t,r){e.rotation=t.rotation;let n=t.path;n?t.root||(t.root=eE.dirname(n)):t.root?n=Pa(t.root,VM):(n=Ut.path,t.root||(t.root=eE.dirname(n))),n?e.path=n:console.error("No path for logger",t),e.level=ur[t.level]??Ut?.level??ur.info,j3(e),e.logToStdstreams=t.stdStreams??!1,e.tag=t.tag??(Ut.path===e.path&&r)}o(SA,"updateLogger");function j3(e){let t=e.conditional??(e.conditional={});t.notify=ur.notify>=e.level?e.notify.bind(e):void 0,t.fatal=ur.fatal>=e.level?e.fatal.bind(e):void 0,t.error=ur.error>=e.level?e.error.bind(e):void 0,t.warn=ur.warn>=e.level?e.warn.bind(e):void 0,t.info=ur.info>=e.level?e.info.bind(e):void 0,t.debug=ur.debug>=e.level?e.debug.bind(e):void 0,t.trace=ur.trace>=e.level?e.trace.bind(e):void 0}o(j3,"updateConditional");async function KM(){X_||(X_=new ywe,await X_.ready(),X_.on("change",KM));let e=X_.config,t=e.logging??{};SA(Ut,t),TA=Ut.path,tE=t.console??!1,t.external&&SA(Jn,t.external);for(let r in e){let n=e[r];n.logging?SA(Ut.forComponent(r),n.logging,r):Ut.hasComponent(r)&&SA(Ut.forComponent(r),t,r)}}o(KM,"updateLogSettings");var YM=class extends ewe{static{o(this,"HarperLogger")}constructor(t,r){t.stdout.removeListener=()=>{},t.stderr.removeListener=()=>{},t.stdout.listenerCount=()=>{},t.stderr.listenerCount=()=>{},super(t),this.level=r}trace(...t){bn="trace",this.level<=ur.trace&&super.info(...t),bn="info"}debug(...t){bn="debug",this.level<=ur.debug&&super.info(...t),bn="info"}info(...t){bn="info",this.level<=ur.info&&super.info(...t),bn="info"}warn(...t){bn="warn",this.level<=ur.warn&&super.warn(...t),bn="info"}error(...t){bn="error",this.level<=ur.error&&super.error(...t),bn="info"}fatal(...t){cm=!0;try{bn="fatal",this.level<=ur.fatal&&super.error(...t),bn="info"}finally{cm=!1}}notify(...t){cm=!0;try{bn="notify",this.level<=ur.notify&&super.info(...t),bn="info"}finally{cm=!1}}withTag(t){return Q3(t,!0,this)}forComponent(t){return this}hasComponent(t){return!1}};Z_===void 0&&J3();IA.exports={notify:dwe,fatal:fwe,error:zM,warn:mwe,info:cwe,debug:uwe,trace:lwe,logLevel:Oo,loggerWithTag:Q3,suppressLogging:owe,initLogSettings:J3,logCustomLevel:hwe,closeLogFile:X3,createLogger:bA,logsAtLevel:swe,getLogFilePath:o(()=>TA,"getLogFilePath"),forComponent:o(e=>Ut.forComponent(e),"forComponent"),setMainLogger:Twe,setLogLevel:_we,OUTPUTS:twe,AuthAuditLog:Rwe,start:KM,startOnMainThread:KM,errorToString:Swe};IA.exports.externalLogger={notify(...e){Jn.notify(...e)},fatal(...e){Jn.fatal(...e)},error(...e){Jn.error(...e)},warn(...e){Jn.warn(...e)},info(...e){Jn.info(...e)},debug(...e){Jn.debug(...e)},trace(...e){Jn.trace(...e)},withTag(e){return Jn.withTag(e)},loggerWithTag(e){return Jn.withTag(e)}};ZNe("logger",IA.exports.externalLogger);function swe(e){return ur[Oo]<=ur[e]}o(swe,"logsAtLevel");function J3(e=!1){try{if(Z_===void 0||e){X3();let t=pwe(),r=k3(["ROOTPATH"]);try{Z_=z3(t)}catch(s){if(!r.ROOTPATH||r.ROOTPATH&&!Ca.pathExistsSync(Pa(r.ROOTPATH,$r.HDB_CONFIG_FILE)))throw s}let n;if({level:Oo,configLogPath:$M,toFile:rE,logConsole:tE,rotation:n,toStream:gA}=Ewe(r.ROOTPATH?Pa(r.ROOTPATH,$r.HDB_CONFIG_FILE):Z_.get("settings_path")),VM=$r.LOG_NAMES.HDB,TA=Pa($M,VM),Ut=bA({path:TA,level:Oo,stdStreams:gA,rotation:n}),Jn=Ut.forComponent("external"),Jn.tag=null,Y3)try{require("segfault-handler").registerHandler(Pa($M,"crash.log"))}catch{}}}catch(t){if(Z_=void 0,t.code===$r.NODE_ERROR_CODES.ENOENT||t.code===$r.NODE_ERROR_CODES.ERR_INVALID_ARG_TYPE){let r=k3(Object.keys($r.CONFIG_PARAM_MAP),!0);for(let s in r){let i=$r.CONFIG_PARAM_MAP[s];i&&i.toLowerCase();let a=r[s];if(i===$r.CONFIG_PARAMS.LOGGING_LEVEL){Oo=a;continue}i===$r.CONFIG_PARAMS.LOGGING_CONSOLE&&(tE=i)}let{defaultLevel:n}=gwe();rE=!1,gA=!0,Oo=Oo===void 0?n:Oo,Ut=bA({level:Oo}),Jn=Ut.forComponent("external"),Jn.tag=null;return}throw zM("Error initializing log settings"),zM(t),t}process.env.DEV_MODE&&(gA=!0),iwe()}o(J3,"initLogSettings");var zc=!0;function iwe(){rE&&(process.stdout.write=function(e){return typeof e=="string"&&zc&&tE&&(e=e.toString(),e[e.length-1]===`
|
|
128
128
|
`&&(e=e.slice(0,-1)),yA(e)),q3.apply(process.stdout,arguments)},process.stderr.write=function(e){return typeof e=="string"&&zc&&tE&&(e[e.length-1]===`
|
|
129
129
|
`&&(e=e.slice(0,-1)),yA(e)),q3.apply(process.stderr,arguments)})}o(iwe,"stdioLogging");function Q3(e,t,r=Ut){return e=e.replace(/ /g,"-"),{notify:n(r.notify,"notify"),fatal:n(r.fatal,"fatal"),error:n(r.error,"error"),warn:n(r.warn,"warn"),info:n(r.info,"info"),debug:n(r.debug,"debug"),trace:n(r.trace,"trace")};function n(s,i){return!t||r.level<=ur[i]?function(...a){AA=e;try{return s.call(r,...a)}finally{AA=void 0}}:null}o(n,"logWithTag")}o(Q3,"loggerWithTag");function owe(e){try{zc=!1,e()}finally{zc=!0}}o(owe,"suppressLogging");var awe=JNe?.name?.replace(/ /g,"-")||"main",bn="info",WM,AA;function bA({path:e,level:t,stdStreams:r,rotation:n,isExternalInstance:s,writeToLog:i,component:a}){t||(t="info");let c=ur[t],l;function u(h){if(rE)if(l.logToStdstreams){f(h.replace(/\x1b\[[0-9;]*m/g,"")),zc=!1;try{process.stdout.write(h)}finally{zc=!0}}else f(h);else r&&process.stdout.write(h)}o(u,"logStdOut");function d(h){if(rE){if(f(h),r){zc=!1;try{process.stderr.write(h)}finally{zc=!0}}}else r&&process.stderr.write(h)}o(d,"logStdErr");let f=e&&K3(e,n,s);function m(h){return{write(p){let E=[bn];E.unshift(WM||awe+"/"+QNe),AA&&E.push(AA),l.tag&&E.push(l.tag),h(`[${E.join("] [")}]: ${p}`)}}}if(o(m,"logPrepend"),s&&(yA=f),l=new YM({stdout:m(i??u),stderr:m(i??d),colorMode:r??!1},c),j3(l),l.path=e,Object.defineProperty(l,"path",{get(){return e},set(h){e=h,f=K3(e,l.rotation,s),s&&(yA=f)},enumerable:!0}),l.closeLogFile=f?.closeLogFile,l.logToStdstreams=r,!a){let h=new Map;l.forComponent=function(p){let E=h.get(p);return E||(E=bA({path:e,level:t,stdStreams:r,isExternalInstance:p==="external",rotation:n,writeToLog:i,component:!0}),h.set(p,E)),E},l.hasComponent=function(p){return h.has(p)}}return l}o(bA,"createLogger");var V3=100;function K3(e,t,r){let n=G3.get(e),s,i,a,c,l=0;n||(n=d,n.closeLogFile=m,n.path=e,G3.set(e,n)),Y3&&JSON.stringify(t)!==JSON.stringify(n.rotation)&&(n.rotation=t,setTimeout(()=>{if(n.rotator?.end(),!t)return;let p=M3();try{n.rotator=p({logger:n,...t})}catch(E){n("Error initializing log rotator",E)}},100));let u=0;return n;function d(p){u++;let E=`${new Date().toISOString()} ${p}${p.endsWith(`
|
|
130
130
|
`)?"":`
|