harperdb 4.5.15 → 4.5.16
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/bin/harperdb.js +1 -1
- package/bin/lite.js +1 -1
- package/launchServiceScripts/launchNatsIngestService.js +1 -1
- package/launchServiceScripts/launchNatsReplyService.js +1 -1
- package/launchServiceScripts/launchUpdateNodes4-0-0.js +1 -1
- package/npm-shrinkwrap.json +77 -63
- package/package.json +2 -2
- package/server/jobs/jobProcess.js +1 -1
- package/server/threads/threadServer.js +1 -1
- package/utility/scripts/restartHdb.js +1 -1
|
@@ -36,7 +36,7 @@ Host ${s}
|
|
|
36
36
|
`+u):await Oe.outputFile(l,u);let f="";if(await Oe.pathExists(Oo)||(await Oe.writeFile(Oo,""),await Oe.chmod(Oo,"0600")),i=="github.com"&&!(await Oe.readFile(Oo,"utf8")).includes("github.com"))try{let S=(await(await fetch("https://api.github.com/meta")).json()).ssh_keys;for(let g of S)Oe.appendFile(Oo,"github.com "+g+`
|
|
37
37
|
`)}catch{f=". Unable to get known hosts from github.com. Set your known hosts manually using set_ssh_known_hosts."}o&&await Oe.appendFile(Oo,o);let d=await Zs(e);return d.message=`Added ssh key: ${r}${f}`,d}a(Mue,"addSSHKey");async function vue(e){let t=Rn.updateSSHKeyValidator(e);if(t)throw Bt(t,t.message,Ht.BAD_REQUEST);let{name:r,key:n}=e;xt.trace("updating ssh key",r);let s=Ie.join(La,r+".key");if(!await Oe.pathExists(s))throw new Error("Key does not exist. Use add_ssh_key");await Oe.outputFile(s,n);let i=await Zs(e);return i.message=`Updated ssh key: ${r}`,i}a(vue,"updateSSHKey");async function Uue(e){let t=Rn.deleteSSHKeyValidator(e);if(t)throw Bt(t,t.message,Ht.BAD_REQUEST);let{name:r}=e;xt.trace("deleting ssh key",r);let n=Ie.join(La,r+".key"),s=Ie.join(La,"config");if(!await Oe.pathExists(n))throw new Error("Key does not exist");let i=await Oe.readFile(s,"utf8"),o=new RegExp(`#${r}[\\S\\s]*?IdentitiesOnly yes`,"g");i=i.replace(o,""),await Oe.outputFile(s,i),Oe.removeSync(n);let c=await Zs(e);return c.message=`Deleted ssh key: ${r}`,c}a(Uue,"deleteSSHKey");async function xue(e){let t=[];return await Oe.pathExists(La)&&(await Oe.readdir(La)).forEach(r=>{r!="known_hosts"&&r!="config"&&t.push({name:r.split(".")[0]})}),t}a(xue,"listSSHKeys");async function Bue(e){let t=Rn.setSSHKnownHostsValidator(e);if(t)throw Bt(t,t.message,Ht.BAD_REQUEST);let{known_hosts:r}=e;await Oe.outputFile(Oo,r);let n=await Zs(e);return n.message="Known hosts successfully set",n}a(Bue,"setSSHKnownHosts");async function Hue(e){return await Oe.pathExists(Oo)?{known_hosts:await Oe.readFile(Oo,"utf8")}:{known_hosts:null}}a(Hue,"getSSHKnownHosts");Object.assign(T$,{customFunctionsStatus:Sue,getCustomFunctions:Tue,getCustomFunction:Aue,setCustomFunction:Rue,dropCustomFunction:yue,addComponent:bue,dropCustomFunctionProject:Oue,packageComponent:Nue,deployComponent:wue,getComponents:Cue,getComponentFile:Pue,setComponentFile:Due,dropComponent:Lue,addSSHKey:Mue,updateSSHKey:vue,deleteSSHKey:Uue,listSSHKeys:xue,setSSHKnownHosts:Bue,getSSHKnownHosts:Hue})});var nw=P((LPe,R$)=>{"use strict";var Ss=require("joi"),A$=rt();R$.exports={readTransactionLogValidator:kue,deleteTransactionLogsBeforeValidator:Fue};function kue(e){let t=Ss.object({schema:Ss.string(),database:Ss.string(),table:Ss.string().required(),from:Ss.date().timestamp(),to:Ss.date().timestamp(),limit:Ss.number().min(1)});return A$.validateBySchema(e,t)}a(kue,"readTransactionLogValidator");function Fue(e){let t=Ss.object({schema:Ss.string(),database:Ss.string(),table:Ss.string().required(),timestamp:Ss.date().timestamp().required()});return A$.validateBySchema(e,t)}a(Fue,"deleteTransactionLogsBeforeValidator")});var Zg=P((vPe,I$)=>{"use strict";var sw=(k(),D($)),Eh=hr(),y$=ae(),b$=le(),O$=so(),N$=j(),{handleHDBError:Jg,hdb_errors:Gue}=me(),{HTTP_STATUS_CODES:Xg}=Gue,{readTransactionLogValidator:que,deleteTransactionLogsBeforeValidator:$ue}=nw(),w$=Bn(),Vue="Logs successfully deleted from transaction log.",Kue="All logs successfully deleted from transaction log.";I$.exports={readTransactionLog:Yue,deleteTransactionLogsBefore:zue};async function Yue(e){let t=que(e);if(t)throw Jg(t,t.message,Xg.BAD_REQUEST,void 0,void 0,!0);e.database=e.database??e.schema??"data";let r=y$.checkSchemaTableExist(e.database,e.table);if(r)throw Jg(new Error,r,Xg.NOT_FOUND,void 0,void 0,!0);return b$.get(sw.CONFIG_PARAMS.CLUSTERING_ENABLED)?await Wue(e):(N$.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)),w$.readAuditLog(e))}a(Yue,"readTransactionLog");async function*Wue(e){let t=O$.createNatsTableStreamName(e.database,e.table),r=await Eh.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===sw.OPERATIONS_ENUM.DELETE&&(i.hash_values=n?.entry?.hash_values),yield i}}a(Wue,"readTransactionLogNats");async function zue(e){let t=$ue(e);if(t)throw Jg(t,t.message,Xg.BAD_REQUEST,void 0,void 0,!0);if(e.database=e.database??e.schema??"data",!b$.get(sw.CONFIG_PARAMS.CLUSTERING_ENABLED))return N$.info("Delete transaction logs called for Plexus"),w$.deleteAuditLogsBefore(e);let{database:r,table:n,timestamp:s}=e,i=y$.checkSchemaTableExist(r,n);if(i)throw Jg(new Error,i,Xg.NOT_FOUND,void 0,void 0,!0);let o=O$.createNatsTableStreamName(r,n),{jsm:c}=await Eh.getNATSReferences(),l=await Eh.getStreamInfo(o),u=new Date(l.state.first_ts).getTime();if(s<=u)return`No transactions exist before: ${s}`;let f=Vue,d,_=new Date(l.state.last_ts).getTime();return s>_?(d=l.state.last_seq+1,f=Kue):d=(await Eh.viewStream(o,parseInt(s),1))[0].nats_sequence,await Eh.purgeTableStream(r,n,{seq:d}),f}a(zue,"deleteTransactionLogsBefore")});var P$=P((xPe,C$)=>{"use strict";var iw=class{static{a(this,"PermissionTableResponseObject")}constructor(t,r,n=[],s=[]){this.schema=t,this.table=r,this.required_table_permissions=n,this.required_attribute_permissions=s}};C$.exports=iw});var L$=P((HPe,D$)=>{"use strict";var ow=class{static{a(this,"PermissionAttributeResponseObject")}constructor(t,r=[]){this.attribute_name=t,this.required_permissions=r}};D$.exports=ow});var cw=P((FPe,v$)=>{"use strict";var M$=P$(),Que=L$(),{HDB_ERROR_MSGS:jue}=Pn(),aw=class{static{a(this,"PermissionResponseObject")}constructor(){this.error=jue.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 M$(t,r,n),i=`${t}_${r}`;this.unauthorized_access[i]=s}addUnauthorizedAttributes(t,r,n,s){let i=[];t.forEach(c=>{let l=new Que(c,s[c]);i.push(l)});let o=`${r}_${n}`;if(this.unauthorized_access[o])this.unauthorized_access[o].required_attribute_permissions=i;else{let c=new M$(r,n,[],i);this.unauthorized_access[o]=c}}getPermsResponse(){let t=Object.values(this.unauthorized_access);return t.length>0||this.invalid_schema_items.length>0?(this.unauthorized_access=t,this):null}};v$.exports=aw});var nS=P((VPe,J$)=>{"use strict";var lw=pn(),eS=Vr(),Ts=og(),Th=io(),uw=bc(),Jue=IO(),Xue=zk(),Ah=Fn(),tS=i_(),mr=j(),Zue=MO(),ede=gg(),tde=sN(),rde=Tg(),nde=aN(),sde=cN(),ide=dN(),ode=_N(),dw=Og(),No=ae(),ade=NG(),fw=NN(),B$=rd(),tn=(k(),D($)),H$=Fq(),cde=$u(),k$=(Au(),D(g_)),F$=(Kg(),D(ch)),G$=Ct(),ir=tw(),lde=require("alasql"),q$=Zg(),$$=fh(),ad=js(),V$=(el(),D(Zc)),K$=cw(),{handleHDBError:yn,hdb_errors:Y$}=me(),{addNodeBack:qPe,removeNodeBack:$Pe}=(el(),D(Zc)),{HDB_ERROR_MSGS:Ur,HTTP_STATUS_CODES:gh}=Y$,J=new Map,W$="delete",Ma="insert",wo="read",fl="update",Sh="describe",U$=Th.describeSchema.name,x$=Th.describeTable.name,z$={delete:!0,deleteRecord:!0,update:!0,updateData:!0,dropAttribute:!0,dropTable:!0,dropSchema:!0,upsert:!0,upsertData:!0},ude={insert:!0,delete:!0,deleteRecord:!0,update:!0,updateData:!0,upsert:!0,upsertData:!0},dde="catchup",fde="handleGetJob",_de="handleGetJobsByStartDate",rS={CSV_DATA_LOAD:"csvDataLoad",CSV_URL_LOAD:"csvURLLoad",CSV_FILE_LOAD:"csvFileLoad",IMPORT_FROM_S3:"importFromS3"},hde=[Ts.createTable.name,Ts.createAttribute.name,Ts.dropTable.name,Ts.dropAttribute.name],Q$={EXPORT_TO_S3:"export_to_s3",EXPORT_LOCAL:"export_local"},re=class{static{a(this,"permission")}constructor(t,r){this.requires_su=t,this.perms=r}};J.set(lw.insert.name,new re(!1,[Ma]));J.set(lw.update.name,new re(!1,[fl]));J.set(lw.upsert.name,new re(!1,[Ma,fl]));J.set(eS.searchByConditions.name,new re(!1,[wo]));J.set(eS.searchByHash.name,new re(!1,[wo]));J.set(eS.searchByValue.name,new re(!1,[wo]));J.set(eS.search.name,new re(!1,[wo]));J.set(Ts.createSchema.name,new re(!0,[]));J.set(Ts.createTable.name,new re(!0,[]));J.set(Ts.createAttribute.name,new re(!1,[Ma]));J.set(Ts.dropSchema.name,new re(!0,[]));J.set(Ts.dropTable.name,new re(!0,[]));J.set(Ts.dropAttribute.name,new re(!0,[]));J.set(Th.describeSchema.name,new re(!1,[wo]));J.set(Th.describeTable.name,new re(!1,[wo]));J.set(uw.deleteRecord.name,new re(!1,[W$]));J.set(Ah.addUser.name,new re(!0,[]));J.set(Ah.alterUser.name,new re(!0,[]));J.set(Ah.dropUser.name,new re(!0,[]));J.set(Ah.listUsersExternal.name,new re(!0,[]));J.set(tS.listRoles.name,new re(!0,[]));J.set(tS.addRole.name,new re(!0,[]));J.set(tS.alterRole.name,new re(!0,[]));J.set(tS.dropRole.name,new re(!0,[]));J.set(Zue.name,new re(!0,[]));J.set(ede.name,new re(!0,[]));J.set(tde.name,new re(!0,[]));J.set(rde.name,new re(!0,[]));J.set(nde.name,new re(!0,[]));J.set(sde.name,new re(!0,[]));J.set(dw.setRoutes.name,new re(!0,[]));J.set(dw.getRoutes.name,new re(!0,[]));J.set(dw.deleteRoutes.name,new re(!0,[]));J.set(G$.setConfiguration.name,new re(!0,[]));J.set(ide.clusterStatus.name,new re(!0,[]));J.set(ode.name,new re(!0,[]));J.set(fw.getFingerprint.name,new re(!0,[]));J.set(fw.setLicense.name,new re(!0,[]));J.set(uw.deleteFilesBefore.name,new re(!0,[]));J.set(uw.deleteAuditLogsBefore.name,new re(!0,[]));J.set(B$.restart.name,new re(!0,[]));J.set(B$.restartService.name,new re(!0,[]));J.set(Jue.name,new re(!0,[]));J.set(Xue.name,new re(!0,[wo]));J.set(cde.systemInformation.name,new re(!0,[]));J.set(G$.getConfiguration.name,new re(!0,[]));J.set(q$.readTransactionLog.name,new re(!0,[]));J.set(q$.deleteTransactionLogsBefore.name,new re(!0,[]));J.set($$.installModules.name,new re(!0,[]));J.set($$.auditModules.name,new re(!0,[]));J.set(ad.createCsr.name,new re(!0,[]));J.set(ad.signCertificate.name,new re(!0,[]));J.set(ad.listCertificates.name,new re(!0,[]));J.set(ad.addCertificate.name,new re(!0,[]));J.set(ad.removeCertificate.name,new re(!0,[]));J.set(ad.getKey.name,new re(!0,[]));J.set(V$.addNodeBack.name,new re(!0,[]));J.set(V$.removeNodeBack.name,new re(!0,[]));J.set(k$.createTokens.name,new re(!1,[]));J.set(k$.refreshOperationToken.name,new re(!1,[]));J.set(F$.login.name,new re(!1,[]));J.set(F$.logout.name,new re(!1,[]));J.set(ir.customFunctionsStatus.name,new re(!0,[]));J.set(ir.getCustomFunctions.name,new re(!0,[]));J.set(ir.getComponents.name,new re(!0,[]));J.set(ir.getComponentFile.name,new re(!0,[]));J.set(ir.setComponentFile.name,new re(!0,[]));J.set(ir.dropComponent.name,new re(!0,[]));J.set(ir.getCustomFunction.name,new re(!0,[]));J.set(ir.setCustomFunction.name,new re(!0,[]));J.set(ir.dropCustomFunction.name,new re(!0,[]));J.set(ir.addComponent.name,new re(!0,[]));J.set(ir.dropCustomFunctionProject.name,new re(!0,[]));J.set(ir.packageComponent.name,new re(!0,[]));J.set(ir.deployComponent.name,new re(!0,[]));J.set(ir.addSSHKey.name,new re(!0,[]));J.set(ir.updateSSHKey.name,new re(!0,[]));J.set(ir.deleteSSHKey.name,new re(!0,[]));J.set(ir.listSSHKeys.name,new re(!0,[]));J.set(ir.setSSHKnownHosts.name,new re(!0,[]));J.set(ir.getSSHKnownHosts.name,new re(!0,[]));J.set(fw.getRegistrationInfo.name,new re(!1,[]));J.set(Ah.userInfo.name,new re(!1,[]));J.set(Th.describeAll.name,new re(!1,[]));J.set(fde,new re(!1,[]));J.set(_de,new re(!0,[]));J.set(dde,new re(!0,[]));J.set(rS.CSV_DATA_LOAD,new re(!1,[Ma,fl]));J.set(rS.CSV_URL_LOAD,new re(!1,[Ma,fl]));J.set(rS.CSV_FILE_LOAD,new re(!1,[Ma,fl]));J.set(rS.IMPORT_FROM_S3,new re(!1,[Ma,fl]));J.set(Q$.EXPORT_TO_S3,new re(!0,[]));J.set(Q$.EXPORT_LOCAL,new re(!0,[]));J.set(tn.VALID_SQL_OPS_ENUM.DELETE,new re(!1,[W$]));J.set(tn.VALID_SQL_OPS_ENUM.SELECT,new re(!1,[wo]));J.set(tn.VALID_SQL_OPS_ENUM.INSERT,new re(!1,[Ma]));J.set(tn.VALID_SQL_OPS_ENUM.UPDATE,new re(!1,[fl]));J$.exports={verifyPerms:pde,verifyPermsAst:mde,verifyBulkLoadAttributePerms:gde};function mde(e,t,r){if(No.isEmptyOrZeroLength(e))throw mr.info("verify_perms_ast has an empty user parameter"),yn(new Error);if(No.isEmptyOrZeroLength(t))throw mr.info("verify_perms_ast has an empty user parameter"),yn(new Error);if(No.isEmptyOrZeroLength(r))throw mr.info("verify_perms_ast has a null operation parameter"),yn(new Error);try{let n=new K$,s=new ade(e),i=s.getSchemas(),o=new Map;if((!i||i.length===0)&&s.affected_attributes&&s.affected_attributes.size>0)throw mr.info("No schemas defined in verifyPermsAst(), will not continue."),yn(new Error);let c=!!t.role.permission.super_user,l=i.includes("system");if(l&&z$[r])throw yn(new Error,Ur.DROP_SYSTEM,gh.FORBIDDEN);if(c&&!l)return null;let u=H$.getRolePermissions(t.role);t.role.permission=u,!c&&e instanceof lde.yy.Select&&(e=s.updateAttributeWildcardsForRolePerms(u));for(let d=0;d<i.length;d++){let _=s.getTablesBySchemaName(i[d]);_&&o.set(i[d],_)}let f=j$(t,r,o,n);return f||(o.forEach((d,_)=>{for(let h=0;h<d.length;h++){let m=s.getAttributesBySchemaTableName(_,d[h]),S=hw(t.role.permission,_,d[h]);_w(m,S,r,d[h],_,n)}}),n.getPermsResponse())}catch(n){throw yn(n)}}a(mde,"verifyPermsAst");function pde(e,t){if(e===null||t===null||e.hdb_user===void 0||e.hdb_user===null)throw mr.info("null required parameter in verifyPerms"),yn(new Error,Ur.DEFAULT_INVALID_REQUEST,gh.BAD_REQUEST);let r;t instanceof Function?r=t.name:r=t;let n=e.action,s=e.schema??e.database,i=e.table,o=new Map;s&&i&&o.set(s,[i]);let c=new K$;if(No.isEmptyOrZeroLength(e.hdb_user?.role)||No.isEmptyOrZeroLength(e.hdb_user?.role?.permission))return mr.info(`User ${e.hdb_user?.username} has no role or permissions. Please assign the user a valid role.`),c.handleUnauthorizedItem(Ur.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,f=o.has(tn.SYSTEM_SCHEMA_NAME)||s===tn.SYSTEM_SCHEMA_NAME;if(l&&f&&ude[e.operation]&&(i===tn.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME||i===tn.SYSTEM_TABLE_NAMES.ROLE_TABLE_NAME||i===tn.SYSTEM_TABLE_NAMES.USER_TABLE_NAME))return null;if(f&&z$[r])throw yn(new Error,Ur.DROP_SYSTEM,gh.FORBIDDEN);if(l&&!f||u===!0&&(r===Ts.createSchema.name||r===Ts.dropSchema.name))return null;if(hde.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 d=H$.getRolePermissions(e.hdb_user?.role);if(e.hdb_user?.role&&(e.hdb_user.role.permission=d),(r===U$||r===x$)&&!d.super_user){if(s===tn.SYSTEM_SCHEMA_NAME)return c.handleUnauthorizedItem(Ur.SCHEMA_PERM_ERROR(s));if(r===U$&&(!d[s]||!d[s][Sh]))return c.handleInvalidItem(Ur.SCHEMA_NOT_FOUND(s));if(r===x$&&(!d[s]||!d[s].tables[i]||!d[s].tables[i][Sh]))return c.handleInvalidItem(Ur.TABLE_NOT_FOUND(s,i))}let _=j$(e.hdb_user,r,o,c,n);if(_)return _;if(J.get(r)&&J.get(r).perms.length===0)return null;if(!l&&e.get_attributes&&tn.SEARCH_WILDCARDS.includes(e.get_attributes[0])){let S=[],g=d[s].tables[i];g[tn.PERMS_CRUD_ENUM.READ]&&(g.attribute_permissions.length>0?g.attribute_permissions.filter(E=>E[tn.PERMS_CRUD_ENUM.READ]).forEach(E=>{S.push(E.attribute_name)}):S=global.hdb_schema[s][i].attributes.map(R=>R.attribute),e.get_attributes=S)}let h=Ede(e),m=hw(e.hdb_user?.role?.permission,s,i);return _w(h,m,r,i,s,c,n),c.getPermsResponse()}a(pde,"verifyPerms");function j$(e,t,r,n,s){if(No.arrayHasEmptyValues([e,t,r]))throw mr.info("hasPermissions has an invalid parameter"),yn(new Error);let i=r.has("system"),o=e.role.permission;if(o.super_user&&(!i||J.get(t).requires_su))return null;if(!J.get(t))throw mr.info(`operation ${t} not found.`),yn(new Error,Ur.OP_NOT_FOUND(t),gh.BAD_REQUEST);if(J.get(t)&&J.get(t).requires_su)return mr.info(`operation ${t} requires SU permissions.`),n.handleUnauthorizedItem(Ur.OP_IS_SU_ONLY(t));let c=r.keys();for(let l of c){try{if(l&&!o[l]||o[l][Sh]===!1){n.addInvalidItem(Ur.SCHEMA_NOT_FOUND(l));continue}}catch{n.addInvalidItem(Ur.SCHEMA_NOT_FOUND(l));continue}let u=r.get(l);for(let f of u){let d=o[l].tables[f];if(!d||d[Sh]===!1)n.addInvalidItem(Ur.TABLE_NOT_FOUND(l,f));else try{let _=[],h=J.get(t).perms;!No.isEmpty(s)&&h.includes(s)&&(h=[s]);for(let m=0;m<h.length;m++){let S=h[m],g=d[S];(g==null||g===!1)&&(mr.info(`Required ${S} permission not found for ${t} ${s?`${s} `:""}operation in role ${e.role.id}`),_.push(S))}_.length>0&&n.addUnauthorizedTable(l,f,_)}catch(_){let h=Ur.UNKNOWN_OP_AUTH_ERROR(t,l,f);throw mr.error(h),mr.error(_),yn(Y$.CHECK_LOGS_WRAPPER(h))}}}return r.size<2?n.getPermsResponse():null}a(j$,"hasPermissions");function _w(e,t,r,n,s,i,o){if(!e||!t)throw mr.info("no attributes specified in checkAttributePerms."),yn(new Error);let c=J.get(r).perms;if(!c||c==="")throw mr.info(`no permissions found for ${r} in checkAttributePerms().`),yn(new Error);if(No.isEmptyOrZeroLength(t))return mr.info("No role permissions set (this is OK)."),null;o&&c.includes(o)&&(c=[o]);let l={};for(let f of e){let d=t.get(f);if(d){if(d[Sh]===!1){i.addInvalidItem(Ur.ATTR_NOT_FOUND(s,n,f),s,n);continue}if(c)for(let _ of c){if(tn.TIME_STAMP_NAMES.includes(d.attribute_name)&&_!==wo)throw yn(new Error,Ur.SYSTEM_TIMESTAMP_PERMS_ERR,gh.FORBIDDEN);d[_]===!1&&(l[d.attribute_name]?l[d.attribute_name].push(_):l[d.attribute_name]=[_])}}else i.addInvalidItem(Ur.ATTR_NOT_FOUND(s,n,f),s,n)}let u=Object.keys(l);u.length>0&&i.addUnauthorizedAttributes(u,s,n,l)}a(_w,"checkAttributePerms");function Ede(e){let t=new Set;try{if(e.action)return t;if(e.operation===tn.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){mr.info(r)}return t}a(Ede,"getRecordAttributes");function hw(e,t,r){let n=new Map;if(No.isEmpty(e))return mr.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{mr.info(`No attribute permissions found for schema ${t} and table ${r}.`)}return n}a(hw,"getAttributePermissions");function gde(e,t,r,n,s,i,o){let c=new Set(i),l=hw(e,n,s);_w(c,l,t,s,n,o,r)}a(gde,"verifyBulkLoadAttributePerms")});var iS=P((YPe,rV)=>{"use strict";rV.exports={evaluateSQL:Dde,processAST:tV,convertSQLToAST:eV,checkASTPermissions:Z$};var Sde=pn(),X$=require("util"),Tde=X$.callbackify(Sde.insert),Ade=Vr().search,Rde=HB().update,yde=X$.callbackify(Rde),bde=FB().convertDelete,va=require("alasql"),Ode=nS(),sS=j(),Nde=mp(),wde=ae(),Rh=(k(),D($)),{hdb_errors:Ide,handleHDBError:mw}=me(),{HTTP_STATUS_CODES:pw}=Ide;Nde(va);var Cde=403,Pde="There was a problem performing this insert. Please check the logs and try again.",Ew=class{static{a(this,"ParsedSQLObject")}constructor(){this.ast=void 0,this.variant=void 0,this.permissions_checked=!1}};function Dde(e,t){let r=e.parsed_sql_object;if(!r){r=eV(e.sql);let n,s=r.ast.statements[0];if(s instanceof va.yy.Insert?n=s.into.databaseid:s instanceof va.yy.Select?n=s.from?s.from[0].databaseid:null:s instanceof va.yy.Update||s instanceof va.yy.Delete?n=s.table.databaseid:sS.error("AST in evaluateSQL is not a valid SQL type."),!(s instanceof va.yy.Select)&&wde.isEmptyOrZeroLength(n))return t("No schema specified",null)}tV(e,r,(n,s)=>{if(n)return t(n);t(null,s)})}a(Dde,"evaluateSQL");function Z$(e,t){let r;try{r=Ode.verifyPermsAst(t.ast.statements[0],e.hdb_user,t.variant),t.permissions_checked=!0}catch(n){throw n}return r||null}a(Z$,"checkASTPermissions");function eV(e){let t=new Ew;if(!e)throw mw(new Error,"The 'sql' parameter is missing from the request body",pw.BAD_REQUEST);try{let r=e.trim(),n=va.parse(r),s=r.split(" ")[0].toLowerCase();t.ast=n,t.variant=s}catch(r){let n=r.message.split(`
|
|
38
38
|
`);throw n[1]?mw(r,`Invalid SQL at: ${n[1]}. Please ensure your SQL is valid. Try adding backticks to reserved words and schema table references.`,pw.BAD_REQUEST):mw(r,"We had trouble parsing your request. Please ensure your SQL is valid. Try adding backticks to reserved words and schema table references.",pw.BAD_REQUEST)}return t}a(eV,"convertSQLToAST");function tV(e,t,r){try{let n=Lde;if(!e.bypass_auth&&!t.permissions_checked){let i=Z$(e,t);if(i&&i.length>0)return r(Cde,i)}let s={statement:t.ast.statements[0],hdb_user:e.hdb_user};switch(t.variant){case Rh.VALID_SQL_OPS_ENUM.SELECT:n=Ade,s=t.ast.statements[0];break;case Rh.VALID_SQL_OPS_ENUM.INSERT:n=Mde;break;case Rh.VALID_SQL_OPS_ENUM.UPDATE:n=yde;break;case Rh.VALID_SQL_OPS_ENUM.DELETE:n=bde;break;default:throw new Error(`unsupported SQL type ${t.variant} in SQL: ${e}`)}n(s,(i,o)=>{if(i){r(i);return}r(null,o)})}catch(n){return r(n)}}a(tV,"processAST");function Lde(e,t){sS.info(e),t("unknown sql statement")}a(Lde,"nullFunction");function Mde({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(o=>o.columnid);try{s.records=vde(i,e.values)}catch(o){return r(o)}Tde(s,(o,c)=>{if(o)return r(o);try{delete c.new_attributes,delete c.txn_time}catch(l){sS.error(`Error delete new_attributes from insert response: ${l}`)}r(null,c)})}a(Mde,"convertInsert");function vde(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]]=va.compile(`SELECT ${s.toString()} AS [${Rh.FUNC_VAL}] FROM ?`)}),n})}catch(r){throw sS.error(r),new Error(Pde)}}a(vde,"createDataObjects")});var yw=P((jPe,oV)=>{var lS=require("clone"),uS=rt(),Ude=ae(),aS=(k(),D($)),zPe=j(),gw=require("fs"),Tw=require("joi"),{string:cS}=Tw.types(),{hdb_errors:xde,handleHDBError:oS}=me(),{HDB_ERROR_MSGS:QPe,HTTP_STATUS_CODES:Sw}=xde,{common_validators:cd}=gi(),nV=" is required",Bde=["insert","update","upsert"],Aw={database:{presence:!1,format:cd.schema_format,length:cd.schema_length},schema:{presence:!1,format:cd.schema_format,length:cd.schema_length},table:{presence:!0,format:cd.schema_format,length:cd.schema_length},action:{inclusion:{within:Bde,message:"is required and must be either insert, update, or upsert"}},file_path:{},csv_url:{url:{allowLocal:!0}},data:{},passthrough_headers:{}},Hde={schema:cS.required(),table:cS.required(),action:cS.valid("insert","update","upsert")},{AWS_ACCESS_KEY:kde,AWS_SECRET:Fde,AWS_BUCKET:Gde,AWS_FILE_KEY:qde,REGION:$de}=aS.S3_BUCKET_AUTH_KEYS,Vde={s3:{presence:!0},[`s3.${kde}`]:{presence:!0,type:"String"},[`s3.${Fde}`]:{presence:!0,type:"String"},[`s3.${Gde}`]:{presence:!0,type:"String"},[`s3.${qde}`]:{presence:!0,type:"String",hasValidFileExt:[".csv",".json"]},[`s3.${$de}`]:{presence:!0,type:"String"}},sV=lS(Aw);sV.data.presence={message:nV};var iV=lS(Aw);iV.file_path.presence={message:nV};var Kde=Object.assign(lS(Aw),Vde),Rw=lS(Hde);Rw.csv_url=cS.uri().messages({"string.uri":"'csv_url' must be a valid url"}).required();Rw.passthrough_headers=Tw.object();function Yde(e){let t=uS.validateObject(e,sV);return dS(e,t)}a(Yde,"dataObject");function Wde(e){let t=uS.validateBySchema(e,Tw.object(Rw));return dS(e,t)}a(Wde,"urlObject");function zde(e){let t=uS.validateObject(e,iV);return dS(e,t)}a(zde,"fileObject");function Qde(e){let t=uS.validateObject(e,Kde);return dS(e,t)}a(Qde,"s3FileObject");function dS(e,t){if(!t){let r=Ude.checkGlobalSchemaTable(e.schema,e.table);if(r)return oS(new Error,r,Sw.BAD_REQUEST);if(e.operation===aS.OPERATIONS_ENUM.CSV_FILE_LOAD)try{gw.accessSync(e.file_path,gw.constants.R_OK|gw.constants.F_OK)}catch(n){return n.code===aS.NODE_ERROR_CODES.ENOENT?oS(n,`No such file or directory ${n.path}`,Sw.BAD_REQUEST):n.code===aS.NODE_ERROR_CODES.EACCES?oS(n,`Permission denied ${n.path}`,Sw.BAD_REQUEST):oS(n)}}return t}a(dS,"postValidateChecks");oV.exports={dataObject:Yde,urlObject:Wde,fileObject:zde,s3FileObject:Qde}});var bw=P((XPe,aV)=>{"use strict";var yh=j(),fS=(k(),D($));async function jde(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===fS.OPERATIONS_ENUM.INSERT||t.operation===fS.OPERATIONS_ENUM.UPDATE||t.operation===fS.OPERATIONS_ENUM.UPSERT?(delete s.new_attributes,delete s.txn_time):t.operation===fS.OPERATIONS_ENUM.DELETE&&delete s.txn_time,s}catch(i){throw i.message&&typeof i.message=="string"&&i.message.includes("already exists")?(yh.info(i.message),i):i.http_resp_msg?(yh.error(`Error calling operation: ${e.name}`),yh.error(i.http_resp_msg),i):(yh.error(`Error calling operation: ${e.name}`),yh.error(i),i)}}a(jde,"callOperationFunctionAsAwait");aV.exports={callOperationFunctionAsAwait:jde}});var Ow=P((eDe,lV)=>{"use strict";var{S3:Jde,GetObjectCommand:Xde}=require("@aws-sdk/client-s3");lV.exports={getFileStreamFromS3:Zde,getS3AuthObj:cV};async function Zde(e){let{s3:t}=e,r={Bucket:t.bucket,Key:t.key};return(await cV(t.aws_access_key_id,t.aws_secret_access_key,t.region).send(new Xde(r))).Body}a(Zde,"getFileStreamFromS3");function cV(e,t,r){return new Jde({credentials:{accessKeyId:e,secretAccessKey:t},region:r})}a(cV,"getS3AuthObj")});var dV=P((rDe,uV)=>{"use strict";var Nw=class{static{a(this,"BulkLoadFileObject")}constructor(t,r,n,s,i,o,c=null){this.op=t,this.action=r,this.schema=n,this.table=s,this.file_path=i,this.file_type=o,this.role_perms=c}},ww=class{static{a(this,"BulkLoadDataObject")}constructor(t,r,n,s){this.action=t,this.schema=r,this.table=n,this.data=s}};uV.exports={BulkLoadFileObject:Nw,BulkLoadDataObject:ww}});var _V=P((sDe,fV)=>{"use strict";var Iw=class{static{a(this,"ClusteringOriginObject")}constructor(t,r,n){this.timestamp=t,this.user=r,this.node_name=n}};fV.exports=Iw});var vw=P((uDe,PV)=>{"use strict";var _S=pn(),mS=yw(),efe=require("needle"),ei=(k(),D($)),oDe=wt(),ld=ae(),{handleHDBError:kt,hdb_errors:RV}=me(),{HTTP_STATUS_CODES:xr,HDB_ERROR_MSGS:pr,CHECK_LOGS_WRAPPER:hl}=RV,ud=j(),Cw=require("papaparse");ld.promisifyPapaParse();var ti=require("fs-extra"),tfe=require("path"),{chain:hV}=require("stream-chain"),mV=require("stream-json/streamers/StreamArray"),pV=require("stream-json/utils/Batch"),EV=require("stream-chain/utils/comp"),{finished:gV}=require("stream"),rfe=le(),yV=bw(),nfe=Ow(),{BulkLoadFileObject:Dw,BulkLoadDataObject:sfe}=dV(),Lw=cw(),{verifyBulkLoadAttributePerms:bV}=nS(),aDe=_V(),cDe=hr(),lDe=so(),{databases:ife}=(ve(),D(it)),{coerceType:ofe}=(df(),D(Uw)),SV="No records parsed from csv file.",_l=`${rfe.get("HDB_ROOT")}/tmp`,{schema_regex:afe}=gi(),TV=1024*1024*2,AV=5e3,cfe={"text/csv":!0,"application/octet-stream":!0,"text/plain":!0,"application/vnd.ms-excel":!0};PV.exports={csvDataLoad:lfe,csvURLLoad:ufe,csvFileLoad:dfe,importFromS3:ffe};async function lfe(e,t){let r=mS.dataObject(e);if(r)throw kt(r,r.message,xr.BAD_REQUEST,void 0,void 0,!0);let n={};try{let s=wV(e.schema,e.table),i=Cw.parse(e.data,{header:!0,skipEmptyLines:!0,transform:Pw.bind(null,s),dynamicTyping:!1}),o=new Lw;e.hdb_user&&e.hdb_user?.role&&e.hdb_user?.role?.permission&&e.hdb_user?.role?.permission?.super_user!==!0&&bV(e.hdb_user?.role?.permission,this.job_operation_function.name,e.action,e.schema,e.table,i.meta.fields,o);let c=o.getPermsResponse();if(c)throw kt(new Error,c,xr.BAD_REQUEST,void 0,void 0,!0);let l=new sfe(e.action,e.schema,e.table,i.data);return n=await yV.callOperationFunctionAsAwait(IV,l,null),n.message===SV?SV:CV(n.records,n.number_written)}catch(s){throw ml(s)}}a(lfe,"csvDataLoad");async function ufe(e){let t=mS.urlObject(e);if(t)throw kt(t,t.message,xr.BAD_REQUEST,void 0,void 0,!0);let r=`${Date.now()}.csv`,n=`${_l}/${r}`;try{await _fe(e,r)}catch(s){throw ud.error(pr.DOWNLOAD_FILE_ERR(r)+" - "+s),kt(s,hl(pr.DOWNLOAD_FILE_ERR(r)))}try{let s=new Dw(this.job_operation_function.name,e.action,e.schema,e.table,n,ei.VALID_S3_FILE_TYPES.CSV,e.hdb_user?.role?.permission),i=await Mw(s);return await hS(n),i}catch(s){throw await hS(n),ml(s)}}a(ufe,"csvURLLoad");async function dfe(e){let t=mS.fileObject(e);if(t)throw kt(t,t.message,xr.BAD_REQUEST,void 0,void 0,!0);let r=new Dw(this.job_operation_function.name,e.action,e.schema,e.table,e.file_path,ei.VALID_S3_FILE_TYPES.CSV,e.hdb_user?.role?.permission);try{return await Mw(r)}catch(n){throw ml(n)}}a(dfe,"csvFileLoad");async function ffe(e){let t=mS.s3FileObject(e);if(t)throw kt(t,t.message,xr.BAD_REQUEST,void 0,void 0,!0);let r;try{let n=tfe.extname(e.s3.key),s=`${Date.now()}${n}`;r=`${_l}/${s}`;let i=new Dw(this.job_operation_function.name,e.action,e.schema,e.table,r,n,e.hdb_user?.role?.permission);await hfe(s,e);let o=await Mw(i);return await hS(r),o}catch(n){throw await hS(r),ml(n)}}a(ffe,"importFromS3");async function _fe(e,t){let r;try{let n=e.passthrough_headers?{headers:e.passthrough_headers}:void 0;r=await efe("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 kt(n,s,n.statusCode,ei.LOG_LEVELS.ERROR,"Error downloading CSV file - "+n)}pfe(r,e.csv_url),await mfe(t,r.raw)}a(_fe,"downloadCSVFile");async function hfe(e,t){try{let r=`${_l}/${e}`;await ti.mkdirp(_l),await ti.writeFile(`${_l}/${e}`,"",{flag:"a+"});let n=await ti.createWriteStream(r),s=await nfe.getFileStreamFromS3(t);await new Promise((i,o)=>{s.on("error",function(c){o(c)}),s.pipe(n).on("error",function(c){o(c)}).on("close",function(){ud.info(`${t.s3.key} successfully downloaded to ${r}`),i()})})}catch(r){throw ud.error(pr.S3_DOWNLOAD_ERR+" - "+r),kt(r,hl(pr.S3_DOWNLOAD_ERR))}}a(hfe,"downloadFileFromS3");async function mfe(e,t){try{await ti.mkdirp(_l),await ti.writeFile(`${_l}/${e}`,t)}catch(r){throw ud.error(pr.WRITE_TEMP_FILE_ERR),kt(r,hl(pr.DEFAULT_BULK_LOAD_ERR))}}a(mfe,"writeFileToTempFolder");async function hS(e){if(e)try{await ti.access(e),await ti.unlink(e)}catch{ud.warn(`could not delete temp csv file at ${e}, file does not exist`)}}a(hS,"deleteTempFile");function pfe(e,t){if(e.statusCode!==RV.HTTP_STATUS_CODES.OK)throw kt(new Error,`CSV Load failed from URL: ${t}, status code: ${e.statusCode}, message: ${e.statusMessage}`,xr.BAD_REQUEST);if(!cfe[e.headers["content-type"]])throw kt(new Error,`CSV Load failed from URL: ${t}, unsupported content type: ${e.headers["content-type"]}`,xr.BAD_REQUEST);if(!e.raw)throw kt(new Error,`CSV Load failed from URL: ${t}, no csv found at url`,xr.BAD_REQUEST)}a(pfe,"validateURLResponse");async function Mw(e){try{let t;switch(e.file_type){case ei.VALID_S3_FILE_TYPES.CSV:t=await Efe(e);break;case ei.VALID_S3_FILE_TYPES.JSON:t=await gfe(e);break;default:throw kt(new Error,pr.DEFAULT_BULK_LOAD_ERR,xr.BAD_REQUEST,ei.LOG_LEVELS.ERROR,pr.INVALID_FILE_EXT_ERR(e))}return CV(t.records,t.number_written)}catch(t){throw ml(t)}}a(Mw,"fileLoad");async function OV(e,t,r,n,s){let i=n.data?n.data:n;if(i.length===0)return;s&&s.pause();let o={operation:e.action,schema:e.schema,table:e.table,records:i};try{let{attributes:c}=await _S.validation(o);e.role_perms&&e.role_perms.super_user!==!0&&bV(e.role_perms,e.op,e.action,e.schema,e.table,c,t),s&&s.resume()}catch(c){let l=kt(c);r(l)}}a(OV,"validateChunk");async function NV(e,t,r,n,s){let i=n.data?n.data:n;if(i.length===0)return;ld.autoCastJSONDeep(i),s&&s.pause();let o=n.meta?n.meta.fields:null;if(o)i.forEach(c=>{!ld.isEmpty(c)&&!ld.isEmpty(c.__parsed_extra)&&delete c.__parsed_extra});else{let c=new Set;i.forEach(l=>{Object.keys(l).forEach(u=>c.add(u))}),o=[...c]}try{let c={schema:e.schema,table:e.table,action:e.action,data:i},l=await yV.callOperationFunctionAsAwait(IV,c,null);t.records+=l.records,t.number_written+=l.number_written,s&&s.resume()}catch(c){let l=kt(c,hl(pr.INSERT_CSV_ERR),xr.INTERNAL_SERVER_ERROR,ei.LOG_LEVELS.ERROR,pr.INSERT_CSV_ERR+" - "+c);r(l)}}a(NV,"insertChunk");async function Efe(e){let t={records:0,number_written:0},r=wV(e.schema,e.table);try{let n=new Lw,s=ti.createReadStream(e.file_path,{highWaterMark:TV});s.setEncoding("utf8"),await Cw.parsePromise(s,OV.bind(null,e,n),Pw.bind(null,r));let i=n.getPermsResponse();if(i)throw kt(new Error,i,xr.BAD_REQUEST);return s=ti.createReadStream(e.file_path,{highWaterMark:TV}),s.setEncoding("utf8"),await Cw.parsePromise(s,NV.bind(null,e,t),Pw.bind(null,r)),s.destroy(),t}catch(n){throw kt(n,hl(pr.PAPA_PARSE_ERR),xr.INTERNAL_SERVER_ERROR,ei.LOG_LEVELS.ERROR,pr.PAPA_PARSE_ERR+n)}}a(Efe,"callPapaParse");function wV(e,t){let r=ife[e][t].attributes,n=new Map;for(let s of r)s.type&&!s.computed&&!s.relationship&&n.set(s.name,i=>ofe(i,s));return n}a(wV,"createTransformMap");function Pw(e,t,r){let n=e.get(r);return n?n(t):ld.autoCast(t)}a(Pw,"typeFunction");async function gfe(e){let t={records:0,number_written:0},r=a(n=>{throw n},"throwErr");try{let n=new Lw,s=hV([ti.createReadStream(e.file_path,{encoding:"utf-8"}),mV.withParser(),c=>c.value,new pV({batchSize:AV}),EV(async c=>{await OV(e,n,r,c)})]);await new Promise((c,l)=>{gV(s,u=>{u?l(u):c()}),s.resume()});let i=n.getPermsResponse();if(i)throw kt(new Error,i,xr.BAD_REQUEST);let o=hV([ti.createReadStream(e.file_path,{encoding:"utf-8"}),mV.withParser(),c=>c.value,new pV({batchSize:AV}),EV(async c=>{await NV(e,t,r,c)})]);return await new Promise((c,l)=>{gV(o,u=>{u?l(u):c()}),o.resume()}),t}catch(n){throw kt(n,hl(pr.INSERT_JSON_ERR),xr.INTERNAL_SERVER_ERROR,ei.LOG_LEVELS.ERROR,pr.INSERT_JSON_ERR+n)}}a(gfe,"insertJson");async function IV(e){let t={};try{e.data&&e.data.length>0&&Sfe(e.data[0])?t=await Tfe(e.data,e.schema,e.table,e.action):(t.message="No records parsed from csv file.",ud.info(t.message))}catch(r){throw ml(r)}return t}a(IV,"callBulkFileLoad");function Sfe(e){let t=Object.keys(e);for(let r of t)if(!afe.test(r))throw new Error(`Invalid column name '${r}', cancelling load operation`);return!0}a(Sfe,"validateColumnNames");async function Tfe(e,t,r,n){n||(n="insert");let s={operation:n,schema:t,table:r,records:e},i;switch(n){case"insert":i=_S.insert;break;case"update":i=_S.update;break;case"upsert":i=_S.upsert;break;default:throw kt(new Error,pr.INVALID_ACTION_PARAM_ERR(n),xr.BAD_REQUEST,ei.LOG_LEVELS.ERROR,pr.INVALID_ACTION_PARAM_ERR(n))}try{let o=await i(s),c;switch(n){case"insert":c=o.inserted_hashes;break;case"update":c=o.update_hashes;break;case"upsert":c=o.upserted_hashes;break;default:break}if(Array.isArray(o.skipped_hashes)&&o.skipped_hashes.length>0){let f=global.hdb_schema[t][r].hash_attribute,d=e.length;for(;d--;)o.skipped_hashes.indexOf(e[d][f])>=0&&e.splice(d,1)}let l=ld.isEmptyOrZeroLength(c)?0:c.length;return{records:e.length,number_written:l,new_attributes:o.new_attributes}}catch(o){throw ml(o)}}a(Tfe,"bulkFileLoad");function CV(e,t){return`successfully loaded ${t} of ${e} records`}a(CV,"buildResponseMsg");function ml(e){return kt(e,hl(pr.DEFAULT_BULK_LOAD_ERR),xr.INTERNAL_SERVER_ERROR,ei.LOG_LEVELS.ERROR,pr.DEFAULT_BULK_LOAD_ERR+" - "+e)}a(ml,"buildTopLevelErrMsg")});var Hw=P((fDe,HV)=>{"use strict";var Bw=Vr(),Afe=Ow(),{AsyncParser:Rfe}=require("json2csv"),pS=require("stream"),Jn=ae(),xw=require("fs-extra"),yfe=require("path"),As=j(),{promisify:MV}=require("util"),bh=ae(),{handleHDBError:or,hdb_errors:bfe}=me(),{HDB_ERROR_MSGS:bn,HTTP_STATUS_CODES:ar}=bfe,{streamAsJSON:Ofe}=(MA(),D(BD)),{Upload:Nfe}=require("@aws-sdk/lib-storage"),{toCsvStream:wfe}=(Xi(),D(KD)),DV=["search_by_value","search_by_hash","sql","search_by_conditions"],LV=["json","csv"],vV="json",UV="csv",Ife="Successfully exported JSON locally.",Cfe="Successfully exported CSV locally.",Pfe=1e3,Dfe=Bw.searchByHash,Lfe=Bw.searchByValue,Mfe=MV(pS.finished);HV.exports={export_to_s3:Bfe,export_local:vfe};async function vfe(e){As.trace(`export_local request to path: ${e.path}, filename: ${e.filename}, format: ${e.format}`);let t=xV(e);if(!Jn.isEmpty(t))throw As.error(t),or(new Error,t,ar.BAD_REQUEST,void 0,void 0,!0);if(Jn.isEmpty(e.path))throw As.error(bn.MISSING_VALUE("path")),or(new Error,bn.MISSING_VALUE("path"),ar.BAD_REQUEST,void 0,void 0,!0);let r=(Jn.isEmpty(e.filename)?new Date().getTime():e.filename)+"."+e.format;e.path.endsWith(yfe.sep)&&(e.path=e.path.substring(0,e.path.length-1));let n=Jn.buildFolderPath(e.path,r);await Ufe(e.path);let s=await BV(e);return await xfe(n,e.format,s)}a(vfe,"export_local");async function Ufe(e){if(As.trace("in confirmPath"),Jn.isEmptyOrZeroLength(e))throw or(new Error,`Invalid path: ${e}`,ar.BAD_REQUEST,void 0,void 0,!0);let t;try{t=await xw.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,As.error(n),or(new Error,n,ar.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 As.error(r),or(new Error,r,ar.BAD_REQUEST,void 0,void 0,!0)}return!0}a(Ufe,"confirmPath");async function xfe(e,t,r){if(As.trace("in saveToLocal"),bh.isEmptyOrZeroLength(e))throw or(new Error,bn.INVALID_VALUE("file_path"),ar.BAD_REQUEST,void 0,void 0,!0);if(bh.isEmptyOrZeroLength(t))throw or(new Error,bn.INVALID_VALUE("Source format"),ar.BAD_REQUEST,void 0,void 0,!0);if(bh.isEmpty(r))throw or(new Error,bn.NOT_FOUND("Data"),ar.BAD_REQUEST,void 0,void 0,!0);if(t===vV){let n=xw.createWriteStream(e);return Ofe(r).pipe(n),await Mfe(n),{message:Ife,path:e}}else if(t===UV){let n=xw.createWriteStream(e),s=pS.Readable.from(r),i={},o=r.getColumns?.();o&&(i.fields=o.map(f=>({label:f,value:f})));let c={objectMode:!0};return await new Rfe(i,c).fromInput(s).toOutput(n).promise(!1),{message:Cfe,path:e}}throw or(new Error,bn.INVALID_VALUE("format"),ar.BAD_REQUEST)}a(xfe,"saveToLocal");async function Bfe(e){if(!e.s3||Object.keys(e.s3).length===0)throw or(new Error,bn.MISSING_VALUE("S3 object"),ar.BAD_REQUEST);if(Jn.isEmptyOrZeroLength(e.s3.aws_access_key_id))throw or(new Error,bn.MISSING_VALUE("aws_access_key_id"),ar.BAD_REQUEST);if(Jn.isEmptyOrZeroLength(e.s3.aws_secret_access_key))throw or(new Error,bn.MISSING_VALUE("aws_secret_access_key"),ar.BAD_REQUEST);if(Jn.isEmptyOrZeroLength(e.s3.bucket))throw or(new Error,bn.MISSING_VALUE("bucket"),ar.BAD_REQUEST);if(Jn.isEmptyOrZeroLength(e.s3.key))throw or(new Error,bn.MISSING_VALUE("key"),ar.BAD_REQUEST);if(Jn.isEmptyOrZeroLength(e.s3.region))throw or(new Error,bn.MISSING_VALUE("region"),ar.BAD_REQUEST);let t=xV(e);if(!Jn.isEmpty(t))throw or(new Error,t,ar.BAD_REQUEST);As.trace(`called export_to_s3 to bucket: ${e.s3.bucket} and query ${e.search_operation.sql}`);let r;try{r=await BV(e)}catch(l){throw As.error(l),l}let n,s=await Afe.getS3AuthObj(e.s3.aws_access_key_id,e.s3.aws_secret_access_key,e.s3.region),i,o=new pS.PassThrough;if(e.format===UV){i=e.s3.key+".csv";let l=wfe(r,r.getColumns?.());l.on("error",u=>{throw u}),l.pipe(o)}else if(e.format===vV){i=e.s3.key+".json";let l=new pS.Readable;l.pipe(o),l.on("error",d=>{throw d}),l.push("[");let u=r.length,f="";for(let[d,_]of r.entries()){let h=d===u-1?JSON.stringify(_):JSON.stringify(_)+",";f+=h,d!==0&&d%Pfe===0&&(l.push(f),f="")}f.length!==0&&l.push(f),l.push("]"),l.push(null)}else throw or(new Error,bn.INVALID_VALUE("format"),ar.BAD_REQUEST);return new Nfe({client:s,params:{Bucket:e.s3.bucket,Key:i,Body:o}}).done()}a(Bfe,"export_to_s3");function xV(e){if(As.trace("in exportCoreValidation"),Jn.isEmpty(e.format))return"format missing";if(LV.indexOf(e.format)<0)return`format invalid. must be one of the following values: ${LV.join(", ")}`;let t=e.search_operation.operation;if(Jn.isEmpty(t))return"search_operation.operation missing";if(DV.indexOf(t)<0)return`search_operation.operation must be one of the following values: ${DV.join(", ")}`}a(xV,"exportCoreValidation");async function BV(e){As.trace("in getRecords");let t,r;if(bh.isEmpty(e.search_operation)||bh.isEmptyOrZeroLength(e.search_operation.operation))throw or(new Error,bn.INVALID_VALUE("Search operation"),ar.BAD_REQUEST);switch(e.search_operation.operation){case"search_by_value":t=Lfe;break;case"search_by_hash":t=Dfe;break;case"search_by_conditions":t=Bw.searchByConditions;break;case"sql":{let n=iS();t=MV(n.evaluateSQL);break}default:throw r=`Operation ${e.search_operation.operation} is not support by export.`,As.error(r),or(new Error,r,ar.BAD_REQUEST)}return e.search_operation.hdb_user=e.hdb_user,t(e.search_operation)}a(BV,"getRecords")});var FV=P((hDe,kV)=>{"use strict";var kw=class{static{a(this,"SqlSearchObject")}constructor(t,r){this.operation="sql",this.sql=t,this.hdb_user=r}};kV.exports=kw});var $V=P((pDe,qV)=>{"use strict";var Hfe=(k(),D($)),GV=require("moment"),kfe=require("uuid").v4,Fw=class{static{a(this,"JobObject")}constructor(){this.id=kfe(),this.type=void 0,this.start_datetime=GV().valueOf(),this.created_datetime=GV().valueOf(),this.end_datetime=void 0,this.status=Hfe.JOB_STATUS_ENUM.CREATED,this.message=void 0,this.user=void 0,this.request=void 0}};qV.exports=Fw});var Gw=P((gDe,JV)=>{"use strict";var Ffe=require("uuid").v4,zV=pn(),QV=Vr(),Gfe=$s(),qfe=du(),$fe=FV(),Rt=(k(),D($)),Vfe=$V(),Kfe=_E(),ri=j(),Yfe=nf(),dd=ae(),{promisify:Wfe}=require("util"),pl=require("moment"),zfe=iS(),ES=yw(),VV=MR(),{deleteTransactionLogsBeforeValidator:Qfe}=nw(),{handleHDBError:KV,hdb_errors:jfe,ClientError:Jfe}=me(),{HTTP_STATUS_CODES:YV}=jfe,WV=QV.searchByValue,Xfe=QV.searchByHash,Zfe=zV.insert,e_e=Wfe(zfe.evaluateSQL),t_e=zV.update;JV.exports={addJob:s_e,updateJob:o_e,handleGetJob:r_e,handleGetJobsByStartDate:n_e,getJobById:jV};async function r_e(e){if(e.id===void 0)throw new Jfe("'id' is required");let t=await jV(e.id);return dd.isEmptyOrZeroLength(t)||(t[0]={...t[0]},t[0].request!==void 0&&delete t[0].request,delete t[0].__createdtime__,delete t[0].__updatedtime__),t}a(r_e,"handleGetJob");async function n_e(e){try{let t=await i_e(e);if(ri.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=pl(r.start_datetime)),r.end_datetime&&(r.end_datetime_converted=pl(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 ri.error(r),new Error(r)}}a(n_e,"handleGetJobsByStartDate");async function s_e(e){let t={message:"",error:"",success:!1,createdJob:void 0};if(!e||Object.keys(e).length===0||dd.isEmptyOrZeroLength(e.operation)){let f="job parameter is invalid";return ri.info(f),t.error=f,t}if(!Rt.JOB_TYPE_ENUM[e.operation])return ri.info(`invalid job type specified: ${e.operation}.`),t;let r=e.operation,n;switch(r){case Rt.OPERATIONS_ENUM.CSV_FILE_LOAD:n=ES.fileObject(e);break;case Rt.OPERATIONS_ENUM.CSV_URL_LOAD:n=ES.urlObject(e);break;case Rt.OPERATIONS_ENUM.CSV_DATA_LOAD:n=ES.dataObject(e);break;case Rt.OPERATIONS_ENUM.IMPORT_FROM_S3:n=ES.s3FileObject(e);break;case Rt.OPERATIONS_ENUM.DELETE_FILES_BEFORE:case Rt.OPERATIONS_ENUM.DELETE_RECORDS_BEFORE:n=VV(e,"date");break;case Rt.OPERATIONS_ENUM.DELETE_AUDIT_LOGS_BEFORE:n=VV(e,"timestamp");break;case Rt.OPERATIONS_ENUM.DELETE_TRANSACTION_LOGS_BEFORE:n=Qfe(e);break;case Rt.OPERATIONS_ENUM.RESTART_SERVICE:if(Rt.HDB_PROCESS_SERVICES[e.service]===void 0)throw KV(new Error,"Invalid service",YV.BAD_REQUEST,void 0,void 0,!0);break;default:break}if(n)throw KV(n,n.message,YV.BAD_REQUEST,void 0,void 0,!0);let s=new Vfe;s.type=e.operation===Rt.OPERATIONS_ENUM.DELETE_RECORDS_BEFORE?Rt.OPERATIONS_ENUM.DELETE_FILES_BEFORE:e.operation,s.type=e.operation,s.user=e.hdb_user?.username;let i=new Gfe(Rt.SYSTEM_SCHEMA_NAME,Rt.SYSTEM_TABLE_NAMES.JOB_TABLE_NAME,"id",s.id,"id",["id"]),o;try{o=Array.from(await WV(i))}catch(f){let d=`There was an error inserting a new job: ${f}`;return ri.error(d),t}let c=Array.isArray(o)?o:Object.keys(o);if(c&&c.length>0){s.id=Ffe();try{o=await WV(i)}catch(f){let d=`There was an error inserting a new job: ${f}`;return ri.error(d),t}if(c=Array.isArray(o)?o:Object.keys(o),c&&c.length>0)return ri.error("Error creating a job, could not find a unique job id."),t}s.request=e;let l=new Yfe(Rt.SYSTEM_SCHEMA_NAME,Rt.SYSTEM_TABLE_NAMES.JOB_TABLE_NAME,"id",[s]),u;try{u=await Zfe(l)}catch(f){return ri.error(`There was an error inserting a job for job type: ${e.operation} -- ${f}`),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 f=`Created a job with type ${s.type} and id ${s.id}`;t.message=f,t.createdJob=s,t.success=!0,ri.trace(f)}return t}a(s_e,"addJob");async function i_e(e){let t=pl(e.from_date,pl.ISO_8601),r=pl(e.to_date,pl.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 $fe(n,e.hdb_user);try{return await e_e(s)}catch(i){throw ri.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.")}}a(i_e,"getJobsInDateRange");async function jV(e){if(dd.isEmptyOrZeroLength(e))return dd.errorizeMessage("Invalid job ID specified.");let t=new qfe(Rt.SYSTEM_SCHEMA_NAME,Rt.SYSTEM_TABLE_NAMES.JOB_TABLE_NAME,[e],["*"]);try{return await Xfe(t)}catch(r){let n=`There was an error searching for a job by id: ${e} ${r}`;return ri.error(n),dd.errorizeMessage("there was an error searching for jobs. Please check the log for details.")}}a(jV,"getJobById");async function o_e(e){if(Object.keys(e).length===0)throw new Error("invalid job object passed to updateJob");if(dd.isEmptyOrZeroLength(e.id))throw new Error("invalid ID passed to updateJob");(e.status===Rt.JOB_STATUS_ENUM.COMPLETE||e.status===Rt.JOB_STATUS_ENUM.ERROR)&&(e.end_datetime=pl().valueOf());let t=new Kfe(Rt.SYSTEM_SCHEMA_NAME,Rt.SYSTEM_TABLE_NAMES.JOB_TABLE_NAME,[e]),r;return r=await t_e(t),r}a(o_e,"updateJob")});var i1=P((TDe,s1)=>{"use strict";var XV=ae(),Er=(k(),D($)),a_e=require("moment"),gS=vw(),Oh=j(),ZV=Gw(),e1=Hw(),t1=bc(),r1=tt(),c_e=Zg(),l_e=rd(),{parentPort:u_e,isMainThread:n1}=require("worker_threads"),{onMessageByType:d_e}=tt(),qw=class{static{a(this,"RunnerMessage")}constructor(t,r){this.job=t,this.json=r}};async function f_e(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(XV.isEmptyOrZeroLength(e.json.operation))throw new Error("Invalid operation");if(XV.isEmptyOrZeroLength(e.job.id))throw new Error("Empty job id specified");switch(e.json.operation){case Er.JOB_TYPE_ENUM.csv_file_load:await Li(e,gS.csvFileLoad);break;case Er.JOB_TYPE_ENUM.csv_url_load:await Li(e,gS.csvURLLoad);break;case Er.JOB_TYPE_ENUM.csv_data_load:await Li(e,gS.csvDataLoad);break;case Er.JOB_TYPE_ENUM.import_from_s3:await Li(e,gS.importFromS3);break;case Er.JOB_TYPE_ENUM.empty_trash:break;case Er.JOB_TYPE_ENUM.export_local:await Li(e,e1.export_local);break;case Er.JOB_TYPE_ENUM.export_to_s3:await Li(e,e1.export_to_s3);break;case Er.JOB_TYPE_ENUM.delete_files_before:case Er.JOB_TYPE_ENUM.delete_records_before:await Li(e,t1.deleteFilesBefore);break;case Er.JOB_TYPE_ENUM.delete_audit_logs_before:await Li(e,t1.deleteAuditLogsBefore);break;case Er.JOB_TYPE_ENUM.delete_transaction_logs_before:await Li(e,c_e.deleteTransactionLogsBefore);break;case Er.JOB_TYPE_ENUM.restart_service:return await Li(e,l_e.restartService),`Restarting ${e.json.service}`;break;default:return`Invalid operation ${e.json.operation} specified`}}a(f_e,"parseMessage");async function Li(e,t){try{e.job.status=Er.JOB_STATUS_ENUM.IN_PROGRESS,e.job.start_datetime=a_e().valueOf(),await ZV.updateJob(e.job),await __e(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):Oh.error(`There was an error running ${t.name} job with id ${e.job.id}`),Oh.error(n),e.job.message=n,e.job.status=Er.JOB_STATUS_ENUM.ERROR;try{await ZV.updateJob(e.job)}catch(s){throw Oh.error(`Unable to update job with id ${e.job.id}`),s}throw r}}a(Li,"runJob");async function __e(e){Oh.trace("launching job thread:",e),n1?r1.startWorker("server/jobs/jobProcess.js",{autoRestart:!1,name:"job",env:{...process.env,[Er.PROCESS_NAME_ENV_PROP]:`JOB-${e}`}}):u_e.postMessage({type:Er.ITC_EVENT_TYPES.START_JOB,jobId:e})}a(__e,"launchJobThread");n1&&d_e(Er.ITC_EVENT_TYPES.START_JOB,async(e,t)=>{try{r1.startWorker("server/jobs/jobProcess.js",{autoRestart:!1,name:"job",env:{...process.env,[Er.PROCESS_NAME_ENV_PROP]:`JOB-${e.jobId}`}})}catch(r){Oh.error(r)}});s1.exports={parseMessage:f_e,RunnerMessage:qw}});var a1=P((RDe,o1)=>{"use strict";var $w=class{static{a(this,"OperationFunctionObject")}constructor(t,r=void 0){this.operation_function=t,this.job_operation_function=r}};o1.exports=$w});var rw=P((ODe,Qw)=>{"use strict";var yS=Vr(),Yw=iS(),SS=vw(),Io=og(),TS=io(),wh=bc(),h_e=IO(),Nh=Fn(),AS=i_(),Pt=tw(),RS=j(),m_e=MO(),p_e=gg(),c1=sN(),E_e=Tg(),g_e=aN(),S_e=cN(),T_e=dN(),A_e=_N(),Vw=Og(),l1=Hw(),R_e=nS(),Ww=Gw(),V=(k(),D($)),{hdb_errors:Ch,handleHDBError:Ih}=me(),{HTTP_STATUS_CODES:u1}=Ch,Kw=NN(),d1=rd(),A1=require("util"),_d=pn(),y_e=ks(),b_e=$u(),f1=i1(),_1=(Au(),D(g_)),h1=(Kg(),D(ch)),m1=Ct(),p1=Zg(),E1=fh(),{setServerUtilities:O_e}=(df(),D(Uw)),{CONTEXT:bDe}=(Xo(),D(NA)),{_assignPackageExport:N_e}=ci(),{transformReq:w_e}=ae(),{server:I_e}=(Pr(),D(Yl)),rn=RS.loggerWithTag("operation"),fd=js(),g1=(el(),D(Zc)),C_e=bw(),S1=yS.searchByHash,P_e=yS.searchByValue,D_e=A1.promisify(yS.search),L_e=A1.promisify(Yw.evaluateSQL),M_e={[V.OPERATIONS_ENUM.CREATE_ATTRIBUTE]:!0,[V.OPERATIONS_ENUM.CREATE_TABLE]:!0,[V.OPERATIONS_ENUM.CREATE_SCHEMA]:!0,[V.OPERATIONS_ENUM.DROP_ATTRIBUTE]:!0,[V.OPERATIONS_ENUM.DROP_TABLE]:!0,[V.OPERATIONS_ENUM.DROP_SCHEMA]:!0},X=a1();async function R1(e,t){try{if(e.body.operation!=="read_log"&&(RS.log_level===V.LOG_LEVELS.INFO||RS.log_level===V.LOG_LEVELS.DEBUG||RS.log_level===V.LOG_LEVELS.TRACE)){let{hdb_user:n,hdb_auth_header:s,password:i,payload:o,...c}=e.body;rn.info(c)}}catch(n){rn.error(n)}let r=await C_e.callOperationFunctionAsAwait(t,e.body,null);if(typeof r!="object"&&(r={message:r}),r instanceof Error)throw r;return M_e[e.body.operation]&&y_e.setSchemaDataToGlobal(n=>{n&&rn.error(n)}),r}a(R1,"processLocalTransaction");var T1=U_e();Qw.exports={chooseOperation:y1,getOperationFunction:b1,operation:zw,processLocalTransaction:R1,executeJob:Rs};O_e(Qw.exports);I_e.operation=zw;function y1(e){let t;try{t=b1(e)}catch(s){throw rn.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=Yw.convertSQLToAST(s);if(e.parsed_sql_object=i,!e.bypass_auth){let o=Yw.checkASTPermissions(e,i);if(o)throw rn.error(`${u1.FORBIDDEN} from operation ${e.operation}`),rn.warn(`User '${e.hdb_user?.username}' is not permitted to ${e.operation}`),Ih(new Error,o,Ch.HTTP_STATUS_CODES.FORBIDDEN,void 0,void 0,!0)}}else if(!e.bypass_auth&&e.operation!==V.OPERATIONS_ENUM.CREATE_AUTHENTICATION_TOKENS&&e.operation!==V.OPERATIONS_ENUM.LOGIN&&e.operation!==V.OPERATIONS_ENUM.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 o=R_e.verifyPerms(i,s);if(o)throw rn.error(`${u1.FORBIDDEN} from operation ${e.operation}`),rn.warn(`User '${i.hdb_user?.username}' is not permitted to ${i.operation}`),Ih(new Error,o,Ch.HTTP_STATUS_CODES.FORBIDDEN,void 0,!1,!0)}}catch(s){throw Ih(s,"There was an error when trying to choose an operation path")}return r}a(y1,"chooseOperation");function b1(e){if(rn.trace(`getOperationFunction with operation: ${e.operation}`),T1.has(e.operation))return T1.get(e.operation);throw Ih(new Error,Ch.HDB_ERROR_MSGS.OP_NOT_FOUND(e.operation),Ch.HTTP_STATUS_CODES.BAD_REQUEST,void 0,void 0,!0)}a(b1,"getOperationFunction");N_e("operation",zw);function zw(e,t,r){e.hdb_user=t?.user,e.bypass_auth=!r;let n=y1(e);return R1({body:e},n)}a(zw,"operation");async function v_e(e){rn.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[V.CLUSTERING_FLAG]=!0;let o;switch(i.operation){case V.OPERATIONS_ENUM.INSERT:o=await _d.insert(i);break;case V.OPERATIONS_ENUM.UPDATE:o=await _d.update(i);break;case V.OPERATIONS_ENUM.UPSERT:o=await _d.upsert(i);break;case V.OPERATIONS_ENUM.DELETE:o=await wh.deleteRecord(i);break;default:rn.warn("invalid operation in catchup");break}await transact_to_clustering_utils.postOperationHandler(i,o,e)}catch(o){rn.info("Invalid operation in transaction"),rn.error(o)}}a(v_e,"catchup");async function Rs(e){w_e(e);let t,r;try{r=await Ww.addJob(e),t=r.createdJob,rn.info("addJob result",r);let n=new f1.RunnerMessage(t,e);return{message:await f1.parseMessage(n)??`Starting job with id ${t.id}`,job_id:t.id}}catch(n){let s=`There was an error executing job: ${n.http_resp_msg?n.http_resp_msg:n}`;throw rn.error(s),Ih(n,s)}}a(Rs,"executeJob");function U_e(){let e=new Map;return e.set(V.OPERATIONS_ENUM.INSERT,new X(_d.insert)),e.set(V.OPERATIONS_ENUM.UPDATE,new X(_d.update)),e.set(V.OPERATIONS_ENUM.UPSERT,new X(_d.upsert)),e.set(V.OPERATIONS_ENUM.SEARCH_BY_CONDITIONS,new X(yS.searchByConditions)),e.set(V.OPERATIONS_ENUM.SEARCH_BY_HASH,new X(S1)),e.set(V.OPERATIONS_ENUM.SEARCH_BY_ID,new X(S1)),e.set(V.OPERATIONS_ENUM.SEARCH_BY_VALUE,new X(P_e)),e.set(V.OPERATIONS_ENUM.SEARCH,new X(D_e)),e.set(V.OPERATIONS_ENUM.SQL,new X(L_e)),e.set(V.OPERATIONS_ENUM.CSV_DATA_LOAD,new X(Rs,SS.csvDataLoad)),e.set(V.OPERATIONS_ENUM.CSV_FILE_LOAD,new X(Rs,SS.csvFileLoad)),e.set(V.OPERATIONS_ENUM.CSV_URL_LOAD,new X(Rs,SS.csvURLLoad)),e.set(V.OPERATIONS_ENUM.IMPORT_FROM_S3,new X(Rs,SS.importFromS3)),e.set(V.OPERATIONS_ENUM.CREATE_SCHEMA,new X(Io.createSchema)),e.set(V.OPERATIONS_ENUM.CREATE_DATABASE,new X(Io.createSchema)),e.set(V.OPERATIONS_ENUM.CREATE_TABLE,new X(Io.createTable)),e.set(V.OPERATIONS_ENUM.CREATE_ATTRIBUTE,new X(Io.createAttribute)),e.set(V.OPERATIONS_ENUM.DROP_SCHEMA,new X(Io.dropSchema)),e.set(V.OPERATIONS_ENUM.DROP_DATABASE,new X(Io.dropSchema)),e.set(V.OPERATIONS_ENUM.DROP_TABLE,new X(Io.dropTable)),e.set(V.OPERATIONS_ENUM.DROP_ATTRIBUTE,new X(Io.dropAttribute)),e.set(V.OPERATIONS_ENUM.DESCRIBE_SCHEMA,new X(TS.describeSchema)),e.set(V.OPERATIONS_ENUM.DESCRIBE_DATABASE,new X(TS.describeSchema)),e.set(V.OPERATIONS_ENUM.DESCRIBE_TABLE,new X(TS.describeTable)),e.set(V.OPERATIONS_ENUM.DESCRIBE_ALL,new X(TS.describeAll)),e.set(V.OPERATIONS_ENUM.DELETE,new X(wh.deleteRecord)),e.set(V.OPERATIONS_ENUM.ADD_USER,new X(Nh.addUser)),e.set(V.OPERATIONS_ENUM.ALTER_USER,new X(Nh.alterUser)),e.set(V.OPERATIONS_ENUM.DROP_USER,new X(Nh.dropUser)),e.set(V.OPERATIONS_ENUM.LIST_USERS,new X(Nh.listUsersExternal)),e.set(V.OPERATIONS_ENUM.LIST_ROLES,new X(AS.listRoles)),e.set(V.OPERATIONS_ENUM.ADD_ROLE,new X(AS.addRole)),e.set(V.OPERATIONS_ENUM.ALTER_ROLE,new X(AS.alterRole)),e.set(V.OPERATIONS_ENUM.DROP_ROLE,new X(AS.dropRole)),e.set(V.OPERATIONS_ENUM.USER_INFO,new X(Nh.userInfo)),e.set(V.OPERATIONS_ENUM.READ_LOG,new X(m_e)),e.set(V.OPERATIONS_ENUM.ADD_NODE,new X(p_e)),e.set(V.OPERATIONS_ENUM.UPDATE_NODE,new X(c1)),e.set(V.OPERATIONS_ENUM.SET_NODE_REPLICATION,new X(c1)),e.set(V.OPERATIONS_ENUM.REMOVE_NODE,new X(E_e)),e.set(V.OPERATIONS_ENUM.CONFIGURE_CLUSTER,new X(g_e)),e.set(V.OPERATIONS_ENUM.PURGE_STREAM,new X(S_e)),e.set(V.OPERATIONS_ENUM.SET_CONFIGURATION,new X(m1.setConfiguration)),e.set(V.OPERATIONS_ENUM.CLUSTER_STATUS,new X(T_e.clusterStatus)),e.set(V.OPERATIONS_ENUM.CLUSTER_NETWORK,new X(A_e)),e.set(V.OPERATIONS_ENUM.CLUSTER_SET_ROUTES,new X(Vw.setRoutes)),e.set(V.OPERATIONS_ENUM.CLUSTER_GET_ROUTES,new X(Vw.getRoutes)),e.set(V.OPERATIONS_ENUM.CLUSTER_DELETE_ROUTES,new X(Vw.deleteRoutes)),e.set(V.OPERATIONS_ENUM.EXPORT_TO_S3,new X(Rs,l1.export_to_s3)),e.set(V.OPERATIONS_ENUM.CREATE_CSR,new X(fd.createCsr)),e.set(V.OPERATIONS_ENUM.SIGN_CERTIFICATE,new X(fd.signCertificate)),e.set(V.OPERATIONS_ENUM.LIST_CERTIFICATES,new X(fd.listCertificates)),e.set(V.OPERATIONS_ENUM.ADD_CERTIFICATES,new X(fd.addCertificate)),e.set(V.OPERATIONS_ENUM.REMOVE_CERTIFICATE,new X(fd.removeCertificate)),e.set(V.OPERATIONS_ENUM.GET_KEY,new X(fd.getKey)),e.set(V.OPERATIONS_ENUM.ADD_NODE_BACK,new X(g1.addNodeBack)),e.set(V.OPERATIONS_ENUM.REMOVE_NODE_BACK,new X(g1.removeNodeBack)),e.set(V.OPERATIONS_ENUM.DELETE_FILES_BEFORE,new X(Rs,wh.deleteFilesBefore)),e.set(V.OPERATIONS_ENUM.DELETE_RECORDS_BEFORE,new X(Rs,wh.deleteFilesBefore)),e.set(V.OPERATIONS_ENUM.EXPORT_LOCAL,new X(Rs,l1.export_local)),e.set(V.OPERATIONS_ENUM.SEARCH_JOBS_BY_START_DATE,new X(Ww.handleGetJobsByStartDate)),e.set(V.OPERATIONS_ENUM.GET_JOB,new X(Ww.handleGetJob)),e.set(V.OPERATIONS_ENUM.GET_FINGERPRINT,new X(Kw.getFingerprint)),e.set(V.OPERATIONS_ENUM.SET_LICENSE,new X(Kw.setLicense)),e.set(V.OPERATIONS_ENUM.GET_REGISTRATION_INFO,new X(Kw.getRegistrationInfo)),e.set(V.OPERATIONS_ENUM.RESTART,new X(d1.restart)),e.set(V.OPERATIONS_ENUM.RESTART_SERVICE,new X(Rs,d1.restartService)),e.set(V.OPERATIONS_ENUM.CATCHUP,new X(v_e)),e.set(V.OPERATIONS_ENUM.SYSTEM_INFORMATION,new X(b_e.systemInformation)),e.set(V.OPERATIONS_ENUM.DELETE_AUDIT_LOGS_BEFORE,new X(Rs,wh.deleteAuditLogsBefore)),e.set(V.OPERATIONS_ENUM.READ_AUDIT_LOG,new X(h_e)),e.set(V.OPERATIONS_ENUM.CREATE_AUTHENTICATION_TOKENS,new X(_1.createTokens)),e.set(V.OPERATIONS_ENUM.REFRESH_OPERATION_TOKEN,new X(_1.refreshOperationToken)),e.set(V.OPERATIONS_ENUM.LOGIN,new X(h1.login)),e.set(V.OPERATIONS_ENUM.LOGOUT,new X(h1.logout)),e.set(V.OPERATIONS_ENUM.GET_CONFIGURATION,new X(m1.getConfiguration)),e.set(V.OPERATIONS_ENUM.CUSTOM_FUNCTIONS_STATUS,new X(Pt.customFunctionsStatus)),e.set(V.OPERATIONS_ENUM.GET_CUSTOM_FUNCTIONS,new X(Pt.getCustomFunctions)),e.set(V.OPERATIONS_ENUM.GET_COMPONENT_FILE,new X(Pt.getComponentFile)),e.set(V.OPERATIONS_ENUM.GET_COMPONENTS,new X(Pt.getComponents)),e.set(V.OPERATIONS_ENUM.SET_COMPONENT_FILE,new X(Pt.setComponentFile)),e.set(V.OPERATIONS_ENUM.DROP_COMPONENT,new X(Pt.dropComponent)),e.set(V.OPERATIONS_ENUM.GET_CUSTOM_FUNCTION,new X(Pt.getCustomFunction)),e.set(V.OPERATIONS_ENUM.SET_CUSTOM_FUNCTION,new X(Pt.setCustomFunction)),e.set(V.OPERATIONS_ENUM.DROP_CUSTOM_FUNCTION,new X(Pt.dropCustomFunction)),e.set(V.OPERATIONS_ENUM.ADD_CUSTOM_FUNCTION_PROJECT,new X(Pt.addComponent)),e.set(V.OPERATIONS_ENUM.ADD_COMPONENT,new X(Pt.addComponent)),e.set(V.OPERATIONS_ENUM.DROP_CUSTOM_FUNCTION_PROJECT,new X(Pt.dropCustomFunctionProject)),e.set(V.OPERATIONS_ENUM.PACKAGE_CUSTOM_FUNCTION_PROJECT,new X(Pt.packageComponent)),e.set(V.OPERATIONS_ENUM.PACKAGE_COMPONENT,new X(Pt.packageComponent)),e.set(V.OPERATIONS_ENUM.DEPLOY_CUSTOM_FUNCTION_PROJECT,new X(Pt.deployComponent)),e.set(V.OPERATIONS_ENUM.DEPLOY_COMPONENT,new X(Pt.deployComponent)),e.set(V.OPERATIONS_ENUM.READ_TRANSACTION_LOG,new X(p1.readTransactionLog)),e.set(V.OPERATIONS_ENUM.DELETE_TRANSACTION_LOGS_BEFORE,new X(Rs,p1.deleteTransactionLogsBefore)),e.set(V.OPERATIONS_ENUM.INSTALL_NODE_MODULES,new X(E1.installModules)),e.set(V.OPERATIONS_ENUM.AUDIT_NODE_MODULES,new X(E1.auditModules)),e.set(V.OPERATIONS_ENUM.GET_BACKUP,new X(Io.getBackup)),e.set(V.OPERATIONS_ENUM.ADD_SSH_KEY,new X(Pt.addSSHKey)),e.set(V.OPERATIONS_ENUM.UPDATE_SSH_KEY,new X(Pt.updateSSHKey)),e.set(V.OPERATIONS_ENUM.DELETE_SSH_KEY,new X(Pt.deleteSSHKey)),e.set(V.OPERATIONS_ENUM.LIST_SSH_KEYS,new X(Pt.listSSHKeys)),e.set(V.OPERATIONS_ENUM.SET_SSH_KNOWN_HOSTS,new X(Pt.setSSHKnownHosts)),e.set(V.OPERATIONS_ENUM.GET_SSH_KNOWN_HOSTS,new X(Pt.getSSHKnownHosts)),e}a(U_e,"initializeOperationFunctionMap")});var NS=P((wDe,w1)=>{"use strict";var bS=(k(),D($)),x_e=ae(),Ph=j(),{handleHDBError:jw,hdb_errors:OS}=me(),{isMainThread:B_e}=require("worker_threads"),{Readable:H_e}=require("stream"),O1=require("os"),k_e=require("util"),F_e=Lb(),G_e=k_e.promisify(F_e.authorize),N1=rw(),{createGzip:q_e,constants:$_e}=require("zlib"),V_e=[bS.OPERATIONS_ENUM.CREATE_AUTHENTICATION_TOKENS,bS.OPERATIONS_ENUM.LOGIN,bS.OPERATIONS_ENUM.LOGOUT];function K_e(e){let t=`Found an uncaught exception with message: ${e.message}. ${O1.EOL}Stack: ${e.stack} ${O1.EOL}Terminating ${B_e?"HDB":"thread"}.`;console.error(t),Ph.fatal(t),process.exit(1)}a(K_e,"handleServerUncaughtException");function Y_e(e,t,r){if(Ph[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:OS.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)}a(Y_e,"serverErrorHandler");function W_e(e,t,r){if(!e.body||Object.keys(e.body).length===0||typeof e.body!="object"){let n=jw(new Error,"Invalid JSON.",OS.HTTP_STATUS_CODES.BAD_REQUEST);r(n,null)}if(x_e.isEmpty(e.body.operation)){let n=jw(new Error,"Request body must include an 'operation' property.",OS.HTTP_STATUS_CODES.BAD_REQUEST);r(n,null)}r()}a(W_e,"reqBodyValidationHandler");function z_e(e,t,r){let n;!V_e.includes(e.body.operation)||e.body.operation===bS.OPERATIONS_ENUM.CREATE_AUTHENTICATION_TOKENS&&!e.body.username&&!e.body.password?G_e(e,t).then(i=>{n=i,e.body.hdb_user=n,r()}).catch(i=>{Ph.warn(i),Ph.warn(`{"ip":"${e.socket.remoteAddress}", "error":"${i.stack}"`);let o=typeof i=="string"?{error:i}:{error:i.message};r(jw(i,o,OS.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())}a(z_e,"authHandler");async function Q_e(e,t,r=!1){let n;try{e.body.bypass_auth&&delete e.body.bypass_auth,n=N1.chooseOperation(e.body);let s=await N1.processLocalTransaction(e,n);if(s instanceof H_e&&s.headers){for(let[i,o]of s.headers)t.header(i,o);e.headers["accept-encoding"]?.includes("gzip")&&(t.header("content-encoding","gzip"),s=s.pipe(q_e({level:$_e.Z_BEST_SPEED})))}return s}catch(s){throw Ph.error(s),s}}a(Q_e,"handlePostRequest");w1.exports={authHandler:z_e,handlePostRequest:Q_e,handleServerUncaughtException:K_e,serverErrorHandler:Y_e,reqBodyValidationHandler:W_e}});var D1=P((CDe,P1)=>{"use strict";var j_e=require("fastify-plugin"),{handlePostRequest:I1,authHandler:J_e,reqBodyValidationHandler:X_e}=NS();async function Z_e(e){e.decorate("hdbCore",{preValidation:[X_e,J_e],request:a(t=>C1(I1(t,response)),"request"),requestWithoutAuthentication:a((t,r)=>C1(I1(t,r,!0)),"requestWithoutAuthentication")})}a(Z_e,"hdbCore");async function C1(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}a(C1,"convertAsyncIterators");P1.exports=j_e(Z_e)});var M1=P((LDe,L1)=>{"use strict";var DDe=require("fs"),wS=le();wS.initSync();var{CONFIG_PARAMS:Jw}=(k(),D($)),ehe=1024*1024*1024;function the(e){let t=wS.get(Jw.HTTP_TIMEOUT),r=wS.get(Jw.HTTP_KEEPALIVETIMEOUT);return{bodyLimit:ehe,connectionTimeout:t,keepAliveTimeout:r,return503OnClosing:!1,forceCloseConnections:!0,ignoreTrailingSlash:!0,maxParamLength:wS.get(Jw.HTTP_MAXPARAMLENGTH)??1e3,https:e}}a(the,"getServerOptions");L1.exports=the});var x1=P((vDe,U1)=>{"use strict";var Xw=le();Xw.initSync();var{CONFIG_PARAMS:v1}=(k(),D($));function rhe(){let e=Xw.get(v1.HTTP_CORSACCESSLIST),t=Xw.get(v1.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}a(rhe,"getCORSOptions");U1.exports=rhe});var k1=P((xDe,H1)=>{"use strict";var B1=le();B1.initSync();var nhe=(k(),D($));function she(){return B1.get(nhe.CONFIG_PARAMS.HTTP_HEADERSTIMEOUT)??6e4}a(she,"getHeaderTimeoutConfig");H1.exports=she});var eI={};Ue(eI,{customFunctionsServer:()=>ahe,ready:()=>Z1,start:()=>ohe});function ohe(e){let t=e.securePort>0;return{async handleFile(r,n,s,i){Co||(Co=X1(t),Ke.http((await Co).server));let o=await Co,c=(0,Zw.dirname)(s),l=(0,Zw.dirname)(n);if(l.startsWith("/")&&(l=l.slice(1)),!F1.has(c)){F1.add(c);try{o.register(lhe(c,l))}catch(u){if(u.message==="Root plugin has already booted")_t.warn(`Could not load root fastify route for ${s}, this may require a restart to install properly`);else throw u}}},ready:Z1}}async function ahe(){try{_t.info("In Custom Functions Fastify server"+process.cwd()),_t.info(`Custom Functions Running with NODE_ENV set as: ${process.env.NODE_ENV}`),_t.debug(`Custom Functions server process ${process.pid} starting up.`),await che();let e=Y1.get(U.HTTP_SECUREPORT)>0,t;try{t=Co=await X1(e)}catch(r){throw _t.error(`Custom Functions buildServer error: ${r}`),r}try{await t.ready()}catch(r){throw _t.error(`Custom Functions server.ready() error: ${r}`),r}t.server.cantCleanupProperly=!0}catch(e){_t.error(`Custom Functions ${process.pid} Error: ${e}`),_t.error(e),process.exit(1)}}async function che(){try{_t.info("Custom Functions starting configuration."),await W1.setUsersWithRolesCache(),_t.info("Custom Functions completed configuration.")}catch(e){_t.error(e)}}function lhe(e,t){return async function(r){try{_t.info("Custom Functions starting buildRoutes"),_t.trace("Loading fastify routes folder "+e),(0,G1.existsSync)(e)&&r.register(K1.default,s=>({dir:e,dirNameRoutePrefix:!1,options:{hdbCore:s.hdbCore,logger:_t.loggerWithTag("custom-function"),prefix:`/${t}`}})).after((s,i,o)=>{s?.message?_t.error(s.message):s&&_t.error(s),o()})}catch(n){_t.error(`Custom Functions errored buildRoutes: ${n}`)}}}async function X1(e){_t.info("Custom Functions starting buildServer.");let t=(0,z1.default)(e),r=(0,q1.default)(t);r.server.headersTimeout=(0,j1.default)(),r.setErrorHandler(J1.serverErrorHandler);let n=(0,Q1.default)();return n&&r.register($1.default,n),r.register(function(s,i,o){s.setNotFoundHandler(function(c,l){r.server.emit("unhandled",c.raw,l.raw)}),o()}),r.register(V1.default),await r.register(ihe),await r.after(),mf(r),_t.info("Custom Functions completed buildServer."),r}function Z1(){if(Co)return Co.then?Co.then(e=>e.ready()):Co.ready()}var Zw,G1,q1,$1,V1,K1,Y1,_t,ihe,W1,z1,Q1,j1,J1,Co,F1,eK=be(()=>{Zw=require("path"),G1=require("fs"),q1=M(require("fastify")),$1=M(require("@fastify/cors")),V1=M(wb()),K1=M(require("@fastify/autoload")),Y1=M(le());k();_t=M(j()),ihe=M(D1()),W1=M(Fn()),z1=M(M1()),Q1=M(x1()),j1=M(k1()),J1=M(NS());Xi();Pr();F1=new Set;a(ohe,"start");a(ahe,"customFunctionsServer");a(che,"setUp");a(lhe,"buildRouteFolder");a(X1,"buildServer");a(Z1,"ready")});var tI={};Ue(tI,{start:()=>uhe});function uhe(e){return{handleDirectory(t,r){if(t==="/"){let n=(0,iK.default)(r,e);return e.server.http(async(s,i)=>{if(!s.isWebSocket)return new Promise(o=>n(s._nodeRequest,s._nodeResponse,()=>{o(i(s))}))}),!0}},handleFile(t,r,n){rK||(rK=!0,e.server.http(async(s,i)=>{if(!s.isWebSocket){let o=tK.get(s.pathname);if(o)return{handlesHeaders:!0,body:(0,nK.default)(s,(0,sK.realpathSync)(o))}}return i(s)},{runFirst:!0})),tK.set(r,n)}}}var nK,sK,iK,tK,rK,oK=be(()=>{nK=M(require("send")),sK=require("fs"),iK=M(require("serve-static")),tK=new Map;a(uhe,"start")});var rI={};Ue(rI,{start:()=>dhe});function dhe({override:e}){return{handleFile:a((t,r,n)=>{IS.default.debug(`Loading env file: ${n}`);for(let[s,i]of Object.entries((0,aK.parse)(t))){if(process.env[s]!==void 0)if(IS.default.warn(`Environment variable conflict: ${s} from ${n} is already set on process.env`),e)IS.default.debug(`override option enabled. overriding environment variable: ${s}`);else continue;process.env[s]=i}},"handleFile")}}var aK,IS,cK=be(()=>{aK=require("dotenv"),IS=M(j());a(dhe,"start")});var gK={};Ue(gK,{startHTTPThreads:()=>_he,startSocketServer:()=>aI,updateWorkerIdleness:()=>EK});async function _he(e=2,t){try{if(t)iI(0,1,!0);else{let{loadRootComponents:r}=MS();if(e===0)return(0,ys.setMainIsWorker)(!0),await uI().startServers(),Promise.resolve([]);await r()}pK();for(let r=0;r<e;r++)iI(r,e);return Promise.all(mK)}finally{(0,ys.threadsHaveStarted)()}}function pK(){let e=(0,fK.checkMemoryLimit)();e&&!process.env.DEV_MODE&&(console.error(e),sI=setInterval(()=>{DS.notify(e)},fhe).unref())}function iI(e,t=1,r){if(nI++,(0,ys.startWorker)("server/threads/threadServer.js",{name:aA.HTTP,workerIndex:e,threadCount:t,async onStarted(n){let s=new Promise((o,c)=>{function l(u){u.type===sA.CHILD_STARTED&&(n.removeListener("message",l),o(n))}a(l,"onMessage"),n.on("message",l),n.on("error",c)});mK.push(s),await s,hd.push(n),n.expectedIdle=1,n.lastIdle=0,n.requests=1,n.on("message",o=>{if(o.requestId){let c=PS.get(o.requestId);c&&c(o)}}),n.on("exit",i),n.on("shutdown",i);function i(){let o=hd.indexOf(n);o>-1&&hd.splice(o,1)}if(a(i,"removeWorker"),md){let o=md;md=[];for(let c of o)hK[c.localPort](null,c)}}}),r){let n=setInterval(()=>{oI?oI=!1:(clearInterval(n),console.log("shut down dynamic thread due to inactivity"),(0,ys.shutdownWorkers)(),nI=0,setTimeout(()=>{global.gc?.()},5e3))},1e4)}}function aI(e=0,t){if(typeof e=="string")try{(0,LS.existsSync)(e)&&(0,LS.unlinkSync)(e)}catch{}let r;t?t==="ip"?r=hhe:r=mhe(t):r=cI;let n=(0,pd.createServer)({allowHalfOpen:!0,pauseOnConnect:!r.readsData}).listen(e);return n._handle&&(n._handle.onconnection=hK[e]=function(s,i){r.readsData||(i.reading=!1,i.readStop()),oI=!0,r(i,(o,c)=>{if(!o){if(lK){let u=i._socket||new pd.Socket({handle:i,writable:!0,readable:!0});lK.deliverSocket(u,e,c),u.resume()}else nI>0?(md.length===0&&setTimeout(()=>{md.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,md.push(i)):(console.log("start up a dynamic thread to handle request"),iI(0));er(!1,"socket-routed");return}o.requests++;let l=i.fd;if(l>=0)o.postMessage({port:e,fd:l,data:c});else{let u=i._socket||new pd.Socket({handle:i,writable:!0,readable:!0});ghe(u,o,e)}er(!0,"socket-routed")})},DS.info(`HarperDB ${_K.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 cI(e,t){let r,n=0;for(let s of hd){if(s.threadId===-1)continue;let i=s.expectedIdle/s.requests;if(i>n)r=s;else if(n>=CS)return CS=i,t(r);n=i}CS=0,t(r)}function hhe(e,t){let r={};e.getpeername(r);let n=r.address,s=Ed.get(n),i=Date.now();if(s&&s.worker.threadId!==-1)return s.lastUsed=i,t(s.worker);cI(e,o=>{Ed.set(n,{worker:o,lastUsed:i}),t(o)})}function mhe(e){let t=new RegExp(`${e}:\\s*(.+)`,"i");return r.readsData=!0,r;function r(n,s){let i=new pd.Socket({handle:n,readable:!0,writable:!0});n._socket=i,i.on("data",o=>{n.readStop();let l=o.toString("latin1").match(t)?.[1],u=Ed.get(l),f=Date.now();if(u&&u.worker.threadId!==-1)return u.lastUsed=f,s(u.worker);cI(n,d=>{Ed.set(l,{worker:d,lastUsed:f}),s(d,o)})})}a(r,"findByHeaderAffinity")}function EK(){CS=0;for(let e of hd)e.expectedIdle=e.recentELU.idle+phe,e.requests=1;hd.sort((e,t)=>e.expectedIdle>t.expectedIdle?-1:1)}function ghe(e,t,r){let n=Ehe++;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(),PS.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")),PS.delete(n)),s.event=="destroy"&&(e.destroy(),PS.delete(n))})}var ys,pd,DS,LS,dK,fK,_K,hd,md,hK,lK,nI,mK,sI,fhe,oI,CS,uK,Ed,phe,PS,Ehe,lI=be(()=>{ys=M(tt()),pd=require("net");k();DS=M(j()),LS=require("fs");Ni();dK=require("worker_threads"),fK=M(Qu()),_K=M(mt()),hd=[],md=[],hK=[],nI=0,mK=[];dK.isMainThread&&(process.on("uncaughtException",e=>{e.code!=="ECONNRESET"&&e.message!=="write EIO"&&console.error("uncaughtException",e)}),(0,ys.onMessageFromWorkers)(e=>{e.type===oA.RESTART&&sI&&(clearInterval(sI),pK())}));fhe=6e5;a(_he,"startHTTPThreads");a(pK,"licenseWarning");a(iI,"startHTTPWorker");a(aI,"startSocketServer");CS=0;a(cI,"findMostIdleWorker");uK=36e5,Ed=new Map;a(hhe,"findByRemoteAddressAffinity");a(mhe,"makeFindByHeaderAffinity");setInterval(()=>{let e=Date.now();for(let[t,r]of Ed)r.lastUsed+uK<e&&Ed.delete(t)},uK).unref();phe=1e3;a(EK,"updateWorkerIdleness");(0,ys.setMonitorListener)(EK);PS=new Map,Ehe=1;a(ghe,"proxySocket")});var MK=P((QDe,LK)=>{var TK=M(require("cluster")),Ua=M(le());k();var Mi=M(j()),AK=M(require("fastify")),RK=M(require("@fastify/cors")),yK=M(require("@fastify/compress")),bK=M(require("@fastify/static")),OK=M(wb()),NK=M(require("path")),wK=M(mt()),IK=M(ks()),CK=M(ae()),PK=M(Fn()),DK=M(Qu());Pr();var xa=M(NS());Xi();Ua.default.initSync();var She=6e4,The=1024*1024*1024,Ahe="TRUE",{CONFIG_PARAMS:Dh}=$,gd;LK.exports={hdbServer:SK,start:SK};async function SK(e){try{Mi.default.debug("In Fastify server"+process.cwd()),Mi.default.debug(`Running with NODE_ENV set as: ${process.env.NODE_ENV}`),Mi.default.debug(`HarperDB server process ${process.pid} starting up.`),global.clustering_on=!1,global.isMaster=TK.default.isMaster,await Rhe();let t=e.securePort>0;gd=yhe(t),await gd.ready(),e||(e={}),e.isOperationsServer=!0;try{Ke.http(gd.server,e),gd.server.closeIdleConnections||await gd.listen({port:0,host:"::"})}catch(r){throw gd.close(),Mi.default.error(r),Mi.default.error("Error configuring operations server"),r}}catch(t){console.error(`Failed to build server on ${process.pid}`,t),Mi.default.fatal(t),process.exit(1)}}a(SK,"operationsServer");async function Rhe(){Mi.default.trace("Configuring HarperDB process."),IK.default.setSchemaDataToGlobal(),await PK.default.setUsersWithRolesCache(),await DK.default.getLicense()}a(Rhe,"setUp");function yhe(e){Mi.default.debug(`HarperDB process starting to build ${e?"HTTPS":"HTTP"} server.`);let t=bhe(e),r=(0,AK.default)(t);r.server.headersTimeout=Nhe(),r.setErrorHandler(xa.serverErrorHandler);let n=Ohe();n&&r.register(RK.default,n),r.register(function(i,o,c){i.setNotFoundHandler(function(l,u){r.server.emit("unhandled",l.raw,u.raw)}),c()}),r.register(OK.default),r.register(yK.default),r.register(bK.default,{root:NK.default.join(wK.PACKAGE_ROOT,"studio/build-local")}),mf(r);let s=Ua.default.get(nA.LOCAL_STUDIO_ON);return r.get("/",function(i,o){return!CK.default.isEmpty(s)&&s.toString().toLowerCase()==="true"?o.sendFile("index.html"):o.sendFile("running.html")}),r.post("/",{preValidation:[xa.reqBodyValidationHandler,xa.authHandler],config:{isOperation:!0}},async function(i,o){return i.body?.operation?.startsWith("restart")&&o.header("Connection","close"),(0,xa.handlePostRequest)(i,o)}),r.get("/health",()=>"HarperDB is running."),Mi.default.debug(`HarperDB process starting up ${e?"HTTPS":"HTTP"} server listener.`),r}a(yhe,"buildServer");function bhe(e){let t=Ua.default.get(Dh.OPERATIONSAPI_NETWORK_TIMEOUT),r=Ua.default.get(Dh.OPERATIONSAPI_NETWORK_KEEPALIVETIMEOUT);return{bodyLimit:The,connectionTimeout:t,keepAliveTimeout:r,forceCloseConnections:!0,return503OnClosing:!1,https:e}}a(bhe,"getServerOptions");function Ohe(){let e=Ua.default.get(Dh.OPERATIONSAPI_NETWORK_CORS),t=Ua.default.get(Dh.OPERATIONSAPI_NETWORK_CORSACCESSLIST),r;return e&&(e===!0||e.toUpperCase()===Ahe)&&(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}a(Ohe,"getCORSOpts");function Nhe(){return Ua.default.get(Dh.OPERATIONSAPI_NETWORK_HEADERSTIMEOUT)??She}a(Nhe,"getHeaderTimeoutConfig")});var pI={};Ue(pI,{disableNATS:()=>Ihe,publishToStream:()=>xS,setNATSReplicator:()=>dI,setPublishToStream:()=>Che,setSubscription:()=>mI,start:()=>whe});function whe(){Lh.default.get(U.CLUSTERING_ENABLED)&&Dhe()}function Ihe(e=!0){HK=e}function Che(e,t){xS=e,mI=t}function Dhe(){if(HK||process.env._DISABLE_NATS)return;let e=je(),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];dI(s,r,i)}}jc((r,n)=>{dI(r.tableName,r.databaseName,r),n&&FK(r)}),!vK&&(vK=!0)}function dI(e,t,r){if(t==="system"&&Lhe.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 qr{static{a(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){FK(i)}static subscribe(){let i=new Dn;return mI(t,e,i),i}static subscribeOnThisThread(i){return i<(Lh.default.get(U.CLUSTERING_LEAFSERVER_STREAMS_MAXINGESTTHREADS)??Phe)}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 vS(s.transaction,s);let o=s.transaction;for(;o.next;)o=o.next;o.next=s.transaction.nats,i.user=s.user,i.context=s}else i=kK;return i}a(n,"getNATSTransaction")}function FK(e){let t=Lh.default.get(U.CLUSTERING_NODENAME);xS(`${_I.SUBJECT_PREFIXES.TXN}.${e.databaseName}.${e.tableName}`,(0,hI.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 UK,_I,hI,xK,BK,Lh,US,HK,xS,mI,Phe,kK,vK,Lhe,vS,fI,GK=be(()=>{ve();Xo();UK=M(hr()),_I=M(wt()),hI=M(so());Gl();xK=M(Gb()),BK=M(an()),Lh=M(le());k();US=M(j());a(whe,"start");a(Ihe,"disableNATS");xS=UK.publishToStream,mI=xK.setSubscription;a(Che,"setPublishToStream");Phe=2;a(Dhe,"assignReplicationSource");Lhe=["hdb_job","hdb_analytics","hdb_raw_analytics","hdb_info","hdb_license"];a(dI,"setNATSReplicator");a(FK,"publishSchema");vS=class{constructor(t,r){this.transaction=t;this.options=r}static{a(this,"NATSTransaction")}user;writes_by_db=new Map;addWrite(t,r){r.expiresAt=this.context?.expiresAt;let n=this.writes_by_db.get(t);n||this.writes_by_db.set(t,n=[]),n.push(r)}commit({timestamp:t}){let r=Lh.default.get(U.CLUSTERING_NODENAME),n=[];for(let[s,i]of this.writes_by_db){let o=[],c=[],l,u;for(let f of i){let d=f.table,_=f.operation=="put"?"upsert":f.operation;l||(US.trace(`Sending transaction event ${_}`),u=l={operation:_,schema:s,table:d,__origin:{user:this.user?.username,timestamp:t,node_name:r}},l.hash_values=c,_!=="delete"&&_!=="invalidate"&&(l.records=o)),l.table===d&&l.operation===_?(o.push(f.record),c.push(f.id)):u=u.next={operation:_,table:d,id:f.id,record:f.record},f.expiresAt&&(u.expiresAt=f.expiresAt)}l&&n.push(xS(`${_I.SUBJECT_PREFIXES.TXN}.${s}.${l.table}`,(0,hI.createNatsTableStreamName)(s,l.table),void 0,l)?.catch(f=>{throw US.error("An error has occurred trying to replicate transaction",l,f),f.statusCode=504,f}))}return Promise.all(n)}},fI=class extends vS{static{a(this,"ImmmediateNATSTransaction")}constructor(){super({get timestamp(){return(0,BK.getNextMonotonicTime)()}})}addWrite(t,r){super.addWrite(t,r),this.commit({})}};kK=new fI});async function YK({clientId:e,user:t,clean:r,will:n,keepalive:s}){let i;if(e&&!r){let o=await EI.get(e,{returnNonexistent:!0});i=new TI(e,t,o),o&&(i.sessionWasPresent=!0)}else{if(e){let o=await EI.get(e);o&&o.delete()}i=new HS(e,t)}return n&&(n.id=e,n.user={username:t?.username},Mh.put(n)),s&&(i.keepalive=s,i.receivedPacket()),i}function gI(){return BS++,BS>65500&&(BS=1),BS}function SI(e,t,r){let{topic:n,retain:s}=e;e.data=t,e.async=!0,r.authorize=!0;let i=as.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 o=i.Resource;return Ot(r,()=>s?t===void 0?o.delete(e,r):o.put(e,e.data,r):o.publish(e,e.data,r))}var $K,Ba,VK,KK,qK,EI,Mh,BS,HS,TI,WK=be(()=>{ve();zl();$K=M(an()),Ba=M(j());sc();VK=M(tt()),KK=M(uI());Pr();qK=100,EI=ut({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"}]}}]}),Mh=ut({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,VK.getWorkerIndex)()===0&&(async()=>{await KK.when_components_loaded,await new Promise(e=>setTimeout(e,2e3));for await(let e of Mh.search({})){let t=e.data,r={...e};r.user?.username&&(r.user=await Ke.getUser(r.user.username));try{await SI(r,t,r)}catch{(0,Ba.warn)("Failed to publish will",t)}Mh.delete(e.id)}})();a(YK,"getSession");BS=1;a(gI,"getNextMessageId");HS=class{static{a(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:o}=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 f=this.subscriptions.find(R=>R.topic===s),d;f?(d=i>0,f.end(),this.subscriptions.splice(this.subscriptions.indexOf(f),1)):d=i===2;let _={search:l,async:!0,user:this.user,startTime:o,omitCurrent:d,url:""};o&&(0,Ba.trace)("Resuming subscription from",s,"from",o);let h=as.getMatch(u,"mqtt");if(!h){let R=new Error(`The topic ${s} does not exist, no resource has been defined to handle this topic`);throw R.statusCode=404,R}if(_.url=h.relativeURL,_.url.indexOf("+")>-1||_.url.indexOf("#")>-1){let R=_.url.slice(1);if(R.indexOf("#")>-1&&R.indexOf("#")!==R.length-1)throw new Error("Multi-level wildcards can only be used at the end of a topic");if(_.isCollection=!0,R.indexOf("+")===R.length-1)_.onlyChildren=!0,_.url="/"+R.slice(0,R.length-1);else{let E=R.split("/"),T;for(let H=0;H<E.length;H++)if(E[H].indexOf("+")>-1)if(E[H]==="+")T=!0;else throw new Error("Single-level wildcards can only be used as a topic level (between or after slashes)");if(n&&T)throw new Error("Filters can not be combined");let w=!0;E[E.length-1]==="#"&&(E.length--,w=!1),T&&(n=a(H=>{let q=H.id;if(!Array.isArray(q))if(q?.indexOf?.("/")>-1)q=q.split("/");else return!1;if(w&&q.length!==E.length)return!1;for(let W=0;W<E.length;W++)if(E[W]!=="+"&&E[W]!==q[W])return!1;return!0},"filter"));let v=E.indexOf("+");_.url="/"+(v>-1?E.slice(0,v):E).concat("").join("/")}}else _.isCollection=!1;let m=h.path,S=h.Resource,g=await Ot(_,async()=>{let R=this.createContext();R.topic=s,R.retainHandling=i,R.isCollection=_.isCollection;let E=await S.subscribe(_,R);if(!E)return;if(!E[Symbol.asyncIterator])throw new Error(`Subscription is not (async) iterable for topic ${s}`);let T=(async()=>{for await(let w of E)try{let v;if(w.type&&w.type!=="put"&&w.type!=="delete"&&w.type!=="message"&&w.type!=="patch"||n&&!n(w))continue;r?(w.topic=s,v=this.needsAcknowledge(w)):(w.acknowledge?.(),v=gI());let H=w.id;if(Array.isArray(H)&&(H=Wl(H)),H==null&&(H=""),await this.listener(m+"/"+H,w.value,v,t)===!1)break;this.awaitingAcks?.size>qK?await new Promise(W=>setTimeout(W,this.awaitingAcks.size-qK)):await new Promise(setImmediate)}catch(v){(0,Ba.warn)(v)}})();return E});if(g)return g.topic=s,g.qos=t.qos,this.subscriptions.push(g),g}resume(){}needsAcknowledge(t){let r=gI();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 SI(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();Ot(r,async()=>{try{if(!t){let n=await Mh.get(this.sessionId);n?.doesExist()&&await SI(n,n.data,r)}}finally{await Mh.delete(this.sessionId)}}).catch(n=>{(0,Ba.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))}};a(SI,"publish");TI=class extends HS{static{a(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=gI(),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,Ba.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,$K.getNextMonotonicTime)()),(0,Ba.trace)("Added durable subscription",t.topic,r),{qos:t.qos,topic:t.topic,startTime:r}}),EI.put(this.sessionRecord)}}});var RI={};Ue(RI,{bypassAuth:()=>Mhe,start:()=>vhe});function Mhe(){XK=!0}function vhe({server:e,port:t,network:r,webSocket:n,securePort:s,requireAuthentication:i}){e.mqtt||(e.mqtt={requireAuthentication:i,sessions:new Set,events:new JK.EventEmitter},e.mqtt.events.on("error",()=>{}));let o=e.mqtt,c=[],l=r?.mtls;return n&&(c=e.ws((u,f,d,_)=>{if(f.headers.get("sec-websocket-protocol")!=="mqtt")return _(u,f,d);o.events.emit("connection",u),cr.debug?.("Received WebSocket connection for MQTT from",u._socket.remoteAddress);let{onMessage:h,onClose:m}=QK(u,S=>{u.send(S)},f,Promise.resolve(d).then(()=>f?.user),o);u.on("message",h),u.on("close",m),u.on("error",S=>{cr.info?.("WebSocket error",S)})},{...n})),(t||s)&&c.push(e.socket(async u=>{let f;if(o.events.emit("connection",u),cr.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{f=await e.getUser(h,null,null),(0,Sd.get)(U.LOGGING_AUDITAUTHEVENTS_LOGSUCCESSFUL)&&FS.notify?.({username:f?.username,status:Ms.SUCCESS,type:Ko.AUTHENTICATION,auth_strategy:"MQTT mTLS",remote_address:u.remoteAddress})}catch(m){throw(0,Sd.get)(U.LOGGING_AUDITAUTHEVENTS_LOGFAILED)&&FS.error?.({username:h,status:Ms.FAILURE,type:Ko.AUTHENTICATION,auth_strategy:"mqtt",remote_address:u.remoteAddress}),m}}else cr.debug?.("MQTT mTLS authorized connection (mTLS did not authorize a user)","from",u.remoteAddress)}catch(h){o.events.emit("error",h,u),cr.error?.(h)}else if(l.required)return cr.info?.(`Unauthorized connection attempt, no authorized client certificate provided, error: ${u.authorizationError}`),u.end()}!f&&XK&&u.remoteAddress.includes("127.0.0.1")&&(f=await(0,jK.getSuperUser)(),cr.debug?.("Auto-authorizing local connection",f?.username));let{onMessage:d,onClose:_}=QK(u,h=>u.write(h),null,f,o);u.on("data",d),u.on("close",_),u.on("error",h=>{cr.info?.("Socket error",h)})},{port:t,securePort:s,mtls:l})),c}function QK(e,t,r,n,s){zK||(zK=!0,d_(d=>{kS>0&&d.push({metric:"mqtt-connections",connections:kS,byThread:!0})}));let i;kS++;let o,c={protocolVersion:4},l=(0,GS.parser)({protocolVersion:5});function u(d){l.parse(d)}a(u,"onMessage");function f(){kS--,i||(i=!0,o?.disconnect?.(),s.events.emit("disconnected",o,e),s.sessions.delete(o),Kn(!1,"connection","mqtt","disconnect"),cr.debug?.("MQTT connection was closed",e.remoteAddress))}return a(f,"onClose"),l.on("packet",async d=>{n?.then&&(n=await n);let _=d.cmd;if(o)o.then&&await o;else if(_!=="connect"){cr.info?.("Received packet before connection was established, closing connection"),e?.destroy?e.destroy():e?.terminate();return}let h=d.topic,m=h?.indexOf("/",1),S=m>0?h.slice(0,m):h;er(d.length,"bytes-received",S,R(d),"mqtt");try{switch(o?.receivedPacket?.(),_){case"connect":if(c.protocolVersion=d.protocolVersion,d.username)try{n=await Ke.getUser(d.username,d.password.toString(),r),(0,Sd.get)(U.LOGGING_AUDITAUTHEVENTS_LOGSUCCESSFUL)&&FS.notify?.({username:n?.username,status:Ms.SUCCESS,type:Ko.AUTHENTICATION,auth_strategy:"MQTT",remote_address:e.remoteAddress})}catch(se){return(0,Sd.get)(U.LOGGING_AUDITAUTHEVENTS_LOGFAILED)&&FS.error?.({username:d.username,status:Ms.FAILURE,type:Ko.AUTHENTICATION,auth_strategy:"mqtt",remote_address:e.remoteAddress}),s.events.emit("auth-failed",d,e,se),Kn(!1,"connection","mqtt","connect"),g({cmd:"connack",reasonCode:4,returnCode:134})}if(!n&&s.requireAuthentication)return s.events.emit("auth-failed",d,e),Kn(!1,"connection","mqtt","connect"),g({cmd:"connack",reasonCode:4,returnCode:134});try{if(s.authorizeClient?.(d,n),d.will){let se=e.deserialize||(e.deserialize=Ji(r?.headers.get?.("content-type")));d.will.data=d.will.payload?.length>0?se(d.will.payload):void 0,delete d.will.payload}o=YK({user:n,...d}),o=await o,o.socket=e,r&&(o.request=r),s.sessions.add(o)}catch(se){return cr.error?.(se),s.events.emit("auth-failed",d,e,se),Kn(!1,"connection","mqtt","connect"),g({cmd:"connack",reasonCode:se.code||5,returnCode:se.code||128})}s.events.emit("connected",o,e),Kn(!0,"connection","mqtt","connect"),g({cmd:"connack",sessionPresent:o.sessionWasPresent,reasonCode:0,returnCode:0});let T=a(async(se,Y,ne,ue)=>{try{if(i)throw new Error("Session disconnected while trying to send message to",se);let oe=se.indexOf("/",1),pe=oe>0?se.slice(0,oe):se;g({cmd:"publish",topic:se,payload:await E(Y),messageId:ne||Math.floor(Math.random()*1e8),qos:ue.qos},pe);let Te=e._socket??e;return Te.writableNeedDrain?new Promise(ye=>Te.once("drain",ye)):!Te.closed}catch(oe){return cr.error?.(oe),o?.disconnect(),s.sessions.delete(o),!1}},"listener");o.setListener(T),o.sessionWasPresent&&await o.resume();break;case"subscribe":let w=[];for(let se of d.subscriptions){let Y;try{let ne=await o.addSubscription(se,se.qos>=1);Y=ne?ne.qos||0:c.protocolVersion<5?128:143}catch(ne){s.events.emit("error",ne,e,se,o),ne.statusCode?ne.statusCode===500?cr.warn?.(ne):cr.info?.(ne):cr.error?.(ne),Y=c.protocolVersion<5?128:ne.statusCode===403?135:ne.statusCode===404?143:128}w.push(Y)}await o.committed,g({cmd:"suback",granted:w,messageId:d.messageId});break;case"unsubscribe":{let se=[];for(let Y of d.unsubscriptions)se.push(o.removeSubscription(Y)?0:17);g({cmd:"unsuback",granted:se,messageId:d.messageId});break}case"pubrel":g({cmd:"pubcomp",messageId:d.messageId,reasonCode:0});return;case"publish":let v=d.qos===2?"pubrec":"puback",H=e.deserialize||(e.deserialize=Ji(r?.headers.get?.("content-type"))),W=(d.payload?.length||0)>0?H(d.payload):void 0,te;try{te=await o.publish(d,W)}catch(se){s.events.emit("error",se,e,d,o),cr.warn?.(se),d.qos>0&&g({cmd:v,messageId:d.messageId,reasonCode:128},d.topic);break}d.qos>0&&g({cmd:v,messageId:d.messageId,reasonCode:te===!1?144:0},d.topic);break;case"pubrec":g({cmd:"pubrel",messageId:d.messageId,reasonCode:0});break;case"pubcomp":case"puback":o.acknowledge(d.messageId);break;case"pingreq":g({cmd:"pingresp"});break;case"disconnect":i=!0,o?.disconnect(!0),s.events.emit("disconnected",o,e),s.sessions.delete(o),Kn(!0,"connection","mqtt","disconnect"),cr.debug?.("Received disconnect command, closing MQTT session",e.remoteAddress),e.close?e.close():e.end();break}}catch(T){s.events.emit("error",T,e,d,o),cr.error?.(T),g({cmd:"disconnect"})}function g(T,w){let v=(0,GS.generate)(T,c);t(v),er(v.length,"bytes-sent",w,R(T),"mqtt")}a(g,"sendPacket");function R(T){return T.qos>0?T.cmd+",qos="+T.qos:T.cmd}a(R,"packetMethodName");function E(T){return ea(T,r)}a(E,"serialize")}),l.on("error",d=>{cr.warn("MQTT parsing error, closing connection:",d.message),e?.destroy?e.destroy():e?.terminate()}),{onMessage:u,onClose:f}}var GS,jK,Sd,AI,JK,FS,cr,XK,zK,kS,ZK=be(()=>{GS=require("mqtt-packet");WK();jK=M(Fn());Xi();Ni();Pr();Sd=M(le());k();AI=M(_i()),JK=require("events"),FS=(0,AI.loggerWithTag)("auth-event"),cr=(0,AI.loggerWithTag)("mqtt"),XK=(0,Sd.get)(U.AUTHENTICATION_AUTHORIZELOCAL)??process.env.DEV_MODE;a(Mhe,"bypassAuth");a(vhe,"start");kS=0;a(QK,"onSocket")});var mh={};Ue(mh,{component_errors:()=>Ad,getComponentName:()=>khe,loadComponent:()=>VS,loadComponentDirectories:()=>sY,setErrorReporter:()=>Hhe});function sY(e,t){t&&(bI=t),e&&(wI=e);let r=[];if((0,ct.existsSync)(yI)){let s=(0,ct.readdirSync)(yI,{withFileTypes:!0});for(let i of s){if(!i.isDirectory()&&!i.isSymbolicLink())continue;let o=i.name,c=(0,gt.join)(yI,o);r.push(VS(c,bI,ZT,!1))}}let n=process.env.RUN_HDB_APP;return n&&r.push(VS(n,bI,n,!1,null,!!process.env.DEV_MODE)),Promise.all(r).then(()=>{nY=!0})}function Hhe(e){vh=e}function Fhe(e,t){return new Promise((r,n)=>{let s=je().system.hdb_info;if(!s)return r();let i=setTimeout(()=>{s.primaryStore.unlock(e,0),n(new Error("symlinking harperdb module timed out"))},1e4);if(s.primaryStore.attemptLock(e,0,()=>{clearTimeout(i),r()}))try{(0,ct.rmSync)(t,{recursive:!0,force:!0}),(0,ct.existsSync)((0,gt.join)(e,"node_modules"))||(0,ct.mkdirSync)((0,gt.join)(e,"node_modules")),(0,ct.symlinkSync)(PI.PACKAGE_ROOT,t,"dir"),r()}finally{s.primaryStore.unlock(e,0)}})}async function VS(e,t,r,n,s,i){let o=(0,ct.realpathSync)(e);if(qS.has(o))return qS.get(o);qS.set(o,!0),s&&(wI=s);try{let c;n&&(Ad=new Map);let l=(0,gt.join)(e,"harperdb-config.yaml");(0,ct.existsSync)(l)?c=n?(0,KS.getConfigObj)():(0,OI.parseDocument)((0,ct.readFileSync)(l,"utf8")).toJSON():!n&&(0,ct.existsSync)(l=(0,gt.join)(e,"config.yaml"))?c=(0,OI.parseDocument)((0,ct.readFileSync)(l,"utf8")).toJSON():c=II;try{let d=(0,gt.join)(e,"node_modules","harperdb");(n||((0,ct.existsSync)(d)||!e.startsWith((0,NI.getHdbBasePath)()))&&(!(0,ct.existsSync)(d)||(0,ct.realpathSync)(PI.PACKAGE_ROOT)!==(0,ct.realpathSync)(d)))&&await Fhe(e,d)}catch(d){El.default.error("Error symlinking harperdb module",d),d.code=="EPERM"&&process.platform==="win32"&&El.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=$S,f=n;for(let d in c){$S=d;let _=c[d];if(Ad.set(n?d:(0,gt.basename)(e),!1),!_)continue;let h,m=_.package;try{if(m){let T=e,w;for(;!(0,ct.existsSync)(w=(0,gt.join)(T,"node_modules",d));)if(T=(0,gt.dirname)(T),T.length<(0,NI.getHdbBasePath)().length){w=null;break}if(w)h=await VS(w,t,r,!1),f=!0;else throw new Error(`Unable to find package ${d}:${m}`)}else h=Bhe[d];if(!h)continue;let S=a(T=>(T.origin=r,ut(T)),"ensureTable"),g=_.network||(_.port||_.securePort)&&_,R=g?.securePort||g?.https&&g.port,E=!g?.https&&g?.port;if(Td.isMainThread&&(h=await h.startOnMainThread?.({server:Ke,ensureTable:S,port:E,securePort:R,resources:t,..._})||h,n&&g))for(let T of[E,R])try{if(+T&&!eY.includes(T)){let w=CI.get(U.HTTP_SESSIONAFFINITY);w&&El.default.warn("Session affinity is not recommended and may cause memory leaks"),(w||!cE)&&(eY.push(T),aI(T,w))}}catch(w){console.error("Error listening on socket",T,w,d)}if(t.isWorker&&(h=await h.start?.({server:Ke,ensureTable:S,port:E,securePort:R,resources:t,..._})||h),wI.set(h,!0),(h.handleFile||h.handleDirectory||h.setupFile||h.setupDirectory)&&_.files!=null){if(_.files.includes(".."))throw(0,rY.handleHDBError)("Can not reference parent directories");let T=(0,gt.join)(e,_.files).replace(/\\/g,"/"),w=T.indexOf("/*");if(w>-1&&_.files!==II[d]?.files&&!(0,ct.existsSync)(T.slice(0,w)))throw new Error(`The path '${T.slice(0,w)}' does not exist and cannot be used as the base of the resolved 'files' path value '${_.files}'`);let v=(0,gt.basename)(e),H=_.path||"/";H=H.startsWith("/")?H:H.startsWith("./")?"/"+v+H.slice(2):H==="."?"/"+v:"/"+v+"/"+H;let q,W,te;if(_.root){let Y=_.root;Y.startsWith("/")&&(Y=Y.slice(1)),Y.endsWith("/")&&(Y=Y.slice(0,-1)),Y+="/",W=(0,gt.join)(e,Y)}else(te=T.indexOf("/*"))>-1?(W=T.slice(0,te+1),q=(0,gt.relative)(e,W)):_.files.indexOf("/")>-1&&(W=T.slice(0,T.lastIndexOf("/")+1),q=(0,gt.relative)(e,W));let se=!1;if(Td.isMainThread&&h.setupDirectory&&(se=await h.setupDirectory?.(H,W,t)),t.isWorker&&h.handleDirectory&&(se=await h.handleDirectory?.(H,W,t)),se){f=!0;continue}for(let Y of await(0,tY.default)(T,{onlyFiles:!1,objectMode:!0})){let{path:ne,dirent:ue}=Y;f=!0;let oe=(0,gt.relative)(e,ne).replace(/\\/g,"/");if(q)if(oe.startsWith(q))oe=oe.slice(q.length+1);else throw new Error(`The root path '${_.root}' does not reference a valid part of the file path '${oe}'.The root path should be used to indicate the relative path/part of the file path for determining the exported web path.`);let pe=H+(H.endsWith("/")?"":"/")+oe;try{if(ue.isFile()){let Te=await xhe(ne);Td.isMainThread&&await h.setupFile?.(Te,pe,ne,t),t.isWorker&&await h.handleFile?.(Te,pe,ne,t)}else Td.isMainThread&&await h.setupDirectory?.(pe,ne,t),t.isWorker&&await h.handleDirectory?.(pe,ne,t)}catch(Te){let ye=`Could not load ${ue.isFile()?"file":"directory"} '${ne}'${_.module?` using '${_.module}'`:""} for application '${e}' due to:
|
|
39
|
-
`;Te.message=`${ye}${Te.message}`,Te.stack=`${ye}${Te.stack}`,vh?.(Te),El.default.error(Te),t.set(_.path||"/",new Zo(Te)),Ad.set(n?d:(0,gt.basename)(e),Te.message)}}}}catch(S){S.message=`Could not load component '${d}' for application '${(0,gt.basename)(e)}' due to: ${S.message}`,vh?.(S),((0,Uh.getWorkerIndex)()===0?console:El.default).error(S),t.set(_.path||"/",new Zo(S),null,!0),Ad.set(n?d:(0,gt.basename)(e),S.message)}}if($S=u,Td.isMainThread&&!nY&&i&&(0,Uh.watchDir)(e,async()=>sY()),c.extensionModule){let d=await nE((0,gt.join)(e,c.extensionModule));return qS.set(o,d),d}if(!f&&t.isWorker){let d=`${e} did not load any modules, resources, or files, is this a valid component?`;vh?.(new Error(d)),((0,Uh.getWorkerIndex)()===0?console:El.default).error(d),Ad.set((0,gt.basename)(e),d)}}catch(c){console.error(`Could not load application directory ${e}`,c),c.message=`Could not load application due to ${c.message}`,vh?.(c),t.set("",new Zo(c))}}var ct,gt,Td,OI,CI,PI,tY,Uh,El,rY,NI,Uhe,KS,xhe,yI,wI,nY,bI,Ad,Bhe,II,eY,qS,vh,$S,khe,ph=be(()=>{ct=require("fs"),gt=require("path"),Td=require("worker_threads"),OI=require("yaml"),CI=M(le()),PI=M(mt());k();PD();tL();Px();vx();Ux();SB();eK();oK();cK();tY=M(require("fast-glob")),Uh=M(tt()),El=M(j());lb();Pr();rY=M(me());ve();lI();NI=M(le()),Uhe=M(MK());Kg();GK();fs();ZK();KS=M(Ct());lE();wA();({readFile:xhe}=ct.promises),yI=(0,KS.resolvePath)(CI.get(U.COMPONENTSROOT)),wI=new Map,Ad=new Map;a(sY,"loadComponentDirectories");Bhe={REST:dE,rest:dE,graphql:GA,graphqlSchema:PA,roles:cb,jsResource:db,fastifyRoutes:eI,login:_b,static:tI,operationsApi:Uhe,customFunctions:{},http:{},clustering:pI,replication:ga,authentication:ch,mqtt:RI,loadEnv:rI},II={rest:!0,graphqlSchema:{files:"*.graphql"},roles:{files:"roles.yaml"},jsResource:{files:"resources.js"},fastifyRoutes:{files:"routes/*.js",path:"."}};Object.defineProperty(II,"static",{value:{files:"web/**"}});eY=[],qS=new Map;a(Hhe,"setErrorReporter");khe=a(()=>$S,"getComponentName");a(Fhe,"symlinkHarperModule");a(VS,"loadComponent")});var MS=P((OLe,oY)=>{var{isMainThread:iY}=require("worker_threads"),{getTables:Ghe,getDatabases:yLe,table:bLe}=(ve(),D(it)),{loadComponentDirectories:qhe,loadComponent:$he}=(ph(),D(mh)),{resetResources:Vhe}=(zl(),D(wD)),Khe=XN(),Yhe=Ct(),{dirname:Whe}=require("path"),{getConnection:zhe}=hr(),Qhe=le(),{CONFIG_PARAMS:jhe}=(k(),D($)),{loadCertificates:Jhe}=js(),DI=new Map;async function Xhe(e=!1){!iY&&Qhe.get(jhe.CLUSTERING_ENABLED)&&zhe();try{iY&&await Khe()}catch(n){console.error(n)}let t=Vhe();Ghe(),t.isWorker=e,await Jhe(),await $he(Whe(Yhe.getConfigFilePath()),t,"hdb",!0,DI),await qhe(DI,t);let r=[];for(let[n]of DI)n.ready&&r.push(n.ready());r.length>0&&await Promise.all(r)}a(Xhe,"loadRootComponents");oY.exports.loadRootComponents=Xhe});var tt=P((wLe,si)=>{"use strict";JT();var{Worker:Zhe,MessageChannel:eme,parentPort:vi,isMainThread:xI,threadId:tme,workerData:Ui}=require("worker_threads"),{PACKAGE_ROOT:rme}=mt(),{join:uY,isAbsolute:nme,extname:sme}=require("path"),{server:dY}=(Pr(),D(Yl)),{watch:ime,readdir:ome}=require("fs/promises"),{totalmem:aY}=require("os"),Rd=(k(),D($)),fY=le(),ni=j(),{randomBytes:ame}=require("crypto"),{_assignPackageExport:cme}=ci(),cY=1024*1024,Ha=[],bs=[],lme=50,BI=1e4,ume="restart",_Y="request_thread_info",hY="resource_report",mY="thread_info",pY="added-port",dme="ack",LI;cme("threads",bs);si.exports={startWorker:MI,restartWorkers:kI,shutdownWorkers:pme,workers:Ha,setMonitorListener:bme,onMessageFromWorkers:Eme,onMessageByType:yY,broadcast:Sme,broadcastWithAcknowledgement:Ame,setChildListenerByType:mme,getWorkerIndex:EY,getWorkerCount:gY,getTicketKeys:TY,setMainIsWorker:_me,setTerminateTimeout:fme,restartNumber:Ui?.restartNumber||1};bs.onMessageByType=yY;bs.sendToThread=function(e,t){if(!t?.type)throw new Error("A message with a type must be provided");let r=bs.find(n=>n.threadId===e);if(r)return r.postMessage(t),!0};si.exports.whenThreadsStarted=new Promise(e=>{si.exports.threadsHaveStarted=e});var HI;function fme(e){BI=e}a(fme,"setTerminateTimeout");function EY(){return Ui?Ui.workerIndex:HI?0:void 0}a(EY,"getWorkerIndex");function gY(){return Ui?Ui.workerCount:HI?1:void 0}a(gY,"getWorkerCount");function _me(e){HI=e,si.exports.threadsHaveStarted()}a(_me,"setMainIsWorker");var SY=1,YS;function TY(){return YS||(YS=xI?ame(48):Ui.ticketKeys,YS)}a(TY,"getTicketKeys");Object.defineProperty(dY,"workerIndex",{get(){return EY()}});Object.defineProperty(dY,"workerCount",{get(){return gY()}});var AY={[_Y](e,t){Rme(t)},[hY](e,t){yme(t,e)}};function MI(e,t={}){let r=process.constrainedMemory?.()||aY();r=Math.min(r,aY(),2e4*cY);let n=fY.get(Rd.CONFIG_PARAMS.THREADS_MAXHEAPMEMORY)??Math.max(Math.floor(r/cY/(10+(t.threadCount||1)/4)),512),s=Math.min(Math.max(n>>6,16),64),i=[],o=[];for(let l of bs){let u=new eme;u.existingPort=l,i.push(u),o.push(u.port2)}sme(e)||(e+=".js");let c=new Zhe(nme(e)?e:uY(rme,e),{resourceLimits:{maxOldGenerationSizeMb:n,maxYoungGenerationSizeMb:s},execArgv:["--enable-source-maps","--expose-internals"],argv:process.argv.slice(2),workerData:{addPorts:o,addThreadIds:i.map(l=>l.existingPort.threadId),workerIndex:t.workerIndex,workerCount:SY=t.threadCount,name:t.name,restartNumber:si.exports.restartNumber,ticketKeys:TY()},transferList:o,...t});for(let{port1:l,existingPort:u}of i)u.postMessage({type:pY,port:l,threadId:c.threadId},[l]);return zS(c,!0),c.unexpectedRestarts=t.unexpectedRestarts||0,c.startCopy=()=>MI(e,t),c.on("error",l=>{ni.error(`Worker index ${t.workerIndex} error:`,l)}),c.on("exit",l=>{Ha.splice(Ha.indexOf(c),1),!c.wasShutdown&&t.autoRestart!==!1&&(c.unexpectedRestarts<lme?(t.unexpectedRestarts=c.unexpectedRestarts+1,MI(e,t)):ni.error(`Thread has been restarted ${c.restarts} times and will not be restarted`))}),c.on("message",l=>{AY[l.type]?.(l,c)}),Ha.push(c),Nme(),t.onStarted&&t.onStarted(c),c.name=t.name,c}a(MI,"startWorker");var hme=[Rd.THREAD_TYPES.HTTP];async function kI(e=null,t=Math.max(SY>3,1),r=!0){if(xI){try{process.chdir(process.cwd())}catch(o){ni.error("Unable to reestablish current working directory",o)}if(r){let{loadRootComponents:o}=MS();await o()}si.exports.restartNumber++,t<1&&(t=t*Ha.length);let n=[],s=[];for(let o of Ha.slice(0)){if(e&&o.name!==e||o.wasShutdown)continue;ni.trace("sending shutdown request to ",o.threadId),o.postMessage({restartNumber:si.exports.restartNumber,type:Rd.ITC_EVENT_TYPES.SHUTDOWN}),o.wasShutdown=!0,o.emit("shutdown",{});let c=hme.indexOf(o.name)>-1,l=new Promise(u=>{let f=setTimeout(()=>{ni.warn("Thread did not voluntarily terminate, terminating from the outside",o.threadId),o.terminate()},BI*2).unref();o.on("exit",()=>{clearTimeout(f),n.splice(n.indexOf(l)),!c&&r&&o.startCopy(),u()})});if(n.push(l),c&&r){let u=o.startCopy(),f=new Promise(d=>{let _=a(h=>{h.type===Rd.ITC_EVENT_TYPES.CHILD_STARTED&&(ni.trace("Worker has started",u.threadId),d(),s.splice(s.indexOf(f)),u.off("message",_))},"startListener");ni.trace("Waiting for worker to start",u.threadId),u.on("message",_)});s.push(f),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}=rd();r&&(e==="http"||!e)&&fY.get(Rd.CONFIG_PARAMS.CLUSTERING_ENABLED)&&await i({service:"clustering"})}else vi.postMessage({type:ume,workerType:e})}a(kI,"restartWorkers");function mme(e,t){AY[e]=t}a(mme,"setChildListenerByType");function pme(e){return kI(e,1/0,!1)}a(pme,"shutdownWorkers");var RY=[];function Eme(e){RY.push(e)}a(Eme,"onMessageFromWorkers");var vI=new Map;function yY(e,t){let r=vI.get(e);r||vI.set(e,r=[]),r.push(t)}a(yY,"onMessageByType");var gme=10;async function Sme(e,t){let r=0;for(let n of bs)try{n.postMessage(e),r++>gme&&(r=0,await new Promise(setImmediate))}catch(s){ni.error("Unable to send message to worker",s)}t&&OY(e,null)}a(Sme,"broadcast");var WS=new Map,Tme=1;function Ame(e){return new Promise(t=>{let r=0;for(let n of bs)try{let s=Tme++,i=a(()=>{WS.delete(s),--r===0&&t(),n!==vi&&--n.refCount===0&&n.unref()},"ack_handler");i.port=n,n.ref(),n.refCount=(n.refCount||0)+1,WS.set(e.requestId=s,i),n.hasAckCloseListener||(n.hasAckCloseListener=!0,n.on(n.close?"close":"exit",()=>{for(let[,o]of WS)o.port===n&&o()})),n.postMessage(e),r++}catch(s){ni.error("Unable to send message to worker",s)}r===0&&t()})}a(Ame,"broadcastWithAcknowledgement");function Rme(e){e.postMessage({type:mY,workers:bY()})}a(Rme,"sendThreadInfo");function bY(){let e=Date.now();return Ha.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}))}a(bY,"getChildWorkerInfo");function yme(e,t){e.resources=t,e.resources.updated=Date.now()}a(yme,"recordResourceReport");var UI;function bme(e){UI=e}a(bme,"setMonitorListener");var Ome=1e3,lY=!1;function Nme(){lY||(lY=!0,setInterval(()=>{for(let e of Ha){let t=e.performance.eventLoopUtilization(),r;e.lastTotalELU?r=e.performance.eventLoopUtilization(t,e.lastTotalELU):r=t,e.lastTotalELU=t,e.recentELU=r}UI&&UI()},Ome).unref())}a(Nme,"startMonitoring");var wme=1e3;if(vi&&Ui?.addPorts){zS(vi);for(let e=0,t=Ui.addPorts.length;e<t;e++){let r=Ui.addPorts[e];r.threadId=Ui.addThreadIds[e],zS(r)}setInterval(()=>{let e=process.memoryUsage();vi.postMessage({type:hY,heapTotal:e.heapTotal,heapUsed:e.heapUsed,external:e.external,arrayBuffers:e.arrayBuffers})},wme).unref(),LI=a(()=>new Promise((e,t)=>{vi.on("message",r),vi.postMessage({type:_Y});function r(n){n.type===mY&&(vi.off("message",r),e(n.workers))}a(r,"receiveThreadInfo")}),"getThreadInfo")}else LI=bY;si.exports.getThreadInfo=LI;function zS(e,t){bs.push(e),e.on("message",r=>{if(r.type===pY)r.port.threadId=r.threadId,zS(r.port);else if(r.type===dme){let n=WS.get(r.id);n&&n()}else OY(r,e)}).on("close",()=>{bs.splice(bs.indexOf(e),1)}).on("exit",()=>{bs.splice(bs.indexOf(e),1)}),t?e.refCount=100:e.unref()}a(zS,"addPort");function OY(e,t){for(let n of RY)n(e,t);let r=vI.get(e.type);if(r)for(let n of r)try{n(e,t)}catch(s){ni.error(s)}}a(OY,"notifyMessageListeners");if(xI){let e,t,r=new Set,n=a(async(s,i)=>{i&&(e=i);for(let o of await ome(s,{withFileTypes:!0}))o.isDirectory()&&o.name!=="node_modules"&&n(uY(s,o.name));try{for await(let{filename:o}of ime(s,{persistent:!1}))r.add(o),t&&clearTimeout(t),t=setTimeout(async()=>{e&&await e(),await kI(),console.log("Reloaded HarperDB components, changed files:",Array.from(r)),r.clear()},100)}catch(o){console.warn("Error trying to watch component directory",s,o)}},"watch_dir");si.exports.watchDir=n,process.env.WATCH_DIR&&n(process.env.WATCH_DIR)}else vi.on("message",async e=>{let{type:t}=e;t===Rd.ITC_EVENT_TYPES.SHUTDOWN&&(si.exports.restartNumber=e.restartNumber,vi.unref(),setTimeout(()=>{ni.warn("Thread did not voluntarily terminate",tme),process.exit(0)},BI).unref())})});var PY={};Ue(PY,{onStorageReclamation:()=>xh,runReclamationHandlers:()=>$I,setAvailableSpaceRatioGetter:()=>Cme});function xh(e,t,r){(r||(0,jS.getWorkerIndex)()===(0,jS.getWorkerCount)()-1)&&(QS.has(e)||QS.set(e,[]),QS.get(e).push({priority:0,handler:t}),qI||(qI=setTimeout($I,wY).unref()))}async function $I(){for(let[e,t]of QS)try{let r=await CY(e),n=Ime/r;for(let s of t){let{priority:i,handler:o}=s;if(s.priority=n,n>1||i>1){let c=o(n>1?n:0);c&&(GI.default.info?.(`Running storage reclamation handler for ${e} with priority ${n}`),await c)}}}catch(r){GI.default.error?.("Error running storage reclamation handlers",r)}qI=setTimeout($I,wY).unref()}function Cme(e){CY=e??IY}var FI,jS,GI,JS,NY,QS,Ime,wY,qI,IY,CY,XS=be(()=>{FI=require("node:fs/promises"),jS=M(tt()),GI=M(_i());k();JS=M(le()),NY=M(ae());JS.default.initSync();QS=new Map,Ime=JS.default.get(U.STORAGE_RECLAMATION_THRESHOLD)??.4,wY=(0,NY.convertToMS)(JS.default.get(U.STORAGE_RECLAMATION_INTERVAL))||36e5;a(xh,"onStorageReclamation");IY=a(async e=>{if(FI.statfs){let t=await(0,FI.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"),CY=IY;a($I,"runReclamationHandlers");a(Cme,"setAvailableSpaceRatioGetter")});var Q0={};Ue(Q0,{ACTION_32_BIT:()=>tp,ACTION_64_BIT:()=>Mme,AUDIT_STORE_OPTIONS:()=>nh,Decoder:()=>Qc,HAS_BLOBS:()=>fn,HAS_CURRENT_RESIDENCY_ID:()=>mc,HAS_EXPIRATION_EXTENDED_TYPE:()=>Rf,HAS_ORIGINATING_OPERATION:()=>Af,HAS_PREVIOUS_RESIDENCY_ID:()=>pc,REMOTE_SEQUENCE_UPDATE:()=>KE,createAuditEntry:()=>Jl,getLastRemoved:()=>Dme,openAuditStore:()=>tT,readAuditEntry:()=>Nt,removeAuditEntry:()=>rT,setAuditRetention:()=>Lme,transactionKeyEncoder:()=>kY});function tT(e){let t=e.auditStore=e.openDB(VI.AUDIT_STORE_NAME,{create:!1,...nh});t||(t=e.auditStore=e.openDB(VI.AUDIT_STORE_NAME,nh),LY(t,1)),t.rootStore=e,t.tableStores=[];let r=[];t.addDeleteRemovalCallback=function(l,u,f){return r[l]=f,t.tableStores[l]=u,t.deleteCallbacks=r,{remove(){delete r[l]}}};let n=null,s,i=0,o=YI;xh(t.env.path,l=>{if(i=l,l)return c(100)});function c(l){l&&(o=l),clearTimeout(n);let u=new Promise(f=>{n=setTimeout(async()=>{if(await s,s=u,t.rootStore.status==="closed"||t.rootStore.status==="closing")return;let d=0,_,h;try{for(let{key:m,value:S}of t.getRange({start:1,snapshot:!1,end:Date.now()-KI/(1+i*i)})){try{_=rT(t,m,S)}catch(g){yd.warn("Error removing audit entry",g)}if(h=m,await new Promise(setImmediate),++d>=Pme){o=10;break}}await _}finally{d===0?o=Math.min(o<<1,KI/10):(LY(t,h),o>100&&(o=o>>1)),f(void 0),c()}},o).unref()});return u}if(a(c,"scheduleAuditCleanup"),t.scheduleAuditCleanup=c,(0,Hh.getWorkerIndex)()===(0,Hh.getWorkerCount)()-1&&c(),(0,Hh.getWorkerIndex)()===0&&!DY)for(let l of t.getKeys({reverse:!0,limit:1}))l>Date.now()&&(DY=!0,yd.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 rT(e,t,r){let n=vme(r),s;if(n&fn){s=Nt(r);let i=e.tableStores[s.tableId],o=i?.getEntry(s.recordId);(!o||o.version!==s.version||!o.value)&&_c(()=>ra(s.getValue(i)),i.rootStore)}if((n&15)===WI){s=s||Nt(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 LY(e,t){zI[0]=t,e.put(Symbol.for("last-removed"),FY)}function Dme(e){let t=e.get(Symbol.for("last-removed"));if(t)return FY.set(t),zI[0]}function Lme(e,t=YI){KI=e,YI=t}function Jl(e,t,r,n,s,i,o,c,l,u,f,d,_){let h=GY[o];if(!h)throw new Error(`Invalid audit entry type ${o}`);let m=1;if(n&&(n>1?ka.setFloat64(0,n):Os.set(JA),m=9),l){if(l&255)throw new Error("Illegal extended type");m+=3}R(s),R(t),g(r),ka.setFloat64(m,e),m+=8,l&mc&&R(u),l&pc&&R(f),l&Rf&&(ka.setFloat64(m,d),m+=8),l&Af&&R(qY[_]),i?g(i):Os[m++]=0,l?ka.setUint32(n?8:0,h|l|3221225472):Os[n?8:0]=h;let S=Os.subarray(0,m);if(c)return Buffer.concat([S,c]);return S;function g(E){let T=m;m+=1,m=(0,gl.writeKey)(E,Os,m);let w=m-T-1;w>127?w>16383?(yd.error("Key or username was too large for audit entry",E),m=T+1,Os[T]=0):(Os.copyWithin(T+2,T+1,m),ka.setUint16(T,w|32768),m++):Os[T]=w}function R(E){E<128?Os[m++]=E:E<16384?(ka.setUint16(m,E|32768),m+=2):E<1056964608?(ka.setUint32(m,E|3221225472),m+=4):(Os[m]=255,ka.setUint32(m+1,E),m+=5)}}function vme(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 Qc(e.buffer,e.byteOffset,e.byteLength));return n.position=t,n.readInt()}function Nt(e,t=0,r=void 0){try{let n=e.dataView||(e.dataView=new Qc(e.buffer,e.byteOffset,e.byteLength));n.position=t;let s;e[n.position]==66&&(s=n.readFloat64());let i=n.readInt(),o=n.readInt(),c=n.readInt(),l=n.readInt(),u=n.position,f=n.position+=l,d=n.readFloat64(),_,h,m,S;if(i&mc&&(_=n.readInt()),i&pc&&(h=n.readInt()),i&Rf&&(m=n.readFloat64()),i&Af){let T=n.readInt();S=qY[T]}l=n.readInt();let g=n.position,R=n.position+=l,E;return{type:GY[i&7],tableId:c,nodeId:o,get recordId(){return(0,gl.readKey)(e,u,f)},getBinaryRecordId(){return e.subarray(u,f)},version:d,previousLocalTime:s,get user(){return R>g?(0,gl.readKey)(e,g,R):void 0},get encoded(){return t?e.subarray(t,r):e},getValue(T,w,v){if(i&ZS||i&Bh&&!w)return E||(E=_c(()=>T.decoder.decode(e.subarray(n.position,r)),T.rootStore)),E;if(i&Bh&&v)return Wy(T.getEntry(this.recordId),v,T)},getBinaryValue(){return i&(ZS|Bh)?e.subarray(n.position,r):void 0},extendedType:i,residencyId:_,previousResidencyId:h,expiresAt:m,originatingOperation:S}}catch(n){return yd.error("Reading audit entry error",n,e),{}}}var gl,eT,VI,Hh,HY,yd,Os,ka,kY,nh,KI,Pme,zI,FY,YI,DY,ZS,Bh,MY,WI,vY,UY,xY,BY,tp,Mme,KE,mc,pc,Af,Rf,fn,GY,qY,Qc,Zi=be(()=>{gl=require("ordered-binary"),eT=M(le()),VI=M(Ut());k();Hh=M(tt()),HY=M(ae());Xl();yd=M(j());Vp();cs();XS();(0,eT.initSync)();Os=Buffer.alloc(2816),ka=new DataView(Os.buffer,Os.byteOffset,2816),kY={writeKey(e,t,r){return e===Tf?(t.set(Tf,r),r+8):typeof e=="number"?((t.dataView||(t.dataView=new DataView(t.buffer,t.byteOffset,t.byteLength))).setFloat64(r,e),r+8):(0,gl.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,gl.readKey)(e,t,r)}},nh={encoding:"binary",keyEncoder:kY},KI=(0,HY.convertToMS)((0,eT.get)(U.LOGGING_AUDITRETENTION))||86400*3,Pme=1e3,zI=new Float64Array(1),FY=new Uint8Array(zI.buffer),YI=1e4,DY=!1;a(tT,"openAuditStore");a(rT,"removeAuditEntry");a(LY,"updateLastRemoved");a(Dme,"getLastRemoved");a(Lme,"setAuditRetention");ZS=16,Bh=32,MY=1,WI=2,vY=3,UY=4,xY=5,BY=6,tp=14,Mme=15,KE=11,mc=512,pc=1024,Af=2048,Rf=4096,fn=8192,GY={put:MY|ZS,[MY]:"put",delete:WI,[WI]:"delete",message:vY|ZS,[vY]:"message",invalidate:UY|Bh,[UY]:"invalidate",patch:xY|Bh,[xY]:"patch",relocate:BY,[BY]:"relocate"},qY={insert:1,update:2,upsert:3,1:"insert",2:"update",3:"upsert"};a(Jl,"createAuditEntry");a(vme,"readAction");a(Nt,"readAuditEntry");Qc=class extends DataView{static{a(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}}}});function JI(e,t,r,n,s){let i=e.primaryStore.env.path,o=e.primaryStore.tableId,c;s?.crossThreads===!1?(c=VY,Ume(e.primaryStore,e.auditStore)):(c=$Y,e.primaryStore.env.hasSubscriptionCommitListener||(e.primaryStore.env.hasSubscriptionCommitListener=!0,e.primaryStore.on("committed",()=>{KY($Y[i])})));let l=c[i]||(c[i]=[]);if(l.auditStore=e.auditStore,l.lastTxnTime==null&&(l.lastTxnTime=Date.now()),s?.scope==="full-database")return;let u=l[o];u||(u=l[o]=new Map,u.envs=l,u.tableId=o,u.store=e.primaryStore),t=Wl(t);let f=new jI(r);f.startTime=n;let d=u.get(t);return d?d.push(f):(u.set(t,d=[f]),d.tables=u,d.key=t),f.subscriptions=d,f}function KY(e){if(!e)return;let t=e.auditStore;t.resetReadTxn(),YY(e.auditStore);let r;for(let{key:n,value:s}of t.getRange({start:e.lastTxnTime,exclusiveStart:!0})){e.lastTxnTime=n;let i=Nt(s),o=e[i.tableId];if(!o)continue;let c=i.recordId,l=Wl(c),u=0;do{let f=o.get(l);if(f){for(let _ of f)if(!(u>0&&!(_.includeDescendants&&!(_.onlyChildren&&u>1)))){if(_.startTime>=n){(0,QI.info)("omitting",c,_.startTime,n);continue}try{let h;_.supportsTransactions&&_.txnInProgress!==i.version&&(h=!0,_.txnInProgress||(r?r.push(_):r=[_]),_.txnInProgress=i.version),_.listener(c,i,n,h)}catch(h){console.error(h),(0,QI.info)(h)}}}if(l==null)break;let d=l.lastIndexOf?.("/",l.length-2);d!==l.length-1&&u++,d>-1?l=l.slice(0,d+1):l=null}while(!0)}if(r)for(let n of r)n.txnInProgress=null,n.listener(null,{type:"end_txn"},e.lastTxnTime,!0)}function Ume(e,t){let r=t||e,n=r.env;if(!n.hasAfterCommitListener){n.hasAfterCommitListener=!0;let s=n.path;r.on("aftercommit",({next:i,last:o,txnId:c})=>{let l=VY[s];if(!l)return;let u=a(()=>{r.threadLocalWrites||(r.threadLocalWrites=new Float64Array(r.getUserSharedBuffer("last-thread-local-write",new ArrayBuffer(8)))),l.txnTime=r.threadLocalWrites[0]||Date.now();try{KY(l)}finally{r.threadLocalWrites[0]=l.lastTxnTime,r.unlock("thread-local-writes")}},"acquiredLock");r.attemptLock("thread-local-writes",u)&&u()})}}function YY(e){e.nextTransaction?.resolve();let t;e.nextTransaction=new Promise(r=>{t=r}),e.nextTransaction.resolve=t}function Tk(e){return e.nextTransaction||(JI({primaryStore:e,auditStore:e},null,null,0,{scope:"full-database"}),YY(e)),e.nextTransaction}var QI,$Y,VY,jI,bO=be(()=>{QI=M(j());Gl();zl();Zi();$Y=Object.create(null),VY=Object.create(null);a(JI,"addSubscription");jI=class extends Dn{static{a(this,"Subscription")}listener;subscriptions;startTime;constructor(t){super(),this.listener=t,this.on("close",()=>this.end())}end(){if(this.subscriptions){if(this.subscriptions.splice(this.subscriptions.indexOf(this),1),this.subscriptions.length===0){let t=this.subscriptions.tables;if(t){let r=this.subscriptions.key;if(t.delete(r),t.size===0){let n=t.envs,s=t.dbi;delete n[s]}}}this.subscriptions=null}}toJSON(){return{name:"subscription"}}};a(KY,"notifyFromTransactionData");a(Ume,"listenToCommits");a(YY,"nextTransaction");a(Tk,"whenNextTransaction")});var Uw={};Ue(Uw,{EVICTED:()=>Jo,INVALIDATED:()=>un,coerceType:()=>iT,makeTable:()=>aT,setServerUtilities:()=>$me});function aT(e){let{primaryKey:t,indices:r,tableId:n,tableName:s,primaryStore:i,databasePath:o,databaseName:c,auditStore:l,schemaDefined:u,dbisDB:f,sealed:d,splitSegments:_,replicate:h}=e,{expirationMS:m,evictionMS:S,audit:g,trackDeletes:R}=e;S??=0;let{attributes:E}=e;E||(E=[]);let T=eR(i,n,l),w,v,H={},q=Promise.resolve(),W,te,se;for(let K of E)(K.assignCreatedTime||K.name==="__createdtime__")&&(W=K),(K.assignUpdatedTime||K.name==="__updatedtime__")&&(te=K),K.expiresAt&&(se=K),K.isPrimaryKey&&(H=K);let Y,ne=[],ue=[],oe=1,pe=2,Te={},ye={},Qt=864e5,lt=0,Tr,ss,Cn,Ml=!1,vl,$T=new Map,VT=new Map,vt,Hd,hm=Tl.get(U.REPLICATION_DATABASES);if(Array.isArray(hm)){for(let K of hm)if(K.name===c&&K.replicateTo>=0){Hd=K.replicateTo;break}}let mm=i.getRange({start:!1,end:!1}).constructor,kd=10,pm=6;g&&$d(),xh(i.env.path,K=>{if(v)return Vi(K)});class Ce extends qr{#e;#t;#n;#r;#s;#i;static name=s;static primaryStore=i;static auditStore=l;static primaryKey=t;static tableName=s;static tableId=n;static indices=r;static audit=g;static databasePath=o;static databaseName=c;static attributes=E;static replicate=h;static sealed=d;static splitSegments=_??!0;static createdTimeProperty=W;static updatedTimeProperty=te;static propertyResolvers;static userResolvers={};static sources=[];static getResidencyById;static get expirationMS(){return m}static dbisDB=f;static schemaDefined=u;static sourcedFrom(p,O){if(O&&(this.sourceOptions=O,(O.expiration||O.eviction||O.scanInterval)&&this.setTTLExpiration(O)),O?.intermediateSource)p.intermediateSource=!0,this.sources.unshift(p);else{if(this.sources.some(I=>!I.intermediateSource)){if(this.sources.some(I=>I.name===p.name))return;throw new Error("Can not have multiple canonical (non-intermediate) sources")}this.sources.push(p)}v=v||p.get&&(!p.get.reliesOnPrototype||p.prototype.get),w=w||p.load;let A=a(I=>{let L=this.sources;if(L=L.filter(B=>B.intermediateSource&&B[I]&&(!B[I].reliesOnPrototype||B.prototype[I])),L.length>0)if(L.length===1){let B=L[0];return(N,x,G)=>{if(N?.source!==B)return B[I](x,G,N)}}else return(B,N,x)=>{let G=[];for(let z of L){if(B?.source===z)break;G.push(z[I](N,x,B))}return Promise.all(G)}},"getApplyToIntermediateSource"),y=this.sources[this.sources.length-1];y.intermediateSource&&(y={});let b=a(I=>{if(y[I]&&(!y[I].reliesOnPrototype||y.prototype[I]))return(L,B,N)=>{if(!L?.source)return y[I](B,N,L)}},"getApplyToCanonicalSource");Te={put:b("put"),patch:b("patch"),delete:b("delete"),publish:b("publish")},ye={put:A("put"),patch:A("patch"),delete:A("delete"),publish:A("publish"),invalidate:A("invalidate")};let C=y.shouldRevalidateEvents;return(async()=>{let I=!1,L,B=a(async(N,x)=>{let G=N.value,z=N.table?Ve[c][N.table]:Ce;if(c===Yd&&(N.table===kl.ROLE_TABLE_NAME||N.table===kl.USER_TABLE_NAME)&&(I=!0),N.id===void 0&&(N.id=G[z.primaryKey],N.id===void 0))throw new Error("Replication message without an id "+JSON.stringify(N));N.source=p;let ie={residencyId:Za(N.residencyList),isNotification:!0,ensureLoaded:!1,nodeId:N.nodeId},F=await z.getResource(N.id,x,ie);switch(N.finished&&await N.finished,N.type){case"put":return C?F._writeInvalidate(G,ie):F._writeUpdate(G,!0,ie);case"patch":return C?F._writeInvalidate(G,ie):F._writeUpdate(G,!1,ie);case"delete":return F._writeDelete(ie);case"publish":case"message":return F._writePublish(G,ie);case"invalidate":return F._writeInvalidate(G,ie);case"relocate":return F._writeRelocate(ie);default:xe.default.error?.("Unknown operation",N.type,N.id)}},"writeUpdate");try{let N=p.subscribe;N&&R==null&&(R=!0);let x={crossThreads:!1,inTransactionUpdates:!0,supportsTransactions:!0,omitCurrent:!0},G=p.subscribeOnThisThread?p.subscribeOnThisThread((0,Sl.getWorkerIndex)(),x):(0,Sl.getWorkerIndex)()===0,z=N&&G&&await p.subscribe?.(x);if(z){let ie;for await(let F of z)try{if(!(F.type==="transaction"?F.writes[0]:F)){xe.default.error?.("Bad subscription event",F);continue}if(F.source=p,F.type==="end_txn"){if(ie?.resolve(),F.localTime&&L!==F.localTime){if(F.remoteNodeIds?.length>0){let ce=[Symbol.for("seq"),F.remoteNodeIds[0]],ee=f.get(ce),Q=ee?.nodes;Q||(Q=[]);for(let fe of F.remoteNodeIds.slice(1)){let Ae=Q.find(De=>De.id===fe);Q=Q.filter(De=>De.id!==fe||De===Ae),Ae||(Ae={id:fe,seqId:0},Q.push(Ae)),Ae.seqId=Math.max(ee?.seqId??1,F.localTime),fe===ie?.nodeId&&(Ae.lastTxnTime=F.timestamp)}let _e=Math.max(ee?.seqId??1,F.localTime);xe.default.trace?.("Received txn",c,new Date(_e),new Date(F.localTime),F.remoteNodeIds),f.put(ce,{seqId:_e,nodes:Q})}L=F.localTime}F.onCommit&&ie?.committed.then(F.onCommit);continue}if(ie)if(F.beginTxn)ie.resolve();else{ie.write_promises.push(B(F,ie));continue}!F.timestamp&&F.version&&(F.timestamp=F.version);let Z=Ot(F,()=>{if(F.type==="transaction"){let ce=[];for(let ee of F.writes)try{ce.push(B(ee,F))}catch(Q){throw Q.message+=" writing "+JSON.stringify(ee)+" of event "+JSON.stringify(F),Q}return Promise.all(ce)}else if(F.type==="define_schema"){let ce=this.attributes.slice(0),ee;for(let Q of F.attributes)ce.find(_e=>_e.name===Q.name)||(ce.push(Q),ee=!0);ee&&(ut({table:s,database:c,attributes:ce,origin:"cluster"}),Fh.signalSchemaChange(new Gh.SchemaEventMsg(process.pid,Gt.CREATE_TABLE,c,s)))}else return F.beginTxn?(ie=F,ie.write_promises=[B(F,F)],new Promise(ce=>{ie.resolve=()=>ce(Promise.all(ie.write_promises))})):B(F,F)});ie&&(ie.committed=Z),I&&Z&&!Z?.waitingForUserChange&&(Z.then(()=>Fh.signalUserChange(new Gh.UserEventMsg(process.pid))),Z.waitingForUserChange=!0),F.onCommit&&(Z?Z.then(F.onCommit):F.onCommit())}catch(qe){xe.default.error?.("error in subscription handler",qe)}}}catch(N){xe.default.error?.(N)}})(),this}static get isCaching(){return v}static get shouldRevalidateEvents(){return this.prototype.get!==Ce.prototype.get}static getResource(p,O,A){let y=super.getResource(p,O,A);if(p!=null){Or(p);try{if(y.getRecord?.())return y;if(typeof p=="object"&&p&&!Array.isArray(p))throw new Error(`Invalid id ${JSON.stringify(p)}`);let b=!A?.async||i.cache?.get?.(p),C=Gr(O),I=C.getReadTxn();if(I?.isDone)throw new Error("You can not read from a transaction that has already been committed/aborted");return Ul(p,O,{transaction:I,ensureLoaded:A?.ensureLoaded},b,L=>{if(L?Ce._updateResource(y,L):y.#e=null,O.onlyIfCached&&O.noCacheStore){if(!y.doesExist())throw new br.ServerError("Entry is not cached",504)}else if(A?.ensureLoaded){let B=xl(p,L,O,y);if(B)return C?.disregardReadTxn(),y.#i=!0,ZI(B,N=>(Ce._updateResource(y,N),y))}return y})}catch(b){throw b.message.includes("Unable to serialize object")&&(b.message+=": "+JSON.stringify(p)),b}}return y}static _updateResource(p,O){p.#r=O,p.#e=O?.value??null,p.#n=O?.version}ensureLoaded(){let p=xl(this.getId(),this.#r,this.getContext());if(p)return this.#i=!0,ZI(p,O=>{this.#r=O,this.#e=O.value,this.#n=O.version})}static getNewId(){let p=H?.type;if(p==="String"||p==="ID")return super.getNewId();if(!vt){let b=i.getEntry(Symbol.for("id_allocation")),C=b?.value,I;if(C&&C.nodeName===server.hostname&&(!Kme(i)||C.pid===process.pid)){let L=C.start,B=C.end;I=L;for(let N of i.getKeys({start:B,end:L,limit:1,reverse:!0}))I=N}else C=y(b?.version??null),I=C.start;vt=new BigInt64Array([BigInt(I)+1n]),vt=new BigInt64Array(i.getUserSharedBuffer("id",vt.buffer)),vt.maxSafeId=C.end}let O=Number(Atomics.add(vt,0,1n)),A=p==="Int"?512:1048576;if(O+A>=vt.maxSafeId){let b=a(C=>{vt.maxSafeId=O+(p==="Int"?1023:4194303);let I=(p==="Int"?Math.pow(2,31):Math.pow(2,49))-1,L=C?void 0:i.useReadTransaction(),B=Number(vt[0]);for(let G of i.getKeys({start:B+1,end:I,limit:1,transaction:L}))I=G;L?.done();let{value:N,version:x}=i.getEntry(Symbol.for("id_allocation"));if(vt.maxSafeId<I){if(N.end>vt.maxSafeId-100)return;xe.default.info?.("New id allocation",O,vt.maxSafeId,x),i.put(Symbol.for("id_allocation"),{start:N.start,end:vt.maxSafeId,nodeName:server.hostname,pid:process.pid},Date.now(),x)}else{xe.default.warn?.(`Id conflict detected, starting new id allocation range, attempting to allocate to ${vt.maxSafeId}, but id of ${I} detected`);let G=y(x);G.alreadyUpdated||Atomics.store(vt,0,BigInt(G.start+1)),vt.maxSafeId=G.end}},"updateEnd");O+A===vt.maxSafeId?setImmediate(b):O+100>=vt.maxSafeId&&(xe.default.warn?.(`Synchronous id allocation required on table ${s}${p=="Int"?", it is highly recommended that you use Long or Float as the type for auto-incremented primary keys":""}`),i.transactionSync(()=>b(!0)))}return O;function y(b){let C=(p==="Int"?Math.pow(2,31):Math.pow(2,49))-1,I=C/4,L,B,N=!1,x,G;do{x=Math.floor(Math.random()*C),G={start:x,end:x+(p==="Int"?1024:4194304),nodeName:server.hostname,pid:process.pid},L=0;for(let z of i.getKeys({start:x,limit:1,reverse:!0}))L=z;B=C;for(let z of i.getKeys({start:x+1,end:C,limit:1}))B=z;I*=.875,I<1e3&&!N&&(N=!0,xe.default.error?.(`Id allocation in table ${s} is very dense, limited safe range of numbers to allocate ids in${p==="Int"?", it is highly recommended that you use Long or Float as the type for auto-incremented primary keys":""}`,x,L,B,I))}while(!(I<B-x&&(I<x-L||L===0)));return i.transactionSync(()=>{let z=i.getEntry(Symbol.for("id_allocation"));return(z?.version??null)==b?(xe.default.info?.("Allocated new id range",G),i.put(Symbol.for("id_allocation"),G,Date.now()),G):(xe.default.debug?.("Looks like ids were already allocated"),{alreadyUpdated:!0,...z.value})})}}static setTTLExpiration(p){if(typeof p=="number")m=p*1e3,S||(S=0);else if(p&&typeof p=="object")m=p.expiration*1e3,S=(p.eviction||0)*1e3,Qt=p.scanInterval*1e3;else throw new Error("Invalid expiration value type");if(m<0)throw new Error("Expiration can not be negative");Qt=Qt||(m+S)/4,Vi()}static getResidencyRecord(p){return f.get([Symbol.for("residency_by_id"),p])}static setResidency(p){Ce.getResidency=p&&((O,A)=>{try{return p(O,A)}catch(y){throw y.message+=` in residency function for table ${s}`,y}})}static setResidencyById(p){Ce.getResidencyById=p&&(O=>{try{return p(O)}catch(A){throw A.message+=` in residency function for table ${s}`,A}})}static getResidency(p,O){if(Ce.getResidencyById)return Ce.getResidencyById(p[t]);let A=Hd;if(O.replicateTo!=null){if(Array.isArray(O.replicateTo))return O.replicateTo.includes(server.hostname)?O.replicateTo:[server.hostname,...O.replicateTo];O.replicateTo>=0&&(A=O.replicateTo)}if(A>=0&&server.nodes){let y=[server.hostname];if(O.previousResidency)y.push(...O.previousResidency.slice(0,A));else{let b=server.nodes.map(L=>L.name),C=Math.floor(b.length*Math.random());y.push(...b.slice(C,C+A));let I=C+A-b.length;I>0&&y.push(...b.slice(0,I))}return y}}static enableAuditing(p=!0){g=p,p&&$d(),Ce.audit=p}static coerceId(p){return p===""?null:iT(p,H)}static async dropTable(){delete Ve[c][s];for(let p of i.getRange({versions:!0,snapshot:!1,lazy:!0}))p.metadataFlags&fn&&p.value&&ra(p.value);if(c===o){for(let p of E)f.remove(Ce.tableName+"/"+p.name),r[p.name]?.drop();f.remove(Ce.tableName+"/"),i.drop(),await f.committed}else console.log("legacy dropTable"),await i.close(),await sT.default.remove(data_path),await sT.default.remove(data_path===standard_path?data_path+MDB_LOCK_FILE_SUFFIX:path.join(path.dirname(data_path),MDB_LEGACY_LOCK_FILE_NAME));Fh.signalSchemaChange(new Gh.SchemaEventMsg(process.pid,Gt.DROP_TABLE,c,s))}get(p){if(typeof p=="string")return this.getProperty(p);if(this.isCollection)return this.search(p);if(this.getId()===null){if(p?.conditions||p?.size>0)return this.search(p);let O={records:"./",name:s,database:c,auditSize:l?.getStats().entryCount,attributes:E};return this.getContext()?.includeExpensiveRecordCountEstimates?Ce.getRecordCount().then(A=>(O.recordCount=A.recordCount,O.estimatedRecordRange=A.estimatedRange,O)):O}if(p?.property)return this.getProperty(p.property);if(this.doesExist()||p?.ensureLoaded===!1||this.getContext()?.returnNonexistent)return this}allowRead(p,O){let A=Fr(p);if(A?.read){if(A.isSuperUser)return!0;let y=A.attribute_permissions,b=O?.select;if(y?.length>0||Ml&&b){if(O||(O={}),b){let C=y?.length>0&&XI(y,"read");O.select=b.map(I=>{let L=I.name||I;if(!C||C[L]){let B=Cn[L]?.definition?.tableClass;if(B){if(I.name||(I={name:I}),!B.prototype.allowRead.call(null,p,I))return!1;if(!I.select)return I.name}return I}}).filter(Boolean)}else O.select=y.filter(C=>C.read&&!Cn[C.attribute_name]).map(C=>C.attribute_name);return O}else return!0}}allowUpdate(p,O){let A=Fr(p);if(A?.update){let y=A.attribute_permissions;if(y?.length>0){let b=XI(y,"update");for(let C in O)if(!b[C])return!1;for(let C of y){let I=C.attribute_name;!C.update&&!(I in O)&&(O[I]=this.getProperty(I))}}return Hl(this.getContext())}}allowCreate(p,O){if(this.isCollection){let A=Fr(p);if(A?.insert){let y=A.attribute_permissions;if(y?.length>0){let b=XI(y,"insert");for(let C in O)if(!b[C])return!1;return Hl(this.getContext())}else return Hl(this.getContext())}}else return this.allowUpdate(p,{})}allowDelete(p){return Fr(p)?.delete&&Hl(this.getContext())}update(p,O){if(!Gr(this.getContext()))throw new Error("Can not update a table resource outside of a transaction");if(p===!1)return this;let y;return typeof p=="object"&&p&&(O?(Object.isFrozen(p)&&(p={...p}),this.#e={},this.#t=p):(y=this.#t,y&&(p=Object.assign(y,p)),this.#t=p)),this._writeUpdate(this.#t,O),this}addTo(p,O){if(typeof O=="number"||typeof O=="bigint")this.#s===zY?this.set(p,(+this.getProperty(p)||0)+O):(this.#s||this.update(),this.set(p,new Wp(O)));else throw new Error("Can not add a non-numeric value")}subtractFrom(p,O){if(typeof O=="number")return this.addTo(p,-O);throw new Error("Can not subtract a non-numeric value")}getMetadata(){return this.#r}getRecord(){return this.#e}getChanges(){return this.#t}_setChanges(p){this.#t=p}setRecord(p){this.#e=p}invalidate(){this._writeInvalidate()}_writeInvalidate(p,O){let A=this.getContext(),y=this.getId();Or(y),Gr(this.getContext()).addWrite({key:y,store:i,invalidated:!0,entry:this.#r,before:Te.invalidate?.bind(this,A,y),beforeIntermediate:ye.invalidate?.bind(this,A,y),commit:a((C,I)=>{if(!($i(C,I,O?.nodeId)<=0)){p??=null;for(let L in r)p||(p={}),p[L]===void 0&&(p[L]=this.getProperty(L));xe.default.trace?.(`Invalidating entry id: ${y}, timestamp: ${new Date(C).toISOString()}`),T(y,p,this.#r,C,un,g,{user:A?.user,residencyId:O?.residencyId,nodeId:O?.nodeId},"invalidate")}},"commit")})}_writeRelocate(p){let O=this.getContext(),A=this.getId();Or(A),Gr(this.getContext()).addWrite({key:A,store:i,invalidated:!0,entry:this.#r,before:Te.relocate?.bind(this,O,A),beforeIntermediate:ye.relocate?.bind(this,O,A),commit:a((b,C)=>{if($i(b,C,p?.nodeId)<=0)return;let I=Ce.getResidencyRecord(p.residencyId),L=0,B=null,N=C?.value;if(I&&!I.includes(server.hostname)){for(let x in r)B||(B={}),B[x]=N(x);L=un}else B=N;xe.default.trace?.(`Relocating entry id: ${A}, timestamp: ${new Date(b).toISOString()}`),T(A,B,this.#r,b,L,g,{user:O.user,residencyId:p.residencyId,nodeId:p.nodeId,expiresAt:p.expiresAt},"relocate",!1,null)},"commit")})}static _recordRelocate(p,O){let A={previousResidency:this.getResidencyRecord(p.residencyId),isRelocation:!0},y=Ki(this.getResidency(O.value,A)),b;if(y){if(!y.includes(server.hostname))return!1;b=Za(y)}let I=T(p.key,O.value,p,p.version,0,!0,{residencyId:b,expiresAt:O.expiresAt},"relocate",!1,null);return!0}static evict(p,O,A){let y=this.Source,b;if(!((v||g)&&(!O||(b=i.getEntry(p),!b||!O)||b.version!==A))){if(v){if(i.hasLock(p,b.version))return;let C;for(let I in r)C||(C={}),C[I]=O[I];if(C)return T(p,C,b,A,Jo,null,null,null,!0)}if(i.ifVersion(p,A,()=>{sn(p,O,null)}),g)return T(p,null,b,A,Jo,null,null,null,!0);hc(i,b??i.getEntry(p),A)}}lock(){throw new Error("Not yet implemented")}static operation(p,O){return p.table||=s,p.schema||=c,rW.operation(p,O)}put(p){this.update(p,!0)}patch(p){this.update(p,!1)}_writeUpdate(p,O,A){let y=this.getContext(),b=Gr(y),C=this.getId();Or(C);let I=this.#r;this.#s=O?zY:Fme;let L={key:C,store:i,entry:I,nodeName:y?.nodeName,validate:a(B=>{p||(p=this.#t),O||p&&Kp(this.#t===p?this:p)?y?.source||(b.checkOverloaded(),this.validate(p,!O),te&&(p[te.name]=te.type==="Date"?new Date(B):te.type==="String"?new Date(B).toISOString():B),O&&(t&&p[t]!==C&&(p[t]=C),W&&(I?.value?p[W.name]=I?.value[W.name]:p[W.name]=W.type==="Date"?new Date(B):W.type==="String"?new Date(B).toISOString():B),p=Mc(p))):b.removeWrite(L)},"validate"),before:O?Te.put?()=>Te.put(y,C,p):null:Te.patch?()=>Te.patch(y,C,p):Te.put?()=>Te.put(y,C,Mc(this)):null,beforeIntermediate:O?ye.put?()=>ye.put(y,C,p):null:ye.patch?()=>ye.patch(y,C,p):ye.put?()=>ye.put(y,C,Mc(this)):null,commit:a((B,N,x)=>{if(x){if(y&&N?.version>(y.lastModified||0)&&(y.lastModified=N.version),this.#r=N,N?.value&&N.value.getRecord)throw new Error("Can not assign a record to a record, check for circular references");O||(this.#e=N?.value??null)}this.#t=void 0,this.#n=B;let G=N?.value,z=p;this.#s=0;let ie=!1,F=$i(B,N,A?.nodeId),qe;if(F<=0)if(g){let _e=N.localTime,fe=N.version;xe.default.trace?.("Applying CRDT update to record with id: ",C,"applying later update:",fe);let Ae=[];for(;_e>B||fe>=B&&_e>0;){let De=l.get(_e);if(!De)break;let we=Nt(De);if(fe=we.version,fe>=B){if(fe===B){if(F=$i(B,{version:fe,localTime:_e},A?.nodeId),F===0)return;if(F>0)continue}if(we.type==="patch")Ae.push(we),qe=p;else if(we.type==="put"||we.type==="delete")return}_e=we.previousLocalTime}Ae.sort((De,we)=>De.version-we.version);for(let De of Ae){let we=De.getValue(i);if(z=$p(z,we,O),xe.default.debug?.("Rebuilding update with future patch:",z),!z)return}}else{if(O)return;z=$p(z,G,O),xe.default.debug?.("Rebuilding update without audit:",z)}let Z;if(O?Z=z:(this.#e=G,Z=Mc(this,z)),this.#e=Z,Z&&Z.getRecord)throw new Error("Can not assign a record to a record, check for circular references");let ce;if(A?.residencyId!=null)ce=A.residencyId;else{I?.residencyId&&(y.previousResidency=Ce.getResidencyRecord(I.residencyId));let _e=Ki(Ce.getResidency(Z,y));if(_e&&!_e.includes(server.hostname))if(qe??=Z,ie=!0,Ce.getResidencyById)Z=void 0;else{Z=null;for(let fe in r)Z||(Z={}),Z[fe]=qe[fe]}ce=Za(_e)}O||(qe=p);let ee=y?.expiresAt??(m?m+Date.now():-1);xe.default.trace?.(`Saving record with id: ${C}, timestamp: ${new Date(B).toISOString()}${ee?", expires at: "+new Date(ee).toISOString():""}${N?", replaces entry from: "+new Date(N.version).toISOString():", new entry"}`,(()=>{try{return JSON.stringify(Z).slice(0,100)}catch{return""}})()),sn(C,G,Z);let Q=O?"put":"patch";T(C,Z,N,B,ie?un:0,g,{omitLocalRecord:ie,user:y?.user,residencyId:ce,expiresAt:ee,nodeId:A?.nodeId,originatingOperation:y?.originatingOperation},Q,!1,qe),y.expiresAt&&Vi()},"commit")};b.addWrite(L)}async delete(p){if(typeof p=="string")return this.deleteProperty(p);if(this.isCollection){for await(let O of this.search(p))(await Ce.getResource(O[t],this.getContext(),{ensureLoaded:!1}))._writeDelete(p);return}return this.#e?this._writeDelete(p):!1}_writeDelete(p){let O=Gr(this.getContext()),A=this.getId();Or(A);let y=this.getContext();return O.addWrite({key:A,store:i,entry:this.#r,nodeName:y?.nodeName,before:Te.delete?.bind(this,y,A),beforeIntermediate:ye.delete?.bind(this,y,A),commit:a((b,C,I)=>{let L=C?.value;I&&(y&&C?.version>(y.lastModified||0)&&(y.lastModified=C.version),Ce._updateResource(this,C)),!($i(b,C,p?.nodeId)<=0)&&(sn(this.getId(),L),xe.default.trace?.(`Deleting record with id: ${A}, txn timestamp: ${new Date(b).toISOString()}`),g||R?(T(A,null,this.#r,b,0,g,{user:y?.user,nodeId:p?.nodeId},"delete"),g||Vi()):hc(i,C))},"commit")}),!0}search(p){let O=this.getContext(),A=Gr(O);if(!p)throw new Error("No query provided");let y=p.conditions;y?y.length===void 0&&(y=y[Symbol.iterator]?Array.from(y):[y]):y=Array.isArray(p)?p:p[Symbol.iterator]?Array.from(p):[],this.getId()&&(y=[{attribute:null,comparator:Array.isArray(this.getId())?"prefix":"starts_with",value:this.getId()}].concat(y));let b,C={};function I(Q,_e){let fe;switch(_e){case"and":case void 0:if(Q.length<1)throw new Error('An "and" operator requires at least one condition');fe=!0;break;case"or":if(Q.length<2)throw new Error('An "or" operator requires at least two conditions');break;default:throw new Error("Invalid operator "+_e)}for(let Ae of Q){if(Ae.conditions){Ae.conditions=I(Ae.conditions,Ae.operator);continue}let De=Ae[0]??Ae.attribute,we=De==null?H:fi(E,De);if(we)(we.type||RA[Ae.comparator])&&(Ae[1]===void 0?Ae.value=B(Ae.value,we):Ae[1]=B(Ae[1],we));else if(De!=null)throw(0,br.handleHDBError)(new Error,`${De} is not a defined attribute`,404);if(Ae.chainedConditions)if(Ae.chainedConditions.length===1&&(!Ae.operator||Ae.operator=="and")){let dr=Ae.chainedConditions[0],Nr,Ps;if(dr.comparator==="gt"||dr.comparator==="greater_than"||dr.comparator==="ge"||dr.comparator==="greater_than_equal"?(Nr=Ae,Ps=dr):(Nr=dr,Ps=Ae),Nr.comparator!=="lt"&&Nr.comparator!=="less_than"&&Nr.comparator!=="le"&&Nr.comparator!=="less_than_equal")throw new Error("Invalid chained condition, only less than and greater than conditions can be chained together");let Re=Ps.comparator==="ge"||Ps.comparator==="greater_than_equal",yt=Nr.comparator==="le"||Nr.comparator==="less_than_equal";Ae.comparator=(Re?"ge":"gt")+(yt?"le":"lt"),Ae.value=[Ps.value,Nr.value]}else throw new Error("Multiple chained conditions are not currently supported")}return Q}a(I,"prepareConditions");function L(Q,_e){if(p.enforceExecutionOrder)return Q;for(let fe of Q)fe.conditions&&(fe.conditions=L(fe.conditions,fe.operator));return Q.length>1&&_e!=="or"?(0,eW.sortBy)(Q,Gm(Ce)):Q}a(L,"orderConditions");function B(Q,_e){return Array.isArray(Q)?Q.map(fe=>iT(fe,_e)):iT(Q,_e)}a(B,"coerceTypedValues");let N=p.operator;(y.length>0||N)&&(y=I(y,N));let x=typeof p.sort=="object"&&p.sort,G;if(x&&N!=="or"){let Q=x.attribute;if(Q==null)throw new br.ClientError("Sort requires an attribute");if(b=y.find(_e=>Kl(_e.attribute)===Kl(Q)),!b){let _e=fi(E,Q);if(!_e)throw(0,br.handleHDBError)(new Error,`${Array.isArray(Q)?Q.join("."):Q} is not a defined attribute`,404);if(_e.indexed)b={attribute:Q,comparator:"sort"},y.push(b);else if(y.length===0&&!p.allowFullScan)throw(0,br.handleHDBError)(new Error,`${Array.isArray(Q)?Q.join("."):Q} is not indexed and not combined with any other conditions`,404)}b&&(b.descending=!!x.descending)}y=L(y,N),x&&(b&&y[0]===b?x.next&&(G={dbOrderedAttribute:x.attribute,attribute:x.next.attribute,descending:x.next.descending,next:x.next.next}):(b&&y.splice(y.indexOf(b),1),G=x));let z=p.select;if(y.length===0&&(y=[{attribute:t,comparator:"greater_than",value:!0}]),p.explain)return{conditions:y,operator:N,postOrdering:G,selectApplied:!!z};let ie=A.useReadTxn(),F=yA(y,N,Ce,ie,p,O,(Q,_e)=>Gd(Q,z,O,ie,_e),C),qe=p.ensureLoaded!==!1;G||(F=ee(F));let Z=Ce.transformEntryForSelect(z,O,ie,C,qe,!0),ce=Ce.transformToOrderedSelect(F,z,G,ie,O,Z);function ee(Q){return p.offset||p.limit!==void 0?Q.slice(p.offset,p.limit!==void 0?(p.offset||0)+p.limit:void 0):Q}return a(ee,"applyOffset"),G&&(ce=ee(ce)),ce.onDone=()=>{ce.onDone=null,A.doneReadTxn()},ce.selectApplied=!0,ce.getColumns=()=>{if(z){let Q=[];for(let _e of z)_e==="*"?Q.push(...E.map(fe=>fe.name)):Q.push(_e.name||_e);return Q}return E.filter(Q=>!Q.computed&&!Q.relationship).map(Q=>Q.name)},ce}static transformToOrderedSelect(p,O,A,y,b,C){let I=new mm;if(A){p=Gd(p,O,y,b,null);let L;I.iterate=function(){let N,x=p[Symbol.asyncIterator]?p[Symbol.asyncIterator]():p[Symbol.iterator](),G,z=A.dbOrderedAttribute,ie,F,qe=!0;function Z(ee){let Q=ee.next&&Z(ee.next),_e=ee.descending;return(fe,Ae)=>{let De=Bl(fe,ee.attribute,y),we=Bl(Ae,ee.attribute,y),dr=_e?(0,Al.compareKeys)(we,De):(0,Al.compareKeys)(De,we);return dr===0?Q?.(fe,Ae)||0:dr}}a(Z,"createComparator");let ce=Z(A);return{async next(){let ee;if(N)if(ee=N.next(),ee.done){if(G)return I.onDone&&I.onDone(),ee}else return{value:await C.call(this,ee.value)};L=[],ie&&L.push(ie);do if(ee=await x.next(),ee.done){if(G=!0,L.length)break;return I.onDone&&I.onDone(),ee}else{let Q=ee.value;if(Q?.then&&(Q=await Q),z){let _e=Bl(Q,z,y);if(qe)qe=!1,F=_e;else if(_e!==F){F=_e,ie=Q;break}}L.push(Q)}while(!0);return A.isGrouped,L.sort(ce),N=L[Symbol.iterator](),ee=N.next(),ee.done?(I.onDone&&I.onDone(),ee):{value:await C.call(this,ee.value)}},return(){I.onDone&&I.onDone(),x.return()},throw(){I.onDone&&I.onDone(),x.throw()}}};let B=a(N=>{if(typeof O=="object"&&Array.isArray(N.attribute))for(let x=0;x<O.length;x++){let G=O[x],z;if(G.name===N.attribute[0]){for(z=G.sort||(G.sort={});z.next;)z=z.next;z.attribute=N.attribute.slice(1),z.descending=N.descending}else G===N.attribute[0]&&(O[x]=z={name:G,sort:{attribute:N.attribute.slice(1),descending:N.descending}})}N.next&&B(N.next)},"applySortingOnSelect");B(A)}else I.iterate=(p[Symbol.asyncIterator]||p[Symbol.iterator]).bind(p),I=I.map(function(L){try{let B=C.call(this,L);return typeof B?.catch=="function"?B.catch(N=>{throw N.partialObject={[t]:L.key},N}):B}catch(B){throw B.partialObject={[t]:L.key},B}});return I}static transformEntryForSelect(p,O,A,y,b,C){if(p&&(p===t||p?.length===1&&p[0]===t&&Array.isArray(p))){let N=a(x=>(O?.transaction?.stale&&(O.transaction.stale=!1),x?.key??x),"transform");return p===t?N:p.asArray?x=>[N(x)]:x=>({[t]:N(x)})}let I;b&&v&&!(typeof p=="string"?[p]:p)?.every(N=>{let x;return typeof N=="object"?x=N.name:x=N,r[x]||x===t})&&(I=!0);let L,B=a(function(N){let x;if(O?.transaction?.stale&&(O.transaction.stale=!1),N!=null){if(x=N.value||N.deref?.()?.value,!x&&(N.key===void 0||N.deref)||N.metadataFlags&un){if(N.metadataFlags&un&&O.replicateFrom===!1&&C&&N.residencyId)return Ga.SKIP;if(N=Ul(N.key??N,O,{transaction:A,lazy:p?.length<4,ensureLoaded:b},this?.isSync,G=>G),N?.then)return N.then(B.bind(this));x=N?.value}if(I&&N?.metadataFlags&(un|Jo)||N?.expiresAt!=null&&N?.expiresAt<Date.now()){if(O.onlyIfCached&&O.noCacheStore)return{[t]:N.key,message:"This entry has expired"};let G=xl(N.key??N,N,O);if(G?.then)return G.then(B)}}if(x==null)return C?Ga.SKIP:x;if(p&&!(p[0]==="*"&&p.length===1)){let G,z=a((F,qe)=>{let Z;typeof F=="object"?Z=F.name:Z=F;let ce=Cn?.[Z],ee;if(ce){let Q=y?.[Z];if(Q)if(Q.hasMappings){let fe=ce.from?x[ce.from]:Kl(N.key);ee=Q.get(fe),ee||(ee=[])}else ee=Q.fromRecord?.(x);else ee=ce(x,O,N);let _e=a(fe=>{if(fe&&typeof fe=="object"){let Ae=ce.definition?.tableClass||Ce;L||(L={});let De=L[Z]||(L[Z]=Ae.transformEntryForSelect(Z===F?null:F.select||(Array.isArray(F)?F:null),O,A,Q,b));if(Array.isArray(fe)){let we=[],dr=Ae.transformToOrderedSelect(fe,F.select,typeof F.sort=="object"&&F.sort,O,A,De)[this.isSync?Symbol.iterator:Symbol.asyncIterator](),Nr=a(Re=>{for(;!Re.done;){if(Re?.then)return Re.then(Nr);we.push(Re.value),Re=dr.next()}qe(we,Z)},"nextValue"),Ps=Nr(dr.next());Ps&&(G||(G=[]),G.push(Ps));return}else if(fe=De.call(this,fe),fe?.then){G||(G=[]),G.push(fe.then(we=>qe(we,Z)));return}}qe(fe,Z)},"handleResolvedValue");ee?.then?(G||(G=[]),G.push(ee.then(_e))):_e(ee);return}else ee=x[Z],ee&&typeof ee=="object"&&Z!==F&&(ee=Ce.transformEntryForSelect(F.select||F,O,A,null)({value:ee}));qe(ee,Z)},"selectAttribute"),ie;if(typeof p=="string")z(p,F=>{ie=F});else if(Array.isArray(p))if(p.asArray)ie=[],p.forEach((F,qe)=>{F==="*"?p[qe]=x:z(F,Z=>ie[qe]=Z)});else{ie={};let F=p.forceNulls;for(let qe of p)if(qe==="*")for(let Z in x)ie[Z]=x[Z];else z(qe,(Z,ce)=>{Z===void 0&&F&&(Z=null),ie[ce]=Z})}else throw new br.ClientError("Invalid select"+p);return G?Promise.all(G).then(()=>ie):ie}return x},"transform");return B}async subscribe(p){if(!l)throw new Error("Can not subscribe to a table without an audit log");g||ut({table:s,database:c,schemaDefined:u,attributes:E,audit:!0}),p||(p={});let O=!p.rawEvents,A=[],y=this,b=JI(Ce,this.getId()??null,function(I,L,B,N){try{let x=L.getValue?.(i,O),G=L.type;if(!x&&G==="patch"&&O){let ie=i.getEntry(I);ie?.version===L.version?x=ie.value:x=L.getValue?.(i,!0,B),G="put"}let z={id:I,localTime:B,value:x,version:L.version,type:G,beginTxn:N};A?A.push(z):this.send(z)}catch(x){xe.default.error?.(x)}},p.startTime||0,p),C=(async()=>{this.isCollection&&(b.includeDescendants=!0,p.onlyChildren&&(b.onlyChildren=!0)),p.supportsTransactions&&(b.supportsTransactions=!0);let I=this.getId(),L=p.previousCount;L>1e3&&(L=1e3);let B=p.startTime;if(this.isCollection){if(B){if(L)throw new br.ClientError("startTime and previousCount can not be combined for a table level subscription");for(let{key:N,value:x}of l.getRange({start:B,exclusiveStart:!0,snapshot:!1})){let G=Nt(x);if(G.tableId!==n)continue;let z=G.recordId;if(I==null||XY(I,z)){let ie=G.getValue(i,O,N);if(b.send({id:z,localTime:N,value:ie,version:G.version,type:G.type}),b.queue?.length>jY&&await b.waitForDrain()===!1)return}b.startTime=N}}else if(L){let N=[];for(let{key:x,value:G}of l.getRange({start:"z",end:!1,reverse:!0}))try{let z=Nt(G);if(z.tableId!==n)continue;let ie=z.recordId;if(I==null||XY(I,ie)){let F=z.getValue(i,O,x);if(N.push({id:ie,localTime:x,value:F,version:z.version,type:z.type}),--L<=0)break}}catch(z){xe.default.error("Error getting history entry",x,z)}for(let x=N.length;x>0;)b.send(N[--x]);N[0]&&(b.startTime=N[0].localTime)}else if(!p.omitCurrent){for(let{key:N,value:x,version:G,localTime:z}of i.getRange({start:I??!1,end:I==null?void 0:[I,Al.MAXIMUM_KEY],versions:!0,snapshot:!1}))if(x&&(b.send({id:N,localTime:z,value:x,version:G,type:"put"}),b.queue?.length>jY&&await b.waitForDrain()===!1))return}}else{L&&!B&&(B=0);let N=this.#r?.localTime;if(N===ZA&&(i.cache?.delete(I),this.#r=i.getEntry(I),xe.default.trace?.("re-retrieved record",N,this.#r?.localTime),N=this.#r?.localTime),xe.default.trace?.("Subscription from",B,"from",I,N),B<N){let x=[],G=N;do{let z=l.get(G);if(z){p.omitCurrent=!0;let ie=Nt(z),F=ie.getValue(i,O,G);O&&(ie.type="put"),x.push({id:I,value:F,localTime:G,...ie}),G=ie.previousLocalTime}else break;L&&L--}while(G>B&&L!==0);for(let z=x.length;z>0;)b.send(x[--z]);b.startTime=N}!p.omitCurrent&&this.doesExist()&&b.send({id:I,localTime:N,value:this.#e,version:this.#n,type:"put"})}for(let N of A)b.send(N);A=null})();return p.listener&&b.on("data",p.listener),b}static subscribeOnThisThread(p,O){return p===0||O?.crossThreads===!1}doesExist(){return!!(this.#e||this.#s)}publish(p,O){this._writePublish(p,O)}_writePublish(p,O){let A=Gr(this.getContext()),y=this.getId()||null;y!=null&&Or(y);let b=this.getContext();A.addWrite({key:y,store:i,entry:this.#r,nodeName:b?.nodeName,validate:a(()=>{b?.source||(A.checkOverloaded(),this.validate(p))},"validate"),before:Te.publish?.bind(this,b,y,p),beforeIntermediate:ye.publish?.bind(this,b,y,p),commit:a((C,I,L)=>{I===void 0&&R&&!g&&Vi(),xe.default.trace?.(`Publishing message to id: ${y}, timestamp: ${new Date(C).toISOString()}`),T(y,I?.value??null,I,I?.version||C,0,!0,{user:b?.user,residencyId:O?.residencyId,expiresAt:b?.expiresAt,nodeId:O?.nodeId},"message",!1,p)},"commit")})}validate(p,O){let A,y=a((b,C,I)=>{if(C.type&&b!=null)if(O&&b.__op__&&(b=b.value),C.properties){typeof b!="object"&&(A||(A=[])).push(`Value ${Ns(b)} in property ${I} must be an object${C.type?" ("+C.type+")":""}`);let L=C.properties;for(let B=0,N=L.length;B<N;B++){let x=L[B],G=y(b[x.name],x,I+"."+x.name);G&&(b[x.name]=G)}if(C.sealed&&b!=null&&typeof b=="object")for(let B in b)L.find(N=>N.name===B)||(A||(A=[])).push(`Property ${B} is not allowed within object in property ${I}`)}else switch(C.type){case"Int":(typeof b!="number"||b>>0!==b)&&(A||(A=[])).push(`Value ${Ns(b)} in property ${I} must be an integer (from -2147483648 to 2147483647)`);break;case"Long":(typeof b!="number"||!(Math.floor(b)===b&&Math.abs(b)<=9007199254740992))&&(A||(A=[])).push(`Value ${Ns(b)} in property ${I} must be an integer (from -9007199254740992 to 9007199254740992)`);break;case"Float":typeof b!="number"&&(A||(A=[])).push(`Value ${Ns(b)} in property ${I} must be a number`);break;case"ID":typeof b=="string"||b?.length>0&&b.every?.(L=>typeof L=="string")||(A||(A=[])).push(`Value ${Ns(b)} in property ${I} must be a string, or an array of strings`);break;case"String":typeof b!="string"&&(A||(A=[])).push(`Value ${Ns(b)} in property ${I} must be a string`);break;case"Boolean":typeof b!="boolean"&&(A||(A=[])).push(`Value ${Ns(b)} in property ${I} must be a boolean`);break;case"Date":if(!(b instanceof Date)){if(typeof b=="string"||typeof b=="number")return new Date(b);(A||(A=[])).push(`Value ${Ns(b)} in property ${I} must be a Date`)}break;case"BigInt":if(typeof b!="bigint"){if(typeof b=="string"||typeof b=="number")return BigInt(b);(A||(A=[])).push(`Value ${Ns(b)} in property ${I} must be a bigint`)}break;case"Bytes":if(!(b instanceof Uint8Array)){if(typeof b=="string")return Buffer.from(b);(A||(A=[])).push(`Value ${Ns(b)} in property ${I} must be a Buffer or Uint8Array`)}break;case"Blob":if(!(b instanceof mi)){if(typeof b=="string"&&(b=Buffer.from(b)),b instanceof Buffer)return createBlob(b,{type:"text/plain"});(A||(A=[])).push(`Value ${Ns(b)} in property ${I} must be a Blob`)}break;case"array":if(Array.isArray(b)){if(C.elements)for(let L=0,B=b.length;L<B;L++){let N=b[L],x=y(N,C.elements,I+"[*]");x&&(b[L]=x)}}else(A||(A=[])).push(`Value ${Ns(b)} in property ${I} must be an Array`);break}C.nullable===!1&&b==null&&(A||(A=[])).push(`Property ${I} is required (and not does not allow null values)`)},"validateValue");for(let b=0,C=E.length;b<C;b++){let I=E[b];if(!(I.relationship||I.computed)&&(!O||I.name in p)){let L=y(p[I.name],I,I.name);L&&(p[I.name]=L)}}if(d)for(let b in p)E.find(C=>C.name===b)||(A||(A=[])).push(`Property ${b} is not allowed`);if(A)throw new br.ClientError(A.join(". "))}getUpdatedTime(){return this.#n}wasLoadedFromSource(){return v?!!this.#i:void 0}static async addAttributes(p){let O=E.slice(0);for(let A of p){if(!A.name)throw new br.ClientError("Attribute name is required");if(A.name.match(/[`/]/))throw new br.ClientError("Attribute names cannot include backticks or forward slashes");(0,tW.validateAttribute)(A.name),O.push(A)}return ut({table:s,database:c,schemaDefined:u,attributes:O}),Ce.indexingOperation}static async removeAttributes(p){let O=E.filter(A=>!p.includes(A.name));return ut({table:s,database:c,schemaDefined:u,attributes:O}),Ce.indexingOperation}static getSize(){let p=i.getStats();return(p.treeBranchPageCount+p.treeLeafPageCount+p.overflowPages)*p.pageSize}static getAuditSize(){let p=l?.getStats();return p&&(p.treeBranchPageCount+p.treeLeafPageCount+p.overflowPages)*p.pageSize}static getStorageStats(){let p=i.env.path,O=sT.default.statfsSync?.(p)??{};return{available:O.bavail*O.bsize,free:O.bfree*O.bsize,size:O.blocks*O.bsize}}static async getRecordCount(p){let O=i.getStats().entryCount,A=1e3/2,y=performance.now(),b=Math.floor(O/2),C=p?.exactCount,I=0,L=0,B;for(let{value:N}of i.getRange({start:!0,lazy:!0,snapshot:!1}))if(N!=null&&I++,L++,await Fa(),!C&&L<b&&performance.now()-y>A){B=L;break}if(B){let N=I;I=0;for(let{value:ee}of i.getRange({start:"\uFFFF",reverse:!0,lazy:!0,limit:B,snapshot:!1}))ee!=null&&I++,await Fa();let x=B*2,G=(I+N)/x,z=Math.pow((I-N+1)/B/2,2)+G*(1-G)/x,ie=Math.max(Math.sqrt(z)*O,1),F=Math.round(G*O),qe=Math.max(F-1.96*ie,I+N),Z=Math.min(F+1.96*ie,O),ce=Math.pow(10,Math.round(Math.log10(ie)));return ce>F&&(ce=ce/10),I=Math.round(F/ce)*ce,{recordCount:I,estimatedRange:[Math.round(qe),Math.round(Z)]}}return{recordCount:I}}static updatedAttributes(){Cn=this.propertyResolvers={$id:a((p,O,A)=>({value:A.key}),"$id"),$updatedtime:a((p,O,A)=>A.version,"$updatedtime"),$record:a((p,O,A)=>A?{value:p}:p,"$record")};for(let p of this.attributes){p.isPrimaryKey&&(H=p),p.resolve=null;let O=p.relationship,A=p.computed;if(O)if(p.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)"),Ml=!0,O.to)p.elements?.definition?(Cn[p.name]=p.resolve=(y,b,C)=>{let I=y[O.from?O.from:t],L=p.elements.definition.tableClass;return C?Vl({attribute:O.to,value:I},Gr(b).getReadTxn(),!1,L,!1).asArray:L.search([{attribute:O.to,value:I}],b).asArray},p.set=()=>{throw new Error("Setting a one-to-many relationship property is not supported")},p.resolve.definition=p.elements.definition,O.from&&(p.resolve.from=O.from)):console.error(`The one-to-many/many-to-many relationship property "${p.name}" in table "${s}" must have an array type referencing a table as the elements`);else if(O.from){let y=p.definition||p.elements?.definition;y?(Cn[p.name]=p.resolve=(b,C,I)=>{let L=b[O.from];if(L!==void 0){if(p.elements){let B,N=L?.map(x=>{let G=I?y.tableClass.primaryStore.getEntry(x,{transaction:Gr(C).getReadTxn()}):y.tableClass.get(x,C);return G?.then&&(B=!0),G});return O.filterMissing?B?Promise.all(N).then(x=>x.filter(ZY)):N.filter(ZY):B?Promise.all(N):N}return I?y.tableClass.primaryStore.getEntry(L,{transaction:Gr(C).getReadTxn()}):y.tableClass.get(L,C)}},p.set=(b,C)=>{if(Array.isArray(C)){let I=C.map(L=>L.getId?.()||L[y.tableClass.primaryKey]);b[O.from]=I}else{let I=C.getId?.()||C[y.tableClass.primaryKey];b[O.from]=I}},p.resolve.definition=p.definition||p.elements?.definition,p.resolve.from=O.from):console.error(`The relationship property "${p.name}" in table "${s}" must be a type that references a table`)}else console.error(`The relationship directive on "${p.name}" in table "${s}" must use either "from" or "to" arguments`);else A&&(typeof A.from=="function"&&this.setComputedAttribute(p.name,A.from),Cn[p.name]=p.resolve=(y,b,C)=>{let I=typeof A.from=="string"?y[A.from]:y,L=this.userResolvers[p.name];if(L)return L(I,b,C);xe.default.warn(`Computed attribute "${p.name}" does not have a function assigned to it. Please use setComputedAttribute('${p.name}', resolver) to assign a resolver function.`),this.userResolvers[p.name]=()=>{}})}zp(this,this)}static setComputedAttribute(p,O){let A=fi(E,p);if(!A){console.error(`The attribute "${p}" does not exist in the table "${s}"`);return}if(!A.computed){console.error(`The attribute "${p}" is not defined as computed in the table "${s}"`);return}this.userResolvers[p]=O}static async deleteHistory(p=0,O=!1){let A;for(let{key:y,value:b}of l.getRange({start:0,end:p}))await Fa(),Nt(b).tableId===n&&(A=rT(l,y,b));if(O)for(let y of i.getRange({start:0,versions:!0})){let{key:b,value:C,localTime:I}=y;await Fa(),C===null&&I<p&&(A=hc(i,y))}await A}static async*getHistory(p=0,O=1/0){for(let{key:A,value:y}of l.getRange({start:p||1,end:O})){await Fa();let b=Nt(y);b.tableId===n&&(yield{id:b.recordId,localTime:A,version:b.version,type:b.type,value:b.getValue(i,!0,A),user:b.user,operation:b.originatingOperation})}}static async getHistoryOfRecord(p){let O=[];if(p==null)throw new Error("An id is required");let A=i.getEntry(p);if(!A)return O;let y=A.localTime;if(!y)throw new Error("The entry does not have a local audit time");let b=0;do{await Fa();let C=l.get(y);if(C){let I=Nt(C);O.push({id:I.recordId,localTime:y,version:I.version,type:I.type,value:I.getValue(i,!0,y),user:I.user}),y=I.previousLocalTime}else break}while(b<1e3&&y);return O.reverse()}static cleanup(){Y?.remove()}}Ce.updatedAttributes();let Fd=Ce.prototype;return m&&Ce.setTTLExpiration(m/1e3),se&&Em(),Ce;function sn(K,p,O){let A;for(let y in r){let b=r[y],C=b.isIndexing,I=Cn[y],L=O&&(I?I(O):O[y]),B=p&&(I?I(p):p[y]);if(L===B&&!C)continue;A=!0;let N=b.indexNulls,x=(0,kh.getIndexedValues)(L,N),G=(0,kh.getIndexedValues)(B,N);if(G?.length>0){let z=new Set(G);if(x=x?x.filter(ie=>{if(z.has(ie))z.delete(ie);else return!0}):[],G=Array.from(z),(G.length>0||x.length>0)&&WY){let ie=G.concat(x).map(F=>({key:F,value:K}));b.prefetch(ie,JY)}for(let ie=0,F=G.length;ie<F;ie++)b.remove(G[ie],K)}else x?.length>0&&WY&&b.prefetch(x.map(z=>({key:z,value:K})),JY);if(x)for(let z=0,ie=x.length;z<ie;z++)b.put(x[z],K)}return A}a(sn,"updateIndices");function Or(K){switch(typeof K){case"number":return!0;case"string":if(K.length<659)return!0;if(K.length>QY)throw new Error("Primary key size is too large: "+K.length);break;case"object":if(K===null)throw new Error("Invalid primary key of null");break;case"bigint":if(K<2n**64n&&K>-(2n**64n))return!0;break;default:throw new Error("Invalid primary key type: "+typeof K)}if((0,Al.writeKey)(K,Gme,0)>QY)throw new Error("Primary key size is too large: "+K.length);return!0}a(Or,"checkValidId");function Ul(K,p,O,A,y){if(Ce.getResidencyById&&O.ensureLoaded&&p?.replicateFrom!==!1){let C=Ki(Ce.getResidencyById(K));if(C&&!C.includes(server.hostname)&&w)return w({key:K,residency:C}).then(y)}let b=a(()=>{if(p?.transaction?.stale&&(p.transaction.stale=!1),O.transaction?.isDone)return y(null,K);let C=i.getEntry(K,O);return C?.residencyId&&C.metadataFlags&un&&w&&O.ensureLoaded&&p?.replicateFrom!==!1?w(C).then(I=>y(I,K),I=>(xe.default.error?.("Error loading remote record",K,C,O,I),y(null,K))):(C&&p&&(C?.version>(p.lastModified||0)&&(p.lastModified=C.version),C?.localTime&&!p.lastRefreshed&&(p.lastRefreshed=C.localTime)),y(C,K))},"whenPrefetched");return A?b():oe>0?(oe--,b()):new Promise((C,I)=>{oe===0?(oe--,i.prefetch([K],()=>{L(),B()})):(ne.push(K),ue.push(B),ne.length>pm&&(oe--,L()));function L(){if(ne.length>0){let N=ue;i.prefetch(ne,()=>{oe===-1?L():oe++;for(let x of N)x()}),ne=[],ue=[],pe>2&&pe--}else oe=pe,pe<kd&&pe++}a(L,"prefetch");function B(){try{C(b())}catch(N){I(N)}}a(B,"load")})}a(Ul,"loadLocalRecord");function Fr(K){if(!K?.role)return;let p=K.role.permission;if(p.super_user)return qme;let O=p[c],A,y=O?.tables;if(y)return y[s];if(c==="data"&&(A=p[s])&&!A.tables)return A}a(Fr,"getTablePermissions");function xl(K,p,O,A){if(v){let y=!1;if(O.noCache?y=!0:(p?(!p.value||p.metadataFlags&(un|Jo)||p.expiresAt!=null&&p.expiresAt<Date.now())&&(y=!0):y=!0,Kn(!y,"cache-hit",s)),y){let b=qd(K,p,O).then(C=>(C?.value&&C?.value.getRecord?.()&&xe.default.error?.("Can not assign a record that is already a resource"),O&&(C?.version>(O.lastModified||0)&&(O.lastModified=C.version),O.lastRefreshed=Date.now()),C));if(O?.onlyIfCached||p?.value&&A?.allowStaleWhileRevalidate?.(p,K)){if(b.catch(C=>xe.default.warn?.(C)),O?.onlyIfCached&&!A.doesExist())throw new br.ServerError("Entry is not cached",504);return}else return b}}else if(p?.value&&p.expiresAt!=null&&p.expiresAt<Date.now())return Ce.evict(p.key,p.value,p.version),p.value=null,{then(y){return y(p)}}}a(xl,"ensureLoadedFromSource");function Gr(K){let p=K?.transaction;if(p){if(!p.lmdbDb)return p.lmdbDb=i,p;do{if(p.lmdbDb?.path===i.path)return p;let O=p.next;if(!O)return p=p.next=new nc,p.lmdbDb=i,p;p=O}while(!0)}else return new Hm}a(Gr,"txnForContext");function Bl(K,p,O){if(!K)return;let A=K.value||i.getEntry(K.key)?.value;if(typeof p=="object"){let b=Cn,C=A;for(let I=0,L=p.length;I<L;I++){let B=p[I],N=b?.[B];C=N&&C?N(C,O,!0)?.value:C?.[B],b=N?.definition?.tableClass?.propertyResolvers}return C}let y=Cn[p];return y?y(A,O):A[p]}a(Bl,"getAttributeValue");function Gd(K,p,O,A,y){let b=y?.length,C={transaction:A,lazy:b>0||typeof p=="string"||p?.length<4,alwaysPrefetch:!0},I;function L(B,N){let x=B?.value;if(!x)return Ga.SKIP;for(let G=0;G<b;G++)if(!I?.includes(G)&&!y[G](x,B))return Ga.SKIP;return N!==void 0&&(B.key=N),B}if(a(L,"processEntry"),b>0||!K.hasEntries){let B=K.map(N=>{if(I=null,typeof N=="object"&&N?.key!==void 0)return b>0?L(N):N;if(N==null)return Ga.SKIP;for(let x=0;x<b;x++){let z=y[x].idFilter;if(z){if(!z(N))return Ga.SKIP;I||(I=[]),I.push(x)}}return Ul(N,O,C,!1,L)});return Array.isArray(K)&&(B=B.filter(N=>N!==Ga.SKIP)),B.hasEntries=!0,B}return K}a(Gd,"transformToEntries");function $i(K,p,O=server.replication?.getThisNodeId(l)){if(K<=p?.version){if(p?.version===K&&O!==void 0){let A=server.replication?.exportIdMapping(l),y=p.localTime,b=y&&l.get(y);if(b){let C,I,L=Nt(b);for(let B in A)A[B]===O&&(C=B),A[B]===L.nodeId&&(I=B);if(C>I)return 1;if(C===I)return 0}}return-1}return 1}a($i,"precedesExistingVersion");async function qd(K,p,O){let A=p?.metadataFlags,y=p?.version,b,C;if(!i.attemptLock(K,y,()=>{clearTimeout(C);let N=i.getEntry(K);!N||!N.value||N.metadataFlags&(un|Jo)?b(qd(K,i.getEntry(K),O)):b(N)}))return new Promise(N=>{b=N,C=setTimeout(()=>{i.unlock(K,y)},kme)});let I=p?.value,L={requestContext:O,replacingRecord:I,replacingEntry:p,replacingVersion:y,noCacheStore:!1,source:null,resourceCache:O?.resourceCache},B=O?.responseHeaders;return new Promise((N,x)=>{let G;ZI(Ot(L,async z=>{let ie=performance.now(),F,qe,Z;try{for(let _e of Ce.sources)if(_e.get&&(!_e.get.reliesOnPrototype||_e.prototype.get)){if(_e.available?.(p)===!1)continue;if(L.source=_e,F=await _e.get(K,L),F)break}Z=A&un;let ee=L.lastModified||Z&&y;qe=Z||ee>y||!I,ee||(ee=(0,kh.getNextMonotonicTime)());let Q=performance.now()-ie;if(er(Q,"cache-resolution",s,null,"success"),B&&aE(B,"Server-Timing",`cache-resolve;dur=${Q.toFixed(2)}`,!0),z.timestamp=ee,m&&L.expiresAt==null&&(L.expiresAt=Date.now()+m),F){if(typeof F!="object")throw new Error("Only objects can be cached and stored in tables");if(F.status>0&&F.headers)if(F.status>=300)if(F.status===304)F=I,ee=y;else throw new br.ServerError(F.body||"Error from source",F.status);else F=F.body;typeof F.toJSON=="function"&&(F=F.toJSON()),t&&F[t]!==K&&(F[t]=K)}G=!0,N({key:K,version:ee,value:F})}catch(ee){ee.message+=` while resolving record ${K} for ${s}`,I&&((ee.code==="ECONNRESET"||ee.code==="ECONNREFUSED"||ee.code==="EAI_AGAIN")&&!O?.mustRevalidate||O?.staleIfError&&(ee.statusCode===500||ee.statusCode===502||ee.statusCode===503||ee.statusCode===504))?(N({key:K,version:y,value:I}),xe.default.trace?.(ee.message,"(returned stale record)")):x(ee);let Q=performance.now()-ie;er(Q,"cache-resolution",s,null,"fail"),B&&aE(B,"Server-Timing",`cache-resolve;dur=${Q.toFixed(2)}`,!0),L.transaction.abort();return}if(O?.noCacheStore||L.noCacheStore){L.transaction.abort();return}Gr(L).addWrite({key:K,store:i,entry:p,nodeName:"source",commit:a((ee,Q)=>{if(Q?.version!==y)return;let _e=sn(K,I,F);if(F){ye.put?.(L,K,F),Q&&(O.previousResidency=Ce.getResidencyRecord(Q.residencyId));let fe,Ae=!1,De,we=Ki(Ce.getResidency(F,O));if(we){if(!we.includes(server.hostname))if(fe=F,Ae=!0,Ce.getResidencyById)F=void 0;else{F=null;for(let dr in r)F||(F={}),F[dr]=fe[dr]}De=Za(we)}xe.default.trace?.(`Writing resolved record from source with id: ${K}, timestamp: ${new Date(ee).toISOString()}`),T(K,F,Q,ee,Ae?un:0,g&&(qe||Ae)||null,{user:L?.user,expiresAt:L.expiresAt,residencyId:De},"put",!!Z,fe)}else Q&&(ye.delete?.(L,K),xe.default.trace?.(`Deleting resolved record from source with id: ${K}, timestamp: ${new Date(ee).toISOString()}`),g||R?T(K,null,Q,ee,0,g&&qe||null,{user:L?.user},"delete",!!Z):hc(i,Q,y))},"commit")})}),()=>{i.unlock(K,y)},z=>{i.unlock(K,y),G&&xe.default.error?.("Error committing cache update",z)})})}a(qd,"getFromSource");function Hl(K){if(!K||K.user?.role?.permission?.super_user)return!0;if(K.replicateTo)throw new br.ClientError("Can not specify replication parameters without super user permissions",403);if(K.replicatedConfirmation)throw new br.ClientError("Can not specify replication confirmation without super user permissions",403);return!0}a(Hl,"checkContextPermissions");function Vi(K){let p=!1;if(K&&(K-lt>1&&(p=!0),lt=K),!(Qt===Tr&&!p)&&(Tr=Qt,(0,Sl.getWorkerIndex)()===(0,Sl.getWorkerCount)()-1))return ss&&clearTimeout(ss),Qt?new Promise(O=>{let A=new Date;A.setMonth(0),A.setDate(1),A.setHours(0),A.setMinutes(0),A.setSeconds(0);let y=Qt/(1+lt),b=p?Date.now():Math.ceil((Date.now()-A.getTime())/y)*y+A.getTime(),C=a(I=>{xe.default.trace?.(`Scheduled next cleanup scan at ${new Date(I)}`),ss=setTimeout(()=>q=q.then(async()=>{if(C(Math.max(I+Qt,Date.now())),i.rootStore.status!=="open"){clearTimeout(ss);return}let L=50,B=new Array(L),N=0,x=Math.pow(lt,8)*(Tl.get(U.STORAGE_RECLAMATION_EVICTIONFACTOR)??1e5),G=S/Math.pow(Math.max(lt,1),4);xe.default.info?.(`Starting cleanup scan for ${s}, evict threshold ${x}, adjusted eviction ${G}ms`);function z(ie,F,qe,Z){let ce=ie+G-Date.now();if(ce<0)return!0;if(lt){let ee=i.lastSize;return qe&fn&&bd(Z,Q=>{Q.size&&(ee+=Q.size)}),xe.default.trace?.(`shouldEvict adjusted ${ce} ${ee}, ${ce*(ie-F)/ee} < ${x}`),ce*(ie-F)/ee<x}return!1}a(z,"shouldEvict");try{let ie=0;for(let F of i.getRange({start:!1,snapshot:!1,versions:!0,lazy:!0})){let{key:qe,value:Z,version:ce,expiresAt:ee,metadataFlags:Q}=F,_e;Z===null&&!g&&ce+Hme<Date.now()?_e=hc(i,F,ce):ee!=null&&z(ee,ce,Q,Z)&&(_e=Ce.evict(qe,Z,ce),ie++),_e&&(await B[N],B[N]=_e.catch(fe=>{xe.default.error?.("Cleanup error",fe)}),++N>=L&&(N=0)),await Fa()}xe.default.info?.(`Finished cleanup scan for ${s}, evicted ${ie} entries`)}catch(ie){xe.default.warn?.(`Error in cleanup scan for ${s}:`,ie)}O(void 0),lt=0}),Math.min(I-Date.now(),2147483647)).unref()},"startNextTimer");C(b)}):void 0}a(Vi,"scheduleCleanup");function $d(){Y=l?.addDeleteRemovalCallback(n,i,(K,p)=>{i.remove(K,p)})}a($d,"addDeleteRemoval");function Em(){(0,Sl.getWorkerIndex)()===0&&setInterval(async()=>{if(!vl){vl=!0;try{let K=se.name,p=r[K];if(!p)throw new Error(`expiresAt attribute ${se} must be indexed`);for(let O of p.getRange({start:!0,values:!1,end:Date.now(),snapshot:!1})){for(let A of p.getValues(O)){let y=i.getEntry(A);y?.value?y.value[K]<Date.now()&&Ce.evict(A,y.value,y.version):i.ifVersion(A,y?.version,()=>p.remove(O,A))}await Fa()}}catch(K){xe.default.error?.("Error in evicting old records",K)}finally{vl=!1}}},Bme).unref()}a(Em,"runRecordExpirationEviction");function Ki(K){if(K!=null){if(Array.isArray(K))return K;if(typeof K=="number"){if(K>=65536)throw new Error(`Shard id ${K} must be below 65536`);let p=server.shards?.get?.(K);if(p)return xe.default.trace?.(`Shard ${K} mapped to ${p.map(O=>O.name).join(", ")}`),p.map(O=>O.name);throw new Error(`Shard ${K} is not defined`)}throw new Error(`Shard or residency list ${K} is not a valid type, must be a shard number or residency list of node hostnames`)}}a(Ki,"residencyFromFunction");function Za(K){if(K){let p=K.join(","),O=f.get([Symbol.for("residency_by_set"),p]);return O||(f.put([Symbol.for("residency_by_set"),p],O=Math.floor(Math.random()*2147418112)+65535),f.put([Symbol.for("residency_by_id"),O],K),O)}}a(Za,"getResidencyId")}function XI(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 JY(){}function $me(e){rW=e}function iT(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 nT(parseInt(e.slice(1),36));if(e==="null")return null;if(!/^-?[0-9]+$/.test(e)&&!(e instanceof Date))throw new SyntaxError;return nT(+e);case"Float":return e==="null"?null:nT(+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;Vme.test(e)||(e+="Z");let n=new Date(e);return nT(n.getTime()),n}return new Date(+e);case void 0:case"Any":return(0,oT.autoCast)(e);default:return e}}catch(n){throw n.message=`Invalid value for attribute ${t.name}: "${e}", expecting ${r}`,n.statusCode=400,n}}function nT(e){if(isNaN(e))throw new SyntaxError;return e}function XY(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 ZI(e,t,r){return e?.then?e.then(t,r):t(e)}function ZY(e){return e!=null}function Ns(e){try{return JSON.stringify(e)}catch{return e}}function Kme(e){let t=process.pid;return e.env.readerList().slice(1).some(r=>+r.match(/\d+/)?.[0]!=t)}var Ga,kh,eW,tW,Tl,br,Fh,Gh,xe,Al,Sl,oT,sT,xme,rW,Bme,Hme,WY,kme,zY,Fme,un,Jo,Gme,QY,jY,qme,oMe,Vme,Fa,df=be(()=>{k();Ga=require("lmdb"),kh=M(an()),eW=require("lodash"),tW=M(sf());Xo();km();Tl=M(le());bO();br=M(me()),Fh=M(ao()),Gh=M(qs());ve();uf();xe=M(_i());jy();sc();Al=require("ordered-binary"),Sl=M(tt());Zi();oT=M(ae());Xl();Ni();Vp();__();sT=M(require("node:fs"));cs();XS();xme=new Uint8Array(9);xme[8]=192;Bme=6e4,Hme=864e5;Tl.initSync();WY=Tl.get(U.STORAGE_PREFETCHWRITES),kme=1e4,zY=1,Fme=2,un=1,Jo=8,Gme=Buffer.allocUnsafeSlow(8192),QY=1978,jY=100,qme={read:!0,insert:!0,update:!0,delete:!0,isSuperUser:!0},oMe=(0,oT.convertToMS)(Tl.get(U.CLUSTERING_LEAFSERVER_STREAMS_MAXAGE))||864e5;a(aT,"makeTable");a(XI,"attributesAsObject");a(JY,"noop");a($me,"setServerUtilities");Vme=/[+-][0-9]{2}:[0-9]{2}|[a-zA-Z]$/;a(iT,"coerceType");a(nT,"rejectNaN");a(XY,"isDescendantId");Fa=a(()=>new Promise(setImmediate),"rest");a(ZI,"when");a(ZY,"exists");a(Ns,"stringify");a(Kme,"hasOtherProcesses")});var it={};Ue(it,{database:()=>_u,database_envs:()=>Po,databases:()=>Ve,dropDatabase:()=>tb,dropTableMeta:()=>jme,getDatabases:()=>je,getDefaultCompression:()=>Fg,getTables:()=>Yme,onRemovedDB:()=>v_,onUpdatedTable:()=>jc,readMetaDb:()=>qh,resetDatabases:()=>ed,table:()=>ut,tables:()=>Vn});function Yme(){return dT||je(),Vn||{}}function je(){if(dT)return Ve;dT=!0,wd=new Map;let e=(0,Wt.getHdbBasePath)()&&(0,Dt.join)((0,Wt.getHdbBasePath)(),tc),t=(0,Wt.get)(U.DATABASES)||{};if(process.env.SCHEMAS_DATA_PATH&&(t.data={path:process.env.SCHEMAS_DATA_PATH}),e=process.env.STORAGE_PATH||(0,Wt.get)(U.STORAGE_PATH)||e&&((0,Xn.existsSync)(e)?e:(0,Dt.join)((0,Wt.getHdbBasePath)(),ym)),!e)return;if((0,Xn.existsSync)(e))for(let n of(0,Xn.readdirSync)(e,{withFileTypes:!0})){let s=(0,Dt.basename)(n.name,".mdb");n.isFile()&&(0,Dt.extname)(n.name).toLowerCase()===".mdb"&&!t[s]?.path&&qh((0,Dt.join)(e,n.name),null,s)}if((0,Xn.existsSync)((0,Nd.getBaseSchemaPath)())){for(let n of(0,Xn.readdirSync)((0,Nd.getBaseSchemaPath)(),{withFileTypes:!0}))if(!n.isFile()){let s=(0,Dt.join)((0,Nd.getBaseSchemaPath)(),n.name),i=(0,Dt.join)((0,Nd.getTransactionAuditStoreBasePath)(),n.name);for(let o of(0,Xn.readdirSync)(s,{withFileTypes:!0}))if(o.isFile()&&(0,Dt.extname)(o.name).toLowerCase()===".mdb"){let c=(0,Dt.join)(i,o.name);qh((0,Dt.join)(s,o.name),(0,Dt.basename)(o.name,".mdb"),n.name,c,!0)}}}if(t)for(let n in t){let s=t[n],i=s.path;if((0,Xn.existsSync)(i))for(let c of(0,Xn.readdirSync)(i,{withFileTypes:!0}))c.isFile()&&(0,Dt.extname)(c.name).toLowerCase()===".mdb"&&qh((0,Dt.join)(i,c.name),(0,Dt.basename)(c.name,".mdb"),n);let o=s.tables;if(o)for(let c in o){let l=o[c],u=(0,Dt.join)(l.path,(0,Dt.basename)(c+".mdb"));(0,Xn.existsSync)(u)&&qh(u,c,n,null,!0)}}for(let n in Ve){let s=wd.get(n);if(s){let i=Ve[n];n.includes("delete")&&Lt.trace(`defined tables ${Array.from(s.keys())}`);for(let o in i)s.has(o)||(Lt.trace(`delete table class ${o}`),delete i[o])}else if(delete Ve[n],n==="data"){for(let i in Vn)delete Vn[i];delete Vn[fT]}}let r=["hdb_temp","hdb_certificate","hdb_analytics","hdb_raw_analytics","hdb_session_will","hdb_job","hdb_license","hdb_info"];if(Ve.system)for(let n of r)Ve.system[n]&&(Ve.system[n].replicate=!1);return wd=null,Ve}function ed(){dT=!1;for(let[,e]of Po)e.needsDeletion=!0;je();for(let[e,t]of Po)t.needsDeletion&&!e.endsWith("system.mdb")&&(t.close(),Po.delete(e),delete Ve[t.databaseName],Vh.forEach(r=>r(t.databaseName)));return Ve}function qh(e,t,r=rC,n,s){let i=new eC.default(e,!1);try{let o=Po.get(e);o?o.needsDeletion=!1:(o=(0,Id.open)(i),Po.set(e,o));let c=new Rl.default(!1),l=o.dbisDb||(o.dbisDb=o.openDB(cT.INTERNAL_DBIS_NAME,c)),u=o.auditStore;u||(n?(0,Xn.existsSync)(n)&&(i.path=n,u=(0,Id.open)(i),u.isLegacy=!0):u=tT(o));let f=oW(r),d=f[fT],_=new Map;for(let{key:h,value:m}of l.getRange({start:!1})){let[S,g]=h.toString().split("/");g===""?g=m.name:g||(g=S,S=t,m.name||(m.name=g,m.indexed=!m.is_hash_attribute)),d?.add(S);let R=_.get(S);R||_.set(S,R={attributes:[]}),(g==null||m.is_hash_attribute)&&(R.primary=m),g!=null&&R.attributes.push(m),Object.defineProperty(m,"key",{value:h,configurable:!0})}for(let[h,m]of _){let{attributes:S,primary:g}=m;if(!g){for(let oe of S)if(oe.is_hash_attribute||oe.isPrimaryKey){g=oe;break}if(!g){Lt.warn(`Unable to find a primary key attribute on table ${h}, with attributes: ${JSON.stringify(S)}`);continue}}let R=f[h],E={},T=[],w,v,H=typeof g.audit=="boolean"?g.audit:(0,Wt.get)(U.LOGGING_AUDITLOG),q=g.trackDeletes,W=g.expiration,te=g.eviction,se=g.sealed,Y=g.splitSegments,ne=g.replicate;if(R)E=R.indices,T=R.attributes,R.schemaVersion++;else{w=g.tableId,w?w>=(l.get(Od)||0)&&(l.putSync(Od,w+1),Lt.info(`Updating next table id (it was out of sync) to ${w+1} for ${h}`)):(g.tableId=w=l.get(Od),w||(w=1),Lt.debug("Table {table_name} missing an id, assigning {table_id}"),l.putSync(Od,w+1),l.putSync(g.key,g));let oe=new Rl.default(!g.is_hash_attribute,g.is_hash_attribute);if(oe.compression=g.compression,oe.compression){let pe=(0,Wt.get)(U.STORAGE_COMPRESSION_THRESHOLD)||iW;oe.compression.threshold=pe}v=sp(o.openDB(g.key,oe),o),o.databaseName=r,v.tableId=w}let ue;for(let oe of S){oe.attribute=oe.name;try{if(!oe.is_hash_attribute&&(oe.indexed||oe.attribute&&!oe.name)){if(!E[oe.name]){let Te=new Rl.default(!oe.is_hash_attribute,oe.is_hash_attribute);E[oe.name]=o.openDB(oe.key,Te),E[oe.name].indexNulls=oe.indexNulls}let pe=T.find(Te=>Te.name===oe.name);pe?T.splice(T.indexOf(pe),1,oe):T.push(oe),ue=!0}}catch(pe){Lt.error("Error trying to update attribute",oe,T,E,pe)}}for(let oe of T)if(!S.find(Te=>Te.name===oe.name)){if(oe.is_hash_attribute){Lt.error("Unable to remove existing primary key attribute",oe);continue}oe.indexed&&(T.splice(T.indexOf(oe),1),ue=!0)}if(R)ue&&(R.schemaVersion++,R.updatedAttributes());else{R=aW(f,h,aT({primaryStore:v,auditStore:u,audit:H,sealed:se,splitSegments:Y,replicate:ne,expirationMS:W&&W*1e3,evictionMS:te&&te*1e3,trackDeletes:q,tableName:h,tableId:w,primaryKey:g.name,databasePath:s?r+"/"+h:r,databaseName:r,indices:E,attributes:S,schemaDefined:g.schemaDefined,dbisDB:l})),R.schemaVersion=1;for(let oe of $h)oe(R)}}return o}catch(o){throw o.message+=` opening database ${e}`,o}}function oW(e){let t=Ve[e];if(t||(e==="data"?t=Ve[e]=Vn:e==="system"?Object.defineProperty(Ve,"system",{value:t=Object.create(null),configurable:!0}):t=Ve[e]=Object.create(null)),wd&&!wd.has(e)){let r=new Set;t[fT]=r,wd.set(e,r)}return t}function aW(e,t,r){return e[t]=r,r}function _u({database:e,table:t}){e||(e=rC),je();let r=oW(e),n=(0,Dt.join)((0,Wt.getHdbBasePath)(),tc),s=(0,Wt.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,Wt.get)(U.STORAGE_PATH)||((0,Xn.existsSync)(n)?n:(0,Dt.join)((0,Wt.getHdbBasePath)(),ym));let o=(0,Dt.join)(n,(i?t:e)+".mdb"),c=Po.get(o);if(!c||c.status==="closed"){let l=new eC.default(o,!1);c=(0,Id.open)(l),Po.set(o,c)}return c.auditStore||(c.auditStore=tT(c)),c}async function tb(e){if(!Ve[e])throw new Error("Schema does not exist");let t=Ve[e],r;for(let n in t)r=t[n].primaryStore.rootStore,Po.delete(r.path),r.status==="open"&&(await r.close(),await Kh.remove(r.path));if(r||(r=_u({database:e,table:null}),r.status==="open"&&(await r.close(),await Kh.remove(r.path))),e==="data"){for(let n in Vn)delete Vn[n];delete Vn[fT]}delete Ve[e],Vh.forEach(n=>n(e)),await nC(r)}function ut(e){let{table:t,database:r,expiration:n,eviction:s,scanInterval:i,attributes:o,audit:c,sealed:l,splitSegments:u,replicate:f,trackDeletes:d,schemaDefined:_,origin:h}=e;r||(r=rC);let m=_u({database:r,table:t}),S=Ve[r];Lt.trace(`Defining ${t} in ${r}`);let g=S?.[t];if(m.status==="closed")throw new Error(`Can not use a closed data store for ${t}`);let R,E,T;_==null&&(_=!0);let w=new Rl.default(!1);for(let Y of o)Y.attribute&&!Y.name?(Y.name=Y.attribute,Y.indexed=!0):Y.attribute=Y.name,Y.expiresAt&&(Y.indexed=!0);let v,H;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,...o)}else{let Y=m.auditStore;E=o.find(pe=>pe.isPrimaryKey)||{},R=E.name,E.is_hash_attribute=E.isPrimaryKey=!0,E.schemaDefined=_,E.compression=Fg(),d&&(E.trackDeletes=!0),c=E.audit=typeof c=="boolean"?c:(0,Wt.get)(U.LOGGING_AUDITLOG),n&&(E.expiration=n),s&&(E.eviction=s),u??=!1,E.splitSegments=u,typeof l=="boolean"&&(E.sealed=l),typeof f=="boolean"&&(E.replicate=f),h&&(E.origins?E.origins.includes(h)||E.origins.push(h):E.origins=[h]),Lt.trace(`${t} table loading, opening primary store`);let ne=new Rl.default(!1,!0);ne.compression=E.compression;let ue=t+"/";if(T=m.dbisDb=m.openDB(cT.INTERNAL_DBIS_NAME,w),se(),T.get(ue))return H&&H(),ed(),ut(e);let oe=sp(m.openDB(ue,ne),m);m.databaseName=r,oe.tableId=T.get(Od),Lt.trace(`Assigning new table id ${oe.tableId} for ${t}`),oe.tableId||(oe.tableId=1),T.put(Od,oe.tableId+1),E.tableId=oe.tableId,g=aW(S,t,aT({primaryStore:oe,auditStore:Y,audit:c,sealed:l,splitSegments:u,replicate:f,trackDeletes:d,expirationMS:n&&n*1e3,evictionMS:s&&s*1e3,primaryKey:R,tableName:t,tableId:oe.tableId,databasePath:r,databaseName:r,indices:{},attributes:o,schemaDefined:_,dbisDB:T})),g.schemaVersion=1,v=!0,T.put(ue,E)}let q=g.indices;T=T||(m.dbisDb=m.openDB(cT.INTERNAL_DBIS_NAME,w)),g.dbisDB=T;let W=[];for(let{key:Y,value:ne}of T.getRange({start:!0})){let[ue,oe]=Y.toString().split("/");if(oe===""&&(oe=ne.name),oe){if(ue!==t)continue}else continue;let pe=o.find(ye=>ye.name===oe),Te=!pe?.indexed&&ne.indexed&&!ne.isPrimaryKey;if((!pe||Te)&&(se(),v=!0,pe||T.remove(Y),Te)){let ye=g.indices[ue];ye&&W.push(ye)}}let te=[];try{for(let Y of o||[]){if((Y.relationship||Y.computed)&&(v=!0,Y.relationship))continue;let ne=t+"/"+(Y.name||"");Object.defineProperty(Y,"key",{value:ne,configurable:!0});let ue=T.get(ne);if(Y.isPrimaryKey){if(ue=ue||T.get(ne=t+"/")||{},c!==void 0&&c!==g.audit||l!==void 0&&l!==g.sealed||f!==void 0&&f!==g.replicate||(+n||void 0)!==(+ue.expiration||void 0)||(+s||void 0)!==(+ue.eviction||void 0)||Y.type!==ue.type){let pe={...ue};typeof c=="boolean"&&(c&&g.enableAuditing(c),pe.audit=c),n&&(pe.expiration=+n),s&&(pe.eviction=+s),l!==void 0&&(pe.sealed=l),f!==void 0&&(pe.replicate=f),Y.type&&(pe.type=Y.type),v=!0,se(),T.put(ne,pe)}continue}ue?.attribute&&!ue.name&&(ue.indexed=!0);let oe=!ue||ue.type!==Y.type||ue.indexed!==Y.indexed||ue.nullable!==Y.nullable||ue.version!==Y.version||JSON.stringify(ue.properties)!==JSON.stringify(Y.properties)||JSON.stringify(ue.elements)!==JSON.stringify(Y.elements);if(Y.indexed){let pe=new Rl.default(!0,!1),Te=m.openDB(ne,pe);(oe||ue.indexingPID&&ue.indexingPID!==process.pid||ue.restartNumber<Yh.workerData?.restartNumber)&&(v=!0,se(),ue=T.get(ne),(oe||ue.indexingPID&&ue.indexingPID!==process.pid||ue.restartNumber<Yh.workerData?.restartNumber)&&(v=!0,Y.indexNulls===void 0&&(Y.indexNulls=!0),g.primaryStore.getStats().entryCount>0&&(Y.lastIndexedKey=ue?.lastIndexedKey??void 0,Y.indexingPID=process.pid,Te.isIndexing=!0,Object.defineProperty(Y,"dbi",{value:Te}),te.push(Y))),T.put(ne,Y)),ue?.indexNulls&&Y.indexNulls===void 0&&(Y.indexNulls=!0),Te.indexNulls=Y.indexNulls,q[Y.name]=Te}else oe&&(v=!0,se(),T.put(ne,Y))}}finally{H&&H()}if(v&&(g.schemaVersion++,g.updatedAttributes()),Lt.trace(`${t} table loading, running index`),te.length>0||W.length>0?g.indexingOperation=Qme(g,te,W):v&&lT.signalSchemaChange(new uT.SchemaEventMsg(process.pid,"schema-change",g.databaseName,g.tableName)),g.origin=h,v)for(let Y of $h)Y(g,h!=="cluster");return(n||s||i)&&g.setTTLExpiration({expiration:n,eviction:s,scanInterval:i}),Lt.trace(`${t} table loaded`),g;function se(){H||m.transactionSync(()=>({then(Y){H=Y}}))}a(se,"startTxn")}async function Qme(e,t,r){try{Lt.info(`Indexing ${e.tableName} attributes`,t);let n=e.schemaVersion;await lT.signalSchemaChange(new uT.SchemaEventMsg(process.pid,"schema-change",e.databaseName,e.tableName));let s;for(let u of r)s=u.drop();let i,o={},c=0,l=t.length;if(await new Promise(u=>setImmediate(u)),l>0){let u;for(let d of t)(0,Id.compareKeys)(d.lastIndexedKey,u)<0&&(u=d.lastIndexedKey),d.lastIndexedKey==null&&d.dbi.clearAsync();let f=0;for(let{key:d,value:_,version:h}of e.primaryStore.getRange({start:u,lazy:l<4,versions:!0,snapshot:!1}))if(_){if(f++,s=e.primaryStore.ifVersion(d,h,()=>{for(let m=0;m<l;m++){let S=t[m],g=S.name;try{let R=S.resolve,E=_&&(R?R(_):_[g]),T=(0,nW.getIndexedValues)(E);if(T)for(let w=0,v=T.length;w<v;w++)S.dbi.put(T[w],d)}catch(R){o[g]||(o[g]=!0,Lt.error(`Error indexing attribute ${g}`,R))}}}),s.then(()=>f--,m=>{f--,Lt.error(m)}),Yh.workerData&&Yh.workerData.restartNumber!==sW.restartNumber&&(i=!0),++c%100===0||i){for(let m of t)m.lastIndexedKey=d,e.dbisDB.put(m.key,m);if(i)return}f>Wme?await s:f>zme&&await new Promise(m=>setImmediate(m))}for(let d of t)delete d.lastIndexedKey,delete d.indexingPID,d.dbi.isIndexing=!1,s=e.dbisDB.put(d.key,d)}await s,await lT.signalSchemaChange(new uT.SchemaEventMsg(process.pid,"indexing-finished",e.databaseName,e.tableName)),Lt.info(`Finished indexing ${e.tableName} attributes`,t)}catch(n){Lt.error("Error in indexing",n)}}function jme({table:e,database:t}){let r=_u({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 jc(e){return $h.push(e),{remove(){let t=$h.indexOf(e);t>-1&&$h.splice(t,1)}}}function v_(e){return Vh.push(e),{remove(){let t=Vh.indexOf(e);t>-1&&Vh.splice(t,1)}}}function Fg(){let e=(0,Wt.get)(U.STORAGE_COMPRESSION),t=(0,Wt.get)(U.STORAGE_COMPRESSION_DICTIONARY),r=(0,Wt.get)(U.STORAGE_COMPRESSION_THRESHOLD)||iW,n={startingOffset:32};return t&&(n.dictionary=Kh.readFileSync(t)),r&&(n.threshold=r),e&&n}var Wt,cT,Id,Dt,Xn,Nd,Rl,eC,Kh,tC,nW,lT,uT,Yh,Lt,sW,rC,fT,iW,Vn,Ve,Od,$h,Vh,dT,Po,wd,Wme,zme,ve=be(()=>{Wt=M(le()),cT=M(Ut()),Id=require("lmdb"),Dt=require("path"),Xn=require("fs"),Nd=M(pt());df();Rl=M(yf()),eC=M(bf());k();Kh=M(require("fs-extra")),tC=M(ci()),nW=M(an()),lT=M(ao()),uT=M(qs()),Yh=require("worker_threads"),Lt=M(j()),sW=M(tt());Zi();Xl();cs();rC="data",fT=Symbol("defined-tables"),iW=((0,Wt.get)(U.STORAGE_PAGESIZE)||4096)-60;(0,Wt.initSync)();Vn=Object.create(null),Ve=Object.create(null);(0,tC._assignPackageExport)("databases",Ve);(0,tC._assignPackageExport)("tables",Vn);Od=Symbol.for("next-table-id"),$h=[],Vh=[],Po=new Map;a(Yme,"getTables");a(je,"getDatabases");a(ed,"resetDatabases");a(qh,"readMetaDb");a(oW,"ensureDB");a(aW,"setTable");a(_u,"database");a(tb,"dropDatabase");a(ut,"table");Wme=1e3,zme=10;a(Qme,"runIndexing");a(jme,"dropTableMeta");a(jc,"onUpdatedTable");a(v_,"onRemovedDB");a(Fg,"getDefaultCompression")});var ae=P((EMe,AW)=>{"use strict";var qa=require("path"),fW=require("fs-extra"),On=j(),cW=require("fs-extra"),_T=require("os"),Jme=require("net"),Xme=require("recursive-iterator"),gr=(k(),D($)),{PACKAGE_ROOT:Zme}=mt(),epe=_A(),lW=require("papaparse"),hT=require("moment"),{inspect:tpe}=require("util"),uW=require("is-number"),pMe=require("lodash"),rpe=require("minimist"),npe=require("https"),spe=require("http"),{hdb_errors:mT}=me(),ipe=/^((\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)))$/,_W=require("util").promisify(setTimeout),ope=100,ape=5,cpe="",lpe=4,dW={true:!0,TRUE:!0,FALSE:!1,false:!1,undefined:null,null:null,NULL:null,NaN:NaN};AW.exports={isEmpty:Zn,isEmptyOrZeroLength:xi,arrayHasEmptyValues:fpe,arrayHasEmptyOrZeroLengthValues:_pe,buildFolderPath:hpe,isBoolean:hW,errorizeMessage:upe,stripFileExtension:ppe,autoCast:Epe,autoCastJSON:mW,autoCastJSONDeep:iC,removeDir:gpe,compareVersions:Spe,isCompatibleDataVersion:Tpe,escapeRawValue:Ape,unescapeValue:Rpe,stringifyProps:ype,timeoutPromise:Ope,isClusterOperation:wpe,getClusterUser:Cpe,checkGlobalSchemaTable:Ipe,getHomeDir:EW,getPropsFilePath:bpe,promisifyPapaParse:Ppe,removeBOM:gW,createEventPromise:Dpe,checkProcessRunning:Lpe,checkSchemaTableExist:Mpe,checkSchemaExists:SW,checkTableExists:TW,getStartOfTomorrowInSeconds:vpe,getLimitKey:Upe,isObject:mpe,isNotEmptyAndHasValue:dpe,autoCasterIsNumberCheck:pW,backtickASTSchemaItems:xpe,isPortTaken:Npe,createForkArgs:Bpe,autoCastBoolean:Hpe,async_set_timeout:_W,getTableHashAttribute:kpe,doesSchemaExist:Fpe,doesTableExist:Gpe,stringifyObj:qpe,ms_to_time:$pe,changeExtension:Vpe,getEnvCliRootPath:oC,noBootFile:Kpe,httpRequest:Ype,transformReq:Wpe,convertToMS:zpe,PACKAGE_ROOT:Zme};function upe(e){return e instanceof Error?e:new Error(e)}a(upe,"errorizeMessage");function Zn(e){return e==null}a(Zn,"isEmpty");function dpe(e){return!Zn(e)&&(e||e===0||e===""||hW(e))}a(dpe,"isNotEmptyAndHasValue");function xi(e){return Zn(e)||e.length===0||e.size===0}a(xi,"isEmptyOrZeroLength");function fpe(e){if(Zn(e))return!0;for(let t=0;t<e.length;t++)if(Zn(e[t]))return!0;return!1}a(fpe,"arrayHasEmptyValues");function _pe(e){if(xi(e))return!0;for(let t=0;t<e.length;t++)if(xi(e[t]))return!0;return!1}a(_pe,"arrayHasEmptyOrZeroLengthValues");function hpe(...e){try{return e.join(qa.sep)}catch{console.error(e)}}a(hpe,"buildFolderPath");function hW(e){return Zn(e)?!1:e===!0||e===!1}a(hW,"isBoolean");function mpe(e){return Zn(e)?!1:typeof e=="object"}a(mpe,"isObject");function ppe(e){return xi(e)?cpe:e.slice(0,-lpe)}a(ppe,"stripFileExtension");function Epe(e){return Zn(e)||e===""||typeof e!="string"?e:dW[e]!==void 0?dW[e]:pW(e)===!0?Number(e):ipe.test(e)?new Date(e):e}a(Epe,"autoCast");function mW(e){if(typeof e=="string"&&(e.startsWith("{")&&e.endsWith("}")||e.startsWith("[")&&e.endsWith("]")))try{return JSON.parse(e)}catch{}return e}a(mW,"autoCastJSON");function iC(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=iC(n);s!==n&&(e[t]=s)}else for(let t in e){let r=e[t],n=iC(r);n!==r&&(e[t]=n)}return e}else return mW(e)}a(iC,"autoCastJSONDeep");function pW(e){if(e.startsWith("0.")&&uW(e))return!0;let t=e.toUpperCase().includes("E");return!!((e!=="0"&&e.startsWith("0"))===!1&&t===!1&&uW(e))}a(pW,"autoCasterIsNumberCheck");async function gpe(e){if(xi(e))throw new Error(`Directory path: ${e} does not exist`);try{await cW.emptyDir(e),await cW.remove(e)}catch(t){throw On.error(`Error removing files in ${e} -- ${t}`),t}}a(gpe,"removeDir");function Spe(e,t){if(xi(e)){On.info("Invalid current version sent as parameter.");return}if(xi(t)){On.info("Invalid upgrade version sent as parameter.");return}let r,n=/(\.0+)+$/,s=e.version?e.version:e,i=t.version?t.version:t,o=s.replace(n,"").split("."),c=i.replace(n,"").split("."),l=Math.min(o.length,c.length);for(let u=0;u<l;u++)if(r=parseInt(o[u],10)-parseInt(c[u],10),r)return r;return o.length-c.length}a(Spe,"compareVersions");function Tpe(e,t,r=!1){let n=e.toString().split("."),s=t.toString().split(".");return n[0]===s[0]&&(!r||n[1]===s[1])}a(Tpe,"isCompatibleDataVersion");function Ape(e){if(Zn(e))return e;let t=String(e);return t==="."?gr.UNICODE_PERIOD:t===".."?gr.UNICODE_PERIOD+gr.UNICODE_PERIOD:t.replace(gr.FORWARD_SLASH_REGEX,gr.UNICODE_FORWARD_SLASH)}a(Ape,"escapeRawValue");function Rpe(e){if(Zn(e))return e;let t=String(e);return t===gr.UNICODE_PERIOD?".":t===gr.UNICODE_PERIOD+gr.UNICODE_PERIOD?"..":String(e).replace(gr.ESCAPED_FORWARD_SLASH_REGEX,"/")}a(Rpe,"unescapeValue");function ype(e,t){if(Zn(e))return On.info("Properties object is null"),"";let r="";return e.each(function(n,s){try{if(t&&t[n]){let i=t[n];for(let o of i)r+=";"+o+_T.EOL}!xi(n)&&n[0]===";"?r+=" "+n+s+_T.EOL:xi(n)||(r+=n+"="+s+_T.EOL)}catch{On.error(`Found bad property during upgrade with key ${n} and value: ${s}`)}}),r}a(ype,"stringifyProps");function EW(){let e;try{e=_T.homedir()}catch{e=process.env.HOME}return e}a(EW,"getHomeDir");function bpe(){let e=qa.join(EW(),gr.HDB_HOME_DIR_NAME,gr.BOOT_PROPS_FILE_NAME);return fW.existsSync(e)||(e=qa.join(__dirname,"../","hdb_boot_properties.file")),e}a(bpe,"getPropsFilePath");function Ope(e,t){let r,n;return n=new Promise(function(s){r=setTimeout(function(){s(t)},e)}),{promise:n,cancel:a(function(){clearTimeout(r)},"cancel")}}a(Ope,"timeoutPromise");async function Npe(e){if(!e)throw new Error("Invalid port passed as parameter");return new Promise((t,r)=>{let n=Jme.createServer().once("error",s=>{s.code==="EADDRINUSE"?t(!0):r(s)}).once("listening",()=>n.once("close",()=>t(!1)).close()).listen(e)})}a(Npe,"isPortTaken");function wpe(e){try{return gr.CLUSTER_OPERATIONS[e.toLowerCase()]!==void 0}catch(t){On.error(`Error checking operation against cluster ops ${t}`)}return!1}a(wpe,"isClusterOperation");function Ipe(e,t){let r=(ve(),D(it)).getDatabases();if(!r[e])return mT.HDB_ERROR_MSGS.SCHEMA_NOT_FOUND(e);if(!r[e][t])return mT.HDB_ERROR_MSGS.TABLE_NOT_FOUND(e,t)}a(Ipe,"checkGlobalSchemaTable");function Cpe(e,t){if(Zn(t)){On.warn("No CLUSTERING_USER defined, clustering disabled");return}if(Zn(e)||xi(e)){On.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){On.error(`unable to find cluster_user due to: ${n.message}`);return}if(r===void 0){On.warn(`CLUSTERING_USER: ${t} not found or is not active.`);return}return r}a(Cpe,"getClusterUser");function Ppe(){lW.parsePromise=function(e,t,r){return new Promise(function(n,s){lW.parse(e,{header:!0,transformHeader:gW,chunk:t.bind(null,s),skipEmptyLines:!0,transform:r,dynamicTyping:!1,error:s,complete:n})})}}a(Ppe,"promisifyPapaParse");function gW(e){if(typeof e!="string")throw new TypeError(`Expected a string, got ${typeof e}`);return e.charCodeAt(0)===65279?e.slice(1):e}a(gW,"removeBOM");function Dpe(e,t,r){return new Promise(n=>{t.once(e,s=>{let i=r;On.info(`Got cluster status event response: ${tpe(s)}`);try{i.cancel()}catch{On.error("Error trying to cancel timeout.")}n(s)})})}a(Dpe,"createEventPromise");async function Lpe(e){let t=!0,r=0;do await _W(ope*r++),(await epe.findPs(e)).length>0&&(t=!1);while(t&&r<ape);if(t)throw new Error(`process ${e} was not started`)}a(Lpe,"checkProcessRunning");function Mpe(e,t){let r=SW(e);if(r)return r;let n=TW(e,t);if(n)return n}a(Mpe,"checkSchemaTableExist");function SW(e){let{getDatabases:t}=(ve(),D(it));if(!t()[e])return mT.HDB_ERROR_MSGS.SCHEMA_NOT_FOUND(e)}a(SW,"checkSchemaExists");function TW(e,t){let{getDatabases:r}=(ve(),D(it));if(!r()[e][t])return mT.HDB_ERROR_MSGS.TABLE_NOT_FOUND(e,t)}a(TW,"checkTableExists");function vpe(){let e=hT().utc().add(1,"d").startOf("d").unix(),t=hT().utc().unix();return e-t}a(vpe,"getStartOfTomorrowInSeconds");function Upe(){return hT().utc().format("DD-MM-YYYY")}a(Upe,"getLimitKey");function xpe(e){try{let t=new Xme(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){On.error("Got an error back ticking items."),On.error(t)}}a(xpe,"backtickASTSchemaItems");function Bpe(e){return[e]}a(Bpe,"createForkArgs");function Hpe(e){return e===!0||typeof e=="string"&&e.toLowerCase()==="true"}a(Hpe,"autoCastBoolean");function kpe(e,t){let{getDatabases:r}=(ve(),D(it)),n=r()[e]?.[t];return n?.primaryKey||n?.hash_attribute}a(kpe,"getTableHashAttribute");function Fpe(e){let{getDatabases:t}=(ve(),D(it));return t()[e]!==void 0}a(Fpe,"doesSchemaExist");function Gpe(e,t){let{getDatabases:r}=(ve(),D(it));return r()[e]?.[t]!==void 0}a(Gpe,"doesTableExist");function qpe(e){try{return JSON.stringify(e)}catch{return e}}a(qpe,"stringifyObj");function $pe(e){let t=hT.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}a($pe,"ms_to_time");function Vpe(e,t){let r=qa.basename(e,qa.extname(e));return qa.join(qa.dirname(e),r+t)}a(Vpe,"changeExtension");function oC(){if(process.env[gr.CONFIG_PARAMS.ROOTPATH.toUpperCase()])return process.env[gr.CONFIG_PARAMS.ROOTPATH.toUpperCase()];let e=rpe(process.argv);if(e[gr.CONFIG_PARAMS.ROOTPATH.toUpperCase()])return e[gr.CONFIG_PARAMS.ROOTPATH.toUpperCase()]}a(oC,"getEnvCliRootPath");var sC;function Kpe(){if(sC)return sC;let e=oC();if(oC()&&fW.pathExistsSync(qa.join(e,gr.HDB_CONFIG_FILE)))return sC=!0,!0}a(Kpe,"noBootFile");function Ype(e,t){let r;return e.protocol==="http:"?r=spe:r=npe,new Promise((n,s)=>{let i=r.request(e,o=>{o.setEncoding("utf8"),o.body="",o.on("data",c=>{o.body+=c}),o.on("end",()=>{n(o)})});i.on("error",o=>{s(o)}),i.write(t instanceof Buffer?t:JSON.stringify(t)),i.end()})}a(Ype,"httpRequest");function Wpe(e){if(!e.schema&&!e.database){e.schema=gr.DEFAULT_DATABASE_NAME;return}e.database&&(e.schema=e.database)}a(Wpe,"transformReq");function zpe(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}a(zpe,"convertToMS")});var le=P((NW,wW)=>{"use strict";var aC=require("fs-extra"),yl=require("path"),RW=require("os"),Qpe=require("properties-reader"),zh=j(),Wh=ae(),Me=(k(),D($)),pT=Ct(),jpe="Error initializing environment manager",ET="BOOT_PROPS_FILE_PATH",yW=!1,Jpe={[Me.HDB_SETTINGS_NAMES.INSTALL_USER]:!0,[Me.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY]:!0,[Me.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]:!0,BOOT_PROPS_FILE_PATH:!0},Do={};Object.assign(NW,wW.exports={BOOT_PROPS_FILE_PATH:ET,getHdbBasePath:Xpe,setHdbBasePath:Zpe,get:bW,initSync:tEe,setProperty:ze,initTestEnvironment:nEe,setCloneVar:rEe});function Xpe(){return Do[Me.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]}a(Xpe,"getHdbBasePath");function Zpe(e){Do[Me.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]=e}a(Zpe,"setHdbBasePath");function bW(e){let t=pT.getConfigValue(e);return t===void 0?Do[e]:t}a(bW,"get");function ze(e,t){Jpe[e]&&(Do[e]=t),pT.updateConfigObject(e,t)}a(ze,"setProperty");function eEe(){let e;try{e=Wh.getPropsFilePath(),aC.accessSync(e,aC.constants.F_OK|aC.constants.R_OK),yW=!0;let t=Qpe(e);return Do[Me.HDB_SETTINGS_NAMES.INSTALL_USER]=t.get(Me.HDB_SETTINGS_NAMES.INSTALL_USER),Do[Me.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY]=t.get(Me.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY),Do[ET]=e,!0}catch{return zh.trace(`Environment manager found no properties file at ${e}`),!1}}a(eEe,"doesPropFileExist");function tEe(e=!1){try{((yW||eEe()||Wh.noBootFile())&&!OW||e)&&(pT.initConfig(e),Do[Me.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]=pT.getConfigValue(Me.HDB_SETTINGS_NAMES.HDB_ROOT_KEY))}catch(t){zh.error(jpe),zh.error(t),console.error(t),process.exit(1)}}a(tEe,"initSync");var OW=!1;function rEe(e){OW=e}a(rEe,"setCloneVar");function nEe(e={}){try{let{keep_alive_timeout:t,headers_timeout:r,server_timeout:n,https_enabled:s,cors_enabled:i,cors_accesslist:o,local_studio_on:c}=e,l=yl.join(__dirname,"../../","unitTests");Do[ET]=yl.join(l,"hdb_boot_properties.file"),ze(Me.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY,yl.join(l,"settings.test")),ze(Me.HDB_SETTINGS_NAMES.INSTALL_USER,RW.userInfo()?RW.userInfo().username:void 0),ze(Me.HDB_SETTINGS_NAMES.LOG_LEVEL_KEY,"debug"),ze(Me.HDB_SETTINGS_NAMES.LOG_PATH_KEY,yl.join(l,"envDir","log")),ze(Me.HDB_SETTINGS_NAMES.LOG_DAILY_ROTATE_KEY,!1),ze(Me.HDB_SETTINGS_NAMES.CLUSTERING_ENABLED_KEY,!0),ze(Me.HDB_SETTINGS_NAMES.CLUSTERING_NODE_NAME_KEY,"1231412de213"),ze(Me.HDB_SETTINGS_NAMES.HDB_ROOT_KEY,yl.join(l,"envDir")),ze(Me.CONFIG_PARAMS.STORAGE_PATH,yl.join(l,"envDir")),s&&(ze(Me.CONFIG_PARAMS.HTTP_SECUREPORT,bW(Me.CONFIG_PARAMS.HTTP_PORT)),ze(Me.CONFIG_PARAMS.HTTP_PORT,null)),ze(Me.CONFIG_PARAMS.CUSTOMFUNCTIONS_NETWORK_HTTPS,!!s),ze(Me.CONFIG_PARAMS.HTTP_PORT,9926),ze(Me.HDB_SETTINGS_NAMES.SERVER_PORT_KEY,9925),ze(Me.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_PORT,9925),ze(Me.HDB_SETTINGS_NAMES.CORS_ENABLED_KEY,Wh.isEmpty(i)?!1:i),ze(Me.CONFIG_PARAMS.HTTP_CORS,Wh.isEmpty(i)?!1:i),ze(Me.HDB_SETTINGS_NAMES.MAX_CUSTOM_FUNCTION_PROCESSES,2),ze(Me.HDB_SETTINGS_NAMES.MAX_HDB_PROCESSES,4),ze(Me.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_PORT_KEY,9926),ze(Me.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_ENABLED_KEY,!0),ze(Me.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_DIRECTORY_KEY,yl.resolve(__dirname,"../../unitTests/server/fastifyRoutes/custom_functions")),ze(Me.HDB_SETTINGS_NAMES.LOCAL_STUDIO_ON,Wh.isEmpty(c)?!1:c),o&&(ze("CORS_ACCESSLIST",o),ze(Me.CONFIG_PARAMS.HTTP_CORSACCESSLIST,o)),n&&(ze(Me.HDB_SETTINGS_NAMES.SERVER_TIMEOUT_KEY,n),ze(Me.CONFIG_PARAMS.HTTP_TIMEOUT,n)),t&&(ze(Me.HDB_SETTINGS_NAMES.SERVER_KEEP_ALIVE_TIMEOUT_KEY,t),ze(Me.CONFIG_PARAMS.HTTP_KEEPALIVETIMEOUT,t)),r&&(ze(Me.HDB_SETTINGS_NAMES.SERVER_HEADERS_TIMEOUT_KEY,r),ze(Me.CONFIG_PARAMS.HTTP_HEADERSTIMEOUT,r))}catch(t){let r=`Error reading in HDB environment variables from path ${ET}. Please check your boot props and settings files`;zh.fatal(r),zh.error(t)}}a(nEe,"initTestEnvironment")});var wE={};Ue(wE,{Blob:()=>mi,blobsWereEncoded:()=>fc,databasePaths:()=>lC,decodeBlobsWithWrites:()=>WE,decodeFromDatabase:()=>_c,decodeWithBlobCallback:()=>zE,deleteBlob:()=>JE,deleteBlobsInObject:()=>ra,deleteRootBlobPathsForDB:()=>nC,encodeBlobsAsBuffers:()=>_Ee,encodeBlobsWithFilePath:()=>rp,findBlobsInObject:()=>bd,getFileId:()=>YE,getFilePathForBlob:()=>BW,getRootBlobPathsForDB:()=>Xh,setDeletionDelay:()=>aEe});function vW(){}function JE(e){let t=BW(e);t&&setTimeout(()=>{(0,Xe.unlink)(t,r=>{r&&Lo.default.debug?.("Error trying to remove blob file",r)})},UW)}function aEe(e){UW=e}function xW(e){let t=Nn.get(e);if(!t)t={storageIndex:0,fileId:null,store:wn},Nn.set(e,t);else{if(t.saving)return t;t.store=wn}return lEe(t),t.source?cC(e,t.source,t):t.contentBuffer?cEe(e,t):cC(e,jh.Readable.from(e.stream()),t),t}function cC(e,t,r){let{filePath:n,fileId:s,store:i,compress:o,flush:c}=r;return r.saving=new Promise((l,u)=>{let f=s+":blob";if(!i.attemptLock(f,0))throw new Error(`Unable to get lock for blob file ${s}`);let d=(0,Xe.createWriteStream)(n,{autoClose:!1,flags:"w"});if(t.errored){let g=Buffer.from(t.errored.toString());d.end(Buffer.concat([m(BigInt(g.length)+0xff000000000000n),g]));return}let _=!1;e.size!==void 0&&(d.write(m(e.size)),_=!0);let h;o?(_||d.write(iEe),h=(0,AT.createDeflate)(),t.pipe(h).pipe(d)):(_||d.write(sEe),t.pipe(d)),t.on("error",S);function m(g){let R=BigInt(g),E=new Uint8Array(Sr),T=new DataView(E.buffer);return R|=BigInt(o?uC:MW)<<48n,T.setBigInt64(0,R),E}a(m,"createHeader");function S(g){i.unlock(f,0);let R=d.fd;g?(R&&(0,Xe.close)(R),u(g)):c?(0,Xe.fdatasync)(R,E=>{E&&u(E),l(),(0,Xe.close)(R)}):(l(),(0,Xe.close)(R))}a(S,"finished"),d.on("error",S).on("finish",()=>{if(_)S();else{let g=h?h.bytesWritten:d.bytesWritten-Sr;e.size=g,(0,Xe.write)(d.fd,m(g),0,Sr,0,S)}})}),e}function YE(e){return Nn.get(e)?.fileId}function BW(e){let t=Nn.get(e);return t?.fileId&&Jh(t)}function Xh(e){if(!e)throw new Error("No store specified, can not determine blob storage path");let t=lC.get(e);if(!t){if(!e.databaseName)return Lo.default.warn?.("No database name specified, can not determine blob storage path"),[];let r=(0,RT.get)(U.STORAGE_BLOBPATHS);r?t=r.map(n=>(0,vo.join)(n,e.databaseName)):t=[(0,vo.join)((0,RT.getHdbBasePath)(),"blobs",e.databaseName)],lC.set(e,t)}return t}async function nC(e){let t=Xh(e);t&&await Promise.all(t.map(r=>HW(r)))}async function HW(e){if((0,Xe.existsSync)(e)){for(let t of await(0,ii.readdir)(e,{withFileTypes:!0}))if(t.isDirectory())await HW((0,vo.join)(e,t.name));else try{await(0,ii.unlink)((0,vo.join)(e,t.name))}catch(r){Lo.default.warn?.("Error deleting file",r)}try{await(0,ii.rmdir)(e)}catch(t){Lo.default.warn?.("Error deleting directory",t)}}}function Jh({storageIndex:e,fileId:t,store:r}){let n=Xh(r);return(0,vo.join)(n[e],t.slice(-9,-6)||"0",t.slice(-6,-3)||"0",t.length<=9?t.slice(-3):t.slice(0,-9)+t.slice(-3))}function cEe(e,t){let r=t.contentBuffer,n=r.length;if(!(n<LW))return e.size=n,cC(e,jh.Readable.from([r]),t)}function lEe(e){let t=Xh(e.store),r=uEe(),n=t?.length>1?dEe(t,r):0,s=r.toString(16);e.storageIndex=n,e.fileId=s;let i=Jh(e),o=(0,vo.dirname)(i);(0,Xe.existsSync)(o)||(0,DW.ensureDirSync)(o),e.filePath=i}function uEe(){let e=PW.get(wn);if(!e){let t=0,r=Xh(wn);for(let n of r){let s=0;for(let i=0;i<3;i++){s=s*4096;let o=0;if((0,Xe.existsSync)(n))for(let c of(0,Xe.readdirSync)(n)){let l=parseInt(c,16);i===2&&c.length>3&&(l=parseInt(c.slice(-3),16),l+=parseInt(c.slice(0,-3),16)*68719476736),l>o&&(o=l)}s+=o,n=(0,vo.join)(n,o.toString(16))}t=Math.max(t,s)}e=new BigInt64Array([BigInt(t)+1n]),e=new BigInt64Array(wn.getUserSharedBuffer("blob-file-id",e.buffer)),PW.set(wn,e)}return Number(Atomics.add(e,0,1n))}function dEe(e,t){let r=Date.now();if(!e.frequencyTable){e.lastUpdated=0;let s=new Array(TT);for(let i=0;i<s.length;i++)s[i]=i%e.length;e.frequencyTable=s}return(e.lastUpdated??0)+6e4<r&&(e.lastUpdated=r,fEe(e)),e.frequencyTable[t%TT]}async function fEe(e){if(!ii.statfs)return;let t=await Promise.all(e.map(async(s,i)=>{let o=await(0,ii.statfs)(s),c=o.bavail*o.bsize;return Math.pow(c,.8)})),r=new Array(TT),n=t.map(s=>1/s);for(let s=0;s<TT;s++){let i=1/0,o=0;for(let c=0;c<n.length;c++)n[c]<i&&(o=c,i=n[c]);n[o]+=1/t[o],r[s]=o}e.frequencyTable=r}function rp(e,t,r){Cd=t,wn=r,fc=!1;try{return e()}finally{Cd=void 0,wn=void 0}}function _Ee(e){Br=[];let t;try{t=e()}catch(n){throw Br=void 0,n}let r=Br.length<2?Br[0]:Promise.all(Br);return Br=void 0,r?r.then(()=>e()):t}function WE(e,t){try{Br=[],bl=t,e()}catch(n){throw bl=void 0,Br=void 0,n}bl=void 0;let r=Br.length<2?Br[0]:Promise.all(Br);return Br=void 0,r}function zE(e,t,r){wn=r;try{return bl=t,e()}finally{bl=void 0}}function _c(e,t){return wn=t,e()}function ra(e){bd(e,t=>{JE(t)})}function bd(e,t){if(e instanceof mi)t(e);else if(Array.isArray(e))for(let r of e)typeof r=="object"&&r&&bd(r,t);else if(e&&typeof e=="object"&&!e[Symbol.iterator])for(let r in e){let n=e[r];typeof n=="object"&&n&&bd(e[r],t)}}function hEe(){return class{static{a(this,"Blob")}content;constructor(t){this.content=t[0]}stream(){return new ReadableStream({start(t){t.enqueue(this.content),t.close()}})}text(){return Promise.resolve(this.content.toString())}arrayBuffer(){return Promise.resolve(this.content.buffer)}get size(){return this.content.length}slice(){throw new Error("Not implemented")}bytes(){return Promise.resolve(this.content)}get type(){return""}}}var Mo,ii,Xe,AT,jh,DW,RT,vo,Lo,LW,Sr,MW,uC,IW,sEe,iEe,CW,Nn,bl,mi,Cd,Br,wn,fc,Qh,gT,oEe,ST,UW,lC,PW,TT,cs=be(()=>{Mo=require("msgpackr"),ii=require("node:fs/promises"),Xe=require("node:fs"),AT=require("node:zlib"),jh=require("node:stream"),DW=require("fs-extra"),RT=M(le());k();vo=require("path"),Lo=M(_i());Xi();LW=8192,Sr=8,MW=0,uC=1,IW=255,sEe=new Uint8Array([0,MW,255,255,255,255,255,255]),iEe=new Uint8Array([0,uC,255,255,255,255,255,255]),CW=0xffffffffffff,Nn=new WeakMap,mi=global.Blob||hEe(),fc=!1,Qh=new Uint8Array(8),gT=new DataView(Qh.buffer),oEe=6e4;a(vW,"InstanceOfBlobWithNoConstructor");vW.prototype=mi.prototype;ST=class e extends vW{static{a(this,"FileBackedBlob")}type="";size;#e;#t;constructor(t){super(),t?.type&&(this.type=t.type),t?.size!=null&&(this.size=t.size)}on(t,r){if(t==="error")this.#e??=[],this.#e.push(r);else if(t==="size")this.#t??=[],this.#t.push(r);else throw new Error("Only 'error' and 'size' events are supported")}toJSON(){if(this.type?.startsWith("text")){let t=Nn.get(this),{start:r,end:n,contentBuffer:s,asString:i}=t;return i||(s&&(n!==void 0||r!==void 0)&&(s=s.subarray(r??0,n??t.contentBuffer.length)),s?(t.asString=s.toString(),t.asString):(kA()&&HA(this.bytes().then(o=>t.contentBuffer=o)),`[blob: ${this.type}, ${this.size} bytes]`))}return{description:"Blobs that are not of type text/* can not be directly serialized as JSON, use as the body of a response or convert to another type"}}async text(){return(await this.bytes()).toString()}bytes(){let t=Nn.get(this),{start:r,end:n,contentBuffer:s}=t;if(s)return(n!==void 0||r!==void 0)&&(s=s.subarray(r??0,n??t.contentBuffer.length)),Promise.resolve(s);let i=Jh(t),o,c=a(async()=>{let l,u=Sr;try{if(l=await(0,ii.readFile)(i),l.length>=Sr){l.copy(Qh,0,0,Sr);let d=gT.getBigUint64(0);if(Number(d>>48n)===IW)throw new Error("Error in blob: "+buffer.subarray(Sr));if(u=Number(d&0xffffffffffffn),u<n&&(u=n),u<CW&&(this.size=u,this.#t))for(let _ of this.#t)_(u)}}catch(d){if(d.code!=="ENOENT")throw d;l=Buffer.alloc(0)}function f(d){if(u>d.length){let _=t.store,h=t.fileId+":blob";if(o)throw new Error("Incomplete blob");return new Promise((m,S)=>{if(_.attemptLock(h,0,()=>(o=!0,_.unlock(h,0),m(c()))))return o=!0,_.unlock(h,0),m(c())})}return(n!=null||r!=null)&&(d=d.subarray(r??0,n??d.length)),d}return a(f,"checkCompletion"),l[1]===uC?new Promise((d,_)=>{(0,AT.deflate)(l.subarray(Sr),(h,m)=>{h?_(h):d(f(m))})}):f(l.subarray(Sr))},"readContents");return c()}async arrayBuffer(){let t=await this.bytes(),r=new ArrayBuffer(t.length);return new Uint8Array(r).set(t),r}stream(){let t=Nn.get(this),{contentBuffer:r,start:n,end:s}=t;if(r)return(s!=null||n!=null)&&(r=r.subarray(n??0,s??t.contentBuffer.length)),new ReadableStream({pull(S){S.enqueue(r),S.close()}});let i=Jh(t),o,c=0,l=0,u,f,d,_=!1,h=this;return new ReadableStream({start(){let S=1e3,g=a((R,E)=>{(0,Xe.open)(i,"r",(T,w)=>{if(T){if(T.code==="ENOENT"&&d!==!1&&(Lo.default.debug?.("File does not exist yet, waiting for it to be created",i,S),S-- >0))return setTimeout(()=>{m(),g(R,E)},20).unref();E(T),h.#e?.forEach(v=>v(T))}else o=w,R(w)})},"openFile");return new Promise(g)},pull:a(S=>{let g=0,R=100;return new Promise(a(function E(T,w){function v(q){(0,Xe.close)(o),clearTimeout(f),u&&u.close(),w(q),h.#e?.forEach(W=>W(q))}a(v,"onError");let H=Buffer.allocUnsafe(262144);(0,Xe.read)(o,H,0,H.length,c,(q,W,te)=>{if(l+=W,q)return v(q);if(c===0){if(W<Sr){R-- >0&&d!==!1?(m(),Lo.default.debug?.("File was empty, waiting for data to be written",i,R),setTimeout(()=>E(T,w),20).unref()):(Lo.default.debug?.("File was empty, throwing error",i,R),w(new Error(`Blob ${t.fileId} was empty`)));return}te.copy(Qh,0,0,Sr);let se=gT.getBigUint64(0);if(Number(se>>48n)===IW)return v(new Error("Error in blob: "+te.subarray(Sr)));if(g=Number(se&0xffffffffffffn),g<CW&&h.size!==g&&(h.size=g,h.#t))for(let Y of h.#t)Y(g);te=te.subarray(Sr,W),l-=Sr}else if(W===0){let se=Buffer.allocUnsafe(8);return(0,Xe.read)(o,se,0,Sr,0,Y=>{if(Y)return v(Y);if(Qh.set(se),g=Number(gT.getBigUint64(0)&0xffffffffffffn),g>l){m()?u?f=setTimeout(()=>{v(new Error("File read timed out"))},oEe).unref():(u=(0,Xe.watch)(i,{persistent:!1},()=>{u.close(),u=null,f&&(clearTimeout(f),f=null,E(T,w))}),E(T,w)):_?v(new Error("Blob is incomplete")):(_=!0,E(T,w));return}(0,Xe.close)(o),S.close(),T()})}else te=te.subarray(0,W);if(n!==void 0||s!==void 0){if(n&&l<n)return c+=W,E(T,w);s&&l>=s&&(l>s&&(te=te.subarray(0,s-c)),l=g=s),n&&n>c&&(te=te.subarray(n-c))}c+=W;try{S.enqueue(te)}catch(se){return Lo.default.debug?.("Error enqueuing chunk",se),T()}l===g&&((0,Xe.close)(o),S.close()),T()})},"readMore"))},"pull"),cancel(){(0,Xe.close)(o),clearTimeout(f),u&&u.close()}});function m(){if(d===void 0){let S=t.store,g=t.fileId+":blob";d=!S.attemptLock(g,0,()=>{d=!1,S.unlock(g,0)}),d||S.unlock(g,0)}return d}}slice(t,r,n){let s=Nn.get(this),i=new e(n&&{type:n});if(s?.fileId){let o={...s,start:t,end:r};Nn.set(i,o),this.size!=null&&(i.size=(r==null?this.size:Math.min(r,this.size))-(t??0))}else if(s?.contentBuffer&&!s.storageBuffer){let o={...s,contentBuffer:s.contentBuffer.subarray(t,r)};Nn.set(i,o),i.size=(r??this.size)-t}else throw new Error("Can not slice a streaming blob that is not backed by a file");return i}save(t){if(wn=t?.primaryStore?.rootStore,!wn)throw new Error("No target table specified");return xW(this).saving??Promise.resolve()}},UW=500;a(JE,"deleteBlob");a(aEe,"setDeletionDelay");global.createBlob=function(e,t){let r=new ST(t),n={storageIndex:0,fileId:null,flush:t?.flush,compress:t?.compress};if(Nn.set(r,n),e instanceof Uint8Array)r.size=e.length,n.contentBuffer=e;else if(e instanceof jh.Readable)n.source=e;else if(typeof e=="string")n.contentBuffer=Buffer.from(e);else if(e?.[Symbol.asyncIterator]||e?.[Symbol.iterator])n.source=jh.Readable.from(e);else throw new Error("Invalid source type");return r};a(xW,"saveBlob");a(cC,"writeBlobWithStream");a(YE,"getFileId");a(BW,"getFilePathForBlob");lC=new Map;a(Xh,"getRootBlobPathsForDB");a(nC,"deleteRootBlobPathsForDB");a(HW,"rimrafSteadily");a(Jh,"getFilePath");a(cEe,"writeBlobWithBuffer");a(lEe,"generateFilePath");PW=new Map;a(uEe,"getNextFileId");TT=128;a(dEe,"getNextStorageIndex");a(fEe,"createFrequencyTableForStoragePaths");a(rp,"encodeBlobsWithFilePath");a(_Ee,"encodeBlobsAsBuffers");a(WE,"decodeBlobsWithWrites");a(zE,"decodeWithBlobCallback");a(_c,"decodeFromDatabase");a(ra,"deleteBlobsInObject");a(bd,"findBlobsInObject");(0,Mo.addExtension)({Class:mi,type:11,unpack:a(function(e){let t=(0,Mo.unpack)(e),r=new ST;if(Object.assign(r,t[0]),typeof t[1]!="object"){if(Nn.set(r,{storageIndex:t[1],fileId:t[2],store:wn}),bl)return bl(r)??r;if(!wn)throw new Error("No store specified, cannot load blob from storage")}else Nn.set(r,{storageIndex:0,fileId:null,storageBuffer:e,contentBuffer:t[1]}),r.size=t[1]?.length;return r},"unpack"),pack:a(function(e){let t=Nn.get(e);if(Cd!==void 0&&(fc=!0,t?.recordId!==void 0&&t.recordId!==Cd))throw new Error("Cannot use the same blob in two different records");let r={...e};if(e.type&&(r.type=e.type),e.size!==void 0&&(r.size=e.size),t){if(t.storageBuffer)return t.storageBuffer;if(t.contentBuffer?.length<LW)return r.size=t.contentBuffer.length,(0,Mo.pack)([r,t.contentBuffer])}if(Cd!==void 0){if(t=xW(e),!t.fileId)throw new Error("Unable to save blob without file id");return t.recordId=Cd,(0,Mo.pack)([r,t.storageIndex,t.fileId])}if(t)try{let n=(0,Xe.readFileSync)(Jh(t));if(n.length>=Sr&&(n.copy(Qh,0,0,Sr),Number(gT.getBigUint64(0)&0xffffffffffffn)===n.length-Sr))return Buffer.concat([(0,Mo.pack)([r]),n]);if(Br)Br.push(e.bytes());else throw new Error("Incomplete blob");return Buffer.alloc(0)}catch(n){if(n.code==="ENOENT"&&Br)return Br.push(e.bytes()),Buffer.alloc(0);throw n}else throw new Error("Blob has no storage info or buffer attached to it")},"pack")});(0,Mo.addExtension)({Class:Promise,type:12,pack(){throw new Error("Cannot encode a promise")}});a(hEe,"polyfillBlob")});var fC=P((bMe,kW)=>{"use strict";var Zh=le();Zh.initSync();var Pd=require("fs-extra"),dC=require("path"),Dd=(k(),D($)),mEe=require("crypto"),pEe=require("uuid").v4;kW.exports=EEe;function EEe(){if(Zh.getHdbBasePath()!==void 0){let e=dC.join(Zh.getHdbBasePath(),Dd.LICENSE_KEY_DIR_NAME,Dd.JWT_ENUM.JWT_PRIVATE_KEY_NAME),t=dC.join(Zh.getHdbBasePath(),Dd.LICENSE_KEY_DIR_NAME,Dd.JWT_ENUM.JWT_PUBLIC_KEY_NAME),r=dC.join(Zh.getHdbBasePath(),Dd.LICENSE_KEY_DIR_NAME,Dd.JWT_ENUM.JWT_PASSPHRASE_NAME);try{Pd.accessSync(r),Pd.accessSync(e),Pd.accessSync(t)}catch(n){if(n.code==="ENOENT"){let s=pEe(),i=mEe.generateKeyPairSync("rsa",{modulusLength:4096,publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs8",format:"pem",cipher:"aes-256-cbc",passphrase:s}});Pd.writeFileSync(r,s),Pd.writeFileSync(e,i.privateKey),Pd.writeFileSync(t,i.publicKey)}else throw n}}}a(EEe,"checkJWTTokenExist")});var GW=P((NMe,FW)=>{"use strict";var _C=class{static{a(this,"HdbInfoInsertObject")}constructor(t,r,n){this.info_id=t,this.data_version_num=r,this.hdb_version_num=n}};FW.exports={HdbInfoInsertObject:_C}});var VW=P((IMe,$W)=>{"use strict";var qW=(k(),D($)),hC=class{static{a(this,"UpgradeObject")}constructor(t,r){this[qW.UPGRADE_JSON_FIELD_NAMES_ENUM.DATA_VERSION]=t,this[qW.UPGRADE_JSON_FIELD_NAMES_ENUM.UPGRADE_VERSION]=r}};$W.exports={UpgradeObject:hC}});var yT=P((PMe,YW)=>{"use strict";var ws=require("prompt"),Ld=require("chalk"),KW=j(),oi=require("os"),mC=rc(),pC=["yes","y"];async function gEe(e){let t=`${oi.EOL}`+Ld.bold.green("Your current HarperDB version requires that we complete an update process.")+`${oi.EOL}If a backup of your data has not been created, we recommend you cancel this process and backup before proceeding.${oi.EOL}${oi.EOL}You can read more about the changes in this upgrade at https://harperdb.io/developers/release-notes/${oi.EOL}`;ws.override=mC(["CONFIRM_UPGRADE"]),ws.start(),ws.message=t;let r={properties:{CONFIRM_UPGRADE:{description:Ld.magenta(`${oi.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 ws.get([r])}catch(s){return KW.error("There was an error when prompting user about an upgrade."),KW.error(s),!1}return pC.includes(n.CONFIRM_UPGRADE)}a(gEe,"forceUpdatePrompt");async function SEe(e){let t=`${oi.EOL}`+Ld.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.${oi.EOL}`);ws.override=mC(["CONFIRM_DOWNGRADE"]),ws.start(),ws.message=t;let r={properties:{CONFIRM_DOWNGRADE:{description:Ld.magenta(`${oi.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 ws.get([r]);return pC.includes(n.CONFIRM_DOWNGRADE)}a(SEe,"forceDowngradePrompt");async function TEe(){let e=`${oi.EOL}`+Ld.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");ws.override=mC(["GENERATE_CERTS"]),ws.start(),ws.message=e;let t={properties:{GENERATE_CERTS:{description:Ld.magenta(`${oi.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 ws.get([t]);return pC.includes(r.GENERATE_CERTS)}a(TEe,"upgradeCertsPrompt");YW.exports={forceUpdatePrompt:gEe,forceDowngradePrompt:SEe,upgradeCertsPrompt:TEe}});var gC=P((LMe,WW)=>{"use strict";var EC=class{static{a(this,"UpgradeDirective")}constructor(t){this.version=t,this.sync_functions=[],this.async_functions=[]}};WW.exports=EC});var QW=P((HMe,zW)=>{"use strict";var AEe=ae(),REe=Ct(),vMe=j(),UMe=require("path"),xMe=require("fs"),BMe=(k(),D($));zW.exports={getOldPropsValue:yEe};function yEe(e,t,r=!1){let n=t.getRaw(e);return AEe.isNotEmptyAndHasValue(n)?n:r?REe.getDefaultConfig(e):""}a(yEe,"getOldPropsValue")});var ZW=P((FMe,XW)=>{"use strict";var $a=require("path"),Va=require("fs-extra"),bEe=require("properties-reader"),OEe=gC(),lr=j(),{getOldPropsValue:ht}=QW(),{HDB_SETTINGS_NAMES:ge,CONFIG_PARAMS:Ol}=(k(),D($)),Nl=Ct(),bT=le(),jW=ae(),Bi=(k(),D($)),SC=new OEe("3.1.0"),JW=[];function NEe(){let e=bEe(bT.get(ge.SETTINGS_PATH_KEY)),t="Updating settings file for version 3.1.0";console.log(t),lr.info(t);let r=` ;Settings for the HarperDB process.
|
|
39
|
+
`;Te.message=`${ye}${Te.message}`,Te.stack=`${ye}${Te.stack}`,vh?.(Te),El.default.error(Te),t.set(_.path||"/",new Zo(Te)),Ad.set(n?d:(0,gt.basename)(e),Te.message)}}}}catch(S){S.message=`Could not load component '${d}' for application '${(0,gt.basename)(e)}' due to: ${S.message}`,vh?.(S),((0,Uh.getWorkerIndex)()===0?console:El.default).error(S),t.set(_.path||"/",new Zo(S),null,!0),Ad.set(n?d:(0,gt.basename)(e),S.message)}}if($S=u,Td.isMainThread&&!nY&&i&&(0,Uh.watchDir)(e,async()=>sY()),c.extensionModule){let d=await nE((0,gt.join)(e,c.extensionModule));return qS.set(o,d),d}if(!f&&t.isWorker){let d=`${e} did not load any modules, resources, or files, is this a valid component?`;vh?.(new Error(d)),((0,Uh.getWorkerIndex)()===0?console:El.default).error(d),Ad.set((0,gt.basename)(e),d)}}catch(c){console.error(`Could not load application directory ${e}`,c),c.message=`Could not load application due to ${c.message}`,vh?.(c),t.set("",new Zo(c))}}var ct,gt,Td,OI,CI,PI,tY,Uh,El,rY,NI,Uhe,KS,xhe,yI,wI,nY,bI,Ad,Bhe,II,eY,qS,vh,$S,khe,ph=be(()=>{ct=require("fs"),gt=require("path"),Td=require("worker_threads"),OI=require("yaml"),CI=M(le()),PI=M(mt());k();PD();tL();Px();vx();Ux();SB();eK();oK();cK();tY=M(require("fast-glob")),Uh=M(tt()),El=M(j());lb();Pr();rY=M(me());ve();lI();NI=M(le()),Uhe=M(MK());Kg();GK();fs();ZK();KS=M(Ct());lE();wA();({readFile:xhe}=ct.promises),yI=(0,KS.resolvePath)(CI.get(U.COMPONENTSROOT)),wI=new Map,Ad=new Map;a(sY,"loadComponentDirectories");Bhe={REST:dE,rest:dE,graphql:GA,graphqlSchema:PA,roles:cb,jsResource:db,fastifyRoutes:eI,login:_b,static:tI,operationsApi:Uhe,customFunctions:{},http:{},clustering:pI,replication:ga,authentication:ch,mqtt:RI,loadEnv:rI},II={rest:!0,graphqlSchema:{files:"*.graphql"},roles:{files:"roles.yaml"},jsResource:{files:"resources.js"},fastifyRoutes:{files:"routes/*.js",path:"."}};Object.defineProperty(II,"static",{value:{files:"web/**"}});eY=[],qS=new Map;a(Hhe,"setErrorReporter");khe=a(()=>$S,"getComponentName");a(Fhe,"symlinkHarperModule");a(VS,"loadComponent")});var MS=P((OLe,oY)=>{var{isMainThread:iY}=require("worker_threads"),{getTables:Ghe,getDatabases:yLe,table:bLe}=(ve(),D(it)),{loadComponentDirectories:qhe,loadComponent:$he}=(ph(),D(mh)),{resetResources:Vhe}=(zl(),D(wD)),Khe=XN(),Yhe=Ct(),{dirname:Whe}=require("path"),{getConnection:zhe}=hr(),Qhe=le(),{CONFIG_PARAMS:jhe}=(k(),D($)),{loadCertificates:Jhe}=js(),DI=new Map;async function Xhe(e=!1){!iY&&Qhe.get(jhe.CLUSTERING_ENABLED)&&zhe();try{iY&&await Khe()}catch(n){console.error(n)}let t=Vhe();Ghe(),t.isWorker=e,await Jhe(),await $he(Whe(Yhe.getConfigFilePath()),t,"hdb",!0,DI),await qhe(DI,t);let r=[];for(let[n]of DI)n.ready&&r.push(n.ready());r.length>0&&await Promise.all(r)}a(Xhe,"loadRootComponents");oY.exports.loadRootComponents=Xhe});var tt=P((wLe,si)=>{"use strict";JT();var{Worker:Zhe,MessageChannel:eme,parentPort:vi,isMainThread:xI,threadId:tme,workerData:Ui}=require("worker_threads"),{PACKAGE_ROOT:rme}=mt(),{join:uY,isAbsolute:nme,extname:sme}=require("path"),{server:dY}=(Pr(),D(Yl)),{watch:ime,readdir:ome}=require("fs/promises"),{totalmem:aY}=require("os"),Rd=(k(),D($)),fY=le(),ni=j(),{randomBytes:ame}=require("crypto"),{_assignPackageExport:cme}=ci(),cY=1024*1024,Ha=[],bs=[],lme=50,BI=1e4,ume="restart",_Y="request_thread_info",hY="resource_report",mY="thread_info",pY="added-port",dme="ack",LI;cme("threads",bs);si.exports={startWorker:MI,restartWorkers:kI,shutdownWorkers:pme,workers:Ha,setMonitorListener:bme,onMessageFromWorkers:Eme,onMessageByType:yY,broadcast:Sme,broadcastWithAcknowledgement:Ame,setChildListenerByType:mme,getWorkerIndex:EY,getWorkerCount:gY,getTicketKeys:TY,setMainIsWorker:_me,setTerminateTimeout:fme,restartNumber:Ui?.restartNumber||1};bs.onMessageByType=yY;bs.sendToThread=function(e,t){if(!t?.type)throw new Error("A message with a type must be provided");let r=bs.find(n=>n.threadId===e);if(r)return r.postMessage(t),!0};si.exports.whenThreadsStarted=new Promise(e=>{si.exports.threadsHaveStarted=e});var HI;function fme(e){BI=e}a(fme,"setTerminateTimeout");function EY(){return Ui?Ui.workerIndex:HI?0:void 0}a(EY,"getWorkerIndex");function gY(){return Ui?Ui.workerCount:HI?1:void 0}a(gY,"getWorkerCount");function _me(e){HI=e,si.exports.threadsHaveStarted()}a(_me,"setMainIsWorker");var SY=1,YS;function TY(){return YS||(YS=xI?ame(48):Ui.ticketKeys,YS)}a(TY,"getTicketKeys");Object.defineProperty(dY,"workerIndex",{get(){return EY()}});Object.defineProperty(dY,"workerCount",{get(){return gY()}});var AY={[_Y](e,t){Rme(t)},[hY](e,t){yme(t,e)}};function MI(e,t={}){let r=process.constrainedMemory?.()||aY();r=Math.min(r,aY(),2e4*cY);let n=fY.get(Rd.CONFIG_PARAMS.THREADS_MAXHEAPMEMORY)??Math.max(Math.floor(r/cY/(10+(t.threadCount||1)/4)),512),s=Math.min(Math.max(n>>6,16),64),i=[],o=[];for(let l of bs){let u=new eme;u.existingPort=l,i.push(u),o.push(u.port2)}sme(e)||(e+=".js");let c=new Zhe(nme(e)?e:uY(rme,e),{resourceLimits:{maxOldGenerationSizeMb:n,maxYoungGenerationSizeMb:s},execArgv:["--enable-source-maps","--expose-internals"],argv:process.argv.slice(2),workerData:{addPorts:o,addThreadIds:i.map(l=>l.existingPort.threadId),workerIndex:t.workerIndex,workerCount:SY=t.threadCount,name:t.name,restartNumber:si.exports.restartNumber,ticketKeys:TY()},transferList:o,...t});for(let{port1:l,existingPort:u}of i)u.postMessage({type:pY,port:l,threadId:c.threadId},[l]);return zS(c,!0),c.unexpectedRestarts=t.unexpectedRestarts||0,c.startCopy=()=>MI(e,t),c.on("error",l=>{ni.error(`Worker index ${t.workerIndex} error:`,l)}),c.on("exit",l=>{Ha.splice(Ha.indexOf(c),1),!c.wasShutdown&&t.autoRestart!==!1&&(c.unexpectedRestarts<lme?(t.unexpectedRestarts=c.unexpectedRestarts+1,MI(e,t)):ni.error(`Thread has been restarted ${c.restarts} times and will not be restarted`))}),c.on("message",l=>{AY[l.type]?.(l,c)}),Ha.push(c),Nme(),t.onStarted&&t.onStarted(c),c.name=t.name,c}a(MI,"startWorker");var hme=[Rd.THREAD_TYPES.HTTP];async function kI(e=null,t=Math.max(SY>3,1),r=!0){if(xI){try{process.chdir(process.cwd())}catch(o){ni.error("Unable to reestablish current working directory",o)}if(r){let{loadRootComponents:o}=MS();await o()}si.exports.restartNumber++,t<1&&(t=t*Ha.length);let n=[],s=[];for(let o of Ha.slice(0)){if(e&&o.name!==e||o.wasShutdown)continue;ni.trace("sending shutdown request to ",o.threadId),o.postMessage({restartNumber:si.exports.restartNumber,type:Rd.ITC_EVENT_TYPES.SHUTDOWN}),o.wasShutdown=!0,o.emit("shutdown",{});let c=hme.indexOf(o.name)>-1,l=new Promise(u=>{let f=setTimeout(()=>{ni.warn("Thread did not voluntarily terminate, terminating from the outside",o.threadId),o.terminate()},BI*2).unref();o.on("exit",()=>{clearTimeout(f),n.splice(n.indexOf(l)),!c&&r&&o.startCopy(),u()})});if(n.push(l),c&&r){let u=o.startCopy(),f=new Promise(d=>{let _=a(h=>{h.type===Rd.ITC_EVENT_TYPES.CHILD_STARTED&&(ni.trace("Worker has started",u.threadId),d(),s.splice(s.indexOf(f)),u.off("message",_))},"startListener");ni.trace("Waiting for worker to start",u.threadId),u.on("message",_)});s.push(f),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}=rd();r&&(e==="http"||!e)&&fY.get(Rd.CONFIG_PARAMS.CLUSTERING_ENABLED)&&await i({service:"clustering"})}else vi.postMessage({type:ume,workerType:e})}a(kI,"restartWorkers");function mme(e,t){AY[e]=t}a(mme,"setChildListenerByType");function pme(e){return kI(e,1/0,!1)}a(pme,"shutdownWorkers");var RY=[];function Eme(e){RY.push(e)}a(Eme,"onMessageFromWorkers");var vI=new Map;function yY(e,t){let r=vI.get(e);r||vI.set(e,r=[]),r.push(t)}a(yY,"onMessageByType");var gme=10;async function Sme(e,t){let r=0;for(let n of bs)try{n.postMessage(e),r++>gme&&(r=0,await new Promise(setImmediate))}catch(s){ni.error("Unable to send message to worker",s)}t&&OY(e,null)}a(Sme,"broadcast");var WS=new Map,Tme=1;function Ame(e){return new Promise(t=>{let r=0;for(let n of bs)try{let s=Tme++,i=a(()=>{WS.delete(s),--r===0&&t(),n!==vi&&--n.refCount===0&&n.unref()},"ack_handler");i.port=n,n.ref(),n.refCount=(n.refCount||0)+1,WS.set(e.requestId=s,i),n.hasAckCloseListener||(n.hasAckCloseListener=!0,n.on(n.close?"close":"exit",()=>{for(let[,o]of WS)o.port===n&&o()})),n.postMessage(e),r++}catch(s){ni.error("Unable to send message to worker",s)}r===0&&t()})}a(Ame,"broadcastWithAcknowledgement");function Rme(e){e.postMessage({type:mY,workers:bY()})}a(Rme,"sendThreadInfo");function bY(){let e=Date.now();return Ha.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}))}a(bY,"getChildWorkerInfo");function yme(e,t){e.resources=t,e.resources.updated=Date.now()}a(yme,"recordResourceReport");var UI;function bme(e){UI=e}a(bme,"setMonitorListener");var Ome=1e3,lY=!1;function Nme(){lY||(lY=!0,setInterval(()=>{for(let e of Ha){let t=e.performance.eventLoopUtilization(),r;e.lastTotalELU?r=e.performance.eventLoopUtilization(t,e.lastTotalELU):r=t,e.lastTotalELU=t,e.recentELU=r}UI&&UI()},Ome).unref())}a(Nme,"startMonitoring");var wme=1e3;if(vi&&Ui?.addPorts){zS(vi);for(let e=0,t=Ui.addPorts.length;e<t;e++){let r=Ui.addPorts[e];r.threadId=Ui.addThreadIds[e],zS(r)}setInterval(()=>{let e=process.memoryUsage();vi.postMessage({type:hY,heapTotal:e.heapTotal,heapUsed:e.heapUsed,external:e.external,arrayBuffers:e.arrayBuffers})},wme).unref(),LI=a(()=>new Promise((e,t)=>{vi.on("message",r),vi.postMessage({type:_Y});function r(n){n.type===mY&&(vi.off("message",r),e(n.workers))}a(r,"receiveThreadInfo")}),"getThreadInfo")}else LI=bY;si.exports.getThreadInfo=LI;function zS(e,t){bs.push(e),e.on("message",r=>{if(r.type===pY)r.port.threadId=r.threadId,zS(r.port);else if(r.type===dme){let n=WS.get(r.id);n&&n()}else OY(r,e)}).on("close",()=>{bs.splice(bs.indexOf(e),1)}).on("exit",()=>{bs.splice(bs.indexOf(e),1)}),t?e.refCount=100:e.unref()}a(zS,"addPort");function OY(e,t){for(let n of RY)n(e,t);let r=vI.get(e.type);if(r)for(let n of r)try{n(e,t)}catch(s){ni.error(s)}}a(OY,"notifyMessageListeners");if(xI){let e,t,r=new Set,n=a(async(s,i)=>{i&&(e=i);for(let o of await ome(s,{withFileTypes:!0}))o.isDirectory()&&o.name!=="node_modules"&&n(uY(s,o.name));try{for await(let{filename:o}of ime(s,{persistent:!1}))r.add(o),t&&clearTimeout(t),t=setTimeout(async()=>{e&&await e(),await kI(),console.log("Reloaded HarperDB components, changed files:",Array.from(r)),r.clear()},100)}catch(o){console.warn("Error trying to watch component directory",s,o)}},"watch_dir");si.exports.watchDir=n,process.env.WATCH_DIR&&n(process.env.WATCH_DIR)}else vi.on("message",async e=>{let{type:t}=e;t===Rd.ITC_EVENT_TYPES.SHUTDOWN&&(si.exports.restartNumber=e.restartNumber,vi.unref(),setTimeout(()=>{ni.warn("Thread did not voluntarily terminate",tme),process.exit(0)},BI).unref())})});var PY={};Ue(PY,{onStorageReclamation:()=>xh,runReclamationHandlers:()=>$I,setAvailableSpaceRatioGetter:()=>Cme});function xh(e,t,r){(r||(0,jS.getWorkerIndex)()===(0,jS.getWorkerCount)()-1)&&(QS.has(e)||QS.set(e,[]),QS.get(e).push({priority:0,handler:t}),qI||(qI=setTimeout($I,wY).unref()))}async function $I(){for(let[e,t]of QS)try{let r=await CY(e),n=Ime/r;for(let s of t){let{priority:i,handler:o}=s;if(s.priority=n,n>1||i>1){let c=o(n>1?n:0);c&&(GI.default.info?.(`Running storage reclamation handler for ${e} with priority ${n}`),await c)}}}catch(r){GI.default.error?.("Error running storage reclamation handlers",r)}qI=setTimeout($I,wY).unref()}function Cme(e){CY=e??IY}var FI,jS,GI,JS,NY,QS,Ime,wY,qI,IY,CY,XS=be(()=>{FI=require("node:fs/promises"),jS=M(tt()),GI=M(_i());k();JS=M(le()),NY=M(ae());JS.default.initSync();QS=new Map,Ime=JS.default.get(U.STORAGE_RECLAMATION_THRESHOLD)??.4,wY=(0,NY.convertToMS)(JS.default.get(U.STORAGE_RECLAMATION_INTERVAL))||36e5;a(xh,"onStorageReclamation");IY=a(async e=>{if(FI.statfs){let t=await(0,FI.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"),CY=IY;a($I,"runReclamationHandlers");a(Cme,"setAvailableSpaceRatioGetter")});var Q0={};Ue(Q0,{ACTION_32_BIT:()=>tp,ACTION_64_BIT:()=>Mme,AUDIT_STORE_OPTIONS:()=>nh,Decoder:()=>Qc,HAS_BLOBS:()=>fn,HAS_CURRENT_RESIDENCY_ID:()=>mc,HAS_EXPIRATION_EXTENDED_TYPE:()=>Rf,HAS_ORIGINATING_OPERATION:()=>Af,HAS_PREVIOUS_RESIDENCY_ID:()=>pc,REMOTE_SEQUENCE_UPDATE:()=>KE,createAuditEntry:()=>Jl,getLastRemoved:()=>Dme,openAuditStore:()=>tT,readAuditEntry:()=>Nt,removeAuditEntry:()=>rT,setAuditRetention:()=>Lme,transactionKeyEncoder:()=>kY});function tT(e){let t=e.auditStore=e.openDB(VI.AUDIT_STORE_NAME,{create:!1,...nh});t||(t=e.auditStore=e.openDB(VI.AUDIT_STORE_NAME,nh),LY(t,1)),t.rootStore=e,t.tableStores=[];let r=[];t.addDeleteRemovalCallback=function(l,u,f){return r[l]=f,t.tableStores[l]=u,t.deleteCallbacks=r,{remove(){delete r[l]}}};let n=null,s,i=0,o=YI;xh(t.env.path,l=>{if(i=l,l)return c(100)});function c(l){l&&(o=l),clearTimeout(n);let u=new Promise(f=>{n=setTimeout(async()=>{if(await s,s=u,t.rootStore.status==="closed"||t.rootStore.status==="closing")return;let d=0,_,h;try{for(let{key:m,value:S}of t.getRange({start:1,snapshot:!1,end:Date.now()-KI/(1+i*i)})){try{_=rT(t,m,S)}catch(g){yd.warn("Error removing audit entry",g)}if(h=m,await new Promise(setImmediate),++d>=Pme){o=10;break}}await _}finally{d===0?o=Math.min(o<<1,KI/10):(LY(t,h),o>100&&(o=o>>1)),f(void 0),c()}},o).unref()});return u}if(a(c,"scheduleAuditCleanup"),t.scheduleAuditCleanup=c,(0,Hh.getWorkerIndex)()===(0,Hh.getWorkerCount)()-1&&c(),(0,Hh.getWorkerIndex)()===0&&!DY)for(let l of t.getKeys({reverse:!0,limit:1}))l>Date.now()&&(DY=!0,yd.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 rT(e,t,r){let n=vme(r),s;if(n&fn){s=Nt(r);let i=e.tableStores[s.tableId],o=i?.getEntry(s.recordId);(!o||o.version!==s.version||!o.value)&&_c(()=>ra(s.getValue(i)),i.rootStore)}if((n&15)===WI){s=s||Nt(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 LY(e,t){zI[0]=t,e.put(Symbol.for("last-removed"),FY)}function Dme(e){let t=e.get(Symbol.for("last-removed"));if(t)return FY.set(t),zI[0]}function Lme(e,t=YI){KI=e,YI=t}function Jl(e,t,r,n,s,i,o,c,l,u,f,d,_){let h=GY[o];if(!h)throw new Error(`Invalid audit entry type ${o}`);let m=1;if(n&&(n>1?ka.setFloat64(0,n):Os.set(JA),m=9),l){if(l&255)throw new Error("Illegal extended type");m+=3}R(s),R(t),g(r),ka.setFloat64(m,e),m+=8,l&mc&&R(u),l&pc&&R(f),l&Rf&&(ka.setFloat64(m,d),m+=8),l&Af&&R(qY[_]),i?g(i):Os[m++]=0,l?ka.setUint32(n?8:0,h|l|3221225472):Os[n?8:0]=h;let S=Os.subarray(0,m);if(c)return Buffer.concat([S,c]);return S;function g(E){let T=m;m+=1,m=(0,gl.writeKey)(E,Os,m);let w=m-T-1;w>127?w>16383?(yd.error("Key or username was too large for audit entry",E),m=T+1,Os[T]=0):(Os.copyWithin(T+2,T+1,m),ka.setUint16(T,w|32768),m++):Os[T]=w}function R(E){E<128?Os[m++]=E:E<16384?(ka.setUint16(m,E|32768),m+=2):E<1056964608?(ka.setUint32(m,E|3221225472),m+=4):(Os[m]=255,ka.setUint32(m+1,E),m+=5)}}function vme(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 Qc(e.buffer,e.byteOffset,e.byteLength));return n.position=t,n.readInt()}function Nt(e,t=0,r=void 0){try{let n=e.dataView||(e.dataView=new Qc(e.buffer,e.byteOffset,e.byteLength));n.position=t;let s;e[n.position]==66&&(s=n.readFloat64());let i=n.readInt(),o=n.readInt(),c=n.readInt(),l=n.readInt(),u=n.position,f=n.position+=l,d=n.readFloat64(),_,h,m,S;if(i&mc&&(_=n.readInt()),i&pc&&(h=n.readInt()),i&Rf&&(m=n.readFloat64()),i&Af){let T=n.readInt();S=qY[T]}l=n.readInt();let g=n.position,R=n.position+=l,E;return{type:GY[i&7],tableId:c,nodeId:o,get recordId(){return(0,gl.readKey)(e,u,f)},getBinaryRecordId(){return e.subarray(u,f)},version:d,previousLocalTime:s,get user(){return R>g?(0,gl.readKey)(e,g,R):void 0},get encoded(){return t?e.subarray(t,r):e},getValue(T,w,v){if(i&ZS||i&Bh&&!w)return E||(E=_c(()=>T.decoder.decode(e.subarray(n.position,r)),T.rootStore)),E;if(i&Bh&&v)return Wy(T.getEntry(this.recordId),v,T)},getBinaryValue(){return i&(ZS|Bh)?e.subarray(n.position,r):void 0},extendedType:i,residencyId:_,previousResidencyId:h,expiresAt:m,originatingOperation:S}}catch(n){return yd.error("Reading audit entry error",n,e),{}}}var gl,eT,VI,Hh,HY,yd,Os,ka,kY,nh,KI,Pme,zI,FY,YI,DY,ZS,Bh,MY,WI,vY,UY,xY,BY,tp,Mme,KE,mc,pc,Af,Rf,fn,GY,qY,Qc,Zi=be(()=>{gl=require("ordered-binary"),eT=M(le()),VI=M(Ut());k();Hh=M(tt()),HY=M(ae());Xl();yd=M(j());Vp();cs();XS();(0,eT.initSync)();Os=Buffer.alloc(2816),ka=new DataView(Os.buffer,Os.byteOffset,2816),kY={writeKey(e,t,r){return e===Tf?(t.set(Tf,r),r+8):typeof e=="number"?((t.dataView||(t.dataView=new DataView(t.buffer,t.byteOffset,t.byteLength))).setFloat64(r,e),r+8):(0,gl.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,gl.readKey)(e,t,r)}},nh={encoding:"binary",keyEncoder:kY},KI=(0,HY.convertToMS)((0,eT.get)(U.LOGGING_AUDITRETENTION))||86400*3,Pme=1e3,zI=new Float64Array(1),FY=new Uint8Array(zI.buffer),YI=1e4,DY=!1;a(tT,"openAuditStore");a(rT,"removeAuditEntry");a(LY,"updateLastRemoved");a(Dme,"getLastRemoved");a(Lme,"setAuditRetention");ZS=16,Bh=32,MY=1,WI=2,vY=3,UY=4,xY=5,BY=6,tp=14,Mme=15,KE=11,mc=512,pc=1024,Af=2048,Rf=4096,fn=8192,GY={put:MY|ZS,[MY]:"put",delete:WI,[WI]:"delete",message:vY|ZS,[vY]:"message",invalidate:UY|Bh,[UY]:"invalidate",patch:xY|Bh,[xY]:"patch",relocate:BY,[BY]:"relocate"},qY={insert:1,update:2,upsert:3,1:"insert",2:"update",3:"upsert"};a(Jl,"createAuditEntry");a(vme,"readAction");a(Nt,"readAuditEntry");Qc=class extends DataView{static{a(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}}}});function JI(e,t,r,n,s){let i=e.primaryStore.env.path,o=e.primaryStore.tableId,c;s?.crossThreads===!1?(c=VY,Ume(e.primaryStore,e.auditStore)):(c=$Y,e.primaryStore.env.hasSubscriptionCommitListener||(e.primaryStore.env.hasSubscriptionCommitListener=!0,e.primaryStore.on("committed",()=>{KY($Y[i])})));let l=c[i]||(c[i]=[]);if(l.auditStore=e.auditStore,l.lastTxnTime==null&&(l.lastTxnTime=Date.now()),s?.scope==="full-database")return;let u=l[o];u||(u=l[o]=new Map,u.envs=l,u.tableId=o,u.store=e.primaryStore),t=Wl(t);let f=new jI(r);f.startTime=n;let d=u.get(t);return d?d.push(f):(u.set(t,d=[f]),d.tables=u,d.key=t),f.subscriptions=d,f}function KY(e){if(!e)return;let t=e.auditStore;t.resetReadTxn(),YY(e.auditStore);let r;for(let{key:n,value:s}of t.getRange({start:e.lastTxnTime,exclusiveStart:!0})){e.lastTxnTime=n;let i=Nt(s),o=e[i.tableId];if(!o)continue;let c=i.recordId,l=Wl(c),u=0;do{let f=o.get(l);if(f){for(let _ of f)if(!(u>0&&!(_.includeDescendants&&!(_.onlyChildren&&u>1)))){if(_.startTime>=n){(0,QI.info)("omitting",c,_.startTime,n);continue}try{let h;_.supportsTransactions&&_.txnInProgress!==i.version&&(h=!0,_.txnInProgress||(r?r.push(_):r=[_]),_.txnInProgress=i.version),_.listener(c,i,n,h)}catch(h){console.error(h),(0,QI.info)(h)}}}if(l==null)break;let d=l.lastIndexOf?.("/",l.length-2);d!==l.length-1&&u++,d>-1?l=l.slice(0,d+1):l=null}while(!0)}if(r)for(let n of r)n.txnInProgress=null,n.listener(null,{type:"end_txn"},e.lastTxnTime,!0)}function Ume(e,t){let r=t||e,n=r.env;if(!n.hasAfterCommitListener){n.hasAfterCommitListener=!0;let s=n.path;r.on("aftercommit",({next:i,last:o,txnId:c})=>{let l=VY[s];if(!l)return;let u=a(()=>{r.threadLocalWrites||(r.threadLocalWrites=new Float64Array(r.getUserSharedBuffer("last-thread-local-write",new ArrayBuffer(8)))),l.txnTime=r.threadLocalWrites[0]||Date.now();try{KY(l)}finally{r.threadLocalWrites[0]=l.lastTxnTime,r.unlock("thread-local-writes")}},"acquiredLock");r.attemptLock("thread-local-writes",u)&&u()})}}function YY(e){e.nextTransaction?.resolve();let t;e.nextTransaction=new Promise(r=>{t=r}),e.nextTransaction.resolve=t}function Tk(e){return e.nextTransaction||(JI({primaryStore:e,auditStore:e},null,null,0,{scope:"full-database"}),YY(e)),e.nextTransaction}var QI,$Y,VY,jI,bO=be(()=>{QI=M(j());Gl();zl();Zi();$Y=Object.create(null),VY=Object.create(null);a(JI,"addSubscription");jI=class extends Dn{static{a(this,"Subscription")}listener;subscriptions;startTime;constructor(t){super(),this.listener=t,this.on("close",()=>this.end())}end(){if(this.subscriptions){if(this.subscriptions.splice(this.subscriptions.indexOf(this),1),this.subscriptions.length===0){let t=this.subscriptions.tables;if(t){let r=this.subscriptions.key;if(t.delete(r),t.size===0){let n=t.envs,s=t.dbi;delete n[s]}}}this.subscriptions=null}}toJSON(){return{name:"subscription"}}};a(KY,"notifyFromTransactionData");a(Ume,"listenToCommits");a(YY,"nextTransaction");a(Tk,"whenNextTransaction")});var Uw={};Ue(Uw,{EVICTED:()=>Jo,INVALIDATED:()=>un,coerceType:()=>iT,makeTable:()=>aT,setServerUtilities:()=>$me});function aT(e){let{primaryKey:t,indices:r,tableId:n,tableName:s,primaryStore:i,databasePath:o,databaseName:c,auditStore:l,schemaDefined:u,dbisDB:f,sealed:d,splitSegments:_,replicate:h}=e,{expirationMS:m,evictionMS:S,audit:g,trackDeletes:R}=e;S??=0;let{attributes:E}=e;E||(E=[]);let T=eR(i,n,l),w,v,H={},q=Promise.resolve(),W,te,se;for(let K of E)(K.assignCreatedTime||K.name==="__createdtime__")&&(W=K),(K.assignUpdatedTime||K.name==="__updatedtime__")&&(te=K),K.expiresAt&&(se=K),K.isPrimaryKey&&(H=K);let Y,ne=[],ue=[],oe=1,pe=2,Te={},ye={},Qt=864e5,lt=0,Tr,ss,Cn,Ml=!1,vl,$T=new Map,VT=new Map,vt,Hd,hm=Tl.get(U.REPLICATION_DATABASES);if(Array.isArray(hm)){for(let K of hm)if(K.name===c&&K.replicateTo>=0){Hd=K.replicateTo;break}}let mm=i.getRange({start:!1,end:!1}).constructor,kd=10,pm=6;g&&$d(),xh(i.env.path,K=>{if(v)return Vi(K)});class Ce extends qr{#e;#t;#n;#r;#s;#i;static name=s;static primaryStore=i;static auditStore=l;static primaryKey=t;static tableName=s;static tableId=n;static indices=r;static audit=g;static databasePath=o;static databaseName=c;static attributes=E;static replicate=h;static sealed=d;static splitSegments=_??!0;static createdTimeProperty=W;static updatedTimeProperty=te;static propertyResolvers;static userResolvers={};static sources=[];static getResidencyById;static get expirationMS(){return m}static dbisDB=f;static schemaDefined=u;static sourcedFrom(p,O){if(O&&(this.sourceOptions=O,(O.expiration||O.eviction||O.scanInterval)&&this.setTTLExpiration(O)),O?.intermediateSource)p.intermediateSource=!0,this.sources.unshift(p);else{if(this.sources.some(I=>!I.intermediateSource)){if(this.sources.some(I=>I.name===p.name))return;throw new Error("Can not have multiple canonical (non-intermediate) sources")}this.sources.push(p)}v=v||p.get&&(!p.get.reliesOnPrototype||p.prototype.get),w=w||p.load;let A=a(I=>{let L=this.sources;if(L=L.filter(B=>B.intermediateSource&&B[I]&&(!B[I].reliesOnPrototype||B.prototype[I])),L.length>0)if(L.length===1){let B=L[0];return(N,x,G)=>{if(N?.source!==B)return B[I](x,G,N)}}else return(B,N,x)=>{let G=[];for(let z of L){if(B?.source===z)break;G.push(z[I](N,x,B))}return Promise.all(G)}},"getApplyToIntermediateSource"),y=this.sources[this.sources.length-1];y.intermediateSource&&(y={});let b=a(I=>{if(y[I]&&(!y[I].reliesOnPrototype||y.prototype[I]))return(L,B,N)=>{if(!L?.source)return y[I](B,N,L)}},"getApplyToCanonicalSource");Te={put:b("put"),patch:b("patch"),delete:b("delete"),publish:b("publish")},ye={put:A("put"),patch:A("patch"),delete:A("delete"),publish:A("publish"),invalidate:A("invalidate")};let C=y.shouldRevalidateEvents;return(async()=>{let I=!1,L,B=a(async(N,x)=>{let G=N.value,z=N.table?Ve[c][N.table]:Ce;if(c===Yd&&(N.table===kl.ROLE_TABLE_NAME||N.table===kl.USER_TABLE_NAME)&&(I=!0),N.id===void 0&&(N.id=G[z.primaryKey],N.id===void 0))throw new Error("Replication message without an id "+JSON.stringify(N));N.source=p;let ie={residencyId:Za(N.residencyList),isNotification:!0,ensureLoaded:!1,nodeId:N.nodeId},F=await z.getResource(N.id,x,ie);switch(N.finished&&await N.finished,N.type){case"put":return C?F._writeInvalidate(G,ie):F._writeUpdate(G,!0,ie);case"patch":return C?F._writeInvalidate(G,ie):F._writeUpdate(G,!1,ie);case"delete":return F._writeDelete(ie);case"publish":case"message":return F._writePublish(G,ie);case"invalidate":return F._writeInvalidate(G,ie);case"relocate":return F._writeRelocate(ie);default:xe.default.error?.("Unknown operation",N.type,N.id)}},"writeUpdate");try{let N=p.subscribe;N&&R==null&&(R=!0);let x={crossThreads:!1,inTransactionUpdates:!0,supportsTransactions:!0,omitCurrent:!0},G=p.subscribeOnThisThread?p.subscribeOnThisThread((0,Sl.getWorkerIndex)(),x):(0,Sl.getWorkerIndex)()===0,z=N&&G&&await p.subscribe?.(x);if(z){let ie;for await(let F of z)try{if(!(F.type==="transaction"?F.writes[0]:F)){xe.default.error?.("Bad subscription event",F);continue}if(F.source=p,F.type==="end_txn"){if(ie?.resolve(),F.localTime&&L!==F.localTime){if(F.remoteNodeIds?.length>0){let ce=[Symbol.for("seq"),F.remoteNodeIds[0]],ee=f.get(ce),Q=ee?.nodes;Q||(Q=[]);for(let fe of F.remoteNodeIds.slice(1)){let Ae=Q.find(De=>De.id===fe);Q=Q.filter(De=>De.id!==fe||De===Ae),Ae||(Ae={id:fe,seqId:0},Q.push(Ae)),Ae.seqId=Math.max(ee?.seqId??1,F.localTime),fe===ie?.nodeId&&(Ae.lastTxnTime=F.timestamp)}let _e=Math.max(ee?.seqId??1,F.localTime);xe.default.trace?.("Received txn",c,new Date(_e),new Date(F.localTime),F.remoteNodeIds),f.put(ce,{seqId:_e,nodes:Q})}L=F.localTime}F.onCommit&&ie?.committed.then(F.onCommit);continue}if(ie)if(F.beginTxn)ie.resolve();else{ie.write_promises.push(B(F,ie));continue}!F.timestamp&&F.version&&(F.timestamp=F.version);let Z=Ot(F,()=>{if(F.type==="transaction"){let ce=[];for(let ee of F.writes)try{ce.push(B(ee,F))}catch(Q){throw Q.message+=" writing "+JSON.stringify(ee)+" of event "+JSON.stringify(F),Q}return Promise.all(ce)}else if(F.type==="define_schema"){let ce=this.attributes.slice(0),ee;for(let Q of F.attributes)ce.find(_e=>_e.name===Q.name)||(ce.push(Q),ee=!0);ee&&(ut({table:s,database:c,attributes:ce,origin:"cluster"}),Fh.signalSchemaChange(new Gh.SchemaEventMsg(process.pid,Gt.CREATE_TABLE,c,s)))}else return F.beginTxn?(ie=F,ie.write_promises=[B(F,F)],new Promise(ce=>{ie.resolve=()=>ce(Promise.all(ie.write_promises))})):B(F,F)});ie&&(ie.committed=Z),I&&Z&&!Z?.waitingForUserChange&&(Z.then(()=>Fh.signalUserChange(new Gh.UserEventMsg(process.pid))),Z.waitingForUserChange=!0),F.onCommit&&(Z?Z.then(F.onCommit):F.onCommit())}catch(qe){xe.default.error?.("error in subscription handler",qe)}}}catch(N){xe.default.error?.(N)}})(),this}static get isCaching(){return v}static get shouldRevalidateEvents(){return this.prototype.get!==Ce.prototype.get}static getResource(p,O,A){let y=super.getResource(p,O,A);if(p!=null){Or(p);try{if(y.getRecord?.())return y;if(typeof p=="object"&&p&&!Array.isArray(p))throw new Error(`Invalid id ${JSON.stringify(p)}`);let b=!A?.async||i.cache?.get?.(p),C=Gr(O),I=C.getReadTxn();if(I?.isDone)throw new Error("You can not read from a transaction that has already been committed/aborted");return Ul(p,O,{transaction:I,ensureLoaded:A?.ensureLoaded},b,L=>{if(L?Ce._updateResource(y,L):y.#e=null,O.onlyIfCached&&O.noCacheStore){if(!y.doesExist())throw new br.ServerError("Entry is not cached",504)}else if(A?.ensureLoaded){let B=xl(p,L,O,y);if(B)return C?.disregardReadTxn(),y.#i=!0,ZI(B,N=>(Ce._updateResource(y,N),y))}return y})}catch(b){throw b.message.includes("Unable to serialize object")&&(b.message+=": "+JSON.stringify(p)),b}}return y}static _updateResource(p,O){p.#r=O,p.#e=O?.value??null,p.#n=O?.version}ensureLoaded(){let p=xl(this.getId(),this.#r,this.getContext());if(p)return this.#i=!0,ZI(p,O=>{this.#r=O,this.#e=O.value,this.#n=O.version})}static getNewId(){let p=H?.type;if(p==="String"||p==="ID")return super.getNewId();if(!vt){let b=i.getEntry(Symbol.for("id_allocation")),C=b?.value,I;if(C&&C.nodeName===server.hostname&&(!Kme(i)||C.pid===process.pid)){let L=C.start,B=C.end;I=L;for(let N of i.getKeys({start:B,end:L,limit:1,reverse:!0}))I=N}else C=y(b?.version??null),I=C.start;vt=new BigInt64Array([BigInt(I)+1n]),vt=new BigInt64Array(i.getUserSharedBuffer("id",vt.buffer)),vt.maxSafeId=C.end}let O=Number(Atomics.add(vt,0,1n)),A=p==="Int"?512:1048576;if(O+A>=vt.maxSafeId){let b=a(C=>{vt.maxSafeId=O+(p==="Int"?1023:4194303);let I=(p==="Int"?Math.pow(2,31):Math.pow(2,49))-1,L=C?void 0:i.useReadTransaction(),B=Number(vt[0]);for(let G of i.getKeys({start:B+1,end:I,limit:1,transaction:L}))I=G;L?.done();let{value:N,version:x}=i.getEntry(Symbol.for("id_allocation"));if(vt.maxSafeId<I){if(N.end>vt.maxSafeId-100)return;xe.default.info?.("New id allocation",O,vt.maxSafeId,x),i.put(Symbol.for("id_allocation"),{start:N.start,end:vt.maxSafeId,nodeName:server.hostname,pid:process.pid},Date.now(),x)}else{xe.default.warn?.(`Id conflict detected, starting new id allocation range, attempting to allocate to ${vt.maxSafeId}, but id of ${I} detected`);let G=y(x);G.alreadyUpdated||Atomics.store(vt,0,BigInt(G.start+1)),vt.maxSafeId=G.end}},"updateEnd");O+A===vt.maxSafeId?setImmediate(b):O+100>=vt.maxSafeId&&(xe.default.warn?.(`Synchronous id allocation required on table ${s}${p=="Int"?", it is highly recommended that you use Long or Float as the type for auto-incremented primary keys":""}`),i.transactionSync(()=>b(!0)))}return O;function y(b){let C=(p==="Int"?Math.pow(2,31):Math.pow(2,49))-1,I=C/4,L,B,N=!1,x,G;do{x=Math.floor(Math.random()*C),G={start:x,end:x+(p==="Int"?1024:4194304),nodeName:server.hostname,pid:process.pid},L=0;for(let z of i.getKeys({start:x,limit:1,reverse:!0}))L=z;B=C;for(let z of i.getKeys({start:x+1,end:C,limit:1}))B=z;I*=.875,I<1e3&&!N&&(N=!0,xe.default.error?.(`Id allocation in table ${s} is very dense, limited safe range of numbers to allocate ids in${p==="Int"?", it is highly recommended that you use Long or Float as the type for auto-incremented primary keys":""}`,x,L,B,I))}while(!(I<B-x&&(I<x-L||L===0)));return i.transactionSync(()=>{let z=i.getEntry(Symbol.for("id_allocation"));return(z?.version??null)==b?(xe.default.info?.("Allocated new id range",G),i.put(Symbol.for("id_allocation"),G,Date.now()),G):(xe.default.debug?.("Looks like ids were already allocated"),{alreadyUpdated:!0,...z.value})})}}static setTTLExpiration(p){if(typeof p=="number")m=p*1e3,S||(S=0);else if(p&&typeof p=="object")m=p.expiration*1e3,S=(p.eviction||0)*1e3,Qt=p.scanInterval*1e3;else throw new Error("Invalid expiration value type");if(m<0)throw new Error("Expiration can not be negative");Qt=Qt||(m+S)/4,Vi()}static getResidencyRecord(p){return f.get([Symbol.for("residency_by_id"),p])}static setResidency(p){Ce.getResidency=p&&((O,A)=>{try{return p(O,A)}catch(y){throw y.message+=` in residency function for table ${s}`,y}})}static setResidencyById(p){Ce.getResidencyById=p&&(O=>{try{return p(O)}catch(A){throw A.message+=` in residency function for table ${s}`,A}})}static getResidency(p,O){if(Ce.getResidencyById)return Ce.getResidencyById(p[t]);let A=Hd;if(O.replicateTo!=null){if(Array.isArray(O.replicateTo))return O.replicateTo.includes(server.hostname)?O.replicateTo:[server.hostname,...O.replicateTo];O.replicateTo>=0&&(A=O.replicateTo)}if(A>=0&&server.nodes){let y=[server.hostname];if(O.previousResidency)y.push(...O.previousResidency.slice(0,A));else{let b=server.nodes.map(L=>L.name),C=Math.floor(b.length*Math.random());y.push(...b.slice(C,C+A));let I=C+A-b.length;I>0&&y.push(...b.slice(0,I))}return y}}static enableAuditing(p=!0){g=p,p&&$d(),Ce.audit=p}static coerceId(p){return p===""?null:iT(p,H)}static async dropTable(){delete Ve[c][s];for(let p of i.getRange({versions:!0,snapshot:!1,lazy:!0}))p.metadataFlags&fn&&p.value&&ra(p.value);if(c===o){for(let p of E)f.remove(Ce.tableName+"/"+p.name),r[p.name]?.drop();f.remove(Ce.tableName+"/"),i.drop(),await f.committed}else console.log("legacy dropTable"),await i.close(),await sT.default.remove(data_path),await sT.default.remove(data_path===standard_path?data_path+MDB_LOCK_FILE_SUFFIX:path.join(path.dirname(data_path),MDB_LEGACY_LOCK_FILE_NAME));Fh.signalSchemaChange(new Gh.SchemaEventMsg(process.pid,Gt.DROP_TABLE,c,s))}get(p){if(typeof p=="string")return this.getProperty(p);if(this.isCollection)return this.search(p);if(this.getId()===null){if(p?.conditions||p?.size>0)return this.search(p);let O={records:"./",name:s,database:c,auditSize:l?.getStats().entryCount,attributes:E};return this.getContext()?.includeExpensiveRecordCountEstimates?Ce.getRecordCount().then(A=>(O.recordCount=A.recordCount,O.estimatedRecordRange=A.estimatedRange,O)):O}if(p?.property)return this.getProperty(p.property);if(this.doesExist()||p?.ensureLoaded===!1||this.getContext()?.returnNonexistent)return this}allowRead(p,O){let A=Fr(p);if(A?.read){if(A.isSuperUser)return!0;let y=A.attribute_permissions,b=O?.select;if(y?.length>0||Ml&&b){if(O||(O={}),b){let C=y?.length>0&&XI(y,"read");O.select=b.map(I=>{let L=I.name||I;if(!C||C[L]){let B=Cn[L]?.definition?.tableClass;if(B){if(I.name||(I={name:I}),!B.prototype.allowRead.call(null,p,I))return!1;if(!I.select)return I.name}return I}}).filter(Boolean)}else O.select=y.filter(C=>C.read&&!Cn[C.attribute_name]).map(C=>C.attribute_name);return O}else return!0}}allowUpdate(p,O){let A=Fr(p);if(A?.update){let y=A.attribute_permissions;if(y?.length>0){let b=XI(y,"update");for(let C in O)if(!b[C])return!1;for(let C of y){let I=C.attribute_name;!C.update&&!(I in O)&&(O[I]=this.getProperty(I))}}return Hl(this.getContext())}}allowCreate(p,O){if(this.isCollection){let A=Fr(p);if(A?.insert){let y=A.attribute_permissions;if(y?.length>0){let b=XI(y,"insert");for(let C in O)if(!b[C])return!1;return Hl(this.getContext())}else return Hl(this.getContext())}}else return this.allowUpdate(p,{})}allowDelete(p){return Fr(p)?.delete&&Hl(this.getContext())}update(p,O){if(!Gr(this.getContext()))throw new Error("Can not update a table resource outside of a transaction");if(p===!1)return this;let y;return typeof p=="object"&&p&&(O?(Object.isFrozen(p)&&(p={...p}),this.#e={},this.#t=p):(y=this.#t,y&&(p=Object.assign(y,p)),this.#t=p)),this._writeUpdate(this.#t,O),this}addTo(p,O){if(typeof O=="number"||typeof O=="bigint")this.#s===zY?this.set(p,(+this.getProperty(p)||0)+O):(this.#s||this.update(),this.set(p,new Wp(O)));else throw new Error("Can not add a non-numeric value")}subtractFrom(p,O){if(typeof O=="number")return this.addTo(p,-O);throw new Error("Can not subtract a non-numeric value")}getMetadata(){return this.#r}getRecord(){return this.#e}getChanges(){return this.#t}_setChanges(p){this.#t=p}setRecord(p){this.#e=p}invalidate(){this._writeInvalidate()}_writeInvalidate(p,O){let A=this.getContext(),y=this.getId();Or(y),Gr(this.getContext()).addWrite({key:y,store:i,invalidated:!0,entry:this.#r,before:Te.invalidate?.bind(this,A,y),beforeIntermediate:ye.invalidate?.bind(this,A,y),commit:a((C,I)=>{if(!($i(C,I,O?.nodeId)<=0)){p??=null;for(let L in r)p||(p={}),p[L]===void 0&&(p[L]=this.getProperty(L));xe.default.trace?.(`Invalidating entry id: ${y}, timestamp: ${new Date(C).toISOString()}`),T(y,p,this.#r,C,un,g,{user:A?.user,residencyId:O?.residencyId,nodeId:O?.nodeId},"invalidate")}},"commit")})}_writeRelocate(p){let O=this.getContext(),A=this.getId();Or(A),Gr(this.getContext()).addWrite({key:A,store:i,invalidated:!0,entry:this.#r,before:Te.relocate?.bind(this,O,A),beforeIntermediate:ye.relocate?.bind(this,O,A),commit:a((b,C)=>{if($i(b,C,p?.nodeId)<=0)return;let I=Ce.getResidencyRecord(p.residencyId),L=0,B=null,N=C?.value;if(I&&!I.includes(server.hostname)){for(let x in r)B||(B={}),B[x]=N(x);L=un}else B=N;xe.default.trace?.(`Relocating entry id: ${A}, timestamp: ${new Date(b).toISOString()}`),T(A,B,this.#r,b,L,g,{user:O.user,residencyId:p.residencyId,nodeId:p.nodeId,expiresAt:p.expiresAt},"relocate",!1,null)},"commit")})}static _recordRelocate(p,O){let A={previousResidency:this.getResidencyRecord(p.residencyId),isRelocation:!0},y=Ki(this.getResidency(O.value,A)),b;if(y){if(!y.includes(server.hostname))return!1;b=Za(y)}let I=T(p.key,O.value,p,p.version,0,!0,{residencyId:b,expiresAt:O.expiresAt},"relocate",!1,null);return!0}static evict(p,O,A){let y=this.Source,b;if(!((v||g)&&(!O||(b=i.getEntry(p),!b||!O)||b.version!==A))){if(v){if(i.hasLock(p,b.version))return;let C;for(let I in r)C||(C={}),C[I]=O[I];if(C)return T(p,C,b,A,Jo,null,null,null,!0)}if(i.ifVersion(p,A,()=>{sn(p,O,null)}),g)return T(p,null,b,A,Jo,null,null,null,!0);hc(i,b??i.getEntry(p),A)}}lock(){throw new Error("Not yet implemented")}static operation(p,O){return p.table||=s,p.schema||=c,rW.operation(p,O)}put(p){this.update(p,!0)}patch(p){this.update(p,!1)}_writeUpdate(p,O,A){let y=this.getContext(),b=Gr(y),C=this.getId();Or(C);let I=this.#r;this.#s=O?zY:Fme;let L={key:C,store:i,entry:I,nodeName:y?.nodeName,validate:a(B=>{p||(p=this.#t),O||p&&Kp(this.#t===p?this:p)?y?.source||(b.checkOverloaded(),this.validate(p,!O),te&&(p[te.name]=te.type==="Date"?new Date(B):te.type==="String"?new Date(B).toISOString():B),O&&(t&&p[t]!==C&&(p[t]=C),W&&(I?.value?p[W.name]=I?.value[W.name]:p[W.name]=W.type==="Date"?new Date(B):W.type==="String"?new Date(B).toISOString():B),p=Mc(p))):b.removeWrite(L)},"validate"),before:O?Te.put?()=>Te.put(y,C,p):null:Te.patch?()=>Te.patch(y,C,p):Te.put?()=>Te.put(y,C,Mc(this)):null,beforeIntermediate:O?ye.put?()=>ye.put(y,C,p):null:ye.patch?()=>ye.patch(y,C,p):ye.put?()=>ye.put(y,C,Mc(this)):null,commit:a((B,N,x)=>{if(x){if(y&&N?.version>(y.lastModified||0)&&(y.lastModified=N.version),this.#r=N,N?.value&&N.value.getRecord)throw new Error("Can not assign a record to a record, check for circular references");O||(this.#e=N?.value??null)}this.#t=void 0,this.#n=B;let G=N?.value,z=p;this.#s=0;let ie=!1,F=$i(B,N,A?.nodeId),qe;if(F<=0)if(g){let _e=N.localTime,fe=N.version;xe.default.trace?.("Applying CRDT update to record with id: ",C,"applying later update:",fe);let Ae=[];for(;_e>B||fe>=B&&_e>0;){let De=l.get(_e);if(!De)break;let we=Nt(De);if(fe=we.version,fe>=B){if(fe===B){if(F=$i(B,{version:fe,localTime:_e},A?.nodeId),F===0)return;if(F>0)continue}if(we.type==="patch")Ae.push(we),qe=p;else if(we.type==="put"||we.type==="delete")return}_e=we.previousLocalTime}Ae.sort((De,we)=>De.version-we.version);for(let De of Ae){let we=De.getValue(i);if(z=$p(z,we,O),xe.default.debug?.("Rebuilding update with future patch:",z),!z)return}}else{if(O)return;z=$p(z,G,O),xe.default.debug?.("Rebuilding update without audit:",z)}let Z;if(O?Z=z:(this.#e=G,Z=Mc(this,z)),this.#e=Z,Z&&Z.getRecord)throw new Error("Can not assign a record to a record, check for circular references");let ce;if(A?.residencyId!=null)ce=A.residencyId;else{I?.residencyId&&(y.previousResidency=Ce.getResidencyRecord(I.residencyId));let _e=Ki(Ce.getResidency(Z,y));if(_e&&!_e.includes(server.hostname))if(qe??=Z,ie=!0,Ce.getResidencyById)Z=void 0;else{Z=null;for(let fe in r)Z||(Z={}),Z[fe]=qe[fe]}ce=Za(_e)}O||(qe=p);let ee=y?.expiresAt??(m?m+Date.now():-1);xe.default.trace?.(`Saving record with id: ${C}, timestamp: ${new Date(B).toISOString()}${ee?", expires at: "+new Date(ee).toISOString():""}${N?", replaces entry from: "+new Date(N.version).toISOString():", new entry"}`,(()=>{try{return JSON.stringify(Z).slice(0,100)}catch{return""}})()),sn(C,G,Z);let Q=O?"put":"patch";T(C,Z,N,B,ie?un:0,g,{omitLocalRecord:ie,user:y?.user,residencyId:ce,expiresAt:ee,nodeId:A?.nodeId,originatingOperation:y?.originatingOperation},Q,!1,qe),y.expiresAt&&Vi()},"commit")};b.addWrite(L)}async delete(p){if(typeof p=="string")return this.deleteProperty(p);if(this.isCollection){for await(let O of this.search(p))(await Ce.getResource(O[t],this.getContext(),{ensureLoaded:!1}))._writeDelete(p);return}return this.#e?this._writeDelete(p):!1}_writeDelete(p){let O=Gr(this.getContext()),A=this.getId();Or(A);let y=this.getContext();return O.addWrite({key:A,store:i,entry:this.#r,nodeName:y?.nodeName,before:Te.delete?.bind(this,y,A),beforeIntermediate:ye.delete?.bind(this,y,A),commit:a((b,C,I)=>{let L=C?.value;I&&(y&&C?.version>(y.lastModified||0)&&(y.lastModified=C.version),Ce._updateResource(this,C)),!($i(b,C,p?.nodeId)<=0)&&(sn(this.getId(),L),xe.default.trace?.(`Deleting record with id: ${A}, txn timestamp: ${new Date(b).toISOString()}`),g||R?(T(A,null,this.#r,b,0,g,{user:y?.user,nodeId:p?.nodeId},"delete"),g||Vi()):hc(i,C))},"commit")}),!0}search(p){let O=this.getContext(),A=Gr(O);if(!p)throw new Error("No query provided");let y=p.conditions;y?y.length===void 0&&(y=y[Symbol.iterator]?Array.from(y):[y]):y=Array.isArray(p)?p:p[Symbol.iterator]?Array.from(p):[],this.getId()&&(y=[{attribute:null,comparator:Array.isArray(this.getId())?"prefix":"starts_with",value:this.getId()}].concat(y));let b,C={};function I(Q,_e){let fe;switch(_e){case"and":case void 0:if(Q.length<1)throw new Error('An "and" operator requires at least one condition');fe=!0;break;case"or":if(Q.length<2)throw new Error('An "or" operator requires at least two conditions');break;default:throw new Error("Invalid operator "+_e)}for(let Ae of Q){if(Ae.conditions){Ae.conditions=I(Ae.conditions,Ae.operator);continue}let De=Ae[0]??Ae.attribute,we=De==null?H:fi(E,De);if(we)(we.type||RA[Ae.comparator])&&(Ae[1]===void 0?Ae.value=B(Ae.value,we):Ae[1]=B(Ae[1],we));else if(De!=null)throw(0,br.handleHDBError)(new Error,`${De} is not a defined attribute`,404);if(Ae.chainedConditions)if(Ae.chainedConditions.length===1&&(!Ae.operator||Ae.operator=="and")){let dr=Ae.chainedConditions[0],Nr,Ps;if(dr.comparator==="gt"||dr.comparator==="greater_than"||dr.comparator==="ge"||dr.comparator==="greater_than_equal"?(Nr=Ae,Ps=dr):(Nr=dr,Ps=Ae),Nr.comparator!=="lt"&&Nr.comparator!=="less_than"&&Nr.comparator!=="le"&&Nr.comparator!=="less_than_equal")throw new Error("Invalid chained condition, only less than and greater than conditions can be chained together");let Re=Ps.comparator==="ge"||Ps.comparator==="greater_than_equal",yt=Nr.comparator==="le"||Nr.comparator==="less_than_equal";Ae.comparator=(Re?"ge":"gt")+(yt?"le":"lt"),Ae.value=[Ps.value,Nr.value]}else throw new Error("Multiple chained conditions are not currently supported")}return Q}a(I,"prepareConditions");function L(Q,_e){if(p.enforceExecutionOrder)return Q;for(let fe of Q)fe.conditions&&(fe.conditions=L(fe.conditions,fe.operator));return Q.length>1&&_e!=="or"?(0,eW.sortBy)(Q,Gm(Ce)):Q}a(L,"orderConditions");function B(Q,_e){return Array.isArray(Q)?Q.map(fe=>iT(fe,_e)):iT(Q,_e)}a(B,"coerceTypedValues");let N=p.operator;(y.length>0||N)&&(y=I(y,N));let x=typeof p.sort=="object"&&p.sort,G;if(x&&N!=="or"){let Q=x.attribute;if(Q==null)throw new br.ClientError("Sort requires an attribute");if(b=y.find(_e=>Kl(_e.attribute)===Kl(Q)),!b){let _e=fi(E,Q);if(!_e)throw(0,br.handleHDBError)(new Error,`${Array.isArray(Q)?Q.join("."):Q} is not a defined attribute`,404);if(_e.indexed)b={attribute:Q,comparator:"sort"},y.push(b);else if(y.length===0&&!p.allowFullScan)throw(0,br.handleHDBError)(new Error,`${Array.isArray(Q)?Q.join("."):Q} is not indexed and not combined with any other conditions`,404)}b&&(b.descending=!!x.descending)}y=L(y,N),x&&(b&&y[0]===b?x.next&&(G={dbOrderedAttribute:x.attribute,attribute:x.next.attribute,descending:x.next.descending,next:x.next.next}):(b&&y.splice(y.indexOf(b),1),G=x));let z=p.select;if(y.length===0&&(y=[{attribute:t,comparator:"greater_than",value:!0}]),p.explain)return{conditions:y,operator:N,postOrdering:G,selectApplied:!!z};let ie=A.useReadTxn(),F=yA(y,N,Ce,ie,p,O,(Q,_e)=>Gd(Q,z,O,ie,_e),C),qe=p.ensureLoaded!==!1;G||(F=ee(F));let Z=Ce.transformEntryForSelect(z,O,ie,C,qe,!0),ce=Ce.transformToOrderedSelect(F,z,G,ie,O,Z);function ee(Q){return p.offset||p.limit!==void 0?Q.slice(p.offset,p.limit!==void 0?(p.offset||0)+p.limit:void 0):Q}return a(ee,"applyOffset"),G&&(ce=ee(ce)),ce.onDone=()=>{ce.onDone=null,A.doneReadTxn()},ce.selectApplied=!0,ce.getColumns=()=>{if(z){let Q=[];for(let _e of z)_e==="*"?Q.push(...E.map(fe=>fe.name)):Q.push(_e.name||_e);return Q}return E.filter(Q=>!Q.computed&&!Q.relationship).map(Q=>Q.name)},ce}static transformToOrderedSelect(p,O,A,y,b,C){let I=new mm;if(A){p=Gd(p,O,y,b,null);let L;I.iterate=function(){let N,x=p[Symbol.asyncIterator]?p[Symbol.asyncIterator]():p[Symbol.iterator](),G,z=A.dbOrderedAttribute,ie,F,qe=!0;function Z(ee){let Q=ee.next&&Z(ee.next),_e=ee.descending;return(fe,Ae)=>{let De=Bl(fe,ee.attribute,y),we=Bl(Ae,ee.attribute,y),dr=_e?(0,Al.compareKeys)(we,De):(0,Al.compareKeys)(De,we);return dr===0?Q?.(fe,Ae)||0:dr}}a(Z,"createComparator");let ce=Z(A);return{async next(){let ee;if(N)if(ee=N.next(),ee.done){if(G)return I.onDone&&I.onDone(),ee}else return{value:await C.call(this,ee.value)};L=[],ie&&L.push(ie);do if(ee=await x.next(),ee.done){if(G=!0,L.length)break;return I.onDone&&I.onDone(),ee}else{let Q=ee.value;if(Q?.then&&(Q=await Q),z){let _e=Bl(Q,z,y);if(qe)qe=!1,F=_e;else if(_e!==F){F=_e,ie=Q;break}}L.push(Q)}while(!0);return A.isGrouped,L.sort(ce),N=L[Symbol.iterator](),ee=N.next(),ee.done?(I.onDone&&I.onDone(),ee):{value:await C.call(this,ee.value)}},return(){I.onDone&&I.onDone(),x.return()},throw(){I.onDone&&I.onDone(),x.throw()}}};let B=a(N=>{if(typeof O=="object"&&Array.isArray(N.attribute))for(let x=0;x<O.length;x++){let G=O[x],z;if(G.name===N.attribute[0]){for(z=G.sort||(G.sort={});z.next;)z=z.next;z.attribute=N.attribute.slice(1),z.descending=N.descending}else G===N.attribute[0]&&(O[x]=z={name:G,sort:{attribute:N.attribute.slice(1),descending:N.descending}})}N.next&&B(N.next)},"applySortingOnSelect");B(A)}else I.iterate=(p[Symbol.asyncIterator]||p[Symbol.iterator]).bind(p),I=I.map(function(L){try{let B=C.call(this,L);return typeof B?.catch=="function"?B.catch(N=>{throw N.partialObject={[t]:L.key},N}):B}catch(B){throw B.partialObject={[t]:L.key},B}});return I}static transformEntryForSelect(p,O,A,y,b,C){if(p&&(p===t||p?.length===1&&p[0]===t&&Array.isArray(p))){let N=a(x=>(O?.transaction?.stale&&(O.transaction.stale=!1),x?.key??x),"transform");return p===t?N:p.asArray?x=>[N(x)]:x=>({[t]:N(x)})}let I;b&&v&&!(typeof p=="string"?[p]:p)?.every(N=>{let x;return typeof N=="object"?x=N.name:x=N,r[x]||x===t})&&(I=!0);let L,B=a(function(N){let x;if(O?.transaction?.stale&&(O.transaction.stale=!1),N!=null){if(x=N.value||N.deref?.()?.value,!x&&(N.key===void 0||N.deref)||N.metadataFlags&un){if(N.metadataFlags&un&&O.replicateFrom===!1&&C&&N.residencyId)return Ga.SKIP;if(N=Ul(N.key??N,O,{transaction:A,lazy:p?.length<4,ensureLoaded:b},this?.isSync,G=>G),N?.then)return N.then(B.bind(this));x=N?.value}if(I&&N?.metadataFlags&(un|Jo)||N?.expiresAt!=null&&N?.expiresAt<Date.now()){if(O.onlyIfCached&&O.noCacheStore)return{[t]:N.key,message:"This entry has expired"};let G=xl(N.key??N,N,O);if(G?.then)return G.then(B)}}if(x==null)return C?Ga.SKIP:x;if(p&&!(p[0]==="*"&&p.length===1)){let G,z=a((F,qe)=>{let Z;typeof F=="object"?Z=F.name:Z=F;let ce=Cn?.[Z],ee;if(ce){let Q=y?.[Z];if(Q)if(Q.hasMappings){let fe=ce.from?x[ce.from]:Kl(N.key);ee=Q.get(fe),ee||(ee=[])}else ee=Q.fromRecord?.(x);else ee=ce(x,O,N);let _e=a(fe=>{if(fe&&typeof fe=="object"){let Ae=ce.definition?.tableClass||Ce;L||(L={});let De=L[Z]||(L[Z]=Ae.transformEntryForSelect(Z===F?null:F.select||(Array.isArray(F)?F:null),O,A,Q,b));if(Array.isArray(fe)){let we=[],dr=Ae.transformToOrderedSelect(fe,F.select,typeof F.sort=="object"&&F.sort,O,A,De)[this.isSync?Symbol.iterator:Symbol.asyncIterator](),Nr=a(Re=>{for(;!Re.done;){if(Re?.then)return Re.then(Nr);we.push(Re.value),Re=dr.next()}qe(we,Z)},"nextValue"),Ps=Nr(dr.next());Ps&&(G||(G=[]),G.push(Ps));return}else if(fe=De.call(this,fe),fe?.then){G||(G=[]),G.push(fe.then(we=>qe(we,Z)));return}}qe(fe,Z)},"handleResolvedValue");ee?.then?(G||(G=[]),G.push(ee.then(_e))):_e(ee);return}else ee=x[Z],ee&&typeof ee=="object"&&Z!==F&&(ee=Ce.transformEntryForSelect(F.select||F,O,A,null)({value:ee}));qe(ee,Z)},"selectAttribute"),ie;if(typeof p=="string")z(p,F=>{ie=F});else if(Array.isArray(p))if(p.asArray)ie=[],p.forEach((F,qe)=>{F==="*"?p[qe]=x:z(F,Z=>ie[qe]=Z)});else{ie={};let F=p.forceNulls;for(let qe of p)if(qe==="*")for(let Z in x)ie[Z]=x[Z];else z(qe,(Z,ce)=>{Z===void 0&&F&&(Z=null),ie[ce]=Z})}else throw new br.ClientError("Invalid select"+p);return G?Promise.all(G).then(()=>ie):ie}return x},"transform");return B}async subscribe(p){if(!l)throw new Error("Can not subscribe to a table without an audit log");g||ut({table:s,database:c,schemaDefined:u,attributes:E,audit:!0}),p||(p={});let O=!p.rawEvents,A=[],y=this,b=JI(Ce,this.getId()??null,function(I,L,B,N){try{let x=L.getValue?.(i,O),G=L.type;if(!x&&G==="patch"&&O){let ie=i.getEntry(I);ie?.version===L.version?x=ie.value:x=L.getValue?.(i,!0,B),G="put"}let z={id:I,localTime:B,value:x,version:L.version,type:G,beginTxn:N};A?A.push(z):this.send(z)}catch(x){xe.default.error?.(x)}},p.startTime||0,p),C=(async()=>{this.isCollection&&(b.includeDescendants=!0,p.onlyChildren&&(b.onlyChildren=!0)),p.supportsTransactions&&(b.supportsTransactions=!0);let I=this.getId(),L=p.previousCount;L>1e3&&(L=1e3);let B=p.startTime;if(this.isCollection){if(B){if(L)throw new br.ClientError("startTime and previousCount can not be combined for a table level subscription");for(let{key:N,value:x}of l.getRange({start:B,exclusiveStart:!0,snapshot:!1})){let G=Nt(x);if(G.tableId!==n)continue;let z=G.recordId;if(I==null||XY(I,z)){let ie=G.getValue(i,O,N);if(b.send({id:z,localTime:N,value:ie,version:G.version,type:G.type}),b.queue?.length>jY&&await b.waitForDrain()===!1)return}b.startTime=N}}else if(L){let N=[];for(let{key:x,value:G}of l.getRange({start:"z",end:!1,reverse:!0}))try{let z=Nt(G);if(z.tableId!==n)continue;let ie=z.recordId;if(I==null||XY(I,ie)){let F=z.getValue(i,O,x);if(N.push({id:ie,localTime:x,value:F,version:z.version,type:z.type}),--L<=0)break}}catch(z){xe.default.error("Error getting history entry",x,z)}for(let x=N.length;x>0;)b.send(N[--x]);N[0]&&(b.startTime=N[0].localTime)}else if(!p.omitCurrent){for(let{key:N,value:x,version:G,localTime:z}of i.getRange({start:I??!1,end:I==null?void 0:[I,Al.MAXIMUM_KEY],versions:!0,snapshot:!1}))if(x&&(b.send({id:N,localTime:z,value:x,version:G,type:"put"}),b.queue?.length>jY&&await b.waitForDrain()===!1))return}}else{L&&!B&&(B=0);let N=this.#r?.localTime;if(N===ZA&&(i.cache?.delete(I),this.#r=i.getEntry(I),xe.default.trace?.("re-retrieved record",N,this.#r?.localTime),N=this.#r?.localTime),xe.default.trace?.("Subscription from",B,"from",I,N),B<N){let x=[],G=N;do{let z=l.get(G);if(z){p.omitCurrent=!0;let ie=Nt(z),F=ie.getValue(i,O,G);O&&(ie.type="put"),x.push({id:I,value:F,localTime:G,...ie}),G=ie.previousLocalTime}else break;L&&L--}while(G>B&&L!==0);for(let z=x.length;z>0;)b.send(x[--z]);b.startTime=N}!p.omitCurrent&&this.doesExist()&&b.send({id:I,localTime:N,value:this.#e,version:this.#n,type:"put"})}for(let N of A)b.send(N);A=null})();return p.listener&&b.on("data",p.listener),b}static subscribeOnThisThread(p,O){return p===0||O?.crossThreads===!1}doesExist(){return!!(this.#e||this.#s)}publish(p,O){this._writePublish(p,O)}_writePublish(p,O){let A=Gr(this.getContext()),y=this.getId()||null;y!=null&&Or(y);let b=this.getContext();A.addWrite({key:y,store:i,entry:this.#r,nodeName:b?.nodeName,validate:a(()=>{b?.source||(A.checkOverloaded(),this.validate(p))},"validate"),before:Te.publish?.bind(this,b,y,p),beforeIntermediate:ye.publish?.bind(this,b,y,p),commit:a((C,I,L)=>{I===void 0&&R&&!g&&Vi(),xe.default.trace?.(`Publishing message to id: ${y}, timestamp: ${new Date(C).toISOString()}`),T(y,I?.value??null,I,I?.version||C,0,!0,{user:b?.user,residencyId:O?.residencyId,expiresAt:b?.expiresAt,nodeId:O?.nodeId},"message",!1,p)},"commit")})}validate(p,O){let A,y=a((b,C,I)=>{if(C.type&&b!=null)if(O&&b.__op__&&(b=b.value),C.properties){typeof b!="object"&&(A||(A=[])).push(`Value ${Ns(b)} in property ${I} must be an object${C.type?" ("+C.type+")":""}`);let L=C.properties;for(let B=0,N=L.length;B<N;B++){let x=L[B],G=y(b[x.name],x,I+"."+x.name);G&&(b[x.name]=G)}if(C.sealed&&b!=null&&typeof b=="object")for(let B in b)L.find(N=>N.name===B)||(A||(A=[])).push(`Property ${B} is not allowed within object in property ${I}`)}else switch(C.type){case"Int":(typeof b!="number"||b>>0!==b)&&(A||(A=[])).push(`Value ${Ns(b)} in property ${I} must be an integer (from -2147483648 to 2147483647)`);break;case"Long":(typeof b!="number"||!(Math.floor(b)===b&&Math.abs(b)<=9007199254740992))&&(A||(A=[])).push(`Value ${Ns(b)} in property ${I} must be an integer (from -9007199254740992 to 9007199254740992)`);break;case"Float":typeof b!="number"&&(A||(A=[])).push(`Value ${Ns(b)} in property ${I} must be a number`);break;case"ID":typeof b=="string"||b?.length>0&&b.every?.(L=>typeof L=="string")||(A||(A=[])).push(`Value ${Ns(b)} in property ${I} must be a string, or an array of strings`);break;case"String":typeof b!="string"&&(A||(A=[])).push(`Value ${Ns(b)} in property ${I} must be a string`);break;case"Boolean":typeof b!="boolean"&&(A||(A=[])).push(`Value ${Ns(b)} in property ${I} must be a boolean`);break;case"Date":if(!(b instanceof Date)){if(typeof b=="string"||typeof b=="number")return new Date(b);(A||(A=[])).push(`Value ${Ns(b)} in property ${I} must be a Date`)}break;case"BigInt":if(typeof b!="bigint"){if(typeof b=="string"||typeof b=="number")return BigInt(b);(A||(A=[])).push(`Value ${Ns(b)} in property ${I} must be a bigint`)}break;case"Bytes":if(!(b instanceof Uint8Array)){if(typeof b=="string")return Buffer.from(b);(A||(A=[])).push(`Value ${Ns(b)} in property ${I} must be a Buffer or Uint8Array`)}break;case"Blob":if(!(b instanceof mi)){if(typeof b=="string"&&(b=Buffer.from(b)),b instanceof Buffer)return createBlob(b,{type:"text/plain"});(A||(A=[])).push(`Value ${Ns(b)} in property ${I} must be a Blob`)}break;case"array":if(Array.isArray(b)){if(C.elements)for(let L=0,B=b.length;L<B;L++){let N=b[L],x=y(N,C.elements,I+"[*]");x&&(b[L]=x)}}else(A||(A=[])).push(`Value ${Ns(b)} in property ${I} must be an Array`);break}C.nullable===!1&&b==null&&(A||(A=[])).push(`Property ${I} is required (and not does not allow null values)`)},"validateValue");for(let b=0,C=E.length;b<C;b++){let I=E[b];if(!(I.relationship||I.computed)&&(!O||I.name in p)){let L=y(p[I.name],I,I.name);L&&(p[I.name]=L)}}if(d)for(let b in p)E.find(C=>C.name===b)||(A||(A=[])).push(`Property ${b} is not allowed`);if(A)throw new br.ClientError(A.join(". "))}getUpdatedTime(){return this.#n}wasLoadedFromSource(){return v?!!this.#i:void 0}static async addAttributes(p){let O=E.slice(0);for(let A of p){if(!A.name)throw new br.ClientError("Attribute name is required");if(A.name.match(/[`/]/))throw new br.ClientError("Attribute names cannot include backticks or forward slashes");(0,tW.validateAttribute)(A.name),O.push(A)}return ut({table:s,database:c,schemaDefined:u,attributes:O}),Ce.indexingOperation}static async removeAttributes(p){let O=E.filter(A=>!p.includes(A.name));return ut({table:s,database:c,schemaDefined:u,attributes:O}),Ce.indexingOperation}static getSize(){let p=i.getStats();return(p.treeBranchPageCount+p.treeLeafPageCount+p.overflowPages)*p.pageSize}static getAuditSize(){let p=l?.getStats();return p&&(p.treeBranchPageCount+p.treeLeafPageCount+p.overflowPages)*p.pageSize}static getStorageStats(){let p=i.env.path,O=sT.default.statfsSync?.(p)??{};return{available:O.bavail*O.bsize,free:O.bfree*O.bsize,size:O.blocks*O.bsize}}static async getRecordCount(p){let O=i.getStats().entryCount,A=1e3/2,y=performance.now(),b=Math.floor(O/2),C=p?.exactCount,I=0,L=0,B;for(let{value:N}of i.getRange({start:!0,lazy:!0,snapshot:!1}))if(N!=null&&I++,L++,await Fa(),!C&&L<b&&performance.now()-y>A){B=L;break}if(B){let N=I;I=0;for(let{value:ee}of i.getRange({start:"\uFFFF",reverse:!0,lazy:!0,limit:B,snapshot:!1}))ee!=null&&I++,await Fa();let x=B*2,G=(I+N)/x,z=Math.pow((I-N+1)/B/2,2)+G*(1-G)/x,ie=Math.max(Math.sqrt(z)*O,1),F=Math.round(G*O),qe=Math.max(F-1.96*ie,I+N),Z=Math.min(F+1.96*ie,O),ce=Math.pow(10,Math.round(Math.log10(ie)));return ce>F&&(ce=ce/10),I=Math.round(F/ce)*ce,{recordCount:I,estimatedRange:[Math.round(qe),Math.round(Z)]}}return{recordCount:I}}static updatedAttributes(){Cn=this.propertyResolvers={$id:a((p,O,A)=>({value:A.key}),"$id"),$updatedtime:a((p,O,A)=>A.version,"$updatedtime"),$record:a((p,O,A)=>A?{value:p}:p,"$record")};for(let p of this.attributes){p.isPrimaryKey&&(H=p),p.resolve=null;let O=p.relationship,A=p.computed;if(O)if(p.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)"),Ml=!0,O.to)p.elements?.definition?(Cn[p.name]=p.resolve=(y,b,C)=>{let I=y[O.from?O.from:t],L=p.elements.definition.tableClass;return C?Vl({attribute:O.to,value:I},Gr(b).getReadTxn(),!1,L,!1).asArray:L.search([{attribute:O.to,value:I}],b).asArray},p.set=()=>{throw new Error("Setting a one-to-many relationship property is not supported")},p.resolve.definition=p.elements.definition,O.from&&(p.resolve.from=O.from)):console.error(`The one-to-many/many-to-many relationship property "${p.name}" in table "${s}" must have an array type referencing a table as the elements`);else if(O.from){let y=p.definition||p.elements?.definition;y?(Cn[p.name]=p.resolve=(b,C,I)=>{let L=b[O.from];if(L!==void 0){if(p.elements){let B,N=L?.map(x=>{let G=I?y.tableClass.primaryStore.getEntry(x,{transaction:Gr(C).getReadTxn()}):y.tableClass.get(x,C);return G?.then&&(B=!0),G});return O.filterMissing?B?Promise.all(N).then(x=>x.filter(ZY)):N.filter(ZY):B?Promise.all(N):N}return I?y.tableClass.primaryStore.getEntry(L,{transaction:Gr(C).getReadTxn()}):y.tableClass.get(L,C)}},p.set=(b,C)=>{if(Array.isArray(C)){let I=C.map(L=>L.getId?.()||L[y.tableClass.primaryKey]);b[O.from]=I}else{let I=C.getId?.()||C[y.tableClass.primaryKey];b[O.from]=I}},p.resolve.definition=p.definition||p.elements?.definition,p.resolve.from=O.from):console.error(`The relationship property "${p.name}" in table "${s}" must be a type that references a table`)}else console.error(`The relationship directive on "${p.name}" in table "${s}" must use either "from" or "to" arguments`);else A&&(typeof A.from=="function"&&this.setComputedAttribute(p.name,A.from),Cn[p.name]=p.resolve=(y,b,C)=>{let I=typeof A.from=="string"?y[A.from]:y,L=this.userResolvers[p.name];if(L)return L(I,b,C);xe.default.warn(`Computed attribute "${p.name}" does not have a function assigned to it. Please use setComputedAttribute('${p.name}', resolver) to assign a resolver function.`),this.userResolvers[p.name]=()=>{}})}zp(this,this)}static setComputedAttribute(p,O){let A=fi(E,p);if(!A){console.error(`The attribute "${p}" does not exist in the table "${s}"`);return}if(!A.computed){console.error(`The attribute "${p}" is not defined as computed in the table "${s}"`);return}this.userResolvers[p]=O}static async deleteHistory(p=0,O=!1){let A;for(let{key:y,value:b}of l.getRange({start:0,end:p}))await Fa(),Nt(b).tableId===n&&(A=rT(l,y,b));if(O)for(let y of i.getRange({start:0,versions:!0})){let{key:b,value:C,localTime:I}=y;await Fa(),C===null&&I<p&&(A=hc(i,y))}await A}static async*getHistory(p=0,O=1/0){for(let{key:A,value:y}of l.getRange({start:p||1,end:O})){await Fa();let b=Nt(y);b.tableId===n&&(yield{id:b.recordId,localTime:A,version:b.version,type:b.type,value:b.getValue(i,!0,A),user:b.user,operation:b.originatingOperation})}}static async getHistoryOfRecord(p){let O=[];if(p==null)throw new Error("An id is required");let A=i.getEntry(p);if(!A)return O;let y=A.localTime;if(!y)throw new Error("The entry does not have a local audit time");let b=0;do{await Fa();let C=l.get(y);if(C){let I=Nt(C);O.push({id:I.recordId,localTime:y,version:I.version,type:I.type,value:I.getValue(i,!0,y),user:I.user}),y=I.previousLocalTime}else break}while(b<1e3&&y);return O.reverse()}static cleanup(){Y?.remove()}}Ce.updatedAttributes();let Fd=Ce.prototype;return m&&Ce.setTTLExpiration(m/1e3),se&&Em(),Ce;function sn(K,p,O){let A;for(let y in r){let b=r[y],C=b.isIndexing,I=Cn[y],L=O&&(I?I(O):O[y]),B=p&&(I?I(p):p[y]);if(L===B&&!C)continue;A=!0;let N=b.indexNulls,x=(0,kh.getIndexedValues)(L,N),G=(0,kh.getIndexedValues)(B,N);if(G?.length>0){let z=new Set(G);if(x=x?x.filter(ie=>{if(z.has(ie))z.delete(ie);else return!0}):[],G=Array.from(z),(G.length>0||x.length>0)&&WY){let ie=G.concat(x).map(F=>({key:F,value:K}));b.prefetch(ie,JY)}for(let ie=0,F=G.length;ie<F;ie++)b.remove(G[ie],K)}else x?.length>0&&WY&&b.prefetch(x.map(z=>({key:z,value:K})),JY);if(x)for(let z=0,ie=x.length;z<ie;z++)b.put(x[z],K)}return A}a(sn,"updateIndices");function Or(K){switch(typeof K){case"number":return!0;case"string":if(K.length<659)return!0;if(K.length>QY)throw new Error("Primary key size is too large: "+K.length);break;case"object":if(K===null)throw new Error("Invalid primary key of null");break;case"bigint":if(K<2n**64n&&K>-(2n**64n))return!0;break;default:throw new Error("Invalid primary key type: "+typeof K)}if((0,Al.writeKey)(K,Gme,0)>QY)throw new Error("Primary key size is too large: "+K.length);return!0}a(Or,"checkValidId");function Ul(K,p,O,A,y){if(Ce.getResidencyById&&O.ensureLoaded&&p?.replicateFrom!==!1){let C=Ki(Ce.getResidencyById(K));if(C&&!C.includes(server.hostname)&&w)return w({key:K,residency:C}).then(y)}let b=a(()=>{if(p?.transaction?.stale&&(p.transaction.stale=!1),O.transaction?.isDone)return y(null,K);let C=i.getEntry(K,O);return C?.residencyId&&C.metadataFlags&un&&w&&O.ensureLoaded&&p?.replicateFrom!==!1?w(C).then(I=>y(I,K),I=>(xe.default.error?.("Error loading remote record",K,C,O,I),y(null,K))):(C&&p&&(C?.version>(p.lastModified||0)&&(p.lastModified=C.version),C?.localTime&&!p.lastRefreshed&&(p.lastRefreshed=C.localTime)),y(C,K))},"whenPrefetched");return A?b():oe>0?(oe--,b()):new Promise((C,I)=>{oe===0?(oe--,i.prefetch([K],()=>{L(),B()})):(ne.push(K),ue.push(B),ne.length>pm&&(oe--,L()));function L(){if(ne.length>0){let N=ue;i.prefetch(ne,()=>{oe===-1?L():oe++;for(let x of N)x()}),ne=[],ue=[],pe>2&&pe--}else oe=pe,pe<kd&&pe++}a(L,"prefetch");function B(){try{C(b())}catch(N){I(N)}}a(B,"load")})}a(Ul,"loadLocalRecord");function Fr(K){if(!K?.role)return;let p=K.role.permission;if(p.super_user)return qme;let O=p[c],A,y=O?.tables;if(y)return y[s];if(c==="data"&&(A=p[s])&&!A.tables)return A}a(Fr,"getTablePermissions");function xl(K,p,O,A){if(v){let y=!1;if(O.noCache?y=!0:(p?(!p.value||p.metadataFlags&(un|Jo)||p.expiresAt!=null&&p.expiresAt<Date.now())&&(y=!0):y=!0,Kn(!y,"cache-hit",s)),y){let b=qd(K,p,O).then(C=>(C?.value&&C?.value.getRecord?.()&&xe.default.error?.("Can not assign a record that is already a resource"),O&&(C?.version>(O.lastModified||0)&&(O.lastModified=C.version),O.lastRefreshed=Date.now()),C));if(O?.onlyIfCached||p?.value&&A?.allowStaleWhileRevalidate?.(p,K)){if(b.catch(C=>xe.default.warn?.(C)),O?.onlyIfCached&&!A.doesExist())throw new br.ServerError("Entry is not cached",504);return}else return b}}else if(p?.value&&p.expiresAt!=null&&p.expiresAt<Date.now())return Ce.evict(p.key,p.value,p.version),p.value=null,{then(y){return y(p)}}}a(xl,"ensureLoadedFromSource");function Gr(K){let p=K?.transaction;if(p){if(!p.lmdbDb)return p.lmdbDb=i,p;do{if(p.lmdbDb?.path===i.path)return p;let O=p.next;if(!O)return p=p.next=new nc,p.lmdbDb=i,p;p=O}while(!0)}else return new Hm}a(Gr,"txnForContext");function Bl(K,p,O){if(!K)return;let A=K.value||i.getEntry(K.key)?.value;if(typeof p=="object"){let b=Cn,C=A;for(let I=0,L=p.length;I<L;I++){let B=p[I],N=b?.[B];C=N&&C?N(C,O,!0)?.value:C?.[B],b=N?.definition?.tableClass?.propertyResolvers}return C}let y=Cn[p];return y?y(A,O):A[p]}a(Bl,"getAttributeValue");function Gd(K,p,O,A,y){let b=y?.length,C={transaction:A,lazy:b>0||typeof p=="string"||p?.length<4,alwaysPrefetch:!0},I;function L(B,N){let x=B?.value;if(!x)return Ga.SKIP;for(let G=0;G<b;G++)if(!I?.includes(G)&&!y[G](x,B))return Ga.SKIP;return N!==void 0&&(B.key=N),B}if(a(L,"processEntry"),b>0||!K.hasEntries){let B=K.map(N=>{if(I=null,typeof N=="object"&&N?.key!==void 0)return b>0?L(N):N;if(N==null)return Ga.SKIP;for(let x=0;x<b;x++){let z=y[x].idFilter;if(z){if(!z(N))return Ga.SKIP;I||(I=[]),I.push(x)}}return Ul(N,O,C,!1,L)});return Array.isArray(K)&&(B=B.filter(N=>N!==Ga.SKIP)),B.hasEntries=!0,B}return K}a(Gd,"transformToEntries");function $i(K,p,O=server.replication?.getThisNodeId(l)){if(K<=p?.version){if(p?.version===K&&O!==void 0){let A=server.replication?.exportIdMapping(l),y=p.localTime,b=y&&l.get(y);if(b){let C,I,L=Nt(b);for(let B in A)A[B]===O&&(C=B),A[B]===L.nodeId&&(I=B);if(C>I)return 1;if(C===I)return 0}}return-1}return 1}a($i,"precedesExistingVersion");async function qd(K,p,O){let A=p?.metadataFlags,y=p?.version,b,C;if(!i.attemptLock(K,y,()=>{clearTimeout(C);let N=i.getEntry(K);!N||!N.value||N.metadataFlags&(un|Jo)?b(qd(K,i.getEntry(K),O)):b(N)}))return new Promise(N=>{b=N,C=setTimeout(()=>{i.unlock(K,y)},kme)});let I=p?.value,L={requestContext:O,replacingRecord:I,replacingEntry:p,replacingVersion:y,noCacheStore:!1,source:null,resourceCache:O?.resourceCache},B=O?.responseHeaders;return new Promise((N,x)=>{let G;ZI(Ot(L,async z=>{let ie=performance.now(),F,qe,Z;try{for(let _e of Ce.sources)if(_e.get&&(!_e.get.reliesOnPrototype||_e.prototype.get)){if(_e.available?.(p)===!1)continue;if(L.source=_e,F=await _e.get(K,L),F)break}Z=A&un;let ee=L.lastModified||Z&&y;qe=Z||ee>y||!I,ee||(ee=(0,kh.getNextMonotonicTime)());let Q=performance.now()-ie;if(er(Q,"cache-resolution",s,null,"success"),B&&aE(B,"Server-Timing",`cache-resolve;dur=${Q.toFixed(2)}`,!0),z.timestamp=ee,m&&L.expiresAt==null&&(L.expiresAt=Date.now()+m),F){if(typeof F!="object")throw new Error("Only objects can be cached and stored in tables");if(F.status>0&&F.headers)if(F.status>=300)if(F.status===304)F=I,ee=y;else throw new br.ServerError(F.body||"Error from source",F.status);else F=F.body;typeof F.toJSON=="function"&&(F=F.toJSON()),t&&F[t]!==K&&(F[t]=K)}G=!0,N({key:K,version:ee,value:F})}catch(ee){ee.message+=` while resolving record ${K} for ${s}`,I&&((ee.code==="ECONNRESET"||ee.code==="ECONNREFUSED"||ee.code==="EAI_AGAIN")&&!O?.mustRevalidate||O?.staleIfError&&(ee.statusCode===500||ee.statusCode===502||ee.statusCode===503||ee.statusCode===504))?(N({key:K,version:y,value:I}),xe.default.trace?.(ee.message,"(returned stale record)")):x(ee);let Q=performance.now()-ie;er(Q,"cache-resolution",s,null,"fail"),B&&aE(B,"Server-Timing",`cache-resolve;dur=${Q.toFixed(2)}`,!0),L.transaction.abort();return}if(O?.noCacheStore||L.noCacheStore){L.transaction.abort();return}Gr(L).addWrite({key:K,store:i,entry:p,nodeName:"source",commit:a((ee,Q)=>{if(Q?.version!==y)return;let _e=sn(K,I,F);if(F){ye.put?.(L,K,F),Q&&(O.previousResidency=Ce.getResidencyRecord(Q.residencyId));let fe,Ae=!1,De,we=Ki(Ce.getResidency(F,O));if(we){if(!we.includes(server.hostname))if(fe=F,Ae=!0,Ce.getResidencyById)F=void 0;else{F=null;for(let dr in r)F||(F={}),F[dr]=fe[dr]}De=Za(we)}xe.default.trace?.(`Writing resolved record from source with id: ${K}, timestamp: ${new Date(ee).toISOString()}`),T(K,F,Q,ee,Ae?un:0,g&&(qe||Ae)||null,{user:L?.user,expiresAt:L.expiresAt,residencyId:De},"put",!!Z,fe)}else Q&&(ye.delete?.(L,K),xe.default.trace?.(`Deleting resolved record from source with id: ${K}, timestamp: ${new Date(ee).toISOString()}`),g||R?T(K,null,Q,ee,0,g&&qe||null,{user:L?.user},"delete",!!Z):hc(i,Q,y))},"commit")})}),()=>{i.unlock(K,y)},z=>{i.unlock(K,y),G&&xe.default.error?.("Error committing cache update",z)})})}a(qd,"getFromSource");function Hl(K){if(!K||K.user?.role?.permission?.super_user)return!0;if(K.replicateTo)throw new br.ClientError("Can not specify replication parameters without super user permissions",403);if(K.replicatedConfirmation)throw new br.ClientError("Can not specify replication confirmation without super user permissions",403);return!0}a(Hl,"checkContextPermissions");function Vi(K){let p=!1;if(K&&(K-lt>1&&(p=!0),lt=K),!(Qt===Tr&&!p)&&(Tr=Qt,(0,Sl.getWorkerIndex)()===(0,Sl.getWorkerCount)()-1))return ss&&clearTimeout(ss),Qt?new Promise(O=>{let A=new Date;A.setMonth(0),A.setDate(1),A.setHours(0),A.setMinutes(0),A.setSeconds(0);let y=Qt/(1+lt),b=p?Date.now():Math.ceil((Date.now()-A.getTime())/y)*y+A.getTime(),C=a(I=>{xe.default.trace?.(`Scheduled next cleanup scan at ${new Date(I)}`),ss=setTimeout(()=>q=q.then(async()=>{if(C(Math.max(I+Qt,Date.now())),i.rootStore.status!=="open"){clearTimeout(ss);return}let L=50,B=new Array(L),N=0,x=Math.pow(lt,8)*(Tl.get(U.STORAGE_RECLAMATION_EVICTIONFACTOR)??1e5),G=S/Math.pow(Math.max(lt,1),4);xe.default.info?.(`Starting cleanup scan for ${s}, evict threshold ${x}, adjusted eviction ${G}ms`);function z(ie,F,qe,Z){let ce=ie+G-Date.now();if(ce<0)return!0;if(lt){let ee=i.lastSize;return qe&fn&&bd(Z,Q=>{Q.size&&(ee+=Q.size)}),xe.default.trace?.(`shouldEvict adjusted ${ce} ${ee}, ${ce*(ie-F)/ee} < ${x}`),ce*(ie-F)/ee<x}return!1}a(z,"shouldEvict");try{let ie=0;for(let F of i.getRange({start:!1,snapshot:!1,versions:!0,lazy:!0})){let{key:qe,value:Z,version:ce,expiresAt:ee,metadataFlags:Q}=F,_e;Z===null&&!g&&ce+Hme<Date.now()?_e=hc(i,F,ce):ee!=null&&z(ee,ce,Q,Z)&&(_e=Ce.evict(qe,Z,ce),ie++),_e&&(await B[N],B[N]=_e.catch(fe=>{xe.default.error?.("Cleanup error",fe)}),++N>=L&&(N=0)),await Fa()}xe.default.info?.(`Finished cleanup scan for ${s}, evicted ${ie} entries`)}catch(ie){xe.default.warn?.(`Error in cleanup scan for ${s}:`,ie)}O(void 0),lt=0}),Math.min(I-Date.now(),2147483647)).unref()},"startNextTimer");C(b)}):void 0}a(Vi,"scheduleCleanup");function $d(){Y=l?.addDeleteRemovalCallback(n,i,(K,p)=>{i.remove(K,p)})}a($d,"addDeleteRemoval");function Em(){(0,Sl.getWorkerIndex)()===0&&setInterval(async()=>{if(!vl){vl=!0;try{let K=se.name,p=r[K];if(!p)throw new Error(`expiresAt attribute ${se} must be indexed`);for(let O of p.getRange({start:!0,values:!1,end:Date.now(),snapshot:!1})){for(let A of p.getValues(O)){let y=i.getEntry(A);y?.value?y.value[K]<Date.now()&&Ce.evict(A,y.value,y.version):i.ifVersion(A,y?.version,()=>p.remove(O,A))}await Fa()}}catch(K){xe.default.error?.("Error in evicting old records",K)}finally{vl=!1}}},Bme).unref()}a(Em,"runRecordExpirationEviction");function Ki(K){if(K!=null){if(Array.isArray(K))return K;if(typeof K=="number"){if(K>=65536)throw new Error(`Shard id ${K} must be below 65536`);let p=server.shards?.get?.(K);if(p)return xe.default.trace?.(`Shard ${K} mapped to ${p.map(O=>O.name).join(", ")}`),p.map(O=>O.name);throw new Error(`Shard ${K} is not defined`)}throw new Error(`Shard or residency list ${K} is not a valid type, must be a shard number or residency list of node hostnames`)}}a(Ki,"residencyFromFunction");function Za(K){if(K){let p=K.join(","),O=f.get([Symbol.for("residency_by_set"),p]);return O||(f.put([Symbol.for("residency_by_set"),p],O=Math.floor(Math.random()*2147418112)+65535),f.put([Symbol.for("residency_by_id"),O],K),O)}}a(Za,"getResidencyId")}function XI(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 JY(){}function $me(e){rW=e}function iT(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 nT(parseInt(e.slice(1),36));if(e==="null")return null;if(!/^-?[0-9]+$/.test(e)&&!(e instanceof Date))throw new SyntaxError;return nT(+e);case"Float":return e==="null"?null:nT(+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;Vme.test(e)||(e+="Z");let n=new Date(e);return nT(n.getTime()),n}return new Date(+e);case void 0:case"Any":return(0,oT.autoCast)(e);default:return e}}catch(n){throw n.message=`Invalid value for attribute ${t.name}: "${e}", expecting ${r}`,n.statusCode=400,n}}function nT(e){if(isNaN(e))throw new SyntaxError;return e}function XY(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 ZI(e,t,r){return e?.then?e.then(t,r):t(e)}function ZY(e){return e!=null}function Ns(e){try{return JSON.stringify(e)}catch{return e}}function Kme(e){let t=process.pid;return e.env.readerList().slice(1).some(r=>+r.match(/\d+/)?.[0]!=t)}var Ga,kh,eW,tW,Tl,br,Fh,Gh,xe,Al,Sl,oT,sT,xme,rW,Bme,Hme,WY,kme,zY,Fme,un,Jo,Gme,QY,jY,qme,oMe,Vme,Fa,df=be(()=>{k();Ga=require("lmdb"),kh=M(an()),eW=require("lodash"),tW=M(sf());Xo();km();Tl=M(le());bO();br=M(me()),Fh=M(ao()),Gh=M(qs());ve();uf();xe=M(_i());jy();sc();Al=require("ordered-binary"),Sl=M(tt());Zi();oT=M(ae());Xl();Ni();Vp();__();sT=M(require("node:fs"));cs();XS();xme=new Uint8Array(9);xme[8]=192;Bme=6e4,Hme=864e5;Tl.initSync();WY=Tl.get(U.STORAGE_PREFETCHWRITES),kme=1e4,zY=1,Fme=2,un=1,Jo=8,Gme=Buffer.allocUnsafeSlow(8192),QY=1978,jY=100,qme={read:!0,insert:!0,update:!0,delete:!0,isSuperUser:!0},oMe=(0,oT.convertToMS)(Tl.get(U.CLUSTERING_LEAFSERVER_STREAMS_MAXAGE))||864e5;a(aT,"makeTable");a(XI,"attributesAsObject");a(JY,"noop");a($me,"setServerUtilities");Vme=/[+-][0-9]{2}:[0-9]{2}|[a-zA-Z]$/;a(iT,"coerceType");a(nT,"rejectNaN");a(XY,"isDescendantId");Fa=a(()=>new Promise(setImmediate),"rest");a(ZI,"when");a(ZY,"exists");a(Ns,"stringify");a(Kme,"hasOtherProcesses")});var it={};Ue(it,{database:()=>_u,database_envs:()=>Po,databases:()=>Ve,dropDatabase:()=>tb,dropTableMeta:()=>jme,getDatabases:()=>je,getDefaultCompression:()=>Fg,getTables:()=>Yme,onRemovedDB:()=>v_,onUpdatedTable:()=>jc,readMetaDb:()=>qh,resetDatabases:()=>ed,table:()=>ut,tables:()=>Vn});function Yme(){return dT||je(),Vn||{}}function je(){if(dT)return Ve;dT=!0,wd=new Map;let e=(0,Wt.getHdbBasePath)()&&(0,Dt.join)((0,Wt.getHdbBasePath)(),tc),t=(0,Wt.get)(U.DATABASES)||{};if(process.env.SCHEMAS_DATA_PATH&&(t.data={path:process.env.SCHEMAS_DATA_PATH}),e=process.env.STORAGE_PATH||(0,Wt.get)(U.STORAGE_PATH)||e&&((0,Xn.existsSync)(e)?e:(0,Dt.join)((0,Wt.getHdbBasePath)(),ym)),!e)return;if((0,Xn.existsSync)(e))for(let n of(0,Xn.readdirSync)(e,{withFileTypes:!0})){let s=(0,Dt.basename)(n.name,".mdb");n.isFile()&&(0,Dt.extname)(n.name).toLowerCase()===".mdb"&&!t[s]?.path&&qh((0,Dt.join)(e,n.name),null,s)}if((0,Xn.existsSync)((0,Nd.getBaseSchemaPath)())){for(let n of(0,Xn.readdirSync)((0,Nd.getBaseSchemaPath)(),{withFileTypes:!0}))if(!n.isFile()){let s=(0,Dt.join)((0,Nd.getBaseSchemaPath)(),n.name),i=(0,Dt.join)((0,Nd.getTransactionAuditStoreBasePath)(),n.name);for(let o of(0,Xn.readdirSync)(s,{withFileTypes:!0}))if(o.isFile()&&(0,Dt.extname)(o.name).toLowerCase()===".mdb"){let c=(0,Dt.join)(i,o.name);qh((0,Dt.join)(s,o.name),(0,Dt.basename)(o.name,".mdb"),n.name,c,!0)}}}if(t)for(let n in t){let s=t[n],i=s.path;if((0,Xn.existsSync)(i))for(let c of(0,Xn.readdirSync)(i,{withFileTypes:!0}))c.isFile()&&(0,Dt.extname)(c.name).toLowerCase()===".mdb"&&qh((0,Dt.join)(i,c.name),(0,Dt.basename)(c.name,".mdb"),n);let o=s.tables;if(o)for(let c in o){let l=o[c],u=(0,Dt.join)(l.path,(0,Dt.basename)(c+".mdb"));(0,Xn.existsSync)(u)&&qh(u,c,n,null,!0)}}for(let n in Ve){let s=wd.get(n);if(s){let i=Ve[n];n.includes("delete")&&Lt.trace(`defined tables ${Array.from(s.keys())}`);for(let o in i)s.has(o)||(Lt.trace(`delete table class ${o}`),delete i[o])}else if(delete Ve[n],n==="data"){for(let i in Vn)delete Vn[i];delete Vn[fT]}}let r=["hdb_temp","hdb_certificate","hdb_analytics","hdb_raw_analytics","hdb_session_will","hdb_job","hdb_license","hdb_info"];if(Ve.system)for(let n of r)Ve.system[n]&&(Ve.system[n].replicate=!1);return wd=null,Ve}function ed(){dT=!1;for(let[,e]of Po)e.needsDeletion=!0;je();for(let[e,t]of Po)t.needsDeletion&&!e.endsWith("system.mdb")&&(t.close(),Po.delete(e),delete Ve[t.databaseName],Vh.forEach(r=>r(t.databaseName)));return Ve}function qh(e,t,r=rC,n,s){let i=new eC.default(e,!1);try{let o=Po.get(e);o?o.needsDeletion=!1:(o=(0,Id.open)(i),Po.set(e,o));let c=new Rl.default(!1),l=o.dbisDb||(o.dbisDb=o.openDB(cT.INTERNAL_DBIS_NAME,c)),u=o.auditStore;u||(n?(0,Xn.existsSync)(n)&&(i.path=n,u=(0,Id.open)(i),u.isLegacy=!0):u=tT(o));let f=oW(r),d=f[fT],_=new Map;for(let{key:h,value:m}of l.getRange({start:!1})){let[S,g]=h.toString().split("/");g===""?g=m.name:g||(g=S,S=t,m.name||(m.name=g,m.indexed=!m.is_hash_attribute)),d?.add(S);let R=_.get(S);R||_.set(S,R={attributes:[]}),(g==null||m.is_hash_attribute)&&(R.primary=m),g!=null&&R.attributes.push(m),Object.defineProperty(m,"key",{value:h,configurable:!0})}for(let[h,m]of _){let{attributes:S,primary:g}=m;if(!g){for(let oe of S)if(oe.is_hash_attribute||oe.isPrimaryKey){g=oe;break}if(!g){Lt.warn(`Unable to find a primary key attribute on table ${h}, with attributes: ${JSON.stringify(S)}`);continue}}let R=f[h],E={},T=[],w,v,H=typeof g.audit=="boolean"?g.audit:(0,Wt.get)(U.LOGGING_AUDITLOG),q=g.trackDeletes,W=g.expiration,te=g.eviction,se=g.sealed,Y=g.splitSegments,ne=g.replicate;if(R)E=R.indices,T=R.attributes,R.schemaVersion++;else{w=g.tableId,w?w>=(l.get(Od)||0)&&(l.putSync(Od,w+1),Lt.info(`Updating next table id (it was out of sync) to ${w+1} for ${h}`)):(g.tableId=w=l.get(Od),w||(w=1),Lt.debug("Table {table_name} missing an id, assigning {table_id}"),l.putSync(Od,w+1),l.putSync(g.key,g));let oe=new Rl.default(!g.is_hash_attribute,g.is_hash_attribute);if(oe.compression=g.compression,oe.compression){let pe=(0,Wt.get)(U.STORAGE_COMPRESSION_THRESHOLD)||iW;oe.compression.threshold=pe}v=sp(o.openDB(g.key,oe),o),o.databaseName=r,v.tableId=w}let ue;for(let oe of S){oe.attribute=oe.name;try{if(!oe.is_hash_attribute&&(oe.indexed||oe.attribute&&!oe.name)){if(!E[oe.name]){let Te=new Rl.default(!oe.is_hash_attribute,oe.is_hash_attribute);E[oe.name]=o.openDB(oe.key,Te),E[oe.name].indexNulls=oe.indexNulls}let pe=T.find(Te=>Te.name===oe.name);pe?T.splice(T.indexOf(pe),1,oe):T.push(oe),ue=!0}}catch(pe){Lt.error("Error trying to update attribute",oe,T,E,pe)}}for(let oe of T)if(!S.find(Te=>Te.name===oe.name)){if(oe.is_hash_attribute){Lt.error("Unable to remove existing primary key attribute",oe);continue}oe.indexed&&(T.splice(T.indexOf(oe),1),ue=!0)}if(R)ue&&(R.schemaVersion++,R.updatedAttributes());else{R=aW(f,h,aT({primaryStore:v,auditStore:u,audit:H,sealed:se,splitSegments:Y,replicate:ne,expirationMS:W&&W*1e3,evictionMS:te&&te*1e3,trackDeletes:q,tableName:h,tableId:w,primaryKey:g.name,databasePath:s?r+"/"+h:r,databaseName:r,indices:E,attributes:S,schemaDefined:g.schemaDefined,dbisDB:l})),R.schemaVersion=1;for(let oe of $h)oe(R)}}return o}catch(o){throw o.message+=` opening database ${e}`,o}}function oW(e){let t=Ve[e];if(t||(e==="data"?t=Ve[e]=Vn:e==="system"?Object.defineProperty(Ve,"system",{value:t=Object.create(null),configurable:!0}):t=Ve[e]=Object.create(null)),wd&&!wd.has(e)){let r=new Set;t[fT]=r,wd.set(e,r)}return t}function aW(e,t,r){return e[t]=r,r}function _u({database:e,table:t}){e||(e=rC),je();let r=oW(e),n=(0,Dt.join)((0,Wt.getHdbBasePath)(),tc),s=(0,Wt.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,Wt.get)(U.STORAGE_PATH)||((0,Xn.existsSync)(n)?n:(0,Dt.join)((0,Wt.getHdbBasePath)(),ym));let o=(0,Dt.join)(n,(i?t:e)+".mdb"),c=Po.get(o);if(!c||c.status==="closed"){let l=new eC.default(o,!1);c=(0,Id.open)(l),Po.set(o,c)}return c.auditStore||(c.auditStore=tT(c)),c}async function tb(e){if(!Ve[e])throw new Error("Schema does not exist");let t=Ve[e],r;for(let n in t)r=t[n].primaryStore.rootStore,Po.delete(r.path),r.status==="open"&&(await r.close(),await Kh.remove(r.path));if(r||(r=_u({database:e,table:null}),r.status==="open"&&(await r.close(),await Kh.remove(r.path))),e==="data"){for(let n in Vn)delete Vn[n];delete Vn[fT]}delete Ve[e],Vh.forEach(n=>n(e)),await nC(r)}function ut(e){let{table:t,database:r,expiration:n,eviction:s,scanInterval:i,attributes:o,audit:c,sealed:l,splitSegments:u,replicate:f,trackDeletes:d,schemaDefined:_,origin:h}=e;r||(r=rC);let m=_u({database:r,table:t}),S=Ve[r];Lt.trace(`Defining ${t} in ${r}`);let g=S?.[t];if(m.status==="closed")throw new Error(`Can not use a closed data store for ${t}`);let R,E,T;_==null&&(_=!0);let w=new Rl.default(!1);for(let Y of o)Y.attribute&&!Y.name?(Y.name=Y.attribute,Y.indexed=!0):Y.attribute=Y.name,Y.expiresAt&&(Y.indexed=!0);let v,H;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,...o)}else{let Y=m.auditStore;E=o.find(pe=>pe.isPrimaryKey)||{},R=E.name,E.is_hash_attribute=E.isPrimaryKey=!0,E.schemaDefined=_,E.compression=Fg(),d&&(E.trackDeletes=!0),c=E.audit=typeof c=="boolean"?c:(0,Wt.get)(U.LOGGING_AUDITLOG),n&&(E.expiration=n),s&&(E.eviction=s),u??=!1,E.splitSegments=u,typeof l=="boolean"&&(E.sealed=l),typeof f=="boolean"&&(E.replicate=f),h&&(E.origins?E.origins.includes(h)||E.origins.push(h):E.origins=[h]),Lt.trace(`${t} table loading, opening primary store`);let ne=new Rl.default(!1,!0);ne.compression=E.compression;let ue=t+"/";if(T=m.dbisDb=m.openDB(cT.INTERNAL_DBIS_NAME,w),se(),T.get(ue))return H&&H(),ed(),ut(e);let oe=sp(m.openDB(ue,ne),m);m.databaseName=r,oe.tableId=T.get(Od),Lt.trace(`Assigning new table id ${oe.tableId} for ${t}`),oe.tableId||(oe.tableId=1),T.put(Od,oe.tableId+1),E.tableId=oe.tableId,g=aW(S,t,aT({primaryStore:oe,auditStore:Y,audit:c,sealed:l,splitSegments:u,replicate:f,trackDeletes:d,expirationMS:n&&n*1e3,evictionMS:s&&s*1e3,primaryKey:R,tableName:t,tableId:oe.tableId,databasePath:r,databaseName:r,indices:{},attributes:o,schemaDefined:_,dbisDB:T})),g.schemaVersion=1,v=!0,T.put(ue,E)}let q=g.indices;T=T||(m.dbisDb=m.openDB(cT.INTERNAL_DBIS_NAME,w)),g.dbisDB=T;let W=[];for(let{key:Y,value:ne}of T.getRange({start:!0})){let[ue,oe]=Y.toString().split("/");if(oe===""&&(oe=ne.name),oe){if(ue!==t)continue}else continue;let pe=o.find(ye=>ye.name===oe),Te=!pe?.indexed&&ne.indexed&&!ne.isPrimaryKey;if((!pe||Te)&&(se(),v=!0,pe||T.remove(Y),Te)){let ye=g.indices[ue];ye&&W.push(ye)}}let te=[];try{for(let Y of o||[]){if((Y.relationship||Y.computed)&&(v=!0,Y.relationship))continue;let ne=t+"/"+(Y.name||"");Object.defineProperty(Y,"key",{value:ne,configurable:!0});let ue=T.get(ne);if(Y.isPrimaryKey){if(ue=ue||T.get(ne=t+"/")||{},c!==void 0&&c!==g.audit||l!==void 0&&l!==g.sealed||f!==void 0&&f!==g.replicate||(+n||void 0)!==(+ue.expiration||void 0)||(+s||void 0)!==(+ue.eviction||void 0)||Y.type!==ue.type){let pe={...ue};typeof c=="boolean"&&(c&&g.enableAuditing(c),pe.audit=c),n&&(pe.expiration=+n),s&&(pe.eviction=+s),l!==void 0&&(pe.sealed=l),f!==void 0&&(pe.replicate=f),Y.type&&(pe.type=Y.type),v=!0,se(),T.put(ne,pe)}continue}ue?.attribute&&!ue.name&&(ue.indexed=!0);let oe=!ue||ue.type!==Y.type||ue.indexed!==Y.indexed||ue.nullable!==Y.nullable||ue.version!==Y.version||JSON.stringify(ue.properties)!==JSON.stringify(Y.properties)||JSON.stringify(ue.elements)!==JSON.stringify(Y.elements);if(Y.indexed){let pe=new Rl.default(!0,!1),Te=m.openDB(ne,pe);(oe||ue.indexingPID&&ue.indexingPID!==process.pid||ue.restartNumber<Yh.workerData?.restartNumber)&&(v=!0,se(),ue=T.get(ne),(oe||ue.indexingPID&&ue.indexingPID!==process.pid||ue.restartNumber<Yh.workerData?.restartNumber)&&(v=!0,Y.indexNulls===void 0&&(Y.indexNulls=!0),g.primaryStore.getStats().entryCount>0&&(Y.lastIndexedKey=ue?.lastIndexedKey??void 0,Y.indexingPID=process.pid,Te.isIndexing=!0,Object.defineProperty(Y,"dbi",{value:Te}),te.push(Y))),T.put(ne,Y)),ue?.indexNulls&&Y.indexNulls===void 0&&(Y.indexNulls=!0),Te.indexNulls=Y.indexNulls,q[Y.name]=Te}else oe&&(v=!0,se(),T.put(ne,Y))}}finally{H&&H()}if(v&&(g.schemaVersion++,g.updatedAttributes()),Lt.trace(`${t} table loading, running index`),te.length>0||W.length>0?g.indexingOperation=Qme(g,te,W):v&&lT.signalSchemaChange(new uT.SchemaEventMsg(process.pid,"schema-change",g.databaseName,g.tableName)),g.origin=h,v)for(let Y of $h)Y(g,h!=="cluster");return(n||s||i)&&g.setTTLExpiration({expiration:n,eviction:s,scanInterval:i}),Lt.trace(`${t} table loaded`),g;function se(){H||m.transactionSync(()=>({then(Y){H=Y}}))}a(se,"startTxn")}async function Qme(e,t,r){try{Lt.info(`Indexing ${e.tableName} attributes`,t);let n=e.schemaVersion;await lT.signalSchemaChange(new uT.SchemaEventMsg(process.pid,"schema-change",e.databaseName,e.tableName));let s;for(let u of r)s=u.drop();let i,o={},c=0,l=t.length;if(await new Promise(u=>setImmediate(u)),l>0){let u;for(let d of t)(0,Id.compareKeys)(d.lastIndexedKey,u)<0&&(u=d.lastIndexedKey),d.lastIndexedKey==null&&d.dbi.clearAsync();let f=0;for(let{key:d,value:_,version:h}of e.primaryStore.getRange({start:u,lazy:l<4,versions:!0,snapshot:!1}))if(_){if(f++,s=e.primaryStore.ifVersion(d,h,()=>{for(let m=0;m<l;m++){let S=t[m],g=S.name;try{let R=S.resolve,E=_&&(R?R(_):_[g]),T=(0,nW.getIndexedValues)(E);if(T)for(let w=0,v=T.length;w<v;w++)S.dbi.put(T[w],d)}catch(R){o[g]||(o[g]=!0,Lt.error(`Error indexing attribute ${g}`,R))}}}),s.then(()=>f--,m=>{f--,Lt.error(m)}),Yh.workerData&&Yh.workerData.restartNumber!==sW.restartNumber&&(i=!0),++c%100===0||i){for(let m of t)m.lastIndexedKey=d,e.dbisDB.put(m.key,m);if(i)return}f>Wme?await s:f>zme&&await new Promise(m=>setImmediate(m))}for(let d of t)delete d.lastIndexedKey,delete d.indexingPID,d.dbi.isIndexing=!1,s=e.dbisDB.put(d.key,d)}await s,await lT.signalSchemaChange(new uT.SchemaEventMsg(process.pid,"indexing-finished",e.databaseName,e.tableName)),Lt.info(`Finished indexing ${e.tableName} attributes`,t)}catch(n){Lt.error("Error in indexing",n)}}function jme({table:e,database:t}){let r=_u({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 jc(e){return $h.push(e),{remove(){let t=$h.indexOf(e);t>-1&&$h.splice(t,1)}}}function v_(e){return Vh.push(e),{remove(){let t=Vh.indexOf(e);t>-1&&Vh.splice(t,1)}}}function Fg(){let e=(0,Wt.get)(U.STORAGE_COMPRESSION),t=(0,Wt.get)(U.STORAGE_COMPRESSION_DICTIONARY),r=(0,Wt.get)(U.STORAGE_COMPRESSION_THRESHOLD)||iW,n={startingOffset:32};return t&&(n.dictionary=Kh.readFileSync(t)),r&&(n.threshold=r),e&&n}var Wt,cT,Id,Dt,Xn,Nd,Rl,eC,Kh,tC,nW,lT,uT,Yh,Lt,sW,rC,fT,iW,Vn,Ve,Od,$h,Vh,dT,Po,wd,Wme,zme,ve=be(()=>{Wt=M(le()),cT=M(Ut()),Id=require("lmdb"),Dt=require("path"),Xn=require("fs"),Nd=M(pt());df();Rl=M(yf()),eC=M(bf());k();Kh=M(require("fs-extra")),tC=M(ci()),nW=M(an()),lT=M(ao()),uT=M(qs()),Yh=require("worker_threads"),Lt=M(j()),sW=M(tt());Zi();Xl();cs();rC="data",fT=Symbol("defined-tables"),iW=((0,Wt.get)(U.STORAGE_PAGESIZE)||4096)-60;(0,Wt.initSync)();Vn=Object.create(null),Ve=Object.create(null);(0,tC._assignPackageExport)("databases",Ve);(0,tC._assignPackageExport)("tables",Vn);Od=Symbol.for("next-table-id"),$h=[],Vh=[],Po=new Map;a(Yme,"getTables");a(je,"getDatabases");a(ed,"resetDatabases");a(qh,"readMetaDb");a(oW,"ensureDB");a(aW,"setTable");a(_u,"database");a(tb,"dropDatabase");a(ut,"table");Wme=1e3,zme=10;a(Qme,"runIndexing");a(jme,"dropTableMeta");a(jc,"onUpdatedTable");a(v_,"onRemovedDB");a(Fg,"getDefaultCompression")});var ae=P((EMe,AW)=>{"use strict";var qa=require("path"),fW=require("fs-extra"),On=j(),cW=require("fs-extra"),_T=require("os"),Jme=require("net"),Xme=require("recursive-iterator"),gr=(k(),D($)),{PACKAGE_ROOT:Zme}=mt(),epe=_A(),lW=require("papaparse"),hT=require("moment"),{inspect:tpe}=require("util"),uW=require("is-number"),pMe=require("lodash"),rpe=require("minimist"),npe=require("https"),spe=require("http"),{hdb_errors:mT}=me(),ipe=/^((\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)))$/,_W=require("util").promisify(setTimeout),ope=100,ape=5,cpe="",lpe=4,dW={true:!0,TRUE:!0,FALSE:!1,false:!1,undefined:null,null:null,NULL:null,NaN:NaN};AW.exports={isEmpty:Zn,isEmptyOrZeroLength:xi,arrayHasEmptyValues:fpe,arrayHasEmptyOrZeroLengthValues:_pe,buildFolderPath:hpe,isBoolean:hW,errorizeMessage:upe,stripFileExtension:ppe,autoCast:Epe,autoCastJSON:mW,autoCastJSONDeep:iC,removeDir:gpe,compareVersions:Spe,isCompatibleDataVersion:Tpe,escapeRawValue:Ape,unescapeValue:Rpe,stringifyProps:ype,timeoutPromise:Ope,isClusterOperation:wpe,getClusterUser:Cpe,checkGlobalSchemaTable:Ipe,getHomeDir:EW,getPropsFilePath:bpe,promisifyPapaParse:Ppe,removeBOM:gW,createEventPromise:Dpe,checkProcessRunning:Lpe,checkSchemaTableExist:Mpe,checkSchemaExists:SW,checkTableExists:TW,getStartOfTomorrowInSeconds:vpe,getLimitKey:Upe,isObject:mpe,isNotEmptyAndHasValue:dpe,autoCasterIsNumberCheck:pW,backtickASTSchemaItems:xpe,isPortTaken:Npe,createForkArgs:Bpe,autoCastBoolean:Hpe,async_set_timeout:_W,getTableHashAttribute:kpe,doesSchemaExist:Fpe,doesTableExist:Gpe,stringifyObj:qpe,ms_to_time:$pe,changeExtension:Vpe,getEnvCliRootPath:oC,noBootFile:Kpe,httpRequest:Ype,transformReq:Wpe,convertToMS:zpe,PACKAGE_ROOT:Zme};function upe(e){return e instanceof Error?e:new Error(e)}a(upe,"errorizeMessage");function Zn(e){return e==null}a(Zn,"isEmpty");function dpe(e){return!Zn(e)&&(e||e===0||e===""||hW(e))}a(dpe,"isNotEmptyAndHasValue");function xi(e){return Zn(e)||e.length===0||e.size===0}a(xi,"isEmptyOrZeroLength");function fpe(e){if(Zn(e))return!0;for(let t=0;t<e.length;t++)if(Zn(e[t]))return!0;return!1}a(fpe,"arrayHasEmptyValues");function _pe(e){if(xi(e))return!0;for(let t=0;t<e.length;t++)if(xi(e[t]))return!0;return!1}a(_pe,"arrayHasEmptyOrZeroLengthValues");function hpe(...e){try{return e.join(qa.sep)}catch{console.error(e)}}a(hpe,"buildFolderPath");function hW(e){return Zn(e)?!1:e===!0||e===!1}a(hW,"isBoolean");function mpe(e){return Zn(e)?!1:typeof e=="object"}a(mpe,"isObject");function ppe(e){return xi(e)?cpe:e.slice(0,-lpe)}a(ppe,"stripFileExtension");function Epe(e){return Zn(e)||e===""||typeof e!="string"?e:dW[e]!==void 0?dW[e]:pW(e)===!0?Number(e):ipe.test(e)?new Date(e):e}a(Epe,"autoCast");function mW(e){if(typeof e=="string"&&(e.startsWith("{")&&e.endsWith("}")||e.startsWith("[")&&e.endsWith("]")))try{return JSON.parse(e)}catch{}return e}a(mW,"autoCastJSON");function iC(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=iC(n);s!==n&&(e[t]=s)}else for(let t in e){let r=e[t],n=iC(r);n!==r&&(e[t]=n)}return e}else return mW(e)}a(iC,"autoCastJSONDeep");function pW(e){if(e.startsWith("0.")&&uW(e))return!0;let t=e.toUpperCase().includes("E");return!!((e!=="0"&&e.startsWith("0"))===!1&&t===!1&&uW(e))}a(pW,"autoCasterIsNumberCheck");async function gpe(e){if(xi(e))throw new Error(`Directory path: ${e} does not exist`);try{await cW.emptyDir(e),await cW.remove(e)}catch(t){throw On.error(`Error removing files in ${e} -- ${t}`),t}}a(gpe,"removeDir");function Spe(e,t){if(xi(e)){On.info("Invalid current version sent as parameter.");return}if(xi(t)){On.info("Invalid upgrade version sent as parameter.");return}let r,n=/(\.0+)+$/,s=e.version?e.version:e,i=t.version?t.version:t,o=s.replace(n,"").split("."),c=i.replace(n,"").split("."),l=Math.min(o.length,c.length);for(let u=0;u<l;u++)if(r=parseInt(o[u],10)-parseInt(c[u],10),r)return r;return o.length-c.length}a(Spe,"compareVersions");function Tpe(e,t,r=!1){let n=e.toString().split("."),s=t.toString().split(".");return n[0]===s[0]&&(!r||n[1]===s[1])}a(Tpe,"isCompatibleDataVersion");function Ape(e){if(Zn(e))return e;let t=String(e);return t==="."?gr.UNICODE_PERIOD:t===".."?gr.UNICODE_PERIOD+gr.UNICODE_PERIOD:t.replace(gr.FORWARD_SLASH_REGEX,gr.UNICODE_FORWARD_SLASH)}a(Ape,"escapeRawValue");function Rpe(e){if(Zn(e))return e;let t=String(e);return t===gr.UNICODE_PERIOD?".":t===gr.UNICODE_PERIOD+gr.UNICODE_PERIOD?"..":String(e).replace(gr.ESCAPED_FORWARD_SLASH_REGEX,"/")}a(Rpe,"unescapeValue");function ype(e,t){if(Zn(e))return On.info("Properties object is null"),"";let r="";return e.each(function(n,s){try{if(t&&t[n]){let i=t[n];for(let o of i)r+=";"+o+_T.EOL}!xi(n)&&n[0]===";"?r+=" "+n+s+_T.EOL:xi(n)||(r+=n+"="+s+_T.EOL)}catch{On.error(`Found bad property during upgrade with key ${n} and value: ${s}`)}}),r}a(ype,"stringifyProps");function EW(){let e;try{e=_T.homedir()}catch{e=process.env.HOME}return e}a(EW,"getHomeDir");function bpe(){let e=qa.join(EW(),gr.HDB_HOME_DIR_NAME,gr.BOOT_PROPS_FILE_NAME);return fW.existsSync(e)||(e=qa.join(__dirname,"../","hdb_boot_properties.file")),e}a(bpe,"getPropsFilePath");function Ope(e,t){let r,n;return n=new Promise(function(s){r=setTimeout(function(){s(t)},e)}),{promise:n,cancel:a(function(){clearTimeout(r)},"cancel")}}a(Ope,"timeoutPromise");async function Npe(e){if(!e)throw new Error("Invalid port passed as parameter");return new Promise((t,r)=>{let n=Jme.createServer().once("error",s=>{s.code==="EADDRINUSE"?t(!0):r(s)}).once("listening",()=>n.once("close",()=>t(!1)).close()).listen(e)})}a(Npe,"isPortTaken");function wpe(e){try{return gr.CLUSTER_OPERATIONS[e.toLowerCase()]!==void 0}catch(t){On.error(`Error checking operation against cluster ops ${t}`)}return!1}a(wpe,"isClusterOperation");function Ipe(e,t){let r=(ve(),D(it)).getDatabases();if(!r[e])return mT.HDB_ERROR_MSGS.SCHEMA_NOT_FOUND(e);if(!r[e][t])return mT.HDB_ERROR_MSGS.TABLE_NOT_FOUND(e,t)}a(Ipe,"checkGlobalSchemaTable");function Cpe(e,t){if(Zn(t)){On.warn("No CLUSTERING_USER defined, clustering disabled");return}if(Zn(e)||xi(e)){On.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){On.error(`unable to find cluster_user due to: ${n.message}`);return}if(r===void 0){On.warn(`CLUSTERING_USER: ${t} not found or is not active.`);return}return r}a(Cpe,"getClusterUser");function Ppe(){lW.parsePromise=function(e,t,r){return new Promise(function(n,s){lW.parse(e,{header:!0,transformHeader:gW,chunk:t.bind(null,s),skipEmptyLines:!0,transform:r,dynamicTyping:!1,error:s,complete:n})})}}a(Ppe,"promisifyPapaParse");function gW(e){if(typeof e!="string")throw new TypeError(`Expected a string, got ${typeof e}`);return e.charCodeAt(0)===65279?e.slice(1):e}a(gW,"removeBOM");function Dpe(e,t,r){return new Promise(n=>{t.once(e,s=>{let i=r;On.info(`Got cluster status event response: ${tpe(s)}`);try{i.cancel()}catch{On.error("Error trying to cancel timeout.")}n(s)})})}a(Dpe,"createEventPromise");async function Lpe(e){let t=!0,r=0;do await _W(ope*r++),(await epe.findPs(e)).length>0&&(t=!1);while(t&&r<ape);if(t)throw new Error(`process ${e} was not started`)}a(Lpe,"checkProcessRunning");function Mpe(e,t){let r=SW(e);if(r)return r;let n=TW(e,t);if(n)return n}a(Mpe,"checkSchemaTableExist");function SW(e){let{getDatabases:t}=(ve(),D(it));if(!t()[e])return mT.HDB_ERROR_MSGS.SCHEMA_NOT_FOUND(e)}a(SW,"checkSchemaExists");function TW(e,t){let{getDatabases:r}=(ve(),D(it));if(!r()[e][t])return mT.HDB_ERROR_MSGS.TABLE_NOT_FOUND(e,t)}a(TW,"checkTableExists");function vpe(){let e=hT().utc().add(1,"d").startOf("d").unix(),t=hT().utc().unix();return e-t}a(vpe,"getStartOfTomorrowInSeconds");function Upe(){return hT().utc().format("DD-MM-YYYY")}a(Upe,"getLimitKey");function xpe(e){try{let t=new Xme(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){On.error("Got an error back ticking items."),On.error(t)}}a(xpe,"backtickASTSchemaItems");function Bpe(e){return[e]}a(Bpe,"createForkArgs");function Hpe(e){return e===!0||typeof e=="string"&&e.toLowerCase()==="true"}a(Hpe,"autoCastBoolean");function kpe(e,t){let{getDatabases:r}=(ve(),D(it)),n=r()[e]?.[t];return n?.primaryKey||n?.hash_attribute}a(kpe,"getTableHashAttribute");function Fpe(e){let{getDatabases:t}=(ve(),D(it));return t()[e]!==void 0}a(Fpe,"doesSchemaExist");function Gpe(e,t){let{getDatabases:r}=(ve(),D(it));return r()[e]?.[t]!==void 0}a(Gpe,"doesTableExist");function qpe(e){try{return JSON.stringify(e)}catch{return e}}a(qpe,"stringifyObj");function $pe(e){let t=hT.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}a($pe,"ms_to_time");function Vpe(e,t){let r=qa.basename(e,qa.extname(e));return qa.join(qa.dirname(e),r+t)}a(Vpe,"changeExtension");function oC(){if(process.env[gr.CONFIG_PARAMS.ROOTPATH.toUpperCase()])return process.env[gr.CONFIG_PARAMS.ROOTPATH.toUpperCase()];let e=rpe(process.argv);if(e[gr.CONFIG_PARAMS.ROOTPATH.toUpperCase()])return e[gr.CONFIG_PARAMS.ROOTPATH.toUpperCase()]}a(oC,"getEnvCliRootPath");var sC;function Kpe(){if(sC)return sC;let e=oC();if(oC()&&fW.pathExistsSync(qa.join(e,gr.HDB_CONFIG_FILE)))return sC=!0,!0}a(Kpe,"noBootFile");function Ype(e,t){let r;return e.protocol==="http:"?r=spe:r=npe,new Promise((n,s)=>{let i=r.request(e,o=>{o.setEncoding("utf8"),o.body="",o.on("data",c=>{o.body+=c}),o.on("end",()=>{n(o)})});i.on("error",o=>{s(o)}),i.write(t instanceof Buffer?t:JSON.stringify(t)),i.end()})}a(Ype,"httpRequest");function Wpe(e){if(!e.schema&&!e.database){e.schema=gr.DEFAULT_DATABASE_NAME;return}e.database&&(e.schema=e.database)}a(Wpe,"transformReq");function zpe(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}a(zpe,"convertToMS")});var le=P((NW,wW)=>{"use strict";var aC=require("fs-extra"),yl=require("path"),RW=require("os"),Qpe=require("properties-reader"),zh=j(),Wh=ae(),Me=(k(),D($)),pT=Ct(),jpe="Error initializing environment manager",ET="BOOT_PROPS_FILE_PATH",yW=!1,Jpe={[Me.HDB_SETTINGS_NAMES.INSTALL_USER]:!0,[Me.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY]:!0,[Me.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]:!0,BOOT_PROPS_FILE_PATH:!0},Do={};Object.assign(NW,wW.exports={BOOT_PROPS_FILE_PATH:ET,getHdbBasePath:Xpe,setHdbBasePath:Zpe,get:bW,initSync:tEe,setProperty:ze,initTestEnvironment:nEe,setCloneVar:rEe});function Xpe(){return Do[Me.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]}a(Xpe,"getHdbBasePath");function Zpe(e){Do[Me.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]=e}a(Zpe,"setHdbBasePath");function bW(e){let t=pT.getConfigValue(e);return t===void 0?Do[e]:t}a(bW,"get");function ze(e,t){Jpe[e]&&(Do[e]=t),pT.updateConfigObject(e,t)}a(ze,"setProperty");function eEe(){let e;try{e=Wh.getPropsFilePath(),aC.accessSync(e,aC.constants.F_OK|aC.constants.R_OK),yW=!0;let t=Qpe(e);return Do[Me.HDB_SETTINGS_NAMES.INSTALL_USER]=t.get(Me.HDB_SETTINGS_NAMES.INSTALL_USER),Do[Me.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY]=t.get(Me.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY),Do[ET]=e,!0}catch{return zh.trace(`Environment manager found no properties file at ${e}`),!1}}a(eEe,"doesPropFileExist");function tEe(e=!1){try{((yW||eEe()||Wh.noBootFile())&&!OW||e)&&(pT.initConfig(e),Do[Me.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]=pT.getConfigValue(Me.HDB_SETTINGS_NAMES.HDB_ROOT_KEY))}catch(t){zh.error(jpe),zh.error(t),console.error(t),process.exit(1)}}a(tEe,"initSync");var OW=!1;function rEe(e){OW=e}a(rEe,"setCloneVar");function nEe(e={}){try{let{keep_alive_timeout:t,headers_timeout:r,server_timeout:n,https_enabled:s,cors_enabled:i,cors_accesslist:o,local_studio_on:c}=e,l=yl.join(__dirname,"../../","unitTests");Do[ET]=yl.join(l,"hdb_boot_properties.file"),ze(Me.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY,yl.join(l,"settings.test")),ze(Me.HDB_SETTINGS_NAMES.INSTALL_USER,RW.userInfo()?RW.userInfo().username:void 0),ze(Me.HDB_SETTINGS_NAMES.LOG_LEVEL_KEY,"debug"),ze(Me.HDB_SETTINGS_NAMES.LOG_PATH_KEY,yl.join(l,"envDir","log")),ze(Me.HDB_SETTINGS_NAMES.LOG_DAILY_ROTATE_KEY,!1),ze(Me.HDB_SETTINGS_NAMES.CLUSTERING_ENABLED_KEY,!0),ze(Me.HDB_SETTINGS_NAMES.CLUSTERING_NODE_NAME_KEY,"1231412de213"),ze(Me.HDB_SETTINGS_NAMES.HDB_ROOT_KEY,yl.join(l,"envDir")),ze(Me.CONFIG_PARAMS.STORAGE_PATH,yl.join(l,"envDir")),s&&(ze(Me.CONFIG_PARAMS.HTTP_SECUREPORT,bW(Me.CONFIG_PARAMS.HTTP_PORT)),ze(Me.CONFIG_PARAMS.HTTP_PORT,null)),ze(Me.CONFIG_PARAMS.CUSTOMFUNCTIONS_NETWORK_HTTPS,!!s),ze(Me.CONFIG_PARAMS.HTTP_PORT,9926),ze(Me.HDB_SETTINGS_NAMES.SERVER_PORT_KEY,9925),ze(Me.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_PORT,9925),ze(Me.HDB_SETTINGS_NAMES.CORS_ENABLED_KEY,Wh.isEmpty(i)?!1:i),ze(Me.CONFIG_PARAMS.HTTP_CORS,Wh.isEmpty(i)?!1:i),ze(Me.HDB_SETTINGS_NAMES.MAX_CUSTOM_FUNCTION_PROCESSES,2),ze(Me.HDB_SETTINGS_NAMES.MAX_HDB_PROCESSES,4),ze(Me.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_PORT_KEY,9926),ze(Me.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_ENABLED_KEY,!0),ze(Me.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_DIRECTORY_KEY,yl.resolve(__dirname,"../../unitTests/server/fastifyRoutes/custom_functions")),ze(Me.HDB_SETTINGS_NAMES.LOCAL_STUDIO_ON,Wh.isEmpty(c)?!1:c),o&&(ze("CORS_ACCESSLIST",o),ze(Me.CONFIG_PARAMS.HTTP_CORSACCESSLIST,o)),n&&(ze(Me.HDB_SETTINGS_NAMES.SERVER_TIMEOUT_KEY,n),ze(Me.CONFIG_PARAMS.HTTP_TIMEOUT,n)),t&&(ze(Me.HDB_SETTINGS_NAMES.SERVER_KEEP_ALIVE_TIMEOUT_KEY,t),ze(Me.CONFIG_PARAMS.HTTP_KEEPALIVETIMEOUT,t)),r&&(ze(Me.HDB_SETTINGS_NAMES.SERVER_HEADERS_TIMEOUT_KEY,r),ze(Me.CONFIG_PARAMS.HTTP_HEADERSTIMEOUT,r))}catch(t){let r=`Error reading in HDB environment variables from path ${ET}. Please check your boot props and settings files`;zh.fatal(r),zh.error(t)}}a(nEe,"initTestEnvironment")});var wE={};Ue(wE,{Blob:()=>mi,blobsWereEncoded:()=>fc,databasePaths:()=>lC,decodeBlobsWithWrites:()=>WE,decodeFromDatabase:()=>_c,decodeWithBlobCallback:()=>zE,deleteBlob:()=>JE,deleteBlobsInObject:()=>ra,deleteRootBlobPathsForDB:()=>nC,encodeBlobsAsBuffers:()=>_Ee,encodeBlobsWithFilePath:()=>rp,findBlobsInObject:()=>bd,getFileId:()=>YE,getFilePathForBlob:()=>BW,getRootBlobPathsForDB:()=>Xh,setDeletionDelay:()=>aEe});function vW(){}function JE(e){let t=BW(e);t&&setTimeout(()=>{(0,Xe.unlink)(t,r=>{r&&Lo.default.debug?.("Error trying to remove blob file",r)})},UW)}function aEe(e){UW=e}function xW(e){let t=Nn.get(e);if(!t)t={storageIndex:0,fileId:null,store:wn},Nn.set(e,t);else{if(t.saving)return t;t.store=wn}return lEe(t),t.source?cC(e,t.source,t):t.contentBuffer?cEe(e,t):cC(e,jh.Readable.from(e.stream()),t),t}function cC(e,t,r){let{filePath:n,fileId:s,store:i,compress:o,flush:c}=r;return r.saving=new Promise((l,u)=>{let f=s+":blob";if(!i.attemptLock(f,0))throw new Error(`Unable to get lock for blob file ${s}`);let d=(0,Xe.createWriteStream)(n,{autoClose:!1,flags:"w"});if(t.errored){let g=Buffer.from(t.errored.toString());d.end(Buffer.concat([m(BigInt(g.length)+0xff000000000000n),g]));return}let _=!1;e.size!==void 0&&(d.write(m(e.size)),_=!0);let h;o?(_||d.write(iEe),h=(0,AT.createDeflate)(),t.pipe(h).pipe(d)):(_||d.write(sEe),t.pipe(d)),t.on("error",S);function m(g){let R=BigInt(g),E=new Uint8Array(Sr),T=new DataView(E.buffer);return R|=BigInt(o?uC:MW)<<48n,T.setBigInt64(0,R),E}a(m,"createHeader");function S(g){i.unlock(f,0);let R=d.fd;g?(R&&(0,Xe.close)(R),u(g)):c?(0,Xe.fdatasync)(R,E=>{E&&u(E),l(),(0,Xe.close)(R)}):(l(),(0,Xe.close)(R))}a(S,"finished"),d.on("error",S).on("finish",()=>{if(_)S();else{let g=h?h.bytesWritten:d.bytesWritten-Sr;e.size=g,(0,Xe.write)(d.fd,m(g),0,Sr,0,S)}})}),e}function YE(e){return Nn.get(e)?.fileId}function BW(e){let t=Nn.get(e);return t?.fileId&&Jh(t)}function Xh(e){if(!e)throw new Error("No store specified, can not determine blob storage path");let t=lC.get(e);if(!t){if(!e.databaseName)return Lo.default.warn?.("No database name specified, can not determine blob storage path"),[];let r=(0,RT.get)(U.STORAGE_BLOBPATHS);r?t=r.map(n=>(0,vo.join)(n,e.databaseName)):t=[(0,vo.join)((0,RT.getHdbBasePath)(),"blobs",e.databaseName)],lC.set(e,t)}return t}async function nC(e){let t=Xh(e);t&&await Promise.all(t.map(r=>HW(r)))}async function HW(e){if((0,Xe.existsSync)(e)){for(let t of await(0,ii.readdir)(e,{withFileTypes:!0}))if(t.isDirectory())await HW((0,vo.join)(e,t.name));else try{await(0,ii.unlink)((0,vo.join)(e,t.name))}catch(r){Lo.default.warn?.("Error deleting file",r)}try{await(0,ii.rmdir)(e)}catch(t){Lo.default.warn?.("Error deleting directory",t)}}}function Jh({storageIndex:e,fileId:t,store:r}){let n=Xh(r);return(0,vo.join)(n[e],t.slice(-9,-6)||"0",t.slice(-6,-3)||"0",t.length<=9?t.slice(-3):t.slice(0,-9)+t.slice(-3))}function cEe(e,t){let r=t.contentBuffer,n=r.length;if(!(n<LW))return e.size=n,cC(e,jh.Readable.from([r]),t)}function lEe(e){let t=Xh(e.store),r=uEe(),n=t?.length>1?dEe(t,r):0,s=r.toString(16);e.storageIndex=n,e.fileId=s;let i=Jh(e),o=(0,vo.dirname)(i);(0,Xe.existsSync)(o)||(0,DW.ensureDirSync)(o),e.filePath=i}function uEe(){let e=PW.get(wn);if(!e){let t=0,r=Xh(wn);for(let n of r){let s=0;for(let i=0;i<3;i++){s=s*4096;let o=0;if((0,Xe.existsSync)(n))for(let c of(0,Xe.readdirSync)(n)){let l=parseInt(c,16);i===2&&c.length>3&&(l=parseInt(c.slice(-3),16),l+=parseInt(c.slice(0,-3),16)*68719476736),l>o&&(o=l)}s+=o,n=(0,vo.join)(n,o.toString(16))}t=Math.max(t,s)}e=new BigInt64Array([BigInt(t)+1n]),e=new BigInt64Array(wn.getUserSharedBuffer("blob-file-id",e.buffer)),PW.set(wn,e)}return Number(Atomics.add(e,0,1n))}function dEe(e,t){let r=Date.now();if(!e.frequencyTable){e.lastUpdated=0;let s=new Array(TT);for(let i=0;i<s.length;i++)s[i]=i%e.length;e.frequencyTable=s}return(e.lastUpdated??0)+6e4<r&&(e.lastUpdated=r,fEe(e)),e.frequencyTable[t%TT]}async function fEe(e){if(!ii.statfs)return;let t=await Promise.all(e.map(async(s,i)=>{let o=await(0,ii.statfs)(s),c=o.bavail*o.bsize;return Math.pow(c,.8)})),r=new Array(TT),n=t.map(s=>1/s);for(let s=0;s<TT;s++){let i=1/0,o=0;for(let c=0;c<n.length;c++)n[c]<i&&(o=c,i=n[c]);n[o]+=1/t[o],r[s]=o}e.frequencyTable=r}function rp(e,t,r){Cd=t,wn=r,fc=!1;try{return e()}finally{Cd=void 0,wn=void 0}}function _Ee(e){Br=[];let t;try{t=e()}catch(n){throw Br=void 0,n}let r=Br.length<2?Br[0]:Promise.all(Br);return Br=void 0,r?r.then(()=>e()):t}function WE(e,t){try{Br=[],bl=t,e()}catch(n){throw bl=void 0,Br=void 0,n}bl=void 0;let r=Br.length<2?Br[0]:Promise.all(Br);return Br=void 0,r}function zE(e,t,r){wn=r;try{return bl=t,e()}finally{bl=void 0}}function _c(e,t){return wn=t,e()}function ra(e){bd(e,t=>{JE(t)})}function bd(e,t){if(e instanceof mi)t(e);else if(Array.isArray(e))for(let r of e)typeof r=="object"&&r&&bd(r,t);else if(e&&typeof e=="object"&&!e[Symbol.iterator])for(let r in e){let n=e[r];typeof n=="object"&&n&&bd(e[r],t)}}function hEe(){return class{static{a(this,"Blob")}content;constructor(t){this.content=t[0]}stream(){return new ReadableStream({start(t){t.enqueue(this.content),t.close()}})}text(){return Promise.resolve(this.content.toString())}arrayBuffer(){return Promise.resolve(this.content.buffer)}get size(){return this.content.length}slice(){throw new Error("Not implemented")}bytes(){return Promise.resolve(this.content)}get type(){return""}}}var Mo,ii,Xe,AT,jh,DW,RT,vo,Lo,LW,Sr,MW,uC,IW,sEe,iEe,CW,Nn,bl,mi,Cd,Br,wn,fc,Qh,gT,oEe,ST,UW,lC,PW,TT,cs=be(()=>{Mo=require("msgpackr"),ii=require("node:fs/promises"),Xe=require("node:fs"),AT=require("node:zlib"),jh=require("node:stream"),DW=require("fs-extra"),RT=M(le());k();vo=require("path"),Lo=M(_i());Xi();LW=8192,Sr=8,MW=0,uC=1,IW=255,sEe=new Uint8Array([0,MW,255,255,255,255,255,255]),iEe=new Uint8Array([0,uC,255,255,255,255,255,255]),CW=0xffffffffffff,Nn=new WeakMap,mi=global.Blob||hEe(),fc=!1,Qh=new Uint8Array(8),gT=new DataView(Qh.buffer),oEe=6e4;a(vW,"InstanceOfBlobWithNoConstructor");vW.prototype=mi.prototype;ST=class e extends vW{static{a(this,"FileBackedBlob")}type="";size;#e;#t;constructor(t){super(),t?.type&&(this.type=t.type),t?.size!=null&&(this.size=t.size)}on(t,r){if(t==="error")this.#e??=[],this.#e.push(r);else if(t==="size")this.#t??=[],this.#t.push(r);else throw new Error("Only 'error' and 'size' events are supported")}toJSON(){if(this.type?.startsWith("text")){let t=Nn.get(this),{start:r,end:n,contentBuffer:s,asString:i}=t;return i||(s&&(n!==void 0||r!==void 0)&&(s=s.subarray(r??0,n??t.contentBuffer.length)),s?(t.asString=s.toString(),t.asString):(kA()&&HA(this.bytes().then(o=>t.contentBuffer=o)),`[blob: ${this.type}, ${this.size} bytes]`))}return{description:"Blobs that are not of type text/* can not be directly serialized as JSON, use as the body of a response or convert to another type"}}async text(){return(await this.bytes()).toString()}bytes(){let t=Nn.get(this),{start:r,end:n,contentBuffer:s}=t;if(s)return(n!==void 0||r!==void 0)&&(s=s.subarray(r??0,n??t.contentBuffer.length)),Promise.resolve(s);let i=Jh(t),o,c=a(async()=>{let l,u=Sr;try{if(l=await(0,ii.readFile)(i),l.length>=Sr){l.copy(Qh,0,0,Sr);let d=gT.getBigUint64(0);if(Number(d>>48n)===IW)throw new Error("Error in blob: "+buffer.subarray(Sr));if(u=Number(d&0xffffffffffffn),u<n&&(u=n),u<CW&&(this.size=u,this.#t))for(let _ of this.#t)_(u)}}catch(d){if(d.code!=="ENOENT")throw d;l=Buffer.alloc(0)}function f(d){if(u>d.length){let _=t.store,h=t.fileId+":blob";if(o)throw new Error("Incomplete blob");return new Promise((m,S)=>{if(_.attemptLock(h,0,()=>(o=!0,m(c()))))return o=!0,_.unlock(h,0),m(c())})}return(n!=null||r!=null)&&(d=d.subarray(r??0,n??d.length)),d}return a(f,"checkCompletion"),l[1]===uC?new Promise((d,_)=>{(0,AT.deflate)(l.subarray(Sr),(h,m)=>{h?_(h):d(f(m))})}):f(l.subarray(Sr))},"readContents");return c()}async arrayBuffer(){let t=await this.bytes(),r=new ArrayBuffer(t.length);return new Uint8Array(r).set(t),r}stream(){let t=Nn.get(this),{contentBuffer:r,start:n,end:s}=t;if(r)return(s!=null||n!=null)&&(r=r.subarray(n??0,s??t.contentBuffer.length)),new ReadableStream({pull(S){S.enqueue(r),S.close()}});let i=Jh(t),o,c=0,l=0,u,f,d,_=!1,h=this;return new ReadableStream({start(){let S=1e3,g=a((R,E)=>{(0,Xe.open)(i,"r",(T,w)=>{if(T){if(T.code==="ENOENT"&&d!==!1&&(Lo.default.debug?.("File does not exist yet, waiting for it to be created",i,S),S-- >0))return setTimeout(()=>{m(),g(R,E)},20).unref();E(T),h.#e?.forEach(v=>v(T))}else o=w,R(w)})},"openFile");return new Promise(g)},pull:a(S=>{let g=0,R=100;return new Promise(a(function E(T,w){function v(q){(0,Xe.close)(o),clearTimeout(f),u&&u.close(),w(q),h.#e?.forEach(W=>W(q))}a(v,"onError");let H=Buffer.allocUnsafe(262144);(0,Xe.read)(o,H,0,H.length,c,(q,W,te)=>{if(l+=W,q)return v(q);if(c===0){if(W<Sr){R-- >0&&d!==!1?(m(),Lo.default.debug?.("File was empty, waiting for data to be written",i,R),setTimeout(()=>E(T,w),20).unref()):(Lo.default.debug?.("File was empty, throwing error",i,R),w(new Error(`Blob ${t.fileId} was empty`)));return}te.copy(Qh,0,0,Sr);let se=gT.getBigUint64(0);if(Number(se>>48n)===IW)return v(new Error("Error in blob: "+te.subarray(Sr)));if(g=Number(se&0xffffffffffffn),g<CW&&h.size!==g&&(h.size=g,h.#t))for(let Y of h.#t)Y(g);te=te.subarray(Sr,W),l-=Sr}else if(W===0){let se=Buffer.allocUnsafe(8);return(0,Xe.read)(o,se,0,Sr,0,Y=>{if(Y)return v(Y);if(Qh.set(se),g=Number(gT.getBigUint64(0)&0xffffffffffffn),g>l){m()?u?f=setTimeout(()=>{v(new Error("File read timed out"))},oEe).unref():(u=(0,Xe.watch)(i,{persistent:!1},()=>{u.close(),u=null,f&&(clearTimeout(f),f=null,E(T,w))}),E(T,w)):_?v(new Error("Blob is incomplete")):(_=!0,E(T,w));return}(0,Xe.close)(o),S.close(),T()})}else te=te.subarray(0,W);if(n!==void 0||s!==void 0){if(n&&l<n)return c+=W,E(T,w);s&&l>=s&&(l>s&&(te=te.subarray(0,s-c)),l=g=s),n&&n>c&&(te=te.subarray(n-c))}c+=W;try{S.enqueue(te)}catch(se){return Lo.default.debug?.("Error enqueuing chunk",se),T()}l===g&&((0,Xe.close)(o),S.close()),T()})},"readMore"))},"pull"),cancel(){(0,Xe.close)(o),clearTimeout(f),u&&u.close()}});function m(){if(d===void 0){let S=t.store,g=t.fileId+":blob";d=!S.attemptLock(g,0,()=>{d=!1}),d||S.unlock(g,0)}return d}}slice(t,r,n){let s=Nn.get(this),i=new e(n&&{type:n});if(s?.fileId){let o={...s,start:t,end:r};Nn.set(i,o),this.size!=null&&(i.size=(r==null?this.size:Math.min(r,this.size))-(t??0))}else if(s?.contentBuffer&&!s.storageBuffer){let o={...s,contentBuffer:s.contentBuffer.subarray(t,r)};Nn.set(i,o),i.size=(r??this.size)-t}else throw new Error("Can not slice a streaming blob that is not backed by a file");return i}save(t){if(wn=t?.primaryStore?.rootStore,!wn)throw new Error("No target table specified");return xW(this).saving??Promise.resolve()}},UW=500;a(JE,"deleteBlob");a(aEe,"setDeletionDelay");global.createBlob=function(e,t){let r=new ST(t),n={storageIndex:0,fileId:null,flush:t?.flush,compress:t?.compress};if(Nn.set(r,n),e instanceof Uint8Array)r.size=e.length,n.contentBuffer=e;else if(e instanceof jh.Readable)n.source=e;else if(typeof e=="string")n.contentBuffer=Buffer.from(e);else if(e?.[Symbol.asyncIterator]||e?.[Symbol.iterator])n.source=jh.Readable.from(e);else throw new Error("Invalid source type");return r};a(xW,"saveBlob");a(cC,"writeBlobWithStream");a(YE,"getFileId");a(BW,"getFilePathForBlob");lC=new Map;a(Xh,"getRootBlobPathsForDB");a(nC,"deleteRootBlobPathsForDB");a(HW,"rimrafSteadily");a(Jh,"getFilePath");a(cEe,"writeBlobWithBuffer");a(lEe,"generateFilePath");PW=new Map;a(uEe,"getNextFileId");TT=128;a(dEe,"getNextStorageIndex");a(fEe,"createFrequencyTableForStoragePaths");a(rp,"encodeBlobsWithFilePath");a(_Ee,"encodeBlobsAsBuffers");a(WE,"decodeBlobsWithWrites");a(zE,"decodeWithBlobCallback");a(_c,"decodeFromDatabase");a(ra,"deleteBlobsInObject");a(bd,"findBlobsInObject");(0,Mo.addExtension)({Class:mi,type:11,unpack:a(function(e){let t=(0,Mo.unpack)(e),r=new ST;if(Object.assign(r,t[0]),typeof t[1]!="object"){if(Nn.set(r,{storageIndex:t[1],fileId:t[2],store:wn}),bl)return bl(r)??r;if(!wn)throw new Error("No store specified, cannot load blob from storage")}else Nn.set(r,{storageIndex:0,fileId:null,storageBuffer:e,contentBuffer:t[1]}),r.size=t[1]?.length;return r},"unpack"),pack:a(function(e){let t=Nn.get(e);if(Cd!==void 0&&(fc=!0,t?.recordId!==void 0&&t.recordId!==Cd))throw new Error("Cannot use the same blob in two different records");let r={...e};if(e.type&&(r.type=e.type),e.size!==void 0&&(r.size=e.size),t){if(t.storageBuffer)return t.storageBuffer;if(t.contentBuffer?.length<LW)return r.size=t.contentBuffer.length,(0,Mo.pack)([r,t.contentBuffer])}if(Cd!==void 0){if(t=xW(e),!t.fileId)throw new Error("Unable to save blob without file id");return t.recordId=Cd,(0,Mo.pack)([r,t.storageIndex,t.fileId])}if(t)try{let n=(0,Xe.readFileSync)(Jh(t));if(n.length>=Sr&&(n.copy(Qh,0,0,Sr),Number(gT.getBigUint64(0)&0xffffffffffffn)===n.length-Sr))return Buffer.concat([(0,Mo.pack)([r]),n]);if(Br)Br.push(e.bytes());else throw new Error("Incomplete blob");return Buffer.alloc(0)}catch(n){if(n.code==="ENOENT"&&Br)return Br.push(e.bytes()),Buffer.alloc(0);throw n}else throw new Error("Blob has no storage info or buffer attached to it")},"pack")});(0,Mo.addExtension)({Class:Promise,type:12,pack(){throw new Error("Cannot encode a promise")}});a(hEe,"polyfillBlob")});var fC=P((bMe,kW)=>{"use strict";var Zh=le();Zh.initSync();var Pd=require("fs-extra"),dC=require("path"),Dd=(k(),D($)),mEe=require("crypto"),pEe=require("uuid").v4;kW.exports=EEe;function EEe(){if(Zh.getHdbBasePath()!==void 0){let e=dC.join(Zh.getHdbBasePath(),Dd.LICENSE_KEY_DIR_NAME,Dd.JWT_ENUM.JWT_PRIVATE_KEY_NAME),t=dC.join(Zh.getHdbBasePath(),Dd.LICENSE_KEY_DIR_NAME,Dd.JWT_ENUM.JWT_PUBLIC_KEY_NAME),r=dC.join(Zh.getHdbBasePath(),Dd.LICENSE_KEY_DIR_NAME,Dd.JWT_ENUM.JWT_PASSPHRASE_NAME);try{Pd.accessSync(r),Pd.accessSync(e),Pd.accessSync(t)}catch(n){if(n.code==="ENOENT"){let s=pEe(),i=mEe.generateKeyPairSync("rsa",{modulusLength:4096,publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs8",format:"pem",cipher:"aes-256-cbc",passphrase:s}});Pd.writeFileSync(r,s),Pd.writeFileSync(e,i.privateKey),Pd.writeFileSync(t,i.publicKey)}else throw n}}}a(EEe,"checkJWTTokenExist")});var GW=P((NMe,FW)=>{"use strict";var _C=class{static{a(this,"HdbInfoInsertObject")}constructor(t,r,n){this.info_id=t,this.data_version_num=r,this.hdb_version_num=n}};FW.exports={HdbInfoInsertObject:_C}});var VW=P((IMe,$W)=>{"use strict";var qW=(k(),D($)),hC=class{static{a(this,"UpgradeObject")}constructor(t,r){this[qW.UPGRADE_JSON_FIELD_NAMES_ENUM.DATA_VERSION]=t,this[qW.UPGRADE_JSON_FIELD_NAMES_ENUM.UPGRADE_VERSION]=r}};$W.exports={UpgradeObject:hC}});var yT=P((PMe,YW)=>{"use strict";var ws=require("prompt"),Ld=require("chalk"),KW=j(),oi=require("os"),mC=rc(),pC=["yes","y"];async function gEe(e){let t=`${oi.EOL}`+Ld.bold.green("Your current HarperDB version requires that we complete an update process.")+`${oi.EOL}If a backup of your data has not been created, we recommend you cancel this process and backup before proceeding.${oi.EOL}${oi.EOL}You can read more about the changes in this upgrade at https://harperdb.io/developers/release-notes/${oi.EOL}`;ws.override=mC(["CONFIRM_UPGRADE"]),ws.start(),ws.message=t;let r={properties:{CONFIRM_UPGRADE:{description:Ld.magenta(`${oi.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 ws.get([r])}catch(s){return KW.error("There was an error when prompting user about an upgrade."),KW.error(s),!1}return pC.includes(n.CONFIRM_UPGRADE)}a(gEe,"forceUpdatePrompt");async function SEe(e){let t=`${oi.EOL}`+Ld.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.${oi.EOL}`);ws.override=mC(["CONFIRM_DOWNGRADE"]),ws.start(),ws.message=t;let r={properties:{CONFIRM_DOWNGRADE:{description:Ld.magenta(`${oi.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 ws.get([r]);return pC.includes(n.CONFIRM_DOWNGRADE)}a(SEe,"forceDowngradePrompt");async function TEe(){let e=`${oi.EOL}`+Ld.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");ws.override=mC(["GENERATE_CERTS"]),ws.start(),ws.message=e;let t={properties:{GENERATE_CERTS:{description:Ld.magenta(`${oi.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 ws.get([t]);return pC.includes(r.GENERATE_CERTS)}a(TEe,"upgradeCertsPrompt");YW.exports={forceUpdatePrompt:gEe,forceDowngradePrompt:SEe,upgradeCertsPrompt:TEe}});var gC=P((LMe,WW)=>{"use strict";var EC=class{static{a(this,"UpgradeDirective")}constructor(t){this.version=t,this.sync_functions=[],this.async_functions=[]}};WW.exports=EC});var QW=P((HMe,zW)=>{"use strict";var AEe=ae(),REe=Ct(),vMe=j(),UMe=require("path"),xMe=require("fs"),BMe=(k(),D($));zW.exports={getOldPropsValue:yEe};function yEe(e,t,r=!1){let n=t.getRaw(e);return AEe.isNotEmptyAndHasValue(n)?n:r?REe.getDefaultConfig(e):""}a(yEe,"getOldPropsValue")});var ZW=P((FMe,XW)=>{"use strict";var $a=require("path"),Va=require("fs-extra"),bEe=require("properties-reader"),OEe=gC(),lr=j(),{getOldPropsValue:ht}=QW(),{HDB_SETTINGS_NAMES:ge,CONFIG_PARAMS:Ol}=(k(),D($)),Nl=Ct(),bT=le(),jW=ae(),Bi=(k(),D($)),SC=new OEe("3.1.0"),JW=[];function NEe(){let e=bEe(bT.get(ge.SETTINGS_PATH_KEY)),t="Updating settings file for version 3.1.0";console.log(t),lr.info(t);let r=` ;Settings for the HarperDB process.
|
|
40
40
|
|
|
41
41
|
;The directory selected during install where the database files reside.
|
|
42
42
|
${ge.HDB_ROOT_KEY} = ${ht(ge.HDB_ROOT_KEY,e)}
|