harperdb 4.5.12 → 4.5.13
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 +2 -2
- package/bin/lite.js +23 -23
- package/launchServiceScripts/launchNatsIngestService.js +23 -23
- package/launchServiceScripts/launchNatsReplyService.js +2 -2
- package/launchServiceScripts/launchUpdateNodes4-0-0.js +24 -24
- package/npm-shrinkwrap.json +38 -31
- package/package.json +1 -1
- package/server/jobs/jobProcess.js +2 -2
- package/server/threads/threadServer.js +24 -24
- package/studio/build-local/asset-manifest.json +2 -2
- package/studio/build-local/index.html +1 -1
- package/studio/build-local/static/js/{main.f785c076.js → main.0bd2b3d8.js} +2 -2
- package/utility/scripts/restartHdb.js +25 -25
- /package/studio/build-local/static/js/{main.f785c076.js.LICENSE.txt → main.0bd2b3d8.js.LICENSE.txt} +0 -0
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
`+JSON.stringify(u)),u.cause&&(t[c--]=u.cause,u&&(n+=`
|
|
5
5
|
Caused by:`));else if(typeof u=="object")try{n+=JSON.stringify(u)}catch{n+="Object ["+Object.keys(u)+"]"}else n+=u;c<i&&(n+=" ")}return`${r} [${o.join("] [")}]: ${n}
|
|
6
6
|
`}a(xs,"createLogRecord");function tf(e){if(li){if(FP(e),os){Wo=!1;try{process.stdout.write(e)}finally{Wo=!0}}}else os&&process.stdout.write(e)}a(tf,"logStdOut");function Hm(e){if(li){if(FP(e),os){Wo=!1;try{process.stderr.write(e)}finally{Wo=!0}}}else os&&process.stderr.write(e)}a(Hm,"logStdErr");function FP(e){TA(),Yo?Wi.appendFileSync(Yo,e):SA||console.log(e)}a(FP,"logToFile");function RA(){try{Wi.closeSync(Yo)}catch{}Yo=null}a(RA,"closeLogFile");function TA(){if(!Yo){try{Yo=Wi.openSync(xm,"a")}catch(e){SA||(SA=!0,console.error(e))}setTimeout(()=>{RA()},F2).unref()}}a(TA,"openLogFile");function qP(...e){mr[Cr]<=mr.info&&tf(xs("info",e))}a(qP,"info");function GP(...e){mr[Cr]<=mr.trace&&tf(xs("trace",e))}a(GP,"trace");function Bm(...e){mr[Cr]<=mr.error&&Hm(xs("error",e))}a(Bm,"error");function $P(...e){mr[Cr]<=mr.debug&&tf(xs("debug",e))}a($P,"debug");function VP(...e){mr[Cr]<=mr.notify&&tf(xs("notify",e))}a(VP,"notify");function KP(...e){mr[Cr]<=mr.fatal&&Hm(xs("fatal",e))}a(KP,"fatal");function YP(...e){mr[Cr]<=mr.warn&&Hm(xs("warn",e))}a(YP,"warn");function Y2(e,t,...r){t===HP.STDERR?Hm(xs(e,r)):tf(xs(e,r))}a(Y2,"logCustomLevel");function W2(){let e;try{e=x2.homedir()}catch{e=process.env.HOME}e||(e="~/");let t=ui.join(e,$t.HDB_HOME_DIR_NAME,$t.BOOT_PROPS_FILE_NAME);return Wi.existsSync(t)||(t=ui.join(AA,"utility/hdb_boot_properties.file")),t}a(W2,"getPropsFilePath");function z2(e){Cr=e}a(z2,"setLogLevel");function UP(e){return e===!0||typeof e=="string"&&e.toLowerCase()==="true"}a(UP,"autoCastBoolean");function j2(e){try{if(e.includes("config/settings.js")){let o=BP(e);return{level:o.get($t.HDB_SETTINGS_NAMES.LOG_LEVEL_KEY),config_log_path:ui.dirname(o.get($t.HDB_SETTINGS_NAMES.LOG_PATH_KEY)),to_file:o.get($t.HDB_SETTINGS_NAMES.LOG_TO_FILE),to_stream:o.get($t.HDB_SETTINGS_NAMES.LOG_TO_STDSTREAMS)}}let t=xP.parseDocument(Wi.readFileSync(e,"utf8")),r=t.getIn(["logging","level"]),n=t.getIn(["logging","root"]),s=t.getIn(["logging","file"]),i=t.getIn(["logging","stdStreams"]);return{level:r,config_log_path:n,to_file:s,to_stream:i}}catch(t){if(t.code===$t.NODE_ERROR_CODES.ENOENT)throw t;console.error("Error accessing config file for logging"),console.error(t)}}a(j2,"getLogConfig");function Q2(){try{let e=xP.parseDocument(Wi.readFileSync(k2,"utf8")),t=e.getIn(["logging","level"]),r=e.getIn(["logging","file"]),n=e.getIn(["logging","stdStreams"]);return{default_level:t,default_to_file:r,default_to_stream:n}}catch(e){console.error("Error accessing default config file for logging"),console.error(e)}}a(Q2,"getDefaultConfig");function J2(e,t,r,n,s,i){this.username=e,this.status=t,this.type=r,this.originating_ip=n,this.request_method=s,this.path=i}a(J2,"AuthAuditLog")});var yA=P((IRe,jP)=>{"use strict";var X2=require("util"),Z2=require("path"),eJ=require("child_process"),tJ=X2.promisify(eJ.execFile),rJ=1e3*1e3*10;jP.exports={findPs:nJ};async function nJ(e){let t={};try{await Promise.all(["comm","args","ppid","uid","%cpu","%mem"].map(async r=>{let{stdout:n}=await tJ("ps",["wwxo",`pid,${r}`],{maxBuffer:rJ});for(let s of n.trim().split(`
|
|
7
|
-
`).slice(1)){s=s.trim();let[i]=s.split(" ",1),o=s.slice(i.length+1).trim();t[i]===void 0&&(t[i]={}),t[i][r]=o}}))}catch(r){throw r}return Object.entries(t).filter(([,r])=>r.comm&&r.args&&r.ppid&&r.uid&&r["%cpu"]&&r["%mem"]&&r.args.includes(e)).map(([r,n])=>({pid:Number.parseInt(r,10),name:Z2.basename(n.comm),cmd:n.args,ppid:Number.parseInt(n.ppid,10),uid:Number.parseInt(n.uid,10),cpu:Number.parseFloat(n["%cpu"]),memory:Number.parseFloat(n["%mem"])}))}a(nJ,"findPs")});var vt=P((PRe,JP)=>{"use strict";var sJ="__dbis__",iJ="__txns__",oJ="__environment_name__",aJ="__dbi_defintion__",cJ={EQUALS:"equals",STARTS_WITH:"startsWith",_STARTS_WITH:"starts_with",ENDS_WITH:"endsWith",_ENDS_WITH:"ends_with",CONTAINS:"contains",SEARCH_ALL:"searchAll",SEARCH_ALL_TO_MAP:"searchAllToMap",BATCH_SEARCH_BY_HASH:"batchSearchByHash",BATCH_SEARCH_BY_HASH_TO_MAP:"batchSearchByHashToMap",GREATER_THAN:"greaterThan",_GREATER_THAN:"greater_than",GREATER_THAN_EQUAL:"greaterThanEqual",_GREATER_THAN_EQUAL:"greater_than_equal",LESS_THAN:"lessThan",_LESS_THAN:"less_than",LESS_THAN_EQUAL:"lessThanEqual",_LESS_THAN_EQUAL:"less_than_equal",BETWEEN:"between"},lJ=["__createdtime__","__updatedtime__"],uJ="\uFFFF",QP={TIMESTAMP:"timestamp",HASH_VALUE:"hash_value",USER_NAME:"user_name"},dJ=Object.values(QP);JP.exports={AUDIT_STORE_NAME:iJ,INTERNAL_DBIS_NAME:sJ,DBI_DEFINITION_NAME:aJ,SEARCH_TYPES:cJ,TIMESTAMP_NAMES:lJ,MAX_SEARCH_KEY_LENGTH:256,ENVIRONMENT_NAME_KEY:oJ,TRANSACTIONS_DBI_NAMES_ENUM:QP,TRANSACTIONS_DBIS:dJ,OVERFLOW_MARKER:uJ}});var Dn=P((DRe,oD)=>{"use strict";var XP=(B(),D(q)),ZP=vt(),eD={CONTINUE:100,OK:200,CREATED:201,BAD_REQUEST:400,UNAUTHORIZED:401,FORBIDDEN:403,NOT_FOUND:404,METHOD_NOT_ALLOWED:405,REQUEST_TIMEOUT:408,CONFLICT:409,TOO_MANY_REQUESTS:429,INTERNAL_SERVER_ERROR:500,NOT_IMPLEMENTED:501,BAD_GATEWAY:502,SERVICE_UNAVAILABLE:503,GATEWAY_TIMEOUT:504,HTTP_VERSION_NOT_SUPPORTED:505,INSUFFICIENT_STORAGE:507,NETWORK_AUTHENTICATION_REQUIRED:511},tD=a(e=>`${e} Check logs and try again.`,"CHECK_LOGS_WRAPPER"),rD={500:tD("There was an error processing your request."),400:"Invalid request"},fJ=rD[eD.INTERNAL_SERVER_ERROR],_J={OP_NOT_SUPPORTED_FOR_FS:a(e=>`${e} is not available for this instance because it uses the File System data store.`,"OP_NOT_SUPPORTED_FOR_FS"),MISSING_VALUE:a(e=>`${e} is missing.`,"MISSING_VALUE"),INVALID_VALUE:a(e=>`${e} is invalid.`,"INVALID_VALUE"),NOT_FOUND:a(e=>`${e} not found.`,"NOT_FOUND")},hJ={CONFIG_VALIDATION:a(e=>`HarperDB config file validation error: ${e}`,"CONFIG_VALIDATION")},mJ={DEFAULT_BULK_LOAD_ERR:"There was an error during your bulk load into HarperDB.",DOWNLOAD_FILE_ERR:a(e=>`There was an error downloading '${e}'.`,"DOWNLOAD_FILE_ERR"),INSERT_JSON_ERR:"There was an error inserting the downloaded JSON data.",INSERT_CSV_ERR:"There was an error inserting the downloaded CSV data.",INVALID_ACTION_PARAM_ERR:a(e=>`Bulk load operation failed - ${e} is not a valid 'action' parameter`,"INVALID_ACTION_PARAM_ERR"),INVALID_FILE_EXT_ERR:a(e=>`Error selecting correct parser - valid file type not found in json - ${e}`,"INVALID_FILE_EXT_ERR"),MAX_FILE_SIZE_ERR:a((e,t)=>`File size is ${e} bytes, which exceeded the maximum size allowed of: ${t} bytes`,"MAX_FILE_SIZE_ERR"),PAPA_PARSE_ERR:"There was an error parsing the downloaded CSV data.",S3_DOWNLOAD_ERR:a(e=>`There was an error downloading '${e}' from AWS.`,"S3_DOWNLOAD_ERR"),WRITE_TEMP_FILE_ERR:"Error writing temporary file to storage"},pJ={BASE_PATH_REQUIRED:"base_path is required",DESTINATION_PATH_REQUIRED:"destination_path is required",ENV_NAME_REQUIRED:"env_name is required",INVALID_BASE_PATH:"invalid base_path",INVALID_DESTINATION_PATH:"invalid destination_path",INVALID_ENVIRONMENT:"invalid environment",ENV_REQUIRED:"env is required",DBI_NAME_REQUIRED:"dbi_name is required",DBI_DOES_NOT_EXIST:"dbi does not exist",HASH_ATTRIBUTE_REQUIRED:"hash_attribute is required",ID_REQUIRED:"id is required",IDS_REQUIRED:"ids is required",IDS_MUST_BE_ITERABLE:"ids must be iterable",FETCH_ATTRIBUTES_REQUIRED:"fetch_attributes is required",FETCH_ATTRIBUTES_MUST_BE_ARRAY:"fetch_attributes must be an array",ATTRIBUTE_REQUIRED:"attribute is required",SEARCH_VALUE_REQUIRED:"search_value is required",SEARCH_VALUE_TOO_LARGE:"search_value is too long",WRITE_ATTRIBUTES_REQUIRED:"write_attributes is required",WRITE_ATTRIBUTES_MUST_BE_ARRAY:"write_attributes must be an array",RECORDS_REQUIRED:"records is required",RECORDS_MUST_BE_ARRAY:"records must be an array",CANNOT_CREATE_INTERNAL_DBIS_NAME:`cannot create a dbi named ${ZP.INTERNAL_DBIS_NAME}`,CANNOT_DROP_INTERNAL_DBIS_NAME:`cannot drop a dbi named ${ZP.INTERNAL_DBIS_NAME}`,START_VALUE_REQUIRED:"start_value is required",END_VALUE_REQUIRED:"end_value is required",CANNOT_COMPARE_STRING_TO_NUMERIC_KEYS:"cannot compare a string to numeric keys",END_VALUE_MUST_BE_GREATER_THAN_START_VALUE:"end_value must be greater than or equal to start_value",UNKNOWN_SEARCH_TYPE:"unknown search type",CANNOT_DROP_TABLE_HASH_ATTRIBUTE:"cannot drop a table's hash attribute"},EJ={ATTR_NAME_LENGTH_ERR:a(e=>`transaction aborted due to attribute name ${e} being too long. Attribute names cannot be longer than ${XP.INSERT_MAX_CHARACTER_SIZE} bytes.`,"ATTR_NAME_LENGTH_ERR"),ATTR_NAME_NULLISH_ERR:"transaction aborted due to record(s) with an attribute name that is null, undefined or empty string",HASH_VAL_LENGTH_ERR:`transaction aborted due to record(s) with a hash value that exceeds ${XP.INSERT_MAX_CHARACTER_SIZE} bytes, check log for more info`,INVALID_FORWARD_SLASH_IN_HASH_ERR:"transaction aborted due to record(s) with a hash value that contains a forward slash, check log for more info",RECORD_MISSING_HASH_ERR:"transaction aborted due to record(s) with no hash value, check log for more info"},nD={GENERIC_AUTH_FAIL:"Login failed",USER_INACTIVE:"Cannot complete request: User is inactive",INVALID_TOKEN:"invalid token",NO_ENCRYPTION_KEYS:"unable to generate JWT as there are no encryption keys. please contact your administrator",INVALID_CREDENTIALS:"invalid credentials",PASSWORD_REQUIRED:"password is required",USERNAME_REQUIRED:"username is required",REFRESH_TOKEN_REQUIRED:"refresh_token is required",INVALID_AUTH_OBJECT:"invalid auth_object",INVALID_BODY:"invalid body",TOKEN_EXPIRED:"token expired",REFRESH_TOKEN_SAVE_FAILED:"unable to store refresh_token"},gJ={DEFAULT_INVALID_REQUEST:"Invalid request",OP_AUTH_PERMS_ERROR:"This operation is not authorized due to role restrictions and/or invalid database items",OP_IS_SU_ONLY:a(e=>`Operation '${e}' is restricted to 'super_user' roles`,"OP_IS_SU_ONLY"),OP_NOT_FOUND:a(e=>`Operation '${e}' not found`,"OP_NOT_FOUND"),SYSTEM_TIMESTAMP_PERMS_ERR:"Internal timestamp attributes - '__createdtime_' and '__updatedtime__' - cannot be inserted to or updated by HDB users.",UNKNOWN_OP_AUTH_ERROR:a((e,t,r)=>`There was an error authorizing ${e} op on table '${t}.${r}'`,"UNKNOWN_OP_AUTH_ERROR"),USER_HAS_NO_PERMS:a(e=>`User ${e} has no role or permissions. Please assign the user a valid role.`,"USER_HAS_NO_PERMS"),DROP_SYSTEM:"The 'system' database, tables and records are used internally by HarperDB and cannot be updated or removed."},SJ={ATTR_PERM_MISSING:a((e,t)=>`${e.toUpperCase()} attribute permission missing for '${t}'`,"ATTR_PERM_MISSING"),ATTR_PERM_MISSING_NAME:"Permission object in 'attribute_permission' missing an 'attribute_name'",ATTR_PERM_NOT_BOOLEAN:a((e,t)=>`${e.toUpperCase()} attribute permission for '${t}' must be a boolean`,"ATTR_PERM_NOT_BOOLEAN"),ATTR_PERMS_ARRAY_MISSING:"Missing 'attribute_permissions' array",ATTR_PERMS_NOT_ARRAY:"Value for 'attribute_permissions' must be an array",INVALID_ATTRIBUTE_IN_PERMS:a(e=>`Invalid attribute '${e}' in 'attribute_permissions'`,"INVALID_ATTRIBUTE_IN_PERMS"),INVALID_PERM_KEY:a(e=>`Invalid table permission key value '${e}'`,"INVALID_PERM_KEY"),INVALID_ATTR_PERM_KEY:a(e=>`Invalid attribute permission key value '${e}'`,"INVALID_ATTR_PERM_KEY"),INVALID_ROLE_JSON_KEYS:a(e=>`Invalid ${e.length>1?"keys":"key"} in JSON body - '${e.join("', '")}'`,"INVALID_ROLE_JSON_KEYS"),MISMATCHED_TABLE_ATTR_PERMS:a(e=>`You have a conflict with TABLE permissions for '${e}' being false and ATTRIBUTE permissions being true`,"MISMATCHED_TABLE_ATTR_PERMS"),OUTDATED_PERMS_TRANSLATION_ERROR:"This instance was recently upgraded and uses our new role permissions structure. Please login to this instance in HarperDB Studio, go to 'Roles', and click 'Update Role Permission' for all standard roles to migrate them to the new structure.",ROLE_ALREADY_EXISTS:a(e=>`A role with name '${e}' already exists`,"ROLE_ALREADY_EXISTS"),ROLE_NOT_FOUND:"Role not found",ROLE_PERMS_ERROR:"Errors in the role permissions JSON provided",SCHEMA_PERM_ERROR:a(e=>`Your role does not have permission to view database metadata for '${e}'`,"SCHEMA_PERM_ERROR"),SCHEMA_TABLE_PERM_ERROR:a((e,t)=>`Your role does not have permission to view database.table metadata for '${e}.${t}'`,"SCHEMA_TABLE_PERM_ERROR"),SU_ROLE_MISSING_ERROR:"Missing 'super_user' key/value in permission set",SU_CU_ROLE_BOOLEAN_ERROR:a(e=>`Value for '${e}' permission must be a boolean`,"SU_CU_ROLE_BOOLEAN_ERROR"),STRUCTURE_USER_ROLE_TYPE_ERROR:a(e=>`Value for '${e}' permission must be a boolean or Array`,"STRUCTURE_USER_ROLE_TYPE_ERROR"),SU_CU_ROLE_NO_PERMS_ALLOWED:a(e=>`Roles with '${e}' set to true cannot have other permissions set.`,"SU_CU_ROLE_NO_PERMS_ALLOWED"),SU_CU_ROLE_COMBINED_ERROR:"Roles cannot have both 'super_user' and 'cluster_user' values included in their permissions set.",TABLE_PERM_MISSING:a(e=>`Missing table ${e.toUpperCase()} permission`,"TABLE_PERM_MISSING"),TABLE_PERM_NOT_BOOLEAN:a(e=>`Table ${e.toUpperCase()} permission must be a boolean`,"TABLE_PERM_NOT_BOOLEAN")},TJ={ATTR_NOT_FOUND:a((e,t,r)=>`Attribute '${r}' does not exist on '${e}.${t}'`,"ATTR_NOT_FOUND"),ATTR_EXISTS_ERR:a((e,t,r)=>`Attribute '${r}' already exists in ${e}.${t}'`,"ATTR_EXISTS_ERR"),DESCRIBE_ALL_ERR:"There was an error during describeAll. Please check the logs and try again.",INVALID_TABLE_ERR:a(e=>`Invalid table ${JSON.stringify(e)}`,"INVALID_TABLE_ERR"),SCHEMA_NOT_FOUND:a(e=>`database '${e}' does not exist`,"SCHEMA_NOT_FOUND"),SCHEMA_EXISTS_ERR:a(e=>`database '${e}' already exists`,"SCHEMA_EXISTS_ERR"),TABLE_EXISTS_ERR:a((e,t)=>`Table '${t}' already exists in '${e}'`,"TABLE_EXISTS_ERR"),SCHEMA_REQUIRED_ERR:"database is required",TABLE_NOT_FOUND:a((e,t)=>`Table '${e}.${t}' does not exist`,"TABLE_NOT_FOUND"),TABLE_REQUIRED_ERR:"table is required"},AJ={OUTER_JOIN_TRANSLATION_ERROR:"There was an error translating the final SQL outer join data."},RJ={ALTER_USER_DUP_ROLES:a(e=>`Update failed. There are duplicates for the '${e}' role which is not allowed. Update your roles and try again.`,"ALTER_USER_DUP_ROLES"),ALTER_USER_ROLE_NOT_FOUND:a(e=>`Update failed. Requested '${e}' role not found.`,"ALTER_USER_ROLE_NOT_FOUND"),DUP_ROLES_FOUND:a(e=>`Multiple ${e} roles found. Roles must have unique 'role' value. Please update and try again.`,"DUP_ROLES_FOUND"),ROLE_NAME_NOT_FOUND:a(e=>`${e} role not found`,"ROLE_NAME_NOT_FOUND"),USER_ALREADY_EXISTS:a(e=>`User ${e} already exists`,"USER_ALREADY_EXISTS"),USER_NOT_EXIST:a(e=>`User ${e} does not exist`,"USER_NOT_EXIST")},sD={INVALID_DATE:"Invalid date, must be in ISO-8601 format (YYYY-MM-DD).",SEARCH_CONDITIONS_INVALID_SORT_ATTRIBUTE:a(e=>`invalid sort attribute '${e}', the attribute must either be the table's hash attribute or an attribute used in conditions.`,"SEARCH_CONDITIONS_INVALID_SORT_ATTRIBUTE")},iD={INVALID_ITC_DATA_TYPE:"Invalid ITC event data type, must be an object",MISSING_TYPE:"ITC event missing 'type'",MISSING_MSG:"ITC event missing 'message'",MISSING_ORIGIN:"ITC event message missing 'originator' property",INVALID_EVENT:a(e=>`ITC server received invalid event type: ${e}`,"INVALID_EVENT")},yJ={FUNCTION_STATUS:"Error getting custom function status, check the log for more details",GET_FUNCTIONS:"Error getting custom functions, check the log for more details",GET_FUNCTION:"Error getting custom function, check the log for more details",SET_FUNCTION:"Error setting custom function, check the log for more details",NO_PROJECT:"Project does not exist. Create one using 'add_custom_function_project'",PROJECT_EXISTS:"Project already exists",VALIDATION_ERR:"Error validating request, check the log for more details",NO_FILE:"File does not exist",BAD_FILE_NAME:"File name can only contain alphanumeric, dash and underscore characters",BAD_PROJECT_NAME:"Project name can only contain alphanumeric, dash and underscores characters",BAD_PACKAGE:"Packaged project must be base64-encoded tar file of project directory",DROP_FUNCTION:"Error dropping custom function, check the log for more details",ADD_FUNCTION:"Error adding custom function project, check the log for more details",DROP_FUNCTION_PROJECT:"Error dropping custom function project, check the log for more details",BAD_FILE_PATH:"Filepath must be valid, and contain the name of the tarball you wish to write",NOT_ENABLED:"Custom functions is not enabled, to enable set fastifyRoutes enabled to true in hdb/harperdb-config.yaml file.",BAD_SSH_KEY_NAME:"SSH key name can only contain alphanumeric, dash and underscore characters"},bJ={CLUSTERING_NOT_ENABLED:"Clustering must be enabled to perform this operation."},OJ={...nD,...mJ,..._J,...gJ,...SJ,...TJ,...AJ,...RJ,...EJ,...sD,...iD,...yJ,...bJ,...hJ};oD.exports={CHECK_LOGS_WRAPPER:tD,HDB_ERROR_MSGS:OJ,DEFAULT_ERROR_MSGS:rD,DEFAULT_ERROR_RESP:fJ,HTTP_STATUS_CODES:eD,LMDB_ERRORS_ENUM:pJ,AUTHENTICATION_ERROR_MSGS:nD,VALIDATION_ERROR_MSGS:sD,ITC_ERRORS:iD}});var me=P((MRe,lD)=>{"use strict";var $l=Dn(),NJ=z(),wJ=(B(),D(q)),km=class extends Error{static{a(this,"HdbError")}constructor(t,r,n,s,i){super(),Error.captureStackTrace(this,aD),this.statusCode=n||$l.HTTP_STATUS_CODES.INTERNAL_SERVER_ERROR,this.http_resp_msg=r||($l.DEFAULT_ERROR_MSGS[n]?$l.DEFAULT_ERROR_MSGS[n]:$l.DEFAULT_ERROR_MSGS[$l.HTTP_STATUS_CODES.INTERNAL_SERVER_ERROR]),this.message=t.message?t.message:this.http_resp_msg,this.type=t.name,s&&(this.logLevel=s),typeof this.message!="string"&&(this.stack=t.stack),i&&NJ[s](i)}},bA=class extends Error{static{a(this,"ClientError")}constructor(t,r){if(t instanceof Error)return t.statusCode=r||400,t;super(t),this.statusCode=r||400}},OA=class extends Error{static{a(this,"ServerError")}constructor(t,r){super(t),this.statusCode=r||500}};function aD(e,t,r,n=wJ.LOG_LEVELS.ERROR,s=null,i=!1){if(cD(e))return e;let o=new km(e,t,r,n,s);return i&&delete o.stack,o}a(aD,"handleHDBError");function cD(e){return e.__proto__.constructor.name===km.name}a(cD,"isHDBError");lD.exports={isHDBError:cD,handleHDBError:aD,ClientError:bA,ServerError:OA,hdb_errors:$l}});var Et=P((URe,pD)=>{"use strict";var af=(B(),D(q)),IJ=oe(),cn=le(),cf=require("path"),CJ=require("minimist"),uD=require("fs-extra"),dD=require("lodash");cn.initSync();var{CONFIG_PARAMS:zo,DATABASES_PARAM_CONFIG:rf,SYSTEM_SCHEMA_NAME:Fm}=af,nf,sf,of;function fD(){if(nf!==void 0)return nf;if(cn.getHdbBasePath()!==void 0)return nf=cn.get(zo.STORAGE_PATH)||cf.join(cn.getHdbBasePath(),af.DATABASES_DIR_NAME),nf}a(fD,"getBaseSchemaPath");function _D(){if(sf!==void 0)return sf;if(cn.getHdbBasePath()!==void 0)return sf=mD(Fm),sf}a(_D,"getSystemSchemaPath");function hD(){if(of!==void 0)return of;if(cn.getHdbBasePath()!==void 0)return of=cn.get(af.CONFIG_PARAMS.STORAGE_AUDIT_PATH)||cf.join(cn.getHdbBasePath(),af.TRANSACTIONS_DIR_NAME),of}a(hD,"getTransactionAuditStoreBasePath");function PJ(e,t){let r=cn.get(zo.DATABASES)?.[e];return t&&r?.tables?.[t]?.auditPath||r?.auditPath||cf.join(hD(),e.toString())}a(PJ,"getTransactionAuditStorePath");function mD(e,t){e=e.toString(),t=t&&t.toString();let r=cn.get(af.CONFIG_PARAMS.DATABASES)?.[e];return t&&r?.tables?.[t]?.path||r?.path||cf.join(fD(),e)}a(mD,"getSchemaPath");function DJ(e,t){e=e.toString(),t=t.toString();let r=process.env;Object.assign(r,CJ(process.argv));let n=r[zo.DATABASES.toUpperCase()];if(n){let i;try{i=JSON.parse(n)}catch(o){if(!IJ.isObject(n))throw o;i=n}for(let o of i){let c=o[Fm];if(!c)continue;let l=cn.get(zo.DATABASES);l=l??{};let u=c?.tables?.[t]?.[rf.PATH];if(u)return dD.set(l,[Fm,rf.TABLES,t,rf.PATH],u),cn.setProperty(zo.DATABASES,l),u;let f=c?.[rf.PATH];if(f)return dD.set(l,[Fm,rf.PATH],f),cn.setProperty(zo.DATABASES,l),f}}let s=r[zo.STORAGE_PATH.toUpperCase()];if(s){if(!uD.pathExistsSync(s))throw new Error(s+" does not exist");let i=cf.join(s,e);return uD.mkdirsSync(i),cn.setProperty(zo.STORAGE_PATH,s),i}return _D()}a(DJ,"initSystemSchemaPaths");function LJ(){nf=void 0,sf=void 0,of=void 0}a(LJ,"resetPaths");pD.exports={getBaseSchemaPath:fD,getSystemSchemaPath:_D,getTransactionAuditStorePath:PJ,getTransactionAuditStoreBasePath:hD,getSchemaPath:mD,initSystemSchemaPaths:DJ,resetPaths:LJ}});var ln=P((kRe,AD)=>{"use strict";var MJ=Dn().LMDB_ERRORS_ENUM,BRe=require("lmdb"),vJ=vt(),HRe=require("buffer").Buffer,{OVERFLOW_MARKER:ED,MAX_SEARCH_KEY_LENGTH:qm}=vJ,gD=["number","string","symbol","boolean","bigint"];function UJ(e){if(e=e?.primaryStore||e,!e)throw new Error(MJ.ENV_REQUIRED)}a(UJ,"validateEnv");function xJ(e){if(e==null)return null;let t;try{t=typeof e=="object"?JSON.stringify(e):e.toString()}catch{t=e.toString()}return t}a(xJ,"stringifyData");function BJ(e){return e instanceof Date?e.valueOf():e}a(BJ,"convertKeyValueToWrite");function HJ(e,t){if(e===null)return t?[null]:void 0;if(e===void 0)return;if(gD.includes(typeof e))return e.length>qm?[e.slice(0,qm)+ED]:[e];let r;if(Array.isArray(e)){r=[];for(let n=0,s=e.length;n<s;n++){let i=e[n];if(gD.includes(typeof i))i.length>qm?r.push(i.slice(0,qm)+ED):r.push(i);else{if(i===null&&t)return r.push(null);if(i instanceof Date)return r.push(i.getTime())}}}else if(e instanceof Date)return[e.getTime()];return r}a(HJ,"getIndexedValues");var Gm=0,SD=0;function TD(){SD=Date.now()-performance.now()}a(TD,"adjustStartTime");TD();var kJ=6e4;setInterval(TD,kJ).unref();function FJ(){let e=performance.now()+SD;return e>Gm?(Gm=e,e):(Gm+=488e-6,Gm)}a(FJ,"getNextMonotonicTime");AD.exports={validateEnv:UJ,stringifyData:xJ,convertKeyValueToWrite:BJ,getNextMonotonicTime:FJ,getIndexedValues:HJ}});var lf=P((qRe,RD)=>{"use strict";var qJ=(B(),D(q)).OPERATIONS_ENUM,NA=class{static{a(this,"InsertObject")}constructor(t,r,n,s,i=void 0){this.operation=qJ.INSERT,this.schema=t,this.table=r,this.hash_attribute=n,this.records=s,this.__origin=i}};RD.exports=NA});var uf=P((VRe,ND)=>{"use strict";var $Re=lf(),$m=(B(),D(q)),wA=oe(),yD=z(),GJ=require("uuid"),{handleHDBError:Vm,hdb_errors:$J}=me(),{HDB_ERROR_MSGS:Km,HTTP_STATUS_CODES:Ym}=$J;ND.exports=bD;function bD(e,t,r){for(let s=0;s<t.length;s++)OD(t[s]);let{records:n}=e;for(let s=0;s<n.length;s++){let i=n[s];VJ(i,r,e.operation)}}a(bD,"processRows");bD.validateAttribute=OD;function OD(e){if(Buffer.byteLength(String(e))>$m.INSERT_MAX_CHARACTER_SIZE)throw Vm(new Error,Km.ATTR_NAME_LENGTH_ERR(e),Ym.BAD_REQUEST,void 0,void 0,!0);if(wA.isEmptyOrZeroLength(e)||wA.isEmpty(e.trim()))throw Vm(new Error,Km.ATTR_NAME_NULLISH_ERR,Ym.BAD_REQUEST,void 0,void 0,!0)}a(OD,"validateAttribute");function VJ(e,t,r){if(!e.hasOwnProperty(t)||wA.isEmptyOrZeroLength(e[t])){if(r===$m.OPERATIONS_ENUM.INSERT||r===$m.OPERATIONS_ENUM.UPSERT){e[t]=GJ.v4();return}throw yD.error("Update transaction aborted due to record with no hash value:",e),Vm(new Error,Km.RECORD_MISSING_HASH_ERR,Ym.BAD_REQUEST,void 0,void 0,!0)}if(Buffer.byteLength(String(e[t]))>$m.INSERT_MAX_CHARACTER_SIZE)throw yD.error(e),Vm(new Error,Km.HASH_VAL_LENGTH_ERR,Ym.BAD_REQUEST,void 0,void 0,!0)}a(VJ,"validateHash")});var wD,Ln,IA,Vl=be(()=>{wD=require("events"),Ln=class extends wD.EventEmitter{static{a(this,"IterableEventQueue")}resolveNext;queue;hasDataListeners;drainCloseListener;currentDrainResolver;[Symbol.asyncIterator](){let t=new IA;return t.queue=this,t}push(t){this.send(t)}send(t){this.resolveNext?(this.resolveNext({value:t}),this.resolveNext=null):this.hasDataListeners?this.emit("data",t):(this.queue||(this.queue=[]),this.queue.push(t))}getNextMessage(){let t=this.queue?.shift();return t||this.emit("drained"),t}waitForDrain(){return new Promise(t=>{!this.queue||this.queue.length===0?t(!0):(this.once("drained",()=>t(!0)),this.currentDrainResolver=t,this.drainCloseListener||(this.drainCloseListener=!0,this.on("close",()=>{this.currentDrainResolver?.(!1)})))})}on(t,r){if(t==="data"&&!this.hasDataListeners)for(this.hasDataListeners=!0;this.queue?.length>0;)r(this.queue.shift());return super.on(t,r)}},IA=class{static{a(this,"EventQueueIterator")}queue;push(t){this.queue.send(t)}next(){let t=this.queue.getNextMessage();return t?{value:t}:new Promise(r=>this.queue.resolveNext=r)}return(t){return this.queue.emit("close"),{value:t,done:!0}}throw(t){return this.queue.emit("close",t),{done:!0}}}});function vD(e){PA=e}function zJ(){WJ=setInterval(function(){for(let e of CA)if(e.stale){let t=e.getContext()?.url;DD.error(`Transaction was open too long and has been aborted, from table: ${e.lmdbDb?.name+(t?" path: "+t:"")}`),e.abort()}else e.stale=!0},YJ).unref()}var DA,PD,DD,LD,MD,ID,CA,KJ,df,CD,PA,oc,Wm,YJ,WJ,zm=be(()=>{DA=M(ln()),PD=M(me()),DD=M(z()),LD=M(le());B();MD=M(oe()),ID=100,CA=new Set,KJ=(0,MD.convertToMS)(LD.get(U.STORAGE_MAXTRANSACTIONQUEUETIME))||45e3;a(vD,"replicationConfirmation");oc=class e{static{a(this,"DatabaseTransaction")}#e;writes=[];lmdbDb;readTxn;readTxnRefCount;readTxnsUsed;validated=0;timestamp=0;overloadChecked;open=1;getReadTxn(){if(this.readTxnRefCount=(this.readTxnRefCount||0)+1,this.stale&&(this.stale=!1),this.readTxn)return this.readTxn.openTimer&&(this.readTxn.openTimer=0),this.readTxn;if(this.open===1)return this.readTxn=this.lmdbDb.useReadTransaction(),this.readTxnsUsed=1,this.readTxn.openTimer&&(this.readTxn.openTimer=0),CA.add(this),this.readTxn}useReadTxn(){return this.getReadTxn(),this.readTxn?.use(),this.readTxnsUsed++,this.readTxn}doneReadTxn(){this.readTxn&&(this.readTxn.done(),--this.readTxnsUsed===0&&(CA.delete(this),this.readTxn=null))}disregardReadTxn(){--this.readTxnRefCount===0&&this.readTxnsUsed===1&&this.doneReadTxn()}checkOverloaded(){if(df&&!this.overloadChecked&&performance.now()-CD>KJ)throw new PD.ServerError("Outstanding write transactions have too long of queue, please try again later",503);this.overloadChecked=!0}addWrite(t){if(this.open===0)throw new Error("Can not use a transaction that is no longer open");if(this.open===2){let r=new e;return r.addWrite(t),r.commit({})}else this.writes.push(t)}removeWrite(t){let r=this.writes.indexOf(t);r>-1&&(this.writes[r]=null)}commit(t={}){let r=this.timestamp;r||(r=this.timestamp=t.timestamp||(0,DA.getNextMonotonicTime)()),t.timestamp||(t.timestamp=r);let n=t.retries||0;if(this.validated<this.writes.length)try{let d=this.validated;this.validated=this.writes.length;for(let h=d;h<this.validated;h++)this.writes[h]?.validate?.(this.timestamp);let _;for(let h=d;h<this.validated;h++){let m=this.writes[h];m&&(m.before||m.beforeIntermediate)&&(_=!0)}if(_)return(async()=>{try{for(let h=0;h<2;h++){let m;for(let S=d;S<this.validated;S++){let g=this.writes[S];if(!g)continue;let A=g[h===0?"before":"beforeIntermediate"];if(A){let E=A();m?m.push?m.push(E):m=[m,E]:m=E}}m&&await(m.push?Promise.all(m):m)}}catch(h){throw this.abort(),h}return this.commit(t)})()}catch(d){throw this.abort(),d}n||this.doneReadTxn(),this.open=t?.doneWriting?2:1;let s,i=[],o=0;this.writes=this.writes.filter(d=>d);let c=a(d=>{d.commit(r,d.entry,n)},"doWrite"),l=a(()=>{let d=this.writes[o++];if(d)if(d.key){n>0&&(d.entry=d.store.getEntry(d.key));let _=d.store.ifVersion(d.key,d.entry?.version??null,l);s=s||_}else l();else for(let _ of this.writes)c(_)},"nextCondition"),u=this.lmdbDb;if(this.writes.length>0&&(u?.retryRisk&&(u.retryRisk*=.99),this.writes.length+(u?.retryRisk||0)<ID>>n?l():s=this.writes[0].store.transaction(()=>{for(let d of this.writes)d.entry=d.store.getEntry(d.key),c(d);return!0})),s)return df||(df=s,CD=performance.now(),df.then(()=>{df=null})),s.then(d=>{if(d){if(this.next&&i.push(this.next.commit(t)),t?.flush&&i.push(this.writes[0].store.flushed),this.replicatedConfirmation){let _=this.writes[0].store.rootStore.databaseName,h=this.writes[this.writes.length-1];PA&&h&&i.push(PA(_,h.store.getEntry(h.key).localTime,this.replicatedConfirmation))}return this.writes=[],this.next=null,Promise.all(i).then(()=>({txnTime:r}))}else return u&&(u.retryRisk=(u.retryRisk||0)+ID/2),t?t.retries=n+1:t={retries:1},this.commit(t)});let f={txnTime:r};if(this.next){let d=this.next?.commit(t);if(d?.then)return d?.then(_=>({txnTime:r,next:_}));f.next=d}return f}abort(){for(;this.readTxnsUsed>0;)this.doneReadTxn();this.open=0,this.writes=[]}getContext(){return this.#e}setContext(t){this.#e=t}},Wm=class extends oc{static{a(this,"ImmediateTransaction")}_timestamp;addWrite(t){super.addWrite(t),this.commit()}get timestamp(){return this._timestamp||(this._timestamp=(0,DA.getNextMonotonicTime)())}getReadTxn(){}},YJ=3e4;a(zJ,"startMonitoringTxns");zJ()});function bt(e,t,r){if(!t)t=e,e={};else if(!e)e={};else if(e?.transaction?.open===1&&typeof t=="function")return t(e.transaction);if(typeof t!="function")throw new Error("Callback function must be provided to transaction");let n=e.transaction=new oc;e.timestamp&&(n.timestamp=e.timestamp),e.replicatedConfirmation&&(n.replicatedConfirmation=e.replicatedConfirmation),n.setContext(e),e.resourceCache||(e.resourceCache=[]);let s;try{if(s=t(n),s?.then)return s.then(i,o)}catch(c){o(c)}return i(s);function i(c){let l=n.commit({doneWriting:!0});return l.then?l.then(()=>c):c}function o(c){throw n.abort({}),c}}var UD,ac=be(()=>{UD=M(ci());zm();a(bt,"transaction");(0,UD._assignPackageExport)("transaction",bt);bt.commit=function(e){let t=(e.getContext?.()||e)?.transaction;if(!t)throw new Error("No active transaction is available to commit");return t.commit()};bt.abort=function(e){let t=(e.getContext?.()||e)?.transaction;if(!t)throw new Error("No active transaction is available to abort");return t.abort()}});function MA(e,t,r,n,s,i,o,c){let l=e[0];if(t==="or"){let d=u(l);for(let h=1;h<e.length;h++){let m=e[h],S=u(m);d=d.concat(S)}let _=new Set;return d.filter(h=>{let m=h.key??h;return _.has(m)?!1:(_.add(m),!0)})}else{let d=u(l),_=f(e.slice(1),!0,l.estimated_count);return _.length>0?o(d,_):d}function u(d){return d.conditions?MA(d.conditions,d.operator,r,n,s,i,o,c):Wl(d,n,d.descending||s.reverse===!0,r,s.allowFullScan,c)}a(u,"executeCondition");function f(d,_,h){return d.map((m,S)=>{if(m.conditions){let E=m.operator==="or",T=f(m.conditions,!E,h);return E?(w,v)=>T.some(k=>k(w,v)):(w,v)=>T.every(k=>k(w,v))}let g=(m.attribute||m[0])===r.primaryKey,A=hf(m,r,i,c,g,h);return _&&S<d.length-1&&h&&(h=n4(r.primaryStore,m.estimated_count,h)),A}).filter(Boolean)}a(f,"mapConditionsToFilters")}function Wl(e,t,r,n,s,i){let o=e[0]??e.attribute,c=e[1]??e.value,l=e.comparator;if(c===void 0&&l!=="sort")throw new dn.ClientError(`Search condition for ${o} must have a value`);if(Array.isArray(o)){let E=o[0],T=fi(n.attributes,E);if(T.relationship){if(o.length<2)throw new dn.ClientError("Can not directly query a relational attribute, must query an attribute within the target table");let w=T.definition?.tableClass||T.elements?.definition?.tableClass,v=new Map,k=Wl({attribute:o.length>2?o.slice(1):o[1],value:c,comparator:l},t,r,w,s,v);if(T.relationship.to){i[o[0]]=v;let $=!!fi(w.attributes,T.relationship.to)?.elements;k=ZJ(k,T,w.primaryStore,$,v)}if(T.relationship.from){let $=a(W=>(W?.key!==void 0&&(W=W.key),Wl({attribute:T.relationship.from,value:W},t,r,n,s,v)),"searchEntry");T.elements?(i[o[0]]=v,k=e4(k,T,w.primaryStore,v,$)):k=k.flatMap($)}return k}else if(o.length===1)o=o[0];else throw new dn.ClientError("Unable to query by attribute "+JSON.stringify(o))}let u,f,d,_;c instanceof Date&&(c=c.getTime());let h;switch(vA[l]||l){case"lt":u=!0,f=c;break;case"le":u=!0,f=c,d=!0;break;case"gt":u=c,_=!0;break;case"ge":u=c;break;case"prefix":Array.isArray(c)?c[c.length-1]!=null&&(c=c.concat(null)):c=[c,null],u=c,f=c.slice(0),f[f.length-1]=di.MAXIMUM_KEY;break;case"starts_with":u=c.toString(),f=c+"\uFFFF";break;case"between":case"gele":case"gelt":case"gtlt":case"gtle":u=c[0],u instanceof Date&&(u=u.getTime()),f=c[1],f instanceof Date&&(f=f.getTime()),d=l==="gele"||l==="gtle"||l==="between",_=l==="gtlt"||l==="gtle";break;case"equals":case void 0:u=c,f=c,d=!0;break;case"ne":if(c===null){u=c,_=!0;break}case"sort":case"contains":case"ends_with":u=!0,h=!0;break;default:throw new dn.ClientError(`Unknown query comparator "${l}"`)}let m,S=o===n.primaryKey||o==null;if(typeof u=="string"&&u.length>as.MAX_SEARCH_KEY_LENGTH&&(u=u.slice(0,as.MAX_SEARCH_KEY_LENGTH)+as.OVERFLOW_MARKER,_=!1,m=hf(e,n,null,i,S)),typeof f=="string"&&f.length>as.MAX_SEARCH_KEY_LENGTH&&(f=f.slice(0,as.MAX_SEARCH_KEY_LENGTH)+as.OVERFLOW_MARKER,d=!0,m=m??hf(e,n,null,i,S)),r){let E=u;u=f,f=E,E=!_,_=!d,d=E}let g=S?n.primaryStore:n.indices[o];if(!g||g.isIndexing||h||c===null&&!g.indexNulls){if(s===!1&&!g)throw new dn.ClientError(`"${o}" is not indexed, can not search for this attribute`,404);if(s===!1&&h)throw new dn.ClientError(`Can not use ${l||"equal"} operator without combining with a condition that uses an index, can not search for attribute ${o}`,403);if(g?.isIndexing)throw new dn.ServerError(`"${o}" is not indexed yet, can not search for this attribute`,503);if(c===null&&g&&!g.indexNulls)throw new dn.ClientError(`"${o}" is not indexed for nulls, index needs to be rebuilt to search for nulls, can not search for this attribute`,400);if(m=m??hf(e,n,null,i,S),!m)throw new dn.ClientError(`Unknown search operator ${e.comparator}`)}let A={start:u,end:f,inclusiveEnd:d,exclusiveStart:_,values:!0,versions:S,transaction:t,reverse:r};if(S){let E=g.getRange(A).map(m?function({key:T,value:w}){return this?.isSync?w&&m(w)?T:jo.SKIP:new Promise((v,k)=>setImmediate(()=>{try{v(w&&m(w)?T:jo.SKIP)}catch($){k($)}}))}:T=>T.value==null&&!(T.metadataFlags&(fn|Jo))?jo.SKIP:T);return E.hasEntries=!0,E}else return g?g.getRange(A).map(m?function({key:E,value:T}){let w;return typeof E=="string"&&E.length>as.MAX_SEARCH_KEY_LENGTH?w=n.primaryStore.get(T):w={[o]:E},this.isSync?m(w)?T:jo.SKIP:new Promise((v,k)=>setImmediate(()=>{try{v(m(w)?T:jo.SKIP)}catch($){k($)}}))}:({value:E})=>E):n.primaryStore.getRange(r?{end:!0,transaction:t,reverse:!0}:{start:!0,transaction:t}).map(function({key:E,value:T}){return this.isSync?T&&m(T)?E:jo.SKIP:new Promise((w,v)=>setImmediate(()=>{try{w(T&&m(T)?E:jo.SKIP)}catch(k){v(k)}}))})}function fi(e,t){if(Array.isArray(t))if(t.length>1){let r=fi(e,t[0]),n=(r?.definition?.tableClass||r?.elements?.definition?.tableClass)?.attributes??r?.properties;return n?fi(n,t.slice(1)):void 0}else t=t.toString();else typeof t!="string"&&(t=t.toString());return e.find(r=>r.name===t)}function ZJ(e,t,r,n,s){return new e.constructor({[Symbol.iterator](){let i;return s.hasMappings=!0,{next(){if(!i){let c=t.relationship.to,l=a((u,f)=>{let d=s.get(u);d?d.push(f):s.set(u,d=[f])},"add_entry");for(let u of e){let f=u.value??r.get(u.key??u),d=f?.[c];if(d!=null&&!s.filters?.some(_=>!_(f)))if(n)for(let _=0;_<d.length;_++)l(d[_],u);else l(d,u)}return i=s.keys()[Symbol.iterator](),this.next()}let o=i.next();return o.done?o:{value:o.value}},return(){if(i?.return)return i.return()}}}})}function e4(e,t,r,n,s){return new e.constructor({[Symbol.iterator](){let i,o,c=new Set;return{next(){let l;if(o)for(;l=o.next(),!l.done;){let u=l.value;if(!c.has(u))return c.add(u),l}if(!i){let u=new Set;n.fromRecord=f=>f[t.relationship.from]?.filter?.(d=>u.has(d));for(let f of e){if(n.filters){let d=r.get(f);if(n.filters.some(_=>!_(d)))continue}u.add(f)}return i=u[Symbol.iterator](),this.next()}do{let u=i.next();return u.done?u:(o=s(u.value)[Symbol.iterator](),this.next())}while(!0)},return(){return o?.return?.()},throw(){return o?.throw?.()}}}})}function hf(e,t,r,n,s,i){let o=e.comparator,c=e[0]??e.attribute,l=e[1]??e.value;if(Array.isArray(c)){if(c.length===0)return()=>!0;if(c.length===1)c=c[0];else if(c.length>1){let f=c[0],d=fi(t.attributes,f),_=d.definition?.tableClass||d.elements.definition?.tableClass,h=n?.[f],m=hf({attribute:c.length>2?c.slice(1):c[1],value:l,comparator:o},_,r,h?.[f]?.joined,c[1]===_.primaryKey,i);if(!m)return;if(h){h.filters||(h.filters=[]),h.filters.push(m);return}let S=t.propertyResolvers?.[f],g,A=a((E,T)=>{let w,v;if(S){if(S.from&&m.idFilter){if(!g)if(m.idFilter.idSet?.size===1){for(let $ of m.idFilter.idSet)e={attribute:S.from,value:$};g=u(S.from,m.idFilter,!0,!0)}else g=u(S.from,m.idFilter,!1,!0);let k=g(E);return g.idFilter&&(A.idFilter=g.idFilter),k}v=S(E,r,T),w=v?.value}else w=E[f];return w?Array.isArray(w)?w.some(m):m(w,v):!1},"recordFilter");return A}}switch(l instanceof Date&&(l=l.getTime()),vA[o]||o){case as.SEARCH_TYPES.EQUALS:case void 0:return u(c,f=>f===l,!0);case"contains":return u(c,f=>f?.toString().includes(l));case"ends_with":return u(c,f=>f?.toString().endsWith(l));case"starts_with":return u(c,f=>typeof f=="string"&&f.startsWith(l),!0);case"prefix":return Array.isArray(l)?l[l.length-1]==null&&(l=l.slice(0,-1)):l=[l],u(c,f=>{if(!Array.isArray(f))return!1;for(let d=0,_=l.length;d<_;d++)if(f[d]!==l[d])return!1;return!0},!0);case"between":return l[0]instanceof Date&&(l[0]=l[0].getTime()),l[1]instanceof Date&&(l[1]=l[1].getTime()),u(c,f=>(0,di.compareKeys)(f,l[0])>=0&&(0,di.compareKeys)(f,l[1])<=0,!0);case"gt":return u(c,f=>(0,di.compareKeys)(f,l)>0);case"ge":return u(c,f=>(0,di.compareKeys)(f,l)>=0);case"lt":return u(c,f=>(0,di.compareKeys)(f,l)<0);case"le":return u(c,f=>(0,di.compareKeys)(f,l)<=0);case"ne":return u(c,f=>(0,di.compareKeys)(f,l)!==0,!1,!0);case"sort":return()=>!0;default:throw new dn.ClientError(`Unknown query comparator "${o}"`)}function u(f,d,_,h){let m;_=_&&!s&&t?.indices[f]&&i>3,_&&(e.estimated_count==null&&Qm(t)(e),m=e.estimated_count>>4,(isNaN(m)||m>=i)&&(_=!1));let S=0,g=3;function A(E){let T=E[f],w;if(typeof T!="object"||!T||h?w=d(T):Array.isArray(T)?w=T.some(d):T instanceof Date&&(w=d(T.getTime())),_&&(g++,!w&&!A.idFilter&&++S/g*(i-g)>m)){let v=Wl(e,r.transaction.getReadTxn(),!1,t).map(zl),k=new Set(v);A.idFilter=$=>k.has(zl($)),A.idFilter.idSet=k}return w}return a(A,"recordFilter"),s&&(A.idFilter=d),A}a(u,"attributeComparator")}function Qm(e){function t(r){if(r.estimated_count===void 0){if(r.conditions){let s;if(r.operator==="or"){s=0;for(let i of r.conditions)t(i),s+=i.estimated_count}else{s=1/0;for(let i of r.conditions)t(i),s=isFinite(s)?s*i.estimated_count/zi(e.primaryStore):i.estimated_count}return r.estimated_count=s,r.estimated_count}let n=r.comparator||r.search_type;if(n=vA[n]||n,n===as.SEARCH_TYPES.EQUALS||!n){let s=r[0]??r.attribute;if(s==null||s===e.primaryKey)r.estimated_count=1;else if(Array.isArray(s)&&s.length>1){let i=fi(e.attributes,s[0]),o=i.definition?.tableClass||i.elements.definition?.tableClass,c=Qm(o)({value:r.value,attribute:s.length>2?s.slice(1):s[1],comparator:"equals"}),l=e.indices[i.relationship.from];r.estimated_count=c+(l?c*zi(e.indices[i.relationship.from])/(zi(o.primaryStore)||1):c)}else{let i=e.indices[s];r.estimated_count=i?i.getValuesCount(r[1]??r.value):1/0}}else if(n==="contains"||n==="ends_with"||n==="ne"){let s=r[0]??r.attribute,i=e.indices[s];r.value===null&&n==="ne"?r.estimated_count=zi(e.primaryStore)-(i?i.getValuesCount(null):0):r.estimated_count=1/0}else n==="starts_with"||n==="prefix"?r.estimated_count=JJ*zi(e.primaryStore)+1:n==="between"?r.estimated_count=QJ*zi(e.primaryStore)+1:n==="sort"?r.estimated_count=zi(e.primaryStore)+1:r.estimated_count=jJ*zi(e.primaryStore)+1;typeof r.descending=="boolean"&&(r.estimated_count/=2)}return r.estimated_count}return a(t,"estimateConditionForTable"),t}function Jm(e){if(e)if(Qo=e,Kl.lastIndex=0,t4.test(e))try{let t=ff(new Yl,"");if(un!==Qo.length)throw new SyntaxError("Unable to parse query, unexpected end of query");return t}catch(t){throw t.statusCode=400,t.message=`Unable to parse query, ${t.message} at position ${un} in '${Qo}'`,t}else return new URLSearchParams(e)}function ff(e,t){let r=Kl,n,s,i,o,c,l=decodeURIComponent,u;for(;n=r.exec(Qo);){un=r.lastIndex;let[,f,d]=n;if(o){if(f)throw new SyntaxError(`expected operator, but encountered '${f}'`);o=!1,c=!1}else c=!0;let _;switch(d){case"=":if(s!=null){if(f.length<=2)i=f;else throw new SyntaxError(`invalid FIQL operator ${f}`);l=xD}else{if(l=decodeURIComponent,i="equals",!f)throw new SyntaxError("attribute must be specified before equality comparator");s=_f(f)}break;case"==":case"!=":case"<":case"<=":case">":case">=":case"===":case"!==":if(i=XJ[d],l=LA[i]?xD:decodeURIComponent,!f)throw new SyntaxError(`attribute must be specified before comparator ${d}`);s=_f(f);break;case"&=":case"|=":case"|":case"&":case"":case void 0:if(s==null){if(s===void 0)throw t?new SyntaxError(`expected '${t}', but encountered ${d[0]?"'"+d[0]+"'":"end of string"}}`):new SyntaxError(`no comparison specified before ${d?"'"+d+"'":"end of string"}`)}else{if(!e.conditions)throw new SyntaxError("conditions/comparisons are not allowed in a property list");let m={comparator:i,attribute:s||null,value:l(f)};if(i==="eq"&&BD(m,f),s===""){let S=e.conditions[e.conditions.length-1];S.chainedConditions=S.chainedConditions||[],S.chainedConditions.push(m),S.operator=u}else jm(e,u),e.conditions.push(m)}d==="&"?(u="and",s=void 0):d==="|"?(u="or",s=void 0):d==="&="?(u="and",s=""):d==="|="&&(u="or",s="");break;case",":if(e.conditions)throw new SyntaxError("conditions/comparisons are not allowed in a property list");e.push(_f(f)),s=void 0;break;case"(":Kl.lastIndex=un;let h=ff(f?[]:new Yl,")");switch(f){case"":jm(e,u),e.conditions.push(h);break;case"limit":switch(h.length){case 1:e.limit=+h[0];break;case 2:e.offset=+h[0],e.limit=h[1]-e.offset;break;default:throw new SyntaxError("limit must have 1 or 2 arguments")}break;case"select":Array.isArray(h[0])&&h.length===1&&!h[0].name?(e.select=h[0],e.select.asArray=!0):h.length===1?e.select=h[0]:h.length===2&&h[1]===""?e.select=h.slice(0,1):e.select=h;break;case"group-by":throw new SyntaxError("group by is not implemented yet");case"sort":e.sort=HD(h);break;default:throw new SyntaxError(`unknown query function call ${f}`)}Qo[un]===","?r.lastIndex=++un:o=!0,s=null;break;case"{":if(e.conditions)throw new SyntaxError("property sets are not allowed in a queries");if(!f)throw new SyntaxError("property sets must have a defined parent property name");Kl.lastIndex=un,_=ff([],"}"),_.name=f,e.push(_),Qo[un]===","?r.lastIndex=++un:o=!0;break;case"[":Kl.lastIndex=un,f?(_=ff(new Yl,"]"),_.name=f):_=ff(e.conditions?new Yl:[],"]"),e.conditions?(jm(e,u),e.conditions.push(_),s=null):e.push(_),Qo[un]===","?r.lastIndex=++un:o=!0;break;case")":case"]":case"}":if(t===d[0]){if(e.conditions){if(s){let m={comparator:i||"equals",attribute:s,value:l(f)};i==="eq"&&BD(m,f),jm(e,u),e.conditions.push(m)}else if(f)throw new SyntaxError("no attribute or comparison specified")}else(f||e.length>0&&c)&&e.push(_f(f));return e}else throw t?new SyntaxError(`expected '${t}', but encountered '${d[0]}'`):new SyntaxError(`unexpected token '${d[0]}'`);default:throw new SyntaxError(`unexpected operator '${d}'`)}if(t!==")"&&(r=s?r4:Kl,r.lastIndex=un),un===Qo.length)return e}if(t)throw new SyntaxError(`expected '${t}', but encountered end of string`)}function jm(e,t){if(e.conditions.length>0)if(e.operator){if(e.operator!==t)throw new SyntaxError("Can not mix operators within a condition grouping")}else e.operator=t}function _f(e){return e.indexOf(".")>-1?e.split(".").map(_f):decodeURIComponent(e)}function xD(e){if(e==="null")return null;if(e.indexOf(":")>-1){let[t,r]=e.split(":");if(t==="number")return r[0]==="$"?parseInt(r.slice(1),36):+r;if(t==="boolean")return r==="true";if(t==="date")return new Date(isNaN(r)?decodeURIComponent(r):+r);if(t==="string")return decodeURIComponent(r);throw new dn.ClientError(`Unknown type ${t}`)}return decodeURIComponent(e)}function BD(e,t){if(t.indexOf("*")>-1)if(t.endsWith("*"))e.comparator="starts_with",e.value=decodeURIComponent(t.slice(0,-1));else throw new dn.ClientError("wildcard can only be used at the end of a string")}function HD(e){let t=kD(e[0]);return e.length>1&&(t.next=HD(e.slice(1))),t}function kD(e){if(Array.isArray(e)){let t=kD(e[0]);return e[0]=t.attribute,t.attribute=e,t}if(typeof e=="string")switch(e[0]){case"-":return{attribute:e.slice(1),descending:!0};case"+":return{attribute:e.slice(1),descending:!1};default:return{attribute:e,descending:!1}}throw new SyntaxError(`Unknown sort type ${e}`)}function zl(e){return Array.isArray(e)?e.join("\0"):e}function zi(e){let t=Date.now();return(e.estimatedEntryCountExpires||0)<t&&(e.estimatedEntryCount=e.getStats().entryCount,e.estimatedEntryCountExpires=t+1e4),e.estimatedEntryCount}function n4(e,t,r){return t*r/zi(e)}var dn,as,di,jo,jJ,QJ,JJ,XJ,LA,vA,t4,Kl,r4,un,Qo,Yl,cc,mf=be(()=>{dn=M(me()),as=M(vt()),di=require("ordered-binary"),jo=require("lmdb");pf();jJ=.3,QJ=.1,JJ=.05,XJ={"<":"lt","<=":"le",">":"gt",">=":"ge","!=":"ne","==":"eq","===":"equals","!==":"not_equal"},LA={lt:!0,le:!0,gt:!0,ge:!0,ne:!0,eq:!0};a(MA,"executeConditions");a(Wl,"searchByIndex");a(fi,"findAttribute");a(ZJ,"joinTo");a(e4,"joinFrom");vA={eq:"equals",greater_than:"gt",greaterThan:"gt",greater_than_equal:"ge",greaterThanEqual:"ge",less_than:"lt",lessThan:"lt",less_than_equal:"le",lessThanEqual:"le",not_equal:"ne",notEqual:"ne",equal:"equals",sw:"starts_with",startsWith:"starts_with",ew:"ends_with",endsWith:"ends_with",ct:"contains",">":"gt",">=":"ge","<":"lt","<=":"le","...":"between"};a(hf,"filterByType");a(Qm,"estimateCondition");t4=/[()[\]|!<>.]|(=\w*=)/,Kl=/([^?&|=<>!([{}\]),]*)([([{}\])|,&]|[=<>!]*)/g,r4=/([^&|=[\]{}]+)([[\]{}]|[&|=]*)/g;a(Jm,"parseQuery");a(ff,"parseBlock");a(jm,"assignOperator");a(_f,"decodeProperty");a(xD,"typedDecoding");a(BD,"wildcardDecoding");a(HD,"toSortObject");a(kD,"toSortEntry");Yl=class{static{a(this,"Query")}constructor(){this.conditions=[]}[Symbol.iterator](){return this.conditions[Symbol.iterator]()}get(t){for(let r=0;r<this.conditions.length;r++){let n=this.conditions[r];if(n.attribute===t)return n.value}}};a(zl,"flattenKey");a(zi,"estimatedEntryCount");a(n4,"intersectionEstimate");cc=class{constructor(t){this.url=t}static{a(this,"SimpleURLQuery")}get(){}[Symbol.iterator](){return[][Symbol.iterator]()}}});var xA={};Ue(xA,{MultiPartId:()=>Zm,Resource:()=>$r,snake_case:()=>i4,transformForSelect:()=>ep});function i4(e){return e[0].toLowerCase()+e.slice(1).replace(/[a-z][A-Z][a-z]/g,t=>t[0]+"_"+t.slice(1))}function FD(e,t){if(lc=!1,e==="")return null;if(e=e.slice(1),t.splitSegments){if(e.indexOf("/")===-1)return e===""?(lc=!0,null):t.coerceId(decodeURIComponent(e));let r=e.split("/"),n=new Zm;for(let s=0;s<r.length;s++){let i=r[s];if(!i&&s===r.length-1){lc=!0;break}n[s]=t.coerceId(decodeURIComponent(i))}return n}else{if(e==="")return lc=!0,null;e[e.length-1]==="/"&&(lc=!0)}return t.coerceId(decodeURIComponent(e))}function Mn(e,t){n.reliesOnPrototype=!0;let r=t.hasContent;return n;function n(s,i,o){let c,l,u,f;if(r?(o?(f=i,o=o.getContext?.()||o):i?typeof s=="object"&&s&&(!Array.isArray(s)||typeof s[0]=="object")?(f=s,c=f[this.primaryKey]??null,o=i.getContext?.()||i):f=i:(f=s,s=void 0,c=f.getId?.()??f[this.primaryKey]),c===null&&(u=!0)):i?o=i.getContext?.()||i:s&&typeof s=="object"&&!Array.isArray(s)&&(o=s),c===void 0)if(typeof s=="object"&&s){if(l=s,typeof(c=s.url)=="string")if(this.directURLMapping)c=c.slice(1);else{let h=c.indexOf("?");if(h>-1){let S=this.parseQuery(c.slice(h+1));l?S&&(l=Object.assign(S,l)):l=S,c=c.slice(0,h)}let m=this.parsePath(c,o,l);m?.id!==void 0?(m.query&&(l?l=Object.assign(m.query,l):l=m.query),u=m.isCollection,c=m.id):c=m}else if(s[Symbol.iterator]){c=[],u=!0;for(let h of s){if(typeof h=="object"&&h)break;c.push(h)}c.length===0?c=null:(c.length===1&&(c=c[0]),l.slice&&(l=l.slice(c.length,l.length),l.length===0&&(l=null,u=!1)))}c===void 0&&(c=s.id??null,c==null&&(u=!0))}else c=s,l=new cc(c),c==null&&(u=!0);o||(o={});let d;if(l?.ensureLoaded!=null||l?.async||u?(d={...t},l?.ensureLoaded!=null&&(d.ensureLoaded=l.ensureLoaded),l?.async&&(d.async=l.async),u&&(d.isCollection=!0)):d=t,o.transaction){let h=this.getResource(c,o,d);return h.then?h.then(_):_(h)}else return bt(o,()=>{let h=this.getResource(c,o,d);return h.then?h.then(_):_(h)},d);function _(h){if(o.authorize){o.authorize=!1;let m=t.type==="read"?h.allowRead(o.user,l,o):t.type==="update"?h.doesExist?.()===!1?h.allowCreate(o.user,f,o):h.allowUpdate(o.user,f,o):t.type==="create"?h.allowCreate(o.user,f,o):h.allowDelete(o.user,l,o);if(m?.then)return m.then(S=>{if(!S)throw new Xm(o.user);return typeof f?.then=="function"?f.then(g=>e(h,l,o,g)):e(h,l,o,f)});if(!m)throw new Xm(o.user)}return typeof f?.then=="function"?f.then(m=>e(h,l,o,m)):e(h,l,o,f)}a(_,"authorizeActionOnResource")}}function vn(e,t){let r=new $D.ClientError(`The ${e.constructor.name} does not have a ${t} method implemented`,405);r.allow=[],r.method=t;for(let n of["get","put","post","delete","query","move","copy"])typeof e[n]=="function"&&r.allow.push(n);throw r}function UA(e,t,r){let n=e.getRecord?.();if(n){let s=e.getChanges?.();return i=>{let o,c;return e.hasOwnProperty(i)&&typeof(o=e[i])!="function"?o:s&&i in s?s[i]:(c=t?.[i])?c(e,r):n[i]}}else return t?s=>{let i=t[s];return i?i(e,r):e[s]}:s=>e[s]}function ep(e,t){let r=t.propertyResolvers,n=t.getContext?.(),s;if(typeof e=="string")return a(function o(c){return c.then?c.then(o):Array.isArray(c)?c.map(o):UA(c,r,n)(e)},"transform");if(typeof e=="object"){if(e.asArray)return a(function c(l){if(l.then)return l.then(c);if(Array.isArray(l))return l.map(c);let u=[],f=i(UA(l,r,n));for(let d of e)u.push(f(d));return u},"transform");let o=e.forceNulls;return a(function c(l){if(l.then)return l.then(c);if(Array.isArray(l))return l.map(_=>_&&typeof _=="object"?c(_):_);let u={},f=i(UA(l,r,n)),d;for(let _ of e){let h=f(_);h===void 0&&o&&(h=null),h?.then?(d||(d=[]),d.push(h.then(m=>u[_.name||_]=m))):u[_.name||_]=h}return d?Promise.all(d).then(()=>u):u},"transform")}else throw new Error("Invalid select argument type "+typeof e);function i(o){return c=>{if(typeof c=="string")return o(c);if(typeof c=="object")if(c.name){s||(s={});let l=s[c.name];if(!l){let f=r[c.name]?.definition?.tableClass;l=s[c.name]=ep(c.select||c,f)}let u=o(c.name);return l(u)}else return o(c);else return c}}a(i,"handleProperty")}var qD,GD,$D,s4,$r,Xm,lc,Zm,Xo=be(()=>{qD=require("crypto");Vl();GD=M(ci()),$D=M(me());ac();mf();s4={json:"application/json",cbor:"application/cbor",msgpack:"application/x-msgpack",csv:"text/csv"},$r=class{static{a(this,"Resource")}#e;#t;#n;static transactions;static directURLMapping=!1;constructor(t,r){this.#e=t;let n=r?.getContext?r.getContext()??null:void 0;this.#t=n!==void 0?n:r||null}static get=Mn(function(t,r,n,s){let i=t.get?.(r);if(i?.then)return i.then(o);return o(i);function o(c){let l;if((l=r?.select)&&c!=null&&!c.selectApplied){let u=ep(l,t.constructor);return typeof c?.map=="function"?c.map(u):u(c)}return c}},{type:"read",letItLinger:!0,ensureLoaded:!0,async:!0});static put=Mn(function(t,r,n,s){if(Array.isArray(s)&&t.#n){let i=[],o=n.authorize;for(let c of s){let l=t.constructor,u=l.getResource(c[l.primaryKey],n,{async:!0});u.then?i.push(u.then(f=>f.put(c,n))):i.push(u.put(c,n))}return Promise.all(i)}return t.put?t.put(s,r):vn(t,"put")},{hasContent:!0,type:"update"});static patch=Mn(function(t,r,n,s){return t.patch?t.patch(s,r):vn(t,"patch")},{hasContent:!0,type:"update"});static delete=Mn(function(t,r,n,s){return t.delete?t.delete(r):vn(t,"delete")},{hasContent:!1,type:"delete"});static getNewId(){return(0,qD.randomUUID)()}static create(t,r,n){let s;return t==null?s=r?.[this.primaryKey]??this.getNewId():Array.isArray(t)&&typeof t[0]!="object"?s=r?.[this.primaryKey]??[...t,this.getNewId()]:typeof t!="object"?s=r?.[this.primaryKey]??[t,this.getNewId()]:(s=t?.[this.primaryKey]??this.getNewId(),n=r||{},r=t),n||(n={}),bt(n,()=>{let i=new this(s,n),o=i.update?i.update(r,!0):vn(i,"update");return n.newLocation=s,n.createdResource=!0,o?.then?o.then(()=>i):i})}static invalidate=Mn(function(t,r,n,s){return t.invalidate?t.invalidate(r):vn(t,"delete")},{hasContent:!1,type:"update"});static post=Mn(function(t,r,n,s){return t.#e!=null&&t.update?.(),t.post(s,r)},{hasContent:!0,type:"create"});static connect=Mn(function(t,r,n,s){return t.connect?t.connect(s,r):vn(t,"connect")},{hasContent:!0,type:"read"});static subscribe=Mn(function(t,r,n,s){return t.subscribe?t.subscribe(r):vn(t,"subscribe")},{type:"read"});static publish=Mn(function(t,r,n,s){return t.#e!=null&&t.update?.(),t.publish?t.publish(s,r):vn(t,"publish")},{hasContent:!0,type:"create"});static search=Mn(function(t,r,n,s){let i=t.search?t.search(r):vn(t,"search"),o=n.select;if(o&&n.hasOwnProperty("select")&&i!=null&&!i.selectApplied){let c=ep(o,t.constructor);return i.map(c)}return i},{type:"read"});static query=Mn(function(t,r,n,s){return t.search?t.search(s,r):vn(t,"search")},{hasContent:!0,type:"read"});static copy=Mn(function(t,r,n,s){return t.copy?t.copy(s,r):vn(t,"copy")},{hasContent:!0,type:"create"});static move=Mn(function(t,r,n,s){return t.move?t.move(s,r):vn(t,"move")},{hasContent:!0,type:"delete"});async post(t){if(this.#n)return(await this.constructor.create(this.#e,t,this.#t)).#e;vn(this,"post")}static isCollection(t){return t&&t.#n}get isCollection(){return this.#n}static coerceId(t){return t}static parseQuery(t){return Jm(t)}static parsePath(t,r,n){let s=t.indexOf(".");if(s>-1){let o=t.slice(s+1),c=r?.headers&&s4[o];if(c)r.requestedContentType=c,t=t.slice(0,s);else if(this.attributes?.find(l=>l.name===o))if(t=t.slice(0,s),n)n.property=o;else return{query:{property:o},id:FD(t,this),isCollection:lc}}let i=FD(t,this);return lc?{id:i,isCollection:!0}:i}static getResource(t,r,n){let s,i=r.getContext?.(),o;typeof r.isCollection=="boolean"&&r.hasOwnProperty("isCollection")?o=r.isCollection:o=n?.isCollection;let c=o&&this.Collection||this;if(i||(i=i===void 0?r:{}),i.transaction){let l;if(i.resourceCache?l=i.resourceCache:l=i.resourceCache=[],l.asMap){let u=l.asMap.get(t);if(s=u?.find(f=>f.constructor===c),s)return s;u||l.asMap.set(t,u=[]),u.push(s=new c(t,i))}else{if(s=l.find(u=>u.#e===t&&u.constructor===c),s)return s;if(l.push(s=new c(t,i)),l.length>10){let u=new Map;for(let f of l){let d=f.#e,_=u.get(d);_?_.push(f):u.set(d,[f])}i.resourceCache.length=0,i.resourceCache.asMap=u}}}else s=new c(t,i);return o&&(s.#n=!0),s}subscribe(t){return new Ln}connect(t,r){return r?.subscribe!==!1?this.subscribe?.(r):new Ln}allowRead(t){return t?.role.permission.super_user}allowUpdate(t){return t?.role.permission.super_user}allowCreate(t){return t?.role.permission.super_user}allowDelete(t){return t?.role.permission.super_user}getId(){return this.#e}getContext(){return this.#t}};(0,GD._assignPackageExport)("Resource",$r);a(i4,"snake_case");Xm=class extends Error{static{a(this,"AccessError")}constructor(t){t?(super("Unauthorized access to resource"),this.statusCode=403):(super("Must login"),this.statusCode=401)}};a(FD,"pathToId");Zm=class extends Array{static{a(this,"MultiPartId")}toString(){return this.join("/")}};a(Mn,"transactional");a(vn,"missingMethod");a(UA,"selectFromObject");a(ep,"transformForSelect")});var Zo,BA=be(()=>{Zo=class{constructor(t){this.error=t}static{a(this,"ErrorResource")}isError=!0;allowRead(){throw this.error}allowUpdate(){throw this.error}allowCreate(){throw this.error}allowDelete(){throw this.error}getId(){throw this.error}getContext(){throw this.error}get(){throw this.error}post(){throw this.error}put(){throw this.error}delete(){throw this.error}connect(){throw this.error}getResource(){return this}publish(){throw this.error}subscribe(){throw this.error}}});var jl={};Ue(jl,{server:()=>Ke});var VD,Ke,Pr=be(()=>{VD=M(ci()),Ke={};(0,VD._assignPackageExport)("server",Ke)});var WD={};Ue(WD,{Resources:()=>tp,keyArrayToString:()=>Ql,resetResources:()=>o4,resources:()=>cs});function o4(){return cs=new tp,Ke.resources=cs,cs}function Ql(e){return Array.isArray(e)?e[e.length-1]===null?e.slice(0,-1).join("/")+"/":e.join("/"):e}var KD,YD,tp,cs,Jl=be(()=>{ac();BA();KD=M(z()),YD=M(me());Pr();tp=class extends Map{static{a(this,"Resources")}isWorker=!0;loginPath;set(t,r,n,s){if(!r)throw new Error("Must provide a resource");t.startsWith("/")&&(t=t.replace(/^\/+/,""));let i={Resource:r,path:t,exportTypes:n,hasSubPaths:!1,relativeURL:""},o=super.get(t);if(o&&(o.Resource.databaseName!==r.databaseName||o.Resource.tableName!==r.tableName)&&!s){let c=new YD.ServerError(`Conflicting paths for ${t}`);KD.default.error(c),i.Resource=new Zo(c)}super.set(t,i);for(let[c,l]of this){let u=2;for(;(u=c.indexOf("/",u))>-1;){let f=this.get(c.slice(0,u));f&&(f.hasSubPaths=!0),u+=2}}}getMatch(t,r){let n=2,s=0,i,o=t.length;for(;n<o;){s=n,n=t.indexOf("/",n),n===-1&&(n=o);let u=n===o?t:t.slice(0,n),f=this.get(u),d=-1;if(!f&&n===o&&(d=u.indexOf("?",s),d!==-1)){let _=u.slice(0,d);f=this.get(_)}if(f&&(!r||f.exportTypes?.[r]!==!1)){if(f.relativeURL=t.slice(d!==-1?d:n),!f.hasSubPaths)return f;i=f}n+=2}if(i)return i;let c=t.indexOf("?"),l=c>-1?t.slice(0,c):t;return i=this.get(l),!i&&l.indexOf(".")>-1&&(i=this.get(l.split(".")[0])),i&&(!r||i.exportTypes?.[r]!==!1)?i.relativeURL=c>-1?t.slice(c):"":i||(i=this.get(""),i&&(!r||i.exportTypes?.[r]!==!1)&&(t.charAt(0)!=="/"&&(t="/"+t),i.relativeURL=t)),i}getResource(t,r){let n=this.getMatch(t);if(n)return t=n.relativeURL,n.Resource.getResource(this.pathToId(t,n.Resource),r)}call(t,r,n){return bt(r,async()=>{let s=this.getMatch(t);if(s)return t=s.relativeURL,n(s.Resource,s.path,t)})}setRepresentation(t,r,n){}};a(o4,"resetResources");a(Ql,"keyArrayToString")});var HA=P((mye,zD)=>{if(__filename.endsWith("dev.js")){let e=require("fast-glob"),{tmpdir:t}=require("node:os"),{relative:r,join:n}=require("node:path"),{existsSync:s,statSync:i,readFileSync:o,writeFileSync:c,unlinkSync:l}=require("node:fs"),{isMainThread:u}=require("node:worker_threads"),{spawnSync:f,spawn:d}=require("node:child_process");process.setSourceMapsEnabled(!0);let{PACKAGE_ROOT:_}=pt(),h=["bin","components","dataLayer","resources","server","sqlTranslator","upgrade","utility","validation"],m="ts-build";if(u){let A=!1,E=!1;if(E=s(n(_,m))){let T=new Set;e.sync(h.map(w=>`${w}/**/*.ts`),{cwd:_}).forEach(w=>{let v=0,k=0;try{T.add(w),v=i(n(_,w)).mtimeMs-5e3,k=i(n(_,m,w.replace(/.ts$/,".js"))).mtimeMs}catch{}v>k&&(A=!0)}),e.sync(h.map(w=>`${w}/**/*.js`),{cwd:n(_,m)}).forEach(w=>{if(!T.has(w.replace(/.js$/,".ts")))try{l(n(_,m,w))}catch{}})}else A=!0;if(A){console.log("Compiling TypeScript...");let T=f("npx",["tsc"],{cwd:_});if(T.stdout?.length&&console.log(T.stdout.toString()),T.stderr?.length&&console.log(T.stderr.toString()),E){let w=n(t(),"harperdb-tsc.pid"),v=!1;if(s(w))try{process.kill(+o(w,"utf8"),0),v=!0}catch{}if(!v){console.log("Starting background TypeScript compilation...");let k=d("npx",["tsc","--watch"],{detached:!0,cwd:_,stdio:"ignore"});k.on("error",$=>{console.error("Error trying to compile TypeScript",$)}),k.pid&&c(w,String(k.pid),"utf-8"),k.unref()}}}}let S=zD.constructor,g=S._findPath;S._findPath=function(A,E,T){if(A.startsWith(".")&&!T&&E.length===1&&E[0].startsWith(_)&&!E[0].includes("node_modules")){let w=r(_,E[0]),v;w.startsWith(m)?v=n(_,r(m,w)):v=n(_,m,w);let k=n(v,A),$=k+".js";if(s($))return $;if(k.includes(".")&&s(k))return k}return g(A,E,T)}}});var qA={};Ue(qA,{loadGQLSchema:()=>l4,start:()=>FA,startOnMainThread:()=>c4});function FA({ensureTable:e}){return{handleFile:t,setupFile:t};async function t(r,n,s,i){let{parse:o,Source:c,Kind:l,NamedTypeNode:u,StringValueNode:f}=await import("graphql"),d=o(new c(r.toString(),s)),_=new Map,h=[],m;for(let A of d.definitions)switch(A.kind){case l.OBJECT_TYPE_DEFINITION:let k=function(W){if(W.kind==="NonNullType"){let Y=k(W.type);return Y.nullable=!1,Y}if(W.kind==="ListType")return{type:"array",elements:k(W.type)};let se={type:W.name?.value};return Object.defineProperty(se,"location",{value:W.loc.startToken}),se};a(k,"getProperty");let E=A.name.value,T=[],w={table:null,database:null,properties:T};_.set(E,w);for(let W of A.directives){if(W.name.value==="table"){for(let se of W.arguments)w[se.name.value]=se.value.value;w.schema&&(w.database=w.schema),w.table||(w.table=E),w.audit&&(w.audit=w.audit!=="false"),w.attributes=w.properties,h.push(w)}if(W.name.value==="sealed"&&(w.sealed=!0),W.name.value==="splitSegments"&&(w.splitSegments=!0),W.name.value==="replicate"&&(w.replicate=!0),W.name.value==="export"){w.export=!0;for(let se of W.arguments)typeof w.export!="object"&&(w.export={}),w.export[se.name.value]=se.value.value}}let v=!1,$={};for(let W of A.fields){let te=k(W.type);te.name=W.name.value,T.push(te),$[te.name]=void 0;for(let se of W.directives){let Y=se.name.value;if(Y==="primaryKey")v?console.warn("Can not define two attributes as a primary key at",se.loc):(te.isPrimaryKey=!0,v=!0);else if(Y==="indexed")te.indexed=!0;else if(Y==="computed"){for(let ne of se.arguments||[])if(ne.name.value==="from"){let ue=ne.value.value;te.computed={from:g(ue,ne,$)},te.version==null&&(te.version=ue)}else ne.name.value==="version"&&(te.version=ne.value.value);te.computed=te.computed||!0}else if(Y==="relationship"){let ne={};for(let ue of se.arguments)ne[ue.name.value]=ue.value.value;te.relationship=ne}else if(Y==="createdTime")te.assignCreatedTime=!0;else if(Y==="updatedTime")te.assignUpdatedTime=!0;else if(Y==="expiresAt")te.expiresAt=!0;else if(Y==="allow"){let ne=te.authorizedRoles=[];for(let ue of se.arguments)ue.name.value==="role"&&ne.push(ue.value.value)}else server.knownGraphQLDirectives.includes(Y)&&console.warn(`@${Y} is an unknown directive, at`,se.loc)}}w.type=E,E==="Query"&&(m=w)}function S(A){let E=_.get(A.type);E?(Object.defineProperty(A,"properties",{value:E.properties}),Object.defineProperty(A,"definition",{value:E})):A.type==="array"?S(A.elements):a4.includes(A.type)||(0,QD.getWorkerIndex)()===0&&console.error(`The type ${A.type} is unknown at line ${A.location.line}, column ${A.location.column}, in ${s}`)}a(S,"connectPropertyType");for(let A of _.values())for(let E of A.properties)S(E);for(let A of h)A.tableClass=e(A),A.export&&(A.export.name===""?i.set((0,kA.dirname)(n),A.tableClass):i.set((0,kA.dirname)(n)+"/"+(A.export.name||A.type),A.tableClass,A.export));function g(A,E,T){return new jD.Script(`function computed(attributes) { return function(record) { with(attributes) { with (record) { return ${A}; } } } } computed;`,{filename:s,lineOffset:E.loc.startToken.line-1,columnOffset:E.loc.startToken.column}).runInThisContext()(T)}a(g,"createComputedFrom")}}var kA,jD,QD,a4,c4,l4,JD=be(()=>{kA=require("path"),jD=require("node:vm");ve();QD=M(Ze()),a4=["ID","Int","Float","Long","String","Boolean","Date","Bytes","Any","BigInt","Blob"];server.knownGraphQLDirectives&&(server.knownGraphQLDirectives=["table","sealed","export","primaryKey","indexed","computed","relationship","createdTime","updatedTime","expiresAt","allow"]);a(FA,"start");c4=FA,l4=FA({ensureTable:dt}).handleFile});var sL={};Ue(sL,{parse:()=>$A,streamAsJSON:()=>Ef,stringify:()=>uc});function Ef(e){return new GA({value:e})}function XD(e){return console.error(e),JSON.stringify(e.toString())}function ZD(e,t,r){return e?.then?r?e.then(t,r):e.then(t):t(e)}function uc(e){try{return JSON.stringify(e)??"null"}catch(t){if(t===rL)return nL(e);if(t.resolution)return t.resolution.then(()=>uc(e));throw t}}function nL(e){let t=typeof e;if(t==="object"){if(e===null)return"null";e.toJSON&&(e=e.toJSON());let r;if(Array.isArray(e)){r="[";for(let n=0;n<e.length;n++)n>0&&(r+=","),r+=nL(e[n]);return r+"]"}else{r="{";let n=!0;for(let s in e)n?n=!1:r+=",",r+=JSON.stringify(s)+":"+uc(e[s]);return r+"}"}}else{if(t==="string")return JSON.stringify(e);if(t==="undefined")return"null"}return e.toString()}function $A(e){return e?.length>0?(typeof e!="string"&&(e=e.toString()),f4.test(e)?u4.parse(e):JSON.parse(e)):null}var eL,tL,u4,d4,rL,GA,f4,VA=be(()=>{eL=require("stream"),tL=M(require("json-bigint-fixes")),u4=(0,tL.default)({useNativeBigInt:!0}),d4=1e4,rL={message:"Cannot serialize BigInt to JSON"};BigInt.prototype.toJSON=function(){throw rL};a(Ef,"streamAsJSON");GA=class extends eL.Readable{static{a(this,"JSONStream")}constructor(t){super(t),this.buffer=[],this.bufferSize=0,this.iterator=this.serialize(t.value,!0),this.activeIterators=[]}*serialize(t){if(t&&typeof t=="object"){let r=t[Symbol.asyncIterator],n=t[Symbol.iterator];if((n||r)&&!t.then){yield"[";let s=!0;if((r||n)&&!(t instanceof Array)){let i=r?t[Symbol.asyncIterator]():t[Symbol.iterator]();this.activeIterators.push(i);let o;for(;;){try{o=i.next(),o.then&&(yield o.then(c=>(o=c,""),c=>(o={done:!1,value:{error:c.toString()}},i={next:a(()=>({done:!0}),"next")},"")))}catch(c){o={done:!1,value:{error:c.toString()}},i={next:a(()=>({done:!0}),"next")}}if(o.done){this.activeIterators.splice(this.activeIterators.indexOf(i),1),yield"]";return}else s?s=!1:yield",",yield*this.serialize(o.value)}}for(let i of t)s?s=!1:yield",",yield*this.serialize(i);yield"]";return}if(t.then)try{yield t.then(s=>this.serialize(s),XD)}catch(s){yield XD(s)}else yield uc(t)}else yield uc(t)}_read(){if(!this._amReading){if(this._amReading=!0,this.done)return this.push(null);ZD(this.readIterator(this.iterator),t=>{t?(this.done=!0,this.push(null)):this._amReading=!1},t=>{console.error(t),this.done=!0,this.push(t.toString()),this.push(null)})}}push(t){return t===null||t instanceof Buffer?(this.bufferSize>0&&this.flush(),super.push(t)):(this.bufferSize+=t.length||t.toString().length,this.buffer.push(t),this.bufferSize>d4?this.flush():!0)}flush(){let t=super.push(this.buffer.join(""));return this.buffer=[],this.bufferSize=0,t}readIterator(t){try{let r;if(t.childIterator)return ZD(this.readIterator(t.childIterator),n=>{if(n)return t.childIterator=null,this.readIterator(t)});do{let n=t.next();if(n.done)return!0;if(r=n.value,r==null)r="null";else{if(r.then)return this.flush(),Promise.resolve(r).then(s=>{if(s&&typeof s.return=="function")return t.childIterator=s,this.readIterator(t);if(this.push(s+""))return this.readIterator(t)});if(typeof r.return=="function")return t.childIterator=r,this.readIterator(t)}}while(this.push(r))}catch(r){return console.error(r),this.push(r.toString()),this.push(null),!0}}_destroy(t,r){for(let n of this.activeIterators)t?n.throw(t):n.return();r()}};a(XD,"handleError");a(ZD,"when");a(uc,"stringify");a(nL,"jsStringify");f4=/[[,:]\s*-?\d{16,}/;a($A,"parse")});var _i=P(np=>{var rp=z();for(let e of["trace","debug","info","warn","error","fatal","notify"])rp.logsAtLevel(e)&&(np[e]=rp[e]);np.loggerWithTag=e=>rp.loggerWithTag(e,!0);np.setLogLevel=rp.setLogLevel});var hp={};Ue(hp,{Blob:()=>hi,blobsWereEncoded:()=>fc,databasePaths:()=>YA,decodeBlobsWithWrites:()=>fp,decodeFromDatabase:()=>_c,decodeWithBlobCallback:()=>_p,deleteBlob:()=>lp,deleteBlobsInObject:()=>ea,deleteRootBlobPathsForDB:()=>zA,encodeBlobsAsBuffers:()=>R4,encodeBlobsWithFilePath:()=>dp,findBlobsInObject:()=>Zl,getFileId:()=>up,getFilePathForBlob:()=>hL,getRootBlobPathsForDB:()=>Af,setDeletionDelay:()=>p4});function dL(){}function lp(e){let t=hL(e);t&&setTimeout(()=>{(0,je.unlink)(t,r=>{r&&ji.default.debug?.("Error trying to remove blob file",r)})},fL)}function p4(e){fL=e}function _L(e){let t=_n.get(e);if(!t)t={storageIndex:0,fileId:null,store:hn},_n.set(e,t);else{if(t.saving)return t;t.store=hn}return g4(t),t.source?KA(e,t.source,t):t.contentBuffer?E4(e,t):KA(e,Sf.Readable.from(e.stream()),t),t}function KA(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,je.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(h4),h=(0,ap.createDeflate)(),t.pipe(h).pipe(d)):(_||d.write(_4),t.pipe(d)),t.on("error",S);function m(g){let A=BigInt(g),E=new Uint8Array(pr),T=new DataView(E.buffer);return A|=BigInt(o?WA:uL)<<48n,T.setBigInt64(0,A),E}a(m,"createHeader");function S(g){i.unlock(f,0);let A=d.fd;g?(A&&(0,je.close)(A),u(g)):c?(0,je.fdatasync)(A,E=>{E&&u(E),l(),(0,je.close)(A)}):(l(),(0,je.close)(A))}a(S,"finished"),d.on("error",S).on("finish",()=>{if(_)S();else{let g=h?h.bytesWritten:d.bytesWritten-pr;e.size=g,(0,je.write)(d.fd,m(g),0,pr,0,S)}})}),e}function up(e){return _n.get(e)?.fileId}function hL(e){let t=_n.get(e);return t?.fileId&&Tf(t)}function Af(e){if(!e)throw new Error("No store specified, can not determine blob storage path");let t=YA.get(e);if(!t){if(!e.databaseName)return ji.default.warn?.("No database name specified, can not determine blob storage path"),[];let r=(0,cp.get)(U.STORAGE_BLOBPATHS);r?t=r.map(n=>(0,Ji.join)(n,e.databaseName)):t=[(0,Ji.join)((0,cp.getHdbBasePath)(),"blobs",e.databaseName)],YA.set(e,t)}return t}async function zA(e){let t=Af(e);t&&await Promise.all(t.map(r=>mL(r)))}async function mL(e){if((0,je.existsSync)(e)){for(let t of await(0,Bs.readdir)(e,{withFileTypes:!0}))if(t.isDirectory())await mL((0,Ji.join)(e,t.name));else try{await(0,Bs.unlink)((0,Ji.join)(e,t.name))}catch(r){ji.default.warn?.("Error deleting file",r)}try{await(0,Bs.rmdir)(e)}catch(t){ji.default.warn?.("Error deleting directory",t)}}}function Tf({storageIndex:e,fileId:t,store:r}){let n=Af(r);return(0,Ji.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 E4(e,t){let r=t.contentBuffer,n=r.length;if(!(n<lL))return e.size=n,KA(e,Sf.Readable.from([r]),t)}function g4(e){let t=Af(e.store),r=S4(),n=t?.length>1?T4(t,r):0,s=r.toString(16);e.storageIndex=n,e.fileId=s;let i=Tf(e),o=(0,Ji.dirname)(i);(0,je.existsSync)(o)||(0,cL.ensureDirSync)(o),e.filePath=i}function S4(){let e=aL.get(hn);if(!e){let t=0,r=Af(hn);for(let n of r){let s=0;for(let i=0;i<3;i++){s=s*4096;let o=0;if((0,je.existsSync)(n))for(let c of(0,je.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,Ji.join)(n,o.toString(16))}t=Math.max(t,s)}e=new BigInt64Array([BigInt(t)+1n]),e=new BigInt64Array(hn.getUserSharedBuffer("blob-file-id",e.buffer)),aL.set(hn,e)}return Number(Atomics.add(e,0,1n))}function T4(e,t){let r=Date.now();if(!e.frequencyTable){e.lastUpdated=0;let s=new Array(op);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,A4(e)),e.frequencyTable[t%op]}async function A4(e){if(!Bs.statfs)return;let t=await Promise.all(e.map(async(s,i)=>{let o=await(0,Bs.statfs)(s),c=o.bavail*o.bsize;return Math.pow(c,.8)})),r=new Array(op),n=t.map(s=>1/s);for(let s=0;s<op;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 dp(e,t,r){Xl=t,hn=r,fc=!1;try{return e()}finally{Xl=void 0,hn=void 0}}function R4(e){Dr=[];let t;try{t=e()}catch(n){throw Dr=void 0,n}let r=Dr.length<2?Dr[0]:Promise.all(Dr);return Dr=void 0,r?r.then(()=>e()):t}function fp(e,t){try{Dr=[],dc=t,e()}catch(n){throw dc=void 0,Dr=void 0,n}dc=void 0;let r=Dr.length<2?Dr[0]:Promise.all(Dr);return Dr=void 0,r}function _p(e,t,r){hn=r;try{return dc=t,e()}finally{dc=void 0}}function _c(e,t){return hn=t,e()}function ea(e){Zl(e,t=>{lp(t)})}function Zl(e,t){if(e instanceof hi)t(e);else if(Array.isArray(e))for(let r of e)typeof r=="object"&&r&&Zl(r,t);else if(e.constructor===Object)for(let r in e){let n=e[r];typeof n=="object"&&n&&Zl(e[r],t)}}function y4(){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 Qi,Bs,je,ap,Sf,cL,cp,Ji,ji,lL,pr,uL,WA,iL,_4,h4,oL,_n,dc,hi,Xl,Dr,hn,fc,gf,sp,m4,ip,fL,YA,aL,op,ls=be(()=>{Qi=require("msgpackr"),Bs=require("node:fs/promises"),je=require("node:fs"),ap=require("node:zlib"),Sf=require("node:stream"),cL=require("fs-extra"),cp=M(le());B();Ji=require("path"),ji=M(_i());Xi();lL=8192,pr=8,uL=0,WA=1,iL=255,_4=new Uint8Array([0,uL,255,255,255,255,255,255]),h4=new Uint8Array([0,WA,255,255,255,255,255,255]),oL=0xffffffffffff,_n=new WeakMap,hi=global.Blob||y4(),fc=!1,gf=new Uint8Array(8),sp=new DataView(gf.buffer),m4=6e4;a(dL,"InstanceOfBlobWithNoConstructor");dL.prototype=hi.prototype;ip=class e extends dL{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=_n.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):(QA()&&jA(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=_n.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=Tf(t),o,c=a(async()=>{let l,u=pr;try{if(l=await(0,Bs.readFile)(i),l.length>=pr){l.copy(gf,0,0,pr);let d=sp.getBigUint64(0);if(Number(d>>48n)===iL)throw new Error("Error in blob: "+buffer.subarray(pr));if(u=Number(d&0xffffffffffffn),u<n&&(u=n),u<oL&&(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]===WA?new Promise((d,_)=>{(0,ap.deflate)(l.subarray(pr),(h,m)=>{h?_(h):d(f(m))})}):f(l.subarray(pr))},"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=_n.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=Tf(t),o,c=0,l=0,u,f,d,_=!1,h=this;return new ReadableStream({start(){let S=1e3,g=a((A,E)=>{(0,je.open)(i,"r",(T,w)=>{if(T){if(T.code==="ENOENT"&&d!==!1&&(ji.default.debug?.("File does not exist yet, waiting for it to be created",i,S),S-- >0))return setTimeout(()=>{m(),g(A,E)},20).unref();E(T),h.#e?.forEach(v=>v(T))}else o=w,A(w)})},"openFile");return new Promise(g)},pull:a(S=>{let g=0,A=100;return new Promise(a(function E(T,w){function v($){(0,je.close)(o),clearTimeout(f),u&&u.close(),w($),h.#e?.forEach(W=>W($))}a(v,"onError");let k=Buffer.allocUnsafe(262144);(0,je.read)(o,k,0,k.length,c,($,W,te)=>{if(l+=W,$)return v($);if(c===0){if(W<pr){A-- >0&&d!==!1?(m(),ji.default.debug?.("File was empty, waiting for data to be written",i,A),setTimeout(()=>E(T,w),20).unref()):(ji.default.debug?.("File was empty, throwing error",i,A),w(new Error(`Blob ${t.fileId} was empty`)));return}te.copy(gf,0,0,pr);let se=sp.getBigUint64(0);if(Number(se>>48n)===iL)return v(new Error("Error in blob: "+te.subarray(pr)));if(g=Number(se&0xffffffffffffn),g<oL&&h.size!==g&&(h.size=g,h.#t))for(let Y of h.#t)Y(g);te=te.subarray(pr,W),l-=pr}else if(W===0){let se=Buffer.allocUnsafe(8);return(0,je.read)(o,se,0,pr,0,Y=>{if(Y)return v(Y);if(gf.set(se),g=Number(sp.getBigUint64(0)&0xffffffffffffn),g>l){m()?u?f=setTimeout(()=>{v(new Error("File read timed out"))},m4).unref():(u=(0,je.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,je.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 ji.default.debug?.("Error enqueuing chunk",se),T()}l===g&&((0,je.close)(o),S.close()),T()})},"readMore"))},"pull"),cancel(){(0,je.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=_n.get(this),i=new e(n&&{type:n});if(s?.fileId){let o={...s,start:t,end:r};_n.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)};_n.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(hn=t?.primaryStore?.rootStore,!hn)throw new Error("No target table specified");return _L(this).saving??Promise.resolve()}},fL=500;a(lp,"deleteBlob");a(p4,"setDeletionDelay");global.createBlob=function(e,t){let r=new ip(t),n={storageIndex:0,fileId:null,flush:t?.flush,compress:t?.compress};if(_n.set(r,n),e instanceof Uint8Array)r.size=e.length,n.contentBuffer=e;else if(e instanceof Sf.Readable)n.source=e;else if(typeof e=="string")n.contentBuffer=Buffer.from(e);else if(e?.[Symbol.asyncIterator]||e?.[Symbol.iterator])n.source=Sf.Readable.from(e);else throw new Error("Invalid source type");return r};a(_L,"saveBlob");a(KA,"writeBlobWithStream");a(up,"getFileId");a(hL,"getFilePathForBlob");YA=new Map;a(Af,"getRootBlobPathsForDB");a(zA,"deleteRootBlobPathsForDB");a(mL,"rimrafSteadily");a(Tf,"getFilePath");a(E4,"writeBlobWithBuffer");a(g4,"generateFilePath");aL=new Map;a(S4,"getNextFileId");op=128;a(T4,"getNextStorageIndex");a(A4,"createFrequencyTableForStoragePaths");a(dp,"encodeBlobsWithFilePath");a(R4,"encodeBlobsAsBuffers");a(fp,"decodeBlobsWithWrites");a(_p,"decodeWithBlobCallback");a(_c,"decodeFromDatabase");a(ea,"deleteBlobsInObject");a(Zl,"findBlobsInObject");(0,Qi.addExtension)({Class:hi,type:11,unpack:a(function(e){let t=(0,Qi.unpack)(e),r=new ip;if(Object.assign(r,t[0]),typeof t[1]!="object"){if(_n.set(r,{storageIndex:t[1],fileId:t[2],store:hn}),dc)return dc(r)??r;if(!hn)throw new Error("No store specified, cannot load blob from storage")}else _n.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=_n.get(e);if(Xl!==void 0&&(fc=!0,t?.recordId!==void 0&&t.recordId!==Xl))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<lL)return r.size=t.contentBuffer.length,(0,Qi.pack)([r,t.contentBuffer])}if(Xl!==void 0){if(t=_L(e),!t.fileId)throw new Error("Unable to save blob without file id");return t.recordId=Xl,(0,Qi.pack)([r,t.storageIndex,t.fileId])}if(t)try{let n=(0,je.readFileSync)(Tf(t));if(n.length>=pr&&(n.copy(gf,0,0,pr),Number(sp.getBigUint64(0)&0xffffffffffffn)===n.length-pr))return Buffer.concat([(0,Qi.pack)([r]),n]);if(Dr)Dr.push(e.bytes());else throw new Error("Incomplete blob");return Buffer.alloc(0)}catch(n){if(n.code==="ENOENT"&&Dr)return Dr.push(e.bytes()),Buffer.alloc(0);throw n}else throw new Error("Blob has no storage info or buffer attached to it")},"pack")});(0,Qi.addExtension)({Class:Promise,type:12,pack(){throw new Error("Cannot encode a promise")}});a(y4,"polyfillBlob")});var yL={};Ue(yL,{asyncSerialization:()=>jA,contentTypes:()=>eR,findBestSerializer:()=>pp,getDeserializer:()=>to,hasAsyncSerialization:()=>QA,registerContentHandlers:()=>bf,serialize:()=>Of,serializeMessage:()=>ta,toCsvStream:()=>mp});function O4(e){try{return e?.[0]===123?ZA(e):e}catch{return e}}function bf(e){e.register(w4,{serializers:[{regex:/^application\/json$/,serializer:Ef},{regex:/^application\/cbor$/,serializer:a(function(t){return new hc.EncoderStream(yf).end(t)},"serializer")},{regex:/^application\/(x-)?msgpack$/,serializer:a(function(t){return(t?.[Symbol.iterator]||t?.[Symbol.asyncIterator])&&!Array.isArray(t)?mc.Readable.from((0,mi.encodeIter)(t,yf)):(0,mi.pack)(t)},"serializer")},{regex:/^text\/csv$/,serializer:a(function(t){return this.header("Content-Disposition",'attachment; filename="data.csv"'),mp(t)},"serializer")}]}),e.addContentTypeParser("application/x-msgpack",{parseAs:"buffer"},(t,r,n)=>{try{n(null,(0,mi.unpack)(r))}catch(s){s.statusCode=400,n(s)}}),e.addContentTypeParser("application/cbor",{parseAs:"buffer"},(t,r,n)=>{try{n(null,(0,hc.decode)(r))}catch(s){s.statusCode=400,n(s)}})}function pp(e){let t=e.headers.asObject||e.headers,r=e.requestedContentType??t.accept,n,s=0,i,o,c=r?r.toLowerCase().split(/\s*,\s*/):[];for(let l of c){let[u,...f]=l.split(/\s*;\s*/),d=1,_={q:1};for(let m of f){let S=m.indexOf("=");_[m.substring(0,S)]=m.substring(S+1)}d=+_.q;let h=Vr.get(u);if(h){let m=(h.q||1)*d;m>s&&(n=h,i=h.type||u,s=m,o=_)}}if(!n){if(r)throw new gL.ClientError("No supported content types found in Accept header, supported types include: "+Array.from(Vr.keys()).join(", "),406);n=Vr.get("application/json"),i="application/json"}return{serializer:n,type:i,parameters:o}}function Of(e,t,r){let n=EL&&t.headers.asObject?.["accept-encoding"]?.includes("br"),s;if(e?.contentType!=null&&e.data!=null)r.headers.set("Content-Type",e.contentType),r.headers.set("Vary","Accept-Encoding"),s=e.data;else if(e instanceof Uint8Array||e instanceof hi)r.headers.set("Content-Type","application/octet-stream"),r.headers.set("Vary","Accept-Encoding"),s=e;else{let i=pp(t);if(i.serializer.compressible===!1&&(n=!1),r.headers.set("Vary","Accept, Accept-Encoding"),r.headers.set("Content-Type",i.type),typeof e=="object"&&e&&(e[Symbol.iterator]||e[Symbol.asyncIterator])&&i.serializer.serializeStream){if(e.mapError){let c=e.getColumns;e=e.mapError(l=>(l.toJSON=()=>({error:l.name,message:l.message,...l.partialObject}),XA.default.warn?.(`Error serializing error ${t?.url||t}: ${l}`),l)),e.getColumns=c}let o=i.serializer.serializeStream(e,r);return n&&(r.headers.set("Content-Encoding","br"),o=o.pipe((0,eo.createBrotliCompress)({params:{[eo.constants.BROTLI_PARAM_MODE]:i.type.includes("json")||i.type.includes("text")?eo.constants.BROTLI_MODE_TEXT:eo.constants.BROTLI_MODE_GENERIC,[eo.constants.BROTLI_PARAM_QUALITY]:2}}))),o}s=i.serializer.serialize(e,r)}return n&&s?.length>EL?(r.headers.set("Content-Encoding","br"),new Promise((i,o)=>(0,eo.brotliCompress)(s,(c,l)=>{c?o(c):i(l)}))):s}function ta(e,t,r){if(e?.contentType!=null&&e.data!=null)return e.data;Zi=r?void 0:[];try{let n;if(t){let s=t.serialize;if(s)n=s(e);else{let i=pp(t);s=t.serialize=i.serializer.serialize,n=s(e)}}else n=Rf(e);return Zi?.length>0?(Zi.length===1?Zi[0]:Promise.all(Zi)).then(()=>ta(e,t,!0)):n}finally{Zi=void 0}}function jA(e){if(Zi)Zi.push(e);else throw new Error("Unable to serialize asynchronously")}function QA(){return!!Zi}function I4(e){return new Promise((t,r)=>{let n=[];e.on("data",s=>n.push(s)),e.on("end",()=>t(Buffer.concat(n))),e.on("error",r)})}function P4(e){return C4.includes(e)}function D4(e){let t=e.indexOf(";"),r;if(t>-1){r={};let n=e.slice(t+1).split(";");for(let s of n){let[i,o]=s.split("=");r[i.trim()]=o.trim()}e=e.slice(0,t)}return{type:e,parameters:r}}function to(e="",t=!1){let r=D4(e),n=r.type&&Vr.get(r.type)?.deserialize||L4(r);return t?s=>I4(s).then(n):n}function L4(e){return e.type.startsWith("text/")?(e.parameters?.charset&&!P4(e.parameters.charset)&&XA.default.info(`Unknown Buffer encoding ${e.parameters.charset} in content-type. Proceeding anyways.`),t=>({contentType:e.type,data:t.toString(e.parameters?.charset||"utf-8")})):e.type==="application/octet-stream"?t=>t:t=>{if(e.type==="")try{if(t?.[0]===123)return ZA(t)}catch{}return{contentType:e.type||"application/octet-stream",data:t}}}function M4(e,t){return{[Symbol.asyncIterator](){let r=e[Symbol.asyncIterator]?e[Symbol.asyncIterator]():e[Symbol.iterator]();return{next(){let n=r.next();return n.then?n.then(s=>({value:t(s.value),done:s.done})):{value:t(n.value),done:n.done}},return(n){return r.return(n)},throw(n){return r.throw(n)}}}}}function mp(e,t){let r=mc.default.Readable.from(e?.[Symbol.iterator]||e?.[Symbol.asyncIterator]?e:[e]),n={};t&&(n.fields=t.map(o=>({label:o,value:o})));let s={objectMode:!0},i=new b4(n,s);return r.pipe(i)}var mi,hc,eo,gL,mc,SL,JA,TL,XA,b4,AL,Rf,ZA,yf,Vr,eR,pL,RL,N4,w4,EL,Zi,C4,Xi=be(()=>{VA();mi=require("msgpackr"),hc=require("cbor-x"),eo=require("zlib"),gL=M(me()),mc=M(require("stream"));Pr();SL=M(ci()),JA=M(le());B();TL=M(require("yaml")),XA=M(_i());ls();({Transform:b4}=require("json2csv")),AL=JA.default.get(U.SERIALIZATION_BIGINT)!==!1,Rf=AL?uc:JSON.stringify,ZA=AL?$A:JSON.parse,yf={useRecords:!1,useToJSON:!0},Vr=new Map,eR=Vr;Ke.contentTypes=eR;(0,SL._assignPackageExport)("contentTypes",eR);Vr.set("application/json",{serializeStream:Ef,serialize:Rf,deserialize(e){return ZA(e)},q:.8});pL=new hc.Encoder(yf);Vr.set("application/cbor",{serializeStream(e){return e[Symbol.asyncIterator]&&(e[Symbol.iterator]=null),new hc.EncoderStream(yf).end(e)},serialize:pL.encode,deserialize:pL.decode,q:1});Vr.set("application/x-msgpack",{serializeStream(e){return(e?.[Symbol.iterator]||e?.[Symbol.asyncIterator])&&!Array.isArray(e)?mc.Readable.from((0,mi.encodeIter)(e,yf)):(0,mi.pack)(e)},serialize:mi.pack,deserialize:mi.unpack,q:.9});Vr.set("text/csv",{serializeStream(e,t){return t.headers.set("Content-Disposition",'attachment; filename="data.csv"'),mp(e,e?.getColumns?.())},serialize(e,t){return t.headers.set("Content-Disposition",'attachment; filename="data.csv"'),e&&!e[Symbol.iterator]&&(e=[e.toJSON?e.toJSON():e]),mp(e,e?.getColumns?.())},q:.1});Vr.set("text/plain",{serialize(e){return e.toString()},serializeStream(e){return mc.Readable.from(e.map?e.map(t=>t.toString()):e)},deserialize(e){return e.toString()},q:.2});Vr.set("text/yaml",{serialize(e){return TL.stringify(e,{aliasDuplicateObjects:!1})},q:.7});Vr.set("text/event-stream",{serializeStream:a(function(e){return mc.Readable.from(M4(e,this.serialize))},"serializeStream"),serialize:a(function(e){if(e.acknowledge&&e.acknowledge(),typeof e=="object"&&"value"in e&&e.timestamp&&(e={data:e.value,event:e.type,id:e.timestamp}),e.data||e.event){let t="";if(e.event&&(t+="event: "+e.event+`
|
|
7
|
+
`).slice(1)){s=s.trim();let[i]=s.split(" ",1),o=s.slice(i.length+1).trim();t[i]===void 0&&(t[i]={}),t[i][r]=o}}))}catch(r){throw r}return Object.entries(t).filter(([,r])=>r.comm&&r.args&&r.ppid&&r.uid&&r["%cpu"]&&r["%mem"]&&r.args.includes(e)).map(([r,n])=>({pid:Number.parseInt(r,10),name:Z2.basename(n.comm),cmd:n.args,ppid:Number.parseInt(n.ppid,10),uid:Number.parseInt(n.uid,10),cpu:Number.parseFloat(n["%cpu"]),memory:Number.parseFloat(n["%mem"])}))}a(nJ,"findPs")});var vt=P((PRe,JP)=>{"use strict";var sJ="__dbis__",iJ="__txns__",oJ="__environment_name__",aJ="__dbi_defintion__",cJ={EQUALS:"equals",STARTS_WITH:"startsWith",_STARTS_WITH:"starts_with",ENDS_WITH:"endsWith",_ENDS_WITH:"ends_with",CONTAINS:"contains",SEARCH_ALL:"searchAll",SEARCH_ALL_TO_MAP:"searchAllToMap",BATCH_SEARCH_BY_HASH:"batchSearchByHash",BATCH_SEARCH_BY_HASH_TO_MAP:"batchSearchByHashToMap",GREATER_THAN:"greaterThan",_GREATER_THAN:"greater_than",GREATER_THAN_EQUAL:"greaterThanEqual",_GREATER_THAN_EQUAL:"greater_than_equal",LESS_THAN:"lessThan",_LESS_THAN:"less_than",LESS_THAN_EQUAL:"lessThanEqual",_LESS_THAN_EQUAL:"less_than_equal",BETWEEN:"between"},lJ=["__createdtime__","__updatedtime__"],uJ="\uFFFF",QP={TIMESTAMP:"timestamp",HASH_VALUE:"hash_value",USER_NAME:"user_name"},dJ=Object.values(QP);JP.exports={AUDIT_STORE_NAME:iJ,INTERNAL_DBIS_NAME:sJ,DBI_DEFINITION_NAME:aJ,SEARCH_TYPES:cJ,TIMESTAMP_NAMES:lJ,MAX_SEARCH_KEY_LENGTH:256,ENVIRONMENT_NAME_KEY:oJ,TRANSACTIONS_DBI_NAMES_ENUM:QP,TRANSACTIONS_DBIS:dJ,OVERFLOW_MARKER:uJ}});var Dn=P((DRe,oD)=>{"use strict";var XP=(B(),D(q)),ZP=vt(),eD={CONTINUE:100,OK:200,CREATED:201,BAD_REQUEST:400,UNAUTHORIZED:401,FORBIDDEN:403,NOT_FOUND:404,METHOD_NOT_ALLOWED:405,REQUEST_TIMEOUT:408,CONFLICT:409,TOO_MANY_REQUESTS:429,INTERNAL_SERVER_ERROR:500,NOT_IMPLEMENTED:501,BAD_GATEWAY:502,SERVICE_UNAVAILABLE:503,GATEWAY_TIMEOUT:504,HTTP_VERSION_NOT_SUPPORTED:505,INSUFFICIENT_STORAGE:507,NETWORK_AUTHENTICATION_REQUIRED:511},tD=a(e=>`${e} Check logs and try again.`,"CHECK_LOGS_WRAPPER"),rD={500:tD("There was an error processing your request."),400:"Invalid request"},fJ=rD[eD.INTERNAL_SERVER_ERROR],_J={OP_NOT_SUPPORTED_FOR_FS:a(e=>`${e} is not available for this instance because it uses the File System data store.`,"OP_NOT_SUPPORTED_FOR_FS"),MISSING_VALUE:a(e=>`${e} is missing.`,"MISSING_VALUE"),INVALID_VALUE:a(e=>`${e} is invalid.`,"INVALID_VALUE"),NOT_FOUND:a(e=>`${e} not found.`,"NOT_FOUND")},hJ={CONFIG_VALIDATION:a(e=>`HarperDB config file validation error: ${e}`,"CONFIG_VALIDATION")},mJ={DEFAULT_BULK_LOAD_ERR:"There was an error during your bulk load into HarperDB.",DOWNLOAD_FILE_ERR:a(e=>`There was an error downloading '${e}'.`,"DOWNLOAD_FILE_ERR"),INSERT_JSON_ERR:"There was an error inserting the downloaded JSON data.",INSERT_CSV_ERR:"There was an error inserting the downloaded CSV data.",INVALID_ACTION_PARAM_ERR:a(e=>`Bulk load operation failed - ${e} is not a valid 'action' parameter`,"INVALID_ACTION_PARAM_ERR"),INVALID_FILE_EXT_ERR:a(e=>`Error selecting correct parser - valid file type not found in json - ${e}`,"INVALID_FILE_EXT_ERR"),MAX_FILE_SIZE_ERR:a((e,t)=>`File size is ${e} bytes, which exceeded the maximum size allowed of: ${t} bytes`,"MAX_FILE_SIZE_ERR"),PAPA_PARSE_ERR:"There was an error parsing the downloaded CSV data.",S3_DOWNLOAD_ERR:a(e=>`There was an error downloading '${e}' from AWS.`,"S3_DOWNLOAD_ERR"),WRITE_TEMP_FILE_ERR:"Error writing temporary file to storage"},pJ={BASE_PATH_REQUIRED:"base_path is required",DESTINATION_PATH_REQUIRED:"destination_path is required",ENV_NAME_REQUIRED:"env_name is required",INVALID_BASE_PATH:"invalid base_path",INVALID_DESTINATION_PATH:"invalid destination_path",INVALID_ENVIRONMENT:"invalid environment",ENV_REQUIRED:"env is required",DBI_NAME_REQUIRED:"dbi_name is required",DBI_DOES_NOT_EXIST:"dbi does not exist",HASH_ATTRIBUTE_REQUIRED:"hash_attribute is required",ID_REQUIRED:"id is required",IDS_REQUIRED:"ids is required",IDS_MUST_BE_ITERABLE:"ids must be iterable",FETCH_ATTRIBUTES_REQUIRED:"fetch_attributes is required",FETCH_ATTRIBUTES_MUST_BE_ARRAY:"fetch_attributes must be an array",ATTRIBUTE_REQUIRED:"attribute is required",SEARCH_VALUE_REQUIRED:"search_value is required",SEARCH_VALUE_TOO_LARGE:"search_value is too long",WRITE_ATTRIBUTES_REQUIRED:"write_attributes is required",WRITE_ATTRIBUTES_MUST_BE_ARRAY:"write_attributes must be an array",RECORDS_REQUIRED:"records is required",RECORDS_MUST_BE_ARRAY:"records must be an array",CANNOT_CREATE_INTERNAL_DBIS_NAME:`cannot create a dbi named ${ZP.INTERNAL_DBIS_NAME}`,CANNOT_DROP_INTERNAL_DBIS_NAME:`cannot drop a dbi named ${ZP.INTERNAL_DBIS_NAME}`,START_VALUE_REQUIRED:"start_value is required",END_VALUE_REQUIRED:"end_value is required",CANNOT_COMPARE_STRING_TO_NUMERIC_KEYS:"cannot compare a string to numeric keys",END_VALUE_MUST_BE_GREATER_THAN_START_VALUE:"end_value must be greater than or equal to start_value",UNKNOWN_SEARCH_TYPE:"unknown search type",CANNOT_DROP_TABLE_HASH_ATTRIBUTE:"cannot drop a table's hash attribute"},EJ={ATTR_NAME_LENGTH_ERR:a(e=>`transaction aborted due to attribute name ${e} being too long. Attribute names cannot be longer than ${XP.INSERT_MAX_CHARACTER_SIZE} bytes.`,"ATTR_NAME_LENGTH_ERR"),ATTR_NAME_NULLISH_ERR:"transaction aborted due to record(s) with an attribute name that is null, undefined or empty string",HASH_VAL_LENGTH_ERR:`transaction aborted due to record(s) with a hash value that exceeds ${XP.INSERT_MAX_CHARACTER_SIZE} bytes, check log for more info`,INVALID_FORWARD_SLASH_IN_HASH_ERR:"transaction aborted due to record(s) with a hash value that contains a forward slash, check log for more info",RECORD_MISSING_HASH_ERR:"transaction aborted due to record(s) with no hash value, check log for more info"},nD={GENERIC_AUTH_FAIL:"Login failed",USER_INACTIVE:"Cannot complete request: User is inactive",INVALID_TOKEN:"invalid token",NO_ENCRYPTION_KEYS:"unable to generate JWT as there are no encryption keys. please contact your administrator",INVALID_CREDENTIALS:"invalid credentials",PASSWORD_REQUIRED:"password is required",USERNAME_REQUIRED:"username is required",REFRESH_TOKEN_REQUIRED:"refresh_token is required",INVALID_AUTH_OBJECT:"invalid auth_object",INVALID_BODY:"invalid body",TOKEN_EXPIRED:"token expired",REFRESH_TOKEN_SAVE_FAILED:"unable to store refresh_token"},gJ={DEFAULT_INVALID_REQUEST:"Invalid request",OP_AUTH_PERMS_ERROR:"This operation is not authorized due to role restrictions and/or invalid database items",OP_IS_SU_ONLY:a(e=>`Operation '${e}' is restricted to 'super_user' roles`,"OP_IS_SU_ONLY"),OP_NOT_FOUND:a(e=>`Operation '${e}' not found`,"OP_NOT_FOUND"),SYSTEM_TIMESTAMP_PERMS_ERR:"Internal timestamp attributes - '__createdtime_' and '__updatedtime__' - cannot be inserted to or updated by HDB users.",UNKNOWN_OP_AUTH_ERROR:a((e,t,r)=>`There was an error authorizing ${e} op on table '${t}.${r}'`,"UNKNOWN_OP_AUTH_ERROR"),USER_HAS_NO_PERMS:a(e=>`User ${e} has no role or permissions. Please assign the user a valid role.`,"USER_HAS_NO_PERMS"),DROP_SYSTEM:"The 'system' database, tables and records are used internally by HarperDB and cannot be updated or removed."},SJ={ATTR_PERM_MISSING:a((e,t)=>`${e.toUpperCase()} attribute permission missing for '${t}'`,"ATTR_PERM_MISSING"),ATTR_PERM_MISSING_NAME:"Permission object in 'attribute_permission' missing an 'attribute_name'",ATTR_PERM_NOT_BOOLEAN:a((e,t)=>`${e.toUpperCase()} attribute permission for '${t}' must be a boolean`,"ATTR_PERM_NOT_BOOLEAN"),ATTR_PERMS_ARRAY_MISSING:"Missing 'attribute_permissions' array",ATTR_PERMS_NOT_ARRAY:"Value for 'attribute_permissions' must be an array",INVALID_ATTRIBUTE_IN_PERMS:a(e=>`Invalid attribute '${e}' in 'attribute_permissions'`,"INVALID_ATTRIBUTE_IN_PERMS"),INVALID_PERM_KEY:a(e=>`Invalid table permission key value '${e}'`,"INVALID_PERM_KEY"),INVALID_ATTR_PERM_KEY:a(e=>`Invalid attribute permission key value '${e}'`,"INVALID_ATTR_PERM_KEY"),INVALID_ROLE_JSON_KEYS:a(e=>`Invalid ${e.length>1?"keys":"key"} in JSON body - '${e.join("', '")}'`,"INVALID_ROLE_JSON_KEYS"),MISMATCHED_TABLE_ATTR_PERMS:a(e=>`You have a conflict with TABLE permissions for '${e}' being false and ATTRIBUTE permissions being true`,"MISMATCHED_TABLE_ATTR_PERMS"),OUTDATED_PERMS_TRANSLATION_ERROR:"This instance was recently upgraded and uses our new role permissions structure. Please login to this instance in HarperDB Studio, go to 'Roles', and click 'Update Role Permission' for all standard roles to migrate them to the new structure.",ROLE_ALREADY_EXISTS:a(e=>`A role with name '${e}' already exists`,"ROLE_ALREADY_EXISTS"),ROLE_NOT_FOUND:"Role not found",ROLE_PERMS_ERROR:"Errors in the role permissions JSON provided",SCHEMA_PERM_ERROR:a(e=>`Your role does not have permission to view database metadata for '${e}'`,"SCHEMA_PERM_ERROR"),SCHEMA_TABLE_PERM_ERROR:a((e,t)=>`Your role does not have permission to view database.table metadata for '${e}.${t}'`,"SCHEMA_TABLE_PERM_ERROR"),SU_ROLE_MISSING_ERROR:"Missing 'super_user' key/value in permission set",SU_CU_ROLE_BOOLEAN_ERROR:a(e=>`Value for '${e}' permission must be a boolean`,"SU_CU_ROLE_BOOLEAN_ERROR"),STRUCTURE_USER_ROLE_TYPE_ERROR:a(e=>`Value for '${e}' permission must be a boolean or Array`,"STRUCTURE_USER_ROLE_TYPE_ERROR"),SU_CU_ROLE_NO_PERMS_ALLOWED:a(e=>`Roles with '${e}' set to true cannot have other permissions set.`,"SU_CU_ROLE_NO_PERMS_ALLOWED"),SU_CU_ROLE_COMBINED_ERROR:"Roles cannot have both 'super_user' and 'cluster_user' values included in their permissions set.",TABLE_PERM_MISSING:a(e=>`Missing table ${e.toUpperCase()} permission`,"TABLE_PERM_MISSING"),TABLE_PERM_NOT_BOOLEAN:a(e=>`Table ${e.toUpperCase()} permission must be a boolean`,"TABLE_PERM_NOT_BOOLEAN")},TJ={ATTR_NOT_FOUND:a((e,t,r)=>`Attribute '${r}' does not exist on '${e}.${t}'`,"ATTR_NOT_FOUND"),ATTR_EXISTS_ERR:a((e,t,r)=>`Attribute '${r}' already exists in ${e}.${t}'`,"ATTR_EXISTS_ERR"),DESCRIBE_ALL_ERR:"There was an error during describeAll. Please check the logs and try again.",INVALID_TABLE_ERR:a(e=>`Invalid table ${JSON.stringify(e)}`,"INVALID_TABLE_ERR"),SCHEMA_NOT_FOUND:a(e=>`database '${e}' does not exist`,"SCHEMA_NOT_FOUND"),SCHEMA_EXISTS_ERR:a(e=>`database '${e}' already exists`,"SCHEMA_EXISTS_ERR"),TABLE_EXISTS_ERR:a((e,t)=>`Table '${t}' already exists in '${e}'`,"TABLE_EXISTS_ERR"),SCHEMA_REQUIRED_ERR:"database is required",TABLE_NOT_FOUND:a((e,t)=>`Table '${e}.${t}' does not exist`,"TABLE_NOT_FOUND"),TABLE_REQUIRED_ERR:"table is required"},AJ={OUTER_JOIN_TRANSLATION_ERROR:"There was an error translating the final SQL outer join data."},RJ={ALTER_USER_DUP_ROLES:a(e=>`Update failed. There are duplicates for the '${e}' role which is not allowed. Update your roles and try again.`,"ALTER_USER_DUP_ROLES"),ALTER_USER_ROLE_NOT_FOUND:a(e=>`Update failed. Requested '${e}' role not found.`,"ALTER_USER_ROLE_NOT_FOUND"),DUP_ROLES_FOUND:a(e=>`Multiple ${e} roles found. Roles must have unique 'role' value. Please update and try again.`,"DUP_ROLES_FOUND"),ROLE_NAME_NOT_FOUND:a(e=>`${e} role not found`,"ROLE_NAME_NOT_FOUND"),USER_ALREADY_EXISTS:a(e=>`User ${e} already exists`,"USER_ALREADY_EXISTS"),USER_NOT_EXIST:a(e=>`User ${e} does not exist`,"USER_NOT_EXIST")},sD={INVALID_DATE:"Invalid date, must be in ISO-8601 format (YYYY-MM-DD).",SEARCH_CONDITIONS_INVALID_SORT_ATTRIBUTE:a(e=>`invalid sort attribute '${e}', the attribute must either be the table's hash attribute or an attribute used in conditions.`,"SEARCH_CONDITIONS_INVALID_SORT_ATTRIBUTE")},iD={INVALID_ITC_DATA_TYPE:"Invalid ITC event data type, must be an object",MISSING_TYPE:"ITC event missing 'type'",MISSING_MSG:"ITC event missing 'message'",MISSING_ORIGIN:"ITC event message missing 'originator' property",INVALID_EVENT:a(e=>`ITC server received invalid event type: ${e}`,"INVALID_EVENT")},yJ={FUNCTION_STATUS:"Error getting custom function status, check the log for more details",GET_FUNCTIONS:"Error getting custom functions, check the log for more details",GET_FUNCTION:"Error getting custom function, check the log for more details",SET_FUNCTION:"Error setting custom function, check the log for more details",NO_PROJECT:"Project does not exist. Create one using 'add_custom_function_project'",PROJECT_EXISTS:"Project already exists",VALIDATION_ERR:"Error validating request, check the log for more details",NO_FILE:"File does not exist",BAD_FILE_NAME:"File name can only contain alphanumeric, dash and underscore characters",BAD_PROJECT_NAME:"Project name can only contain alphanumeric, dash and underscores characters",BAD_PACKAGE:"Packaged project must be base64-encoded tar file of project directory",DROP_FUNCTION:"Error dropping custom function, check the log for more details",ADD_FUNCTION:"Error adding custom function project, check the log for more details",DROP_FUNCTION_PROJECT:"Error dropping custom function project, check the log for more details",BAD_FILE_PATH:"Filepath must be valid, and contain the name of the tarball you wish to write",NOT_ENABLED:"Custom functions is not enabled, to enable set fastifyRoutes enabled to true in hdb/harperdb-config.yaml file.",BAD_SSH_KEY_NAME:"SSH key name can only contain alphanumeric, dash and underscore characters"},bJ={CLUSTERING_NOT_ENABLED:"Clustering must be enabled to perform this operation."},OJ={...nD,...mJ,..._J,...gJ,...SJ,...TJ,...AJ,...RJ,...EJ,...sD,...iD,...yJ,...bJ,...hJ};oD.exports={CHECK_LOGS_WRAPPER:tD,HDB_ERROR_MSGS:OJ,DEFAULT_ERROR_MSGS:rD,DEFAULT_ERROR_RESP:fJ,HTTP_STATUS_CODES:eD,LMDB_ERRORS_ENUM:pJ,AUTHENTICATION_ERROR_MSGS:nD,VALIDATION_ERROR_MSGS:sD,ITC_ERRORS:iD}});var me=P((MRe,lD)=>{"use strict";var $l=Dn(),NJ=z(),wJ=(B(),D(q)),km=class extends Error{static{a(this,"HdbError")}constructor(t,r,n,s,i){super(),Error.captureStackTrace(this,aD),this.statusCode=n||$l.HTTP_STATUS_CODES.INTERNAL_SERVER_ERROR,this.http_resp_msg=r||($l.DEFAULT_ERROR_MSGS[n]?$l.DEFAULT_ERROR_MSGS[n]:$l.DEFAULT_ERROR_MSGS[$l.HTTP_STATUS_CODES.INTERNAL_SERVER_ERROR]),this.message=t.message?t.message:this.http_resp_msg,this.type=t.name,s&&(this.logLevel=s),typeof this.message!="string"&&(this.stack=t.stack),i&&NJ[s](i)}},bA=class extends Error{static{a(this,"ClientError")}constructor(t,r){if(t instanceof Error)return t.statusCode=r||400,t;super(t),this.statusCode=r||400}},OA=class extends Error{static{a(this,"ServerError")}constructor(t,r){super(t),this.statusCode=r||500}};function aD(e,t,r,n=wJ.LOG_LEVELS.ERROR,s=null,i=!1){if(cD(e))return e;let o=new km(e,t,r,n,s);return i&&delete o.stack,o}a(aD,"handleHDBError");function cD(e){return e.__proto__.constructor.name===km.name}a(cD,"isHDBError");lD.exports={isHDBError:cD,handleHDBError:aD,ClientError:bA,ServerError:OA,hdb_errors:$l}});var Et=P((URe,pD)=>{"use strict";var af=(B(),D(q)),IJ=oe(),cn=le(),cf=require("path"),CJ=require("minimist"),uD=require("fs-extra"),dD=require("lodash");cn.initSync();var{CONFIG_PARAMS:zo,DATABASES_PARAM_CONFIG:rf,SYSTEM_SCHEMA_NAME:Fm}=af,nf,sf,of;function fD(){if(nf!==void 0)return nf;if(cn.getHdbBasePath()!==void 0)return nf=cn.get(zo.STORAGE_PATH)||cf.join(cn.getHdbBasePath(),af.DATABASES_DIR_NAME),nf}a(fD,"getBaseSchemaPath");function _D(){if(sf!==void 0)return sf;if(cn.getHdbBasePath()!==void 0)return sf=mD(Fm),sf}a(_D,"getSystemSchemaPath");function hD(){if(of!==void 0)return of;if(cn.getHdbBasePath()!==void 0)return of=cn.get(af.CONFIG_PARAMS.STORAGE_AUDIT_PATH)||cf.join(cn.getHdbBasePath(),af.TRANSACTIONS_DIR_NAME),of}a(hD,"getTransactionAuditStoreBasePath");function PJ(e,t){let r=cn.get(zo.DATABASES)?.[e];return t&&r?.tables?.[t]?.auditPath||r?.auditPath||cf.join(hD(),e.toString())}a(PJ,"getTransactionAuditStorePath");function mD(e,t){e=e.toString(),t=t&&t.toString();let r=cn.get(af.CONFIG_PARAMS.DATABASES)?.[e];return t&&r?.tables?.[t]?.path||r?.path||cf.join(fD(),e)}a(mD,"getSchemaPath");function DJ(e,t){e=e.toString(),t=t.toString();let r=process.env;Object.assign(r,CJ(process.argv));let n=r[zo.DATABASES.toUpperCase()];if(n){let i;try{i=JSON.parse(n)}catch(o){if(!IJ.isObject(n))throw o;i=n}for(let o of i){let c=o[Fm];if(!c)continue;let l=cn.get(zo.DATABASES);l=l??{};let u=c?.tables?.[t]?.[rf.PATH];if(u)return dD.set(l,[Fm,rf.TABLES,t,rf.PATH],u),cn.setProperty(zo.DATABASES,l),u;let f=c?.[rf.PATH];if(f)return dD.set(l,[Fm,rf.PATH],f),cn.setProperty(zo.DATABASES,l),f}}let s=r[zo.STORAGE_PATH.toUpperCase()];if(s){if(!uD.pathExistsSync(s))throw new Error(s+" does not exist");let i=cf.join(s,e);return uD.mkdirsSync(i),cn.setProperty(zo.STORAGE_PATH,s),i}return _D()}a(DJ,"initSystemSchemaPaths");function LJ(){nf=void 0,sf=void 0,of=void 0}a(LJ,"resetPaths");pD.exports={getBaseSchemaPath:fD,getSystemSchemaPath:_D,getTransactionAuditStorePath:PJ,getTransactionAuditStoreBasePath:hD,getSchemaPath:mD,initSystemSchemaPaths:DJ,resetPaths:LJ}});var ln=P((kRe,AD)=>{"use strict";var MJ=Dn().LMDB_ERRORS_ENUM,BRe=require("lmdb"),vJ=vt(),HRe=require("buffer").Buffer,{OVERFLOW_MARKER:ED,MAX_SEARCH_KEY_LENGTH:qm}=vJ,gD=["number","string","symbol","boolean","bigint"];function UJ(e){if(e=e?.primaryStore||e,!e)throw new Error(MJ.ENV_REQUIRED)}a(UJ,"validateEnv");function xJ(e){if(e==null)return null;let t;try{t=typeof e=="object"?JSON.stringify(e):e.toString()}catch{t=e.toString()}return t}a(xJ,"stringifyData");function BJ(e){return e instanceof Date?e.valueOf():e}a(BJ,"convertKeyValueToWrite");function HJ(e,t){if(e===null)return t?[null]:void 0;if(e===void 0)return;if(gD.includes(typeof e))return e.length>qm?[e.slice(0,qm)+ED]:[e];let r;if(Array.isArray(e)){r=[];for(let n=0,s=e.length;n<s;n++){let i=e[n];if(gD.includes(typeof i))i.length>qm?r.push(i.slice(0,qm)+ED):r.push(i);else{if(i===null&&t)return r.push(null);if(i instanceof Date)return r.push(i.getTime())}}}else if(e instanceof Date)return[e.getTime()];return r}a(HJ,"getIndexedValues");var Gm=0,SD=0;function TD(){SD=Date.now()-performance.now()}a(TD,"adjustStartTime");TD();var kJ=6e4;setInterval(TD,kJ).unref();function FJ(){let e=performance.now()+SD;return e>Gm?(Gm=e,e):(Gm+=488e-6,Gm)}a(FJ,"getNextMonotonicTime");AD.exports={validateEnv:UJ,stringifyData:xJ,convertKeyValueToWrite:BJ,getNextMonotonicTime:FJ,getIndexedValues:HJ}});var lf=P((qRe,RD)=>{"use strict";var qJ=(B(),D(q)).OPERATIONS_ENUM,NA=class{static{a(this,"InsertObject")}constructor(t,r,n,s,i=void 0){this.operation=qJ.INSERT,this.schema=t,this.table=r,this.hash_attribute=n,this.records=s,this.__origin=i}};RD.exports=NA});var uf=P((VRe,ND)=>{"use strict";var $Re=lf(),$m=(B(),D(q)),wA=oe(),yD=z(),GJ=require("uuid"),{handleHDBError:Vm,hdb_errors:$J}=me(),{HDB_ERROR_MSGS:Km,HTTP_STATUS_CODES:Ym}=$J;ND.exports=bD;function bD(e,t,r){for(let s=0;s<t.length;s++)OD(t[s]);let{records:n}=e;for(let s=0;s<n.length;s++){let i=n[s];VJ(i,r,e.operation)}}a(bD,"processRows");bD.validateAttribute=OD;function OD(e){if(Buffer.byteLength(String(e))>$m.INSERT_MAX_CHARACTER_SIZE)throw Vm(new Error,Km.ATTR_NAME_LENGTH_ERR(e),Ym.BAD_REQUEST,void 0,void 0,!0);if(wA.isEmptyOrZeroLength(e)||wA.isEmpty(e.trim()))throw Vm(new Error,Km.ATTR_NAME_NULLISH_ERR,Ym.BAD_REQUEST,void 0,void 0,!0)}a(OD,"validateAttribute");function VJ(e,t,r){if(!e.hasOwnProperty(t)||wA.isEmptyOrZeroLength(e[t])){if(r===$m.OPERATIONS_ENUM.INSERT||r===$m.OPERATIONS_ENUM.UPSERT){e[t]=GJ.v4();return}throw yD.error("Update transaction aborted due to record with no hash value:",e),Vm(new Error,Km.RECORD_MISSING_HASH_ERR,Ym.BAD_REQUEST,void 0,void 0,!0)}if(Buffer.byteLength(String(e[t]))>$m.INSERT_MAX_CHARACTER_SIZE)throw yD.error(e),Vm(new Error,Km.HASH_VAL_LENGTH_ERR,Ym.BAD_REQUEST,void 0,void 0,!0)}a(VJ,"validateHash")});var wD,Ln,IA,Vl=be(()=>{wD=require("events"),Ln=class extends wD.EventEmitter{static{a(this,"IterableEventQueue")}resolveNext;queue;hasDataListeners;drainCloseListener;currentDrainResolver;[Symbol.asyncIterator](){let t=new IA;return t.queue=this,t}push(t){this.send(t)}send(t){this.resolveNext?(this.resolveNext({value:t}),this.resolveNext=null):this.hasDataListeners?this.emit("data",t):(this.queue||(this.queue=[]),this.queue.push(t))}getNextMessage(){let t=this.queue?.shift();return t||this.emit("drained"),t}waitForDrain(){return new Promise(t=>{!this.queue||this.queue.length===0?t(!0):(this.once("drained",()=>t(!0)),this.currentDrainResolver=t,this.drainCloseListener||(this.drainCloseListener=!0,this.on("close",()=>{this.currentDrainResolver?.(!1)})))})}on(t,r){if(t==="data"&&!this.hasDataListeners)for(this.hasDataListeners=!0;this.queue?.length>0;)r(this.queue.shift());return super.on(t,r)}},IA=class{static{a(this,"EventQueueIterator")}queue;push(t){this.queue.send(t)}next(){let t=this.queue.getNextMessage();return t?{value:t}:new Promise(r=>this.queue.resolveNext=r)}return(t){return this.queue.emit("close"),{value:t,done:!0}}throw(t){return this.queue.emit("close",t),{done:!0}}}});function vD(e){PA=e}function zJ(){WJ=setInterval(function(){for(let e of CA)if(e.stale){let t=e.getContext()?.url;DD.error(`Transaction was open too long and has been aborted, from table: ${e.lmdbDb?.name+(t?" path: "+t:"")}`),e.abort()}else e.stale=!0},YJ).unref()}var DA,PD,DD,LD,MD,ID,CA,KJ,df,CD,PA,oc,Wm,YJ,WJ,zm=be(()=>{DA=M(ln()),PD=M(me()),DD=M(z()),LD=M(le());B();MD=M(oe()),ID=100,CA=new Set,KJ=(0,MD.convertToMS)(LD.get(U.STORAGE_MAXTRANSACTIONQUEUETIME))||45e3;a(vD,"replicationConfirmation");oc=class e{static{a(this,"DatabaseTransaction")}#e;writes=[];lmdbDb;readTxn;readTxnRefCount;readTxnsUsed;validated=0;timestamp=0;overloadChecked;open=1;getReadTxn(){if(this.readTxnRefCount=(this.readTxnRefCount||0)+1,this.stale&&(this.stale=!1),this.readTxn)return this.readTxn.openTimer&&(this.readTxn.openTimer=0),this.readTxn;if(this.open===1)return this.readTxn=this.lmdbDb.useReadTransaction(),this.readTxnsUsed=1,this.readTxn.openTimer&&(this.readTxn.openTimer=0),CA.add(this),this.readTxn}useReadTxn(){return this.getReadTxn(),this.readTxn?.use(),this.readTxnsUsed++,this.readTxn}doneReadTxn(){this.readTxn&&(this.readTxn.done(),--this.readTxnsUsed===0&&(CA.delete(this),this.readTxn=null))}disregardReadTxn(){--this.readTxnRefCount===0&&this.readTxnsUsed===1&&this.doneReadTxn()}checkOverloaded(){if(df&&!this.overloadChecked&&performance.now()-CD>KJ)throw new PD.ServerError("Outstanding write transactions have too long of queue, please try again later",503);this.overloadChecked=!0}addWrite(t){if(this.open===0)throw new Error("Can not use a transaction that is no longer open");if(this.open===2){let r=new e;return r.addWrite(t),r.commit({})}else this.writes.push(t)}removeWrite(t){let r=this.writes.indexOf(t);r>-1&&(this.writes[r]=null)}commit(t={}){let r=this.timestamp;r||(r=this.timestamp=t.timestamp||(0,DA.getNextMonotonicTime)()),t.timestamp||(t.timestamp=r);let n=t.retries||0;if(this.validated<this.writes.length)try{let d=this.validated;this.validated=this.writes.length;for(let h=d;h<this.validated;h++)this.writes[h]?.validate?.(this.timestamp);let _;for(let h=d;h<this.validated;h++){let m=this.writes[h];m&&(m.before||m.beforeIntermediate)&&(_=!0)}if(_)return(async()=>{try{for(let h=0;h<2;h++){let m;for(let S=d;S<this.validated;S++){let g=this.writes[S];if(!g)continue;let A=g[h===0?"before":"beforeIntermediate"];if(A){let E=A();m?m.push?m.push(E):m=[m,E]:m=E}}m&&await(m.push?Promise.all(m):m)}}catch(h){throw this.abort(),h}return this.commit(t)})()}catch(d){throw this.abort(),d}n||this.doneReadTxn(),this.open=t?.doneWriting?2:1;let s,i=[],o=0;this.writes=this.writes.filter(d=>d);let c=a(d=>{d.commit(r,d.entry,n)},"doWrite"),l=a(()=>{let d=this.writes[o++];if(d)if(d.key){n>0&&(d.entry=d.store.getEntry(d.key));let _=d.store.ifVersion(d.key,d.entry?.version??null,l);s=s||_}else l();else for(let _ of this.writes)c(_)},"nextCondition"),u=this.lmdbDb;if(this.writes.length>0&&(u?.retryRisk&&(u.retryRisk*=.99),this.writes.length+(u?.retryRisk||0)<ID>>n?l():s=this.writes[0].store.transaction(()=>{for(let d of this.writes)d.entry=d.store.getEntry(d.key),c(d);return!0})),s)return df||(df=s,CD=performance.now(),df.then(()=>{df=null})),s.then(d=>{if(d){if(this.next&&i.push(this.next.commit(t)),t?.flush&&i.push(this.writes[0].store.flushed),this.replicatedConfirmation){let _=this.writes[0].store.rootStore.databaseName,h=this.writes[this.writes.length-1];PA&&h&&i.push(PA(_,h.store.getEntry(h.key).localTime,this.replicatedConfirmation))}return this.writes=[],this.next=null,Promise.all(i).then(()=>({txnTime:r}))}else return u&&(u.retryRisk=(u.retryRisk||0)+ID/2),t?t.retries=n+1:t={retries:1},this.commit(t)});let f={txnTime:r};if(this.next){let d=this.next?.commit(t);if(d?.then)return d?.then(_=>({txnTime:r,next:_}));f.next=d}return f}abort(){for(;this.readTxnsUsed>0;)this.doneReadTxn();this.open=0,this.writes=[]}getContext(){return this.#e}setContext(t){this.#e=t}},Wm=class extends oc{static{a(this,"ImmediateTransaction")}_timestamp;addWrite(t){super.addWrite(t),this.commit()}get timestamp(){return this._timestamp||(this._timestamp=(0,DA.getNextMonotonicTime)())}getReadTxn(){}},YJ=3e4;a(zJ,"startMonitoringTxns");zJ()});function bt(e,t,r){if(!t)t=e,e={};else if(!e)e={};else if(e?.transaction?.open===1&&typeof t=="function")return t(e.transaction);if(typeof t!="function")throw new Error("Callback function must be provided to transaction");let n=e.transaction=new oc;e.timestamp&&(n.timestamp=e.timestamp),e.replicatedConfirmation&&(n.replicatedConfirmation=e.replicatedConfirmation),n.setContext(e),e.resourceCache||(e.resourceCache=[]);let s;try{if(s=t(n),s?.then)return s.then(i,o)}catch(c){o(c)}return i(s);function i(c){let l=n.commit({doneWriting:!0});return l.then?l.then(()=>c):c}function o(c){throw n.abort({}),c}}var UD,ac=be(()=>{UD=M(ci());zm();a(bt,"transaction");(0,UD._assignPackageExport)("transaction",bt);bt.commit=function(e){let t=(e.getContext?.()||e)?.transaction;if(!t)throw new Error("No active transaction is available to commit");return t.commit()};bt.abort=function(e){let t=(e.getContext?.()||e)?.transaction;if(!t)throw new Error("No active transaction is available to abort");return t.abort()}});function MA(e,t,r,n,s,i,o,c){let l=e[0];if(t==="or"){let d=u(l);for(let h=1;h<e.length;h++){let m=e[h],S=u(m);d=d.concat(S)}let _=new Set;return d.filter(h=>{let m=h.key??h;return _.has(m)?!1:(_.add(m),!0)})}else{let d=u(l),_=f(e.slice(1),!0,l.estimated_count);return _.length>0?o(d,_):d}function u(d){return d.conditions?MA(d.conditions,d.operator,r,n,s,i,o,c):Wl(d,n,d.descending||s.reverse===!0,r,s.allowFullScan,c)}a(u,"executeCondition");function f(d,_,h){return d.map((m,S)=>{if(m.conditions){let E=m.operator==="or",T=f(m.conditions,!E,h);return E?(w,v)=>T.some(k=>k(w,v)):(w,v)=>T.every(k=>k(w,v))}let g=(m.attribute||m[0])===r.primaryKey,A=hf(m,r,i,c,g,h);return _&&S<d.length-1&&h&&(h=n4(r.primaryStore,m.estimated_count,h)),A}).filter(Boolean)}a(f,"mapConditionsToFilters")}function Wl(e,t,r,n,s,i){let o=e[0]??e.attribute,c=e[1]??e.value,l=e.comparator;if(c===void 0&&l!=="sort")throw new dn.ClientError(`Search condition for ${o} must have a value`);if(Array.isArray(o)){let E=o[0],T=fi(n.attributes,E);if(T.relationship){if(o.length<2)throw new dn.ClientError("Can not directly query a relational attribute, must query an attribute within the target table");let w=T.definition?.tableClass||T.elements?.definition?.tableClass,v=new Map,k=Wl({attribute:o.length>2?o.slice(1):o[1],value:c,comparator:l},t,r,w,s,v);if(T.relationship.to){i[o[0]]=v;let $=!!fi(w.attributes,T.relationship.to)?.elements;k=ZJ(k,T,w.primaryStore,$,v)}if(T.relationship.from){let $=a(W=>(W?.key!==void 0&&(W=W.key),Wl({attribute:T.relationship.from,value:W},t,r,n,s,v)),"searchEntry");T.elements?(i[o[0]]=v,k=e4(k,T,w.primaryStore,v,$)):k=k.flatMap($)}return k}else if(o.length===1)o=o[0];else throw new dn.ClientError("Unable to query by attribute "+JSON.stringify(o))}let u,f,d,_;c instanceof Date&&(c=c.getTime());let h;switch(vA[l]||l){case"lt":u=!0,f=c;break;case"le":u=!0,f=c,d=!0;break;case"gt":u=c,_=!0;break;case"ge":u=c;break;case"prefix":Array.isArray(c)?c[c.length-1]!=null&&(c=c.concat(null)):c=[c,null],u=c,f=c.slice(0),f[f.length-1]=di.MAXIMUM_KEY;break;case"starts_with":u=c.toString(),f=c+"\uFFFF";break;case"between":case"gele":case"gelt":case"gtlt":case"gtle":u=c[0],u instanceof Date&&(u=u.getTime()),f=c[1],f instanceof Date&&(f=f.getTime()),d=l==="gele"||l==="gtle"||l==="between",_=l==="gtlt"||l==="gtle";break;case"equals":case void 0:u=c,f=c,d=!0;break;case"ne":if(c===null){u=c,_=!0;break}case"sort":case"contains":case"ends_with":u=!0,h=!0;break;default:throw new dn.ClientError(`Unknown query comparator "${l}"`)}let m,S=o===n.primaryKey||o==null;if(typeof u=="string"&&u.length>as.MAX_SEARCH_KEY_LENGTH&&(u=u.slice(0,as.MAX_SEARCH_KEY_LENGTH)+as.OVERFLOW_MARKER,_=!1,m=hf(e,n,null,i,S)),typeof f=="string"&&f.length>as.MAX_SEARCH_KEY_LENGTH&&(f=f.slice(0,as.MAX_SEARCH_KEY_LENGTH)+as.OVERFLOW_MARKER,d=!0,m=m??hf(e,n,null,i,S)),r){let E=u;u=f,f=E,E=!_,_=!d,d=E}let g=S?n.primaryStore:n.indices[o];if(!g||g.isIndexing||h||c===null&&!g.indexNulls){if(s===!1&&!g)throw new dn.ClientError(`"${o}" is not indexed, can not search for this attribute`,404);if(s===!1&&h)throw new dn.ClientError(`Can not use ${l||"equal"} operator without combining with a condition that uses an index, can not search for attribute ${o}`,403);if(g?.isIndexing)throw new dn.ServerError(`"${o}" is not indexed yet, can not search for this attribute`,503);if(c===null&&g&&!g.indexNulls)throw new dn.ClientError(`"${o}" is not indexed for nulls, index needs to be rebuilt to search for nulls, can not search for this attribute`,400);if(m=m??hf(e,n,null,i,S),!m)throw new dn.ClientError(`Unknown search operator ${e.comparator}`)}let A={start:u,end:f,inclusiveEnd:d,exclusiveStart:_,values:!0,versions:S,transaction:t,reverse:r};if(S){let E=g.getRange(A).map(m?function({key:T,value:w}){return this?.isSync?w&&m(w)?T:jo.SKIP:new Promise((v,k)=>setImmediate(()=>{try{v(w&&m(w)?T:jo.SKIP)}catch($){k($)}}))}:T=>T.value==null&&!(T.metadataFlags&(fn|Jo))?jo.SKIP:T);return E.hasEntries=!0,E}else return g?g.getRange(A).map(m?function({key:E,value:T}){let w;return typeof E=="string"&&E.length>as.MAX_SEARCH_KEY_LENGTH?w=n.primaryStore.get(T):w={[o]:E},this.isSync?m(w)?T:jo.SKIP:new Promise((v,k)=>setImmediate(()=>{try{v(m(w)?T:jo.SKIP)}catch($){k($)}}))}:({value:E})=>E):n.primaryStore.getRange(r?{end:!0,transaction:t,reverse:!0}:{start:!0,transaction:t}).map(function({key:E,value:T}){return this.isSync?T&&m(T)?E:jo.SKIP:new Promise((w,v)=>setImmediate(()=>{try{w(T&&m(T)?E:jo.SKIP)}catch(k){v(k)}}))})}function fi(e,t){if(Array.isArray(t))if(t.length>1){let r=fi(e,t[0]),n=(r?.definition?.tableClass||r?.elements?.definition?.tableClass)?.attributes??r?.properties;return n?fi(n,t.slice(1)):void 0}else t=t.toString();else typeof t!="string"&&(t=t.toString());return e.find(r=>r.name===t)}function ZJ(e,t,r,n,s){return new e.constructor({[Symbol.iterator](){let i;return s.hasMappings=!0,{next(){if(!i){let c=t.relationship.to,l=a((u,f)=>{let d=s.get(u);d?d.push(f):s.set(u,d=[f])},"add_entry");for(let u of e){let f=u.value??r.get(u.key??u),d=f?.[c];if(d!=null&&!s.filters?.some(_=>!_(f)))if(n)for(let _=0;_<d.length;_++)l(d[_],u);else l(d,u)}return i=s.keys()[Symbol.iterator](),this.next()}let o=i.next();return o.done?o:{value:o.value}},return(){if(i?.return)return i.return()}}}})}function e4(e,t,r,n,s){return new e.constructor({[Symbol.iterator](){let i,o,c=new Set;return{next(){let l;if(o)for(;l=o.next(),!l.done;){let u=l.value;if(!c.has(u))return c.add(u),l}if(!i){let u=new Set;n.fromRecord=f=>f[t.relationship.from]?.filter?.(d=>u.has(d));for(let f of e){if(n.filters){let d=r.get(f);if(n.filters.some(_=>!_(d)))continue}u.add(f)}return i=u[Symbol.iterator](),this.next()}do{let u=i.next();return u.done?u:(o=s(u.value)[Symbol.iterator](),this.next())}while(!0)},return(){return o?.return?.()},throw(){return o?.throw?.()}}}})}function hf(e,t,r,n,s,i){let o=e.comparator,c=e[0]??e.attribute,l=e[1]??e.value;if(Array.isArray(c)){if(c.length===0)return()=>!0;if(c.length===1)c=c[0];else if(c.length>1){let f=c[0],d=fi(t.attributes,f),_=d.definition?.tableClass||d.elements.definition?.tableClass,h=n?.[f],m=hf({attribute:c.length>2?c.slice(1):c[1],value:l,comparator:o},_,r,h?.[f]?.joined,c[1]===_.primaryKey,i);if(!m)return;if(h){h.filters||(h.filters=[]),h.filters.push(m);return}let S=t.propertyResolvers?.[f],g,A=a((E,T)=>{let w,v;if(S){if(S.from&&m.idFilter){if(!g)if(m.idFilter.idSet?.size===1){for(let $ of m.idFilter.idSet)e={attribute:S.from,value:$};g=u(S.from,m.idFilter,!0,!0)}else g=u(S.from,m.idFilter,!1,!0);let k=g(E);return g.idFilter&&(A.idFilter=g.idFilter),k}v=S(E,r,T),w=v?.value}else w=E[f];return w?Array.isArray(w)?w.some(m):m(w,v):!1},"recordFilter");return A}}switch(l instanceof Date&&(l=l.getTime()),vA[o]||o){case as.SEARCH_TYPES.EQUALS:case void 0:return u(c,f=>f===l,!0);case"contains":return u(c,f=>f?.toString().includes(l));case"ends_with":return u(c,f=>f?.toString().endsWith(l));case"starts_with":return u(c,f=>typeof f=="string"&&f.startsWith(l),!0);case"prefix":return Array.isArray(l)?l[l.length-1]==null&&(l=l.slice(0,-1)):l=[l],u(c,f=>{if(!Array.isArray(f))return!1;for(let d=0,_=l.length;d<_;d++)if(f[d]!==l[d])return!1;return!0},!0);case"between":return l[0]instanceof Date&&(l[0]=l[0].getTime()),l[1]instanceof Date&&(l[1]=l[1].getTime()),u(c,f=>(0,di.compareKeys)(f,l[0])>=0&&(0,di.compareKeys)(f,l[1])<=0,!0);case"gt":return u(c,f=>(0,di.compareKeys)(f,l)>0);case"ge":return u(c,f=>(0,di.compareKeys)(f,l)>=0);case"lt":return u(c,f=>(0,di.compareKeys)(f,l)<0);case"le":return u(c,f=>(0,di.compareKeys)(f,l)<=0);case"ne":return u(c,f=>(0,di.compareKeys)(f,l)!==0,!1,!0);case"sort":return()=>!0;default:throw new dn.ClientError(`Unknown query comparator "${o}"`)}function u(f,d,_,h){let m;_=_&&!s&&t?.indices[f]&&i>3,_&&(e.estimated_count==null&&Qm(t)(e),m=e.estimated_count>>4,(isNaN(m)||m>=i)&&(_=!1));let S=0,g=3;function A(E){let T=E[f],w;if(typeof T!="object"||!T||h?w=d(T):Array.isArray(T)?w=T.some(d):T instanceof Date&&(w=d(T.getTime())),_&&(g++,!w&&!A.idFilter&&++S/g*(i-g)>m)){let v=Wl(e,r.transaction.getReadTxn(),!1,t).map(zl),k=new Set(v);A.idFilter=$=>k.has(zl($)),A.idFilter.idSet=k}return w}return a(A,"recordFilter"),s&&(A.idFilter=d),A}a(u,"attributeComparator")}function Qm(e){function t(r){if(r.estimated_count===void 0){if(r.conditions){let s;if(r.operator==="or"){s=0;for(let i of r.conditions)t(i),s+=i.estimated_count}else{s=1/0;for(let i of r.conditions)t(i),s=isFinite(s)?s*i.estimated_count/zi(e.primaryStore):i.estimated_count}return r.estimated_count=s,r.estimated_count}let n=r.comparator||r.search_type;if(n=vA[n]||n,n===as.SEARCH_TYPES.EQUALS||!n){let s=r[0]??r.attribute;if(s==null||s===e.primaryKey)r.estimated_count=1;else if(Array.isArray(s)&&s.length>1){let i=fi(e.attributes,s[0]),o=i.definition?.tableClass||i.elements.definition?.tableClass,c=Qm(o)({value:r.value,attribute:s.length>2?s.slice(1):s[1],comparator:"equals"}),l=e.indices[i.relationship.from];r.estimated_count=c+(l?c*zi(e.indices[i.relationship.from])/(zi(o.primaryStore)||1):c)}else{let i=e.indices[s];r.estimated_count=i?i.getValuesCount(r[1]??r.value):1/0}}else if(n==="contains"||n==="ends_with"||n==="ne"){let s=r[0]??r.attribute,i=e.indices[s];r.value===null&&n==="ne"?r.estimated_count=zi(e.primaryStore)-(i?i.getValuesCount(null):0):r.estimated_count=1/0}else n==="starts_with"||n==="prefix"?r.estimated_count=JJ*zi(e.primaryStore)+1:n==="between"?r.estimated_count=QJ*zi(e.primaryStore)+1:n==="sort"?r.estimated_count=zi(e.primaryStore)+1:r.estimated_count=jJ*zi(e.primaryStore)+1;typeof r.descending=="boolean"&&(r.estimated_count/=2)}return r.estimated_count}return a(t,"estimateConditionForTable"),t}function Jm(e){if(e)if(Qo=e,Kl.lastIndex=0,t4.test(e))try{let t=ff(new Yl,"");if(un!==Qo.length)throw new SyntaxError("Unable to parse query, unexpected end of query");return t}catch(t){throw t.statusCode=400,t.message=`Unable to parse query, ${t.message} at position ${un} in '${Qo}'`,t}else return new URLSearchParams(e)}function ff(e,t){let r=Kl,n,s,i,o,c,l=decodeURIComponent,u;for(;n=r.exec(Qo);){un=r.lastIndex;let[,f,d]=n;if(o){if(f)throw new SyntaxError(`expected operator, but encountered '${f}'`);o=!1,c=!1}else c=!0;let _;switch(d){case"=":if(s!=null){if(f.length<=2)i=f;else throw new SyntaxError(`invalid FIQL operator ${f}`);l=xD}else{if(l=decodeURIComponent,i="equals",!f)throw new SyntaxError("attribute must be specified before equality comparator");s=_f(f)}break;case"==":case"!=":case"<":case"<=":case">":case">=":case"===":case"!==":if(i=XJ[d],l=LA[i]?xD:decodeURIComponent,!f)throw new SyntaxError(`attribute must be specified before comparator ${d}`);s=_f(f);break;case"&=":case"|=":case"|":case"&":case"":case void 0:if(s==null){if(s===void 0)throw t?new SyntaxError(`expected '${t}', but encountered ${d[0]?"'"+d[0]+"'":"end of string"}}`):new SyntaxError(`no comparison specified before ${d?"'"+d+"'":"end of string"}`)}else{if(!e.conditions)throw new SyntaxError("conditions/comparisons are not allowed in a property list");let m={comparator:i,attribute:s||null,value:l(f)};if(i==="eq"&&BD(m,f),s===""){let S=e.conditions[e.conditions.length-1];S.chainedConditions=S.chainedConditions||[],S.chainedConditions.push(m),S.operator=u}else jm(e,u),e.conditions.push(m)}d==="&"?(u="and",s=void 0):d==="|"?(u="or",s=void 0):d==="&="?(u="and",s=""):d==="|="&&(u="or",s="");break;case",":if(e.conditions)throw new SyntaxError("conditions/comparisons are not allowed in a property list");e.push(_f(f)),s=void 0;break;case"(":Kl.lastIndex=un;let h=ff(f?[]:new Yl,")");switch(f){case"":jm(e,u),e.conditions.push(h);break;case"limit":switch(h.length){case 1:e.limit=+h[0];break;case 2:e.offset=+h[0],e.limit=h[1]-e.offset;break;default:throw new SyntaxError("limit must have 1 or 2 arguments")}break;case"select":Array.isArray(h[0])&&h.length===1&&!h[0].name?(e.select=h[0],e.select.asArray=!0):h.length===1?e.select=h[0]:h.length===2&&h[1]===""?e.select=h.slice(0,1):e.select=h;break;case"group-by":throw new SyntaxError("group by is not implemented yet");case"sort":e.sort=HD(h);break;default:throw new SyntaxError(`unknown query function call ${f}`)}Qo[un]===","?r.lastIndex=++un:o=!0,s=null;break;case"{":if(e.conditions)throw new SyntaxError("property sets are not allowed in a queries");if(!f)throw new SyntaxError("property sets must have a defined parent property name");Kl.lastIndex=un,_=ff([],"}"),_.name=f,e.push(_),Qo[un]===","?r.lastIndex=++un:o=!0;break;case"[":Kl.lastIndex=un,f?(_=ff(new Yl,"]"),_.name=f):_=ff(e.conditions?new Yl:[],"]"),e.conditions?(jm(e,u),e.conditions.push(_),s=null):e.push(_),Qo[un]===","?r.lastIndex=++un:o=!0;break;case")":case"]":case"}":if(t===d[0]){if(e.conditions){if(s){let m={comparator:i||"equals",attribute:s,value:l(f)};i==="eq"&&BD(m,f),jm(e,u),e.conditions.push(m)}else if(f)throw new SyntaxError("no attribute or comparison specified")}else(f||e.length>0&&c)&&e.push(_f(f));return e}else throw t?new SyntaxError(`expected '${t}', but encountered '${d[0]}'`):new SyntaxError(`unexpected token '${d[0]}'`);default:throw new SyntaxError(`unexpected operator '${d}'`)}if(t!==")"&&(r=s?r4:Kl,r.lastIndex=un),un===Qo.length)return e}if(t)throw new SyntaxError(`expected '${t}', but encountered end of string`)}function jm(e,t){if(e.conditions.length>0)if(e.operator){if(e.operator!==t)throw new SyntaxError("Can not mix operators within a condition grouping")}else e.operator=t}function _f(e){return e.indexOf(".")>-1?e.split(".").map(_f):decodeURIComponent(e)}function xD(e){if(e==="null")return null;if(e.indexOf(":")>-1){let[t,r]=e.split(":");if(t==="number")return r[0]==="$"?parseInt(r.slice(1),36):+r;if(t==="boolean")return r==="true";if(t==="date")return new Date(isNaN(r)?decodeURIComponent(r):+r);if(t==="string")return decodeURIComponent(r);throw new dn.ClientError(`Unknown type ${t}`)}return decodeURIComponent(e)}function BD(e,t){if(t.indexOf("*")>-1)if(t.endsWith("*"))e.comparator="starts_with",e.value=decodeURIComponent(t.slice(0,-1));else throw new dn.ClientError("wildcard can only be used at the end of a string")}function HD(e){let t=kD(e[0]);return e.length>1&&(t.next=HD(e.slice(1))),t}function kD(e){if(Array.isArray(e)){let t=kD(e[0]);return e[0]=t.attribute,t.attribute=e,t}if(typeof e=="string")switch(e[0]){case"-":return{attribute:e.slice(1),descending:!0};case"+":return{attribute:e.slice(1),descending:!1};default:return{attribute:e,descending:!1}}throw new SyntaxError(`Unknown sort type ${e}`)}function zl(e){return Array.isArray(e)?e.join("\0"):e}function zi(e){let t=Date.now();return(e.estimatedEntryCountExpires||0)<t&&(e.estimatedEntryCount=e.getStats().entryCount,e.estimatedEntryCountExpires=t+1e4),e.estimatedEntryCount}function n4(e,t,r){return t*r/zi(e)}var dn,as,di,jo,jJ,QJ,JJ,XJ,LA,vA,t4,Kl,r4,un,Qo,Yl,cc,mf=be(()=>{dn=M(me()),as=M(vt()),di=require("ordered-binary"),jo=require("lmdb");pf();jJ=.3,QJ=.1,JJ=.05,XJ={"<":"lt","<=":"le",">":"gt",">=":"ge","!=":"ne","==":"eq","===":"equals","!==":"not_equal"},LA={lt:!0,le:!0,gt:!0,ge:!0,ne:!0,eq:!0};a(MA,"executeConditions");a(Wl,"searchByIndex");a(fi,"findAttribute");a(ZJ,"joinTo");a(e4,"joinFrom");vA={eq:"equals",greater_than:"gt",greaterThan:"gt",greater_than_equal:"ge",greaterThanEqual:"ge",less_than:"lt",lessThan:"lt",less_than_equal:"le",lessThanEqual:"le",not_equal:"ne",notEqual:"ne",equal:"equals",sw:"starts_with",startsWith:"starts_with",ew:"ends_with",endsWith:"ends_with",ct:"contains",">":"gt",">=":"ge","<":"lt","<=":"le","...":"between"};a(hf,"filterByType");a(Qm,"estimateCondition");t4=/[()[\]|!<>.]|(=\w*=)/,Kl=/([^?&|=<>!([{}\]),]*)([([{}\])|,&]|[=<>!]*)/g,r4=/([^&|=[\]{}]+)([[\]{}]|[&|=]*)/g;a(Jm,"parseQuery");a(ff,"parseBlock");a(jm,"assignOperator");a(_f,"decodeProperty");a(xD,"typedDecoding");a(BD,"wildcardDecoding");a(HD,"toSortObject");a(kD,"toSortEntry");Yl=class{static{a(this,"Query")}constructor(){this.conditions=[]}[Symbol.iterator](){return this.conditions[Symbol.iterator]()}get(t){for(let r=0;r<this.conditions.length;r++){let n=this.conditions[r];if(n.attribute===t)return n.value}}};a(zl,"flattenKey");a(zi,"estimatedEntryCount");a(n4,"intersectionEstimate");cc=class{constructor(t){this.url=t}static{a(this,"SimpleURLQuery")}get(){}[Symbol.iterator](){return[][Symbol.iterator]()}}});var xA={};Ue(xA,{MultiPartId:()=>Zm,Resource:()=>$r,snake_case:()=>i4,transformForSelect:()=>ep});function i4(e){return e[0].toLowerCase()+e.slice(1).replace(/[a-z][A-Z][a-z]/g,t=>t[0]+"_"+t.slice(1))}function FD(e,t){if(lc=!1,e==="")return null;if(e=e.slice(1),t.splitSegments){if(e.indexOf("/")===-1)return e===""?(lc=!0,null):t.coerceId(decodeURIComponent(e));let r=e.split("/"),n=new Zm;for(let s=0;s<r.length;s++){let i=r[s];if(!i&&s===r.length-1){lc=!0;break}n[s]=t.coerceId(decodeURIComponent(i))}return n}else{if(e==="")return lc=!0,null;e[e.length-1]==="/"&&(lc=!0)}return t.coerceId(decodeURIComponent(e))}function Mn(e,t){n.reliesOnPrototype=!0;let r=t.hasContent;return n;function n(s,i,o){let c,l,u,f;if(r?(o?(f=i,o=o.getContext?.()||o):i?typeof s=="object"&&s&&(!Array.isArray(s)||typeof s[0]=="object")?(f=s,c=f[this.primaryKey]??null,o=i.getContext?.()||i):f=i:(f=s,s=void 0,c=f.getId?.()??f[this.primaryKey]),c===null&&(u=!0)):i?o=i.getContext?.()||i:s&&typeof s=="object"&&!Array.isArray(s)&&(o=s),c===void 0)if(typeof s=="object"&&s){if(l=s,typeof(c=s.url)=="string")if(this.directURLMapping)c=c.slice(1);else{let h=c.indexOf("?");if(h>-1){let S=this.parseQuery(c.slice(h+1));l?S&&(l=Object.assign(S,l)):l=S,c=c.slice(0,h)}let m=this.parsePath(c,o,l);m?.id!==void 0?(m.query&&(l?l=Object.assign(m.query,l):l=m.query),u=m.isCollection,c=m.id):c=m}else if(s[Symbol.iterator]){c=[],u=!0;for(let h of s){if(typeof h=="object"&&h)break;c.push(h)}c.length===0?c=null:(c.length===1&&(c=c[0]),l.slice&&(l=l.slice(c.length,l.length),l.length===0&&(l=null,u=!1)))}c===void 0&&(c=s.id??null,c==null&&(u=!0))}else c=s,l=new cc(c),c==null&&(u=!0);o||(o={});let d;if(l?.ensureLoaded!=null||l?.async||u?(d={...t},l?.ensureLoaded!=null&&(d.ensureLoaded=l.ensureLoaded),l?.async&&(d.async=l.async),u&&(d.isCollection=!0)):d=t,o.transaction){let h=this.getResource(c,o,d);return h.then?h.then(_):_(h)}else return bt(o,()=>{let h=this.getResource(c,o,d);return h.then?h.then(_):_(h)},d);function _(h){if(o.authorize){o.authorize=!1;let m=t.type==="read"?h.allowRead(o.user,l,o):t.type==="update"?h.doesExist?.()===!1?h.allowCreate(o.user,f,o):h.allowUpdate(o.user,f,o):t.type==="create"?h.allowCreate(o.user,f,o):h.allowDelete(o.user,l,o);if(m?.then)return m.then(S=>{if(!S)throw new Xm(o.user);return typeof f?.then=="function"?f.then(g=>e(h,l,o,g)):e(h,l,o,f)});if(!m)throw new Xm(o.user)}return typeof f?.then=="function"?f.then(m=>e(h,l,o,m)):e(h,l,o,f)}a(_,"authorizeActionOnResource")}}function vn(e,t){let r=new $D.ClientError(`The ${e.constructor.name} does not have a ${t} method implemented`,405);r.allow=[],r.method=t;for(let n of["get","put","post","delete","query","move","copy"])typeof e[n]=="function"&&r.allow.push(n);throw r}function UA(e,t,r){let n=e.getRecord?.();if(n){let s=e.getChanges?.();return i=>{let o,c;return e.hasOwnProperty(i)&&typeof(o=e[i])!="function"?o:s&&i in s?s[i]:(c=t?.[i])?c(e,r):n[i]}}else return t?s=>{let i=t[s];return i?i(e,r):e[s]}:s=>e[s]}function ep(e,t){let r=t.propertyResolvers,n=t.getContext?.(),s;if(typeof e=="string")return a(function o(c){return c.then?c.then(o):Array.isArray(c)?c.map(o):UA(c,r,n)(e)},"transform");if(typeof e=="object"){if(e.asArray)return a(function c(l){if(l.then)return l.then(c);if(Array.isArray(l))return l.map(c);let u=[],f=i(UA(l,r,n));for(let d of e)u.push(f(d));return u},"transform");let o=e.forceNulls;return a(function c(l){if(l.then)return l.then(c);if(Array.isArray(l))return l.map(_=>_&&typeof _=="object"?c(_):_);let u={},f=i(UA(l,r,n)),d;for(let _ of e){let h=f(_);h===void 0&&o&&(h=null),h?.then?(d||(d=[]),d.push(h.then(m=>u[_.name||_]=m))):u[_.name||_]=h}return d?Promise.all(d).then(()=>u):u},"transform")}else throw new Error("Invalid select argument type "+typeof e);function i(o){return c=>{if(typeof c=="string")return o(c);if(typeof c=="object")if(c.name){s||(s={});let l=s[c.name];if(!l){let f=r[c.name]?.definition?.tableClass;l=s[c.name]=ep(c.select||c,f)}let u=o(c.name);return l(u)}else return o(c);else return c}}a(i,"handleProperty")}var qD,GD,$D,s4,$r,Xm,lc,Zm,Xo=be(()=>{qD=require("crypto");Vl();GD=M(ci()),$D=M(me());ac();mf();s4={json:"application/json",cbor:"application/cbor",msgpack:"application/x-msgpack",csv:"text/csv"},$r=class{static{a(this,"Resource")}#e;#t;#n;static transactions;static directURLMapping=!1;constructor(t,r){this.#e=t;let n=r?.getContext?r.getContext()??null:void 0;this.#t=n!==void 0?n:r||null}static get=Mn(function(t,r,n,s){let i=t.get?.(r);if(i?.then)return i.then(o);return o(i);function o(c){let l;if((l=r?.select)&&c!=null&&!c.selectApplied){let u=ep(l,t.constructor);return typeof c?.map=="function"?c.map(u):u(c)}return c}},{type:"read",letItLinger:!0,ensureLoaded:!0,async:!0});static put=Mn(function(t,r,n,s){if(Array.isArray(s)&&t.#n){let i=[],o=n.authorize;for(let c of s){let l=t.constructor,u=l.getResource(c[l.primaryKey],n,{async:!0});u.then?i.push(u.then(f=>f.put(c,n))):i.push(u.put(c,n))}return Promise.all(i)}return t.put?t.put(s,r):vn(t,"put")},{hasContent:!0,type:"update"});static patch=Mn(function(t,r,n,s){return t.patch?t.patch(s,r):vn(t,"patch")},{hasContent:!0,type:"update"});static delete=Mn(function(t,r,n,s){return t.delete?t.delete(r):vn(t,"delete")},{hasContent:!1,type:"delete"});static getNewId(){return(0,qD.randomUUID)()}static create(t,r,n){let s;return t==null?s=r?.[this.primaryKey]??this.getNewId():Array.isArray(t)&&typeof t[0]!="object"?s=r?.[this.primaryKey]??[...t,this.getNewId()]:typeof t!="object"?s=r?.[this.primaryKey]??[t,this.getNewId()]:(s=t?.[this.primaryKey]??this.getNewId(),n=r||{},r=t),n||(n={}),bt(n,()=>{let i=new this(s,n),o=i.update?i.update(r,!0):vn(i,"update");return n.newLocation=s,n.createdResource=!0,o?.then?o.then(()=>i):i})}static invalidate=Mn(function(t,r,n,s){return t.invalidate?t.invalidate(r):vn(t,"delete")},{hasContent:!1,type:"update"});static post=Mn(function(t,r,n,s){return t.#e!=null&&t.update?.(),t.post(s,r)},{hasContent:!0,type:"create"});static connect=Mn(function(t,r,n,s){return t.connect?t.connect(s,r):vn(t,"connect")},{hasContent:!0,type:"read"});static subscribe=Mn(function(t,r,n,s){return t.subscribe?t.subscribe(r):vn(t,"subscribe")},{type:"read"});static publish=Mn(function(t,r,n,s){return t.#e!=null&&t.update?.(),t.publish?t.publish(s,r):vn(t,"publish")},{hasContent:!0,type:"create"});static search=Mn(function(t,r,n,s){let i=t.search?t.search(r):vn(t,"search"),o=n.select;if(o&&n.hasOwnProperty("select")&&i!=null&&!i.selectApplied){let c=ep(o,t.constructor);return i.map(c)}return i},{type:"read"});static query=Mn(function(t,r,n,s){return t.search?t.search(s,r):vn(t,"search")},{hasContent:!0,type:"read"});static copy=Mn(function(t,r,n,s){return t.copy?t.copy(s,r):vn(t,"copy")},{hasContent:!0,type:"create"});static move=Mn(function(t,r,n,s){return t.move?t.move(s,r):vn(t,"move")},{hasContent:!0,type:"delete"});async post(t){if(this.#n)return(await this.constructor.create(this.#e,t,this.#t)).#e;vn(this,"post")}static isCollection(t){return t&&t.#n}get isCollection(){return this.#n}static coerceId(t){return t}static parseQuery(t){return Jm(t)}static parsePath(t,r,n){let s=t.indexOf(".");if(s>-1){let o=t.slice(s+1),c=r?.headers&&s4[o];if(c)r.requestedContentType=c,t=t.slice(0,s);else if(this.attributes?.find(l=>l.name===o))if(t=t.slice(0,s),n)n.property=o;else return{query:{property:o},id:FD(t,this),isCollection:lc}}let i=FD(t,this);return lc?{id:i,isCollection:!0}:i}static getResource(t,r,n){let s,i=r.getContext?.(),o;typeof r.isCollection=="boolean"&&r.hasOwnProperty("isCollection")?o=r.isCollection:o=n?.isCollection;let c=o&&this.Collection||this;if(i||(i=i===void 0?r:{}),i.transaction){let l;if(i.resourceCache?l=i.resourceCache:l=i.resourceCache=[],l.asMap){let u=l.asMap.get(t);if(s=u?.find(f=>f.constructor===c),s)return s;u||l.asMap.set(t,u=[]),u.push(s=new c(t,i))}else{if(s=l.find(u=>u.#e===t&&u.constructor===c),s)return s;if(l.push(s=new c(t,i)),l.length>10){let u=new Map;for(let f of l){let d=f.#e,_=u.get(d);_?_.push(f):u.set(d,[f])}i.resourceCache.length=0,i.resourceCache.asMap=u}}}else s=new c(t,i);return o&&(s.#n=!0),s}subscribe(t){return new Ln}connect(t,r){return r?.subscribe!==!1?this.subscribe?.(r):new Ln}allowRead(t){return t?.role.permission.super_user}allowUpdate(t){return t?.role.permission.super_user}allowCreate(t){return t?.role.permission.super_user}allowDelete(t){return t?.role.permission.super_user}getId(){return this.#e}getContext(){return this.#t}};(0,GD._assignPackageExport)("Resource",$r);a(i4,"snake_case");Xm=class extends Error{static{a(this,"AccessError")}constructor(t){t?(super("Unauthorized access to resource"),this.statusCode=403):(super("Must login"),this.statusCode=401)}};a(FD,"pathToId");Zm=class extends Array{static{a(this,"MultiPartId")}toString(){return this.join("/")}};a(Mn,"transactional");a(vn,"missingMethod");a(UA,"selectFromObject");a(ep,"transformForSelect")});var Zo,BA=be(()=>{Zo=class{constructor(t){this.error=t}static{a(this,"ErrorResource")}isError=!0;allowRead(){throw this.error}allowUpdate(){throw this.error}allowCreate(){throw this.error}allowDelete(){throw this.error}getId(){throw this.error}getContext(){throw this.error}get(){throw this.error}post(){throw this.error}put(){throw this.error}delete(){throw this.error}connect(){throw this.error}getResource(){return this}publish(){throw this.error}subscribe(){throw this.error}}});var jl={};Ue(jl,{server:()=>Ke});var VD,Ke,Pr=be(()=>{VD=M(ci()),Ke={};(0,VD._assignPackageExport)("server",Ke)});var WD={};Ue(WD,{Resources:()=>tp,keyArrayToString:()=>Ql,resetResources:()=>o4,resources:()=>cs});function o4(){return cs=new tp,Ke.resources=cs,cs}function Ql(e){return Array.isArray(e)?e[e.length-1]===null?e.slice(0,-1).join("/")+"/":e.join("/"):e}var KD,YD,tp,cs,Jl=be(()=>{ac();BA();KD=M(z()),YD=M(me());Pr();tp=class extends Map{static{a(this,"Resources")}isWorker=!0;loginPath;set(t,r,n,s){if(!r)throw new Error("Must provide a resource");t.startsWith("/")&&(t=t.replace(/^\/+/,""));let i={Resource:r,path:t,exportTypes:n,hasSubPaths:!1,relativeURL:""},o=super.get(t);if(o&&(o.Resource.databaseName!==r.databaseName||o.Resource.tableName!==r.tableName)&&!s){let c=new YD.ServerError(`Conflicting paths for ${t}`);KD.default.error(c),i.Resource=new Zo(c)}super.set(t,i);for(let[c,l]of this){let u=2;for(;(u=c.indexOf("/",u))>-1;){let f=this.get(c.slice(0,u));f&&(f.hasSubPaths=!0),u+=2}}}getMatch(t,r){let n=2,s=0,i,o=t.length;for(;n<o;){s=n,n=t.indexOf("/",n),n===-1&&(n=o);let u=n===o?t:t.slice(0,n),f=this.get(u),d=-1;if(!f&&n===o&&(d=u.indexOf("?",s),d!==-1)){let _=u.slice(0,d);f=this.get(_)}if(f&&(!r||f.exportTypes?.[r]!==!1)){if(f.relativeURL=t.slice(d!==-1?d:n),!f.hasSubPaths)return f;i=f}n+=2}if(i)return i;let c=t.indexOf("?"),l=c>-1?t.slice(0,c):t;return i=this.get(l),!i&&l.indexOf(".")>-1&&(i=this.get(l.split(".")[0])),i&&(!r||i.exportTypes?.[r]!==!1)?i.relativeURL=c>-1?t.slice(c):"":i||(i=this.get(""),i&&(!r||i.exportTypes?.[r]!==!1)&&(t.charAt(0)!=="/"&&(t="/"+t),i.relativeURL=t)),i}getResource(t,r){let n=this.getMatch(t);if(n)return t=n.relativeURL,n.Resource.getResource(this.pathToId(t,n.Resource),r)}call(t,r,n){return bt(r,async()=>{let s=this.getMatch(t);if(s)return t=s.relativeURL,n(s.Resource,s.path,t)})}setRepresentation(t,r,n){}};a(o4,"resetResources");a(Ql,"keyArrayToString")});var HA=P((mye,zD)=>{if(__filename.endsWith("dev.js")){let e=require("fast-glob"),{tmpdir:t}=require("node:os"),{relative:r,join:n}=require("node:path"),{existsSync:s,statSync:i,readFileSync:o,writeFileSync:c,unlinkSync:l}=require("node:fs"),{isMainThread:u}=require("node:worker_threads"),{spawnSync:f,spawn:d}=require("node:child_process");process.setSourceMapsEnabled(!0);let{PACKAGE_ROOT:_}=pt(),h=["bin","components","dataLayer","resources","server","sqlTranslator","upgrade","utility","validation"],m="ts-build";if(u){let A=!1,E=!1;if(E=s(n(_,m))){let T=new Set;e.sync(h.map(w=>`${w}/**/*.ts`),{cwd:_}).forEach(w=>{let v=0,k=0;try{T.add(w),v=i(n(_,w)).mtimeMs-5e3,k=i(n(_,m,w.replace(/.ts$/,".js"))).mtimeMs}catch{}v>k&&(A=!0)}),e.sync(h.map(w=>`${w}/**/*.js`),{cwd:n(_,m)}).forEach(w=>{if(!T.has(w.replace(/.js$/,".ts")))try{l(n(_,m,w))}catch{}})}else A=!0;if(A){console.log("Compiling TypeScript...");let T=f("npx",["tsc"],{cwd:_});if(T.stdout?.length&&console.log(T.stdout.toString()),T.stderr?.length&&console.log(T.stderr.toString()),E){let w=n(t(),"harperdb-tsc.pid"),v=!1;if(s(w))try{process.kill(+o(w,"utf8"),0),v=!0}catch{}if(!v){console.log("Starting background TypeScript compilation...");let k=d("npx",["tsc","--watch"],{detached:!0,cwd:_,stdio:"ignore"});k.on("error",$=>{console.error("Error trying to compile TypeScript",$)}),k.pid&&c(w,String(k.pid),"utf-8"),k.unref()}}}}let S=zD.constructor,g=S._findPath;S._findPath=function(A,E,T){if(A.startsWith(".")&&!T&&E.length===1&&E[0].startsWith(_)&&!E[0].includes("node_modules")){let w=r(_,E[0]),v;w.startsWith(m)?v=n(_,r(m,w)):v=n(_,m,w);let k=n(v,A),$=k+".js";if(s($))return $;if(k.includes(".")&&s(k))return k}return g(A,E,T)}}});var qA={};Ue(qA,{loadGQLSchema:()=>l4,start:()=>FA,startOnMainThread:()=>c4});function FA({ensureTable:e}){return{handleFile:t,setupFile:t};async function t(r,n,s,i){let{parse:o,Source:c,Kind:l,NamedTypeNode:u,StringValueNode:f}=await import("graphql"),d=o(new c(r.toString(),s)),_=new Map,h=[],m;for(let A of d.definitions)switch(A.kind){case l.OBJECT_TYPE_DEFINITION:let k=function(W){if(W.kind==="NonNullType"){let Y=k(W.type);return Y.nullable=!1,Y}if(W.kind==="ListType")return{type:"array",elements:k(W.type)};let se={type:W.name?.value};return Object.defineProperty(se,"location",{value:W.loc.startToken}),se};a(k,"getProperty");let E=A.name.value,T=[],w={table:null,database:null,properties:T};_.set(E,w);for(let W of A.directives){if(W.name.value==="table"){for(let se of W.arguments)w[se.name.value]=se.value.value;w.schema&&(w.database=w.schema),w.table||(w.table=E),w.audit&&(w.audit=w.audit!=="false"),w.attributes=w.properties,h.push(w)}if(W.name.value==="sealed"&&(w.sealed=!0),W.name.value==="splitSegments"&&(w.splitSegments=!0),W.name.value==="replicate"&&(w.replicate=!0),W.name.value==="export"){w.export=!0;for(let se of W.arguments)typeof w.export!="object"&&(w.export={}),w.export[se.name.value]=se.value.value}}let v=!1,$={};for(let W of A.fields){let te=k(W.type);te.name=W.name.value,T.push(te),$[te.name]=void 0;for(let se of W.directives){let Y=se.name.value;if(Y==="primaryKey")v?console.warn("Can not define two attributes as a primary key at",se.loc):(te.isPrimaryKey=!0,v=!0);else if(Y==="indexed")te.indexed=!0;else if(Y==="computed"){for(let ne of se.arguments||[])if(ne.name.value==="from"){let ue=ne.value.value;te.computed={from:g(ue,ne,$)},te.version==null&&(te.version=ue)}else ne.name.value==="version"&&(te.version=ne.value.value);te.computed=te.computed||!0}else if(Y==="relationship"){let ne={};for(let ue of se.arguments)ne[ue.name.value]=ue.value.value;te.relationship=ne}else if(Y==="createdTime")te.assignCreatedTime=!0;else if(Y==="updatedTime")te.assignUpdatedTime=!0;else if(Y==="expiresAt")te.expiresAt=!0;else if(Y==="allow"){let ne=te.authorizedRoles=[];for(let ue of se.arguments)ue.name.value==="role"&&ne.push(ue.value.value)}else server.knownGraphQLDirectives.includes(Y)&&console.warn(`@${Y} is an unknown directive, at`,se.loc)}}w.type=E,E==="Query"&&(m=w)}function S(A){let E=_.get(A.type);E?(Object.defineProperty(A,"properties",{value:E.properties}),Object.defineProperty(A,"definition",{value:E})):A.type==="array"?S(A.elements):a4.includes(A.type)||(0,QD.getWorkerIndex)()===0&&console.error(`The type ${A.type} is unknown at line ${A.location.line}, column ${A.location.column}, in ${s}`)}a(S,"connectPropertyType");for(let A of _.values())for(let E of A.properties)S(E);for(let A of h)A.tableClass=e(A),A.export&&(A.export.name===""?i.set((0,kA.dirname)(n),A.tableClass):i.set((0,kA.dirname)(n)+"/"+(A.export.name||A.type),A.tableClass,A.export));function g(A,E,T){return new jD.Script(`function computed(attributes) { return function(record) { with(attributes) { with (record) { return ${A}; } } } } computed;`,{filename:s,lineOffset:E.loc.startToken.line-1,columnOffset:E.loc.startToken.column}).runInThisContext()(T)}a(g,"createComputedFrom")}}var kA,jD,QD,a4,c4,l4,JD=be(()=>{kA=require("path"),jD=require("node:vm");ve();QD=M(Ze()),a4=["ID","Int","Float","Long","String","Boolean","Date","Bytes","Any","BigInt","Blob"];server.knownGraphQLDirectives&&(server.knownGraphQLDirectives=["table","sealed","export","primaryKey","indexed","computed","relationship","createdTime","updatedTime","expiresAt","allow"]);a(FA,"start");c4=FA,l4=FA({ensureTable:dt}).handleFile});var sL={};Ue(sL,{parse:()=>$A,streamAsJSON:()=>Ef,stringify:()=>uc});function Ef(e){return new GA({value:e})}function XD(e){return console.error(e),JSON.stringify(e.toString())}function ZD(e,t,r){return e?.then?r?e.then(t,r):e.then(t):t(e)}function uc(e){try{return JSON.stringify(e)??"null"}catch(t){if(t===rL)return nL(e);if(t.resolution)return t.resolution.then(()=>uc(e));throw t}}function nL(e){let t=typeof e;if(t==="object"){if(e===null)return"null";e.toJSON&&(e=e.toJSON());let r;if(Array.isArray(e)){r="[";for(let n=0;n<e.length;n++)n>0&&(r+=","),r+=nL(e[n]);return r+"]"}else{r="{";let n=!0;for(let s in e)n?n=!1:r+=",",r+=JSON.stringify(s)+":"+uc(e[s]);return r+"}"}}else{if(t==="string")return JSON.stringify(e);if(t==="undefined")return"null"}return e.toString()}function $A(e){return e?.length>0?(typeof e!="string"&&(e=e.toString()),f4.test(e)?u4.parse(e):JSON.parse(e)):null}var eL,tL,u4,d4,rL,GA,f4,VA=be(()=>{eL=require("stream"),tL=M(require("json-bigint-fixes")),u4=(0,tL.default)({useNativeBigInt:!0}),d4=1e4,rL={message:"Cannot serialize BigInt to JSON"};BigInt.prototype.toJSON=function(){throw rL};a(Ef,"streamAsJSON");GA=class extends eL.Readable{static{a(this,"JSONStream")}constructor(t){super(t),this.buffer=[],this.bufferSize=0,this.iterator=this.serialize(t.value,!0),this.activeIterators=[]}*serialize(t){if(t&&typeof t=="object"){let r=t[Symbol.asyncIterator],n=t[Symbol.iterator];if((n||r)&&!t.then){yield"[";let s=!0;if((r||n)&&!(t instanceof Array)){let i=r?t[Symbol.asyncIterator]():t[Symbol.iterator]();this.activeIterators.push(i);let o;for(;;){try{o=i.next(),o.then&&(yield o.then(c=>(o=c,""),c=>(o={done:!1,value:{error:c.toString()}},i={next:a(()=>({done:!0}),"next")},"")))}catch(c){o={done:!1,value:{error:c.toString()}},i={next:a(()=>({done:!0}),"next")}}if(o.done){this.activeIterators.splice(this.activeIterators.indexOf(i),1),yield"]";return}else s?s=!1:yield",",yield*this.serialize(o.value)}}for(let i of t)s?s=!1:yield",",yield*this.serialize(i);yield"]";return}if(t.then)try{yield t.then(s=>this.serialize(s),XD)}catch(s){yield XD(s)}else yield uc(t)}else yield uc(t)}_read(){if(!this._amReading){if(this._amReading=!0,this.done)return this.push(null);ZD(this.readIterator(this.iterator),t=>{t?(this.done=!0,this.push(null)):this._amReading=!1},t=>{console.error(t),this.done=!0,this.push(t.toString()),this.push(null)})}}push(t){return t===null||t instanceof Buffer?(this.bufferSize>0&&this.flush(),super.push(t)):(this.bufferSize+=t.length||t.toString().length,this.buffer.push(t),this.bufferSize>d4?this.flush():!0)}flush(){let t=super.push(this.buffer.join(""));return this.buffer=[],this.bufferSize=0,t}readIterator(t){try{let r;if(t.childIterator)return ZD(this.readIterator(t.childIterator),n=>{if(n)return t.childIterator=null,this.readIterator(t)});do{let n=t.next();if(n.done)return!0;if(r=n.value,r==null)r="null";else{if(r.then)return this.flush(),Promise.resolve(r).then(s=>{if(s&&typeof s.return=="function")return t.childIterator=s,this.readIterator(t);if(this.push(s+""))return this.readIterator(t)});if(typeof r.return=="function")return t.childIterator=r,this.readIterator(t)}}while(this.push(r))}catch(r){return console.error(r),this.push(r.toString()),this.push(null),!0}}_destroy(t,r){for(let n of this.activeIterators)t?n.throw(t):n.return();r()}};a(XD,"handleError");a(ZD,"when");a(uc,"stringify");a(nL,"jsStringify");f4=/[[,:]\s*-?\d{16,}/;a($A,"parse")});var _i=P(np=>{var rp=z();for(let e of["trace","debug","info","warn","error","fatal","notify"])rp.logsAtLevel(e)&&(np[e]=rp[e]);np.loggerWithTag=e=>rp.loggerWithTag(e,!0);np.setLogLevel=rp.setLogLevel});var hp={};Ue(hp,{Blob:()=>hi,blobsWereEncoded:()=>fc,databasePaths:()=>YA,decodeBlobsWithWrites:()=>fp,decodeFromDatabase:()=>_c,decodeWithBlobCallback:()=>_p,deleteBlob:()=>lp,deleteBlobsInObject:()=>ea,deleteRootBlobPathsForDB:()=>zA,encodeBlobsAsBuffers:()=>R4,encodeBlobsWithFilePath:()=>dp,findBlobsInObject:()=>Zl,getFileId:()=>up,getFilePathForBlob:()=>hL,getRootBlobPathsForDB:()=>Af,setDeletionDelay:()=>p4});function dL(){}function lp(e){let t=hL(e);t&&setTimeout(()=>{(0,je.unlink)(t,r=>{r&&ji.default.debug?.("Error trying to remove blob file",r)})},fL)}function p4(e){fL=e}function _L(e){let t=_n.get(e);if(!t)t={storageIndex:0,fileId:null,store:hn},_n.set(e,t);else{if(t.saving)return t;t.store=hn}return g4(t),t.source?KA(e,t.source,t):t.contentBuffer?E4(e,t):KA(e,Sf.Readable.from(e.stream()),t),t}function KA(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,je.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(h4),h=(0,ap.createDeflate)(),t.pipe(h).pipe(d)):(_||d.write(_4),t.pipe(d)),t.on("error",S);function m(g){let A=BigInt(g),E=new Uint8Array(pr),T=new DataView(E.buffer);return A|=BigInt(o?WA:uL)<<48n,T.setBigInt64(0,A),E}a(m,"createHeader");function S(g){i.unlock(f,0);let A=d.fd;g?(A&&(0,je.close)(A),u(g)):c?(0,je.fdatasync)(A,E=>{E&&u(E),l(),(0,je.close)(A)}):(l(),(0,je.close)(A))}a(S,"finished"),d.on("error",S).on("finish",()=>{if(_)S();else{let g=h?h.bytesWritten:d.bytesWritten-pr;e.size=g,(0,je.write)(d.fd,m(g),0,pr,0,S)}})}),e}function up(e){return _n.get(e)?.fileId}function hL(e){let t=_n.get(e);return t?.fileId&&Tf(t)}function Af(e){if(!e)throw new Error("No store specified, can not determine blob storage path");let t=YA.get(e);if(!t){if(!e.databaseName)return ji.default.warn?.("No database name specified, can not determine blob storage path"),[];let r=(0,cp.get)(U.STORAGE_BLOBPATHS);r?t=r.map(n=>(0,Ji.join)(n,e.databaseName)):t=[(0,Ji.join)((0,cp.getHdbBasePath)(),"blobs",e.databaseName)],YA.set(e,t)}return t}async function zA(e){let t=Af(e);t&&await Promise.all(t.map(r=>mL(r)))}async function mL(e){if((0,je.existsSync)(e)){for(let t of await(0,Bs.readdir)(e,{withFileTypes:!0}))if(t.isDirectory())await mL((0,Ji.join)(e,t.name));else try{await(0,Bs.unlink)((0,Ji.join)(e,t.name))}catch(r){ji.default.warn?.("Error deleting file",r)}try{await(0,Bs.rmdir)(e)}catch(t){ji.default.warn?.("Error deleting directory",t)}}}function Tf({storageIndex:e,fileId:t,store:r}){let n=Af(r);return(0,Ji.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 E4(e,t){let r=t.contentBuffer,n=r.length;if(!(n<lL))return e.size=n,KA(e,Sf.Readable.from([r]),t)}function g4(e){let t=Af(e.store),r=S4(),n=t?.length>1?T4(t,r):0,s=r.toString(16);e.storageIndex=n,e.fileId=s;let i=Tf(e),o=(0,Ji.dirname)(i);(0,je.existsSync)(o)||(0,cL.ensureDirSync)(o),e.filePath=i}function S4(){let e=aL.get(hn);if(!e){let t=0,r=Af(hn);for(let n of r){let s=0;for(let i=0;i<3;i++){s=s*4096;let o=0;if((0,je.existsSync)(n))for(let c of(0,je.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,Ji.join)(n,o.toString(16))}t=Math.max(t,s)}e=new BigInt64Array([BigInt(t)+1n]),e=new BigInt64Array(hn.getUserSharedBuffer("blob-file-id",e.buffer)),aL.set(hn,e)}return Number(Atomics.add(e,0,1n))}function T4(e,t){let r=Date.now();if(!e.frequencyTable){e.lastUpdated=0;let s=new Array(op);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,A4(e)),e.frequencyTable[t%op]}async function A4(e){if(!Bs.statfs)return;let t=await Promise.all(e.map(async(s,i)=>{let o=await(0,Bs.statfs)(s),c=o.bavail*o.bsize;return Math.pow(c,.8)})),r=new Array(op),n=t.map(s=>1/s);for(let s=0;s<op;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 dp(e,t,r){Xl=t,hn=r,fc=!1;try{return e()}finally{Xl=void 0,hn=void 0}}function R4(e){Dr=[];let t;try{t=e()}catch(n){throw Dr=void 0,n}let r=Dr.length<2?Dr[0]:Promise.all(Dr);return Dr=void 0,r?r.then(()=>e()):t}function fp(e,t){try{Dr=[],dc=t,e()}catch(n){throw dc=void 0,Dr=void 0,n}dc=void 0;let r=Dr.length<2?Dr[0]:Promise.all(Dr);return Dr=void 0,r}function _p(e,t,r){hn=r;try{return dc=t,e()}finally{dc=void 0}}function _c(e,t){return hn=t,e()}function ea(e){Zl(e,t=>{lp(t)})}function Zl(e,t){if(e instanceof hi)t(e);else if(Array.isArray(e))for(let r of e)typeof r=="object"&&r&&Zl(r,t);else if(e&&typeof e=="object"&&!e[Symbol.iterator])for(let r in e){let n=e[r];typeof n=="object"&&n&&Zl(e[r],t)}}function y4(){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 Qi,Bs,je,ap,Sf,cL,cp,Ji,ji,lL,pr,uL,WA,iL,_4,h4,oL,_n,dc,hi,Xl,Dr,hn,fc,gf,sp,m4,ip,fL,YA,aL,op,ls=be(()=>{Qi=require("msgpackr"),Bs=require("node:fs/promises"),je=require("node:fs"),ap=require("node:zlib"),Sf=require("node:stream"),cL=require("fs-extra"),cp=M(le());B();Ji=require("path"),ji=M(_i());Xi();lL=8192,pr=8,uL=0,WA=1,iL=255,_4=new Uint8Array([0,uL,255,255,255,255,255,255]),h4=new Uint8Array([0,WA,255,255,255,255,255,255]),oL=0xffffffffffff,_n=new WeakMap,hi=global.Blob||y4(),fc=!1,gf=new Uint8Array(8),sp=new DataView(gf.buffer),m4=6e4;a(dL,"InstanceOfBlobWithNoConstructor");dL.prototype=hi.prototype;ip=class e extends dL{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=_n.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):(QA()&&jA(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=_n.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=Tf(t),o,c=a(async()=>{let l,u=pr;try{if(l=await(0,Bs.readFile)(i),l.length>=pr){l.copy(gf,0,0,pr);let d=sp.getBigUint64(0);if(Number(d>>48n)===iL)throw new Error("Error in blob: "+buffer.subarray(pr));if(u=Number(d&0xffffffffffffn),u<n&&(u=n),u<oL&&(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]===WA?new Promise((d,_)=>{(0,ap.deflate)(l.subarray(pr),(h,m)=>{h?_(h):d(f(m))})}):f(l.subarray(pr))},"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=_n.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=Tf(t),o,c=0,l=0,u,f,d,_=!1,h=this;return new ReadableStream({start(){let S=1e3,g=a((A,E)=>{(0,je.open)(i,"r",(T,w)=>{if(T){if(T.code==="ENOENT"&&d!==!1&&(ji.default.debug?.("File does not exist yet, waiting for it to be created",i,S),S-- >0))return setTimeout(()=>{m(),g(A,E)},20).unref();E(T),h.#e?.forEach(v=>v(T))}else o=w,A(w)})},"openFile");return new Promise(g)},pull:a(S=>{let g=0,A=100;return new Promise(a(function E(T,w){function v($){(0,je.close)(o),clearTimeout(f),u&&u.close(),w($),h.#e?.forEach(W=>W($))}a(v,"onError");let k=Buffer.allocUnsafe(262144);(0,je.read)(o,k,0,k.length,c,($,W,te)=>{if(l+=W,$)return v($);if(c===0){if(W<pr){A-- >0&&d!==!1?(m(),ji.default.debug?.("File was empty, waiting for data to be written",i,A),setTimeout(()=>E(T,w),20).unref()):(ji.default.debug?.("File was empty, throwing error",i,A),w(new Error(`Blob ${t.fileId} was empty`)));return}te.copy(gf,0,0,pr);let se=sp.getBigUint64(0);if(Number(se>>48n)===iL)return v(new Error("Error in blob: "+te.subarray(pr)));if(g=Number(se&0xffffffffffffn),g<oL&&h.size!==g&&(h.size=g,h.#t))for(let Y of h.#t)Y(g);te=te.subarray(pr,W),l-=pr}else if(W===0){let se=Buffer.allocUnsafe(8);return(0,je.read)(o,se,0,pr,0,Y=>{if(Y)return v(Y);if(gf.set(se),g=Number(sp.getBigUint64(0)&0xffffffffffffn),g>l){m()?u?f=setTimeout(()=>{v(new Error("File read timed out"))},m4).unref():(u=(0,je.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,je.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 ji.default.debug?.("Error enqueuing chunk",se),T()}l===g&&((0,je.close)(o),S.close()),T()})},"readMore"))},"pull"),cancel(){(0,je.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=_n.get(this),i=new e(n&&{type:n});if(s?.fileId){let o={...s,start:t,end:r};_n.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)};_n.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(hn=t?.primaryStore?.rootStore,!hn)throw new Error("No target table specified");return _L(this).saving??Promise.resolve()}},fL=500;a(lp,"deleteBlob");a(p4,"setDeletionDelay");global.createBlob=function(e,t){let r=new ip(t),n={storageIndex:0,fileId:null,flush:t?.flush,compress:t?.compress};if(_n.set(r,n),e instanceof Uint8Array)r.size=e.length,n.contentBuffer=e;else if(e instanceof Sf.Readable)n.source=e;else if(typeof e=="string")n.contentBuffer=Buffer.from(e);else if(e?.[Symbol.asyncIterator]||e?.[Symbol.iterator])n.source=Sf.Readable.from(e);else throw new Error("Invalid source type");return r};a(_L,"saveBlob");a(KA,"writeBlobWithStream");a(up,"getFileId");a(hL,"getFilePathForBlob");YA=new Map;a(Af,"getRootBlobPathsForDB");a(zA,"deleteRootBlobPathsForDB");a(mL,"rimrafSteadily");a(Tf,"getFilePath");a(E4,"writeBlobWithBuffer");a(g4,"generateFilePath");aL=new Map;a(S4,"getNextFileId");op=128;a(T4,"getNextStorageIndex");a(A4,"createFrequencyTableForStoragePaths");a(dp,"encodeBlobsWithFilePath");a(R4,"encodeBlobsAsBuffers");a(fp,"decodeBlobsWithWrites");a(_p,"decodeWithBlobCallback");a(_c,"decodeFromDatabase");a(ea,"deleteBlobsInObject");a(Zl,"findBlobsInObject");(0,Qi.addExtension)({Class:hi,type:11,unpack:a(function(e){let t=(0,Qi.unpack)(e),r=new ip;if(Object.assign(r,t[0]),typeof t[1]!="object"){if(_n.set(r,{storageIndex:t[1],fileId:t[2],store:hn}),dc)return dc(r)??r;if(!hn)throw new Error("No store specified, cannot load blob from storage")}else _n.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=_n.get(e);if(Xl!==void 0&&(fc=!0,t?.recordId!==void 0&&t.recordId!==Xl))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<lL)return r.size=t.contentBuffer.length,(0,Qi.pack)([r,t.contentBuffer])}if(Xl!==void 0){if(t=_L(e),!t.fileId)throw new Error("Unable to save blob without file id");return t.recordId=Xl,(0,Qi.pack)([r,t.storageIndex,t.fileId])}if(t)try{let n=(0,je.readFileSync)(Tf(t));if(n.length>=pr&&(n.copy(gf,0,0,pr),Number(sp.getBigUint64(0)&0xffffffffffffn)===n.length-pr))return Buffer.concat([(0,Qi.pack)([r]),n]);if(Dr)Dr.push(e.bytes());else throw new Error("Incomplete blob");return Buffer.alloc(0)}catch(n){if(n.code==="ENOENT"&&Dr)return Dr.push(e.bytes()),Buffer.alloc(0);throw n}else throw new Error("Blob has no storage info or buffer attached to it")},"pack")});(0,Qi.addExtension)({Class:Promise,type:12,pack(){throw new Error("Cannot encode a promise")}});a(y4,"polyfillBlob")});var yL={};Ue(yL,{asyncSerialization:()=>jA,contentTypes:()=>eR,findBestSerializer:()=>pp,getDeserializer:()=>to,hasAsyncSerialization:()=>QA,registerContentHandlers:()=>bf,serialize:()=>Of,serializeMessage:()=>ta,toCsvStream:()=>mp});function O4(e){try{return e?.[0]===123?ZA(e):e}catch{return e}}function bf(e){e.register(w4,{serializers:[{regex:/^application\/json$/,serializer:Ef},{regex:/^application\/cbor$/,serializer:a(function(t){return new hc.EncoderStream(yf).end(t)},"serializer")},{regex:/^application\/(x-)?msgpack$/,serializer:a(function(t){return(t?.[Symbol.iterator]||t?.[Symbol.asyncIterator])&&!Array.isArray(t)?mc.Readable.from((0,mi.encodeIter)(t,yf)):(0,mi.pack)(t)},"serializer")},{regex:/^text\/csv$/,serializer:a(function(t){return this.header("Content-Disposition",'attachment; filename="data.csv"'),mp(t)},"serializer")}]}),e.addContentTypeParser("application/x-msgpack",{parseAs:"buffer"},(t,r,n)=>{try{n(null,(0,mi.unpack)(r))}catch(s){s.statusCode=400,n(s)}}),e.addContentTypeParser("application/cbor",{parseAs:"buffer"},(t,r,n)=>{try{n(null,(0,hc.decode)(r))}catch(s){s.statusCode=400,n(s)}})}function pp(e){let t=e.headers.asObject||e.headers,r=e.requestedContentType??t.accept,n,s=0,i,o,c=r?r.toLowerCase().split(/\s*,\s*/):[];for(let l of c){let[u,...f]=l.split(/\s*;\s*/),d=1,_={q:1};for(let m of f){let S=m.indexOf("=");_[m.substring(0,S)]=m.substring(S+1)}d=+_.q;let h=Vr.get(u);if(h){let m=(h.q||1)*d;m>s&&(n=h,i=h.type||u,s=m,o=_)}}if(!n){if(r)throw new gL.ClientError("No supported content types found in Accept header, supported types include: "+Array.from(Vr.keys()).join(", "),406);n=Vr.get("application/json"),i="application/json"}return{serializer:n,type:i,parameters:o}}function Of(e,t,r){let n=EL&&t.headers.asObject?.["accept-encoding"]?.includes("br"),s;if(e?.contentType!=null&&e.data!=null)r.headers.set("Content-Type",e.contentType),r.headers.set("Vary","Accept-Encoding"),s=e.data;else if(e instanceof Uint8Array||e instanceof hi)r.headers.set("Content-Type","application/octet-stream"),r.headers.set("Vary","Accept-Encoding"),s=e;else{let i=pp(t);if(i.serializer.compressible===!1&&(n=!1),r.headers.set("Vary","Accept, Accept-Encoding"),r.headers.set("Content-Type",i.type),typeof e=="object"&&e&&(e[Symbol.iterator]||e[Symbol.asyncIterator])&&i.serializer.serializeStream){if(e.mapError){let c=e.getColumns;e=e.mapError(l=>(l.toJSON=()=>({error:l.name,message:l.message,...l.partialObject}),XA.default.warn?.(`Error serializing error ${t?.url||t}: ${l}`),l)),e.getColumns=c}let o=i.serializer.serializeStream(e,r);return n&&(r.headers.set("Content-Encoding","br"),o=o.pipe((0,eo.createBrotliCompress)({params:{[eo.constants.BROTLI_PARAM_MODE]:i.type.includes("json")||i.type.includes("text")?eo.constants.BROTLI_MODE_TEXT:eo.constants.BROTLI_MODE_GENERIC,[eo.constants.BROTLI_PARAM_QUALITY]:2}}))),o}s=i.serializer.serialize(e,r)}return n&&s?.length>EL?(r.headers.set("Content-Encoding","br"),new Promise((i,o)=>(0,eo.brotliCompress)(s,(c,l)=>{c?o(c):i(l)}))):s}function ta(e,t,r){if(e?.contentType!=null&&e.data!=null)return e.data;Zi=r?void 0:[];try{let n;if(t){let s=t.serialize;if(s)n=s(e);else{let i=pp(t);s=t.serialize=i.serializer.serialize,n=s(e)}}else n=Rf(e);return Zi?.length>0?(Zi.length===1?Zi[0]:Promise.all(Zi)).then(()=>ta(e,t,!0)):n}finally{Zi=void 0}}function jA(e){if(Zi)Zi.push(e);else throw new Error("Unable to serialize asynchronously")}function QA(){return!!Zi}function I4(e){return new Promise((t,r)=>{let n=[];e.on("data",s=>n.push(s)),e.on("end",()=>t(Buffer.concat(n))),e.on("error",r)})}function P4(e){return C4.includes(e)}function D4(e){let t=e.indexOf(";"),r;if(t>-1){r={};let n=e.slice(t+1).split(";");for(let s of n){let[i,o]=s.split("=");r[i.trim()]=o.trim()}e=e.slice(0,t)}return{type:e,parameters:r}}function to(e="",t=!1){let r=D4(e),n=r.type&&Vr.get(r.type)?.deserialize||L4(r);return t?s=>I4(s).then(n):n}function L4(e){return e.type.startsWith("text/")?(e.parameters?.charset&&!P4(e.parameters.charset)&&XA.default.info(`Unknown Buffer encoding ${e.parameters.charset} in content-type. Proceeding anyways.`),t=>({contentType:e.type,data:t.toString(e.parameters?.charset||"utf-8")})):e.type==="application/octet-stream"?t=>t:t=>{if(e.type==="")try{if(t?.[0]===123)return ZA(t)}catch{}return{contentType:e.type||"application/octet-stream",data:t}}}function M4(e,t){return{[Symbol.asyncIterator](){let r=e[Symbol.asyncIterator]?e[Symbol.asyncIterator]():e[Symbol.iterator]();return{next(){let n=r.next();return n.then?n.then(s=>({value:t(s.value),done:s.done})):{value:t(n.value),done:n.done}},return(n){return r.return(n)},throw(n){return r.throw(n)}}}}}function mp(e,t){let r=mc.default.Readable.from(e?.[Symbol.iterator]||e?.[Symbol.asyncIterator]?e:[e]),n={};t&&(n.fields=t.map(o=>({label:o,value:o})));let s={objectMode:!0},i=new b4(n,s);return r.pipe(i)}var mi,hc,eo,gL,mc,SL,JA,TL,XA,b4,AL,Rf,ZA,yf,Vr,eR,pL,RL,N4,w4,EL,Zi,C4,Xi=be(()=>{VA();mi=require("msgpackr"),hc=require("cbor-x"),eo=require("zlib"),gL=M(me()),mc=M(require("stream"));Pr();SL=M(ci()),JA=M(le());B();TL=M(require("yaml")),XA=M(_i());ls();({Transform:b4}=require("json2csv")),AL=JA.default.get(U.SERIALIZATION_BIGINT)!==!1,Rf=AL?uc:JSON.stringify,ZA=AL?$A:JSON.parse,yf={useRecords:!1,useToJSON:!0},Vr=new Map,eR=Vr;Ke.contentTypes=eR;(0,SL._assignPackageExport)("contentTypes",eR);Vr.set("application/json",{serializeStream:Ef,serialize:Rf,deserialize(e){return ZA(e)},q:.8});pL=new hc.Encoder(yf);Vr.set("application/cbor",{serializeStream(e){return e[Symbol.asyncIterator]&&(e[Symbol.iterator]=null),new hc.EncoderStream(yf).end(e)},serialize:pL.encode,deserialize:pL.decode,q:1});Vr.set("application/x-msgpack",{serializeStream(e){return(e?.[Symbol.iterator]||e?.[Symbol.asyncIterator])&&!Array.isArray(e)?mc.Readable.from((0,mi.encodeIter)(e,yf)):(0,mi.pack)(e)},serialize:mi.pack,deserialize:mi.unpack,q:.9});Vr.set("text/csv",{serializeStream(e,t){return t.headers.set("Content-Disposition",'attachment; filename="data.csv"'),mp(e,e?.getColumns?.())},serialize(e,t){return t.headers.set("Content-Disposition",'attachment; filename="data.csv"'),e&&!e[Symbol.iterator]&&(e=[e.toJSON?e.toJSON():e]),mp(e,e?.getColumns?.())},q:.1});Vr.set("text/plain",{serialize(e){return e.toString()},serializeStream(e){return mc.Readable.from(e.map?e.map(t=>t.toString()):e)},deserialize(e){return e.toString()},q:.2});Vr.set("text/yaml",{serialize(e){return TL.stringify(e,{aliasDuplicateObjects:!1})},q:.7});Vr.set("text/event-stream",{serializeStream:a(function(e){return mc.Readable.from(M4(e,this.serialize))},"serializeStream"),serialize:a(function(e){if(e.acknowledge&&e.acknowledge(),typeof e=="object"&&"value"in e&&e.timestamp&&(e={data:e.value,event:e.type,id:e.timestamp}),e.data||e.event){let t="";if(e.event&&(t+="event: "+e.event+`
|
|
8
8
|
`),e.data){let r=e.data;typeof r=="object"&&(r=Rf(r)),t+="data: "+r+`
|
|
9
9
|
`}return e.id&&(t+="id: "+e.id+`
|
|
10
10
|
`),e.retry&&(t+="retry: "+e.retry+`
|
|
@@ -129,4 +129,4 @@ Connection: close\r
|
|
|
129
129
|
\r
|
|
130
130
|
`))}},25).unref()}o.close?.(()=>{if(st.get(zt.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_DOMAINSOCKET)&&wd()==0)try{yW(NW(st.get(zt.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_DOMAINSOCKET)))}catch{}clearInterval(c),setTimeout(()=>{console.log("forced close server",i,oT),o.cantCleanupProperly||In.warn("Had to forcefully exit the thread",oT),process.exit(0)},5e3).unref()})}if(wW||process.env.DEV_MODE)try{require("inspector").close()}catch(i){In.info("Could not close debugger",i)}}}).ref();let e;Zh&&!Mge&&(e=CW()),Promise.resolve(e).then(()=>{if(wd()===0)try{Pge(nC)}catch(t){console.error("Error displaying start-up log",t)}em?.postMessage({type:zt.ITC_EVENT_TYPES.CHILD_STARTED})})})}a(IW,"startServers");function CW(){let e=[];for(let t in ki){let r=ki[t];if(t.includes?.("/")&&wd()==0){yge(t)&&yW(t),e.push(new Promise((o,c)=>{r.listen({path:t},()=>{o({port:t,name:r.name,protocol_name:r.protocol_name}),In.info("Domain socket listening on "+t)}).on("error",c)}));continue}let n,s=st.get(zt.CONFIG_PARAMS.HTTP_THREADRANGE);if(s){let o=typeof s=="string"?s.split("-"):s,c=wd();if(c<o[0]||c>o[1])continue}let i;try{let o=t.lastIndexOf(":");o>0?Zh?n={fd:Zh(+t.slice(o+1).replace(/[\[\]]/g,""),t.slice(0,o))}:n={host:+t.slice(o+1).replace(/[\[\]]/g,""),port:t.slice(0,o)}:Zh?n={fd:Zh(+t,"::")}:n={port:t}}catch(o){console.error(`Unable to bind to port ${t}`,o);continue}e.push(new Promise((o,c)=>{r.listen(n,()=>{o({port:t,name:r.name,protocol_name:r.protocol_name}),In.trace("Listening on port "+t,oT)}).on("error",c)}))}return Promise.all(e)}a(CW,"listenOnPorts");!tC&&!mge?.noServerStart&&IW();function oC(e,t,r){let n=e?.read?e:new pge({fd:e,readable:!0,writable:!0,allowHalfOpen:!0}),s=ki[t];if(s.isSecure&&(n.startTime=performance.now()),s)typeof s=="function"?s(n):s.emit("connection",n),r&&n.emit("data",r);else{let i=a(o=>{setTimeout(()=>{let c=ki[t];c?(typeof c=="function"?c(n):c.emit("connection",n),r&&n.emit("data",r)):o<5?i(o+1):(In.error(`Server on port ${t} was not registered`),n.destroy())},1e3)},"retry");i(1)}return n}a(oC,"deliverSocket");var gW=new Map;function vge(e){let{port:t,event:r,data:n,requestId:s}=e,i;switch(i=gW.get(s),r){case"connection":i=oC(void 0,t),gW.set(s,i),i.write=(c,l,u)=>(em.postMessage({requestId:s,event:"data",data:c.toString("latin1")}),u&&u(),!0),i.end=(c,l,u)=>(em.postMessage({requestId:s,event:"end",data:c?.toString("latin1")}),u&&u(),!0);let o=i.destroy;i.destroy=()=>{o.call(i),em.postMessage({requestId:s,event:"destroy"})};break;case"data":i._readableState.destroyed||i.emit("data",Buffer.from(n,"latin1"));break;case"drain":i._readableState.destroyed||i.emit("drain",{});break;case"end":i._readableState.destroyed||i.emit("end",{});break;case"error":i._readableState.destroyed||i.emit("error",{});break}}a(vge,"proxyRequest");var{getComponentName:cT}=(Oh(),D(bh));function aC(e,t,r=!0){t||(t=st.get(zt.CONFIG_PARAMS.HTTP_PORT));let n=ki[t];if(n){let s=n.lastServer||n;if(s===e)throw new Error(`Can not register the same server twice for the same port ${t}`);if(r&&!!s.sessionIdContext!=!!e.sessionIdContext&&+t)throw new Error(`Can not mix secure HTTPS and insecure HTTP on the same port ${t}`);s.off("unhandled",RW),s.on("unhandled",(i,o)=>{e.cantCleanupProperly&&(n.cantCleanupProperly=!0),e.emit("request",i,o)}),n.lastServer=e}else ki[t]=e;e.on("unhandled",RW)}a(aC,"registerServer");function cC(e){let t=[],r=e?.securePort;return r&&t.push({port:r,secure:!0}),r=e?.port,r&&t.push({port:r,secure:!1}),t.length===0&&(t=[],st.get(zt.CONFIG_PARAMS.HTTP_PORT)!=null&&t.push({port:st.get(zt.CONFIG_PARAMS.HTTP_PORT),secure:st.get(zt.CONFIG_PARAMS.CUSTOMFUNCTIONS_NETWORK_HTTPS)}),st.get(zt.CONFIG_PARAMS.HTTP_SECUREPORT)!=null&&t.push({port:st.get(zt.CONFIG_PARAMS.HTTP_SECUREPORT),secure:!0})),e?.isOperationsServer&&st.get(zt.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_DOMAINSOCKET)&&t.push({port:NW(st.get(zt.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_DOMAINSOCKET)),secure:!1}),t}a(cC,"getPorts");function lC(e,t){let r=[];for(let{port:n,secure:s}of cC(t))r.push(PW(n,s,t?.isOperationsServer,t?.mtls)),typeof e=="function"?sC[t?.runFirst?"unshift":"push"]({listener:e,port:t?.port||n}):(e.isSecure=s,aC(e,n,!1)),aT[n]=uT(sC,n);return r}a(lC,"httpServer");function lT(e,t){let r=nC.get(e)??[];nC.set(e,[...r,t])}a(lT,"setPortServerMap");function PW(e,t,r,n){if(lT(e,{protocol_name:t?"HTTPS":"HTTP",name:cT()}),!iT[e]){let s=r?"operationsApi_network":"http",i=st.get(s+"_keepAliveTimeout"),o=st.get(s+"_timeout"),c=st.get(s+"_headersTimeout"),l={keepAliveTimeout:i,headersTimeout:c,requestTimeout:o,highWaterMark:128*1024,noDelay:!0,keepAlive:!0,keepAliveInitialDelay:600,maxHeaderSize:st.get(zt.CONFIG_PARAMS.HTTP_MAXHEADERSIZE)},u=st.get(s+"_mtls"),f=st.get(s+"_mtls_required"),d;if(t){let m=st.get("tls");d=st.get(s+"_http2"),Object.assign(l,{allowHTTP1:!0,rejectUnauthorized:!!f,requestCert:!!(u||n),ticketKeys:Nge(),SNICallback:OW(r?"operations-api":"server",u),ciphers:m.ciphers??m[0]?.ciphers})}let _=Cge(),h=iT[e]=(t?d?Age:Tge:gge)(l,async(m,S)=>{try{let A=performance.now(),E=new bW(m,S);r&&(E.isOperationsServer=!0);let T=await aT[e](E);if(!T){if(E._nodeResponse.statusCode)return;T=DW(E)}if(T.headers?.set||(T.headers=new rC(T.headers)),_?T.headers?.set?.("Server","Unlicensed HarperDB, this should only be used for educational and development purposes"):T.headers?.set?.("Server","HarperDB"),T.status===-1){for(let ne of T.headers||[])S.setHeader(ne[0],ne[1]);return m.baseRequest=E,S.baseResponse=T,iT[e].emit("unhandled",m,S)}let w=T.status||200,v=performance.now(),k=v-A,$=T.body,W,te=!1;if(!T.handlesHeaders){let ne=T.headers||new rC;$?$.length>=0?(typeof $=="string"?ne.set("Content-Length",Buffer.byteLength($)):ne.set("Content-Length",$.length),W=!0):$ instanceof Rge&&($.size?ne.set("Content-Length",$.size):$.on&&(te=!0,$.on("size",ae=>{S.headersSent||S.setHeader("Content-Length",ae)})),$=$.stream()):(ne.set("Content-Length","0"),W=!0);let ue=`hdb;dur=${k.toFixed(2)}`;if(T.wasCacheMiss&&(ue+=", miss"),Ige(ne,"Server-Timing",ue,!0),!S.headersSent)if(te){if(S.statusCode=w,ne)if(ne[Symbol.iterator])for(let[ae,pe]of ne)S.setHeader(ae,pe);else for(let ae in ne)S.setHeader(ae,ne[ae])}else S.writeHead(w,ne&&(ne[Symbol.iterator]?Array.from(ne):ne));W&&S.end($)}let se=E.handlerPath,Y=E.method;if(Jh(k,"duration",se,Y,T.wasCacheMiss==null?void 0:T.wasCacheMiss?"cache-miss":"cache-hit"),pW(w<400,"success",se,Y),pW(1,"response_"+w,se,Y),!W)if($ instanceof ReadableStream&&($=EW.fromWeb($)),($[Symbol.iterator]||$[Symbol.asyncIterator])&&($=EW.from($)),$?.pipe){$.pipe(S),$.destroy&&S.on("close",()=>{$.destroy()});let ne=0;$.on("data",ue=>{ne+=ue.length}),$.on("end",()=>{Jh(performance.now()-v,"transfer",se,Y),Jh(ne,"bytes-sent",se,Y)})}else $?.then?$.then(ne=>{S.end(ne)},g):S.end($)}catch(A){g(A)}function g(A){let E=A.headers;S.writeHead(A.statusCode||500,E&&(E[Symbol.iterator]?Array.from(E):E)),S.end(A.toString()),A.statusCode?A.statusCode===500?In.warn(A):In.info(A):In.error(A)}a(g,"onError")});i>=0&&(h.keepAliveTimeout=i),c>=0&&(h.headersTimeout=c),t&&(h.ports||(h.ports=[]),h.ports.push(e),l.SNICallback.initialize(h),u&&(h.mtlsConfig=u),h.on("secureConnection",m=>{m._parent.startTime&&Jh(performance.now()-m._parent.startTime,"tls-handshake",e),Jh(m.isSessionReused(),"tls-reused",e)}),h.isSecure=!0),aC(h,e)}return iT[e]}a(PW,"getHTTPServer");function uT(e,t){let r=DW;for(let n=e.length;n>0;){let{listener:s,port:i}=e[--n];if(i===t||i==="all"){let o=r;r=a((...c)=>s(...c,o),"next_callback")}}return r}a(uT,"makeCallbackChain");function DW(e){return e.user&&(e._nodeRequest.user=e.user),{status:-1,body:"Not found",headers:new rC}}a(DW,"unhandled");function Uge(e,t){lC(e,{requestOnly:!0,...t})}a(Uge,"onRequest");function xge(e,t){let r;if(t.securePort){lT(t.securePort,{protocol_name:"TLS",name:cT()});let n=OW("server",t.mtls),s=st.get("tls");r=Oge({rejectUnauthorized:!!t.mtls?.required,requestCert:!!t.mtls,noDelay:!0,keepAlive:!0,keepAliveInitialDelay:600,ciphers:s.ciphers??s[0]?.ciphers,SNICallback:n},e),n.initialize(r),ki[t.securePort]=r}return t.port&&(lT(t.port,{protocol_name:"TCP",name:cT()}),r=Ege(e,{noDelay:!0,keepAlive:!0,keepAliveInitialDelay:600}),ki[t.port]=r),r}a(xge,"onSocket");Object.defineProperty(Sge.prototype,"upgrade",{get(){return"connection"in this.headers&&"upgrade"in this.headers&&this.headers.connection.toLowerCase().includes("upgrade")&&this.headers.upgrade.toLowerCase()=="websocket"},set(e){}});var SW=[],iC={};function LW(e,t){for(let{port:r}of cC(t))SW[t?.runFirst?"unshift":"push"]({listener:e,port:r}),iC[r]=uT(SW,r)}a(LW,"onUpgrade");var TW=[],AW={};function Bge(e,t){let r=[];for(let{port:n,secure:s}of cC(t)){lT(n,{protocol_name:s?"WSS":"WS",name:cT()});let i=PW(n,s,t?.isOperationsServer,t?.mtls);Xh[n]||(Xh[n]=new bge({noServer:!0,maxPayload:t.maxPayload??100*1024*1024}),Xh[n].on("connection",(o,c)=>{let l=new bW(c);l.isWebSocket=!0;let u=aT[n](l);AW[n](o,l,u)}),LW((o,c,l,u)=>o.__harperdb_request_upgraded?u(o,c,l):Xh[n].handleUpgrade(o,c,l,f=>{o.__harperdb_request_upgraded=!0,u(o,c,l),Xh[n].emit("connection",f,o)}),{port:n}),i.on("upgrade",(o,c,l)=>{iC[n]&&iC[n](o,c,l)})),r.push(i),TW[t?.runFirst?"unshift":"push"]({listener:e,port:n}),AW[n]=uT(TW,n),aT[n]=uT(sC,n)}return r}a(Bge,"onWebSocket");function RW(e,t){t.writeHead(404),t.end(`Not found
|
|
131
131
|
`)}a(RW,"defaultNotFound")});var mW={};Ue(mW,{startHTTPThreads:()=>kge,startSocketServer:()=>mC,updateWorkerIdleness:()=>qW});async function kge(e=2,t){try{if(t)_C(0,1,!0);else{let{loadRootComponents:r}=dT();if(e===0)return(0,Cs.setMainIsWorker)(!0),await uC().startServers(),Promise.resolve([]);await r()}FW();for(let r=0;r<e;r++)_C(r,e);return Promise.all(kW)}finally{(0,Cs.threadsHaveStarted)()}}function FW(){let e=(0,xW.checkMemoryLimit)();e&&!process.env.DEV_MODE&&(console.error(e),fC=setInterval(()=>{hT.notify(e)},Hge).unref())}function _C(e,t=1,r){if(dC++,(0,Cs.startWorker)("server/threads/threadServer.js",{name:EA.HTTP,workerIndex:e,threadCount:t,async onStarted(n){let s=new Promise((o,c)=>{function l(u){u.type===hA.CHILD_STARTED&&(n.removeListener("message",l),o(n))}a(l,"onMessage"),n.on("message",l),n.on("error",c)});kW.push(s),await s,Id.push(n),n.expectedIdle=1,n.lastIdle=0,n.requests=1,n.on("message",o=>{if(o.requestId){let c=_T.get(o.requestId);c&&c(o)}}),n.on("exit",i),n.on("shutdown",i);function i(){let o=Id.indexOf(n);o>-1&&Id.splice(o,1)}if(a(i,"removeWorker"),Cd){let o=Cd;Cd=[];for(let c of o)HW[c.localPort](null,c)}}}),r){let n=setInterval(()=>{hC?hC=!1:(clearInterval(n),console.log("shut down dynamic thread due to inactivity"),(0,Cs.shutdownWorkers)(),dC=0,setTimeout(()=>{global.gc?.()},5e3))},1e4)}}function mC(e=0,t){if(typeof e=="string")try{(0,mT.existsSync)(e)&&(0,mT.unlinkSync)(e)}catch{}let r;t?t==="ip"?r=Fge:r=qge(t):r=pC;let n=(0,Pd.createServer)({allowHalfOpen:!0,pauseOnConnect:!r.readsData}).listen(e);return n._handle&&(n._handle.onconnection=HW[e]=function(s,i){r.readsData||(i.reading=!1,i.readStop()),hC=!0,r(i,(o,c)=>{if(!o){if(MW){let u=i._socket||new Pd.Socket({handle:i,writable:!0,readable:!0});MW.deliverSocket(u,e,c),u.resume()}else dC>0?(Cd.length===0&&setTimeout(()=>{Cd.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,Cd.push(i)):(console.log("start up a dynamic thread to handle request"),_C(0));rr(!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});Vge(u,o,e)}rr(!0,"socket-routed")})},hT.info(`HarperDB ${BW.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 pC(e,t){let r,n=0;for(let s of Id){if(s.threadId===-1)continue;let i=s.expectedIdle/s.requests;if(i>n)r=s;else if(n>=fT)return fT=i,t(r);n=i}fT=0,t(r)}function Fge(e,t){let r={};e.getpeername(r);let n=r.address,s=Dd.get(n),i=Date.now();if(s&&s.worker.threadId!==-1)return s.lastUsed=i,t(s.worker);pC(e,o=>{Dd.set(n,{worker:o,lastUsed:i}),t(o)})}function qge(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=Dd.get(l),f=Date.now();if(u&&u.worker.threadId!==-1)return u.lastUsed=f,s(u.worker);pC(n,d=>{Dd.set(l,{worker:d,lastUsed:f}),s(d,o)})})}a(r,"findByHeaderAffinity")}function qW(){fT=0;for(let e of Id)e.expectedIdle=e.recentELU.idle+Gge,e.requests=1;Id.sort((e,t)=>e.expectedIdle>t.expectedIdle?-1:1)}function Vge(e,t,r){let n=$ge++;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(),_T.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")),_T.delete(n)),s.event=="destroy"&&(e.destroy(),_T.delete(n))})}var Cs,Pd,hT,mT,UW,xW,BW,Id,Cd,HW,MW,dC,kW,fC,Hge,hC,fT,vW,Dd,Gge,_T,$ge,eC=be(()=>{Cs=M(Ze()),Pd=require("net");B();hT=M(z()),mT=require("fs");wi();UW=require("worker_threads"),xW=M(td()),BW=M(pt()),Id=[],Cd=[],HW=[],dC=0,kW=[];UW.isMainThread&&(process.on("uncaughtException",e=>{e.code!=="ECONNRESET"&&e.message!=="write EIO"&&console.error("uncaughtException",e)}),(0,Cs.onMessageFromWorkers)(e=>{e.type===pA.RESTART&&fC&&(clearInterval(fC),FW())}));Hge=6e5;a(kge,"startHTTPThreads");a(FW,"licenseWarning");a(_C,"startHTTPWorker");a(mC,"startSocketServer");fT=0;a(pC,"findMostIdleWorker");vW=36e5,Dd=new Map;a(Fge,"findByRemoteAddressAffinity");a(qge,"makeFindByHeaderAffinity");setInterval(()=>{let e=Date.now();for(let[t,r]of Dd)r.lastUsed+vW<e&&Dd.delete(t)},vW).unref();Gge=1e3;a(qW,"updateWorkerIdleness");(0,Cs.setMonitorListener)(qW);_T=new Map,$ge=1;a(Vge,"proxySocket")});var rz=P((xve,tz)=>{var $W=M(require("cluster")),Wa=M(le());B();var Fi=M(z()),VW=M(require("fastify")),KW=M(require("@fastify/cors")),YW=M(require("@fastify/compress")),WW=M(require("@fastify/static")),zW=M(Gb()),jW=M(require("path")),QW=M(pt()),JW=M(fs()),XW=M(oe()),ZW=M(qn()),ez=M(td());Pr();var za=M(HS());Xi();Wa.default.initSync();var Kge=6e4,Yge=1024*1024*1024,Wge="TRUE",{CONFIG_PARAMS:rm}=q,Ld;tz.exports={hdbServer:GW,start:GW};async function GW(e){try{Fi.default.debug("In Fastify server"+process.cwd()),Fi.default.debug(`Running with NODE_ENV set as: ${process.env.NODE_ENV}`),Fi.default.debug(`HarperDB server process ${process.pid} starting up.`),global.clustering_on=!1,global.isMaster=$W.default.isMaster,await zge();let t=e.securePort>0;Ld=jge(t),await Ld.ready(),e||(e={}),e.isOperationsServer=!0;try{Ke.http(Ld.server,e),Ld.server.closeIdleConnections||await Ld.listen({port:0,host:"::"})}catch(r){throw Ld.close(),Fi.default.error(r),Fi.default.error("Error configuring operations server"),r}}catch(t){console.error(`Failed to build server on ${process.pid}`,t),Fi.default.fatal(t),process.exit(1)}}a(GW,"operationsServer");async function zge(){Fi.default.trace("Configuring HarperDB process."),JW.default.setSchemaDataToGlobal(),await ZW.default.setUsersWithRolesCache(),await ez.default.getLicense()}a(zge,"setUp");function jge(e){Fi.default.debug(`HarperDB process starting to build ${e?"HTTPS":"HTTP"} server.`);let t=Qge(e),r=(0,VW.default)(t);r.server.headersTimeout=Xge(),r.setErrorHandler(za.serverErrorHandler);let n=Jge();n&&r.register(KW.default,n),r.register(function(i,o,c){i.setNotFoundHandler(function(l,u){r.server.emit("unhandled",l.raw,u.raw)}),c()}),r.register(zW.default),r.register(YW.default),r.register(WW.default,{root:jW.default.join(QW.PACKAGE_ROOT,"studio/build-local")}),bf(r);let s=Wa.default.get(_A.LOCAL_STUDIO_ON);return r.get("/",function(i,o){return!XW.default.isEmpty(s)&&s.toString().toLowerCase()==="true"?o.sendFile("index.html"):o.sendFile("running.html")}),r.post("/",{preValidation:[za.reqBodyValidationHandler,za.authHandler],config:{isOperation:!0}},async function(i,o){return i.body?.operation?.startsWith("restart")&&o.header("Connection","close"),(0,za.handlePostRequest)(i,o)}),r.get("/health",()=>"HarperDB is running."),Fi.default.debug(`HarperDB process starting up ${e?"HTTPS":"HTTP"} server listener.`),r}a(jge,"buildServer");function Qge(e){let t=Wa.default.get(rm.OPERATIONSAPI_NETWORK_TIMEOUT),r=Wa.default.get(rm.OPERATIONSAPI_NETWORK_KEEPALIVETIMEOUT);return{bodyLimit:Yge,connectionTimeout:t,keepAliveTimeout:r,forceCloseConnections:!0,return503OnClosing:!1,https:e}}a(Qge,"getServerOptions");function Jge(){let e=Wa.default.get(rm.OPERATIONSAPI_NETWORK_CORS),t=Wa.default.get(rm.OPERATIONSAPI_NETWORK_CORSACCESSLIST),r;return e&&(e===!0||e.toUpperCase()===Wge)&&(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(Jge,"getCORSOpts");function Xge(){return Wa.default.get(rm.OPERATIONSAPI_NETWORK_HEADERSTIMEOUT)??Kge}a(Xge,"getHeaderTimeoutConfig")});var RC={};Ue(RC,{disableNATS:()=>eSe,publishToStream:()=>gT,setNATSReplicator:()=>EC,setPublishToStream:()=>tSe,setSubscription:()=>AC,start:()=>Zge});function Zge(){nm.default.get(U.CLUSTERING_ENABLED)&&nSe()}function eSe(e=!0){az=e}function tSe(e,t){gT=e,AC=t}function nSe(){if(az||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];EC(s,r,i)}}Zc((r,n)=>{EC(r.tableName,r.databaseName,r),n&&lz(r)}),!nz&&(nz=!0)}function EC(e,t,r){if(t==="system"&&sSe.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 $r{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){lz(i)}static subscribe(){let i=new Ln;return AC(t,e,i),i}static subscribeOnThisThread(i){return i<(nm.default.get(U.CLUSTERING_LEAFSERVER_STREAMS_MAXINGESTTHREADS)??rSe)}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 pT(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=cz;return i}a(n,"getNATSTransaction")}function lz(e){let t=nm.default.get(U.CLUSTERING_NODENAME);gT(`${SC.SUBJECT_PREFIXES.TXN}.${e.databaseName}.${e.tableName}`,(0,TC.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 sz,SC,TC,iz,oz,nm,ET,az,gT,AC,rSe,cz,nz,sSe,pT,gC,uz=be(()=>{ve();Xo();sz=M(Ut()),SC=M(ot()),TC=M(ao());Vl();iz=M(rO()),oz=M(ln()),nm=M(le());B();ET=M(z());a(Zge,"start");a(eSe,"disableNATS");gT=sz.publishToStream,AC=iz.setSubscription;a(tSe,"setPublishToStream");rSe=2;a(nSe,"assignReplicationSource");sSe=["hdb_job","hdb_analytics","hdb_raw_analytics","hdb_info","hdb_license"];a(EC,"setNATSReplicator");a(lz,"publishSchema");pT=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=nm.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||(ET.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(gT(`${SC.SUBJECT_PREFIXES.TXN}.${s}.${l.table}`,(0,TC.createNatsTableStreamName)(s,l.table),void 0,l)?.catch(f=>{throw ET.error("An error has occurred trying to replicate transaction",l,f),f.statusCode=504,f}))}return Promise.all(n)}},gC=class extends pT{static{a(this,"ImmmediateNATSTransaction")}constructor(){super({get timestamp(){return(0,oz.getNextMonotonicTime)()}})}addWrite(t,r){super.addWrite(t,r),this.commit({})}};cz=new gC});async function mz({clientId:e,user:t,clean:r,will:n,keepalive:s}){let i;if(e&&!r){let o=await yC.get(e,{returnNonexistent:!0});i=new NC(e,t,o),o&&(i.sessionWasPresent=!0)}else{if(e){let o=await yC.get(e);o&&o.delete()}i=new TT(e,t)}return n&&(n.id=e,n.user={username:t?.username},sm.put(n)),s&&(i.keepalive=s,i.receivedPacket()),i}function bC(){return ST++,ST>65500&&(ST=1),ST}function OC(e,t,r){let{topic:n,retain:s}=e;e.data=t,e.async=!0,r.authorize=!0;let i=cs.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 bt(r,()=>s?t===void 0?o.delete(e,r):o.put(e,e.data,r):o.publish(e,e.data,r))}var fz,ja,_z,hz,dz,yC,sm,ST,TT,NC,pz=be(()=>{ve();Jl();fz=M(ln()),ja=M(z());ac();_z=M(Ze()),hz=M(uC());Pr();dz=100,yC=dt({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"}]}}]}),sm=dt({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,_z.getWorkerIndex)()===0&&(async()=>{await hz.when_components_loaded,await new Promise(e=>setTimeout(e,2e3));for await(let e of sm.search({})){let t=e.data,r={...e};r.user?.username&&(r.user=await Ke.getUser(r.user.username));try{await OC(r,t,r)}catch{(0,ja.warn)("Failed to publish will",t)}sm.delete(e.id)}})();a(mz,"getSession");ST=1;a(bC,"getNextMessageId");TT=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(A=>A.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,ja.trace)("Resuming subscription from",s,"from",o);let h=cs.getMatch(u,"mqtt");if(!h){let A=new Error(`The topic ${s} does not exist, no resource has been defined to handle this topic`);throw A.statusCode=404,A}if(_.url=h.relativeURL,_.url.indexOf("+")>-1||_.url.indexOf("#")>-1){let A=_.url.slice(1);if(A.indexOf("#")>-1&&A.indexOf("#")!==A.length-1)throw new Error("Multi-level wildcards can only be used at the end of a topic");if(_.isCollection=!0,A.indexOf("+")===A.length-1)_.onlyChildren=!0,_.url="/"+A.slice(0,A.length-1);else{let E=A.split("/"),T;for(let k=0;k<E.length;k++)if(E[k].indexOf("+")>-1)if(E[k]==="+")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(k=>{let $=k.id;if(!Array.isArray($))if($?.indexOf?.("/")>-1)$=$.split("/");else return!1;if(w&&$.length!==E.length)return!1;for(let W=0;W<E.length;W++)if(E[W]!=="+"&&E[W]!==$[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 bt(_,async()=>{let A=this.createContext();A.topic=s,A.retainHandling=i,A.isCollection=_.isCollection;let E=await S.subscribe(_,A);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=bC());let k=w.id;if(Array.isArray(k)&&(k=Ql(k)),k==null&&(k=""),await this.listener(m+"/"+k,w.value,v,t)===!1)break;this.awaitingAcks?.size>dz?await new Promise(W=>setTimeout(W,this.awaitingAcks.size-dz)):await new Promise(setImmediate)}catch(v){(0,ja.warn)(v)}})();return E});if(g)return g.topic=s,g.qos=t.qos,this.subscriptions.push(g),g}resume(){}needsAcknowledge(t){let r=bC();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 OC(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();bt(r,async()=>{try{if(!t){let n=await sm.get(this.sessionId);n?.doesExist()&&await OC(n,n.data,r)}}finally{await sm.delete(this.sessionId)}}).catch(n=>{(0,ja.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(OC,"publish");NC=class extends TT{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=bC(),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,ja.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,fz.getNextMonotonicTime)()),(0,ja.trace)("Added durable subscription",t.topic,r),{qos:t.qos,topic:t.topic,startTime:r}}),yC.put(this.sessionRecord)}}});var IC={};Ue(IC,{bypassAuth:()=>iSe,start:()=>oSe});function iSe(){Az=!0}function oSe({server:e,port:t,network:r,webSocket:n,securePort:s,requireAuthentication:i}){e.mqtt||(e.mqtt={requireAuthentication:i,sessions:new Set,events:new Tz.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),fr.debug?.("Received WebSocket connection for MQTT from",u._socket.remoteAddress);let{onMessage:h,onClose:m}=gz(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=>{fr.info?.("WebSocket error",S)})},{...n})),(t||s)&&c.push(e.socket(async u=>{let f;if(o.events.emit("connection",u),fr.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,Md.get)(U.LOGGING_AUDITAUTHEVENTS_LOGSUCCESSFUL)&&RT.notify?.({username:f?.username,status:vs.SUCCESS,type:Ko.AUTHENTICATION,auth_strategy:"MQTT mTLS",remote_address:u.remoteAddress})}catch(m){throw(0,Md.get)(U.LOGGING_AUDITAUTHEVENTS_LOGFAILED)&&RT.error?.({username:h,status:vs.FAILURE,type:Ko.AUTHENTICATION,auth_strategy:"mqtt",remote_address:u.remoteAddress}),m}}else fr.debug?.("MQTT mTLS authorized connection (mTLS did not authorize a user)","from",u.remoteAddress)}catch(h){o.events.emit("error",h,u),fr.error?.(h)}else if(l.required)return fr.info?.(`Unauthorized connection attempt, no authorized client certificate provided, error: ${u.authorizationError}`),u.end()}!f&&Az&&u.remoteAddress.includes("127.0.0.1")&&(f=await(0,Sz.getSuperUser)(),fr.debug?.("Auto-authorizing local connection",f?.username));let{onMessage:d,onClose:_}=gz(u,h=>u.write(h),null,f,o);u.on("data",d),u.on("close",_),u.on("error",h=>{fr.info?.("Socket error",h)})},{port:t,securePort:s,mtls:l})),c}function gz(e,t,r,n,s){Ez||(Ez=!0,g_(d=>{AT>0&&d.push({metric:"mqtt-connections",connections:AT,byThread:!0})}));let i;AT++;let o,c={protocolVersion:4},l=(0,yT.parser)({protocolVersion:5});function u(d){l.parse(d)}a(u,"onMessage");function f(){AT--,i||(i=!0,o?.disconnect?.(),s.events.emit("disconnected",o,e),s.sessions.delete(o),Yn(!1,"connection","mqtt","disconnect"),fr.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"){fr.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;rr(d.length,"bytes-received",S,A(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,Md.get)(U.LOGGING_AUDITAUTHEVENTS_LOGSUCCESSFUL)&&RT.notify?.({username:n?.username,status:vs.SUCCESS,type:Ko.AUTHENTICATION,auth_strategy:"MQTT",remote_address:e.remoteAddress})}catch(se){return(0,Md.get)(U.LOGGING_AUDITAUTHEVENTS_LOGFAILED)&&RT.error?.({username:d.username,status:vs.FAILURE,type:Ko.AUTHENTICATION,auth_strategy:"mqtt",remote_address:e.remoteAddress}),s.events.emit("auth-failed",d,e,se),Yn(!1,"connection","mqtt","connect"),g({cmd:"connack",reasonCode:4,returnCode:134})}if(!n&&s.requireAuthentication)return s.events.emit("auth-failed",d,e),Yn(!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=to(r?.headers.get?.("content-type")));d.will.data=d.will.payload?.length>0?se(d.will.payload):void 0,delete d.will.payload}o=mz({user:n,...d}),o=await o,o.socket=e,r&&(o.request=r),s.sessions.add(o)}catch(se){return fr.error?.(se),s.events.emit("auth-failed",d,e,se),Yn(!1,"connection","mqtt","connect"),g({cmd:"connack",reasonCode:se.code||5,returnCode:se.code||128})}s.events.emit("connected",o,e),Yn(!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 ae=se.indexOf("/",1),pe=ae>0?se.slice(0,ae):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(ae){return fr.error?.(ae),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?fr.warn?.(ne):fr.info?.(ne):fr.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",k=e.deserialize||(e.deserialize=to(r?.headers.get?.("content-type"))),W=(d.payload?.length||0)>0?k(d.payload):void 0,te;try{te=await o.publish(d,W)}catch(se){s.events.emit("error",se,e,d,o),fr.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),Yn(!0,"connection","mqtt","disconnect"),fr.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),fr.error?.(T),g({cmd:"disconnect"})}function g(T,w){let v=(0,yT.generate)(T,c);t(v),rr(v.length,"bytes-sent",w,A(T),"mqtt")}a(g,"sendPacket");function A(T){return T.qos>0?T.cmd+",qos="+T.qos:T.cmd}a(A,"packetMethodName");function E(T){return ta(T,r)}a(E,"serialize")}),l.on("error",d=>{fr.warn("MQTT parsing error, closing connection:",d.message),e?.destroy?e.destroy():e?.terminate()}),{onMessage:u,onClose:f}}var yT,Sz,Md,wC,Tz,RT,fr,Az,Ez,AT,Rz=be(()=>{yT=require("mqtt-packet");pz();Sz=M(qn());Xi();wi();Pr();Md=M(le());B();wC=M(_i()),Tz=require("events"),RT=(0,wC.loggerWithTag)("auth-event"),fr=(0,wC.loggerWithTag)("mqtt"),Az=(0,Md.get)(U.AUTHENTICATION_AUTHORIZELOCAL)??process.env.DEV_MODE;a(iSe,"bypassAuth");a(oSe,"start");AT=0;a(gz,"onSocket")});var bh={};Ue(bh,{component_errors:()=>Ud,getComponentName:()=>dSe,loadComponent:()=>NT,loadComponentDirectories:()=>wz,setErrorReporter:()=>uSe});function wz(e,t){t&&(PC=t),e&&(MC=e);let r=[];if((0,lt.existsSync)(CC)){let s=(0,lt.readdirSync)(CC,{withFileTypes:!0});for(let i of s){if(!i.isDirectory()&&!i.isSymbolicLink())continue;let o=i.name,c=(0,St.join)(CC,o);r.push(NT(c,PC,lA,!1))}}let n=process.env.RUN_HDB_APP;return n&&r.push(NT(n,PC,n,!1,null,!!process.env.DEV_MODE)),Promise.all(r).then(()=>{Nz=!0})}function uSe(e){im=e}function fSe(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,lt.rmSync)(t,{recursive:!0,force:!0}),(0,lt.existsSync)((0,St.join)(e,"node_modules"))||(0,lt.mkdirSync)((0,St.join)(e,"node_modules")),(0,lt.symlinkSync)(xC.PACKAGE_ROOT,t,"dir"),r()}finally{s.primaryStore.unlock(e,0)}})}async function NT(e,t,r,n,s,i){let o=(0,lt.realpathSync)(e);if(bT.has(o))return bT.get(o);bT.set(o,!0),s&&(MC=s);try{let c;n&&(Ud=new Map);let l=(0,St.join)(e,"harperdb-config.yaml");(0,lt.existsSync)(l)?c=n?(0,wT.getConfigObj)():(0,DC.parseDocument)((0,lt.readFileSync)(l,"utf8")).toJSON():!n&&(0,lt.existsSync)(l=(0,St.join)(e,"config.yaml"))?c=(0,DC.parseDocument)((0,lt.readFileSync)(l,"utf8")).toJSON():c=vC;try{let d=(0,St.join)(e,"node_modules","harperdb");(n||((0,lt.existsSync)(d)||!e.startsWith((0,LC.getHdbBasePath)()))&&(!(0,lt.existsSync)(d)||(0,lt.realpathSync)(xC.PACKAGE_ROOT)!==(0,lt.realpathSync)(d)))&&await fSe(e,d)}catch(d){Il.default.error("Error symlinking harperdb module",d),d.code=="EPERM"&&process.platform==="win32"&&Il.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=OT,f=n;for(let d in c){OT=d;let _=c[d];if(Ud.set(n?d:(0,St.basename)(e),!1),!_)continue;let h,m=_.package;try{if(m){let T=e,w;for(;!(0,lt.existsSync)(w=(0,St.join)(T,"node_modules",d));)if(T=(0,St.dirname)(T),T.length<(0,LC.getHdbBasePath)().length){w=null;break}if(w)h=await NT(w,t,r,!1),f=!0;else throw new Error(`Unable to find package ${d}:${m}`)}else h=lSe[d];if(!h)continue;let S=a(T=>(T.origin=r,dt(T)),"ensureTable"),g=_.network||(_.port||_.securePort)&&_,A=g?.securePort||g?.https&&g.port,E=!g?.https&&g?.port;if(vd.isMainThread&&(h=await h.startOnMainThread?.({server:Ke,ensureTable:S,port:E,securePort:A,resources:t,..._})||h,n&&g))for(let T of[E,A])try{if(+T&&!yz.includes(T)){let w=UC.get(U.HTTP_SESSIONAFFINITY);w&&Il.default.warn("Session affinity is not recommended and may cause memory leaks"),(w||!wE)&&(yz.push(T),mC(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:A,resources:t,..._})||h),MC.set(h,!0),(h.handleFile||h.handleDirectory||h.setupFile||h.setupDirectory)&&_.files!=null){if(_.files.includes(".."))throw(0,Oz.handleHDBError)("Can not reference parent directories");let T=(0,St.join)(e,_.files).replace(/\\/g,"/"),w=T.indexOf("/*");if(w>-1&&_.files!==vC[d]?.files&&!(0,lt.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,St.basename)(e),k=_.path||"/";k=k.startsWith("/")?k:k.startsWith("./")?"/"+v+k.slice(2):k==="."?"/"+v:"/"+v+"/"+k;let $,W,te;if(_.root){let Y=_.root;Y.startsWith("/")&&(Y=Y.slice(1)),Y.endsWith("/")&&(Y=Y.slice(0,-1)),Y+="/",W=(0,St.join)(e,Y)}else(te=T.indexOf("/*"))>-1?(W=T.slice(0,te+1),$=(0,St.relative)(e,W)):_.files.indexOf("/")>-1&&(W=T.slice(0,T.lastIndexOf("/")+1),$=(0,St.relative)(e,W));let se=!1;if(vd.isMainThread&&h.setupDirectory&&(se=await h.setupDirectory?.(k,W,t)),t.isWorker&&h.handleDirectory&&(se=await h.handleDirectory?.(k,W,t)),se){f=!0;continue}for(let Y of await(0,bz.default)(T,{onlyFiles:!1,objectMode:!0})){let{path:ne,dirent:ue}=Y;f=!0;let ae=(0,St.relative)(e,ne).replace(/\\/g,"/");if($)if(ae.startsWith($))ae=ae.slice($.length+1);else throw new Error(`The root path '${_.root}' does not reference a valid part of the file path '${ae}'.The root path should be used to indicate the relative path/part of the file path for determining the exported web path.`);let pe=k+(k.endsWith("/")?"":"/")+ae;try{if(ue.isFile()){let Te=await cSe(ne);vd.isMainThread&&await h.setupFile?.(Te,pe,ne,t),t.isWorker&&await h.handleFile?.(Te,pe,ne,t)}else vd.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:
|
|
132
|
-
`;Te.message=`${ye}${Te.message}`,Te.stack=`${ye}${Te.stack}`,im?.(Te),Il.default.error(Te),t.set(_.path||"/",new Zo(Te)),Ud.set(n?d:(0,St.basename)(e),Te.message)}}}}catch(S){S.message=`Could not load component '${d}' for application '${(0,St.basename)(e)}' due to: ${S.message}`,im?.(S),((0,om.getWorkerIndex)()===0?console:Il.default).error(S),t.set(_.path||"/",new Zo(S),null,!0),Ud.set(n?d:(0,St.basename)(e),S.message)}}if(OT=u,vd.isMainThread&&!Nz&&i&&(0,om.watchDir)(e,async()=>wz()),c.extensionModule){let d=await RE((0,St.join)(e,c.extensionModule));return bT.set(o,d),d}if(!f&&t.isWorker){let d=`${e} did not load any modules, resources, or files, is this a valid component?`;im?.(new Error(d)),((0,om.getWorkerIndex)()===0?console:Il.default).error(d),Ud.set((0,St.basename)(e),d)}}catch(c){console.error(`Could not load application directory ${e}`,c),c.message=`Could not load application due to ${c.message}`,im?.(c),t.set("",new Zo(c))}}var lt,St,vd,DC,UC,xC,bz,om,Il,Oz,LC,aSe,wT,cSe,CC,MC,Nz,PC,Ud,lSe,vC,yz,bT,im,OT,dSe,Oh=be(()=>{lt=require("fs"),St=require("path"),vd=require("worker_threads"),DC=require("yaml"),UC=M(le()),xC=M(pt());B();JD();ML();cB();fB();_B();JB();LK();HK();FK();bz=M(require("fast-glob")),om=M(Ze()),Il=M(z());bb();Pr();Oz=M(me());ve();eC();LC=M(le()),aSe=M(rz());nS();uz();hs();Rz();wT=M(wt());IE();BA();({readFile:cSe}=lt.promises),CC=(0,wT.resolvePath)(UC.get(U.COMPONENTSROOT)),MC=new Map,Ud=new Map;a(wz,"loadComponentDirectories");lSe={REST:PE,rest:PE,graphql:rR,graphqlSchema:qA,roles:yb,jsResource:Nb,fastifyRoutes:pI,login:Ib,static:EI,operationsApi:aSe,customFunctions:{},http:{},clustering:RC,replication:Sa,authentication:Eh,mqtt:IC,loadEnv:gI},vC={rest:!0,graphqlSchema:{files:"*.graphql"},roles:{files:"roles.yaml"},jsResource:{files:"resources.js"},fastifyRoutes:{files:"routes/*.js",path:"."}};Object.defineProperty(vC,"static",{value:{files:"web/**"}});yz=[],bT=new Map;a(uSe,"setErrorReporter");dSe=a(()=>OT,"getComponentName");a(fSe,"symlinkHarperModule");a(NT,"loadComponent")});var dT=P((fUe,Cz)=>{var{isMainThread:Iz}=require("worker_threads"),{getTables:_Se,getDatabases:uUe,table:dUe}=(ve(),D(it)),{loadComponentDirectories:hSe,loadComponent:mSe}=(Oh(),D(bh)),{resetResources:pSe}=(Jl(),D(WD)),ESe=hw(),gSe=wt(),{dirname:SSe}=require("path"),{getConnection:TSe}=Ut(),ASe=le(),{CONFIG_PARAMS:RSe}=(B(),D(q)),{loadCertificates:ySe}=Js(),BC=new Map;async function bSe(e=!1){!Iz&&ASe.get(RSe.CLUSTERING_ENABLED)&&TSe();try{Iz&&await ESe()}catch(n){console.error(n)}let t=pSe();_Se(),t.isWorker=e,await ySe(),await mSe(SSe(gSe.getConfigFilePath()),t,"hdb",!0,BC),await hSe(BC,t);let r=[];for(let[n]of BC)n.ready&&r.push(n.ready());r.length>0&&await Promise.all(r)}a(bSe,"loadRootComponents");Cz.exports.loadRootComponents=bSe});var Ze=P((hUe,ai)=>{"use strict";HA();var{Worker:OSe,MessageChannel:NSe,parentPort:qi,isMainThread:GC,threadId:wSe,workerData:Gi}=require("worker_threads"),{PACKAGE_ROOT:ISe}=pt(),{join:Mz,isAbsolute:CSe,extname:PSe}=require("path"),{server:vz}=(Pr(),D(jl)),{watch:DSe,readdir:LSe}=require("fs/promises"),{totalmem:Pz}=require("os"),xd=(B(),D(q)),Uz=le(),oi=z(),{randomBytes:MSe}=require("crypto"),{_assignPackageExport:vSe}=ci(),Dz=1024*1024,Qa=[],Ps=[],USe=50,$C=1e4,xSe="restart",xz="request_thread_info",Bz="resource_report",Hz="thread_info",kz="added-port",BSe="ack",HC;vSe("threads",Ps);ai.exports={startWorker:kC,restartWorkers:KC,shutdownWorkers:GSe,workers:Qa,setMonitorListener:QSe,onMessageFromWorkers:$Se,onMessageByType:Yz,broadcast:KSe,broadcastWithAcknowledgement:WSe,setChildListenerByType:qSe,getWorkerIndex:Fz,getWorkerCount:qz,getTicketKeys:$z,setMainIsWorker:kSe,setTerminateTimeout:HSe,restartNumber:Gi?.restartNumber||1};Ps.onMessageByType=Yz;Ps.sendToThread=function(e,t){if(!t?.type)throw new Error("A message with a type must be provided");let r=Ps.find(n=>n.threadId===e);if(r)return r.postMessage(t),!0};ai.exports.whenThreadsStarted=new Promise(e=>{ai.exports.threadsHaveStarted=e});var VC;function HSe(e){$C=e}a(HSe,"setTerminateTimeout");function Fz(){return Gi?Gi.workerIndex:VC?0:void 0}a(Fz,"getWorkerIndex");function qz(){return Gi?Gi.workerCount:VC?1:void 0}a(qz,"getWorkerCount");function kSe(e){VC=e,ai.exports.threadsHaveStarted()}a(kSe,"setMainIsWorker");var Gz=1,IT;function $z(){return IT||(IT=GC?MSe(48):Gi.ticketKeys,IT)}a($z,"getTicketKeys");Object.defineProperty(vz,"workerIndex",{get(){return Fz()}});Object.defineProperty(vz,"workerCount",{get(){return qz()}});var Vz={[xz](e,t){zSe(t)},[Bz](e,t){jSe(t,e)}};function kC(e,t={}){let r=process.constrainedMemory?.()||Pz();r=Math.min(r,Pz(),2e4*Dz);let n=Uz.get(xd.CONFIG_PARAMS.THREADS_MAXHEAPMEMORY)??Math.max(Math.floor(r/Dz/(10+(t.threadCount||1)/4)),512),s=Math.min(Math.max(n>>6,16),64),i=[],o=[];for(let l of Ps){let u=new NSe;u.existingPort=l,i.push(u),o.push(u.port2)}PSe(e)||(e+=".js");let c=new OSe(CSe(e)?e:Mz(ISe,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:Gz=t.threadCount,name:t.name,restartNumber:ai.exports.restartNumber,ticketKeys:$z()},transferList:o,...t});for(let{port1:l,existingPort:u}of i)u.postMessage({type:kz,port:l,threadId:c.threadId},[l]);return PT(c,!0),c.unexpectedRestarts=t.unexpectedRestarts||0,c.startCopy=()=>kC(e,t),c.on("error",l=>{oi.error(`Worker index ${t.workerIndex} error:`,l)}),c.on("exit",l=>{Qa.splice(Qa.indexOf(c),1),!c.wasShutdown&&t.autoRestart!==!1&&(c.unexpectedRestarts<USe?(t.unexpectedRestarts=c.unexpectedRestarts+1,kC(e,t)):oi.error(`Thread has been restarted ${c.restarts} times and will not be restarted`))}),c.on("message",l=>{Vz[l.type]?.(l,c)}),Qa.push(c),XSe(),t.onStarted&&t.onStarted(c),c.name=t.name,c}a(kC,"startWorker");var FSe=[xd.THREAD_TYPES.HTTP];async function KC(e=null,t=Math.max(Gz>3,1),r=!0){if(GC){try{process.chdir(process.cwd())}catch(o){oi.error("Unable to reestablish current working directory",o)}if(r){let{loadRootComponents:o}=dT();await o()}ai.exports.restartNumber++,t<1&&(t=t*Qa.length);let n=[],s=[];for(let o of Qa.slice(0)){if(e&&o.name!==e||o.wasShutdown)continue;oi.trace("sending shutdown request to ",o.threadId),o.postMessage({restartNumber:ai.exports.restartNumber,type:xd.ITC_EVENT_TYPES.SHUTDOWN}),o.wasShutdown=!0,o.emit("shutdown",{});let c=FSe.indexOf(o.name)>-1,l=new Promise(u=>{let f=setTimeout(()=>{oi.warn("Thread did not voluntarily terminate, terminating from the outside",o.threadId),o.terminate()},$C*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===xd.ITC_EVENT_TYPES.CHILD_STARTED&&(oi.trace("Worker has started",u.threadId),d(),s.splice(s.indexOf(f)),u.off("message",_))},"startListener");oi.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}=cd();r&&(e==="http"||!e)&&Uz.get(xd.CONFIG_PARAMS.CLUSTERING_ENABLED)&&await i({service:"clustering"})}else qi.postMessage({type:xSe,workerType:e})}a(KC,"restartWorkers");function qSe(e,t){Vz[e]=t}a(qSe,"setChildListenerByType");function GSe(e){return KC(e,1/0,!1)}a(GSe,"shutdownWorkers");var Kz=[];function $Se(e){Kz.push(e)}a($Se,"onMessageFromWorkers");var FC=new Map;function Yz(e,t){let r=FC.get(e);r||FC.set(e,r=[]),r.push(t)}a(Yz,"onMessageByType");var VSe=10;async function KSe(e,t){let r=0;for(let n of Ps)try{n.postMessage(e),r++>VSe&&(r=0,await new Promise(setImmediate))}catch(s){oi.error("Unable to send message to worker",s)}t&&zz(e,null)}a(KSe,"broadcast");var CT=new Map,YSe=1;function WSe(e){return new Promise(t=>{let r=0;for(let n of Ps)try{let s=YSe++,i=a(()=>{CT.delete(s),--r===0&&t(),n!==qi&&--n.refCount===0&&n.unref()},"ack_handler");i.port=n,n.ref(),n.refCount=(n.refCount||0)+1,CT.set(e.requestId=s,i),n.hasAckCloseListener||(n.hasAckCloseListener=!0,n.on(n.close?"close":"exit",()=>{for(let[,o]of CT)o.port===n&&o()})),n.postMessage(e),r++}catch(s){oi.error("Unable to send message to worker",s)}r===0&&t()})}a(WSe,"broadcastWithAcknowledgement");function zSe(e){e.postMessage({type:Hz,workers:Wz()})}a(zSe,"sendThreadInfo");function Wz(){let e=Date.now();return Qa.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(Wz,"getChildWorkerInfo");function jSe(e,t){e.resources=t,e.resources.updated=Date.now()}a(jSe,"recordResourceReport");var qC;function QSe(e){qC=e}a(QSe,"setMonitorListener");var JSe=1e3,Lz=!1;function XSe(){Lz||(Lz=!0,setInterval(()=>{for(let e of Qa){let t=e.performance.eventLoopUtilization(),r;e.lastTotalELU?r=e.performance.eventLoopUtilization(t,e.lastTotalELU):r=t,e.lastTotalELU=t,e.recentELU=r}qC&&qC()},JSe).unref())}a(XSe,"startMonitoring");var ZSe=1e3;if(qi&&Gi?.addPorts){PT(qi);for(let e=0,t=Gi.addPorts.length;e<t;e++){let r=Gi.addPorts[e];r.threadId=Gi.addThreadIds[e],PT(r)}setInterval(()=>{let e=process.memoryUsage();qi.postMessage({type:Bz,heapTotal:e.heapTotal,heapUsed:e.heapUsed,external:e.external,arrayBuffers:e.arrayBuffers})},ZSe).unref(),HC=a(()=>new Promise((e,t)=>{qi.on("message",r),qi.postMessage({type:xz});function r(n){n.type===Hz&&(qi.off("message",r),e(n.workers))}a(r,"receiveThreadInfo")}),"getThreadInfo")}else HC=Wz;ai.exports.getThreadInfo=HC;function PT(e,t){Ps.push(e),e.on("message",r=>{if(r.type===kz)r.port.threadId=r.threadId,PT(r.port);else if(r.type===BSe){let n=CT.get(r.id);n&&n()}else zz(r,e)}).on("close",()=>{Ps.splice(Ps.indexOf(e),1)}).on("exit",()=>{Ps.splice(Ps.indexOf(e),1)}),t?e.refCount=100:e.unref()}a(PT,"addPort");function zz(e,t){for(let n of Kz)n(e,t);let r=FC.get(e.type);if(r)for(let n of r)try{n(e,t)}catch(s){oi.error(s)}}a(zz,"notifyMessageListeners");if(GC){let e,t,r=new Set,n=a(async(s,i)=>{i&&(e=i);for(let o of await LSe(s,{withFileTypes:!0}))o.isDirectory()&&o.name!=="node_modules"&&n(Mz(s,o.name));try{for await(let{filename:o}of DSe(s,{persistent:!1}))r.add(o),t&&clearTimeout(t),t=setTimeout(async()=>{e&&await e(),await KC(),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");ai.exports.watchDir=n,process.env.WATCH_DIR&&n(process.env.WATCH_DIR)}else qi.on("message",async e=>{let{type:t}=e;t===xd.ITC_EVENT_TYPES.SHUTDOWN&&(ai.exports.restartNumber=e.restartNumber,qi.unref(),setTimeout(()=>{oi.warn("Thread did not voluntarily terminate",wSe),process.exit(0)},$C).unref())})});var wx={};Ue(wx,{ACTION_32_BIT:()=>Ap,ACTION_64_BIT:()=>rTe,AUDIT_STORE_OPTIONS:()=>fh,Decoder:()=>Xc,HAS_BLOBS:()=>pn,HAS_CURRENT_RESIDENCY_ID:()=>Sc,HAS_EXPIRATION_EXTENDED_TYPE:()=>Df,HAS_ORIGINATING_OPERATION:()=>Pf,HAS_PREVIOUS_RESIDENCY_ID:()=>Tc,REMOTE_SEQUENCE_UPDATE:()=>cg,createAuditEntry:()=>ru,getLastRemoved:()=>kO,openAuditStore:()=>MT,readAuditEntry:()=>Ot,removeAuditEntry:()=>vT,setAuditRetention:()=>tTe,transactionKeyEncoder:()=>nj});function MT(e){let t=e.auditStore=e.openDB(YC.AUDIT_STORE_NAME,{create:!1,...fh});t||(t=e.auditStore=e.openDB(YC.AUDIT_STORE_NAME,fh),Qz(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=zC;Qh(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()-WC/(1+i*i)})){try{_=vT(t,m,S)}catch(g){Bd.warn("Error removing audit entry",g)}if(h=m,await new Promise(setImmediate),++d>=eTe){o=10;break}}await _}finally{d===0?o=Math.min(o<<1,WC/10):(Qz(t,h),o>100&&(o=o>>1)),f(void 0),c()}},o).unref()});return u}if(a(c,"scheduleAuditCleanup"),t.scheduleAuditCleanup=c,(0,cm.getWorkerIndex)()===(0,cm.getWorkerCount)()-1&&c(),(0,cm.getWorkerIndex)()===0&&!jz)for(let l of t.getKeys({reverse:!0,limit:1}))l>Date.now()&&(jz=!0,Bd.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 vT(e,t,r){let n=nTe(r),s;if(n&pn){s=Ot(r);let i=e.tableStores[s.tableId],o=i?.getEntry(s.recordId);(!o||o.version!==s.version||!o.value)&&_c(()=>ea(s.getValue(i)),i.rootStore)}if((n&15)===jC){s=s||Ot(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 Qz(e,t){QC[0]=t,e.put(Symbol.for("last-removed"),sj)}function kO(e){let t=e.get(Symbol.for("last-removed"));if(t)return sj.set(t),QC[0]}function tTe(e,t=zC){WC=e,zC=t}function ru(e,t,r,n,s,i,o,c,l,u,f,d,_){let h=ij[o];if(!h)throw new Error(`Invalid audit entry type ${o}`);let m=1;if(n&&(n>1?Ja.setFloat64(0,n):Ds.set(fR),m=9),l){if(l&255)throw new Error("Illegal extended type");m+=3}A(s),A(t),g(r),Ja.setFloat64(m,e),m+=8,l&Sc&&A(u),l&Tc&&A(f),l&Df&&(Ja.setFloat64(m,d),m+=8),l&Pf&&A(oj[_]),i?g(i):Ds[m++]=0,l?Ja.setUint32(n?8:0,h|l|3221225472):Ds[n?8:0]=h;let S=Ds.subarray(0,m);if(c)return Buffer.concat([S,c]);return S;function g(E){let T=m;m+=1,m=(0,Cl.writeKey)(E,Ds,m);let w=m-T-1;w>127?w>16383?(Bd.error("Key or username was too large for audit entry",E),m=T+1,Ds[T]=0):(Ds.copyWithin(T+2,T+1,m),Ja.setUint16(T,w|32768),m++):Ds[T]=w}function A(E){E<128?Ds[m++]=E:E<16384?(Ja.setUint16(m,E|32768),m+=2):E<1056964608?(Ja.setUint32(m,E|3221225472),m+=4):(Ds[m]=255,Ja.setUint32(m+1,E),m+=5)}}function nTe(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 Xc(e.buffer,e.byteOffset,e.byteLength));return n.position=t,n.readInt()}function Ot(e,t=0,r=void 0){try{let n=e.dataView||(e.dataView=new Xc(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&Sc&&(_=n.readInt()),i&Tc&&(h=n.readInt()),i&Df&&(m=n.readFloat64()),i&Pf){let T=n.readInt();S=oj[T]}l=n.readInt();let g=n.position,A=n.position+=l,E;return{type:ij[i&7],tableId:c,nodeId:o,get recordId(){return(0,Cl.readKey)(e,u,f)},getBinaryRecordId(){return e.subarray(u,f)},version:d,previousLocalTime:s,get user(){return A>g?(0,Cl.readKey)(e,g,A):void 0},get encoded(){return t?e.subarray(t,r):e},getValue(T,w,v){if(i&DT||i&am&&!w)return E||(E=_c(()=>T.decoder.decode(e.subarray(n.position,r)),T.rootStore)),E;if(i&am&&v)return cb(T.getEntry(this.recordId),v,T)},getBinaryValue(){return i&(DT|am)?e.subarray(n.position,r):void 0},extendedType:i,residencyId:_,previousResidencyId:h,expiresAt:m,originatingOperation:S}}catch(n){return Bd.error("Reading audit entry error",n,e),{}}}var Cl,LT,YC,cm,rj,Bd,Ds,Ja,nj,fh,WC,eTe,QC,sj,zC,jz,DT,am,Jz,jC,Xz,Zz,ej,tj,Ap,rTe,cg,Sc,Tc,Pf,Df,pn,ij,oj,Xc,ro=be(()=>{Cl=require("ordered-binary"),LT=M(le()),YC=M(vt());B();cm=M(Ze()),rj=M(oe());nu();Bd=M(z());lE();ls();nT();(0,LT.initSync)();Ds=Buffer.alloc(2816),Ja=new DataView(Ds.buffer,Ds.byteOffset,2816),nj={writeKey(e,t,r){return e===Cf?(t.set(Cf,r),r+8):typeof e=="number"?((t.dataView||(t.dataView=new DataView(t.buffer,t.byteOffset,t.byteLength))).setFloat64(r,e),r+8):(0,Cl.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,Cl.readKey)(e,t,r)}},fh={encoding:"binary",keyEncoder:nj},WC=(0,rj.convertToMS)((0,LT.get)(U.LOGGING_AUDITRETENTION))||86400*3,eTe=1e3,QC=new Float64Array(1),sj=new Uint8Array(QC.buffer),zC=1e4,jz=!1;a(MT,"openAuditStore");a(vT,"removeAuditEntry");a(Qz,"updateLastRemoved");a(kO,"getLastRemoved");a(tTe,"setAuditRetention");DT=16,am=32,Jz=1,jC=2,Xz=3,Zz=4,ej=5,tj=6,Ap=14,rTe=15,cg=11,Sc=512,Tc=1024,Pf=2048,Df=4096,pn=8192,ij={put:Jz|DT,[Jz]:"put",delete:jC,[jC]:"delete",message:Xz|DT,[Xz]:"message",invalidate:Zz|am,[Zz]:"invalidate",patch:ej|am,[ej]:"patch",relocate:tj,[tj]:"relocate"},oj={insert:1,update:2,upsert:3,1:"insert",2:"update",3:"upsert"};a(ru,"createAuditEntry");a(nTe,"readAction");a(Ot,"readAuditEntry");Xc=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 ZC(e,t,r,n,s){let i=e.primaryStore.env.path,o=e.primaryStore.tableId,c;s?.crossThreads===!1?(c=cj,sTe(e.primaryStore,e.auditStore)):(c=aj,e.primaryStore.env.hasSubscriptionCommitListener||(e.primaryStore.env.hasSubscriptionCommitListener=!0,e.primaryStore.on("committed",()=>{lj(aj[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=Ql(t);let f=new XC(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 lj(e){if(!e)return;let t=e.auditStore;t.resetReadTxn(),uj(e.auditStore);let r;for(let{key:n,value:s}of t.getRange({start:e.lastTxnTime,exclusiveStart:!0})){e.lastTxnTime=n;let i=Ot(s),o=e[i.tableId];if(!o)continue;let c=i.recordId,l=Ql(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,JC.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,JC.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 sTe(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=cj[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{lj(l)}finally{r.threadLocalWrites[0]=l.lastTxnTime,r.unlock("thread-local-writes")}},"acquiredLock");r.attemptLock("thread-local-writes",u)&&u()})}}function uj(e){e.nextTransaction?.resolve();let t;e.nextTransaction=new Promise(r=>{t=r}),e.nextTransaction.resolve=t}function Xk(e){return e.nextTransaction||(ZC({primaryStore:e,auditStore:e},null,null,0,{scope:"full-database"}),uj(e)),e.nextTransaction}var JC,aj,cj,XC,FO=be(()=>{JC=M(z());Vl();Jl();ro();aj=Object.create(null),cj=Object.create(null);a(ZC,"addSubscription");XC=class extends Ln{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(lj,"notifyFromTransactionData");a(sTe,"listenToCommits");a(uj,"nextTransaction");a(Xk,"whenNextTransaction")});var Jw={};Ue(Jw,{EVICTED:()=>Jo,INVALIDATED:()=>fn,coerceType:()=>BT,makeTable:()=>kT,setServerUtilities:()=>fTe});function kT(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:A}=e;S??=0;let{attributes:E}=e;E||(E=[]);let T=mR(i,n,l),w,v,k={},$=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&&(k=K);let Y,ne=[],ue=[],ae=1,pe=2,Te={},ye={},Qt=864e5,ut=0,Rr,is,Pn,xl=!1,Bl,eA=new Map,tA=new Map,Lt,$d,ym=Dl.get(U.REPLICATION_DATABASES);if(Array.isArray(ym)){for(let K of ym)if(K.name===c&&K.replicateTo>=0){$d=K.replicateTo;break}}let bm=i.getRange({start:!1,end:!1}).constructor,Vd=10,Om=6;g&&zd(),Qh(i.env.path,K=>{if(v)return Ki(K)});class Ce extends $r{#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 R=a(I=>{let L=this.sources;if(L=L.filter(H=>H.intermediateSource&&H[I]&&(!H[I].reliesOnPrototype||H.prototype[I])),L.length>0)if(L.length===1){let H=L[0];return(N,x,G)=>{if(N?.source!==H)return H[I](x,G,N)}}else return(H,N,x)=>{let G=[];for(let j of L){if(H?.source===j)break;G.push(j[I](N,x,H))}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,H,N)=>{if(!L?.source)return y[I](H,N,L)}},"getApplyToCanonicalSource");Te={put:b("put"),patch:b("patch"),delete:b("delete"),publish:b("publish")},ye={put:R("put"),patch:R("patch"),delete:R("delete"),publish:R("publish"),invalidate:R("invalidate")};let C=y.shouldRevalidateEvents;return(async()=>{let I=!1,L,H=a(async(N,x)=>{let G=N.value,j=N.table?Ve[c][N.table]:Ce;if(c===Jd&&(N.table===Gl.ROLE_TABLE_NAME||N.table===Gl.USER_TABLE_NAME)&&(I=!0),N.id===void 0&&(N.id=G[j.primaryKey],N.id===void 0))throw new Error("Replication message without an id "+JSON.stringify(N));N.source=p;let ie={residencyId:tc(N.residencyList),isNotification:!0,ensureLoaded:!1,nodeId:N.nodeId},F=await j.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&&A==null&&(A=!0);let x={crossThreads:!1,inTransactionUpdates:!0,supportsTransactions:!0,omitCurrent:!0},G=p.subscribeOnThisThread?p.subscribeOnThisThread((0,Pl.getWorkerIndex)(),x):(0,Pl.getWorkerIndex)()===0,j=N&&G&&await p.subscribe?.(x);if(j){let ie;for await(let F of j)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(H(F,ie));continue}!F.timestamp&&F.version&&(F.timestamp=F.version);let Z=bt(F,()=>{if(F.type==="transaction"){let ce=[];for(let ee of F.writes)try{ce.push(H(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&&(dt({table:s,database:c,attributes:ce,origin:"cluster"}),um.signalSchemaChange(new dm.SchemaEventMsg(process.pid,Gt.CREATE_TABLE,c,s)))}else return F.beginTxn?(ie=F,ie.write_promises=[H(F,F)],new Promise(ce=>{ie.resolve=()=>ce(Promise.all(ie.write_promises))})):H(F,F)});ie&&(ie.committed=Z),I&&Z&&!Z?.waitingForUserChange&&(Z.then(()=>um.signalUserChange(new dm.UserEventMsg(process.pid))),Z.waitingForUserChange=!0),F.onCommit&&(Z?Z.then(F.onCommit):F.onCommit())}catch(Ge){xe.default.error?.("error in subscription handler",Ge)}}}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,R){let y=super.getResource(p,O,R);if(p!=null){wr(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=!R?.async||i.cache?.get?.(p),C=qr(O),I=C.getReadTxn();if(I?.isDone)throw new Error("You can not read from a transaction that has already been committed/aborted");return Hl(p,O,{transaction:I,ensureLoaded:R?.ensureLoaded},b,L=>{if(L?Ce._updateResource(y,L):y.#e=null,O.onlyIfCached&&O.noCacheStore){if(!y.doesExist())throw new Nr.ServerError("Entry is not cached",504)}else if(R?.ensureLoaded){let H=kl(p,L,O,y);if(H)return C?.disregardReadTxn(),y.#i=!0,tP(H,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=kl(this.getId(),this.#r,this.getContext());if(p)return this.#i=!0,tP(p,O=>{this.#r=O,this.#e=O.value,this.#n=O.version})}static getNewId(){let p=k?.type;if(p==="String"||p==="ID")return super.getNewId();if(!Lt){let b=i.getEntry(Symbol.for("id_allocation")),C=b?.value,I;if(C&&C.nodeName===server.hostname&&(!hTe(i)||C.pid===process.pid)){let L=C.start,H=C.end;I=L;for(let N of i.getKeys({start:H,end:L,limit:1,reverse:!0}))I=N}else C=y(b?.version??null),I=C.start;Lt=new BigInt64Array([BigInt(I)+1n]),Lt=new BigInt64Array(i.getUserSharedBuffer("id",Lt.buffer)),Lt.maxSafeId=C.end}let O=Number(Atomics.add(Lt,0,1n)),R=p==="Int"?512:1048576;if(O+R>=Lt.maxSafeId){let b=a(C=>{Lt.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(),H=Number(Lt[0]);for(let G of i.getKeys({start:H+1,end:I,limit:1,transaction:L}))I=G;L?.done();let{value:N,version:x}=i.getEntry(Symbol.for("id_allocation"));if(Lt.maxSafeId<I){if(N.end>Lt.maxSafeId-100)return;xe.default.info?.("New id allocation",O,Lt.maxSafeId,x),i.put(Symbol.for("id_allocation"),{start:N.start,end:Lt.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 ${Lt.maxSafeId}, but id of ${I} detected`);let G=y(x);G.alreadyUpdated||Atomics.store(Lt,0,BigInt(G.start+1)),Lt.maxSafeId=G.end}},"updateEnd");O+R===Lt.maxSafeId?setImmediate(b):O+100>=Lt.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,H,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 j of i.getKeys({start:x,limit:1,reverse:!0}))L=j;H=C;for(let j of i.getKeys({start:x+1,end:C,limit:1}))H=j;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,H,I))}while(!(I<H-x&&(I<x-L||L===0)));return i.transactionSync(()=>{let j=i.getEntry(Symbol.for("id_allocation"));return(j?.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,...j.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,Ki()}static getResidencyRecord(p){return f.get([Symbol.for("residency_by_id"),p])}static setResidency(p){Ce.getResidency=p&&((O,R)=>{try{return p(O,R)}catch(y){throw y.message+=` in residency function for table ${s}`,y}})}static setResidencyById(p){Ce.getResidencyById=p&&(O=>{try{return p(O)}catch(R){throw R.message+=` in residency function for table ${s}`,R}})}static getResidency(p,O){if(Ce.getResidencyById)return Ce.getResidencyById(p[t]);let R=$d;if(O.replicateTo!=null){if(Array.isArray(O.replicateTo))return O.replicateTo.includes(server.hostname)?O.replicateTo:[server.hostname,...O.replicateTo];O.replicateTo>=0&&(R=O.replicateTo)}if(R>=0&&server.nodes){let y=[server.hostname];if(O.previousResidency)y.push(...O.previousResidency.slice(0,R));else{let b=server.nodes.map(L=>L.name),C=Math.floor(b.length*Math.random());y.push(...b.slice(C,C+R));let I=C+R-b.length;I>0&&y.push(...b.slice(0,I))}return y}}static enableAuditing(p=!0){g=p,p&&zd(),Ce.audit=p}static coerceId(p){return p===""?null:BT(p,k)}static async dropTable(){delete Ve[c][s];for(let p of i.getRange({versions:!0,snapshot:!1,lazy:!0}))p.metadataFlags&pn&&p.value&&ea(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 xT.default.remove(data_path),await xT.default.remove(data_path===standard_path?data_path+MDB_LOCK_FILE_SUFFIX:path.join(path.dirname(data_path),MDB_LEGACY_LOCK_FILE_NAME));um.signalSchemaChange(new dm.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(R=>(O.recordCount=R.recordCount,O.estimatedRecordRange=R.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 R=Fr(p);if(R?.read){if(R.isSuperUser)return!0;let y=R.attribute_permissions,b=O?.select;if(y?.length>0||xl&&b){if(O||(O={}),b){let C=y?.length>0&&eP(y,"read");O.select=b.map(I=>{let L=I.name||I;if(!C||C[L]){let H=Pn[L]?.definition?.tableClass;if(H){if(I.name||(I={name:I}),!H.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&&!Pn[C.attribute_name]).map(C=>C.attribute_name);return O}else return!0}}allowUpdate(p,O){let R=Fr(p);if(R?.update){let y=R.attribute_permissions;if(y?.length>0){let b=eP(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 ql(this.getContext())}}allowCreate(p,O){if(this.isCollection){let R=Fr(p);if(R?.insert){let y=R.attribute_permissions;if(y?.length>0){let b=eP(y,"insert");for(let C in O)if(!b[C])return!1;return ql(this.getContext())}else return ql(this.getContext())}}else return this.allowUpdate(p,{})}allowDelete(p){return Fr(p)?.delete&&ql(this.getContext())}update(p,O){if(!qr(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===fj?this.set(p,(+this.getProperty(p)||0)+O):(this.#s||this.update(),this.set(p,new fE(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 R=this.getContext(),y=this.getId();wr(y),qr(this.getContext()).addWrite({key:y,store:i,invalidated:!0,entry:this.#r,before:Te.invalidate?.bind(this,R,y),beforeIntermediate:ye.invalidate?.bind(this,R,y),commit:a((C,I)=>{if(!(Vi(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,fn,g,{user:R?.user,residencyId:O?.residencyId,nodeId:O?.nodeId},"invalidate")}},"commit")})}_writeRelocate(p){let O=this.getContext(),R=this.getId();wr(R),qr(this.getContext()).addWrite({key:R,store:i,invalidated:!0,entry:this.#r,before:Te.relocate?.bind(this,O,R),beforeIntermediate:ye.relocate?.bind(this,O,R),commit:a((b,C)=>{if(Vi(b,C,p?.nodeId)<=0)return;let I=Ce.getResidencyRecord(p.residencyId),L=0,H=null,N=C?.value;if(I&&!I.includes(server.hostname)){for(let x in r)H||(H={}),H[x]=N(x);L=fn}else H=N;xe.default.trace?.(`Relocating entry id: ${R}, timestamp: ${new Date(b).toISOString()}`),T(R,H,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 R={previousResidency:this.getResidencyRecord(p.residencyId),isRelocation:!0},y=Yi(this.getResidency(O.value,R)),b;if(y){if(!y.includes(server.hostname))return!1;b=tc(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,R){let y=this.Source,b;if(!((v||g)&&(!O||(b=i.getEntry(p),!b||!O)||b.version!==R))){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,R,Jo,null,null,null,!0)}if(i.ifVersion(p,R,()=>{an(p,O,null)}),g)return T(p,null,b,R,Jo,null,null,null,!0);gc(i,b??i.getEntry(p),R)}}lock(){throw new Error("Not yet implemented")}static operation(p,O){return p.table||=s,p.schema||=c,Tj.operation(p,O)}put(p){this.update(p,!0)}patch(p){this.update(p,!1)}_writeUpdate(p,O,R){let y=this.getContext(),b=qr(y),C=this.getId();wr(C);let I=this.#r;this.#s=O?fj:lTe;let L={key:C,store:i,entry:I,nodeName:y?.nodeName,validate:a(H=>{p||(p=this.#t),O||p&&uE(this.#t===p?this:p)?y?.source||(b.checkOverloaded(),this.validate(p,!O),te&&(p[te.name]=te.type==="Date"?new Date(H):te.type==="String"?new Date(H).toISOString():H),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(H):W.type==="String"?new Date(H).toISOString():H),p=xc(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,xc(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,xc(this)):null,commit:a((H,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=H;let G=N?.value,j=p;this.#s=0;let ie=!1,F=Vi(H,N,R?.nodeId),Ge;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>H||fe>=H&&_e>0;){let De=l.get(_e);if(!De)break;let we=Ot(De);if(fe=we.version,fe>=H){if(fe===H){if(F=Vi(H,{version:fe,localTime:_e},R?.nodeId),F===0)return;if(F>0)continue}if(we.type==="patch")Ae.push(we),Ge=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(j=cE(j,we,O),xe.default.debug?.("Rebuilding update with future patch:",j),!j)return}}else{if(O)return;j=cE(j,G,O),xe.default.debug?.("Rebuilding update without audit:",j)}let Z;if(O?Z=j:(this.#e=G,Z=xc(this,j)),this.#e=Z,Z&&Z.getRecord)throw new Error("Can not assign a record to a record, check for circular references");let ce;if(R?.residencyId!=null)ce=R.residencyId;else{I?.residencyId&&(y.previousResidency=Ce.getResidencyRecord(I.residencyId));let _e=Yi(Ce.getResidency(Z,y));if(_e&&!_e.includes(server.hostname))if(Ge??=Z,ie=!0,Ce.getResidencyById)Z=void 0;else{Z=null;for(let fe in r)Z||(Z={}),Z[fe]=Ge[fe]}ce=tc(_e)}O||(Ge=p);let ee=y?.expiresAt??(m?m+Date.now():-1);xe.default.trace?.(`Saving record with id: ${C}, timestamp: ${new Date(H).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""}})()),an(C,G,Z);let Q=O?"put":"patch";T(C,Z,N,H,ie?fn:0,g,{omitLocalRecord:ie,user:y?.user,residencyId:ce,expiresAt:ee,nodeId:R?.nodeId,originatingOperation:y?.originatingOperation},Q,!1,Ge),y.expiresAt&&Ki()},"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=qr(this.getContext()),R=this.getId();wr(R);let y=this.getContext();return O.addWrite({key:R,store:i,entry:this.#r,nodeName:y?.nodeName,before:Te.delete?.bind(this,y,R),beforeIntermediate:ye.delete?.bind(this,y,R),commit:a((b,C,I)=>{let L=C?.value;I&&(y&&C?.version>(y.lastModified||0)&&(y.lastModified=C.version),Ce._updateResource(this,C)),!(Vi(b,C,p?.nodeId)<=0)&&(an(this.getId(),L),xe.default.trace?.(`Deleting record with id: ${R}, txn timestamp: ${new Date(b).toISOString()}`),g||A?(T(R,null,this.#r,b,0,g,{user:y?.user,nodeId:p?.nodeId},"delete"),g||Ki()):gc(i,C))},"commit")}),!0}search(p){let O=this.getContext(),R=qr(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?k:fi(E,De);if(we)(we.type||LA[Ae.comparator])&&(Ae[1]===void 0?Ae.value=H(Ae.value,we):Ae[1]=H(Ae[1],we));else if(De!=null)throw(0,Nr.handleHDBError)(new Error,`${De} is not a defined attribute`,404);if(Ae.chainedConditions)if(Ae.chainedConditions.length===1&&(!Ae.operator||Ae.operator=="and")){let _r=Ae.chainedConditions[0],Ir,Ms;if(_r.comparator==="gt"||_r.comparator==="greater_than"||_r.comparator==="ge"||_r.comparator==="greater_than_equal"?(Ir=Ae,Ms=_r):(Ir=_r,Ms=Ae),Ir.comparator!=="lt"&&Ir.comparator!=="less_than"&&Ir.comparator!=="le"&&Ir.comparator!=="less_than_equal")throw new Error("Invalid chained condition, only less than and greater than conditions can be chained together");let Re=Ms.comparator==="ge"||Ms.comparator==="greater_than_equal",yt=Ir.comparator==="le"||Ir.comparator==="less_than_equal";Ae.comparator=(Re?"ge":"gt")+(yt?"le":"lt"),Ae.value=[Ms.value,Ir.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,gj.sortBy)(Q,Qm(Ce)):Q}a(L,"orderConditions");function H(Q,_e){return Array.isArray(Q)?Q.map(fe=>BT(fe,_e)):BT(Q,_e)}a(H,"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 Nr.ClientError("Sort requires an attribute");if(b=y.find(_e=>zl(_e.attribute)===zl(Q)),!b){let _e=fi(E,Q);if(!_e)throw(0,Nr.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,Nr.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 j=p.select;if(y.length===0&&(y=[{attribute:t,comparator:"greater_than",value:!0}]),p.explain)return{conditions:y,operator:N,postOrdering:G,selectApplied:!!j};let ie=R.useReadTxn(),F=MA(y,N,Ce,ie,p,O,(Q,_e)=>Yd(Q,j,O,ie,_e),C),Ge=p.ensureLoaded!==!1;G||(F=ee(F));let Z=Ce.transformEntryForSelect(j,O,ie,C,Ge,!0),ce=Ce.transformToOrderedSelect(F,j,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,R.doneReadTxn()},ce.selectApplied=!0,ce.getColumns=()=>{if(j){let Q=[];for(let _e of j)_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,R,y,b,C){let I=new bm;if(R){p=Yd(p,O,y,b,null);let L;I.iterate=function(){let N,x=p[Symbol.asyncIterator]?p[Symbol.asyncIterator]():p[Symbol.iterator](),G,j=R.dbOrderedAttribute,ie,F,Ge=!0;function Z(ee){let Q=ee.next&&Z(ee.next),_e=ee.descending;return(fe,Ae)=>{let De=Fl(fe,ee.attribute,y),we=Fl(Ae,ee.attribute,y),_r=_e?(0,Ll.compareKeys)(we,De):(0,Ll.compareKeys)(De,we);return _r===0?Q?.(fe,Ae)||0:_r}}a(Z,"createComparator");let ce=Z(R);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),j){let _e=Fl(Q,j,y);if(Ge)Ge=!1,F=_e;else if(_e!==F){F=_e,ie=Q;break}}L.push(Q)}while(!0);return R.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 H=a(N=>{if(typeof O=="object"&&Array.isArray(N.attribute))for(let x=0;x<O.length;x++){let G=O[x],j;if(G.name===N.attribute[0]){for(j=G.sort||(G.sort={});j.next;)j=j.next;j.attribute=N.attribute.slice(1),j.descending=N.descending}else G===N.attribute[0]&&(O[x]=j={name:G,sort:{attribute:N.attribute.slice(1),descending:N.descending}})}N.next&&H(N.next)},"applySortingOnSelect");H(R)}else I.iterate=(p[Symbol.asyncIterator]||p[Symbol.iterator]).bind(p),I=I.map(function(L){try{let H=C.call(this,L);return typeof H?.catch=="function"?H.catch(N=>{throw N.partialObject={[t]:L.key},N}):H}catch(H){throw H.partialObject={[t]:L.key},H}});return I}static transformEntryForSelect(p,O,R,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,H=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&fn){if(N.metadataFlags&fn&&O.replicateFrom===!1&&C&&N.residencyId)return Za.SKIP;if(N=Hl(N.key??N,O,{transaction:R,lazy:p?.length<4,ensureLoaded:b},this?.isSync,G=>G),N?.then)return N.then(H.bind(this));x=N?.value}if(I&&N?.metadataFlags&(fn|Jo)||N?.expiresAt!=null&&N?.expiresAt<Date.now()){if(O.onlyIfCached&&O.noCacheStore)return{[t]:N.key,message:"This entry has expired"};let G=kl(N.key??N,N,O);if(G?.then)return G.then(H)}}if(x==null)return C?Za.SKIP:x;if(p&&!(p[0]==="*"&&p.length===1)){let G,j=a((F,Ge)=>{let Z;typeof F=="object"?Z=F.name:Z=F;let ce=Pn?.[Z],ee;if(ce){let Q=y?.[Z];if(Q)if(Q.hasMappings){let fe=ce.from?x[ce.from]:zl(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,R,Q,b));if(Array.isArray(fe)){let we=[],_r=Ae.transformToOrderedSelect(fe,F.select,typeof F.sort=="object"&&F.sort,O,R,De)[this.isSync?Symbol.iterator:Symbol.asyncIterator](),Ir=a(Re=>{for(;!Re.done;){if(Re?.then)return Re.then(Ir);we.push(Re.value),Re=_r.next()}Ge(we,Z)},"nextValue"),Ms=Ir(_r.next());Ms&&(G||(G=[]),G.push(Ms));return}else if(fe=De.call(this,fe),fe?.then){G||(G=[]),G.push(fe.then(we=>Ge(we,Z)));return}}Ge(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,R,null)({value:ee}));Ge(ee,Z)},"selectAttribute"),ie;if(typeof p=="string")j(p,F=>{ie=F});else if(Array.isArray(p))if(p.asArray)ie=[],p.forEach((F,Ge)=>{F==="*"?p[Ge]=x:j(F,Z=>ie[Ge]=Z)});else{ie={};let F=p.forceNulls;for(let Ge of p)if(Ge==="*")for(let Z in x)ie[Z]=x[Z];else j(Ge,(Z,ce)=>{Z===void 0&&F&&(Z=null),ie[ce]=Z})}else throw new Nr.ClientError("Invalid select"+p);return G?Promise.all(G).then(()=>ie):ie}return x},"transform");return H}async subscribe(p){if(!l)throw new Error("Can not subscribe to a table without an audit log");g||dt({table:s,database:c,schemaDefined:u,attributes:E,audit:!0}),p||(p={});let O=!p.rawEvents,R=[],y=this,b=ZC(Ce,this.getId()??null,function(I,L,H,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,H),G="put"}let j={id:I,localTime:H,value:x,version:L.version,type:G,beginTxn:N};R?R.push(j):this.send(j)}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 H=p.startTime;if(this.isCollection){if(H){if(L)throw new Nr.ClientError("startTime and previousCount can not be combined for a table level subscription");for(let{key:N,value:x}of l.getRange({start:H,exclusiveStart:!0,snapshot:!1})){let G=Ot(x);if(G.tableId!==n)continue;let j=G.recordId;if(I==null||pj(I,j)){let ie=G.getValue(i,O,N);if(b.send({id:j,localTime:N,value:ie,version:G.version,type:G.type}),b.queue?.length>hj&&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 j=Ot(G);if(j.tableId!==n)continue;let ie=j.recordId;if(I==null||pj(I,ie)){let F=j.getValue(i,O,x);if(N.push({id:ie,localTime:x,value:F,version:j.version,type:j.type}),--L<=0)break}}catch(j){xe.default.error("Error getting history entry",x,j)}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:j}of i.getRange({start:I??!1,end:I==null?void 0:[I,Ll.MAXIMUM_KEY],versions:!0,snapshot:!1}))if(x&&(b.send({id:N,localTime:j,value:x,version:G,type:"put"}),b.queue?.length>hj&&await b.waitForDrain()===!1))return}}else{L&&!H&&(H=0);let N=this.#r?.localTime;if(N===hR&&(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",H,"from",I,N),H<N){let x=[],G=N;do{let j=l.get(G);if(j){p.omitCurrent=!0;let ie=Ot(j),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>H&&L!==0);for(let j=x.length;j>0;)b.send(x[--j]);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 R)b.send(N);R=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 R=qr(this.getContext()),y=this.getId()||null;y!=null&&wr(y);let b=this.getContext();R.addWrite({key:y,store:i,entry:this.#r,nodeName:b?.nodeName,validate:a(()=>{b?.source||(R.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&&A&&!g&&Ki(),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 R,y=a((b,C,I)=>{if(C.type&&b!=null)if(O&&b.__op__&&(b=b.value),C.properties){typeof b!="object"&&(R||(R=[])).push(`Value ${Ls(b)} in property ${I} must be an object${C.type?" ("+C.type+")":""}`);let L=C.properties;for(let H=0,N=L.length;H<N;H++){let x=L[H],G=y(b[x.name],x,I+"."+x.name);G&&(b[x.name]=G)}if(C.sealed&&b!=null&&typeof b=="object")for(let H in b)L.find(N=>N.name===H)||(R||(R=[])).push(`Property ${H} is not allowed within object in property ${I}`)}else switch(C.type){case"Int":(typeof b!="number"||b>>0!==b)&&(R||(R=[])).push(`Value ${Ls(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))&&(R||(R=[])).push(`Value ${Ls(b)} in property ${I} must be an integer (from -9007199254740992 to 9007199254740992)`);break;case"Float":typeof b!="number"&&(R||(R=[])).push(`Value ${Ls(b)} in property ${I} must be a number`);break;case"ID":typeof b=="string"||b?.length>0&&b.every?.(L=>typeof L=="string")||(R||(R=[])).push(`Value ${Ls(b)} in property ${I} must be a string, or an array of strings`);break;case"String":typeof b!="string"&&(R||(R=[])).push(`Value ${Ls(b)} in property ${I} must be a string`);break;case"Boolean":typeof b!="boolean"&&(R||(R=[])).push(`Value ${Ls(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);(R||(R=[])).push(`Value ${Ls(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);(R||(R=[])).push(`Value ${Ls(b)} in property ${I} must be a bigint`)}break;case"Bytes":if(!(b instanceof Uint8Array)){if(typeof b=="string")return Buffer.from(b);(R||(R=[])).push(`Value ${Ls(b)} in property ${I} must be a Buffer or Uint8Array`)}break;case"Blob":if(!(b instanceof hi)){if(typeof b=="string"&&(b=Buffer.from(b)),b instanceof Buffer)return createBlob(b,{type:"text/plain"});(R||(R=[])).push(`Value ${Ls(b)} in property ${I} must be a Blob`)}break;case"array":if(Array.isArray(b)){if(C.elements)for(let L=0,H=b.length;L<H;L++){let N=b[L],x=y(N,C.elements,I+"[*]");x&&(b[L]=x)}}else(R||(R=[])).push(`Value ${Ls(b)} in property ${I} must be an Array`);break}C.nullable===!1&&b==null&&(R||(R=[])).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)||(R||(R=[])).push(`Property ${b} is not allowed`);if(R)throw new Nr.ClientError(R.join(". "))}getUpdatedTime(){return this.#n}wasLoadedFromSource(){return v?!!this.#i:void 0}static async addAttributes(p){let O=E.slice(0);for(let R of p){if(!R.name)throw new Nr.ClientError("Attribute name is required");if(R.name.match(/[`/]/))throw new Nr.ClientError("Attribute names cannot include backticks or forward slashes");(0,Sj.validateAttribute)(R.name),O.push(R)}return dt({table:s,database:c,schemaDefined:u,attributes:O}),Ce.indexingOperation}static async removeAttributes(p){let O=E.filter(R=>!p.includes(R.name));return dt({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=xT.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,R=1e3/2,y=performance.now(),b=Math.floor(O/2),C=p?.exactCount,I=0,L=0,H;for(let{value:N}of i.getRange({start:!0,lazy:!0,snapshot:!1}))if(N!=null&&I++,L++,await Xa(),!C&&L<b&&performance.now()-y>R){H=L;break}if(H){let N=I;I=0;for(let{value:ee}of i.getRange({start:"\uFFFF",reverse:!0,lazy:!0,limit:H,snapshot:!1}))ee!=null&&I++,await Xa();let x=H*2,G=(I+N)/x,j=Math.pow((I-N+1)/H/2,2)+G*(1-G)/x,ie=Math.max(Math.sqrt(j)*O,1),F=Math.round(G*O),Ge=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(Ge),Math.round(Z)]}}return{recordCount:I}}static updatedAttributes(){Pn=this.propertyResolvers={$id:a((p,O,R)=>({value:R.key}),"$id"),$updatedtime:a((p,O,R)=>R.version,"$updatedtime"),$record:a((p,O,R)=>R?{value:p}:p,"$record")};for(let p of this.attributes){p.isPrimaryKey&&(k=p),p.resolve=null;let O=p.relationship,R=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)"),R&&console.error("A relationship property is already computed and can not be combined with a computed function (the relationship will be given precedence)"),xl=!0,O.to)p.elements?.definition?(Pn[p.name]=p.resolve=(y,b,C)=>{let I=y[O.from?O.from:t],L=p.elements.definition.tableClass;return C?Wl({attribute:O.to,value:I},qr(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?(Pn[p.name]=p.resolve=(b,C,I)=>{let L=b[O.from];if(L!==void 0){if(p.elements){let H,N=L?.map(x=>{let G=I?y.tableClass.primaryStore.getEntry(x,{transaction:qr(C).getReadTxn()}):y.tableClass.get(x,C);return G?.then&&(H=!0),G});return O.filterMissing?H?Promise.all(N).then(x=>x.filter(Ej)):N.filter(Ej):H?Promise.all(N):N}return I?y.tableClass.primaryStore.getEntry(L,{transaction:qr(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 R&&(typeof R.from=="function"&&this.setComputedAttribute(p.name,R.from),Pn[p.name]=p.resolve=(y,b,C)=>{let I=typeof R.from=="string"?y[R.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]=()=>{}})}_E(this,this)}static setComputedAttribute(p,O){let R=fi(E,p);if(!R){console.error(`The attribute "${p}" does not exist in the table "${s}"`);return}if(!R.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 R;for(let{key:y,value:b}of l.getRange({start:0,end:p}))await Xa(),Ot(b).tableId===n&&(R=vT(l,y,b));if(O)for(let y of i.getRange({start:0,versions:!0})){let{key:b,value:C,localTime:I}=y;await Xa(),C===null&&I<p&&(R=gc(i,y))}await R}static async*getHistory(p=0,O=1/0){for(let{key:R,value:y}of l.getRange({start:p||1,end:O})){await Xa();let b=Ot(y);b.tableId===n&&(yield{id:b.recordId,localTime:R,version:b.version,type:b.type,value:b.getValue(i,!0,R),user:b.user,operation:b.originatingOperation})}}static async getHistoryOfRecord(p){let O=[];if(p==null)throw new Error("An id is required");let R=i.getEntry(p);if(!R)return O;let y=R.localTime;if(!y)throw new Error("The entry does not have a local audit time");let b=0;do{await Xa();let C=l.get(y);if(C){let I=Ot(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 Kd=Ce.prototype;return m&&Ce.setTTLExpiration(m/1e3),se&&Nm(),Ce;function an(K,p,O){let R;for(let y in r){let b=r[y],C=b.isIndexing,I=Pn[y],L=O&&(I?I(O):O[y]),H=p&&(I?I(p):p[y]);if(L===H&&!C)continue;R=!0;let N=b.indexNulls,x=(0,lm.getIndexedValues)(L,N),G=(0,lm.getIndexedValues)(H,N);if(G?.length>0){let j=new Set(G);if(x=x?x.filter(ie=>{if(j.has(ie))j.delete(ie);else return!0}):[],G=Array.from(j),(G.length>0||x.length>0)&&dj){let ie=G.concat(x).map(F=>({key:F,value:K}));b.prefetch(ie,mj)}for(let ie=0,F=G.length;ie<F;ie++)b.remove(G[ie],K)}else x?.length>0&&dj&&b.prefetch(x.map(j=>({key:j,value:K})),mj);if(x)for(let j=0,ie=x.length;j<ie;j++)b.put(x[j],K)}return R}a(an,"updateIndices");function wr(K){switch(typeof K){case"number":return!0;case"string":if(K.length<659)return!0;if(K.length>_j)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,Ll.writeKey)(K,uTe,0)>_j)throw new Error("Primary key size is too large: "+K.length);return!0}a(wr,"checkValidId");function Hl(K,p,O,R,y){if(Ce.getResidencyById&&O.ensureLoaded&&p?.replicateFrom!==!1){let C=Yi(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&fn&&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 R?b():ae>0?(ae--,b()):new Promise((C,I)=>{ae===0?(ae--,i.prefetch([K],()=>{L(),H()})):(ne.push(K),ue.push(H),ne.length>Om&&(ae--,L()));function L(){if(ne.length>0){let N=ue;i.prefetch(ne,()=>{ae===-1?L():ae++;for(let x of N)x()}),ne=[],ue=[],pe>2&&pe--}else ae=pe,pe<Vd&&pe++}a(L,"prefetch");function H(){try{C(b())}catch(N){I(N)}}a(H,"load")})}a(Hl,"loadLocalRecord");function Fr(K){if(!K?.role)return;let p=K.role.permission;if(p.super_user)return dTe;let O=p[c],R,y=O?.tables;if(y)return y[s];if(c==="data"&&(R=p[s])&&!R.tables)return R}a(Fr,"getTablePermissions");function kl(K,p,O,R){if(v){let y=!1;if(O.noCache?y=!0:(p?(!p.value||p.metadataFlags&(fn|Jo)||p.expiresAt!=null&&p.expiresAt<Date.now())&&(y=!0):y=!0,Yn(!y,"cache-hit",s)),y){let b=Wd(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&&R?.allowStaleWhileRevalidate?.(p,K)){if(b.catch(C=>xe.default.warn?.(C)),O?.onlyIfCached&&!R.doesExist())throw new Nr.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(kl,"ensureLoadedFromSource");function qr(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 oc,p.lmdbDb=i,p;p=O}while(!0)}else return new Wm}a(qr,"txnForContext");function Fl(K,p,O){if(!K)return;let R=K.value||i.getEntry(K.key)?.value;if(typeof p=="object"){let b=Pn,C=R;for(let I=0,L=p.length;I<L;I++){let H=p[I],N=b?.[H];C=N&&C?N(C,O,!0)?.value:C?.[H],b=N?.definition?.tableClass?.propertyResolvers}return C}let y=Pn[p];return y?y(R,O):R[p]}a(Fl,"getAttributeValue");function Yd(K,p,O,R,y){let b=y?.length,C={transaction:R,lazy:b>0||typeof p=="string"||p?.length<4,alwaysPrefetch:!0},I;function L(H,N){let x=H?.value;if(!x)return Za.SKIP;for(let G=0;G<b;G++)if(!I?.includes(G)&&!y[G](x,H))return Za.SKIP;return N!==void 0&&(H.key=N),H}if(a(L,"processEntry"),b>0||!K.hasEntries){let H=K.map(N=>{if(I=null,typeof N=="object"&&N?.key!==void 0)return b>0?L(N):N;if(N==null)return Za.SKIP;for(let x=0;x<b;x++){let j=y[x].idFilter;if(j){if(!j(N))return Za.SKIP;I||(I=[]),I.push(x)}}return Hl(N,O,C,!1,L)});return Array.isArray(K)&&(H=H.filter(N=>N!==Za.SKIP)),H.hasEntries=!0,H}return K}a(Yd,"transformToEntries");function Vi(K,p,O=server.replication?.getThisNodeId(l)){if(K<=p?.version){if(p?.version===K&&O!==void 0){let R=server.replication?.exportIdMapping(l),y=p.localTime,b=y&&l.get(y);if(b){let C,I,L=Ot(b);for(let H in R)R[H]===O&&(C=H),R[H]===L.nodeId&&(I=H);if(C>I)return 1;if(C===I)return 0}}return-1}return 1}a(Vi,"precedesExistingVersion");async function Wd(K,p,O){let R=p?.metadataFlags,y=p?.version,b,C;if(!i.attemptLock(K,y,()=>{clearTimeout(C);let N=i.getEntry(K);!N||!N.value||N.metadataFlags&(fn|Jo)?b(Wd(K,i.getEntry(K),O)):b(N)}))return new Promise(N=>{b=N,C=setTimeout(()=>{i.unlock(K,y)},cTe)});let I=p?.value,L={requestContext:O,replacingRecord:I,replacingEntry:p,replacingVersion:y,noCacheStore:!1,source:null,resourceCache:O?.resourceCache},H=O?.responseHeaders;return new Promise((N,x)=>{let G;tP(bt(L,async j=>{let ie=performance.now(),F,Ge,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=R&fn;let ee=L.lastModified||Z&&y;Ge=Z||ee>y||!I,ee||(ee=(0,lm.getNextMonotonicTime)());let Q=performance.now()-ie;if(rr(Q,"cache-resolution",s,null,"success"),H&&NE(H,"Server-Timing",`cache-resolve;dur=${Q.toFixed(2)}`,!0),j.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 Nr.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;rr(Q,"cache-resolution",s,null,"fail"),H&&NE(H,"Server-Timing",`cache-resolve;dur=${Q.toFixed(2)}`,!0),L.transaction.abort();return}if(O?.noCacheStore||L.noCacheStore){L.transaction.abort();return}qr(L).addWrite({key:K,store:i,entry:p,nodeName:"source",commit:a((ee,Q)=>{if(Q?.version!==y)return;let _e=an(K,I,F);if(F){ye.put?.(L,K,F),Q&&(O.previousResidency=Ce.getResidencyRecord(Q.residencyId));let fe,Ae=!1,De,we=Yi(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 _r in r)F||(F={}),F[_r]=fe[_r]}De=tc(we)}xe.default.trace?.(`Writing resolved record from source with id: ${K}, timestamp: ${new Date(ee).toISOString()}`),T(K,F,Q,ee,Ae?fn:0,g&&(Ge||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||A?T(K,null,Q,ee,0,g&&Ge||null,{user:L?.user},"delete",!!Z):gc(i,Q,y))},"commit")})}),()=>{i.unlock(K,y)},j=>{i.unlock(K,y),G&&xe.default.error?.("Error committing cache update",j)})})}a(Wd,"getFromSource");function ql(K){if(!K||K.user?.role?.permission?.super_user)return!0;if(K.replicateTo)throw new Nr.ClientError("Can not specify replication parameters without super user permissions",403);if(K.replicatedConfirmation)throw new Nr.ClientError("Can not specify replication confirmation without super user permissions",403);return!0}a(ql,"checkContextPermissions");function Ki(K){let p=!1;if(K&&(K-ut>1&&(p=!0),ut=K),!(Qt===Rr&&!p)&&(Rr=Qt,(0,Pl.getWorkerIndex)()===(0,Pl.getWorkerCount)()-1))return is&&clearTimeout(is),Qt?new Promise(O=>{let R=new Date;R.setMonth(0),R.setDate(1),R.setHours(0),R.setMinutes(0),R.setSeconds(0);let y=Qt/(1+ut),b=p?Date.now():Math.ceil((Date.now()-R.getTime())/y)*y+R.getTime(),C=a(I=>{xe.default.trace?.(`Scheduled next cleanup scan at ${new Date(I)}`),is=setTimeout(()=>$=$.then(async()=>{if(C(Math.max(I+Qt,Date.now())),i.rootStore.status!=="open"){clearTimeout(is);return}let L=50,H=new Array(L),N=0,x=Math.pow(ut,8)*(Dl.get(U.STORAGE_RECLAMATION_EVICTIONFACTOR)??1e5),G=S/Math.pow(Math.max(ut,1),4);xe.default.info?.(`Starting cleanup scan for ${s}, evict threshold ${x}, adjusted eviction ${G}ms`);function j(ie,F,Ge,Z){let ce=ie+G-Date.now();if(ce<0)return!0;if(ut){let ee=i.lastSize;return Ge&pn&&Zl(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(j,"shouldEvict");try{let ie=0;for(let F of i.getRange({start:!1,snapshot:!1,versions:!0,lazy:!0})){let{key:Ge,value:Z,version:ce,expiresAt:ee,metadataFlags:Q}=F,_e;Z===null&&!g&&ce+aTe<Date.now()?_e=gc(i,F,ce):ee!=null&&j(ee,ce,Q,Z)&&(_e=Ce.evict(Ge,Z,ce),ie++),_e&&(await H[N],H[N]=_e.catch(fe=>{xe.default.error?.("Cleanup error",fe)}),++N>=L&&(N=0)),await Xa()}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),ut=0}),Math.min(I-Date.now(),2147483647)).unref()},"startNextTimer");C(b)}):void 0}a(Ki,"scheduleCleanup");function zd(){Y=l?.addDeleteRemovalCallback(n,i,(K,p)=>{i.remove(K,p)})}a(zd,"addDeleteRemoval");function Nm(){(0,Pl.getWorkerIndex)()===0&&setInterval(async()=>{if(!Bl){Bl=!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 R of p.getValues(O)){let y=i.getEntry(R);y?.value?y.value[K]<Date.now()&&Ce.evict(R,y.value,y.version):i.ifVersion(R,y?.version,()=>p.remove(O,R))}await Xa()}}catch(K){xe.default.error?.("Error in evicting old records",K)}finally{Bl=!1}}},oTe).unref()}a(Nm,"runRecordExpirationEviction");function Yi(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(Yi,"residencyFromFunction");function tc(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(tc,"getResidencyId")}function eP(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 mj(){}function fTe(e){Tj=e}function BT(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 UT(parseInt(e.slice(1),36));if(e==="null")return null;if(!/^-?[0-9]+$/.test(e)&&!(e instanceof Date))throw new SyntaxError;return UT(+e);case"Float":return e==="null"?null:UT(+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;_Te.test(e)||(e+="Z");let n=new Date(e);return UT(n.getTime()),n}return new Date(+e);case void 0:case"Any":return(0,HT.autoCast)(e);default:return e}}catch(n){throw n.message=`Invalid value for attribute ${t.name}: "${e}", expecting ${r}`,n.statusCode=400,n}}function UT(e){if(isNaN(e))throw new SyntaxError;return e}function pj(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 tP(e,t,r){return e?.then?e.then(t,r):t(e)}function Ej(e){return e!=null}function Ls(e){try{return JSON.stringify(e)}catch{return e}}function hTe(e){let t=process.pid;return e.env.readerList().slice(1).some(r=>+r.match(/\d+/)?.[0]!=t)}var Za,lm,gj,Sj,Dl,Nr,um,dm,xe,Ll,Pl,HT,xT,iTe,Tj,oTe,aTe,dj,cTe,fj,lTe,fn,Jo,uTe,_j,hj,dTe,KUe,_Te,Xa,pf=be(()=>{B();Za=require("lmdb"),lm=M(ln()),gj=require("lodash"),Sj=M(uf());Xo();zm();Dl=M(le());FO();Nr=M(me()),um=M(lo()),dm=M($s());ve();mf();xe=M(_i());db();ac();Ll=require("ordered-binary"),Pl=M(Ze());ro();HT=M(oe());nu();wi();lE();T_();xT=M(require("node:fs"));ls();nT();iTe=new Uint8Array(9);iTe[8]=192;oTe=6e4,aTe=864e5;Dl.initSync();dj=Dl.get(U.STORAGE_PREFETCHWRITES),cTe=1e4,fj=1,lTe=2,fn=1,Jo=8,uTe=Buffer.allocUnsafeSlow(8192),_j=1978,hj=100,dTe={read:!0,insert:!0,update:!0,delete:!0,isSuperUser:!0},KUe=(0,HT.convertToMS)(Dl.get(U.CLUSTERING_LEAFSERVER_STREAMS_MAXAGE))||864e5;a(kT,"makeTable");a(eP,"attributesAsObject");a(mj,"noop");a(fTe,"setServerUtilities");_Te=/[+-][0-9]{2}:[0-9]{2}|[a-zA-Z]$/;a(BT,"coerceType");a(UT,"rejectNaN");a(pj,"isDescendantId");Xa=a(()=>new Promise(setImmediate),"rest");a(tP,"when");a(Ej,"exists");a(Ls,"stringify");a(hTe,"hasOtherProcesses")});var it={};Ue(it,{database:()=>Tu,database_envs:()=>qo,databases:()=>Ve,dropDatabase:()=>pb,dropTableMeta:()=>STe,getDatabases:()=>Je,getDefaultCompression:()=>Xg,getTables:()=>mTe,onRemovedDB:()=>G_,onUpdatedTable:()=>Zc,readMetaDb:()=>fm,resetDatabases:()=>od,table:()=>dt,tables:()=>Kn});function mTe(){return $T||Je(),Kn||{}}function Je(){if($T)return Ve;$T=!0,Fd=new Map;let e=(0,jt.getHdbBasePath)()&&(0,Pt.join)((0,jt.getHdbBasePath)(),sc),t=(0,jt.get)(U.DATABASES)||{};if(process.env.SCHEMAS_DATA_PATH&&(t.data={path:process.env.SCHEMAS_DATA_PATH}),e=process.env.STORAGE_PATH||(0,jt.get)(U.STORAGE_PATH)||e&&((0,ns.existsSync)(e)?e:(0,Pt.join)((0,jt.getHdbBasePath)(),Lm)),!e)return;if((0,ns.existsSync)(e))for(let n of(0,ns.readdirSync)(e,{withFileTypes:!0})){let s=(0,Pt.basename)(n.name,".mdb");n.isFile()&&(0,Pt.extname)(n.name).toLowerCase()===".mdb"&&!t[s]?.path&&fm((0,Pt.join)(e,n.name),null,s)}if((0,ns.existsSync)((0,kd.getBaseSchemaPath)())){for(let n of(0,ns.readdirSync)((0,kd.getBaseSchemaPath)(),{withFileTypes:!0}))if(!n.isFile()){let s=(0,Pt.join)((0,kd.getBaseSchemaPath)(),n.name),i=(0,Pt.join)((0,kd.getTransactionAuditStoreBasePath)(),n.name);for(let o of(0,ns.readdirSync)(s,{withFileTypes:!0}))if(o.isFile()&&(0,Pt.extname)(o.name).toLowerCase()===".mdb"){let c=(0,Pt.join)(i,o.name);fm((0,Pt.join)(s,o.name),(0,Pt.basename)(o.name,".mdb"),n.name,c,!0)}}}if(t)for(let n in t){let s=t[n],i=s.path;if((0,ns.existsSync)(i))for(let c of(0,ns.readdirSync)(i,{withFileTypes:!0}))c.isFile()&&(0,Pt.extname)(c.name).toLowerCase()===".mdb"&&fm((0,Pt.join)(i,c.name),(0,Pt.basename)(c.name,".mdb"),n);let o=s.tables;if(o)for(let c in o){let l=o[c],u=(0,Pt.join)(l.path,(0,Pt.basename)(c+".mdb"));(0,ns.existsSync)(u)&&fm(u,c,n,null,!0)}}for(let n in Ve){let s=Fd.get(n);if(s){let i=Ve[n];n.includes("delete")&&Dt.trace(`defined tables ${Array.from(s.keys())}`);for(let o in i)s.has(o)||(Dt.trace(`delete table class ${o}`),delete i[o])}else if(delete Ve[n],n==="data"){for(let i in Kn)delete Kn[i];delete Kn[VT]}}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 Fd=null,Ve}function od(){$T=!1;for(let[,e]of qo)e.needsDeletion=!0;Je();for(let[e,t]of qo)t.needsDeletion&&!e.endsWith("system.mdb")&&(t.close(),qo.delete(e),delete Ve[t.databaseName],hm.forEach(r=>r(t.databaseName)));return Ve}function fm(e,t,r=sP,n,s){let i=new rP.default(e,!1);try{let o=qo.get(e);o?o.needsDeletion=!1:(o=(0,qd.open)(i),qo.set(e,o));let c=new Ml.default(!1),l=o.dbisDb||(o.dbisDb=o.openDB(FT.INTERNAL_DBIS_NAME,c)),u=o.auditStore;u||(n?(0,ns.existsSync)(n)&&(i.path=n,u=(0,qd.open)(i),u.isLegacy=!0):u=MT(o));let f=bj(r),d=f[VT],_=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 A=_.get(S);A||_.set(S,A={attributes:[]}),(g==null||m.is_hash_attribute)&&(A.primary=m),g!=null&&A.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 ae of S)if(ae.is_hash_attribute||ae.isPrimaryKey){g=ae;break}if(!g){Dt.warn(`Unable to find a primary key attribute on table ${h}, with attributes: ${JSON.stringify(S)}`);continue}}let A=f[h],E={},T=[],w,v,k=typeof g.audit=="boolean"?g.audit:(0,jt.get)(U.LOGGING_AUDITLOG),$=g.trackDeletes,W=g.expiration,te=g.eviction,se=g.sealed,Y=g.splitSegments,ne=g.replicate;if(A)E=A.indices,T=A.attributes,A.schemaVersion++;else{w=g.tableId,w?w>=(l.get(Hd)||0)&&(l.putSync(Hd,w+1),Dt.info(`Updating next table id (it was out of sync) to ${w+1} for ${h}`)):(g.tableId=w=l.get(Hd),w||(w=1),Dt.debug("Table {table_name} missing an id, assigning {table_id}"),l.putSync(Hd,w+1),l.putSync(g.key,g));let ae=new Ml.default(!g.is_hash_attribute,g.is_hash_attribute);if(ae.compression=g.compression,ae.compression){let pe=(0,jt.get)(U.STORAGE_COMPRESSION_THRESHOLD)||yj;ae.compression.threshold=pe}v=yp(o.openDB(g.key,ae),o),o.databaseName=r,v.tableId=w}let ue;for(let ae of S){ae.attribute=ae.name;try{if(!ae.is_hash_attribute&&(ae.indexed||ae.attribute&&!ae.name)){if(!E[ae.name]){let Te=new Ml.default(!ae.is_hash_attribute,ae.is_hash_attribute);E[ae.name]=o.openDB(ae.key,Te),E[ae.name].indexNulls=ae.indexNulls}let pe=T.find(Te=>Te.name===ae.name);pe?T.splice(T.indexOf(pe),1,ae):T.push(ae),ue=!0}}catch(pe){Dt.error("Error trying to update attribute",ae,T,E,pe)}}for(let ae of T)if(!S.find(Te=>Te.name===ae.name)){if(ae.is_hash_attribute){Dt.error("Unable to remove existing primary key attribute",ae);continue}ae.indexed&&(T.splice(T.indexOf(ae),1),ue=!0)}if(A)ue&&(A.schemaVersion++,A.updatedAttributes());else{A=Oj(f,h,kT({primaryStore:v,auditStore:u,audit:k,sealed:se,splitSegments:Y,replicate:ne,expirationMS:W&&W*1e3,evictionMS:te&&te*1e3,trackDeletes:$,tableName:h,tableId:w,primaryKey:g.name,databasePath:s?r+"/"+h:r,databaseName:r,indices:E,attributes:S,schemaDefined:g.schemaDefined,dbisDB:l})),A.schemaVersion=1;for(let ae of _m)ae(A)}}return o}catch(o){throw o.message+=` opening database ${e}`,o}}function bj(e){let t=Ve[e];if(t||(e==="data"?t=Ve[e]=Kn:e==="system"?Object.defineProperty(Ve,"system",{value:t=Object.create(null),configurable:!0}):t=Ve[e]=Object.create(null)),Fd&&!Fd.has(e)){let r=new Set;t[VT]=r,Fd.set(e,r)}return t}function Oj(e,t,r){return e[t]=r,r}function Tu({database:e,table:t}){e||(e=sP),Je();let r=bj(e),n=(0,Pt.join)((0,jt.getHdbBasePath)(),sc),s=(0,jt.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,jt.get)(U.STORAGE_PATH)||((0,ns.existsSync)(n)?n:(0,Pt.join)((0,jt.getHdbBasePath)(),Lm));let o=(0,Pt.join)(n,(i?t:e)+".mdb"),c=qo.get(o);if(!c||c.status==="closed"){let l=new rP.default(o,!1);c=(0,qd.open)(l),qo.set(o,c)}return c.auditStore||(c.auditStore=MT(c)),c}async function pb(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,qo.delete(r.path),r.status==="open"&&(await r.close(),await mm.remove(r.path));if(r||(r=Tu({database:e,table:null}),r.status==="open"&&(await r.close(),await mm.remove(r.path))),e==="data"){for(let n in Kn)delete Kn[n];delete Kn[VT]}delete Ve[e],hm.forEach(n=>n(e)),await zA(r)}function dt(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=sP);let m=Tu({database:r,table:t}),S=Ve[r];Dt.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 A,E,T;_==null&&(_=!0);let w=new Ml.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,k;if(g){if(A=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)||{},A=E.name,E.is_hash_attribute=E.isPrimaryKey=!0,E.schemaDefined=_,E.compression=Xg(),d&&(E.trackDeletes=!0),c=E.audit=typeof c=="boolean"?c:(0,jt.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]),Dt.trace(`${t} table loading, opening primary store`);let ne=new Ml.default(!1,!0);ne.compression=E.compression;let ue=t+"/";if(T=m.dbisDb=m.openDB(FT.INTERNAL_DBIS_NAME,w),se(),T.get(ue))return k&&k(),od(),dt(e);let ae=yp(m.openDB(ue,ne),m);m.databaseName=r,ae.tableId=T.get(Hd),Dt.trace(`Assigning new table id ${ae.tableId} for ${t}`),ae.tableId||(ae.tableId=1),T.put(Hd,ae.tableId+1),E.tableId=ae.tableId,g=Oj(S,t,kT({primaryStore:ae,auditStore:Y,audit:c,sealed:l,splitSegments:u,replicate:f,trackDeletes:d,expirationMS:n&&n*1e3,evictionMS:s&&s*1e3,primaryKey:A,tableName:t,tableId:ae.tableId,databasePath:r,databaseName:r,indices:{},attributes:o,schemaDefined:_,dbisDB:T})),g.schemaVersion=1,v=!0,T.put(ue,E)}let $=g.indices;T=T||(m.dbisDb=m.openDB(FT.INTERNAL_DBIS_NAME,w)),g.dbisDB=T;let W=[];for(let{key:Y,value:ne}of T.getRange({start:!0})){let[ue,ae]=Y.toString().split("/");if(ae===""&&(ae=ne.name),ae){if(ue!==t)continue}else continue;let pe=o.find(ye=>ye.name===ae),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 ae=!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 Ml.default(!0,!1),Te=m.openDB(ne,pe);(ae||ue.indexingPID&&ue.indexingPID!==process.pid||ue.restartNumber<pm.workerData?.restartNumber)&&(v=!0,se(),ue=T.get(ne),(ae||ue.indexingPID&&ue.indexingPID!==process.pid||ue.restartNumber<pm.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,$[Y.name]=Te}else ae&&(v=!0,se(),T.put(ne,Y))}}finally{k&&k()}if(v&&(g.schemaVersion++,g.updatedAttributes()),Dt.trace(`${t} table loading, running index`),te.length>0||W.length>0?g.indexingOperation=gTe(g,te,W):v&&qT.signalSchemaChange(new GT.SchemaEventMsg(process.pid,"schema-change",g.databaseName,g.tableName)),g.origin=h,v)for(let Y of _m)Y(g,h!=="cluster");return(n||s||i)&&g.setTTLExpiration({expiration:n,eviction:s,scanInterval:i}),Dt.trace(`${t} table loaded`),g;function se(){k||m.transactionSync(()=>({then(Y){k=Y}}))}a(se,"startTxn")}async function gTe(e,t,r){try{Dt.info(`Indexing ${e.tableName} attributes`,t);let n=e.schemaVersion;await qT.signalSchemaChange(new GT.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,qd.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 A=S.resolve,E=_&&(A?A(_):_[g]),T=(0,Aj.getIndexedValues)(E);if(T)for(let w=0,v=T.length;w<v;w++)S.dbi.put(T[w],d)}catch(A){o[g]||(o[g]=!0,Dt.error(`Error indexing attribute ${g}`,A))}}}),s.then(()=>f--,m=>{f--,Dt.error(m)}),pm.workerData&&pm.workerData.restartNumber!==Rj.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>pTe?await s:f>ETe&&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 qT.signalSchemaChange(new GT.SchemaEventMsg(process.pid,"indexing-finished",e.databaseName,e.tableName)),Dt.info(`Finished indexing ${e.tableName} attributes`,t)}catch(n){Dt.error("Error in indexing",n)}}function STe({table:e,database:t}){let r=Tu({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 Zc(e){return _m.push(e),{remove(){let t=_m.indexOf(e);t>-1&&_m.splice(t,1)}}}function G_(e){return hm.push(e),{remove(){let t=hm.indexOf(e);t>-1&&hm.splice(t,1)}}}function Xg(){let e=(0,jt.get)(U.STORAGE_COMPRESSION),t=(0,jt.get)(U.STORAGE_COMPRESSION_DICTIONARY),r=(0,jt.get)(U.STORAGE_COMPRESSION_THRESHOLD)||yj,n={startingOffset:32};return t&&(n.dictionary=mm.readFileSync(t)),r&&(n.threshold=r),e&&n}var jt,FT,qd,Pt,ns,kd,Ml,rP,mm,nP,Aj,qT,GT,pm,Dt,Rj,sP,VT,yj,Kn,Ve,Hd,_m,hm,$T,qo,Fd,pTe,ETe,ve=be(()=>{jt=M(le()),FT=M(vt()),qd=require("lmdb"),Pt=require("path"),ns=require("fs"),kd=M(Et());pf();Ml=M(Lf()),rP=M(Mf());B();mm=M(require("fs-extra")),nP=M(ci()),Aj=M(ln()),qT=M(lo()),GT=M($s()),pm=require("worker_threads"),Dt=M(z()),Rj=M(Ze());ro();nu();ls();sP="data",VT=Symbol("defined-tables"),yj=((0,jt.get)(U.STORAGE_PAGESIZE)||4096)-60;(0,jt.initSync)();Kn=Object.create(null),Ve=Object.create(null);(0,nP._assignPackageExport)("databases",Ve);(0,nP._assignPackageExport)("tables",Kn);Hd=Symbol.for("next-table-id"),_m=[],hm=[],qo=new Map;a(mTe,"getTables");a(Je,"getDatabases");a(od,"resetDatabases");a(fm,"readMetaDb");a(bj,"ensureDB");a(Oj,"setTable");a(Tu,"database");a(pb,"dropDatabase");a(dt,"table");pTe=1e3,ETe=10;a(gTe,"runIndexing");a(STe,"dropTableMeta");a(Zc,"onUpdatedTable");a(G_,"onRemovedDB");a(Xg,"getDefaultCompression")});var oe=P((r0e,kj)=>{"use strict";var ec=require("path"),Pj=require("fs-extra"),Cn=z(),Nj=require("fs-extra"),KT=require("os"),TTe=require("net"),ATe=require("recursive-iterator"),Ar=(B(),D(q)),{PACKAGE_ROOT:RTe}=pt(),yTe=yA(),wj=require("papaparse"),YT=require("moment"),{inspect:bTe}=require("util"),Ij=require("is-number"),t0e=require("lodash"),OTe=require("minimist"),NTe=require("https"),wTe=require("http"),{hdb_errors:WT}=me(),ITe=/^((\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)))$/,Dj=require("util").promisify(setTimeout),CTe=100,PTe=5,DTe="",LTe=4,Cj={true:!0,TRUE:!0,FALSE:!1,false:!1,undefined:null,null:null,NULL:null,NaN:NaN};kj.exports={isEmpty:ss,isEmptyOrZeroLength:$i,arrayHasEmptyValues:UTe,arrayHasEmptyOrZeroLengthValues:xTe,buildFolderPath:BTe,isBoolean:Lj,errorizeMessage:MTe,stripFileExtension:kTe,autoCast:FTe,autoCastJSON:Mj,autoCastJSONDeep:oP,removeDir:qTe,compareVersions:GTe,isCompatibleDataVersion:$Te,escapeRawValue:VTe,unescapeValue:KTe,stringifyProps:YTe,timeoutPromise:zTe,isClusterOperation:QTe,getClusterUser:XTe,checkGlobalSchemaTable:JTe,getHomeDir:Uj,getPropsFilePath:WTe,promisifyPapaParse:ZTe,removeBOM:xj,createEventPromise:eAe,checkProcessRunning:tAe,checkSchemaTableExist:rAe,checkSchemaExists:Bj,checkTableExists:Hj,getStartOfTomorrowInSeconds:nAe,getLimitKey:sAe,isObject:HTe,isNotEmptyAndHasValue:vTe,autoCasterIsNumberCheck:vj,backtickASTSchemaItems:iAe,isPortTaken:jTe,createForkArgs:oAe,autoCastBoolean:aAe,async_set_timeout:Dj,getTableHashAttribute:cAe,doesSchemaExist:lAe,doesTableExist:uAe,stringifyObj:dAe,ms_to_time:fAe,changeExtension:_Ae,getEnvCliRootPath:aP,noBootFile:hAe,httpRequest:mAe,transformReq:pAe,convertToMS:EAe,PACKAGE_ROOT:RTe};function MTe(e){return e instanceof Error?e:new Error(e)}a(MTe,"errorizeMessage");function ss(e){return e==null}a(ss,"isEmpty");function vTe(e){return!ss(e)&&(e||e===0||e===""||Lj(e))}a(vTe,"isNotEmptyAndHasValue");function $i(e){return ss(e)||e.length===0||e.size===0}a($i,"isEmptyOrZeroLength");function UTe(e){if(ss(e))return!0;for(let t=0;t<e.length;t++)if(ss(e[t]))return!0;return!1}a(UTe,"arrayHasEmptyValues");function xTe(e){if($i(e))return!0;for(let t=0;t<e.length;t++)if($i(e[t]))return!0;return!1}a(xTe,"arrayHasEmptyOrZeroLengthValues");function BTe(...e){try{return e.join(ec.sep)}catch{console.error(e)}}a(BTe,"buildFolderPath");function Lj(e){return ss(e)?!1:e===!0||e===!1}a(Lj,"isBoolean");function HTe(e){return ss(e)?!1:typeof e=="object"}a(HTe,"isObject");function kTe(e){return $i(e)?DTe:e.slice(0,-LTe)}a(kTe,"stripFileExtension");function FTe(e){return ss(e)||e===""||typeof e!="string"?e:Cj[e]!==void 0?Cj[e]:vj(e)===!0?Number(e):ITe.test(e)?new Date(e):e}a(FTe,"autoCast");function Mj(e){if(typeof e=="string"&&(e.startsWith("{")&&e.endsWith("}")||e.startsWith("[")&&e.endsWith("]")))try{return JSON.parse(e)}catch{}return e}a(Mj,"autoCastJSON");function oP(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=oP(n);s!==n&&(e[t]=s)}else for(let t in e){let r=e[t],n=oP(r);n!==r&&(e[t]=n)}return e}else return Mj(e)}a(oP,"autoCastJSONDeep");function vj(e){if(e.startsWith("0.")&&Ij(e))return!0;let t=e.toUpperCase().includes("E");return!!((e!=="0"&&e.startsWith("0"))===!1&&t===!1&&Ij(e))}a(vj,"autoCasterIsNumberCheck");async function qTe(e){if($i(e))throw new Error(`Directory path: ${e} does not exist`);try{await Nj.emptyDir(e),await Nj.remove(e)}catch(t){throw Cn.error(`Error removing files in ${e} -- ${t}`),t}}a(qTe,"removeDir");function GTe(e,t){if($i(e)){Cn.info("Invalid current version sent as parameter.");return}if($i(t)){Cn.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(GTe,"compareVersions");function $Te(e,t,r=!1){let n=e.toString().split("."),s=t.toString().split(".");return n[0]===s[0]&&(!r||n[1]===s[1])}a($Te,"isCompatibleDataVersion");function VTe(e){if(ss(e))return e;let t=String(e);return t==="."?Ar.UNICODE_PERIOD:t===".."?Ar.UNICODE_PERIOD+Ar.UNICODE_PERIOD:t.replace(Ar.FORWARD_SLASH_REGEX,Ar.UNICODE_FORWARD_SLASH)}a(VTe,"escapeRawValue");function KTe(e){if(ss(e))return e;let t=String(e);return t===Ar.UNICODE_PERIOD?".":t===Ar.UNICODE_PERIOD+Ar.UNICODE_PERIOD?"..":String(e).replace(Ar.ESCAPED_FORWARD_SLASH_REGEX,"/")}a(KTe,"unescapeValue");function YTe(e,t){if(ss(e))return Cn.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+KT.EOL}!$i(n)&&n[0]===";"?r+=" "+n+s+KT.EOL:$i(n)||(r+=n+"="+s+KT.EOL)}catch{Cn.error(`Found bad property during upgrade with key ${n} and value: ${s}`)}}),r}a(YTe,"stringifyProps");function Uj(){let e;try{e=KT.homedir()}catch{e=process.env.HOME}return e}a(Uj,"getHomeDir");function WTe(){let e=ec.join(Uj(),Ar.HDB_HOME_DIR_NAME,Ar.BOOT_PROPS_FILE_NAME);return Pj.existsSync(e)||(e=ec.join(__dirname,"../","hdb_boot_properties.file")),e}a(WTe,"getPropsFilePath");function zTe(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(zTe,"timeoutPromise");async function jTe(e){if(!e)throw new Error("Invalid port passed as parameter");return new Promise((t,r)=>{let n=TTe.createServer().once("error",s=>{s.code==="EADDRINUSE"?t(!0):r(s)}).once("listening",()=>n.once("close",()=>t(!1)).close()).listen(e)})}a(jTe,"isPortTaken");function QTe(e){try{return Ar.CLUSTER_OPERATIONS[e.toLowerCase()]!==void 0}catch(t){Cn.error(`Error checking operation against cluster ops ${t}`)}return!1}a(QTe,"isClusterOperation");function JTe(e,t){let r=(ve(),D(it)).getDatabases();if(!r[e])return WT.HDB_ERROR_MSGS.SCHEMA_NOT_FOUND(e);if(!r[e][t])return WT.HDB_ERROR_MSGS.TABLE_NOT_FOUND(e,t)}a(JTe,"checkGlobalSchemaTable");function XTe(e,t){if(ss(t)){Cn.warn("No CLUSTERING_USER defined, clustering disabled");return}if(ss(e)||$i(e)){Cn.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){Cn.error(`unable to find cluster_user due to: ${n.message}`);return}if(r===void 0){Cn.warn(`CLUSTERING_USER: ${t} not found or is not active.`);return}return r}a(XTe,"getClusterUser");function ZTe(){wj.parsePromise=function(e,t,r){return new Promise(function(n,s){wj.parse(e,{header:!0,transformHeader:xj,chunk:t.bind(null,s),skipEmptyLines:!0,transform:r,dynamicTyping:!1,error:s,complete:n})})}}a(ZTe,"promisifyPapaParse");function xj(e){if(typeof e!="string")throw new TypeError(`Expected a string, got ${typeof e}`);return e.charCodeAt(0)===65279?e.slice(1):e}a(xj,"removeBOM");function eAe(e,t,r){return new Promise(n=>{t.once(e,s=>{let i=r;Cn.info(`Got cluster status event response: ${bTe(s)}`);try{i.cancel()}catch{Cn.error("Error trying to cancel timeout.")}n(s)})})}a(eAe,"createEventPromise");async function tAe(e){let t=!0,r=0;do await Dj(CTe*r++),(await yTe.findPs(e)).length>0&&(t=!1);while(t&&r<PTe);if(t)throw new Error(`process ${e} was not started`)}a(tAe,"checkProcessRunning");function rAe(e,t){let r=Bj(e);if(r)return r;let n=Hj(e,t);if(n)return n}a(rAe,"checkSchemaTableExist");function Bj(e){let{getDatabases:t}=(ve(),D(it));if(!t()[e])return WT.HDB_ERROR_MSGS.SCHEMA_NOT_FOUND(e)}a(Bj,"checkSchemaExists");function Hj(e,t){let{getDatabases:r}=(ve(),D(it));if(!r()[e][t])return WT.HDB_ERROR_MSGS.TABLE_NOT_FOUND(e,t)}a(Hj,"checkTableExists");function nAe(){let e=YT().utc().add(1,"d").startOf("d").unix(),t=YT().utc().unix();return e-t}a(nAe,"getStartOfTomorrowInSeconds");function sAe(){return YT().utc().format("DD-MM-YYYY")}a(sAe,"getLimitKey");function iAe(e){try{let t=new ATe(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){Cn.error("Got an error back ticking items."),Cn.error(t)}}a(iAe,"backtickASTSchemaItems");function oAe(e){return[e]}a(oAe,"createForkArgs");function aAe(e){return e===!0||typeof e=="string"&&e.toLowerCase()==="true"}a(aAe,"autoCastBoolean");function cAe(e,t){let{getDatabases:r}=(ve(),D(it)),n=r()[e]?.[t];return n?.primaryKey||n?.hash_attribute}a(cAe,"getTableHashAttribute");function lAe(e){let{getDatabases:t}=(ve(),D(it));return t()[e]!==void 0}a(lAe,"doesSchemaExist");function uAe(e,t){let{getDatabases:r}=(ve(),D(it));return r()[e]?.[t]!==void 0}a(uAe,"doesTableExist");function dAe(e){try{return JSON.stringify(e)}catch{return e}}a(dAe,"stringifyObj");function fAe(e){let t=YT.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(fAe,"ms_to_time");function _Ae(e,t){let r=ec.basename(e,ec.extname(e));return ec.join(ec.dirname(e),r+t)}a(_Ae,"changeExtension");function aP(){if(process.env[Ar.CONFIG_PARAMS.ROOTPATH.toUpperCase()])return process.env[Ar.CONFIG_PARAMS.ROOTPATH.toUpperCase()];let e=OTe(process.argv);if(e[Ar.CONFIG_PARAMS.ROOTPATH.toUpperCase()])return e[Ar.CONFIG_PARAMS.ROOTPATH.toUpperCase()]}a(aP,"getEnvCliRootPath");var iP;function hAe(){if(iP)return iP;let e=aP();if(aP()&&Pj.pathExistsSync(ec.join(e,Ar.HDB_CONFIG_FILE)))return iP=!0,!0}a(hAe,"noBootFile");function mAe(e,t){let r;return e.protocol==="http:"?r=wTe:r=NTe,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(mAe,"httpRequest");function pAe(e){if(!e.schema&&!e.database){e.schema=Ar.DEFAULT_DATABASE_NAME;return}e.database&&(e.schema=e.database)}a(pAe,"transformReq");function EAe(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(EAe,"convertToMS")});var le=P((Vj,Kj)=>{"use strict";var cP=require("fs-extra"),vl=require("path"),Fj=require("os"),gAe=require("properties-reader"),gm=z(),Em=oe(),Me=(B(),D(q)),zT=wt(),SAe="Error initializing environment manager",jT="BOOT_PROPS_FILE_PATH",qj=!1,TAe={[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},Go={};Object.assign(Vj,Kj.exports={BOOT_PROPS_FILE_PATH:jT,getHdbBasePath:AAe,setHdbBasePath:RAe,get:Gj,initSync:bAe,setProperty:ze,initTestEnvironment:NAe,setCloneVar:OAe});function AAe(){return Go[Me.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]}a(AAe,"getHdbBasePath");function RAe(e){Go[Me.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]=e}a(RAe,"setHdbBasePath");function Gj(e){let t=zT.getConfigValue(e);return t===void 0?Go[e]:t}a(Gj,"get");function ze(e,t){TAe[e]&&(Go[e]=t),zT.updateConfigObject(e,t)}a(ze,"setProperty");function yAe(){let e;try{e=Em.getPropsFilePath(),cP.accessSync(e,cP.constants.F_OK|cP.constants.R_OK),qj=!0;let t=gAe(e);return Go[Me.HDB_SETTINGS_NAMES.INSTALL_USER]=t.get(Me.HDB_SETTINGS_NAMES.INSTALL_USER),Go[Me.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY]=t.get(Me.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY),Go[jT]=e,!0}catch{return gm.trace(`Environment manager found no properties file at ${e}`),!1}}a(yAe,"doesPropFileExist");function bAe(e=!1){try{((qj||yAe()||Em.noBootFile())&&!$j||e)&&(zT.initConfig(e),Go[Me.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]=zT.getConfigValue(Me.HDB_SETTINGS_NAMES.HDB_ROOT_KEY))}catch(t){gm.error(SAe),gm.error(t),console.error(t),process.exit(1)}}a(bAe,"initSync");var $j=!1;function OAe(e){$j=e}a(OAe,"setCloneVar");function NAe(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=vl.join(__dirname,"../../","unitTests");Go[jT]=vl.join(l,"hdb_boot_properties.file"),ze(Me.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY,vl.join(l,"settings.test")),ze(Me.HDB_SETTINGS_NAMES.INSTALL_USER,Fj.userInfo()?Fj.userInfo().username:void 0),ze(Me.HDB_SETTINGS_NAMES.LOG_LEVEL_KEY,"debug"),ze(Me.HDB_SETTINGS_NAMES.LOG_PATH_KEY,vl.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,vl.join(l,"envDir")),ze(Me.CONFIG_PARAMS.STORAGE_PATH,vl.join(l,"envDir")),s&&(ze(Me.CONFIG_PARAMS.HTTP_SECUREPORT,Gj(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,Em.isEmpty(i)?!1:i),ze(Me.CONFIG_PARAMS.HTTP_CORS,Em.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,vl.resolve(__dirname,"../../unitTests/server/fastifyRoutes/custom_functions")),ze(Me.HDB_SETTINGS_NAMES.LOCAL_STUDIO_ON,Em.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 ${jT}. Please check your boot props and settings files`;gm.fatal(r),gm.error(t)}}a(NAe,"initTestEnvironment")});var Qj=P((i0e,jj)=>{"use strict";var zj=require("joi"),{string:Sm,boolean:Yj,array:wAe}=zj.types(),Wj=(B(),D(q)),IAe=et();jj.exports=CAe;function CAe(e){let t=zj.object({operation:Sm.valid(Wj.OPERATIONS_ENUM.ADD_NODE,Wj.OPERATIONS_ENUM.UPDATE_NODE).required(),node_name:Sm.required(),subscriptions:wAe.items({schema:Sm.required(),table:Sm.optional(),hash_attribute:Sm.optional(),subscribe:Yj.required(),publish:Yj.required()}).min(1).required()});return IAe.validateBySchema(e,t)}a(CAe,"updateRemoteSourceValidator")});var Tm=P((a0e,Jj)=>{"use strict";var lP=class{static{a(this,"UpdateRemoteResponseObject")}constructor(t,r,n=void 0){this.status=t,this.message=r,this.system_info=n}};Jj.exports=lP});var tQ=P((l0e,eQ)=>{"use strict";var PAe=Qj(),$o=z(),uP=ot(),DAe=(B(),D(q)),dP=Es(),Ul=Ut(),Xj=W_(),LAe=gu(),{Node:MAe,NodeSubscription:Zj}=Oa(),fP=Tm(),_P=oe(),vAe=le(),{cloneDeep:UAe}=require("lodash"),{broadcast:xAe}=Ze();eQ.exports=BAe;async function BAe(e){try{let t=PAe(e);if(t)return $o.error(`Validation error in updateRemoteSource: ${t.message}`),new fP(uP.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR,t.message);let{subscriptions:r,node_name:n,system_info:s}=e,i=[],o=UAe(await dP.getNodeRecord(n)),c=!_P.isEmptyOrZeroLength(o);o=c?o[0]:o,c&&$o.trace(`Existing record found for ${n}, updating records subscriptions`);for(let u=0,f=r.length;u<f;u++){let d=r[u],_=d.schema,h=d.table;if(!_P.doesSchemaExist(_)){$o.trace(`updateRemoteSource creating schema: ${_}`);try{await Xj.createSchema({operation:"create_schema",schema:_})}catch(m){$o.error(m)}}if(h&&!_P.doesTableExist(_,h)){let m=new LAe(_,h,d.hash_attribute);d.attributes&&(m.attributes=d.attributes),$o.trace(`updateRemoteSource creating table: ${h} in schema: ${_} with attributes: ${JSON.stringify(d.attributes)}`);try{await Xj.createTable(m)}catch(S){$o.error(S)}}if($o.trace(`Creating local stream for ${_}.${h}`),await Ul.createLocalTableStream(_,h),c?(await Ul.updateConsumerIterator(_,h,n,"stop"),await Ul.updateRemoteConsumer(d,n),d.subscribe===!0&&await Ul.updateConsumerIterator(_,h,n,"start")):(await Ul.updateRemoteConsumer(d,n),d.subscribe===!0?await Ul.updateConsumerIterator(_,h,n,"start"):await Ul.updateConsumerIterator(_,h,n,"stop")),c){let m=!1;for(let S=0,g=o.subscriptions.length;S<g;S++){let A=o.subscriptions[S];if(A.schema===_&&A.table===h){A.publish=d.publish,A.subscribe=d.subscribe,m=!0;break}}m||o.subscriptions.push(new Zj(_,h,d.publish,d.subscribe))}else i.push(new Zj(_,h,d.publish,d.subscribe))}c||(o=new MAe(n,i,void 0),$o.trace(`No record found for ${n}, creating a new one`));let l=Object.create({});return Object.assign(l,o),l.system_info=s,await dP.upsertNodeRecord(l),xAe({type:"nats_update"}),new fP(uP.UPDATE_REMOTE_RESPONSE_STATUSES.SUCCESS,`Node ${vAe.get(DAe.CONFIG_PARAMS.CLUSTERING_NODENAME)} successfully updated remote source`,await dP.getSystemInfo())}catch(t){$o.error(t);let r=t.message?t.message:t;return new fP(uP.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR,r)}}a(BAe,"updateRemoteSource")});var iQ=P((d0e,sQ)=>{"use strict";var nQ=require("joi"),{string:rQ}=nQ.types(),HAe=(B(),D(q)),kAe=et();sQ.exports=FAe;function FAe(e){let t=nQ.object({operation:rQ.valid(HAe.OPERATIONS_ENUM.REMOVE_NODE).required(),node_name:rQ.required()});return kAe.validateBySchema(e,t)}a(FAe,"removeRemoteSourceValidator")});var cQ=P((_0e,aQ)=>{"use strict";var qAe=iQ(),QT=z(),JT=ot(),hP=(B(),D(q)),GAe=Es(),$Ae=oe(),oQ=Ut(),VAe=le(),XT=Tm(),{NodeSubscription:KAe}=Oa(),YAe=Eu(),WAe=oa(),{broadcast:zAe}=Ze(),jAe=VAe.get(hP.CONFIG_PARAMS.CLUSTERING_NODENAME);aQ.exports=QAe;async function QAe(e){try{let t=qAe(e);if(t)return QT.error(`Validation error in removeRemoteSource: ${t.message}`),new XT(JT.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR,t.message);let r=e.node_name,n=await GAe.getNodeRecord(r);if($Ae.isEmptyOrZeroLength(n)){let i=`No record found for node '${r}'`;return QT.error(i),new XT(JT.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR,i)}n=n[0];for(let i=0,o=n.subscriptions.length;i<o;i++){let c=n.subscriptions[i];QT.trace(`remove remote source removing subscription: ${c.schema}.${c.table} for node: ${r}`);let l=new KAe(c.schema,c.table,!1,!1);await oQ.updateConsumerIterator(c.schema,c.table,r,"stop"),await oQ.updateRemoteConsumer(l,r)}let s=new YAe(hP.SYSTEM_SCHEMA_NAME,hP.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,[r]);return await WAe.deleteRecord(s),zAe({type:"nats_update"}),new XT(JT.UPDATE_REMOTE_RESPONSE_STATUSES.SUCCESS,`Node ${jAe} successfully removed node '${r}'.`)}catch(t){QT.error(t);let r=t.message?t.message:t;return new XT(JT.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR,r)}}a(QAe,"removeRemoteSource")});var fQ=P((m0e,dQ)=>{"use strict";var ZT=z(),Am=(B(),D(q)),lQ=ot(),mP=le(),JAe=oe(),uQ=Tm(),XAe=Es(),ZAe=y_(),eRe=zr();dQ.exports=tRe;async function tRe(e){try{ZT.trace("getRemoteSourceConfig called");let t=process.uptime()*1e3,r=JAe.ms_to_time(t),n=new rRe(mP.get(Am.CONFIG_PARAMS.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT),mP.get(Am.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_PORT)??mP.get(Am.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_SECUREPORT),r,await XAe.getSystemInfo());try{let s={name:e.node_name,system_info:e.system_info},i=new ZAe(Am.SYSTEM_SCHEMA_NAME,Am.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,[s]);await eRe.update(i)}catch(s){ZT.error("Get remote config encountered an error updating system info for node:",e.node_name,s)}return ZT.trace("getRemoteSourceConfig response:",n),new uQ(lQ.UPDATE_REMOTE_RESPONSE_STATUSES.SUCCESS,n)}catch(t){ZT.error(t);let r=t.message?t.message:t;return new uQ(lQ.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR,r)}}a(tRe,"getRemoteSourceConfig");function rRe(e,t,r,n){this.uptime=r,this.ports={clustering:e,operations_api:t},this.system_info=n}a(rRe,"ConfigResponseObject")});var pQ=P((E0e,mQ)=>{"use strict";var _Q=le();_Q.initSync();var hQ=Ut(),Rm=z(),Gd=(B(),D(q)),pP=ot(),nRe=tQ(),sRe=cQ(),iRe=fQ(),oRe=Tm(),{encode:aRe,decode:cRe}=require("msgpackr"),lRe=fs(),uRe=Ai(),dRe=require("util"),fRe=(B(),D(q)),{isMainThread:_Re,parentPort:hRe}=require("worker_threads");Ze();var mRe=dRe.promisify(lRe.setSchemaDataToGlobal),EP=_Q.get(Gd.CONFIG_PARAMS.CLUSTERING_NODENAME);mQ.exports=pRe;async function pRe(){try{Rm.notify("Starting reply service."),await mRe();let e=await hQ.getConnection(),t=`${EP}.__request__`,r=e.subscribe(t,{queue:EP});await ERe(r)}catch(e){Rm.error(e)}}a(pRe,"initialize");async function ERe(e){for await(let t of e){let r=cRe(t.data),n;switch(r.operation){case Gd.OPERATIONS_ENUM.ADD_NODE:case Gd.OPERATIONS_ENUM.UPDATE_NODE:n=await nRe(r);break;case Gd.OPERATIONS_ENUM.REMOVE_NODE:n=await sRe(r);break;case Gd.OPERATIONS_ENUM.CLUSTER_STATUS:n=await iRe(r);break;case Gd.OPERATIONS_ENUM.DESCRIBE_ALL:n=await gRe();break;default:let s=`node '${EP}' reply service received unrecognized request operation`;Rm.error(s),n=new oRe(pP.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR,s)}Rm.trace(n),t.respond(aRe(n))}}a(ERe,"handleRequest");async function gRe(){try{return{status:pP.UPDATE_REMOTE_RESPONSE_STATUSES.SUCCESS,message:await uRe.describeAll({bypass_auth:!0})}}catch(e){return Rm.error(e),{status:pP.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR,message:e.message}}}a(gRe,"getRemoteDescribeAll");_Re||hRe.on("message",async e=>{let{type:t}=e;t===fRe.ITC_EVENT_TYPES.SHUTDOWN&&hQ.closeConnection()})});var SRe=pQ();(async()=>{try{await SRe()}catch(e){console.error("Error launching Nats reply service."),console.error(e)}})();
|
|
132
|
+
`;Te.message=`${ye}${Te.message}`,Te.stack=`${ye}${Te.stack}`,im?.(Te),Il.default.error(Te),t.set(_.path||"/",new Zo(Te)),Ud.set(n?d:(0,St.basename)(e),Te.message)}}}}catch(S){S.message=`Could not load component '${d}' for application '${(0,St.basename)(e)}' due to: ${S.message}`,im?.(S),((0,om.getWorkerIndex)()===0?console:Il.default).error(S),t.set(_.path||"/",new Zo(S),null,!0),Ud.set(n?d:(0,St.basename)(e),S.message)}}if(OT=u,vd.isMainThread&&!Nz&&i&&(0,om.watchDir)(e,async()=>wz()),c.extensionModule){let d=await RE((0,St.join)(e,c.extensionModule));return bT.set(o,d),d}if(!f&&t.isWorker){let d=`${e} did not load any modules, resources, or files, is this a valid component?`;im?.(new Error(d)),((0,om.getWorkerIndex)()===0?console:Il.default).error(d),Ud.set((0,St.basename)(e),d)}}catch(c){console.error(`Could not load application directory ${e}`,c),c.message=`Could not load application due to ${c.message}`,im?.(c),t.set("",new Zo(c))}}var lt,St,vd,DC,UC,xC,bz,om,Il,Oz,LC,aSe,wT,cSe,CC,MC,Nz,PC,Ud,lSe,vC,yz,bT,im,OT,dSe,Oh=be(()=>{lt=require("fs"),St=require("path"),vd=require("worker_threads"),DC=require("yaml"),UC=M(le()),xC=M(pt());B();JD();ML();cB();fB();_B();JB();LK();HK();FK();bz=M(require("fast-glob")),om=M(Ze()),Il=M(z());bb();Pr();Oz=M(me());ve();eC();LC=M(le()),aSe=M(rz());nS();uz();hs();Rz();wT=M(wt());IE();BA();({readFile:cSe}=lt.promises),CC=(0,wT.resolvePath)(UC.get(U.COMPONENTSROOT)),MC=new Map,Ud=new Map;a(wz,"loadComponentDirectories");lSe={REST:PE,rest:PE,graphql:rR,graphqlSchema:qA,roles:yb,jsResource:Nb,fastifyRoutes:pI,login:Ib,static:EI,operationsApi:aSe,customFunctions:{},http:{},clustering:RC,replication:Sa,authentication:Eh,mqtt:IC,loadEnv:gI},vC={rest:!0,graphqlSchema:{files:"*.graphql"},roles:{files:"roles.yaml"},jsResource:{files:"resources.js"},fastifyRoutes:{files:"routes/*.js",path:"."}};Object.defineProperty(vC,"static",{value:{files:"web/**"}});yz=[],bT=new Map;a(uSe,"setErrorReporter");dSe=a(()=>OT,"getComponentName");a(fSe,"symlinkHarperModule");a(NT,"loadComponent")});var dT=P((fUe,Cz)=>{var{isMainThread:Iz}=require("worker_threads"),{getTables:_Se,getDatabases:uUe,table:dUe}=(ve(),D(it)),{loadComponentDirectories:hSe,loadComponent:mSe}=(Oh(),D(bh)),{resetResources:pSe}=(Jl(),D(WD)),ESe=hw(),gSe=wt(),{dirname:SSe}=require("path"),{getConnection:TSe}=Ut(),ASe=le(),{CONFIG_PARAMS:RSe}=(B(),D(q)),{loadCertificates:ySe}=Js(),BC=new Map;async function bSe(e=!1){!Iz&&ASe.get(RSe.CLUSTERING_ENABLED)&&TSe();try{Iz&&await ESe()}catch(n){console.error(n)}let t=pSe();_Se(),t.isWorker=e,await ySe(),await mSe(SSe(gSe.getConfigFilePath()),t,"hdb",!0,BC),await hSe(BC,t);let r=[];for(let[n]of BC)n.ready&&r.push(n.ready());r.length>0&&await Promise.all(r)}a(bSe,"loadRootComponents");Cz.exports.loadRootComponents=bSe});var Ze=P((hUe,ai)=>{"use strict";HA();var{Worker:OSe,MessageChannel:NSe,parentPort:qi,isMainThread:GC,threadId:wSe,workerData:Gi}=require("worker_threads"),{PACKAGE_ROOT:ISe}=pt(),{join:Mz,isAbsolute:CSe,extname:PSe}=require("path"),{server:vz}=(Pr(),D(jl)),{watch:DSe,readdir:LSe}=require("fs/promises"),{totalmem:Pz}=require("os"),xd=(B(),D(q)),Uz=le(),oi=z(),{randomBytes:MSe}=require("crypto"),{_assignPackageExport:vSe}=ci(),Dz=1024*1024,Qa=[],Ps=[],USe=50,$C=1e4,xSe="restart",xz="request_thread_info",Bz="resource_report",Hz="thread_info",kz="added-port",BSe="ack",HC;vSe("threads",Ps);ai.exports={startWorker:kC,restartWorkers:KC,shutdownWorkers:GSe,workers:Qa,setMonitorListener:QSe,onMessageFromWorkers:$Se,onMessageByType:Yz,broadcast:KSe,broadcastWithAcknowledgement:WSe,setChildListenerByType:qSe,getWorkerIndex:Fz,getWorkerCount:qz,getTicketKeys:$z,setMainIsWorker:kSe,setTerminateTimeout:HSe,restartNumber:Gi?.restartNumber||1};Ps.onMessageByType=Yz;Ps.sendToThread=function(e,t){if(!t?.type)throw new Error("A message with a type must be provided");let r=Ps.find(n=>n.threadId===e);if(r)return r.postMessage(t),!0};ai.exports.whenThreadsStarted=new Promise(e=>{ai.exports.threadsHaveStarted=e});var VC;function HSe(e){$C=e}a(HSe,"setTerminateTimeout");function Fz(){return Gi?Gi.workerIndex:VC?0:void 0}a(Fz,"getWorkerIndex");function qz(){return Gi?Gi.workerCount:VC?1:void 0}a(qz,"getWorkerCount");function kSe(e){VC=e,ai.exports.threadsHaveStarted()}a(kSe,"setMainIsWorker");var Gz=1,IT;function $z(){return IT||(IT=GC?MSe(48):Gi.ticketKeys,IT)}a($z,"getTicketKeys");Object.defineProperty(vz,"workerIndex",{get(){return Fz()}});Object.defineProperty(vz,"workerCount",{get(){return qz()}});var Vz={[xz](e,t){zSe(t)},[Bz](e,t){jSe(t,e)}};function kC(e,t={}){let r=process.constrainedMemory?.()||Pz();r=Math.min(r,Pz(),2e4*Dz);let n=Uz.get(xd.CONFIG_PARAMS.THREADS_MAXHEAPMEMORY)??Math.max(Math.floor(r/Dz/(10+(t.threadCount||1)/4)),512),s=Math.min(Math.max(n>>6,16),64),i=[],o=[];for(let l of Ps){let u=new NSe;u.existingPort=l,i.push(u),o.push(u.port2)}PSe(e)||(e+=".js");let c=new OSe(CSe(e)?e:Mz(ISe,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:Gz=t.threadCount,name:t.name,restartNumber:ai.exports.restartNumber,ticketKeys:$z()},transferList:o,...t});for(let{port1:l,existingPort:u}of i)u.postMessage({type:kz,port:l,threadId:c.threadId},[l]);return PT(c,!0),c.unexpectedRestarts=t.unexpectedRestarts||0,c.startCopy=()=>kC(e,t),c.on("error",l=>{oi.error(`Worker index ${t.workerIndex} error:`,l)}),c.on("exit",l=>{Qa.splice(Qa.indexOf(c),1),!c.wasShutdown&&t.autoRestart!==!1&&(c.unexpectedRestarts<USe?(t.unexpectedRestarts=c.unexpectedRestarts+1,kC(e,t)):oi.error(`Thread has been restarted ${c.restarts} times and will not be restarted`))}),c.on("message",l=>{Vz[l.type]?.(l,c)}),Qa.push(c),XSe(),t.onStarted&&t.onStarted(c),c.name=t.name,c}a(kC,"startWorker");var FSe=[xd.THREAD_TYPES.HTTP];async function KC(e=null,t=Math.max(Gz>3,1),r=!0){if(GC){try{process.chdir(process.cwd())}catch(o){oi.error("Unable to reestablish current working directory",o)}if(r){let{loadRootComponents:o}=dT();await o()}ai.exports.restartNumber++,t<1&&(t=t*Qa.length);let n=[],s=[];for(let o of Qa.slice(0)){if(e&&o.name!==e||o.wasShutdown)continue;oi.trace("sending shutdown request to ",o.threadId),o.postMessage({restartNumber:ai.exports.restartNumber,type:xd.ITC_EVENT_TYPES.SHUTDOWN}),o.wasShutdown=!0,o.emit("shutdown",{});let c=FSe.indexOf(o.name)>-1,l=new Promise(u=>{let f=setTimeout(()=>{oi.warn("Thread did not voluntarily terminate, terminating from the outside",o.threadId),o.terminate()},$C*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===xd.ITC_EVENT_TYPES.CHILD_STARTED&&(oi.trace("Worker has started",u.threadId),d(),s.splice(s.indexOf(f)),u.off("message",_))},"startListener");oi.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}=cd();r&&(e==="http"||!e)&&Uz.get(xd.CONFIG_PARAMS.CLUSTERING_ENABLED)&&await i({service:"clustering"})}else qi.postMessage({type:xSe,workerType:e})}a(KC,"restartWorkers");function qSe(e,t){Vz[e]=t}a(qSe,"setChildListenerByType");function GSe(e){return KC(e,1/0,!1)}a(GSe,"shutdownWorkers");var Kz=[];function $Se(e){Kz.push(e)}a($Se,"onMessageFromWorkers");var FC=new Map;function Yz(e,t){let r=FC.get(e);r||FC.set(e,r=[]),r.push(t)}a(Yz,"onMessageByType");var VSe=10;async function KSe(e,t){let r=0;for(let n of Ps)try{n.postMessage(e),r++>VSe&&(r=0,await new Promise(setImmediate))}catch(s){oi.error("Unable to send message to worker",s)}t&&zz(e,null)}a(KSe,"broadcast");var CT=new Map,YSe=1;function WSe(e){return new Promise(t=>{let r=0;for(let n of Ps)try{let s=YSe++,i=a(()=>{CT.delete(s),--r===0&&t(),n!==qi&&--n.refCount===0&&n.unref()},"ack_handler");i.port=n,n.ref(),n.refCount=(n.refCount||0)+1,CT.set(e.requestId=s,i),n.hasAckCloseListener||(n.hasAckCloseListener=!0,n.on(n.close?"close":"exit",()=>{for(let[,o]of CT)o.port===n&&o()})),n.postMessage(e),r++}catch(s){oi.error("Unable to send message to worker",s)}r===0&&t()})}a(WSe,"broadcastWithAcknowledgement");function zSe(e){e.postMessage({type:Hz,workers:Wz()})}a(zSe,"sendThreadInfo");function Wz(){let e=Date.now();return Qa.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(Wz,"getChildWorkerInfo");function jSe(e,t){e.resources=t,e.resources.updated=Date.now()}a(jSe,"recordResourceReport");var qC;function QSe(e){qC=e}a(QSe,"setMonitorListener");var JSe=1e3,Lz=!1;function XSe(){Lz||(Lz=!0,setInterval(()=>{for(let e of Qa){let t=e.performance.eventLoopUtilization(),r;e.lastTotalELU?r=e.performance.eventLoopUtilization(t,e.lastTotalELU):r=t,e.lastTotalELU=t,e.recentELU=r}qC&&qC()},JSe).unref())}a(XSe,"startMonitoring");var ZSe=1e3;if(qi&&Gi?.addPorts){PT(qi);for(let e=0,t=Gi.addPorts.length;e<t;e++){let r=Gi.addPorts[e];r.threadId=Gi.addThreadIds[e],PT(r)}setInterval(()=>{let e=process.memoryUsage();qi.postMessage({type:Bz,heapTotal:e.heapTotal,heapUsed:e.heapUsed,external:e.external,arrayBuffers:e.arrayBuffers})},ZSe).unref(),HC=a(()=>new Promise((e,t)=>{qi.on("message",r),qi.postMessage({type:xz});function r(n){n.type===Hz&&(qi.off("message",r),e(n.workers))}a(r,"receiveThreadInfo")}),"getThreadInfo")}else HC=Wz;ai.exports.getThreadInfo=HC;function PT(e,t){Ps.push(e),e.on("message",r=>{if(r.type===kz)r.port.threadId=r.threadId,PT(r.port);else if(r.type===BSe){let n=CT.get(r.id);n&&n()}else zz(r,e)}).on("close",()=>{Ps.splice(Ps.indexOf(e),1)}).on("exit",()=>{Ps.splice(Ps.indexOf(e),1)}),t?e.refCount=100:e.unref()}a(PT,"addPort");function zz(e,t){for(let n of Kz)n(e,t);let r=FC.get(e.type);if(r)for(let n of r)try{n(e,t)}catch(s){oi.error(s)}}a(zz,"notifyMessageListeners");if(GC){let e,t,r=new Set,n=a(async(s,i)=>{i&&(e=i);for(let o of await LSe(s,{withFileTypes:!0}))o.isDirectory()&&o.name!=="node_modules"&&n(Mz(s,o.name));try{for await(let{filename:o}of DSe(s,{persistent:!1}))r.add(o),t&&clearTimeout(t),t=setTimeout(async()=>{e&&await e(),await KC(),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");ai.exports.watchDir=n,process.env.WATCH_DIR&&n(process.env.WATCH_DIR)}else qi.on("message",async e=>{let{type:t}=e;t===xd.ITC_EVENT_TYPES.SHUTDOWN&&(ai.exports.restartNumber=e.restartNumber,qi.unref(),setTimeout(()=>{oi.warn("Thread did not voluntarily terminate",wSe),process.exit(0)},$C).unref())})});var wx={};Ue(wx,{ACTION_32_BIT:()=>Ap,ACTION_64_BIT:()=>rTe,AUDIT_STORE_OPTIONS:()=>fh,Decoder:()=>Xc,HAS_BLOBS:()=>pn,HAS_CURRENT_RESIDENCY_ID:()=>Sc,HAS_EXPIRATION_EXTENDED_TYPE:()=>Df,HAS_ORIGINATING_OPERATION:()=>Pf,HAS_PREVIOUS_RESIDENCY_ID:()=>Tc,REMOTE_SEQUENCE_UPDATE:()=>cg,createAuditEntry:()=>ru,getLastRemoved:()=>kO,openAuditStore:()=>MT,readAuditEntry:()=>Ot,removeAuditEntry:()=>vT,setAuditRetention:()=>tTe,transactionKeyEncoder:()=>nj});function MT(e){let t=e.auditStore=e.openDB(YC.AUDIT_STORE_NAME,{create:!1,...fh});t||(t=e.auditStore=e.openDB(YC.AUDIT_STORE_NAME,fh),Qz(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=zC;Qh(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()-WC/(1+i*i)})){try{_=vT(t,m,S)}catch(g){Bd.warn("Error removing audit entry",g)}if(h=m,await new Promise(setImmediate),++d>=eTe){o=10;break}}await _}finally{d===0?o=Math.min(o<<1,WC/10):(Qz(t,h),o>100&&(o=o>>1)),f(void 0),c()}},o).unref()});return u}if(a(c,"scheduleAuditCleanup"),t.scheduleAuditCleanup=c,(0,cm.getWorkerIndex)()===(0,cm.getWorkerCount)()-1&&c(),(0,cm.getWorkerIndex)()===0&&!jz)for(let l of t.getKeys({reverse:!0,limit:1}))l>Date.now()&&(jz=!0,Bd.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 vT(e,t,r){let n=nTe(r),s;if(n&pn){s=Ot(r);let i=e.tableStores[s.tableId],o=i?.getEntry(s.recordId);(!o||o.version!==s.version||!o.value)&&_c(()=>ea(s.getValue(i)),i.rootStore)}if((n&15)===jC){s=s||Ot(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 Qz(e,t){QC[0]=t,e.put(Symbol.for("last-removed"),sj)}function kO(e){let t=e.get(Symbol.for("last-removed"));if(t)return sj.set(t),QC[0]}function tTe(e,t=zC){WC=e,zC=t}function ru(e,t,r,n,s,i,o,c,l,u,f,d,_){let h=ij[o];if(!h)throw new Error(`Invalid audit entry type ${o}`);let m=1;if(n&&(n>1?Ja.setFloat64(0,n):Ds.set(fR),m=9),l){if(l&255)throw new Error("Illegal extended type");m+=3}A(s),A(t),g(r),Ja.setFloat64(m,e),m+=8,l&Sc&&A(u),l&Tc&&A(f),l&Df&&(Ja.setFloat64(m,d),m+=8),l&Pf&&A(oj[_]),i?g(i):Ds[m++]=0,l?Ja.setUint32(n?8:0,h|l|3221225472):Ds[n?8:0]=h;let S=Ds.subarray(0,m);if(c)return Buffer.concat([S,c]);return S;function g(E){let T=m;m+=1,m=(0,Cl.writeKey)(E,Ds,m);let w=m-T-1;w>127?w>16383?(Bd.error("Key or username was too large for audit entry",E),m=T+1,Ds[T]=0):(Ds.copyWithin(T+2,T+1,m),Ja.setUint16(T,w|32768),m++):Ds[T]=w}function A(E){E<128?Ds[m++]=E:E<16384?(Ja.setUint16(m,E|32768),m+=2):E<1056964608?(Ja.setUint32(m,E|3221225472),m+=4):(Ds[m]=255,Ja.setUint32(m+1,E),m+=5)}}function nTe(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 Xc(e.buffer,e.byteOffset,e.byteLength));return n.position=t,n.readInt()}function Ot(e,t=0,r=void 0){try{let n=e.dataView||(e.dataView=new Xc(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&Sc&&(_=n.readInt()),i&Tc&&(h=n.readInt()),i&Df&&(m=n.readFloat64()),i&Pf){let T=n.readInt();S=oj[T]}l=n.readInt();let g=n.position,A=n.position+=l,E;return{type:ij[i&7],tableId:c,nodeId:o,get recordId(){return(0,Cl.readKey)(e,u,f)},getBinaryRecordId(){return e.subarray(u,f)},version:d,previousLocalTime:s,get user(){return A>g?(0,Cl.readKey)(e,g,A):void 0},get encoded(){return t?e.subarray(t,r):e},getValue(T,w,v){if(i&DT||i&am&&!w)return E||(E=_c(()=>T.decoder.decode(e.subarray(n.position,r)),T.rootStore)),E;if(i&am&&v)return cb(T.getEntry(this.recordId),v,T)},getBinaryValue(){return i&(DT|am)?e.subarray(n.position,r):void 0},extendedType:i,residencyId:_,previousResidencyId:h,expiresAt:m,originatingOperation:S}}catch(n){return Bd.error("Reading audit entry error",n,e),{}}}var Cl,LT,YC,cm,rj,Bd,Ds,Ja,nj,fh,WC,eTe,QC,sj,zC,jz,DT,am,Jz,jC,Xz,Zz,ej,tj,Ap,rTe,cg,Sc,Tc,Pf,Df,pn,ij,oj,Xc,ro=be(()=>{Cl=require("ordered-binary"),LT=M(le()),YC=M(vt());B();cm=M(Ze()),rj=M(oe());nu();Bd=M(z());lE();ls();nT();(0,LT.initSync)();Ds=Buffer.alloc(2816),Ja=new DataView(Ds.buffer,Ds.byteOffset,2816),nj={writeKey(e,t,r){return e===Cf?(t.set(Cf,r),r+8):typeof e=="number"?((t.dataView||(t.dataView=new DataView(t.buffer,t.byteOffset,t.byteLength))).setFloat64(r,e),r+8):(0,Cl.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,Cl.readKey)(e,t,r)}},fh={encoding:"binary",keyEncoder:nj},WC=(0,rj.convertToMS)((0,LT.get)(U.LOGGING_AUDITRETENTION))||86400*3,eTe=1e3,QC=new Float64Array(1),sj=new Uint8Array(QC.buffer),zC=1e4,jz=!1;a(MT,"openAuditStore");a(vT,"removeAuditEntry");a(Qz,"updateLastRemoved");a(kO,"getLastRemoved");a(tTe,"setAuditRetention");DT=16,am=32,Jz=1,jC=2,Xz=3,Zz=4,ej=5,tj=6,Ap=14,rTe=15,cg=11,Sc=512,Tc=1024,Pf=2048,Df=4096,pn=8192,ij={put:Jz|DT,[Jz]:"put",delete:jC,[jC]:"delete",message:Xz|DT,[Xz]:"message",invalidate:Zz|am,[Zz]:"invalidate",patch:ej|am,[ej]:"patch",relocate:tj,[tj]:"relocate"},oj={insert:1,update:2,upsert:3,1:"insert",2:"update",3:"upsert"};a(ru,"createAuditEntry");a(nTe,"readAction");a(Ot,"readAuditEntry");Xc=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 ZC(e,t,r,n,s){let i=e.primaryStore.env.path,o=e.primaryStore.tableId,c;s?.crossThreads===!1?(c=cj,sTe(e.primaryStore,e.auditStore)):(c=aj,e.primaryStore.env.hasSubscriptionCommitListener||(e.primaryStore.env.hasSubscriptionCommitListener=!0,e.primaryStore.on("committed",()=>{lj(aj[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=Ql(t);let f=new XC(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 lj(e){if(!e)return;let t=e.auditStore;t.resetReadTxn(),uj(e.auditStore);let r;for(let{key:n,value:s}of t.getRange({start:e.lastTxnTime,exclusiveStart:!0})){e.lastTxnTime=n;let i=Ot(s),o=e[i.tableId];if(!o)continue;let c=i.recordId,l=Ql(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,JC.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,JC.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 sTe(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=cj[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{lj(l)}finally{r.threadLocalWrites[0]=l.lastTxnTime,r.unlock("thread-local-writes")}},"acquiredLock");r.attemptLock("thread-local-writes",u)&&u()})}}function uj(e){e.nextTransaction?.resolve();let t;e.nextTransaction=new Promise(r=>{t=r}),e.nextTransaction.resolve=t}function Xk(e){return e.nextTransaction||(ZC({primaryStore:e,auditStore:e},null,null,0,{scope:"full-database"}),uj(e)),e.nextTransaction}var JC,aj,cj,XC,FO=be(()=>{JC=M(z());Vl();Jl();ro();aj=Object.create(null),cj=Object.create(null);a(ZC,"addSubscription");XC=class extends Ln{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(lj,"notifyFromTransactionData");a(sTe,"listenToCommits");a(uj,"nextTransaction");a(Xk,"whenNextTransaction")});var Jw={};Ue(Jw,{EVICTED:()=>Jo,INVALIDATED:()=>fn,coerceType:()=>BT,makeTable:()=>kT,setServerUtilities:()=>fTe});function kT(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:A}=e;S??=0;let{attributes:E}=e;E||(E=[]);let T=mR(i,n,l),w,v,k={},$=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&&(k=K);let Y,ne=[],ue=[],ae=1,pe=2,Te={},ye={},Qt=864e5,ut=0,Rr,is,Pn,xl=!1,Bl,eA=new Map,tA=new Map,Lt,$d,ym=Dl.get(U.REPLICATION_DATABASES);if(Array.isArray(ym)){for(let K of ym)if(K.name===c&&K.replicateTo>=0){$d=K.replicateTo;break}}let bm=i.getRange({start:!1,end:!1}).constructor,Vd=10,Om=6;g&&zd(),Qh(i.env.path,K=>{if(v)return Ki(K)});class Ce extends $r{#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 R=a(I=>{let L=this.sources;if(L=L.filter(H=>H.intermediateSource&&H[I]&&(!H[I].reliesOnPrototype||H.prototype[I])),L.length>0)if(L.length===1){let H=L[0];return(N,x,G)=>{if(N?.source!==H)return H[I](x,G,N)}}else return(H,N,x)=>{let G=[];for(let j of L){if(H?.source===j)break;G.push(j[I](N,x,H))}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,H,N)=>{if(!L?.source)return y[I](H,N,L)}},"getApplyToCanonicalSource");Te={put:b("put"),patch:b("patch"),delete:b("delete"),publish:b("publish")},ye={put:R("put"),patch:R("patch"),delete:R("delete"),publish:R("publish"),invalidate:R("invalidate")};let C=y.shouldRevalidateEvents;return(async()=>{let I=!1,L,H=a(async(N,x)=>{let G=N.value,j=N.table?Ve[c][N.table]:Ce;if(c===Jd&&(N.table===Gl.ROLE_TABLE_NAME||N.table===Gl.USER_TABLE_NAME)&&(I=!0),N.id===void 0&&(N.id=G[j.primaryKey],N.id===void 0))throw new Error("Replication message without an id "+JSON.stringify(N));N.source=p;let ie={residencyId:tc(N.residencyList),isNotification:!0,ensureLoaded:!1,nodeId:N.nodeId},F=await j.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&&A==null&&(A=!0);let x={crossThreads:!1,inTransactionUpdates:!0,supportsTransactions:!0,omitCurrent:!0},G=p.subscribeOnThisThread?p.subscribeOnThisThread((0,Pl.getWorkerIndex)(),x):(0,Pl.getWorkerIndex)()===0,j=N&&G&&await p.subscribe?.(x);if(j){let ie;for await(let F of j)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(H(F,ie));continue}!F.timestamp&&F.version&&(F.timestamp=F.version);let Z=bt(F,()=>{if(F.type==="transaction"){let ce=[];for(let ee of F.writes)try{ce.push(H(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&&(dt({table:s,database:c,attributes:ce,origin:"cluster"}),um.signalSchemaChange(new dm.SchemaEventMsg(process.pid,Gt.CREATE_TABLE,c,s)))}else return F.beginTxn?(ie=F,ie.write_promises=[H(F,F)],new Promise(ce=>{ie.resolve=()=>ce(Promise.all(ie.write_promises))})):H(F,F)});ie&&(ie.committed=Z),I&&Z&&!Z?.waitingForUserChange&&(Z.then(()=>um.signalUserChange(new dm.UserEventMsg(process.pid))),Z.waitingForUserChange=!0),F.onCommit&&(Z?Z.then(F.onCommit):F.onCommit())}catch(Ge){xe.default.error?.("error in subscription handler",Ge)}}}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,R){let y=super.getResource(p,O,R);if(p!=null){wr(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=!R?.async||i.cache?.get?.(p),C=qr(O),I=C.getReadTxn();if(I?.isDone)throw new Error("You can not read from a transaction that has already been committed/aborted");return Hl(p,O,{transaction:I,ensureLoaded:R?.ensureLoaded},b,L=>{if(L?Ce._updateResource(y,L):y.#e=null,O.onlyIfCached&&O.noCacheStore){if(!y.doesExist())throw new Nr.ServerError("Entry is not cached",504)}else if(R?.ensureLoaded){let H=kl(p,L,O,y);if(H)return C?.disregardReadTxn(),y.#i=!0,tP(H,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=kl(this.getId(),this.#r,this.getContext());if(p)return this.#i=!0,tP(p,O=>{this.#r=O,this.#e=O.value,this.#n=O.version})}static getNewId(){let p=k?.type;if(p==="String"||p==="ID")return super.getNewId();if(!Lt){let b=i.getEntry(Symbol.for("id_allocation")),C=b?.value,I;if(C&&C.nodeName===server.hostname&&(!hTe(i)||C.pid===process.pid)){let L=C.start,H=C.end;I=L;for(let N of i.getKeys({start:H,end:L,limit:1,reverse:!0}))I=N}else C=y(b?.version??null),I=C.start;Lt=new BigInt64Array([BigInt(I)+1n]),Lt=new BigInt64Array(i.getUserSharedBuffer("id",Lt.buffer)),Lt.maxSafeId=C.end}let O=Number(Atomics.add(Lt,0,1n)),R=p==="Int"?512:1048576;if(O+R>=Lt.maxSafeId){let b=a(C=>{Lt.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(),H=Number(Lt[0]);for(let G of i.getKeys({start:H+1,end:I,limit:1,transaction:L}))I=G;L?.done();let{value:N,version:x}=i.getEntry(Symbol.for("id_allocation"));if(Lt.maxSafeId<I){if(N.end>Lt.maxSafeId-100)return;xe.default.info?.("New id allocation",O,Lt.maxSafeId,x),i.put(Symbol.for("id_allocation"),{start:N.start,end:Lt.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 ${Lt.maxSafeId}, but id of ${I} detected`);let G=y(x);G.alreadyUpdated||Atomics.store(Lt,0,BigInt(G.start+1)),Lt.maxSafeId=G.end}},"updateEnd");O+R===Lt.maxSafeId?setImmediate(b):O+100>=Lt.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,H,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 j of i.getKeys({start:x,limit:1,reverse:!0}))L=j;H=C;for(let j of i.getKeys({start:x+1,end:C,limit:1}))H=j;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,H,I))}while(!(I<H-x&&(I<x-L||L===0)));return i.transactionSync(()=>{let j=i.getEntry(Symbol.for("id_allocation"));return(j?.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,...j.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,Ki()}static getResidencyRecord(p){return f.get([Symbol.for("residency_by_id"),p])}static setResidency(p){Ce.getResidency=p&&((O,R)=>{try{return p(O,R)}catch(y){throw y.message+=` in residency function for table ${s}`,y}})}static setResidencyById(p){Ce.getResidencyById=p&&(O=>{try{return p(O)}catch(R){throw R.message+=` in residency function for table ${s}`,R}})}static getResidency(p,O){if(Ce.getResidencyById)return Ce.getResidencyById(p[t]);let R=$d;if(O.replicateTo!=null){if(Array.isArray(O.replicateTo))return O.replicateTo.includes(server.hostname)?O.replicateTo:[server.hostname,...O.replicateTo];O.replicateTo>=0&&(R=O.replicateTo)}if(R>=0&&server.nodes){let y=[server.hostname];if(O.previousResidency)y.push(...O.previousResidency.slice(0,R));else{let b=server.nodes.map(L=>L.name),C=Math.floor(b.length*Math.random());y.push(...b.slice(C,C+R));let I=C+R-b.length;I>0&&y.push(...b.slice(0,I))}return y}}static enableAuditing(p=!0){g=p,p&&zd(),Ce.audit=p}static coerceId(p){return p===""?null:BT(p,k)}static async dropTable(){delete Ve[c][s];for(let p of i.getRange({versions:!0,snapshot:!1,lazy:!0}))p.metadataFlags&pn&&p.value&&ea(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 xT.default.remove(data_path),await xT.default.remove(data_path===standard_path?data_path+MDB_LOCK_FILE_SUFFIX:path.join(path.dirname(data_path),MDB_LEGACY_LOCK_FILE_NAME));um.signalSchemaChange(new dm.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(R=>(O.recordCount=R.recordCount,O.estimatedRecordRange=R.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 R=Fr(p);if(R?.read){if(R.isSuperUser)return!0;let y=R.attribute_permissions,b=O?.select;if(y?.length>0||xl&&b){if(O||(O={}),b){let C=y?.length>0&&eP(y,"read");O.select=b.map(I=>{let L=I.name||I;if(!C||C[L]){let H=Pn[L]?.definition?.tableClass;if(H){if(I.name||(I={name:I}),!H.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&&!Pn[C.attribute_name]).map(C=>C.attribute_name);return O}else return!0}}allowUpdate(p,O){let R=Fr(p);if(R?.update){let y=R.attribute_permissions;if(y?.length>0){let b=eP(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 ql(this.getContext())}}allowCreate(p,O){if(this.isCollection){let R=Fr(p);if(R?.insert){let y=R.attribute_permissions;if(y?.length>0){let b=eP(y,"insert");for(let C in O)if(!b[C])return!1;return ql(this.getContext())}else return ql(this.getContext())}}else return this.allowUpdate(p,{})}allowDelete(p){return Fr(p)?.delete&&ql(this.getContext())}update(p,O){if(!qr(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===fj?this.set(p,(+this.getProperty(p)||0)+O):(this.#s||this.update(),this.set(p,new fE(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 R=this.getContext(),y=this.getId();wr(y),qr(this.getContext()).addWrite({key:y,store:i,invalidated:!0,entry:this.#r,before:Te.invalidate?.bind(this,R,y),beforeIntermediate:ye.invalidate?.bind(this,R,y),commit:a((C,I)=>{if(!(Vi(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,fn,g,{user:R?.user,residencyId:O?.residencyId,nodeId:O?.nodeId},"invalidate")}},"commit")})}_writeRelocate(p){let O=this.getContext(),R=this.getId();wr(R),qr(this.getContext()).addWrite({key:R,store:i,invalidated:!0,entry:this.#r,before:Te.relocate?.bind(this,O,R),beforeIntermediate:ye.relocate?.bind(this,O,R),commit:a((b,C)=>{if(Vi(b,C,p?.nodeId)<=0)return;let I=Ce.getResidencyRecord(p.residencyId),L=0,H=null,N=C?.value;if(I&&!I.includes(server.hostname)){for(let x in r)H||(H={}),H[x]=N(x);L=fn}else H=N;xe.default.trace?.(`Relocating entry id: ${R}, timestamp: ${new Date(b).toISOString()}`),T(R,H,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 R={previousResidency:this.getResidencyRecord(p.residencyId),isRelocation:!0},y=Yi(this.getResidency(O.value,R)),b;if(y){if(!y.includes(server.hostname))return!1;b=tc(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,R){let y=this.Source,b;if(!((v||g)&&(!O||(b=i.getEntry(p),!b||!O)||b.version!==R))){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,R,Jo,null,null,null,!0)}if(i.ifVersion(p,R,()=>{an(p,O,null)}),g)return T(p,null,b,R,Jo,null,null,null,!0);gc(i,b??i.getEntry(p),R)}}lock(){throw new Error("Not yet implemented")}static operation(p,O){return p.table||=s,p.schema||=c,Tj.operation(p,O)}put(p){this.update(p,!0)}patch(p){this.update(p,!1)}_writeUpdate(p,O,R){let y=this.getContext(),b=qr(y),C=this.getId();wr(C);let I=this.#r;this.#s=O?fj:lTe;let L={key:C,store:i,entry:I,nodeName:y?.nodeName,validate:a(H=>{p||(p=this.#t),O||p&&uE(this.#t===p?this:p)?y?.source||(b.checkOverloaded(),this.validate(p,!O),te&&(p[te.name]=te.type==="Date"?new Date(H):te.type==="String"?new Date(H).toISOString():H),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(H):W.type==="String"?new Date(H).toISOString():H),p=xc(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,xc(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,xc(this)):null,commit:a((H,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=H;let G=N?.value,j=p;this.#s=0;let ie=!1,F=Vi(H,N,R?.nodeId),Ge;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>H||fe>=H&&_e>0;){let De=l.get(_e);if(!De)break;let we=Ot(De);if(fe=we.version,fe>=H){if(fe===H){if(F=Vi(H,{version:fe,localTime:_e},R?.nodeId),F===0)return;if(F>0)continue}if(we.type==="patch")Ae.push(we),Ge=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(j=cE(j,we,O),xe.default.debug?.("Rebuilding update with future patch:",j),!j)return}}else{if(O)return;j=cE(j,G,O),xe.default.debug?.("Rebuilding update without audit:",j)}let Z;if(O?Z=j:(this.#e=G,Z=xc(this,j)),this.#e=Z,Z&&Z.getRecord)throw new Error("Can not assign a record to a record, check for circular references");let ce;if(R?.residencyId!=null)ce=R.residencyId;else{I?.residencyId&&(y.previousResidency=Ce.getResidencyRecord(I.residencyId));let _e=Yi(Ce.getResidency(Z,y));if(_e&&!_e.includes(server.hostname))if(Ge??=Z,ie=!0,Ce.getResidencyById)Z=void 0;else{Z=null;for(let fe in r)Z||(Z={}),Z[fe]=Ge[fe]}ce=tc(_e)}O||(Ge=p);let ee=y?.expiresAt??(m?m+Date.now():-1);xe.default.trace?.(`Saving record with id: ${C}, timestamp: ${new Date(H).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""}})()),an(C,G,Z);let Q=O?"put":"patch";T(C,Z,N,H,ie?fn:0,g,{omitLocalRecord:ie,user:y?.user,residencyId:ce,expiresAt:ee,nodeId:R?.nodeId,originatingOperation:y?.originatingOperation},Q,!1,Ge),y.expiresAt&&Ki()},"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=qr(this.getContext()),R=this.getId();wr(R);let y=this.getContext();return O.addWrite({key:R,store:i,entry:this.#r,nodeName:y?.nodeName,before:Te.delete?.bind(this,y,R),beforeIntermediate:ye.delete?.bind(this,y,R),commit:a((b,C,I)=>{let L=C?.value;I&&(y&&C?.version>(y.lastModified||0)&&(y.lastModified=C.version),Ce._updateResource(this,C)),!(Vi(b,C,p?.nodeId)<=0)&&(an(this.getId(),L),xe.default.trace?.(`Deleting record with id: ${R}, txn timestamp: ${new Date(b).toISOString()}`),g||A?(T(R,null,this.#r,b,0,g,{user:y?.user,nodeId:p?.nodeId},"delete"),g||Ki()):gc(i,C))},"commit")}),!0}search(p){let O=this.getContext(),R=qr(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?k:fi(E,De);if(we)(we.type||LA[Ae.comparator])&&(Ae[1]===void 0?Ae.value=H(Ae.value,we):Ae[1]=H(Ae[1],we));else if(De!=null)throw(0,Nr.handleHDBError)(new Error,`${De} is not a defined attribute`,404);if(Ae.chainedConditions)if(Ae.chainedConditions.length===1&&(!Ae.operator||Ae.operator=="and")){let _r=Ae.chainedConditions[0],Ir,Ms;if(_r.comparator==="gt"||_r.comparator==="greater_than"||_r.comparator==="ge"||_r.comparator==="greater_than_equal"?(Ir=Ae,Ms=_r):(Ir=_r,Ms=Ae),Ir.comparator!=="lt"&&Ir.comparator!=="less_than"&&Ir.comparator!=="le"&&Ir.comparator!=="less_than_equal")throw new Error("Invalid chained condition, only less than and greater than conditions can be chained together");let Re=Ms.comparator==="ge"||Ms.comparator==="greater_than_equal",yt=Ir.comparator==="le"||Ir.comparator==="less_than_equal";Ae.comparator=(Re?"ge":"gt")+(yt?"le":"lt"),Ae.value=[Ms.value,Ir.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,gj.sortBy)(Q,Qm(Ce)):Q}a(L,"orderConditions");function H(Q,_e){return Array.isArray(Q)?Q.map(fe=>BT(fe,_e)):BT(Q,_e)}a(H,"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 Nr.ClientError("Sort requires an attribute");if(b=y.find(_e=>zl(_e.attribute)===zl(Q)),!b){let _e=fi(E,Q);if(!_e)throw(0,Nr.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,Nr.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 j=p.select;if(y.length===0&&(y=[{attribute:t,comparator:"greater_than",value:!0}]),p.explain)return{conditions:y,operator:N,postOrdering:G,selectApplied:!!j};let ie=R.useReadTxn(),F=MA(y,N,Ce,ie,p,O,(Q,_e)=>Yd(Q,j,O,ie,_e),C),Ge=p.ensureLoaded!==!1;G||(F=ee(F));let Z=Ce.transformEntryForSelect(j,O,ie,C,Ge,!0),ce=Ce.transformToOrderedSelect(F,j,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,R.doneReadTxn()},ce.selectApplied=!0,ce.getColumns=()=>{if(j){let Q=[];for(let _e of j)_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,R,y,b,C){let I=new bm;if(R){p=Yd(p,O,y,b,null);let L;I.iterate=function(){let N,x=p[Symbol.asyncIterator]?p[Symbol.asyncIterator]():p[Symbol.iterator](),G,j=R.dbOrderedAttribute,ie,F,Ge=!0;function Z(ee){let Q=ee.next&&Z(ee.next),_e=ee.descending;return(fe,Ae)=>{let De=Fl(fe,ee.attribute,y),we=Fl(Ae,ee.attribute,y),_r=_e?(0,Ll.compareKeys)(we,De):(0,Ll.compareKeys)(De,we);return _r===0?Q?.(fe,Ae)||0:_r}}a(Z,"createComparator");let ce=Z(R);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),j){let _e=Fl(Q,j,y);if(Ge)Ge=!1,F=_e;else if(_e!==F){F=_e,ie=Q;break}}L.push(Q)}while(!0);return R.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 H=a(N=>{if(typeof O=="object"&&Array.isArray(N.attribute))for(let x=0;x<O.length;x++){let G=O[x],j;if(G.name===N.attribute[0]){for(j=G.sort||(G.sort={});j.next;)j=j.next;j.attribute=N.attribute.slice(1),j.descending=N.descending}else G===N.attribute[0]&&(O[x]=j={name:G,sort:{attribute:N.attribute.slice(1),descending:N.descending}})}N.next&&H(N.next)},"applySortingOnSelect");H(R)}else I.iterate=(p[Symbol.asyncIterator]||p[Symbol.iterator]).bind(p),I=I.map(function(L){try{let H=C.call(this,L);return typeof H?.catch=="function"?H.catch(N=>{throw N.partialObject={[t]:L.key},N}):H}catch(H){throw H.partialObject={[t]:L.key},H}});return I}static transformEntryForSelect(p,O,R,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,H=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&fn){if(N.metadataFlags&fn&&O.replicateFrom===!1&&C&&N.residencyId)return Za.SKIP;if(N=Hl(N.key??N,O,{transaction:R,lazy:p?.length<4,ensureLoaded:b},this?.isSync,G=>G),N?.then)return N.then(H.bind(this));x=N?.value}if(I&&N?.metadataFlags&(fn|Jo)||N?.expiresAt!=null&&N?.expiresAt<Date.now()){if(O.onlyIfCached&&O.noCacheStore)return{[t]:N.key,message:"This entry has expired"};let G=kl(N.key??N,N,O);if(G?.then)return G.then(H)}}if(x==null)return C?Za.SKIP:x;if(p&&!(p[0]==="*"&&p.length===1)){let G,j=a((F,Ge)=>{let Z;typeof F=="object"?Z=F.name:Z=F;let ce=Pn?.[Z],ee;if(ce){let Q=y?.[Z];if(Q)if(Q.hasMappings){let fe=ce.from?x[ce.from]:zl(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,R,Q,b));if(Array.isArray(fe)){let we=[],_r=Ae.transformToOrderedSelect(fe,F.select,typeof F.sort=="object"&&F.sort,O,R,De)[this.isSync?Symbol.iterator:Symbol.asyncIterator](),Ir=a(Re=>{for(;!Re.done;){if(Re?.then)return Re.then(Ir);we.push(Re.value),Re=_r.next()}Ge(we,Z)},"nextValue"),Ms=Ir(_r.next());Ms&&(G||(G=[]),G.push(Ms));return}else if(fe=De.call(this,fe),fe?.then){G||(G=[]),G.push(fe.then(we=>Ge(we,Z)));return}}Ge(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,R,null)({value:ee}));Ge(ee,Z)},"selectAttribute"),ie;if(typeof p=="string")j(p,F=>{ie=F});else if(Array.isArray(p))if(p.asArray)ie=[],p.forEach((F,Ge)=>{F==="*"?p[Ge]=x:j(F,Z=>ie[Ge]=Z)});else{ie={};let F=p.forceNulls;for(let Ge of p)if(Ge==="*")for(let Z in x)ie[Z]=x[Z];else j(Ge,(Z,ce)=>{Z===void 0&&F&&(Z=null),ie[ce]=Z})}else throw new Nr.ClientError("Invalid select"+p);return G?Promise.all(G).then(()=>ie):ie}return x},"transform");return H}async subscribe(p){if(!l)throw new Error("Can not subscribe to a table without an audit log");g||dt({table:s,database:c,schemaDefined:u,attributes:E,audit:!0}),p||(p={});let O=!p.rawEvents,R=[],y=this,b=ZC(Ce,this.getId()??null,function(I,L,H,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,H),G="put"}let j={id:I,localTime:H,value:x,version:L.version,type:G,beginTxn:N};R?R.push(j):this.send(j)}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 H=p.startTime;if(this.isCollection){if(H){if(L)throw new Nr.ClientError("startTime and previousCount can not be combined for a table level subscription");for(let{key:N,value:x}of l.getRange({start:H,exclusiveStart:!0,snapshot:!1})){let G=Ot(x);if(G.tableId!==n)continue;let j=G.recordId;if(I==null||pj(I,j)){let ie=G.getValue(i,O,N);if(b.send({id:j,localTime:N,value:ie,version:G.version,type:G.type}),b.queue?.length>hj&&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 j=Ot(G);if(j.tableId!==n)continue;let ie=j.recordId;if(I==null||pj(I,ie)){let F=j.getValue(i,O,x);if(N.push({id:ie,localTime:x,value:F,version:j.version,type:j.type}),--L<=0)break}}catch(j){xe.default.error("Error getting history entry",x,j)}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:j}of i.getRange({start:I??!1,end:I==null?void 0:[I,Ll.MAXIMUM_KEY],versions:!0,snapshot:!1}))if(x&&(b.send({id:N,localTime:j,value:x,version:G,type:"put"}),b.queue?.length>hj&&await b.waitForDrain()===!1))return}}else{L&&!H&&(H=0);let N=this.#r?.localTime;if(N===hR&&(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",H,"from",I,N),H<N){let x=[],G=N;do{let j=l.get(G);if(j){p.omitCurrent=!0;let ie=Ot(j),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>H&&L!==0);for(let j=x.length;j>0;)b.send(x[--j]);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 R)b.send(N);R=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 R=qr(this.getContext()),y=this.getId()||null;y!=null&&wr(y);let b=this.getContext();R.addWrite({key:y,store:i,entry:this.#r,nodeName:b?.nodeName,validate:a(()=>{b?.source||(R.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&&A&&!g&&Ki(),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 R,y=a((b,C,I)=>{if(C.type&&b!=null)if(O&&b.__op__&&(b=b.value),C.properties){typeof b!="object"&&(R||(R=[])).push(`Value ${Ls(b)} in property ${I} must be an object${C.type?" ("+C.type+")":""}`);let L=C.properties;for(let H=0,N=L.length;H<N;H++){let x=L[H],G=y(b[x.name],x,I+"."+x.name);G&&(b[x.name]=G)}if(C.sealed&&b!=null&&typeof b=="object")for(let H in b)L.find(N=>N.name===H)||(R||(R=[])).push(`Property ${H} is not allowed within object in property ${I}`)}else switch(C.type){case"Int":(typeof b!="number"||b>>0!==b)&&(R||(R=[])).push(`Value ${Ls(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))&&(R||(R=[])).push(`Value ${Ls(b)} in property ${I} must be an integer (from -9007199254740992 to 9007199254740992)`);break;case"Float":typeof b!="number"&&(R||(R=[])).push(`Value ${Ls(b)} in property ${I} must be a number`);break;case"ID":typeof b=="string"||b?.length>0&&b.every?.(L=>typeof L=="string")||(R||(R=[])).push(`Value ${Ls(b)} in property ${I} must be a string, or an array of strings`);break;case"String":typeof b!="string"&&(R||(R=[])).push(`Value ${Ls(b)} in property ${I} must be a string`);break;case"Boolean":typeof b!="boolean"&&(R||(R=[])).push(`Value ${Ls(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);(R||(R=[])).push(`Value ${Ls(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);(R||(R=[])).push(`Value ${Ls(b)} in property ${I} must be a bigint`)}break;case"Bytes":if(!(b instanceof Uint8Array)){if(typeof b=="string")return Buffer.from(b);(R||(R=[])).push(`Value ${Ls(b)} in property ${I} must be a Buffer or Uint8Array`)}break;case"Blob":if(!(b instanceof hi)){if(typeof b=="string"&&(b=Buffer.from(b)),b instanceof Buffer)return createBlob(b,{type:"text/plain"});(R||(R=[])).push(`Value ${Ls(b)} in property ${I} must be a Blob`)}break;case"array":if(Array.isArray(b)){if(C.elements)for(let L=0,H=b.length;L<H;L++){let N=b[L],x=y(N,C.elements,I+"[*]");x&&(b[L]=x)}}else(R||(R=[])).push(`Value ${Ls(b)} in property ${I} must be an Array`);break}C.nullable===!1&&b==null&&(R||(R=[])).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)||(R||(R=[])).push(`Property ${b} is not allowed`);if(R)throw new Nr.ClientError(R.join(". "))}getUpdatedTime(){return this.#n}wasLoadedFromSource(){return v?!!this.#i:void 0}static async addAttributes(p){let O=E.slice(0);for(let R of p){if(!R.name)throw new Nr.ClientError("Attribute name is required");if(R.name.match(/[`/]/))throw new Nr.ClientError("Attribute names cannot include backticks or forward slashes");(0,Sj.validateAttribute)(R.name),O.push(R)}return dt({table:s,database:c,schemaDefined:u,attributes:O}),Ce.indexingOperation}static async removeAttributes(p){let O=E.filter(R=>!p.includes(R.name));return dt({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=xT.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,R=1e3/2,y=performance.now(),b=Math.floor(O/2),C=p?.exactCount,I=0,L=0,H;for(let{value:N}of i.getRange({start:!0,lazy:!0,snapshot:!1}))if(N!=null&&I++,L++,await Xa(),!C&&L<b&&performance.now()-y>R){H=L;break}if(H){let N=I;I=0;for(let{value:ee}of i.getRange({start:"\uFFFF",reverse:!0,lazy:!0,limit:H,snapshot:!1}))ee!=null&&I++,await Xa();let x=H*2,G=(I+N)/x,j=Math.pow((I-N+1)/H/2,2)+G*(1-G)/x,ie=Math.max(Math.sqrt(j)*O,1),F=Math.round(G*O),Ge=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(Ge),Math.round(Z)]}}return{recordCount:I}}static updatedAttributes(){Pn=this.propertyResolvers={$id:a((p,O,R)=>({value:R.key}),"$id"),$updatedtime:a((p,O,R)=>R.version,"$updatedtime"),$record:a((p,O,R)=>R?{value:p}:p,"$record")};for(let p of this.attributes){p.isPrimaryKey&&(k=p),p.resolve=null;let O=p.relationship,R=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)"),R&&console.error("A relationship property is already computed and can not be combined with a computed function (the relationship will be given precedence)"),xl=!0,O.to)p.elements?.definition?(Pn[p.name]=p.resolve=(y,b,C)=>{let I=y[O.from?O.from:t],L=p.elements.definition.tableClass;return C?Wl({attribute:O.to,value:I},qr(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?(Pn[p.name]=p.resolve=(b,C,I)=>{let L=b[O.from];if(L!==void 0){if(p.elements){let H,N=L?.map(x=>{let G=I?y.tableClass.primaryStore.getEntry(x,{transaction:qr(C).getReadTxn()}):y.tableClass.get(x,C);return G?.then&&(H=!0),G});return O.filterMissing?H?Promise.all(N).then(x=>x.filter(Ej)):N.filter(Ej):H?Promise.all(N):N}return I?y.tableClass.primaryStore.getEntry(L,{transaction:qr(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 R&&(typeof R.from=="function"&&this.setComputedAttribute(p.name,R.from),Pn[p.name]=p.resolve=(y,b,C)=>{let I=typeof R.from=="string"?y[R.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]=()=>{}})}_E(this,this)}static setComputedAttribute(p,O){let R=fi(E,p);if(!R){console.error(`The attribute "${p}" does not exist in the table "${s}"`);return}if(!R.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 R;for(let{key:y,value:b}of l.getRange({start:0,end:p}))await Xa(),Ot(b).tableId===n&&(R=vT(l,y,b));if(O)for(let y of i.getRange({start:0,versions:!0})){let{key:b,value:C,localTime:I}=y;await Xa(),C===null&&I<p&&(R=gc(i,y))}await R}static async*getHistory(p=0,O=1/0){for(let{key:R,value:y}of l.getRange({start:p||1,end:O})){await Xa();let b=Ot(y);b.tableId===n&&(yield{id:b.recordId,localTime:R,version:b.version,type:b.type,value:b.getValue(i,!0,R),user:b.user,operation:b.originatingOperation})}}static async getHistoryOfRecord(p){let O=[];if(p==null)throw new Error("An id is required");let R=i.getEntry(p);if(!R)return O;let y=R.localTime;if(!y)throw new Error("The entry does not have a local audit time");let b=0;do{await Xa();let C=l.get(y);if(C){let I=Ot(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 Kd=Ce.prototype;return m&&Ce.setTTLExpiration(m/1e3),se&&Nm(),Ce;function an(K,p,O){let R;for(let y in r){let b=r[y],C=b.isIndexing,I=Pn[y],L=O&&(I?I(O):O[y]),H=p&&(I?I(p):p[y]);if(L===H&&!C)continue;R=!0;let N=b.indexNulls,x=(0,lm.getIndexedValues)(L,N),G=(0,lm.getIndexedValues)(H,N);if(G?.length>0){let j=new Set(G);if(x=x?x.filter(ie=>{if(j.has(ie))j.delete(ie);else return!0}):[],G=Array.from(j),(G.length>0||x.length>0)&&dj){let ie=G.concat(x).map(F=>({key:F,value:K}));b.prefetch(ie,mj)}for(let ie=0,F=G.length;ie<F;ie++)b.remove(G[ie],K)}else x?.length>0&&dj&&b.prefetch(x.map(j=>({key:j,value:K})),mj);if(x)for(let j=0,ie=x.length;j<ie;j++)b.put(x[j],K)}return R}a(an,"updateIndices");function wr(K){switch(typeof K){case"number":return!0;case"string":if(K.length<659)return!0;if(K.length>_j)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,Ll.writeKey)(K,uTe,0)>_j)throw new Error("Primary key size is too large: "+K.length);return!0}a(wr,"checkValidId");function Hl(K,p,O,R,y){if(Ce.getResidencyById&&O.ensureLoaded&&p?.replicateFrom!==!1){let C=Yi(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&fn&&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 R?b():ae>0?(ae--,b()):new Promise((C,I)=>{ae===0?(ae--,i.prefetch([K],()=>{L(),H()})):(ne.push(K),ue.push(H),ne.length>Om&&(ae--,L()));function L(){if(ne.length>0){let N=ue;i.prefetch(ne,()=>{ae===-1?L():ae++;for(let x of N)x()}),ne=[],ue=[],pe>2&&pe--}else ae=pe,pe<Vd&&pe++}a(L,"prefetch");function H(){try{C(b())}catch(N){I(N)}}a(H,"load")})}a(Hl,"loadLocalRecord");function Fr(K){if(!K?.role)return;let p=K.role.permission;if(p.super_user)return dTe;let O=p[c],R,y=O?.tables;if(y)return y[s];if(c==="data"&&(R=p[s])&&!R.tables)return R}a(Fr,"getTablePermissions");function kl(K,p,O,R){if(v){let y=!1;if(O.noCache?y=!0:(p?(!p.value||p.metadataFlags&(fn|Jo)||p.expiresAt!=null&&p.expiresAt<Date.now())&&(y=!0):y=!0,Yn(!y,"cache-hit",s)),y){let b=Wd(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&&R?.allowStaleWhileRevalidate?.(p,K)){if(b.catch(C=>xe.default.warn?.(C)),O?.onlyIfCached&&!R.doesExist())throw new Nr.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(kl,"ensureLoadedFromSource");function qr(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 oc,p.lmdbDb=i,p;p=O}while(!0)}else return new Wm}a(qr,"txnForContext");function Fl(K,p,O){if(!K)return;let R=K.value||i.getEntry(K.key)?.value;if(typeof p=="object"){let b=Pn,C=R;for(let I=0,L=p.length;I<L;I++){let H=p[I],N=b?.[H];C=N&&C?N(C,O,!0)?.value:C?.[H],b=N?.definition?.tableClass?.propertyResolvers}return C}let y=Pn[p];return y?y(R,O):R[p]}a(Fl,"getAttributeValue");function Yd(K,p,O,R,y){let b=y?.length,C={transaction:R,lazy:b>0||typeof p=="string"||p?.length<4,alwaysPrefetch:!0},I;function L(H,N){let x=H?.value;if(!x)return Za.SKIP;for(let G=0;G<b;G++)if(!I?.includes(G)&&!y[G](x,H))return Za.SKIP;return N!==void 0&&(H.key=N),H}if(a(L,"processEntry"),b>0||!K.hasEntries){let H=K.map(N=>{if(I=null,typeof N=="object"&&N?.key!==void 0)return b>0?L(N):N;if(N==null)return Za.SKIP;for(let x=0;x<b;x++){let j=y[x].idFilter;if(j){if(!j(N))return Za.SKIP;I||(I=[]),I.push(x)}}return Hl(N,O,C,!1,L)});return Array.isArray(K)&&(H=H.filter(N=>N!==Za.SKIP)),H.hasEntries=!0,H}return K}a(Yd,"transformToEntries");function Vi(K,p,O=server.replication?.getThisNodeId(l)){if(K<=p?.version){if(p?.version===K&&O!==void 0){let R=server.replication?.exportIdMapping(l),y=p.localTime,b=y&&l.get(y);if(b){let C,I,L=Ot(b);for(let H in R)R[H]===O&&(C=H),R[H]===L.nodeId&&(I=H);if(C>I)return 1;if(C===I)return 0}}return-1}return 1}a(Vi,"precedesExistingVersion");async function Wd(K,p,O){let R=p?.metadataFlags,y=p?.version,b,C;if(!i.attemptLock(K,y,()=>{clearTimeout(C);let N=i.getEntry(K);!N||!N.value||N.metadataFlags&(fn|Jo)?b(Wd(K,i.getEntry(K),O)):b(N)}))return new Promise(N=>{b=N,C=setTimeout(()=>{i.unlock(K,y)},cTe)});let I=p?.value,L={requestContext:O,replacingRecord:I,replacingEntry:p,replacingVersion:y,noCacheStore:!1,source:null,resourceCache:O?.resourceCache},H=O?.responseHeaders;return new Promise((N,x)=>{let G;tP(bt(L,async j=>{let ie=performance.now(),F,Ge,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=R&fn;let ee=L.lastModified||Z&&y;Ge=Z||ee>y||!I,ee||(ee=(0,lm.getNextMonotonicTime)());let Q=performance.now()-ie;if(rr(Q,"cache-resolution",s,null,"success"),H&&NE(H,"Server-Timing",`cache-resolve;dur=${Q.toFixed(2)}`,!0),j.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 Nr.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;rr(Q,"cache-resolution",s,null,"fail"),H&&NE(H,"Server-Timing",`cache-resolve;dur=${Q.toFixed(2)}`,!0),L.transaction.abort();return}if(O?.noCacheStore||L.noCacheStore){L.transaction.abort();return}qr(L).addWrite({key:K,store:i,entry:p,nodeName:"source",commit:a((ee,Q)=>{if(Q?.version!==y)return;let _e=an(K,I,F);if(F){ye.put?.(L,K,F),Q&&(O.previousResidency=Ce.getResidencyRecord(Q.residencyId));let fe,Ae=!1,De,we=Yi(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 _r in r)F||(F={}),F[_r]=fe[_r]}De=tc(we)}xe.default.trace?.(`Writing resolved record from source with id: ${K}, timestamp: ${new Date(ee).toISOString()}`),T(K,F,Q,ee,Ae?fn:0,g&&(Ge||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||A?T(K,null,Q,ee,0,g&&Ge||null,{user:L?.user},"delete",!!Z):gc(i,Q,y))},"commit")})}),()=>{i.unlock(K,y)},j=>{i.unlock(K,y),G&&xe.default.error?.("Error committing cache update",j)})})}a(Wd,"getFromSource");function ql(K){if(!K||K.user?.role?.permission?.super_user)return!0;if(K.replicateTo)throw new Nr.ClientError("Can not specify replication parameters without super user permissions",403);if(K.replicatedConfirmation)throw new Nr.ClientError("Can not specify replication confirmation without super user permissions",403);return!0}a(ql,"checkContextPermissions");function Ki(K){let p=!1;if(K&&(K-ut>1&&(p=!0),ut=K),!(Qt===Rr&&!p)&&(Rr=Qt,(0,Pl.getWorkerIndex)()===(0,Pl.getWorkerCount)()-1))return is&&clearTimeout(is),Qt?new Promise(O=>{let R=new Date;R.setMonth(0),R.setDate(1),R.setHours(0),R.setMinutes(0),R.setSeconds(0);let y=Qt/(1+ut),b=p?Date.now():Math.ceil((Date.now()-R.getTime())/y)*y+R.getTime(),C=a(I=>{xe.default.trace?.(`Scheduled next cleanup scan at ${new Date(I)}`),is=setTimeout(()=>$=$.then(async()=>{if(C(Math.max(I+Qt,Date.now())),i.rootStore.status!=="open"){clearTimeout(is);return}let L=50,H=new Array(L),N=0,x=Math.pow(ut,8)*(Dl.get(U.STORAGE_RECLAMATION_EVICTIONFACTOR)??1e5),G=S/Math.pow(Math.max(ut,1),4);xe.default.info?.(`Starting cleanup scan for ${s}, evict threshold ${x}, adjusted eviction ${G}ms`);function j(ie,F,Ge,Z){let ce=ie+G-Date.now();if(ce<0)return!0;if(ut){let ee=i.lastSize;return Ge&pn&&Zl(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(j,"shouldEvict");try{let ie=0;for(let F of i.getRange({start:!1,snapshot:!1,versions:!0,lazy:!0})){let{key:Ge,value:Z,version:ce,expiresAt:ee,metadataFlags:Q}=F,_e;Z===null&&!g&&ce+aTe<Date.now()?_e=gc(i,F,ce):ee!=null&&j(ee,ce,Q,Z)&&(_e=Ce.evict(Ge,Z,ce),ie++),_e&&(await H[N],H[N]=_e.catch(fe=>{xe.default.error?.("Cleanup error",fe)}),++N>=L&&(N=0)),await Xa()}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),ut=0}),Math.min(I-Date.now(),2147483647)).unref()},"startNextTimer");C(b)}):void 0}a(Ki,"scheduleCleanup");function zd(){Y=l?.addDeleteRemovalCallback(n,i,(K,p)=>{i.remove(K,p)})}a(zd,"addDeleteRemoval");function Nm(){(0,Pl.getWorkerIndex)()===0&&setInterval(async()=>{if(!Bl){Bl=!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 R of p.getValues(O)){let y=i.getEntry(R);y?.value?y.value[K]<Date.now()&&Ce.evict(R,y.value,y.version):i.ifVersion(R,y?.version,()=>p.remove(O,R))}await Xa()}}catch(K){xe.default.error?.("Error in evicting old records",K)}finally{Bl=!1}}},oTe).unref()}a(Nm,"runRecordExpirationEviction");function Yi(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(Yi,"residencyFromFunction");function tc(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(tc,"getResidencyId")}function eP(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 mj(){}function fTe(e){Tj=e}function BT(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 UT(parseInt(e.slice(1),36));if(e==="null")return null;if(!/^-?[0-9]+$/.test(e)&&!(e instanceof Date))throw new SyntaxError;return UT(+e);case"Float":return e==="null"?null:UT(+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;_Te.test(e)||(e+="Z");let n=new Date(e);return UT(n.getTime()),n}return new Date(+e);case void 0:case"Any":return(0,HT.autoCast)(e);default:return e}}catch(n){throw n.message=`Invalid value for attribute ${t.name}: "${e}", expecting ${r}`,n.statusCode=400,n}}function UT(e){if(isNaN(e))throw new SyntaxError;return e}function pj(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 tP(e,t,r){return e?.then?e.then(t,r):t(e)}function Ej(e){return e!=null}function Ls(e){try{return JSON.stringify(e)}catch{return e}}function hTe(e){let t=process.pid;return e.env.readerList().slice(1).some(r=>+r.match(/\d+/)?.[0]!=t)}var Za,lm,gj,Sj,Dl,Nr,um,dm,xe,Ll,Pl,HT,xT,iTe,Tj,oTe,aTe,dj,cTe,fj,lTe,fn,Jo,uTe,_j,hj,dTe,KUe,_Te,Xa,pf=be(()=>{B();Za=require("lmdb"),lm=M(ln()),gj=require("lodash"),Sj=M(uf());Xo();zm();Dl=M(le());FO();Nr=M(me()),um=M(lo()),dm=M($s());ve();mf();xe=M(_i());db();ac();Ll=require("ordered-binary"),Pl=M(Ze());ro();HT=M(oe());nu();wi();lE();T_();xT=M(require("node:fs"));ls();nT();iTe=new Uint8Array(9);iTe[8]=192;oTe=6e4,aTe=864e5;Dl.initSync();dj=Dl.get(U.STORAGE_PREFETCHWRITES),cTe=1e4,fj=1,lTe=2,fn=1,Jo=8,uTe=Buffer.allocUnsafeSlow(8192),_j=1978,hj=100,dTe={read:!0,insert:!0,update:!0,delete:!0,isSuperUser:!0},KUe=(0,HT.convertToMS)(Dl.get(U.CLUSTERING_LEAFSERVER_STREAMS_MAXAGE))||864e5;a(kT,"makeTable");a(eP,"attributesAsObject");a(mj,"noop");a(fTe,"setServerUtilities");_Te=/[+-][0-9]{2}:[0-9]{2}|[a-zA-Z]$/;a(BT,"coerceType");a(UT,"rejectNaN");a(pj,"isDescendantId");Xa=a(()=>new Promise(setImmediate),"rest");a(tP,"when");a(Ej,"exists");a(Ls,"stringify");a(hTe,"hasOtherProcesses")});var it={};Ue(it,{database:()=>Tu,database_envs:()=>qo,databases:()=>Ve,dropDatabase:()=>pb,dropTableMeta:()=>STe,getDatabases:()=>Je,getDefaultCompression:()=>Xg,getTables:()=>mTe,onRemovedDB:()=>G_,onUpdatedTable:()=>Zc,readMetaDb:()=>fm,resetDatabases:()=>od,table:()=>dt,tables:()=>Kn});function mTe(){return $T||Je(),Kn||{}}function Je(){if($T)return Ve;$T=!0,Fd=new Map;let e=(0,jt.getHdbBasePath)()&&(0,Pt.join)((0,jt.getHdbBasePath)(),sc),t=(0,jt.get)(U.DATABASES)||{};if(process.env.SCHEMAS_DATA_PATH&&(t.data={path:process.env.SCHEMAS_DATA_PATH}),e=process.env.STORAGE_PATH||(0,jt.get)(U.STORAGE_PATH)||e&&((0,ns.existsSync)(e)?e:(0,Pt.join)((0,jt.getHdbBasePath)(),Lm)),!e)return;if((0,ns.existsSync)(e))for(let n of(0,ns.readdirSync)(e,{withFileTypes:!0})){let s=(0,Pt.basename)(n.name,".mdb");n.isFile()&&(0,Pt.extname)(n.name).toLowerCase()===".mdb"&&!t[s]?.path&&fm((0,Pt.join)(e,n.name),null,s)}if((0,ns.existsSync)((0,kd.getBaseSchemaPath)())){for(let n of(0,ns.readdirSync)((0,kd.getBaseSchemaPath)(),{withFileTypes:!0}))if(!n.isFile()){let s=(0,Pt.join)((0,kd.getBaseSchemaPath)(),n.name),i=(0,Pt.join)((0,kd.getTransactionAuditStoreBasePath)(),n.name);for(let o of(0,ns.readdirSync)(s,{withFileTypes:!0}))if(o.isFile()&&(0,Pt.extname)(o.name).toLowerCase()===".mdb"){let c=(0,Pt.join)(i,o.name);fm((0,Pt.join)(s,o.name),(0,Pt.basename)(o.name,".mdb"),n.name,c,!0)}}}if(t)for(let n in t){let s=t[n],i=s.path;if((0,ns.existsSync)(i))for(let c of(0,ns.readdirSync)(i,{withFileTypes:!0}))c.isFile()&&(0,Pt.extname)(c.name).toLowerCase()===".mdb"&&fm((0,Pt.join)(i,c.name),(0,Pt.basename)(c.name,".mdb"),n);let o=s.tables;if(o)for(let c in o){let l=o[c],u=(0,Pt.join)(l.path,(0,Pt.basename)(c+".mdb"));(0,ns.existsSync)(u)&&fm(u,c,n,null,!0)}}for(let n in Ve){let s=Fd.get(n);if(s){let i=Ve[n];n.includes("delete")&&Dt.trace(`defined tables ${Array.from(s.keys())}`);for(let o in i)s.has(o)||(Dt.trace(`delete table class ${o}`),delete i[o])}else if(delete Ve[n],n==="data"){for(let i in Kn)delete Kn[i];delete Kn[VT]}}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 Fd=null,Ve}function od(){$T=!1;for(let[,e]of qo)e.needsDeletion=!0;Je();for(let[e,t]of qo)t.needsDeletion&&!e.endsWith("system.mdb")&&(t.close(),qo.delete(e),delete Ve[t.databaseName],hm.forEach(r=>r(t.databaseName)));return Ve}function fm(e,t,r=sP,n,s){let i=new rP.default(e,!1);try{let o=qo.get(e);o?o.needsDeletion=!1:(o=(0,qd.open)(i),qo.set(e,o));let c=new Ml.default(!1),l=o.dbisDb||(o.dbisDb=o.openDB(FT.INTERNAL_DBIS_NAME,c)),u=o.auditStore;u||(n?(0,ns.existsSync)(n)&&(i.path=n,u=(0,qd.open)(i),u.isLegacy=!0):u=MT(o));let f=bj(r),d=f[VT],_=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 A=_.get(S);A||_.set(S,A={attributes:[]}),(g==null||m.is_hash_attribute)&&(A.primary=m),g!=null&&A.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 ae of S)if(ae.is_hash_attribute||ae.isPrimaryKey){g=ae;break}if(!g){Dt.warn(`Unable to find a primary key attribute on table ${h}, with attributes: ${JSON.stringify(S)}`);continue}}let A=f[h],E={},T=[],w,v,k=typeof g.audit=="boolean"?g.audit:(0,jt.get)(U.LOGGING_AUDITLOG),$=g.trackDeletes,W=g.expiration,te=g.eviction,se=g.sealed,Y=g.splitSegments,ne=g.replicate;if(A)E=A.indices,T=A.attributes,A.schemaVersion++;else{w=g.tableId,w?w>=(l.get(Hd)||0)&&(l.putSync(Hd,w+1),Dt.info(`Updating next table id (it was out of sync) to ${w+1} for ${h}`)):(g.tableId=w=l.get(Hd),w||(w=1),Dt.debug("Table {table_name} missing an id, assigning {table_id}"),l.putSync(Hd,w+1),l.putSync(g.key,g));let ae=new Ml.default(!g.is_hash_attribute,g.is_hash_attribute);if(ae.compression=g.compression,ae.compression){let pe=(0,jt.get)(U.STORAGE_COMPRESSION_THRESHOLD)||yj;ae.compression.threshold=pe}v=yp(o.openDB(g.key,ae),o),o.databaseName=r,v.tableId=w}let ue;for(let ae of S){ae.attribute=ae.name;try{if(!ae.is_hash_attribute&&(ae.indexed||ae.attribute&&!ae.name)){if(!E[ae.name]){let Te=new Ml.default(!ae.is_hash_attribute,ae.is_hash_attribute);E[ae.name]=o.openDB(ae.key,Te),E[ae.name].indexNulls=ae.indexNulls}let pe=T.find(Te=>Te.name===ae.name);pe?T.splice(T.indexOf(pe),1,ae):T.push(ae),ue=!0}}catch(pe){Dt.error("Error trying to update attribute",ae,T,E,pe)}}for(let ae of T)if(!S.find(Te=>Te.name===ae.name)){if(ae.is_hash_attribute){Dt.error("Unable to remove existing primary key attribute",ae);continue}ae.indexed&&(T.splice(T.indexOf(ae),1),ue=!0)}if(A)ue&&(A.schemaVersion++,A.updatedAttributes());else{A=Oj(f,h,kT({primaryStore:v,auditStore:u,audit:k,sealed:se,splitSegments:Y,replicate:ne,expirationMS:W&&W*1e3,evictionMS:te&&te*1e3,trackDeletes:$,tableName:h,tableId:w,primaryKey:g.name,databasePath:s?r+"/"+h:r,databaseName:r,indices:E,attributes:S,schemaDefined:g.schemaDefined,dbisDB:l})),A.schemaVersion=1;for(let ae of _m)ae(A)}}return o}catch(o){throw o.message+=` opening database ${e}`,o}}function bj(e){let t=Ve[e];if(t||(e==="data"?t=Ve[e]=Kn:e==="system"?Object.defineProperty(Ve,"system",{value:t=Object.create(null),configurable:!0}):t=Ve[e]=Object.create(null)),Fd&&!Fd.has(e)){let r=new Set;t[VT]=r,Fd.set(e,r)}return t}function Oj(e,t,r){return e[t]=r,r}function Tu({database:e,table:t}){e||(e=sP),Je();let r=bj(e),n=(0,Pt.join)((0,jt.getHdbBasePath)(),sc),s=(0,jt.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,jt.get)(U.STORAGE_PATH)||((0,ns.existsSync)(n)?n:(0,Pt.join)((0,jt.getHdbBasePath)(),Lm));let o=(0,Pt.join)(n,(i?t:e)+".mdb"),c=qo.get(o);if(!c||c.status==="closed"){let l=new rP.default(o,!1);c=(0,qd.open)(l),qo.set(o,c)}return c.auditStore||(c.auditStore=MT(c)),c}async function pb(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,qo.delete(r.path),r.status==="open"&&(await r.close(),await mm.remove(r.path));if(r||(r=Tu({database:e,table:null}),r.status==="open"&&(await r.close(),await mm.remove(r.path))),e==="data"){for(let n in Kn)delete Kn[n];delete Kn[VT]}delete Ve[e],hm.forEach(n=>n(e)),await zA(r)}function dt(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=sP);let m=Tu({database:r,table:t}),S=Ve[r];Dt.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 A,E,T;_==null&&(_=!0);let w=new Ml.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,k;if(g){if(A=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)||{},A=E.name,E.is_hash_attribute=E.isPrimaryKey=!0,E.schemaDefined=_,E.compression=Xg(),d&&(E.trackDeletes=!0),c=E.audit=typeof c=="boolean"?c:(0,jt.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]),Dt.trace(`${t} table loading, opening primary store`);let ne=new Ml.default(!1,!0);ne.compression=E.compression;let ue=t+"/";if(T=m.dbisDb=m.openDB(FT.INTERNAL_DBIS_NAME,w),se(),T.get(ue))return k&&k(),od(),dt(e);let ae=yp(m.openDB(ue,ne),m);m.databaseName=r,ae.tableId=T.get(Hd),Dt.trace(`Assigning new table id ${ae.tableId} for ${t}`),ae.tableId||(ae.tableId=1),T.put(Hd,ae.tableId+1),E.tableId=ae.tableId,g=Oj(S,t,kT({primaryStore:ae,auditStore:Y,audit:c,sealed:l,splitSegments:u,replicate:f,trackDeletes:d,expirationMS:n&&n*1e3,evictionMS:s&&s*1e3,primaryKey:A,tableName:t,tableId:ae.tableId,databasePath:r,databaseName:r,indices:{},attributes:o,schemaDefined:_,dbisDB:T})),g.schemaVersion=1,v=!0,T.put(ue,E)}let $=g.indices;T=T||(m.dbisDb=m.openDB(FT.INTERNAL_DBIS_NAME,w)),g.dbisDB=T;let W=[];for(let{key:Y,value:ne}of T.getRange({start:!0})){let[ue,ae]=Y.toString().split("/");if(ae===""&&(ae=ne.name),ae){if(ue!==t)continue}else continue;let pe=o.find(ye=>ye.name===ae),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 ae=!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 Ml.default(!0,!1),Te=m.openDB(ne,pe);(ae||ue.indexingPID&&ue.indexingPID!==process.pid||ue.restartNumber<pm.workerData?.restartNumber)&&(v=!0,se(),ue=T.get(ne),(ae||ue.indexingPID&&ue.indexingPID!==process.pid||ue.restartNumber<pm.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,$[Y.name]=Te}else ae&&(v=!0,se(),T.put(ne,Y))}}finally{k&&k()}if(v&&(g.schemaVersion++,g.updatedAttributes()),Dt.trace(`${t} table loading, running index`),te.length>0||W.length>0?g.indexingOperation=gTe(g,te,W):v&&qT.signalSchemaChange(new GT.SchemaEventMsg(process.pid,"schema-change",g.databaseName,g.tableName)),g.origin=h,v)for(let Y of _m)Y(g,h!=="cluster");return(n||s||i)&&g.setTTLExpiration({expiration:n,eviction:s,scanInterval:i}),Dt.trace(`${t} table loaded`),g;function se(){k||m.transactionSync(()=>({then(Y){k=Y}}))}a(se,"startTxn")}async function gTe(e,t,r){try{Dt.info(`Indexing ${e.tableName} attributes`,t);let n=e.schemaVersion;await qT.signalSchemaChange(new GT.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,qd.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 A=S.resolve,E=_&&(A?A(_):_[g]),T=(0,Aj.getIndexedValues)(E);if(T)for(let w=0,v=T.length;w<v;w++)S.dbi.put(T[w],d)}catch(A){o[g]||(o[g]=!0,Dt.error(`Error indexing attribute ${g}`,A))}}}),s.then(()=>f--,m=>{f--,Dt.error(m)}),pm.workerData&&pm.workerData.restartNumber!==Rj.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>pTe?await s:f>ETe&&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 qT.signalSchemaChange(new GT.SchemaEventMsg(process.pid,"indexing-finished",e.databaseName,e.tableName)),Dt.info(`Finished indexing ${e.tableName} attributes`,t)}catch(n){Dt.error("Error in indexing",n)}}function STe({table:e,database:t}){let r=Tu({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 Zc(e){return _m.push(e),{remove(){let t=_m.indexOf(e);t>-1&&_m.splice(t,1)}}}function G_(e){return hm.push(e),{remove(){let t=hm.indexOf(e);t>-1&&hm.splice(t,1)}}}function Xg(){let e=(0,jt.get)(U.STORAGE_COMPRESSION),t=(0,jt.get)(U.STORAGE_COMPRESSION_DICTIONARY),r=(0,jt.get)(U.STORAGE_COMPRESSION_THRESHOLD)||yj,n={startingOffset:32};return t&&(n.dictionary=mm.readFileSync(t)),r&&(n.threshold=r),e&&n}var jt,FT,qd,Pt,ns,kd,Ml,rP,mm,nP,Aj,qT,GT,pm,Dt,Rj,sP,VT,yj,Kn,Ve,Hd,_m,hm,$T,qo,Fd,pTe,ETe,ve=be(()=>{jt=M(le()),FT=M(vt()),qd=require("lmdb"),Pt=require("path"),ns=require("fs"),kd=M(Et());pf();Ml=M(Lf()),rP=M(Mf());B();mm=M(require("fs-extra")),nP=M(ci()),Aj=M(ln()),qT=M(lo()),GT=M($s()),pm=require("worker_threads"),Dt=M(z()),Rj=M(Ze());ro();nu();ls();sP="data",VT=Symbol("defined-tables"),yj=((0,jt.get)(U.STORAGE_PAGESIZE)||4096)-60;(0,jt.initSync)();Kn=Object.create(null),Ve=Object.create(null);(0,nP._assignPackageExport)("databases",Ve);(0,nP._assignPackageExport)("tables",Kn);Hd=Symbol.for("next-table-id"),_m=[],hm=[],qo=new Map;a(mTe,"getTables");a(Je,"getDatabases");a(od,"resetDatabases");a(fm,"readMetaDb");a(bj,"ensureDB");a(Oj,"setTable");a(Tu,"database");a(pb,"dropDatabase");a(dt,"table");pTe=1e3,ETe=10;a(gTe,"runIndexing");a(STe,"dropTableMeta");a(Zc,"onUpdatedTable");a(G_,"onRemovedDB");a(Xg,"getDefaultCompression")});var oe=P((r0e,kj)=>{"use strict";var ec=require("path"),Pj=require("fs-extra"),Cn=z(),Nj=require("fs-extra"),KT=require("os"),TTe=require("net"),ATe=require("recursive-iterator"),Ar=(B(),D(q)),{PACKAGE_ROOT:RTe}=pt(),yTe=yA(),wj=require("papaparse"),YT=require("moment"),{inspect:bTe}=require("util"),Ij=require("is-number"),t0e=require("lodash"),OTe=require("minimist"),NTe=require("https"),wTe=require("http"),{hdb_errors:WT}=me(),ITe=/^((\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)))$/,Dj=require("util").promisify(setTimeout),CTe=100,PTe=5,DTe="",LTe=4,Cj={true:!0,TRUE:!0,FALSE:!1,false:!1,undefined:null,null:null,NULL:null,NaN:NaN};kj.exports={isEmpty:ss,isEmptyOrZeroLength:$i,arrayHasEmptyValues:UTe,arrayHasEmptyOrZeroLengthValues:xTe,buildFolderPath:BTe,isBoolean:Lj,errorizeMessage:MTe,stripFileExtension:kTe,autoCast:FTe,autoCastJSON:Mj,autoCastJSONDeep:oP,removeDir:qTe,compareVersions:GTe,isCompatibleDataVersion:$Te,escapeRawValue:VTe,unescapeValue:KTe,stringifyProps:YTe,timeoutPromise:zTe,isClusterOperation:QTe,getClusterUser:XTe,checkGlobalSchemaTable:JTe,getHomeDir:Uj,getPropsFilePath:WTe,promisifyPapaParse:ZTe,removeBOM:xj,createEventPromise:eAe,checkProcessRunning:tAe,checkSchemaTableExist:rAe,checkSchemaExists:Bj,checkTableExists:Hj,getStartOfTomorrowInSeconds:nAe,getLimitKey:sAe,isObject:HTe,isNotEmptyAndHasValue:vTe,autoCasterIsNumberCheck:vj,backtickASTSchemaItems:iAe,isPortTaken:jTe,createForkArgs:oAe,autoCastBoolean:aAe,async_set_timeout:Dj,getTableHashAttribute:cAe,doesSchemaExist:lAe,doesTableExist:uAe,stringifyObj:dAe,ms_to_time:fAe,changeExtension:_Ae,getEnvCliRootPath:aP,noBootFile:hAe,httpRequest:mAe,transformReq:pAe,convertToMS:EAe,PACKAGE_ROOT:RTe};function MTe(e){return e instanceof Error?e:new Error(e)}a(MTe,"errorizeMessage");function ss(e){return e==null}a(ss,"isEmpty");function vTe(e){return!ss(e)&&(e||e===0||e===""||Lj(e))}a(vTe,"isNotEmptyAndHasValue");function $i(e){return ss(e)||e.length===0||e.size===0}a($i,"isEmptyOrZeroLength");function UTe(e){if(ss(e))return!0;for(let t=0;t<e.length;t++)if(ss(e[t]))return!0;return!1}a(UTe,"arrayHasEmptyValues");function xTe(e){if($i(e))return!0;for(let t=0;t<e.length;t++)if($i(e[t]))return!0;return!1}a(xTe,"arrayHasEmptyOrZeroLengthValues");function BTe(...e){try{return e.join(ec.sep)}catch{console.error(e)}}a(BTe,"buildFolderPath");function Lj(e){return ss(e)?!1:e===!0||e===!1}a(Lj,"isBoolean");function HTe(e){return ss(e)?!1:typeof e=="object"}a(HTe,"isObject");function kTe(e){return $i(e)?DTe:e.slice(0,-LTe)}a(kTe,"stripFileExtension");function FTe(e){return ss(e)||e===""||typeof e!="string"?e:Cj[e]!==void 0?Cj[e]:vj(e)===!0?Number(e):ITe.test(e)?new Date(e):e}a(FTe,"autoCast");function Mj(e){if(typeof e=="string"&&(e.startsWith("{")&&e.endsWith("}")||e.startsWith("[")&&e.endsWith("]")))try{return JSON.parse(e)}catch{}return e}a(Mj,"autoCastJSON");function oP(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=oP(n);s!==n&&(e[t]=s)}else for(let t in e){let r=e[t],n=oP(r);n!==r&&(e[t]=n)}return e}else return Mj(e)}a(oP,"autoCastJSONDeep");function vj(e){if(e.startsWith("0.")&&Ij(e))return!0;let t=e.toUpperCase().includes("E");return!!((e!=="0"&&e.startsWith("0"))===!1&&t===!1&&Ij(e))}a(vj,"autoCasterIsNumberCheck");async function qTe(e){if($i(e))throw new Error(`Directory path: ${e} does not exist`);try{await Nj.emptyDir(e),await Nj.remove(e)}catch(t){throw Cn.error(`Error removing files in ${e} -- ${t}`),t}}a(qTe,"removeDir");function GTe(e,t){if($i(e)){Cn.info("Invalid current version sent as parameter.");return}if($i(t)){Cn.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(GTe,"compareVersions");function $Te(e,t,r=!1){let n=e.toString().split("."),s=t.toString().split(".");return n[0]===s[0]&&(!r||n[1]===s[1])}a($Te,"isCompatibleDataVersion");function VTe(e){if(ss(e))return e;let t=String(e);return t==="."?Ar.UNICODE_PERIOD:t===".."?Ar.UNICODE_PERIOD+Ar.UNICODE_PERIOD:t.replace(Ar.FORWARD_SLASH_REGEX,Ar.UNICODE_FORWARD_SLASH)}a(VTe,"escapeRawValue");function KTe(e){if(ss(e))return e;let t=String(e);return t===Ar.UNICODE_PERIOD?".":t===Ar.UNICODE_PERIOD+Ar.UNICODE_PERIOD?"..":String(e).replace(Ar.ESCAPED_FORWARD_SLASH_REGEX,"/")}a(KTe,"unescapeValue");function YTe(e,t){if(ss(e))return Cn.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+KT.EOL}!$i(n)&&n[0]===";"?r+=" "+n+s+KT.EOL:$i(n)||(r+=n+"="+s+KT.EOL)}catch{Cn.error(`Found bad property during upgrade with key ${n} and value: ${s}`)}}),r}a(YTe,"stringifyProps");function Uj(){let e;try{e=KT.homedir()}catch{e=process.env.HOME}return e}a(Uj,"getHomeDir");function WTe(){let e=ec.join(Uj(),Ar.HDB_HOME_DIR_NAME,Ar.BOOT_PROPS_FILE_NAME);return Pj.existsSync(e)||(e=ec.join(__dirname,"../","hdb_boot_properties.file")),e}a(WTe,"getPropsFilePath");function zTe(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(zTe,"timeoutPromise");async function jTe(e){if(!e)throw new Error("Invalid port passed as parameter");return new Promise((t,r)=>{let n=TTe.createServer().once("error",s=>{s.code==="EADDRINUSE"?t(!0):r(s)}).once("listening",()=>n.once("close",()=>t(!1)).close()).listen(e)})}a(jTe,"isPortTaken");function QTe(e){try{return Ar.CLUSTER_OPERATIONS[e.toLowerCase()]!==void 0}catch(t){Cn.error(`Error checking operation against cluster ops ${t}`)}return!1}a(QTe,"isClusterOperation");function JTe(e,t){let r=(ve(),D(it)).getDatabases();if(!r[e])return WT.HDB_ERROR_MSGS.SCHEMA_NOT_FOUND(e);if(!r[e][t])return WT.HDB_ERROR_MSGS.TABLE_NOT_FOUND(e,t)}a(JTe,"checkGlobalSchemaTable");function XTe(e,t){if(ss(t)){Cn.warn("No CLUSTERING_USER defined, clustering disabled");return}if(ss(e)||$i(e)){Cn.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){Cn.error(`unable to find cluster_user due to: ${n.message}`);return}if(r===void 0){Cn.warn(`CLUSTERING_USER: ${t} not found or is not active.`);return}return r}a(XTe,"getClusterUser");function ZTe(){wj.parsePromise=function(e,t,r){return new Promise(function(n,s){wj.parse(e,{header:!0,transformHeader:xj,chunk:t.bind(null,s),skipEmptyLines:!0,transform:r,dynamicTyping:!1,error:s,complete:n})})}}a(ZTe,"promisifyPapaParse");function xj(e){if(typeof e!="string")throw new TypeError(`Expected a string, got ${typeof e}`);return e.charCodeAt(0)===65279?e.slice(1):e}a(xj,"removeBOM");function eAe(e,t,r){return new Promise(n=>{t.once(e,s=>{let i=r;Cn.info(`Got cluster status event response: ${bTe(s)}`);try{i.cancel()}catch{Cn.error("Error trying to cancel timeout.")}n(s)})})}a(eAe,"createEventPromise");async function tAe(e){let t=!0,r=0;do await Dj(CTe*r++),(await yTe.findPs(e)).length>0&&(t=!1);while(t&&r<PTe);if(t)throw new Error(`process ${e} was not started`)}a(tAe,"checkProcessRunning");function rAe(e,t){let r=Bj(e);if(r)return r;let n=Hj(e,t);if(n)return n}a(rAe,"checkSchemaTableExist");function Bj(e){let{getDatabases:t}=(ve(),D(it));if(!t()[e])return WT.HDB_ERROR_MSGS.SCHEMA_NOT_FOUND(e)}a(Bj,"checkSchemaExists");function Hj(e,t){let{getDatabases:r}=(ve(),D(it));if(!r()[e][t])return WT.HDB_ERROR_MSGS.TABLE_NOT_FOUND(e,t)}a(Hj,"checkTableExists");function nAe(){let e=YT().utc().add(1,"d").startOf("d").unix(),t=YT().utc().unix();return e-t}a(nAe,"getStartOfTomorrowInSeconds");function sAe(){return YT().utc().format("DD-MM-YYYY")}a(sAe,"getLimitKey");function iAe(e){try{let t=new ATe(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){Cn.error("Got an error back ticking items."),Cn.error(t)}}a(iAe,"backtickASTSchemaItems");function oAe(e){return[e]}a(oAe,"createForkArgs");function aAe(e){return e===!0||typeof e=="string"&&e.toLowerCase()==="true"}a(aAe,"autoCastBoolean");function cAe(e,t){let{getDatabases:r}=(ve(),D(it)),n=r()[e]?.[t];return n?.primaryKey||n?.hash_attribute}a(cAe,"getTableHashAttribute");function lAe(e){let{getDatabases:t}=(ve(),D(it));return t()[e]!==void 0}a(lAe,"doesSchemaExist");function uAe(e,t){let{getDatabases:r}=(ve(),D(it));return r()[e]?.[t]!==void 0}a(uAe,"doesTableExist");function dAe(e){try{return JSON.stringify(e)}catch{return e}}a(dAe,"stringifyObj");function fAe(e){let t=YT.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(fAe,"ms_to_time");function _Ae(e,t){let r=ec.basename(e,ec.extname(e));return ec.join(ec.dirname(e),r+t)}a(_Ae,"changeExtension");function aP(){if(process.env[Ar.CONFIG_PARAMS.ROOTPATH.toUpperCase()])return process.env[Ar.CONFIG_PARAMS.ROOTPATH.toUpperCase()];let e=OTe(process.argv);if(e[Ar.CONFIG_PARAMS.ROOTPATH.toUpperCase()])return e[Ar.CONFIG_PARAMS.ROOTPATH.toUpperCase()]}a(aP,"getEnvCliRootPath");var iP;function hAe(){if(iP)return iP;let e=aP();if(aP()&&Pj.pathExistsSync(ec.join(e,Ar.HDB_CONFIG_FILE)))return iP=!0,!0}a(hAe,"noBootFile");function mAe(e,t){let r;return e.protocol==="http:"?r=wTe:r=NTe,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(mAe,"httpRequest");function pAe(e){if(!e.schema&&!e.database){e.schema=Ar.DEFAULT_DATABASE_NAME;return}e.database&&(e.schema=e.database)}a(pAe,"transformReq");function EAe(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(EAe,"convertToMS")});var le=P((Vj,Kj)=>{"use strict";var cP=require("fs-extra"),vl=require("path"),Fj=require("os"),gAe=require("properties-reader"),gm=z(),Em=oe(),Me=(B(),D(q)),zT=wt(),SAe="Error initializing environment manager",jT="BOOT_PROPS_FILE_PATH",qj=!1,TAe={[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},Go={};Object.assign(Vj,Kj.exports={BOOT_PROPS_FILE_PATH:jT,getHdbBasePath:AAe,setHdbBasePath:RAe,get:Gj,initSync:bAe,setProperty:ze,initTestEnvironment:NAe,setCloneVar:OAe});function AAe(){return Go[Me.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]}a(AAe,"getHdbBasePath");function RAe(e){Go[Me.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]=e}a(RAe,"setHdbBasePath");function Gj(e){let t=zT.getConfigValue(e);return t===void 0?Go[e]:t}a(Gj,"get");function ze(e,t){TAe[e]&&(Go[e]=t),zT.updateConfigObject(e,t)}a(ze,"setProperty");function yAe(){let e;try{e=Em.getPropsFilePath(),cP.accessSync(e,cP.constants.F_OK|cP.constants.R_OK),qj=!0;let t=gAe(e);return Go[Me.HDB_SETTINGS_NAMES.INSTALL_USER]=t.get(Me.HDB_SETTINGS_NAMES.INSTALL_USER),Go[Me.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY]=t.get(Me.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY),Go[jT]=e,!0}catch{return gm.trace(`Environment manager found no properties file at ${e}`),!1}}a(yAe,"doesPropFileExist");function bAe(e=!1){try{((qj||yAe()||Em.noBootFile())&&!$j||e)&&(zT.initConfig(e),Go[Me.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]=zT.getConfigValue(Me.HDB_SETTINGS_NAMES.HDB_ROOT_KEY))}catch(t){gm.error(SAe),gm.error(t),console.error(t),process.exit(1)}}a(bAe,"initSync");var $j=!1;function OAe(e){$j=e}a(OAe,"setCloneVar");function NAe(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=vl.join(__dirname,"../../","unitTests");Go[jT]=vl.join(l,"hdb_boot_properties.file"),ze(Me.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY,vl.join(l,"settings.test")),ze(Me.HDB_SETTINGS_NAMES.INSTALL_USER,Fj.userInfo()?Fj.userInfo().username:void 0),ze(Me.HDB_SETTINGS_NAMES.LOG_LEVEL_KEY,"debug"),ze(Me.HDB_SETTINGS_NAMES.LOG_PATH_KEY,vl.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,vl.join(l,"envDir")),ze(Me.CONFIG_PARAMS.STORAGE_PATH,vl.join(l,"envDir")),s&&(ze(Me.CONFIG_PARAMS.HTTP_SECUREPORT,Gj(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,Em.isEmpty(i)?!1:i),ze(Me.CONFIG_PARAMS.HTTP_CORS,Em.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,vl.resolve(__dirname,"../../unitTests/server/fastifyRoutes/custom_functions")),ze(Me.HDB_SETTINGS_NAMES.LOCAL_STUDIO_ON,Em.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 ${jT}. Please check your boot props and settings files`;gm.fatal(r),gm.error(t)}}a(NAe,"initTestEnvironment")});var Qj=P((i0e,jj)=>{"use strict";var zj=require("joi"),{string:Sm,boolean:Yj,array:wAe}=zj.types(),Wj=(B(),D(q)),IAe=et();jj.exports=CAe;function CAe(e){let t=zj.object({operation:Sm.valid(Wj.OPERATIONS_ENUM.ADD_NODE,Wj.OPERATIONS_ENUM.UPDATE_NODE).required(),node_name:Sm.required(),subscriptions:wAe.items({schema:Sm.required(),table:Sm.optional(),hash_attribute:Sm.optional(),subscribe:Yj.required(),publish:Yj.required()}).min(1).required()});return IAe.validateBySchema(e,t)}a(CAe,"updateRemoteSourceValidator")});var Tm=P((a0e,Jj)=>{"use strict";var lP=class{static{a(this,"UpdateRemoteResponseObject")}constructor(t,r,n=void 0){this.status=t,this.message=r,this.system_info=n}};Jj.exports=lP});var tQ=P((l0e,eQ)=>{"use strict";var PAe=Qj(),$o=z(),uP=ot(),DAe=(B(),D(q)),dP=Es(),Ul=Ut(),Xj=W_(),LAe=gu(),{Node:MAe,NodeSubscription:Zj}=Oa(),fP=Tm(),_P=oe(),vAe=le(),{cloneDeep:UAe}=require("lodash"),{broadcast:xAe}=Ze();eQ.exports=BAe;async function BAe(e){try{let t=PAe(e);if(t)return $o.error(`Validation error in updateRemoteSource: ${t.message}`),new fP(uP.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR,t.message);let{subscriptions:r,node_name:n,system_info:s}=e,i=[],o=UAe(await dP.getNodeRecord(n)),c=!_P.isEmptyOrZeroLength(o);o=c?o[0]:o,c&&$o.trace(`Existing record found for ${n}, updating records subscriptions`);for(let u=0,f=r.length;u<f;u++){let d=r[u],_=d.schema,h=d.table;if(!_P.doesSchemaExist(_)){$o.trace(`updateRemoteSource creating schema: ${_}`);try{await Xj.createSchema({operation:"create_schema",schema:_})}catch(m){$o.error(m)}}if(h&&!_P.doesTableExist(_,h)){let m=new LAe(_,h,d.hash_attribute);d.attributes&&(m.attributes=d.attributes),$o.trace(`updateRemoteSource creating table: ${h} in schema: ${_} with attributes: ${JSON.stringify(d.attributes)}`);try{await Xj.createTable(m)}catch(S){$o.error(S)}}if($o.trace(`Creating local stream for ${_}.${h}`),await Ul.createLocalTableStream(_,h),c?(await Ul.updateConsumerIterator(_,h,n,"stop"),await Ul.updateRemoteConsumer(d,n),d.subscribe===!0&&await Ul.updateConsumerIterator(_,h,n,"start")):(await Ul.updateRemoteConsumer(d,n),d.subscribe===!0?await Ul.updateConsumerIterator(_,h,n,"start"):await Ul.updateConsumerIterator(_,h,n,"stop")),c){let m=!1;for(let S=0,g=o.subscriptions.length;S<g;S++){let A=o.subscriptions[S];if(A.schema===_&&A.table===h){A.publish=d.publish,A.subscribe=d.subscribe,m=!0;break}}m||o.subscriptions.push(new Zj(_,h,d.publish,d.subscribe))}else i.push(new Zj(_,h,d.publish,d.subscribe))}c||(o=new MAe(n,i,void 0),$o.trace(`No record found for ${n}, creating a new one`));let l=Object.create({});return Object.assign(l,o),l.system_info=s,await dP.upsertNodeRecord(l),xAe({type:"nats_update"}),new fP(uP.UPDATE_REMOTE_RESPONSE_STATUSES.SUCCESS,`Node ${vAe.get(DAe.CONFIG_PARAMS.CLUSTERING_NODENAME)} successfully updated remote source`,await dP.getSystemInfo())}catch(t){$o.error(t);let r=t.message?t.message:t;return new fP(uP.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR,r)}}a(BAe,"updateRemoteSource")});var iQ=P((d0e,sQ)=>{"use strict";var nQ=require("joi"),{string:rQ}=nQ.types(),HAe=(B(),D(q)),kAe=et();sQ.exports=FAe;function FAe(e){let t=nQ.object({operation:rQ.valid(HAe.OPERATIONS_ENUM.REMOVE_NODE).required(),node_name:rQ.required()});return kAe.validateBySchema(e,t)}a(FAe,"removeRemoteSourceValidator")});var cQ=P((_0e,aQ)=>{"use strict";var qAe=iQ(),QT=z(),JT=ot(),hP=(B(),D(q)),GAe=Es(),$Ae=oe(),oQ=Ut(),VAe=le(),XT=Tm(),{NodeSubscription:KAe}=Oa(),YAe=Eu(),WAe=oa(),{broadcast:zAe}=Ze(),jAe=VAe.get(hP.CONFIG_PARAMS.CLUSTERING_NODENAME);aQ.exports=QAe;async function QAe(e){try{let t=qAe(e);if(t)return QT.error(`Validation error in removeRemoteSource: ${t.message}`),new XT(JT.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR,t.message);let r=e.node_name,n=await GAe.getNodeRecord(r);if($Ae.isEmptyOrZeroLength(n)){let i=`No record found for node '${r}'`;return QT.error(i),new XT(JT.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR,i)}n=n[0];for(let i=0,o=n.subscriptions.length;i<o;i++){let c=n.subscriptions[i];QT.trace(`remove remote source removing subscription: ${c.schema}.${c.table} for node: ${r}`);let l=new KAe(c.schema,c.table,!1,!1);await oQ.updateConsumerIterator(c.schema,c.table,r,"stop"),await oQ.updateRemoteConsumer(l,r)}let s=new YAe(hP.SYSTEM_SCHEMA_NAME,hP.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,[r]);return await WAe.deleteRecord(s),zAe({type:"nats_update"}),new XT(JT.UPDATE_REMOTE_RESPONSE_STATUSES.SUCCESS,`Node ${jAe} successfully removed node '${r}'.`)}catch(t){QT.error(t);let r=t.message?t.message:t;return new XT(JT.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR,r)}}a(QAe,"removeRemoteSource")});var fQ=P((m0e,dQ)=>{"use strict";var ZT=z(),Am=(B(),D(q)),lQ=ot(),mP=le(),JAe=oe(),uQ=Tm(),XAe=Es(),ZAe=y_(),eRe=zr();dQ.exports=tRe;async function tRe(e){try{ZT.trace("getRemoteSourceConfig called");let t=process.uptime()*1e3,r=JAe.ms_to_time(t),n=new rRe(mP.get(Am.CONFIG_PARAMS.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT),mP.get(Am.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_PORT)??mP.get(Am.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_SECUREPORT),r,await XAe.getSystemInfo());try{let s={name:e.node_name,system_info:e.system_info},i=new ZAe(Am.SYSTEM_SCHEMA_NAME,Am.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,[s]);await eRe.update(i)}catch(s){ZT.error("Get remote config encountered an error updating system info for node:",e.node_name,s)}return ZT.trace("getRemoteSourceConfig response:",n),new uQ(lQ.UPDATE_REMOTE_RESPONSE_STATUSES.SUCCESS,n)}catch(t){ZT.error(t);let r=t.message?t.message:t;return new uQ(lQ.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR,r)}}a(tRe,"getRemoteSourceConfig");function rRe(e,t,r,n){this.uptime=r,this.ports={clustering:e,operations_api:t},this.system_info=n}a(rRe,"ConfigResponseObject")});var pQ=P((E0e,mQ)=>{"use strict";var _Q=le();_Q.initSync();var hQ=Ut(),Rm=z(),Gd=(B(),D(q)),pP=ot(),nRe=tQ(),sRe=cQ(),iRe=fQ(),oRe=Tm(),{encode:aRe,decode:cRe}=require("msgpackr"),lRe=fs(),uRe=Ai(),dRe=require("util"),fRe=(B(),D(q)),{isMainThread:_Re,parentPort:hRe}=require("worker_threads");Ze();var mRe=dRe.promisify(lRe.setSchemaDataToGlobal),EP=_Q.get(Gd.CONFIG_PARAMS.CLUSTERING_NODENAME);mQ.exports=pRe;async function pRe(){try{Rm.notify("Starting reply service."),await mRe();let e=await hQ.getConnection(),t=`${EP}.__request__`,r=e.subscribe(t,{queue:EP});await ERe(r)}catch(e){Rm.error(e)}}a(pRe,"initialize");async function ERe(e){for await(let t of e){let r=cRe(t.data),n;switch(r.operation){case Gd.OPERATIONS_ENUM.ADD_NODE:case Gd.OPERATIONS_ENUM.UPDATE_NODE:n=await nRe(r);break;case Gd.OPERATIONS_ENUM.REMOVE_NODE:n=await sRe(r);break;case Gd.OPERATIONS_ENUM.CLUSTER_STATUS:n=await iRe(r);break;case Gd.OPERATIONS_ENUM.DESCRIBE_ALL:n=await gRe();break;default:let s=`node '${EP}' reply service received unrecognized request operation`;Rm.error(s),n=new oRe(pP.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR,s)}Rm.trace(n),t.respond(aRe(n))}}a(ERe,"handleRequest");async function gRe(){try{return{status:pP.UPDATE_REMOTE_RESPONSE_STATUSES.SUCCESS,message:await uRe.describeAll({bypass_auth:!0})}}catch(e){return Rm.error(e),{status:pP.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR,message:e.message}}}a(gRe,"getRemoteDescribeAll");_Re||hRe.on("message",async e=>{let{type:t}=e;t===fRe.ITC_EVENT_TYPES.SHUTDOWN&&hQ.closeConnection()})});var SRe=pQ();(async()=>{try{await SRe()}catch(e){console.error("Error launching Nats reply service."),console.error(e)}})();
|